
    Mh                       d Z ddlm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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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&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5  ej6        d          Z7 ej6        d          Z8d$d%dZ9 G d de)          Z:	 	 d&d'd#Z;dS )(znbclient implementation.    )annotationsN)asynccontextmanagercontextmanager)Empty)dedent	monotonic)KernelClient)KernelManager)NotebookNode)output_from_msg)
AnyBoolCallableDictEnumIntegerListTypeUnicodedefault)LoggingConfigurable   )CellControlSignalCellExecutionCompleteCellExecutionErrorCellTimeoutErrorDeadKernelError)OutputWidget)ensure_asyncrun_hookrun_syncz.*\r(?=[^\n])z[^\n]\bmsgdict[str, t.Any] | Nonereturnstrc                D   | rld| v rh| d         }d|v r\t          |d         t          j                  r<	 t          j                            |d         d          }|r|S n# t          $ r Y nw xY wt          j                                                                        dz   S )z Get the timestamp for a message.headerdatez%Y-%m-%dT%H:%M:%S.%fZZ)
isinstancedatetimestrftime	Exceptionutcnow	isoformat)r#   
msg_headerformatted_times      O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/nbclient/client.py	timestampr4   (   s    
 x3]
ZJz&/A8CT$U$U
!)!2!;!;v&(?" " #* *)*     ##%%//11C77s   )A 
A,+A,c                      e Zd ZU dZ edd ed                                        d          Z edd ed                                        d          Z	d	e
d
<    ed ed                                        d          Z edd ed                                        d          Z ed ed                                        d          Z ed ed                                        d          Z e e             ed                                        d          Z ed ed                                        d          Z ed ed                                        d          Z e e                                          d          Z ed ed                                        d          Z ed ed                                        d          Z ed ed                                        d          Z ed ed                                        d          Z edd ed                                        d          Z edd ed                                        d          Z edd gd ed!          "                              d          Z ed#d$"                              d          Z e de!d%&          Z" e#dd ed'                                        d          Z$ e#dd ed(                                        d          Z% e#dd ed)                                        d          Z& e#dd ed*                                        d          Z' e#dd ed+                                        d          Z( e#dd ed,                                        d          Z) e#dd ed-                                        d          Z* e#dd ed.                                        d          Z+ e,d/          dd2            Z- e ed3                    Z.d4e
d5<    eg d6d7                              d          Z/ e ed8                    Z0d4e
d9<    e ed:                    Z1dd fdBZ2ddCZ3ddEZ4ddFZ5 e6e5          Z7ddHZ8 e6e8          Z9ddJZ: e6e:          Z;e<ddL            Z=e>ddN            Z?dddQZ@ e6e@          ZAddRZBddVZCdd^ZDddbZEddcZFddeZG	 dddgZHddhZI	 dddjZJ e6eJ          ZKeKZLddlZMddnZN	 	 dddqZO e6eO          ZPddrZQdduZRddvZSddwZTddxZUddzZVdd|ZWddZXddZYddZZ xZ[S )NotebookClientz@
    Encompasses a Client for executing cells in a notebook
    NTa  
            The time to wait (in seconds) for output from executions.
            If a cell execution takes longer, a TimeoutError is raised.

            ``None`` or ``-1`` will disable the timeout. If ``timeout_func`` is set,
            it overrides ``timeout``.
            )
allow_nonehelpconfiga   
            A callable which, when given the cell source as input,
            returns the time to wait (in seconds) for output from cell
            executions. If a cell execution takes longer, a TimeoutError
            is raised.

            Returning ``None`` or ``-1`` will disable the timeout for the cell.
            Not setting ``timeout_func`` will cause the client to
            default to using the ``timeout`` trait for all cells. The
            ``timeout_func`` trait overrides ``timeout`` if it is not ``None``.
            )default_valuer7   r8   z"t.Callable[..., int | None] | Nonetimeout_funcFz
            If execution of a cell times out, interrupt the kernel and
            continue executing other cells rather than throwing an error and
            stopping.
            )r8   a  
            If a cell execution was interrupted after a timeout, don't wait for
            the execute_reply from the kernel (e.g. KeyboardInterrupt error).
            Instead, return an execute_reply with the given error, which should
            be of the following form::

                {
                    'ename': str,  # Exception name, as a string
                    'evalue': str,  # Exception value, as a string
                    'traceback': list(str),  # traceback frames, as strings
                }
            <   z
            The time to wait (in seconds) for the kernel to start.
            If kernel startup takes longer, a RuntimeError is
            raised.
            a  
            If ``False`` (default), when a cell raises an error the
            execution is stopped and a ``CellExecutionError``
            is raised, except if the error name is in
            ``allow_error_names``.
            If ``True``, execution errors are ignored and the execution
            is continued until the end of the notebook. Output from
            exceptions is included in the cell output in both cases.
            z
            List of error names which won't stop the execution. Use this if the
            ``allow_errors`` option it too general and you want to allow only
            specific kinds of errors.
            a  
            If False (default), errors from executing the notebook can be
            allowed with a ``raises-exception`` tag on a single cell, or the
            ``allow_errors`` or ``allow_error_names`` configurable options for
            all cells. An allowed error will be recorded in notebook output, and
            execution will continue. If an error occurs when it is not
            explicitly allowed, a ``CellExecutionError`` will be raised.
            If True, ``CellExecutionError`` will be raised for any error that occurs
            while executing the notebook. This overrides the ``allow_errors``
            and ``allow_error_names`` options and the ``raises-exception`` cell
            tag.
            zskip-executionz^
            Name of the cell tag to use to denote a cell that should be skipped.
             z
            Name of kernel to use to execute the cells.
            If not set, use the kernel_spec embedded in the notebook.
            a   
            If ``False`` (default), then the kernel will continue waiting for
            iopub messages until it receives a kernel idle message, or until a
            timeout occurs, at which point the currently executing cell will be
            skipped. If ``True``, then an error will be raised after the first
            timeout. This option generally does not need to be used, but may be
            useful in contexts where there is the possibility of executing
            notebooks with memory-consuming infinite loops.
            z
            If ``True`` (default), then the state of the Jupyter widgets created
            at the kernel will be stored in the metadata of the notebook.
            z
            If ``True`` (default), then the execution timings of each cell will
            be stored in the metadata of the notebook.
               a  
            The time to wait (in seconds) for IOPub output. This generally
            doesn't need to be set, but on some slow networks (such as CI
            systems) the default timeout might not be long enough to get all
            messages.
               z
            The time to wait (in seconds) for Shell output before retrying.
            This generally doesn't need to be set, but if one needs to check
            for dead kernels at a faster rate this can help.
            graceful	immediatea  
            If ``graceful`` (default), then the kernel is given time to clean
            up after executing all cells, e.g., to execute its ``atexit`` hooks.
            If ``immediate``, then the kernel is signaled to immediately
            terminate.
            )r;   r8   z:memory:a  Path to file to use for SQLite history database for an IPython kernel.

        The specific value ``:memory:`` (including the colon
        at both end but not the back ticks), avoids creating a history file. Otherwise, IPython
        will create a history file for each kernel.

        When running kernels simultaneously (e.g. via multiprocessing) saving history a single
        SQLite file can result in database errors, so using ``:memory:`` is recommended in
        non-interactive contexts.
        z The kernel manager class to use.)r:   klassr8   z
            A callable which executes after the kernel manager and kernel client are setup, and
            cells are about to execute.
            Called with kwargs ``notebook``.
            z
            A callable which executes after the kernel is cleaned up.
            Called with kwargs ``notebook``.
            z
            A callable which executes when the notebook encounters an error.
            Called with kwargs ``notebook``.
            z
            A callable which executes before a cell is executed and before non-executing cells
            are skipped.
            Called with kwargs ``cell`` and ``cell_index``.
            z
            A callable which executes just before a code cell is executed.
            Called with kwargs ``cell`` and ``cell_index``.
            z
            A callable which executes after a cell execution is complete. It is
            called even when a cell results in a failure.
            Called with kwargs ``cell`` and ``cell_index``.
            z
            A callable which executes just after a code cell is executed, whether
            or not it results in an error.
            Called with kwargs ``cell``, ``cell_index`` and ``execute_reply``.
            a  
            A callable which executes when a cell execution results in an error.
            This is executed even if errors are suppressed with ``cell_allows_errors``.
            Called with kwargs ``cell`, ``cell_index`` and ``execute_reply``.
            kernel_manager_classr%   type[KernelManager]c                    ddl m} |S )zBUse a dynamic default to avoid importing jupyter_client at startupr   )AsyncKernelManager)jupyter_clientrG   )selfrG   s     r3   _kernel_manager_class_defaultz,NotebookClient._kernel_manager_class_default  s     	655555!!    aP  
              mapping of locations of outputs with a given display_id
              tracks cell index and output index within cell.outputs for
              each appearance of the display_id
              {
                   'display_id': {
                  cell_idx: [output_idx,]
                   }
              }
              dict[str, t.Any]_display_id_map)z	text/htmlzapplication/pdfz
text/latexzimage/svg+xmlz	image/pngz
image/jpegztext/markdownz
text/plainz
            An ordered list of preferred output type, the first
            encountered will usually be used when converting discarding
            the others.
            z
            Additional resources used in the conversion process. For example,
            passing ``{'metadata': {'path': run_path}}`` sets the
            execution path to ``run_path``.
            	resourceszY
            Merge all stream outputs with shared names into single streams.
            nbr   kmKernelManager | Nonekwt.AnyNonec                     t                      j        di | || _        || _        |du | _        d| _        |                                  ddt          ii| _        d| j	        i| _
        dS )a  Initializes the execution manager.

        Parameters
        ----------
        nb : NotebookNode
            Notebook being executed.
        km : KernelManager (optional)
            Optional kernel manager. If none is provided, a kernel manager will
            be created.
        Nz@jupyter-widgets/outputOutputModelzjupyter.widget )super__init__rO   rP   owns_kmkcreset_execution_trackersr   widget_registryon_comm_open_jupyter_widgetcomm_open_handlers)rI   rO   rP   rR   	__class__s       r3   rY   zNotebookClient.__init__  s     	2 "(*4Z'+%%'''%|'D=

 d>5
rK   c                    d| _         d| _        i | _        i | _        i | _        t          j        t                    | _        i | _	        dS )z"Resets any per-execution trackers.Nr   )
task_poll_for_replycode_cells_executedrM   widget_statewidget_bufferscollectionsdefaultdictlistoutput_hook_stackcomm_objectsrI   s    r3   r\   z'NotebookClient.reset_execution_trackers  sM    AE #$ !9;PR )4(?(E(E.0rK   r   c                D   | j         s<| j        j                            di                               d          }||| _         | j         s!|                     | j                  | _        n&|                     | j         | j                  | _        | j        J | j        S )zCreates a new kernel manager.

        Returns
        -------
        km : KernelManager
            Kernel manager whose client class is asynchronous.
        
kernelspecnameNr9   )kernel_namer:   )ro   rO   metadatagetrD   r:   rP   )rI   kns     r3   create_kernel_managerz$NotebookClient.create_kernel_manager  s      	&!%%lB77;;FCCB~#%  	b//t{/CCDGG//D<LUYU`/aaDGw"""wrK   c                F  K   | j         J | j        dk    }	 t          | j                                                    d {V r.t          | j                             |                     d {V  n)# t          $ r}dt          |          vr Y d }~nd }~ww xY wt          | j                                                    d {V  t          | dd           rC| j        >t          | j        	                                           d {V  d | _        d | _         d S d S d S # t          | j                                                    d {V  t          | dd           rA| j        :t          | j        	                                           d {V  d | _        d | _         w xY w)NrB   )nowzNo kernel is running!r[   )
rP   shutdown_kernelr    is_aliveRuntimeErrorr&   cleanup_resourcesgetattrr[   stop_channels)rI   ru   es      r3   _async_cleanup_kernelz$NotebookClient._async_cleanup_kernel  s     w""""k1	!$'"2"2"4"455555555 E"47#:#:s#:#C#CDDDDDDDDD 	 	 	&c!ff44 54444	 tw88::;;;;;;;;;tT4(( TW-@"47#8#8#:#:;;;;;;;;; -@-@ tw88::;;;;;;;;;tT4(( TW-@"47#8#8#:#:;;;;;;;;;s1   AA3 2D  3
B=BD  BD   B F kwargsc                  K   | j         J | j                            di                               d          pd}|r	d|vr||d<   t          d | j        D                       }t          | j         d          r.| j         j        r"| j        r|s| xj        d| j         gz  c_        t           | j         j	        d	d| j        i|           d{V  dS )
aQ  Creates a new kernel.

        Parameters
        ----------
        kwargs :
            Any options for ``self.kernel_manager_class.start_kernel()``. Because
            that defaults to AsyncKernelManager, this will likely include options
            accepted by ``AsyncKernelManager.start_kernel()``, which includes ``cwd``.
        Nrp   pathcwdc              3  @   K   | ]}|                     d           V  dS )z--HistoryManager.hist_fileN)
startswith).0args     r3   	<genexpr>z8NotebookClient.async_start_new_kernel.<locals>.<genexpr>  s@       &
 &
=@CNN788&
 &
 &
 &
 &
 &
rK   	ipykernelz--HistoryManager.hist_file=extra_argumentsrW   )
rP   rN   rq   anyr   hasattrr   ipython_hist_filer    start_kernel)rI   r~   resource_pathhas_history_manager_args       r3   async_start_new_kernelz%NotebookClient.async_start_new_kernel  s2      w"""**:r::>>vFFN$ 	*U&00)F5M"% &
 &
DHDX&
 &
 &
 #
 #
 DG[))	]!	] &	] ,		]   %[4CY%[%[$\\  /47/__@T_X^__```````````rK   r
   c           
     v  K   | j         J 	 | j                                         | _        t          | j                                                   d{V  t          | j                            | j                             d{V  n|# t          $ ro}| j        	                    d
                    t          | j         dd          t          |                               |                                  d{V   d}~ww xY wd| j        _        t          | j        | j                   d{V  | j        S )zCreates a new kernel client.

        Returns
        -------
        kc : KernelClient
            Kernel client as created by the kernel manager ``km``.
        NtimeoutzAError occurred while starting new kernel client for kernel {}: {}	kernel_idFnotebook)rP   clientr[   r    start_channelswait_for_readystartup_timeoutr.   logerrorformatrz   r&   r}   allow_stdinr!   on_notebook_startrO   )rI   r|   s     r3   async_start_new_kernel_clientz,NotebookClient.async_start_new_kernel_client*  s^      w"""	gnn&&DGtw5577888888888tw55d>R5SSTTTTTTTTTT 	 	 	HNNSZZDG[$77Q   
 ,,.........	 $t-@@@@@@@@@@ws   A=B 
DA*C??Dt.Generator[None, None, None]c              +  Z  K   |                     d| j                  }| j        |                                 | _        | j        j        s | j        di | | j        |                                  	 dV  |r|                                  dS dS # |r|                                  w w xY w)a'  
        Context manager for setting up the kernel to execute a notebook.

        The assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).

        When control returns from the yield it stops the client's zmq channels, and shuts
        down the kernel.
        
cleanup_kcNrW   )	poprZ   rP   rs   
has_kernelstart_new_kernelr[   start_new_kernel_client_cleanup_kernel)rI   r~   r   s      r3   setup_kernelzNotebookClient.setup_kernelE  s       ZZdl;;
 7?0022DGw! 	,!D!++F+++7?((***	'EEE '$$&&&&&' 'z '$$&&&&'s   3B B*t.AsyncGenerator[None, None]c               $   K   |                     d j                  } j                                          _        t	          j         j                   d fd}t          j                    }	 |	                    t          j        |           |	                    t          j        |           n# t          $ r Y nw xY w j        j        s  j        di | d{V   j                                          d{V  	 dW V  n5# t          $ r(}t%           j         j                   d{V  |d}~ww xY w	 |r                                  d{V  t%           j         j                   d{V  t	          j         j                   	 |                    t          j                   |                    t          j                   dS # t          $ r Y dS w xY w# |r                                  d{V  t%           j         j                   d{V  t	          j         j                   	 |                    t          j                   |                    t          j                   w # t          $ r Y w w xY wxY w)	a  
        Context manager for setting up the kernel to execute a notebook.

        This assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).

        When control returns from the yield it stops the client's zmq channels, and shuts
        down the kernel.

        Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown.
        r   Nr%   rT   c                     t          j                                                    _        t	          j         j                   dS )zHandle signals.N)asyncioensure_futurer}   _async_cleanup_kernel_futureatexit
unregisterr   rk   s   r3   	on_signalz4NotebookClient.async_setup_kernel.<locals>.on_signaly  s<    070EdF`F`FbFb0c0cD-d233333rK   r   r%   rT   rW   )r   rZ   rP   rs   r   registerr   r   get_event_loopadd_signal_handlersignalSIGINTSIGTERMrx   r   r   r[   r   r!   on_notebook_errorrO   r}   on_notebook_completer   remove_signal_handler)rI   r~   r   r   loopr|   s   `     r3   async_setup_kernelz!NotebookClient.async_setup_kernelc  s(      ZZdl;;
7?0022DG 	,---	4 	4 	4 	4 	4 	4
 %''	##FM9===##FNI>>>> 	 	 	 D	
 w! 	8-$-777777777777?44666666666	EEEEE 	 	 	41DGDDDDDDDDDDG	 
  30022222222244twGGGGGGGGGGd2333**6=999**6>:::::     30022222222244twGGGGGGGGGGd2333**6=999**6>::::   st   2A B3 3
C ?C D
 	G( 

D<#D77D<<G( >G 
G%$G%(AJ >I?>J?
J	JJJreset_kcboolc                   K   |r!| j         r|                                  d{V  |                                   | j        di |4 d{V  | j        J | j                            d| j        z             t          | j        	                                           d{V }| 
                    |           d{V }|Kd|d         v r|d         d         | j        j        d<   n%t          dt          |d                   z             t          | j        j                  D ]+\  }}|                     ||| j        dz              d{V  ,|                                  ddd          d{V  n# 1 d{V swxY w Y   | j        S )	aT  
        Executes each code cell.

        Parameters
        ----------
        kwargs :
            Any option for ``self.kernel_manager_class.start_kernel()``. Because
            that defaults to AsyncKernelManager, this will likely include options
            accepted by ``jupyter_client.AsyncKernelManager.start_kernel()``,
            which includes ``cwd``.

            ``reset_kc`` if True, the kernel client will be reset and a new one
            will be created (default: False).

        Returns
        -------
        nb : NotebookNode
            The executed notebook.
        Nz"Executing notebook with kernel: %slanguage_infocontentzMKernel info received message content has no "language_info" key. Content is:
r   )execution_countrW   )rZ   r}   r\   r   r[   r   inforo   r    kernel_infoasync_wait_for_replyrO   rp   rx   r&   	enumeratecellsasync_execute_cellrc   set_widgets_metadata)rI   r   r~   msg_idinfo_msgindexcells          r3   async_executezNotebookClient.async_execute  s     (  	/ 	/,,.........%%'''*4*44V44 	( 	( 	( 	( 	( 	( 	( 	(7&&&HMM>AQQRRR'(;(;(=(=>>>>>>>>F!66v>>>>>>>>H#"hy&9998@8KO8\DG$_55&(*-hy.A*B*BC    )77  t --%1IA1M .           %%''''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(* ws   DE88
FFc                x     j         rd fd j                                         D             dddi j        j        _         j        j        j        d         d                                         D ]G\  }} j                            |          }|r$t          |                                          |d<   FdS dS )	zSet with widget metadata.z)application/vnd.jupyter.widget-state+jsonc                J    i | ]\  }}d |v 	|                     |           S )_model_name)_serialize_widget_state)r   model_idstaterI   s      r3   
<dictcomp>z7NotebookClient.set_widgets_metadata.<locals>.<dictcomp>  sB       +He(E11 !$">">u"E"E111rK      r   )r   version_majorversion_minorr   buffersN)	rd   itemsrO   rp   widgetsre   rq   rh   values)rI   keywidgetr   s   `   r3   r   z#NotebookClient.set_widgets_metadata  s     	?;   /3/@/F/F/H/H  
 &'%&> >
(DG$  $w/7;  uww? ?V -11#66 ?(,W^^-=-=(>(>F9%#	? 	?? ?rK   
display_idr&   r#   c                   || j         vr#| j                            d|| j                    dS |d         d         dk    rd|d         d<   	 t          |          }n4# t          $ r' | j                            d|d                     Y dS w xY w| j         |                                         D ]G\  }}| j        d         |         }|d	         }|D ]$}|d
         ||         d
<   |d         ||         d<   %HdS )z&Update outputs with a given display_idzdisplay id %r not in %sNr(   msg_typeupdate_display_datadisplay_dataunhandled iopub msg: r   outputsdatarp   )rM   r   debugr   
ValueErrorr   r   rO   )	rI   r   r#   outcell_idxoutput_indicesr   r   
output_idxs	            r3   _update_display_idz!NotebookClient._update_display_id  s=   T111HNN4j$BVWWWFx=$(===(6CM*%	!#&&CC 	 	 	HNND3z?DDEEEFF	 )-(<Z(H(N(N(P(P 	B 	B$Hn77#H-D9oG, B B
.1&k
#F+25j/
#J//B	B 	Bs   A -BBr   r   r   
int | Nonetask_poll_output_msgasyncio.Future[t.Any]task_poll_kernel_alivec                  K   | j         J d }| t                      |z   }t          |          }d }	 	 |r
|}	d|i|	d<   n3t          | j         j                            |                     d {V }	|	d                             d          |k    r| j        rt          |	          |d         d         d<   	 t          j
        || j                   d {V  nm# t          j        t          f$ rT | j        r0|                                 t!          j        d| j        |          d | j                            d           Y nw xY w|                                 |	S |t)          d	|t                      z
            }n^# t          $ rQ |J |                                 |                                  d {V  |                     ||           d {V }Y nw xY w)
NTr   parent_headerr   rp   	executionzshell.execute_replyz Timeout waiting for IOPub outputr   )r[   r	   floatr    shell_channelget_msgrq   record_timingr4   r   wait_foriopub_timeoutTimeoutErrorr   raise_on_iopub_timeoutcancelr   error_from_timeout_and_cellr   warningmax_async_check_alive_async_handle_timeout)
rI   r   r   r   r   r   new_timeoutdeadlineerror_on_timeout_execute_replyr#   s
             r3   _async_poll_for_replyz$NotebookClient._async_poll_for_reply  sp      w"""$( {{W,H..K)-&	aa1 a8C,4f+=C(( ,TW-B-J-JS^-J-_-_ ` ```````C'++H55??) ^OXY\~~Z(56KL	Q%./CTEWXXXXXXXXXX#0%8 Q Q Q6 Q299;;;"2"N BDDVX\# ##'( !H,,-OPPPPPQ +11333J".&)!X	-C&D&D a a a***&--///--/////////7;7Q7QRY[_7`7`1`1`1`1`1`1`...a3	as>   BE> 8 C E> A'E E> EE> !E> >AGGparent_msg_id
cell_indexintc                  K   | j         J 	 t          | j         j                            d                      d {V }|d                             d          |k    r*	 |                     |||           n# t          $ r Y d S w xY w})NTr   r   r   )r[   r    iopub_channelr   rq   process_messager   )rI   r  r   r	  r#   s        r3   _async_poll_output_msgz%NotebookClient._async_poll_output_msg(  s       w"""	$TW%:%B%B4%B%P%PQQQQQQQQC?#''11]BB((dJ????,   FF	s    A8 8
BBc                   K   	 t          j        d           d {V  	 |                                  d {V  n3# t          $ r& | j        J | j                                         Y d S w xY wj)NTr   )r   sleepr  r   rb   r   rk   s    r3   _async_poll_kernel_alivez'NotebookClient._async_poll_kernel_alive5  s      	-"""""""""--//////////"   /;;;(//111		s   : ,A*)A*NotebookNode | Nonec                f    | j         ||                      |          }n| j        }|r|dk     rd }|S )Nr   )r<   r   )rI   r   r   s      r3   _get_timeoutzNotebookClient._get_timeout?  sF    (T-=''--GGlG 	'A++GrK   None | dict[str, t.Any]c                T  K   | j                             d|z             | j        ri| j                             d           | j        J t	          | j                                                   d {V  | j        rdi | j        ddii}|S d S |J t          j        d||          )Nz(Timeout waiting for execute reply (%is).zInterrupting kernelr   statusr   zCell execution timed out)	r   r   interrupt_on_timeoutrP   r    interrupt_kernelerror_on_timeoutr   r   )rI   r   r   execute_replys       r3   r  z$NotebookClient._async_handle_timeoutJ  s       	AGKLLL$ 	HNN01117&&&tw7799:::::::::$ %!*,Xt/D,XhPW,X,X Y$$4###">*GT  rK   c                   K   | j         J t          | j                                                    d {V s)| j                            d           t          d          d S )Nz,Kernel died while waiting for execute reply.Kernel died)r[   r    rw   r   r   r   rk   s    r3   r  z!NotebookClient._async_check_alive\  sq      w"""!$'"2"2"4"455555555 	1HNNIJJJ!-000	1 	1rK   r$   c                  K   | j         J |                     |          }d}	 	 t          | j         j                            | j                             d{V }|d                             d          |k    r|S nZ# t          $ rM |                                  d{V  || j        z  }|r$||k    r| 	                    ||           d{V  Y nY nw xY wdS )zWait for a message reply.Nr   Tr   r   r   )
r[   r  r    r   r   shell_timeout_intervalrq   r   r  r  )rI   r   r   r   cummulative_timer#   s         r3   r   z#NotebookClient.async_wait_for_replyb  sJ      w"""##D))	.:G)11$:U1VV/ / ) ) ) ) ) ) '++H55??J @    --///////// D$??  /'9944WdCCCCCCCCCE	 ts   8A? ?ACCr  c                8    ||t                      z
  dk    rdS dS )Nr   TFr   )rI   r  s     r3   _passed_deadlinezNotebookClient._passed_deadline~  s%    Hy{{$:a$?$?4urK   
exec_replyc                8  K   |d S |d         }|d         dk    rd S | j          o?| j        p8|                    d          | j        v pd|j                            dg           v }t          | j        |||           d {V  |st          j        ||          d S )Nr   r  r   enameraises-exceptiontagsr   r	  r  )	force_raise_errorsallow_errorsrq   allow_error_namesrp   r!   on_cell_errorr   from_cell_and_msg)rI   r   r	  r#  exec_reply_contentcell_allows_errorss         r3   _check_raise_for_errorz%NotebookClient._check_raise_for_error  s       4'	2h'7224"&"99 
 C!%%g..$2HHC!T]%6%6vr%B%BB 	
 TjPZ
 
 
 	
 	
 	
 	
 	
 	
 	
 " 	Q$6t=OPPP	Q 	QrK   r   store_historyc           	     	  K   | j         J t          | j        ||           d{V  |j        dk    s|j                                        s| j                            d|           |S | j        |j	        
                    dg           v r| j                            d|           |S | j        ri |d         d<   | j                            d	|j                   | j         o#| j        pd
|j	        
                    dg           v }t          | j        ||           d{V  t          | j                             |j        ||                      d{V }t          | j        ||           d{V  | xj        dz  c_        |                     |          }g |_        d| _        t-          j        |                                           }t-          j        |                     |||                    }	t-          j        |                     ||||	|                    | _        	 | j         d{V }
nt# t,          j        $ r% |	                                 t=          d          dt>          $ r5}	 tA          |tB                    s|	                                  #  xY wd}~ww xY w|r||d<   t          | j"        |||
           d{V  | j#        r|j        rg }i }|j        D ]q}|d         dk    rN|d         |v r#||d                  dxx         |d         z  cc<   ;|$                    |           |||d         <   \|$                    |           r|%                                D ]}|d         }tM          |d                   tM          |          k     rR|d         }tN          (                    d|d                   |d<   tM          |d                   tM          |          k     RtR          (                    d|d                   |d<   tU          |          D ]\  }}|d         dk    rz|d         dk    rntM          |          |dz   k    rX||dz            d         dk    rC||dz            d         dk    r.|+                    |dz             }|,                    ||           ||_        | -                    |||
           d{V  || j.        d         |<   |S )a  
        Executes a single code cell.

        To execute all cells see :meth:`execute`.

        Parameters
        ----------
        cell : nbformat.NotebookNode
            The cell which is currently being processed.
        cell_index : int
            The position of the cell within the notebook object.
        execution_count : int
            The execution count to be assigned to the cell (default: Use kernel response)
        store_history : bool
            Determines if history should be stored in the kernel (default: False).
            Specific to ipython kernels, which can store command histories.

        Returns
        -------
        output : dict
            The execution output payload (or None for no output).

        Raises
        ------
        CellExecutionError
            If execution failed and should raise an exception, this will be raised
            with defaults about the failure.

        Returns
        -------
        cell : NotebookNode
            The cell which was just processed.
        N)r   r	  codezSkipping non-executing cell %sr'  zSkipping tagged cell %srp   r   zExecuting cell:
%sr&  )r1  stop_on_errorr   Fr  r   r(  output_typestreamrn   textr>   stderrr   stdoutr   )/r[   r!   on_cell_start	cell_typesourcestripr   r   skip_cells_with_tagrp   rq   r   r)  r*  on_cell_executer    executeon_cell_completerc   r  r   clear_before_next_outputr   r   r  r  r  rb   CancelledErrorr   r   r.   r+   r   on_cell_executedcoalesce_streamsappendr   len_RGX_BACKSPACEsub_RGX_CARRIAGERETURNr   r   insertr0  rO   )rI   r   r	  r   r1  r/  r  exec_timeoutr   r   r#  r|   new_outputsstreamsoutputoldir9  s                     r3   r   z!NotebookClient.async_execute_cell  s     P w"""t)LLLLLLLLLL>V##4;+<+<+>+>#HNN;ZHHHK#t}'8'8'D'DDDHNN4jAAAK 	/,.D[),dk:::"&"99 
T!3t}7H7HQS7T7T!T 	 t+$:NNNNNNNNNN*GOO=L^H^   
 
 
 
 
 
 
 

 t,4JOOOOOOOOOO  A%  ((..(-%!(!6t7T7T7V7V!W!W&4''tZHH 
  
 $+#8&&t\3GI_ $
 $
 
	#7777777JJ% 	; 	; 	; '')))!-00d: 	 	 	!!%677 2(//111	  	6&5D"#!S]
 
 
 	
 	
 	
 	
 	
 	
 	
   #	'T\ #	'K/1G, / /-(H44f~00v/7776&>I7777#**622228v//&&v.... "..** M MVn&.))CHH44 .C%3%7%7F6N%K%KF6N &.))CHH44
 "5!8!8VF^!L!Lv '{33 6 6	6-(H4489S9SK((AE11'A.}=II'A.v6(BB!,Q!7!7#**1f555&DL))$
JGGGGGGGGG'+$s*   *H8 8<J)5)JJ$J!!J$$J)c                   |d         }| j                             d|           |d         }| j                             d|           |                    d          }|r|                    d          nd}|r|dv r|                     ||           d	|v r|d	         |d	<   | j        r|d
k    rV|d         dk    rt          |          |d         d         d<   nO|d         dk    rt          |          |d         d         d<   n$|dk    rt          |          |d         d         d<   |d
k    r|d         dk    rt                      nv|dk    r|                     |j        ||           nS|	                    d          r| 
                    |j        ||           n!|dvr|                     |j        |||          S dS )a  
        Processes a kernel message, updates cell state, and returns the
        resulting output object that was appended to cell.outputs.

        The input argument *cell* is modified in-place.

        Parameters
        ----------
        msg : dict
            The kernel message being processed.
        cell : nbformat.NotebookNode
            The cell which is currently being processed.
        cell_index : int
            The position of the cell within the notebook object.

        Returns
        -------
        output : NotebookNode
            The execution output payload (or None for no output).

        Raises
        ------
        CellExecutionComplete
          Once a message arrives which indicates computation completeness.

        r   zmsg_type: %sr   zcontent: %s	transientr   N>   r   execute_resultr   r   r  execution_stateidlerp   r   ziopub.status.idlebusyziopub.status.busyexecute_inputziopub.execute_inputclear_outputcomm)rX  r   )r   r   rq   r   r   r4   r   rY  r   r   handle_comm_msgrO  )rI   r#   r   r	  r   r   rS  r   s           r3   r  zNotebookClient.process_message-  s   : z?~x000i.}g...
 KK,,	4=GY]]<0004
 	5(&___##J444 ''&-.?&@D"# 	V8##,-77IRSVD$[12EFF./699IRSVD$[12EF_,,GPQT~~Z -.CDx()V33+--- 4''dlC<<<<  (( 	J  sJ????EEE;;t|S*jIIItrK   outslist[NotebookNode]c                   |d         }d}|d                              d          }| j        |         r-| j        |         d         }|                    ||||           dS 	 t          |          }n.# t          $ r! | j                            d|            Y dS w xY w| j        r=| j                            d           g |dd<   | 	                    |           d| _        |rS| j
                            |i           }	|	                    |g           }
|
                    t          |                     |r|                    |           |S )	zHandle output.r   Nr   r   r   zExecuting delayed clear_outputF)rq   ri   rO  r   r   r   r   rB  r   clear_display_id_mappingrM   
setdefaultrF  rG  )rI   r\  r#   r   r	  r   r   r  hookcell_mapoutput_idx_lists              r3   rO  zNotebookClient.outputr  sy   
 z?#'O,00::!-0 	 )-8<DKKc:z:::4	!#&&CC 	 	 	HNN=8==>>>44	 ( 	2HNN;<<<DG))*555,1D) 	. +66z2FFH&11*bAAO""3t99--- 	KK
s   !A1 1'BBc                   |d         }|d                              d          }| j        |         r,| j        |         d         }|                    |||           dS |                     d          r#| j                            d           d| _        dS | j                            d	           g |dd<   |                     |           dS )
zClear output.r   r   r   r_  NwaitzWait to clear outputTzImmediate clear output)rq   ri   rY  r   r   rB  r`  )rI   r\  r#   r	  r   r  rb  s          r3   rY  zNotebookClient.clear_output  s     i.O,00::!-0 	 )-8<DdC444F;;v 	6HNN1222,0D)))HNN3444DG))*55555rK   c                V    | j                                         D ]\  }}||v rg ||<   dS )z&Clear a display id mapping for a cell.N)rM   r   )rI   r	  _rc  s       r3   r`  z'NotebookClient.clear_display_id_mapping  sD    /5577 	* 	*KAxX%%')$	* 	*rK   c                B   |d         }|d         }| j         rd|v r| j                            |d         i                               |d                    |                    d          rZ|d         }|| j        vr
i | j        |<   d |                     |          D             }| j        |                             |           |d         dk    r|d                             d	          }| j                            |          }	|	r)|d         d         } |	|          }
|
r|
| j        |<   dS dS | j	        
                    d
|           dS |d         dk    rA|d         }|d         d         }|| j        v r$| j        |                             |           dS dS dS )zHandle a comm message.r   r   r   comm_idbuffer_pathsc                :    i | ]}t          |d                    |S )r   )tuple)r   ks     r3   r   z2NotebookClient.handle_comm_msg.<locals>.<dictcomp>  s9     F F F,-E!F)$$aF F FrK   r   	comm_opentarget_namez!No handler found for comm target comm_msgN)store_widget_staterd   ra  updaterq   re   _get_buffer_datar_   rj   r   r   
handle_msg)rI   r\  r#   r	  r   r   rj  new_bufferstargethandlercomm_objects              r3   r[  zNotebookClient.handle_comm_msg  s    i.v" 
	Aw$(();R@@GGWVVVxx'' A!),$"55535D'0F F151F1Fs1K1KF F F #G,33K@@@ z?k))^''66F-11&99G Qi.3%gcll =1<D%g...= =   !OV!O!OPPPPP_
**)nG)nY/G$+++!'*55c:::::	 +* ,+rK   r   c                    |                     d          |                     d          |                     d          |dS )zFSerialize a widget state, following format in @jupyter-widgets/schema.r   _model_module_model_module_version)
model_namemodel_modulemodel_module_versionr   )rq   )rI   r   s     r3   r   z&NotebookClient._serialize_widget_state  sD      ))M22!IIo66$)II.E$F$F	
 
 	
rK   list[dict[str, str]]c                    g }|d         d         d         }|d         }t          ||          D ]C\  }}|                    t          j        |                              d          d|d           D|S )Nr   r   rk  r   zutf-8base64)r   encodingr   )ziprF  r  	b64encodedecode)rI   r#   encoded_bufferspathsr   r   buffers          r3   rt  zNotebookClient._get_buffer_data  s    Iv&~6i.w// 	 	LD&""",V44;;GDD (      rK   rb  r   c                F    | j         |                             |           dS )zRegisters an override object that handles output/clear_output instead.

        Multiple hooks can be registered, where the last one will be used (stack based)
        N)ri   rF  )rI   r   rb  s      r3   register_output_hookz#NotebookClient.register_output_hook  s&     	v&--d33333rK   c                T    | j         |                                         }||k    sJ dS )zGUnregisters an override object that handles output/clear_output insteadN)ri   r   )rI   r   rb  removed_hooks       r3   remove_output_hookz!NotebookClient.remove_output_hook  s4     -f599;;t######rK   t.Any | Nonec                    |d         }|d         }|d         }|d         d         }| j                             |d                   }|r0|                    |d                   }|r |||| j        |           S dS )z"Handle a jupyter widget comm open.r   r   r   rj  r{  r   N)r]   rq   r[   )rI   r#   r   r   r   rj  modulewidget_classs           r3   r^   z*NotebookClient.on_comm_open_jupyter_widget   s    i.vWi.+%))%*@AA 	C!::eM&:;;L C#|GUDGTBBBtrK   )r%   rE   N)rO   r   rP   rQ   rR   rS   r%   rT   r   )r%   r   )r~   rS   r%   rT   )r%   r
   )r~   rS   r%   r   )r~   rS   r%   r   )F)r   r   r~   rS   r%   r   )r   r&   r#   rL   r%   rT   )r   r&   r   r   r   r   r   r   r   r   r%   rL   )r  r&   r   r   r	  r
  r%   rT   )r   r  r%   r   )r   r
  r   r  r%   r  )r   r&   r   r  r%   r$   )r  r   r%   r   )r   r   r	  r
  r#  r$   r%   rT   )NT)
r   r   r	  r
  r   r   r1  r   r%   r   )r#   rL   r   r   r	  r
  r%   r  )
r\  r]  r#   rL   r   r&   r	  r
  r%   r  )r\  r]  r#   rL   r	  r
  r%   rT   )r	  r
  r%   rT   )r   rL   r%   rL   )r#   rL   r%   r  )r   r&   rb  r   r%   rT   )r#   rL   r%   r  )\__name__
__module____qualname____doc__r   r   tagr   r   r<   __annotations__r   r  r   r  r   r*  r   r   r+  r)  r>  r   ro   r   rr  r   r   r  r   rv   r   r   r   rD   r   r   r   r   r:  r?  rA  rD  r,  r   rJ   rM   display_data_priorityrN   rE  rY   r\   rs   r}   r"   r   r   r   r   r   r   r   r   r   r   r@  r   r   r  r  r  r  r  r  r   wait_for_reply_wait_for_replyr"  r0  r   execute_cellr  rO  rY  r`  r[  r   rt  r  r  r^   __classcell__)r`   s   @r3   r6   r6   <   s          gV
 
   
cc  8;sV

 
8 8 8  
cc!     $  4V
 
	 	 	 
cc  tV
 
  " 
cc# & g
V
 
	 	 	 
cc  4V

 

   
cc  		V
 
	 	 	 
cc  V
 
    
cc! $ "'V
 
   
cc  d7799oo)))66O'
V
 
   
cc  "TV

 

   
cc  V
 
   
cc  DV
 
   
cc  G	V
 
   
cc  %W	V
 

 
 
 
cc  d	[! V
 
   
cc    	   
cc   4=/Q   !V
 

 
 
 
cc  $8V
 
	 	 	 
cc  !V
 
	 	 	 
cc  HV
 

 
 
 
cc  hV
 
	 	 	 
cc   xV
 

 
 
 
cc   xV
 

 
 
 
cc  HV
 

 
 
 
cc  W#$$" " " %$" )-V	
 
) ) )O     !D		
 		
 		
    
cc! $ #'$V
 
# # #I     tV
 
  
 
 
 
 
 
 
21 1 1 1   (   & h455Oa a a a8  x 677   2 'h'DEE' ' ' ^': 7 7 7 7r- - - - -^ h}%%G? ? ? ?*B B B B,-a -a -a -a^      	 	 	 	 9=    $1 1 1 1 8<    0 X233N$O   
Q Q Q Q2 '+"Q Q Q Q Qf 8.//LC C C CJ& & & &P6 6 6 6,* * * *!; !; !; !;F
 
 
 
   4 4 4 4$ $ $ $       rK   r6   rO   r   r   
str | NonerP   rQ   r~   rS   c                \    i }|d|i|d<   t          d| ||d|                                S )a+  Execute a notebook's code, updating outputs within the notebook object.

    This is a convenient wrapper around NotebookClient. It returns the
    modified notebook object.

    Parameters
    ----------
    nb : NotebookNode
      The notebook object to be executed
    cwd : str, optional
      If supplied, the kernel will run in this directory
    km : AsyncKernelManager, optional
      If supplied, the specified kernel manager will be used for code execution.
    kwargs :
      Any other options for NotebookClient, e.g. timeout, kernel_name
    Nr   rp   )rO   rN   rP   rW   )r6   r@  )rO   r   rP   r~   rN   s        r3   r@  r@    sE    , I
!'	*FR9FFvFFNNPPPrK   r  )r#   r$   r%   r&   )NN)
rO   r   r   r  rP   rQ   r~   rS   r%   r   )<r  
__future__r   r   r   r  rf   r,   rer   typingt
contextlibr   r   queuer   textwrapr   timer	   jupyter_client.clientr
   jupyter_client.managerr   nbformatr   nbformat.v4r   	traitletsr   r   r   r   r   r   r   r   r   r   traitlets.config.configurabler   
exceptionsr   r   r   r   r   output_widgetr   utilr    r!   r"   compilerJ  rH  r4   r6   r@  rW   rK   r3   <module>r     sv     " " " " " "         				      : : : : : : : :                   . . . . . . 0 0 0 0 0 0 ! ! ! ! ! ! ' ' ' ' ' ' \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ = = = = = =              ( ' ' ' ' ' 2 2 2 2 2 2 2 2 2 2 bj!122 J''
8 8 8 8 8(O O O O O( O O Oh& #Q Q Q Q Q Q QrK   