
    Vf%"                    0   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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mZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
l m!Z" ddl#m$Z$m%Z% dZ&ejN                  ejP                     d   ejN                  ejP                     d   dejN                  ejP                     d   dZ)dZ*d Z+ejX                  Z-d Z.d Z/d5dZ0d6dZ1d6dZ2d Z3d Z4d Z5d7dZ6 ej0                  jn                  d8i  ejp                          G d d             Z9 G d d      Z: G d  d!      Z; G d" d#      Z< G d$ d%      Z=d& Z>d9d'Z?d:d(Z@d) ZAd;d*ZB G d+ d,      ZC G d- d.      ZDd/ ZEd<d0ZFd1 ZGd=d2ZHd>d3ZId4 ZJy)?a  
plotly
======

A module that contains the plotly class, a liaison between the user
and ploty's servers.

1. get DEFAULT_PLOT_OPTIONS for options

2. update plot_options with .plotly/ dir

3. update plot_options with _plot_options

4. update plot_options with kwargs!

    )absolute_importN)CompoundValidatoris_array)PlotlyJSONEncoder)filessessiontoolsutils
exceptions)v2)chunked_requests)Grid)dashboard_objs)
get_configget_credentialsworld_readable	auto_openTsharing)r   r   validater   zKWhoops, sharing can only be set to either 'public', 'private', or 'secret'.c                     t        j                  | |fi | 	 t        j                  j	                          y # t
        j                  $ r  t        j
                  j                  d      w xY w)NzSign in failed.)	r   sign_inr   userscurrentr   PlotlyRequestError_plotly_utilsPlotlyError)usernameapi_keykwargss      c/var/www/html/software/conda/envs/catlas/lib/python3.12/site-packages/chart_studio/plotly/plotly.pyr   r   <   s\    OOHg00F 	(( F&&223DEEFs	   8 3A+c                 
   t        j                  t              }t        j                         }t        j                         }t        j                  |       } | ||fD ],  }t        j                  |       t        j                  |       . i }|j                  |       |j                  |       |j                  |       |j                  |        |j                         D ci c]  \  }}||v s|dk(  r|| }}}|S c c}}w )ai  
    Given some plot_options as part of a plot call, decide on final options.
    Precedence:
        1 - Start with DEFAULT_PLOT_OPTIONS
        2 - Update each key with ~/.plotly/.config options (tls.get_config)
        3 - Update each key with session plot options (set by py.sign_in)
        4 - Update each key with plot, iplot call signature options

    filename)copydeepcopyDEFAULT_PLOT_OPTIONSr	   get_config_filer   get_session_plot_optionsr
   ,validate_world_readable_and_sharing_settingsset_sharing_and_world_readableupdateitems)plot_options_from_argsdefault_plot_optionsfile_optionssession_options
option_setuser_plot_optionskvs           r    _plot_option_logicr4   I   s     ==)=>((*L668O!]]+AB .M 9
:::F,,Z89 12\*_-34 &++-Aq$$Z 	
1  s   $C?c                    ddl m}m} d|vrd|d<   t        | fi |}t	        | t
              r/| j                  di       }t	        ||      r:|j                         }n)t	        | |      r| j                  j                         }ni }t               }|j                  dd      |d<   |j                  dd	      |d<   	 t        |d          t        |d         d
z   |d<   	 t        |d          t        |d         d
z   |d<   t        j                  |fi |S # t        t        f$ r Y Jw xY w# t        t        f$ r Y <w xY w)a  Create a unique url for this plot in Plotly and open in IPython.

    plot_options keyword arguments:
    filename (string) -- the name that will be associated with this figure
    sharing ('public' | 'private' | 'secret') -- Toggle who can view this graph
        - 'public': Anyone can view this graph. It will appear in your profile
                    and can appear in search engines. You do not need to be
                    logged in to Plotly to view this chart.
        - 'private': Only you can view this plot. It will not appear in the
                     Plotly feed, your profile, or search engines. You must be
                     logged in to Plotly to view this graph. You can privately
                     share this graph with other Plotly users in your online
                     Plotly account and they will need to be logged in to
                     view this plot.
        - 'secret': Anyone with this secret link can view this chart. It will
                    not appear in the Plotly feed, your profile, or search
                    engines. If it is embedded inside a webpage or an IPython
                    notebook, anybody who is viewing that page will be able to
                    view the graph. You do not need to be logged in to view
                    this plot.
    world_readable (default=True) -- Deprecated: use "sharing".
                                     Make this figure private/public
    r   
BaseFigureBaseLayoutTyper   Flayoutwidth100%height  px)plotly.basedatatypesr7   r8   plot
isinstancedictgetto_plotly_jsonr9   floatstr
ValueError	TypeErrorr	   embed)figure_or_dataplot_optionsr7   r8   urlr9   embed_optionss          r    iplotrN   k   sR   0 @,&$)[!
~
.
.C.$'##Hb1fn-**,F	NJ	/&&557FM#ZZ8M'$jj37M(DmG$% "%]7%;!<t!CgFmH%& #&mH&=">"Eh;;s,m,, 	"  	" s$   ;D D+ D('D(+D=<D=c                 &   ddl }|j                  j                  | |      }|d   D ]V  }d|v r	|d   dk(  rt        |j	                               D ]+  \  }}	 t        |      dkD  rd}t        j                  |       - X t        |      }|dd	}	|j                  d
d      }
|
rY|
d   dk(  r|
dd }
|
j                  d      }dj                  |dd       }|d   }
|rt        j                  |       ||	d<   |
|	d
<   nd}|j                  dd      }|dk(  rd|	d<   n>|dk(  rd|	d<   n3|dk(  rd|	d<   d|	d<   n#t        j                   j#                  t$              t'        |      \  }}t        |      dkD  rE|
sd}n|r|dz   |
z   dz   }n|
dz   }t(        j+                  |||	d   d       t-        ||       ||	d<   t/        |	d      }|dk(  r|d   dd dz   |d   z   }n|d   }|j                  dd      }|rt1        |       |S # t        $ r Y w xY w)a  Create a unique url for this plot in Plotly and optionally open url.

    plot_options keyword arguments:
    filename (string) -- the name that will be associated with this figure
    auto_open (default=True) -- Toggle browser options
        True: open this plot in a new browser tab
        False: do not open plot in the browser, but do return the unique url
    sharing ('public' | 'private' | 'secret') -- Toggle who can view this
                                                  graph
        - 'public': Anyone can view this graph. It will appear in your profile
                    and can appear in search engines. You do not need to be
                    logged in to Plotly to view this chart.
        - 'private': Only you can view this plot. It will not appear in the
                     Plotly feed, your profile, or search engines. You must be
                     logged in to Plotly to view this graph. You can privately
                     share this graph with other Plotly users in your online
                     Plotly account and they will need to be logged in to
                     view this plot.
        - 'secret': Anyone with this secret link can view this chart. It will
                    not appear in the Plotly feed, your profile, or search
                    engines. If it is embedded inside a webpage or an IPython
                    notebook, anybody who is viewing that page will be able to
                    view the graph. You do not need to be logged in to view
                    this plot.
    world_readable (default=True) -- Deprecated: use "sharing".
                                     Make this figure private/public

    r   Ndatatype	scattergli@  aU  Woah there! Look at all those points! Due to browser limitations, the Plotly SVG drawing functions have a hard time graphing more than 500k data points for line charts, or 40k points for other types of charts. Here are some suggestions:
(1) Use the `plotly.graph_objs.Scattergl` trace object to generate a WebGl graph.
(2) Trying using the image API to return an image instead of a graph URL
(3) Use matplotlib
(4) See if you can create your visualization with fewer data points

If the visualization you're using aggregates points (e.g., box plot, histogram, etc.) you can disregard this warning.T)figurer   r"   /parent_path r   publicr   privateFsecretshare_key_enabled_grid)gridr"   r   r   rS   r@   web_url?share_key=	share_keyr   )plotly.toolsr	   !return_figure_from_figure_or_datalistr+   lenwarningswarnrH   r4   rC   splitjoinfile_opsensure_dirsr   r   r   SHARING_ERROR_MSG_extract_grid_from_fig_likegrid_opsupload_set_grid_column_references_create_or_update	_open_url)rJ   r   rK   plotlyrS   entrykeyvalmsgpayloadr"   pathsrV   r   r]   grid_filename	file_infor^   r   s                      r    r@   r@      s   : \\;;NHUF eO%-;">U[[]+ 	HCs8e#2 $ MM#&+	8 &l3L  48G 
D1HB<3"~H s#hhuQr{+9   -%0GM"&
 y$/G($( !	I	$) !	H	$) !'+#$&&223DEE /v6LFD 4y1} M'#-87BM$w.M""#34	 	 	
 	$FD1"!'62I (I&s+m;i>TTI&   d3I' N[  s   %H	HHc                     ddl }|j                  j                  | ||      } |r"t        |t              r| j                  |       n!|t        j                  j                  d      t        | fi |S )a  Replot a matplotlib figure with plotly in IPython.

    This function:
    1. converts the mpl figure into JSON (run help(plotly.tools.mpl_to_plotly))
    2. makes a request to Plotly to save this figure in your account
    3. displays the image in your IPython output cell

    Positional arguments:
    fig -- a figure object from matplotlib

    Keyword arguments:
    resize (default=True) -- allow plotly to choose the figure size
    strip_style (default=False) -- allow plotly to choose style options
    update (default=None) -- update the resulting figure with an 'update'
        dictionary-like object resembling a plotly 'Figure' object

    Additional keyword arguments:
    plot_options -- run help(plotly.plotly.iplot)

    r   Nresizestrip_stylev'update' must be dictionary-like and a valid plotly Figure object. Run 'help(plotly.graph_objs.Figure)' for more info.)
ra   r	   mpl_to_plotlyrA   rB   r*   r   r   PlotlyGraphObjectErrorrN   figr}   r~   r*   rK   rr   s         r    	iplot_mplr   /  sq    * 
,,
$
$S[
$
QC*VT*

6		&&==J
 	
 %%%    c                     ddl }|j                  j                  | ||      } |r"t        |t              r| j                  |       n!|t        j                  j                  d      t        | fi |S )a  Replot a matplotlib figure with plotly.

    This function:
    1. converts the mpl figure into JSON (run help(plotly.tools.mpl_to_plotly))
    2. makes a request to Plotly to save this figure in your account
    3. opens your figure in a browser tab OR returns the unique figure url

    Positional arguments:
    fig -- a figure object from matplotlib

    Keyword arguments:
    resize (default=True) -- allow plotly to choose the figure size
    strip_style (default=False) -- allow plotly to choose style options
    update (default=None) -- update the resulting figure with an 'update'
        dictionary-like object resembling a plotly 'Figure' object

    Additional keyword arguments:
    plot_options -- run help(plotly.plotly.plot)

    r   Nr|   r   )
ra   r	   r   rA   rB   r*   r   r   r   r@   r   s         r    plot_mplr   Q  sq    * 
,,
$
$S[
$
QC*VT*

6		&&==J
 	
 $|$$r   c                     d\  }}	 | j                  |      }	 | j                  |      }||| |<   ||| |<   yy# t        $ r Y -w xY w# t        $ r Y *w xY w)zSwap obj[key1] with obj[key2]NNN)popKeyError)objkey1key2val1val2s        r    
_swap_keysr   s  s{    JD$wwt}wwt} D	D	     s    : A	 	AA		AAc                    g d}|D ]  }t        | |d   |d           	 t        | d         }t        | d   d         }| d   D ]  }t        |      |k7  st         | j                  d      }t	        |      D cg c]  }t	        |      D cg c]  }d c} c}}| d<   t	        |      D ]#  }	t	        |      D ]  }
||	   |
   | d   |
   |	<    % yc c}w c c}}w # t
        t        t        f$ rq}d}	 | d   d}t        | d         dk(  rd}n# t
        t        f$ r Y nw xY w|r2t        j                  dj                  t        |                   Y d}~yY d}~yd}~ww xY w)	z Swap x and y data and references))xy)x0y0)dxdy)xbinsybins)nbinsxnbinsy)autobinxautobiny)error_xerror_yr      zFNTz~Data in this file required an 'xy' swap but the 'z' matrix in one of the data objects could not be transposed. Here's why:

{})r   rd   rH   r   ranger   
IndexErrorre   rf   formatrepr)data_objswapsswaprowscolsrowr   cccrrriiijjjerrrf   s                r    _swap_xy_datar     s   E  /8T!Wd1g./8C=!8C=#$C= 	 C3x4	 
 LL?DT{KuT{3!3K; 	6CT{ 6*+C&+c"3'6	6 4K i, 	}(8C=!Q&)$ 		MM#VDI.  se   5C  &C  <C	CC8C  CC   E%4E 7DE D$!E #D$$2E  E%c                 <   t        | t              r6| j                         D ci c]  \  }}t        |      t        |       c}}S t        | t              r| D cg c]  }t        |       c}S t        | t
              r| j                  d      S | S c c}}w c c}w )z6Convert unicode strings in JSON object to byte stringsutf-8)rA   rB   	iteritemsbyteifyrc   unicodeencode)inputrt   valueelements       r    r   r     s|    %?D?PQegen,QQ	E4	 056W 66	E7	#||G$$ R6s   BBc                    ddl }t               d   }|| }|dt        |       |k7  r/t        j                  j                  dj                  ||            |dz   }|j                  |d      j                  d      d   }|j                  |d      j                  d      d   }n| }	 t        |       t        |      dk  rt        j                  j                  d
      dj                  ||      }t        j                  j                  |d      }	|	j                         }
t        j                   rt#        |
      }
t%        |
d         D ]  \  }}	 t'        |d   dk(  d|v d|vf      r|j)                  d      |d<   |d   dv rd|d<   d|v rs|j)                  d      |d<   |d   dk(  r|d   dk(  rt+        |       |d   dk(  r<d|v rd|vr|d   dk(  rt+        |       |d= d|v rd|vr|d   dk(  rt+        |       |d= ||
d   |<    t%        |
d         D ]  \  }}d|v s|
d   |   d=  |r|
S |j.                  j1                  |
d      S # t        $ r  t        j                  j                  d	      w xY w# t,        $ r Y =w xY w)a4  Returns a JSON figure representation for the specified file

    Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair.
    Since each file is given a corresponding unique url, you may also simply
    pass a valid plotly url as the first argument.

    Examples:
        fig = get_figure('https://plotly.com/~chris/1638')
        fig = get_figure('chris', 1638)

    Note, if you're using a file_owner string as the first argument, you MUST
    specify a `file_id` keyword argument. Else, if you're using a url string
    as the first argument, you MUST NOT specify a `file_id` keyword argument,
     or file_id must be set to Python's None value.

    Positional arguments:
    file_owner_or_url (string) -- a valid plotly username OR a valid plotly url

    Keyword arguments:
    file_id (default=None) -- an int or string that can be converted to int
                              if you're using a url, don't fill this in!
    raw (default=False) -- if true, return unicode JSON string verbatim**

    **by default, plotly will return a Figure object. This representation used
    to decode the keys and values from unicode (if possible) and remove
    information irrelevant to the figure representation. Now if in Python 2,
    unicode is converted to regular strings. Also irrelevant information is
    now NOT stripped: an error will be raised if a figure contains invalid
    properties.

    Finally this function converts the JSON dictionary objects to plotly
    `graph objects`.

    Run `help(plotly.graph_objs.Figure)` for a list of valid properties.

    r   Nplotly_domainzBecause you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '{0}', we expected it to start with '{1}'.
Run help on this function for more information./~rW   rU   r   zThe 'file_id' argument was not able to be converted into an integer number. Make sure that the positional 'file_id' argument is a number that can be converted into an integer or a string that can be converted into an integer.z5The 'file_id' argument must be a non-negative number.{}:{}T)inline_datarP   rQ   
histogramyr   r   )
histogramxr   	histogrambardirorientationbarhr   r   r3   streamFigure)obj_type)ra   r   rd   r   r   r   r   replacerg   intrG   r   plotscontentjsonsixPY2r   	enumerateallr   r   r   r	   get_graph_obj)file_owner_or_urlfile_idrawrr   plotly_rest_urlrL   head
file_ownerfidresponserS   indexrs   s                r    
get_figurer     s   J  l?3O%_%&/9**66
 6#/  %[[r*005a8
++dB'--c215&

G 7|a&&22C
 	
 ..W
-Cxx6H]]_F
ww!&.1 u	v,.50@'QVBVW "'7!3g V} << +f5 ',yy':m$=E)]+s2%e,=K/u3e+; /36)%0!-0u3e+; /36)%0!-0$)F6N5!5@ "&.1 0uuvu%h/0 <<%%fx%@@q  
&&225
 	

Z  		s   'I B7I<)I9<	J	J	c                       e Zd ZdZdZdZ ej                  j                  di  e	j                         d        Zd ZddZed        Zd Zdd
Zd Zy	)Streama  
    Interface to Plotly's real-time graphing API.

    NOTE: Streaming is no longer supported in Plotly Cloud.
    Streaming is still available as part of Plotly On-Premises.

    Initialize a Stream object with a stream_id
    found in {plotly_domain}/settings.
    Real-time graphs are initialized with a call to `plot` that embeds
    your unique `stream_id`s in each of the graph's traces. The `Stream`
    interface plots data to these traces, as identified with the unique
    stream_id, in real-time.
    Every viewer of the graph sees the same data at the same time.

    View examples and tutorials here:
    https://plotly.com/python/streaming/

    Stream example:
    # Initialize a streaming graph
    # by embedding stream_id's in the graph's traces
    import plotly.plotly as py
    from plotly.graph_objs import Data, Scatter, Stream
    stream_id = "your_stream_id" # See {plotly_domain}/settings
    py.plot(Data([Scatter(x=[], y=[],
                          stream=Stream(token=stream_id, maxpoints=100))]))
    # Stream data to the import trace
    stream = Stream(stream_id) # Initialize a stream object
    stream.open() # Open the stream
    stream.write(dict(x=1, y=1)) # Plot (1, 1) in your graph

    P   i  c                      || _         d| _        y)a  
        Initialize a Stream object with your unique stream_id.
        Find your stream_id at {plotly_domain}/settings.

        For more help, see: `help(plotly.plotly.Stream)`
        or see examples and tutorials here:
        https://plotly.com/python/streaming/

        N)	stream_id_stream)selfr   s     r    __init__zStream.__init__U  s     #r   c                 &   t               d   }t               d   }d|v }|r| j                  n| j                  }t        j                  j
                  j                  j                  |      j                  xs |}|| j                  d}|||||d}|S )zU
        Returns the streaming server, port, ssl_enabled flag, and headers.

        plotly_streaming_domainplotly_ssl_verificationhttps)Hostzplotly-streamtoken)serverportssl_enabledssl_verification_enabledheaders)
r   
HTTPS_PORT	HTTP_PORTr   movesurllibparseurlparsehostnamer   )r   streaming_urlr   r   r   hostr   streaming_specss           r    get_streaming_specszStream.get_streaming_specsc  s    
 #%>?#-<0I#J ."-t4>> yy%%..}=FFW-t~~F&(@
 r   c                     	 | j                   j                  d|       y# t        $ r  t        j                  j                  d      w xY w)a  
        Keep stream alive. Streams will close after ~1 min of inactivity.

        If the interval between stream writes is > 30 seconds, you should
        consider adding a heartbeat between your stream.write() calls like so:
        >>> stream.heartbeat()

        
reconnect_ontStream has not been opened yet, cannot write to a closed connection. Call `open()` on the stream to open the stream.N)r   writeAttributeErrorr   r   r   )r   r   s     r    	heartbeatzStream.heartbeat|  sL    	LLt,? 	**66B 	s	     )A	c                 P    | j                   y| j                   j                         S NF)r   _isconnectedr   s    r    	connectedzStream.connected  s"    <<||((**r   c                 X    | j                         }t        j                  di || _        y)z
        Open streaming connection to plotly.

        For more help, see: `help(plotly.plotly.Stream)`
        or see examples and tutorials here:
        https://plotly.com/python/streaming/

        N )r   r   r   r   )r   r   s     r    openzStream.open  s'     224'..AAr   Nc                    ddl m} t        ||      r|j                         }nt	        j
                  |      }|j                  dd       ||j                  t        |             t        j                  |t              }|dz  }	 | j                  j                  ||       y# t        $ r  t        j                   j#                  d	      w xY w)
a  
        Write to an open stream.

        Once you've instantiated a 'Stream' object with a 'stream_id',
        you can 'write' to it in real time.

        positional arguments:
        trace - A dict of properties to stream
                Some valid keys for trace dictionaries:
                    'x', 'y', 'text', 'z', 'marker', 'line'

        keyword arguments:
        layout (default=None) - A valid Layout object or dict with
                                compatible properties
                                Run help(plotly.graph_objs.Layout)

        Examples:

        Append a point to a scatter trace
        >>> write(dict(x=1, y=2))

        Overwrite the x and y properties of a scatter trace
        >>> write(dict(x=[1, 2, 3], y=[10, 20, 30]))

        Append a point to a scatter trace and set the points text value
        >>> write(dict(x=1, y=2, text='scatter text'))

        Append a point to a scatter trace and set the points color
        >>> write(dict(x=1, y=3, marker=go.Marker(color='blue')))

        Set a new z value array for a Heatmap trace
        >>> write(dict(z=[[1, 2, 3], [4, 5, 6]]))

        The connection to plotly's servers is checked before writing
        and reconnected if disconnected and if the response status code
        is in `reconnect_on`.

        For more help, see: `help(plotly.plotly.Stream)`
        or see examples and tutorials here:

        r   )BaseTraceTyperQ   N)r9   clsr   r   r   )r?   r  rA   rD   r#   r$   r   r*   rB   _jsondumpsr   r   r  r  r   r   r   )r   tracer9   r   r  stream_objectjdatas          r    r  zStream.write  s    X 	7e]+!002M MM%0M 	&$'  V!45 M/@A	LLu<@ 	**66B 	s   	B' ')Cc                     	 | j                   j                          y# t        $ r  t        j                  j                  d      w xY w)z
        Close the stream connection to plotly's streaming servers.

        For more help, see: `help(plotly.plotly.Stream)`
        or see examples and tutorials here:
        https://plotly.com/python/streaming/

        zStream has not been opened yet.N)r   closer  r   r   r   r  s    r    r  zStream.close  sB    	LL  	**661 	s	    )Ar
  )   rW   i  i  )Nr  )__name__
__module____qualname____doc__r   r   r   r
   template_docr	   r&   r   r   r  propertyr  r  r  r  r
  r   r    r   r   0  sy    @ IJ%]%%@(=(=(=(?@ A2$ + +
BDLr   r   c                   H    e Zd ZdZedd       Zedd       Ze	 dd       Zy)imagezP
    Helper functions wrapped around plotly's static image generation api.

    Nc                    ddl }|j                  j                  | d      }|dvrt        j                  j                  d      |	 t        |      }||d}|||d<   |||d	<   |||d
<   t        j                  j                  |      }|j                  }	d|	v r|	d   dv r|j                  S d|	v rd|	d   v r|j                         d   S yy#  t        j                  j                  d      xY w)aD  Return a static image of the plot described by `figure_or_data`.

        positional arguments:
        - figure_or_data: The figure dict-like or data list-like object that
                          describes a plotly figure.
                          Same argument used in `py.plot`, `py.iplot`,
                          see https://plotly.com/python for examples
        - format: 'png', 'svg', 'jpeg', 'pdf', 'emf'
        - width: output width
        - height: output height
        - scale: Increase the resolution of the image by `scale`
                 amount (e.g. `3`)
                 Only valid for PNG and JPEG images.

        example:
        ```
        import plotly.plotly as py
        fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
        py.image.get(fig, 'png', scale=3)
        ```

        r   NT)pngsvgjpegpdfemfzInvalid format. This version of your Plotly-Python package currently only supports png, svg, jpeg, and pdf. Learn more about image exporting, and the currently supported file types here: https://plotly.com/python/static-image-export/z0Invalid scale parameter. Scale must be a number.)rS   r   r:   r<   scalezcontent-type)z	image/pngz
image/jpegzapplication/pdfzimage/svg+xmlz	image/emfr   r   )ra   r	   rb   r   r   r   rE   r   imagescreater   r   r   )
rJ   r   r:   r<   r'  rr   rS   rw   r   r   s
             r    rC   z	image.get  s0   2 	??PTU==**66A  e $v6$GG &GH$GG99##G,""W$)@ E
 *
 ###w&6W^5L+L==?7++ ,M&1#..::F s   C !C/c                     |dk(  rt         j                  j                  d      | j                  |||||      }ddlm}m}m}	 |dk(  r | |	|             y | ||             y)a4  Display a static image of the plot described by `figure_or_data`
        in an IPython Notebook.

        positional arguments:
        - figure_or_data: The figure dict-like or data list-like object that
                          describes a plotly figure.
                          Same argument used in `py.plot`, `py.iplot`,
                          see https://plotly.com/python for examples
        - format: 'png', 'svg', 'jpeg', 'pdf'
        - width: output width
        - height: output height
        - scale: Increase the resolution of the image by `scale` amount
               Only valid for PNG and JPEG images.

        example:
        ```
        import plotly.plotly as py
        fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
        py.image.ishow(fig, 'png', scale=3)
        r%  zAw, snap! It's not currently possible to embed a pdf into an IPython notebook. You can save the pdf with the `image.save_as` or you can embed an png, jpeg, or svg.r   )displayImageSVGr#  N)r   r   r   rC   IPython.displayr+  r,  r-  )
r  rJ   r   r:   r<   r'  imgr+  r,  r-  s
             r    ishowzimage.ishowA  sf    , U?**66.  ggnfeVUC77U?CHE#Jr   c                    t         j                  j                  |      \  }}|s|s|dz  }n|r|s|dd }n|s
|r|d|z   z  }| j                  |||||      }	t	        |d      }
|
j                  |	       |
j                          y)a%  Save a image of the plot described by `figure_or_data` locally as
        `filename`.

        Valid image formats are 'png', 'svg', 'jpeg', 'pdf' and 'emf'.
        The format is taken as the extension of the filename or as the
        supplied format.

        positional arguments:
        - figure_or_data: The figure dict-like or data list-like object that
                          describes a plotly figure.
                          Same argument used in `py.plot`, `py.iplot`,
                          see https://plotly.com/python for examples
        - filename: The filepath to save the image to
        - format: 'png', 'svg', 'jpeg', 'pdf', 'emf'
        - width: output width
        - height: output height
        - scale: Increase the resolution of the image by `scale` amount
               Only valid for PNG and JPEG images.

        example:
        ```
        import plotly.plotly as py
        fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
        py.image.save_as(fig, 'my_image.png', scale=3)
        ```
        z.pngr   N.wb)ospathsplitextrC   r  r  r  )r  rJ   r"   r   r:   r<   r'  baseextr/  fs              r    save_aszimage.save_asg  s    > gg&&x0s6HWFf$HggnfeVUC4 			r   )r"  NNN)NNNN)	r  r  r  r  staticmethodrC   classmethodr0  r:  r
  r   r    r   r     sJ    
 @, @,D #  # J SW* *r   r   c                   0    e Zd ZdZed        Zed        Zy)ri   z0
    Interface to Plotly's File System API

    c                 \    t         j                  j                  d|i      }|j                  S )as  
        Create folder(s) specified by folder_path in your Plotly account.

        If the intermediate directories do not exist,
        they will be created. If they already exist,
        no error will be thrown.

        Mimics the shell's mkdir -p.

        Returns:
        - 200 if folders already existed, nothing was created
        - 201 if path was created
        Raises:
        -  exceptions.PlotlyRequestError with status code
           400 if the path already exists.

        Usage:
        >> mkdirs('new folder')
        >> mkdirs('existing folder/new folder')
        >> mkdirs('new/folder/path')

        r5  )r   foldersr)  status_code)r  folder_pathr   s      r    mkdirszfile_ops.mkdirs  s)    0 ::$$fk%:;###r   c                     	 | j                  |       y# t        j                  $ r}d|j                  v rn|Y d}~yd}~ww xY w)z
        Create folder(s) if they don't exist, but unlike mkdirs, doesn't
        raise an error if folder path already exist
        already existsN)rB  r   r   message)r  rA  es      r    rj   zfile_ops.ensure_dirs  sB    	JJ{#,, 	199, 	s    A=AN)r  r  r  r  r<  rB  rj   r
  r   r    ri   ri     s/    
 $ $4  r   ri   c                   z    e Zd ZdZed        Zed        Ze	 d	d       Zed
d       Z	ed
d       Z
ed
d       Zy)rm   a4  
    Interface to Plotly's Grid API.
    Plotly Grids are Plotly's tabular data object, rendered
    in an online spreadsheet. Plotly graphs can be made from
    references of columns of Plotly grid objects. Free-form
    JSON Metadata can be saved with Plotly grids.

    To create a Plotly grid in your Plotly account from Python,
    see `grid_ops.upload`.

    To add rows or columns to an existing Plotly grid, see
    `grid_ops.append_rows` and `grid_ops.append_columns`
    respectively.

    To delete one of your grid objects, see `grid_ops.delete`.

    c                     |D ]G  }|D ]@  }|d   |j                   k(  sdj                  ||d         |_        |j                  |       B I y )Nname{0}:{1}uid)rI  r   idremove)r  request_columnsresponse_columnsgrid_idreq_colresp_cols         r    _fill_in_response_column_idsz%grid_ops._fill_in_response_column_ids  sW    & 	6G, 6F#w||3!*!1!1'8E?!KGJ$++H56	6r   c                 F    | ry t         j                  j                  d      )NzaThis operation requires that the grid has already been uploaded to Plotly. Try `uploading` first.)r   r   r   )r   s    r    ensure_uploadedzgrid_ops.ensure_uploaded  s&    &&220
 	
r   Nc                    |j                         }|||d<   ||d}|r]|d   dk(  r|dd }|j                  d      }dj                  |dd       }	|d   }|	dk7  rt        j	                  |	       ||d<   |	r|	|d<   t        |      }
|
d	   }|
d
   }|
d   }| j                  |||       ||_        |t        j                  ||       |rt        |       |S )av
  
        Upload a grid to your Plotly account with the specified filename.

        Positional arguments:
            - grid: A plotly.grid_objs.Grid object,
                    call `help(plotly.grid_ops.Grid)` for more info.
            - filename: Name of the grid to be saved in your Plotly account.
                        To save a grid in a folder in your Plotly account,
                        separate specify a filename with folders and filename
                        separated by backslashes (`/`).
                        If a grid, plot, or folder already exists with the same
                        filename, a `plotly.exceptions.RequestError` will be
                        thrown with status_code 409.  If filename is None,
                        and randomly generated filename will be used.

        Optional keyword arguments:
            - world_readable (default=True): make this grid publically (True)
                                             or privately (False) viewable.
            - auto_open (default=True): Automatically open this grid in
                                        the browser (True)
            - meta (default=None): Optional Metadata to associate with
                                   this grid.
                                   Metadata is any arbitrary
                                   JSON-encodable object, for example:
                                   `{"experiment name": "GaAs"}`

        Filenames must be unique. To overwrite a grid with the same filename,
        you'll first have to delete the grid with the blocking name. See
        `plotly.plotly.grid_ops.delete`.

        Usage example 1: Upload a plotly grid
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py
        column_1 = Column([1, 2, 3], 'time')
        column_2 = Column([4, 2, 5], 'voltage')
        grid = Grid([column_1, column_2])
        py.grid_ops.upload(grid, 'time vs voltage')
        ```

        Usage example 2: Make a graph based with data that is sourced
                         from a newly uploaded Plotly grid
        ```
        import plotly.plotly as py
        from plotly.grid_objs import Grid, Column
        from plotly.graph_objs import Scatter
        # Upload a grid
        column_1 = Column([1, 2, 3], 'time')
        column_2 = Column([4, 2, 5], 'voltage')
        grid = Grid([column_1, column_2])
        py.grid_ops.upload(grid, 'time vs voltage')

        # Build a Plotly graph object sourced from the
        # grid's columns
        trace = Scatter(xsrc=grid[0], ysrc=grid[1])
        py.plot([trace], filename='graph from grid')
        ```

        metadata)rP   r   rT   rU   r   rW   r"   rV   r   r   r^   )r]   )_to_plotly_grid_jsonrg   rh   ri   rj   _create_or_overwrite_gridrS  rL  meta_opsrn   rq   )r  r]   r"   r   r   meta	grid_jsonrw   rx   rV   rz   r   r   r^   s                 r    rn   zgrid_ops.upload  s
   @ --/	$(Ij!$G |s"#Ab>NN3'E((52;/KRyHb $$[1"*GJ)4&-g6	 I& 	((tS9OODtO,gr   c                 l   t        ||      }t        j                  |       |D cg c]  }|j                   }}|r*|D cg c]  }|j                   }}|j	                  |       t        j                  |      }|r4t        j                  j                  |      }	t        j                  |	      dt        j                  |t              i}
|}t        j                  j!                  ||
      }|j#                         }| j%                  ||d   |       |r|j	                  |       yyc c}w c c}w )a  
        Append columns to a Plotly grid.

        `columns` is an iterable of plotly.grid_objs.Column objects
        and only one of `grid` and `grid_url` needs to specified.

        `grid` is a ploty.grid_objs.Grid object that has already been
        uploaded to plotly with the grid_ops.upload method.

        `grid_url` is a unique URL of a `grid` in your plotly account.

        Usage example 1: Upload a grid to Plotly, and then append a column
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py
        column_1 = Column([1, 2, 3], 'time')
        grid = Grid([column_1])
        py.grid_ops.upload(grid, 'time vs voltage')

        # append a column to the grid
        column_2 = Column([4, 2, 5], 'voltage')
        py.grid_ops.append_columns([column_2], grid=grid)
        ```

        Usage example 2: Append a column to a grid that already exists on
                         Plotly
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py

        grid_url = 'https://plotly.com/~chris/3143'
        column_1 = Column([1, 2, 3], 'time')
        py.grid_ops.append_columns([column_1], grid_url=grid_url)
        ```

        r   r  N)parse_grid_id_argsrm   rU  rI  extendr
   get_first_duplicater   NON_UNIQUE_COLUMN_MESSAGEr   
InputErrorr  r  r   r   grids
col_creater   rS  )r  columnsr]   grid_urlrP  ccolumn_namesexisting_column_namesduplicate_namer   bodyr   r   parsed_contents                 r    append_columnszgrid_ops.append_columnsR  s   L %T84  ) )0010059$:QVV$:!$: 5622<@66==nMC'',, G1BCD88&&sD1!((.2H#NKK  # 1$:s   D,D1c                 4   t        ||      }t        j                  |       |rt        |D cg c]  }| c}      }t	        |      D ]c  \  }}t        |      |k7  st        j                  dj                  |t        |      t        |      dk(  rdnd||dk(  r
d            d             |}	t        j                  j                  |	d|i       |rt        |D 
cg c]  }
t        |
j                         c}
      }|D ]M  }|t        |j                        z
  }t        |      D cg c]  }d }}|j                  j                  |       O t        | }t        ||      D ]   \  }}|j                  j                  |       " y	y	c c}w c c}
w c c}w )
a  
        Append rows to a Plotly grid.

        `rows` is an iterable of rows, where each row is a
        list of numbers, strings, or dates. The number of items
        in each row must be equal to the number of columns
        in the grid. If appending rows to a grid with columns of
        unequal length, Plotly will fill the columns with shorter
        length with empty strings.

        Only one of `grid` and `grid_url` needs to specified.

        `grid` is a ploty.grid_objs.Grid object that has already been
        uploaded to plotly with the grid_ops.upload method.

        `grid_url` is a unique URL of a `grid` in your plotly account.

        Usage example 1: Upload a grid to Plotly, and then append rows
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py
        column_1 = Column([1, 2, 3], 'time')
        column_2 = Column([5, 2, 7], 'voltage')
        grid = Grid([column_1, column_2])
        py.grid_ops.upload(grid, 'time vs voltage')

        # append a row to the grid
        row = [1, 5]
        py.grid_ops.append_rows([row], grid=grid)
        ```

        Usage example 2: Append a row to a grid that already exists on Plotly
        ```
        from plotly.grid_objs import Grid
        import plotly.plotly as py

        grid_url = 'https://plotly.com/~chris/3143'

        row = [1, 5]
        py.grid_ops.append_rows([row], grid=grid_url)
        ```

        zThe number of entries in each row needs to equal the number of columns in the grid. Row {0} has {1} {2} but your grid has {3} {4}. r   rs   entriescolumnre  r   rW   N)r^  rm   rU  rd   r   r   rb  r   r   rc  r   maxrP   r   r_  zip)r  r   r]   rf  rP  rp  	n_columnsrow_ir   r   collongest_column_lengthn_empty_rows_empty_string_rowscolumn_extensionslocal_columncolumn_extensions                     r    append_rowszgrid_ops.append_rows  s   Z %T84  )$7V78I'o 
ss8y($//- .4V!H'*3x1}G)%(1QH.	  =F.	  
S64.)$'$(G3SXX(G$H! 64s6;;7GG16|1D$EAR$E!$E""#456
 !$T
25d<M2N ;..!!(()9:; ' 8( )H %Fs   	FF*	Fc                     t        ||      }t        j                  |       t        j                  j                  |       t        j                  j                  |       y)a  
        Delete a grid from your Plotly account.

        Only one of `grid` or `grid_url` needs to be specified.

        `grid` is a plotly.grid_objs.Grid object that has already
               been uploaded to Plotly.

        `grid_url` is the URL of the Plotly grid to delete

        Usage example 1: Upload a grid to plotly, then delete it
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py
        column_1 = Column([1, 2, 3], 'time')
        column_2 = Column([4, 2, 5], 'voltage')
        grid = Grid([column_1, column_2])
        py.grid_ops.upload(grid, 'time vs voltage')

        # now delete it, and free up that filename
        py.grid_ops.delete(grid)
        ```

        Usage example 2: Delete a plotly grid by url
        ```
        import plotly.plotly as py

        grid_url = 'https://plotly.com/~chris/3'
        py.grid_ops.delete(grid_url=grid_url)
        ```

        N)r^  rm   rU  r   rc  trashpermanent_delete)r  r]   rf  r   s       r    deletezgrid_ops.delete  sA    D !x0  %
s
!!#&r   )NTTNr   )r  r  r  r  r<  rS  r;  rU  rn   rm  r}  r  r
  r   r    rm   rm     s    $ 6 6 
 
 LPf fP <! <!| N; N;` $' $'r   rm   c                   "    e Zd ZdZedd       Zy)rZ  a  
    Interface to Plotly's Metadata API.

    In Plotly, Metadata is arbitrary, free-form JSON data that is
    associated with Plotly grids. Metadata is viewable with any grid
    that is shared and grids are searchable by key value pairs in
    the Metadata. Metadata is any JSON-encodable object.

    To upload Metadata, either use the optional keyword argument `meta`
    in the `py.grid_ops.upload` method, or use `py.meta_ops.upload`.

    Nc                 z    t        ||      }t        j                  j                  |d|i      j	                         S )a  
        Upload Metadata to a Plotly grid.

        Metadata is any JSON-encodable object. For example,
        a dictionary, string, or list.

        Only one of `grid` or `grid_url` needs to be specified.

        `grid` is a plotly.grid_objs.Grid object that has already
               been uploaded to Plotly.

        `grid_url` is the URL of the Plotly grid to attach Metadata to.

        Usage example 1: Upload a grid to Plotly, then attach Metadata to it
        ```
        from plotly.grid_objs import Grid, Column
        import plotly.plotly as py
        column_1 = Column([1, 2, 3], 'time')
        column_2 = Column([4, 2, 5], 'voltage')
        grid = Grid([column_1, column_2])
        py.grid_ops.upload(grid, 'time vs voltage')

        # now attach Metadata to the grid
        meta = {'experment': 'GaAs'}
        py.meta_ops.upload(meta, grid=grid)
        ```

        Usage example 2: Upload Metadata to an existing Plotly grid
        ```
        import plotly.plotly as py

        grid_url = 'https://plotly.com/~chris/3143'

        meta = {'experment': 'GaAs'}

        py.meta_ops.upload(meta, grid_url=grid_Url)
        ```

        rW  )r^  r   rc  r*   r   )r  r[  r]   rf  r   s        r    rn   zmeta_ops.upload  s4    R !x0xxsZ$67<<>>r   r   r  r  r  r  r<  rn   r
  r   r    rZ  rZ  
  s     )? )?r   rZ  c                     | | j                   }nd}||g}d}t        ||      D cg c]
  \  }}|	| }}}|st        j                  d      t	        |      dkD  rt        j                  d      |j                         }|dk(  rvt        j                  j                  j                  j                  |      j                  }	|	j                  dd      j                  d	      d
d \  }
}dj                  |
|      S | j                   S c c}}w )z{
    Return the grid_id from the non-None input argument.

    Raise an error if more than one argument was supplied.

    N)r]   rf  a  One of the two keyword arguments is required:
    `grid` or `grid_url`

grid: a plotly.graph_objs.Grid object that has already
    been uploaded to Plotly.

grid_url: the url where the grid can be accessed on
    Plotly, e.g. 'https://plotly.com/~chris/3043'

r   zCOnly one of `grid` or `grid_url` is required. 
You supplied both. 
rf  r   rW   rU   r      rJ  )rL  rr  r   rb  rd   r   r   r   r   r   r   r5  r   rg   r   )r]   rf  id_from_gridargs	arg_namesarg_nameargsupplied_arg_namessupplied_arg_namer5  r   r   s               r    r^  r^  E  s    ww(#D$I '*)T&:"Xsco  ##D
 	
 
	 1	$##V
 	
 /224
*99##))228<AAD"&,,tR"8">">s"CAa"HJ##J8877N1s
   
D
D
c                    t         j                  j                  j                  j	                  |       }|j
                  j                  d      d   j                  d      d   }|j
                  j                  d      d   }dj                  ||      }ddd}t        j                  j                  ||      }t        j                  d	       t        j                  j                  |      j                         d
   }|s5|dz  }|dk(  rt        j                   j#                  d      t%        | |       | dz   |j                         d   z   }	|	S )zS
    Check that share key is enabled and update url to include the secret key

    rU   r   ~r  r   TF)r[   r      r[   2   zuThe sharekey could not be enabled at this time so the graph is saved as private. Try again to save as 'secret' later.r_   r`   )r   r   r   r   r   r5  rg   r   r   r   r*   timesleepretriever   r   r   r   add_share_key_to_url)
plot_urlattempturlsplitr   idlocalr   rk  r   r[   url_share_keys
             r    r  r  n  s#   
 yy%%..x8H}}""3'*005a8Hmm!!#&q)G
..7
+C!%?DxxsD)H 	JJqM))#.3356IJ1b=**66L  	Xw/},x}}{/KKMr   c                     t        d|       }t        j                  j                  |      }|j	                         }|r|S t        ||      S )a  
    Returns the specified grid as a Grid instance or in JSON/dict form.

    :param (str) grid_url: The web_url which locates a Plotly grid.
    :param (bool) raw: if False, will output a Grid instance of the JSON grid
    being retrieved. If True, raw JSON will be returned.
    N)r^  r   rc  r   r   r   )rf  r   r   r   rl  s        r    get_gridr    sE     T8
,Cxx$H]]_N
$$r   c                    t        t        |dz         }d| v r| d   dz   | d   z   }n| j                  dd      }|r	 t        j                  j	                  |      }t        |j                  t              r|j                  j                  d      }n|j                  }t        j                  |      }|d   |k(  r|d   }|j                  ||       }n4t        j                  j                  d	j                  |||d   
            n|j#                  |       }|j%                          |j                         }	|	j                  d|	      }	|	S # t        j                   $ r |j#                  |       }Y Zw xY w)aF  
    Create or update (if file exists) and plot, spectacle, or dashboard
    object
    Parameters
    ----------
    data: dict
        update/create API payload
    filetype: str
        One of 'plot', 'grid', 'spectacle_presentation', or 'dashboard'
    Returns
    -------
    dict
        File info from API response
    srV   rU   r"   Nr   filetyper   z
'{filename}' is already a {other_filetype} in your account. 
While you can overwrite {filetype}s with the same name, you can't overwrite
files with a different type. Try deleting '{filename}' in your account or
changing the filename.)r"   r  other_filetypefile)getattrr   rC   r   lookuprA   r   bytesdecoder   loadsr*   r   r   r   r   r   r)  raise_for_status)
rP   r  
api_moduler"   
lookup_resr   matching_filer   resrz   s
             r    rp   rp     su    X^,J &,tJ/??88J-	*2J*,,e4$,,33G<$,, JJw/MZ(H4#E* ''T2#..:: !&!)!)'4Z'@ ! 
 
 " %  
Ifi0I ,, 	*##D)C	*s   C
E $E32E3c                 (   t         j                  }d| v r| d   dz   | d   z   }n| j                  dd      }|r	 t         j                  j	                  |      }t        |j                  t              r|j                  j                  d      }n|j                  }t        j                  |      }|d   }|j                  |      }|j                          	 |j                  |       }|j                          |j                         }
|
j                  d|
      }
|
S # t        j                  $ r
}	Y d}	~	^d}	~	ww xY w# t        j                  $ rC}	|dkD  r8d|	j                   v r*t#        j$                  d	       t'        | |d	z
  
      cY d}	~	S  d}	~	ww xY w)a%  
    Create or overwrite (if file exists) a grid

    Parameters
    ----------
    data: dict
        update/create API payload
    filetype: str
        One of 'plot', 'grid', 'spectacle_presentation', or 'dashboard'

    Returns
    -------
    dict
        File info from API response
    rV   rU   r"   Nr   r   r   rD  r   )max_retriesr  )r   rc  rC   r   r  rA   r   r  r  r   r  destroyr  r   r   r)  rE  r  r  rY  )rP   r  r  r"   r  r   r  r   r  rF  rz   s              r    rY  rY    sk     J &,tJ/??88J-	2J*,,e4$,,33G<$,, JJw/M&C $$S)C  "% 
Ifi0I+ ,, 	 	 (( ?/199<JJqM,T{QOOs6   BD D; D83D8;F7FFFFc                   d    e Zd ZdZedd       Zed        Zed	d       Zed        Zed        Z	y)
dashboard_opsa  
    Interface to Plotly's Dashboards API.

    Plotly Dashboards are JSON blobs. They are made up by a bunch of
    containers which contain either empty boxes or boxes with file urls.
    For more info on Dashboard objects themselves, run
    `help(plotly.dashboard_objs)`.

    Example 1: Upload Simple Dashboard
    ```
    import plotly.plotly as py
    import plotly.dashboard_objs as dashboard
    box_1 = {
        'type': 'box',
        'boxType': 'plot',
        'fileId': 'username:123',
        'title': 'box 1'
    }

    box_2 = {
        'type': 'box',
        'boxType': 'plot',
        'fileId': 'username:456',
        'title': 'box 2'
    }

    my_dboard = dashboard.Dashboard()
    my_dboard.insert(box_1)
    # my_dboard.get_preview()
    my_dboard.insert(box_2, 'above', 1)
    # my_dboard.get_preview()

    py.dashboard_ops.upload(my_dboard)
    ```

    Example 2: Retreive Dashboard from Plotly
    ```
    # works if you have at least one dashboard in your files
    import plotly.plotly as py
    import plotly.dashboard_objs as dashboard

    dboard_names = get_dashboard_names()
    first_dboard = get_dashboard(dboard_names[0])

    first_dboard.get_preview()
    ```
    c                     |dk(  rd}n|dk(  rd}n|dk(  rd}t        j                  |      |d}t        |d      }|d   }|dk(  rt        |      }|rt	        j
                  |d          |S )	a  
        BETA function for uploading/overwriting dashboards to Plotly.

        :param (dict) dashboard: the JSON dashboard to be uploaded. Use
            plotly.dashboard_objs.dashboard_objs to create a Dashboard
            object.
        :param (str) filename: the name of the dashboard to be saved in
            your Plotly account. Will overwrite a dashboard of the same
            name if it already exists in your files.
        :param (str) sharing: can be set to either 'public', 'private'
            or 'secret'. If 'public', your dashboard will be viewable by
            all other users. If 'private' only you can see your dashboard.
            If 'secret', the url will be returned with a sharekey appended
            to the url. Anyone with the url may view the dashboard.
        :param (bool) auto_open: automatically opens the dashboard in the
            browser.
        rX   TrY   FrZ   r   r"   r   	dashboardr^   )r   r  rp   r  
webbrowseropen_new)	r  r  r"   r   r   r   rP   rz   rL   s	            r    rn   zdashboard_ops.uploadP  s    & h!N	!"N "N zz), ,
 &dK8		"h&s+C	) 45
r   c                 ^   g }t         j                  j                         j                         }|d   D ]  }|d   r	|j	                  |        |d   rXt         j
                  j                  d|d         j                         }|d   D ]  }|d   r	|j	                  |        |d   rX|S )NresultsdeletednextrC   )r   
dashboardsrc   r   appendr
   request)r  r  r  r  s       r    _get_all_dashboardsz!dashboard_ops._get_all_dashboards|  s    
mm  "'')Y 	-IY'!!),	- &k((""5#f+6;;=C ^ 1	 +%%i01 &k r   c                    | j                         }t        |      D ]  \  }}|d   |k(  s n t        j                  j	                  d|   d   d         j                         }|rt        j                  |d         }|S |S )Nr"   rC   api_urlsr  r   )r  r   r   r
   r  r   r  )r  dashboard_nameonly_contentr  r   dboardr  dashboard_jsons           r    _get_dashboard_jsonz!dashboard_ops._get_dashboard_json  s    ,,.
&z2 	ME6j!^3	 HH$$:e$Z0>

$& 	 !ZZ	)(<=N!!r   c                 N    | j                  |      }t        j                  |      S )z1Returns a Dashboard object from a dashboard name.)r  r  	Dashboard)r  r  r  s      r    get_dashboardzdashboard_ops.get_dashboard  s%     00@"">22r   c                 d    | j                         }|D cg c]  }t        |d          c}S c c}w )z>Return list of all active dashboard names from users' account.r"   )r  rF   )r  r  r  s      r    get_dashboard_namesz!dashboard_ops.get_dashboard_names  s0     ,,.
6@AFF:&'AAAs   -NrX   TT)
r  r  r  r  r<  rn   r  r  r  r  r
  r   r    r  r    so    .` ) )V     3 3
 B Br   r  c                   "    e Zd ZdZedd       Zy)presentation_opsz<
    Interface to Plotly's Spectacle-Presentations API.
    c                    |dk(  rd}n*|dv rd}n#t         j                  j                  t              t	        j
                  |      ||d}t        |d      }|d   }|dk(  rt        |      }|rt        j                  |d          |S )	as  
        Function for uploading presentations to Plotly.

        :param (dict) presentation: the JSON presentation to be uploaded. Use
            plotly.presentation_objs.Presentation to create presentations
            from a Markdown-like string.
        :param (str) filename: the name of the presentation to be saved in
            your Plotly account. Will overwrite a presentation of the same
            name if it already exists in your files.
        :param (str) sharing: can be set to either 'public', 'private'
            or 'secret'. If 'public', your presentation will be viewable by
            all other users. If 'private' only you can see your presentation.
            If it is set to 'secret', the url will be returned with a string
            of random characters appended to the url which is called a
            sharekey. The point of a sharekey is that it makes the url very
            hard to guess, but anyone with the url can view the presentation.
        :param (bool) auto_open: automatically opens the presentation in the
            browser.

        See the documentation online for examples.
        rX   T)rY   rZ   Fr  spectacle_presentationr^   rZ   )
r   r   r   rk   r   r  rp   r  r  r  )	r  presentationr"   r   r   r   rP   rz   rL   s	            r    rn   zpresentation_ops.upload  s    . h!N--"N**667HIIzz,/ ,
 &d,DE		"h&s+C	) 45
r   Nr  r  r
  r   r    r  r    s     , ,r   r  c           
      x   ddl m} t        | j                               D ]  }dj	                  |      }||v r7| |   }t        |      s) ||||z         }|j                  |       d| |<   | |= O||v sT|j                  |   }	t        |	t              stt        | |   ||   |dj	                  ||              y)a"  
    Extract inline data arrays from a graph_obj instance and place them in
    a grid

    Parameters
    ----------
    obj_dict: dict
        dict representing a graph object that may contain inline arrays
    reference_obj: BasePlotlyType
        An empty instance of a `graph_obj` with type corresponding to obj_dict
    grid: Grid
        Grid to extract data arrays too
    path: str
        Path string of the location of `obj_dict` in the figure

    Returns
    -------
    None
        Function modifies obj_dict and grid in-place
    r   )Columnz{}srcTBDz{path}{prop}.)r5  propN)chart_studio.grid_objsr  rc   keysr   r   r  _validatorsrA   r   _extract_grid_graph_obj)
obj_dictreference_objr]   r5  r  r  propsrcru   rp  prop_validators
             r    r  r    s    , .X]]_% ..&m#4.C}TD[1F#$)!TN]"*66t<N.*;<'TN!$'#**4*@	r   c           
         ddl m} ddlm} |d}t	        g       }nd}t        | |      r| j                         }nMt        | t              r|rt        j                  |       n| }n#t        dj                  t        |                    |       }i }t        |j                  dg             D ]c  \  }	}
|
j                  dd	      }||vr#|j                  d|i      j                   d
   ||<   ||   }t#        |
|||dj                  |	      z          e d|v r2t        |d         D ]!  \  }	}t%        ||dj                  |	             # ||fS )a  
    Extract inline data arrays from a figure and place them in a grid

    Parameters
    ----------
    fig: dict
         A dict representing a figure or a frame
    grid: Grid or None (default None)
        The grid to place the extracted columns in. If None, a new grid will
        be constructed
    path: str (default '')
        Parent path, set to `frames` for use with frame objects
    Returns
    -------
    (dict, Grid)
        * dict: Figure dict with data arrays removed
        * Grid: Grid object containing one column for each removed data array.
                Columns are named with the path the corresponding data array
                (e.g. 'data.0.marker.size')
    r   r7   )r   TFzInvalid figure type {}rP   rQ   scatterrT   zdata.{}.framesz
frames.{}.)r?   r7   plotly.graph_objsr   r   rA   to_dictrB   r#   r$   rG   r   rQ   r   rC   	add_tracerP   r  rl   )r   r]   r5  r7   r   copy_figfig_dictreference_figreference_tracesi
trace_dict
trace_typereference_trace
frame_dicts                 r    rl   rl     s^   * 0(|Bx #z";;=	C	)14==%s188cCDD HM"8<<#;< 

:^^FI6
--+8+B+B$,d2,Z( +:6tj6G6G6J/J	


 8&x'9: 	RMAz'
D,:M:Ma:PQ	R T>r   c                     ddl m} |D ]C  }|j                  |j                        }| }|dd D ]  }||   }	 |j                  ||d   dz   <   E y)a  
    Populate *src columns in a figure from uploaded grid

    Parameters
    ----------
    figure: dict
        Figure dict that previously had inline data arrays extracted
    grid: Grid
        Grid that was created by extracting inline data arrays from figure
        using the _extract_grid_from_fig_like function

    Returns
    -------
    None
        Function modifies figure in-place
    r   r  NrT   src)r?   r7   _str_to_dict_pathrI  rL  )rS   r]   r7   ru  	prop_pathprop_parentr  s          r    ro   ro   Y  sg    " 0 400:	crN 	,D%d+K	, .1VVIbME)*4r   c                      t        | |||      S )a  
    BETA function that creates plots with animations via `frames`.

    Creates an animated plot using 'frames' alongside 'data' and 'layout'.
    This BETA endpoint is subject to deprecation in the future. In relation
    to `plotly.plotly.plot`, folder-creation and overwriting are not supported
    but creating a plot with or without animations via frames is supported.

    :param (str) filename: if set to 'None', an automatically-generated plot
        name will be created. Does not support folder creation, meaning that
        a folder of the form 'folder/name' will NOT create a the folder and
        place the plot in it.
    :param (str) sharing: see `plotly.plotly.plot()` doc string.
    :param (bool) auto_open: if True, opens plot in the browser. If False,
        returns the url for the plot instead.

    Example 1: Simple Animation
    ```
    import plotly.plotly as py
    from plotly.grid_objs import Grid, Column

    column_1 = Column([0.5], 'x')
    column_2 = Column([0.5], 'y')
    column_3 = Column([1.5], 'x2')
    column_4 = Column([1.5], 'y2')

    grid = Grid([column_1, column_2, column_3, column_4])
    py.grid_ops.upload(grid, 'ping_pong_grid', auto_open=False)

    # create figure
    figure = {
        'data': [
            {
                'xsrc': grid.get_column_reference('x'),
                'ysrc': grid.get_column_reference('y'),
                'mode': 'markers',
            }
        ],
        'layout': {'title': 'Ping Pong Animation',
                   'xaxis': {'range': [0, 2], 'autorange': False},
                   'yaxis': {'range': [0, 2], 'autorange': False},
                   'updatemenus': [{
                       'buttons': [
                           {'args': [None],
                            'label': u'Play',
                            'method': u'animate'}
                   ],
                   'pad': {'r': 10, 't': 87},
                   'showactive': False,
                   'type': 'buttons'
                    }]},
        'frames': [
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x2'),
                        'ysrc': grid.get_column_reference('y2'),
                        'mode': 'markers',
                    }
                ]
            },
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x'),
                        'ysrc': grid.get_column_reference('y'),
                        'mode': 'markers',
                    }
                ]
            }
        ]
    }

    py.create_animations(figure, 'ping_pong')
    ```

    Example 2: Growing Circles Animation
    ```
    import plotly.plotly as py
    from plotly.grid_objs import Grid, Column

    column_1 = Column([0.9, 1.1], 'x')
    column_2 = Column([1.0, 1.0], 'y')
    column_3 = Column([0.8, 1.2], 'x2')
    column_4 = Column([1.2, 0.8], 'y2')
    column_5 = Column([0.7, 1.3], 'x3')
    column_6 = Column([0.7, 1.3], 'y3')
    column_7 = Column([0.6, 1.4], 'x4')
    column_8 = Column([1.5, 0.5], 'y4')
    column_9 = Column([0.4, 1.6], 'x5')
    column_10 = Column([1.2, 0.8], 'y5')

    grid = Grid([column_1, column_2, column_3, column_4, column_5,
                 column_6, column_7, column_8, column_9, column_10])
    py.grid_ops.upload(grid, 'growing_circles_grid', auto_open=False)

    # create figure
    figure = {
        'data': [
            {
                'xsrc': grid.get_column_reference('x'),
                'ysrc': grid.get_column_reference('y'),
                'mode': 'markers',
                'marker': {'color': '#48186a', 'size': 10}
            }
        ],
        'layout': {'title': 'Growing Circles',
                   'xaxis': {'range': [0, 2], 'autorange': False},
                   'yaxis': {'range': [0, 2], 'autorange': False},
                   'updatemenus': [{
                       'buttons': [
                           {'args': [None],
                            'label': u'Play',
                            'method': u'animate'}
                   ],
                   'pad': {'r': 10, 't': 87},
                   'showactive': False,
                   'type': 'buttons'
                    }]},
        'frames': [
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x2'),
                        'ysrc': grid.get_column_reference('y2'),
                        'mode': 'markers',
                        'marker': {'color': '#3b528b', 'size': 25}
                    }
                ]
            },
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x3'),
                        'ysrc': grid.get_column_reference('y3'),
                        'mode': 'markers',
                        'marker': {'color': '#26828e', 'size': 50}
                    }
                ]
            },
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x4'),
                        'ysrc': grid.get_column_reference('y4'),
                        'mode': 'markers',
                        'marker': {'color': '#5ec962', 'size': 80}
                    }
                ]
            },
            {
                'data': [
                    {
                        'xsrc': grid.get_column_reference('x5'),
                        'ysrc': grid.get_column_reference('y5'),
                        'mode': 'markers',
                        'marker': {'color': '#d8e219', 'size': 100}
                    }
                ]
            }
        ]
    }
    py.create_animations(figure, 'growing_circles')
    ```
    )r"   r   r   )r@   )rS   r"   r   r   s       r    create_animationsr  u  s    P 7iPPr   c                 r   ddl m}m} t        | |||      }t	        | t
              r/| j                  di       }t	        ||      r:|j                         }n)t	        | |      r| j                  j                         }ni }t               }|j                  dd      |d<   |j                  dd      |d<   	 t        |d          t        |d         dz   |d<   	 t        |d          t        |d         dz   |d<   t        j                  |fi |S # t        t        f$ r Y Jw xY w# t        t        f$ r Y <w xY w)	z
    Create a unique url for this animated plot in Plotly and open in IPython.

    This function is based off `plotly.plotly.iplot`. See `plotly.plotly.
    create_animations` Doc String for param descriptions.
    r   r6   r9   r:   r;   r<   r=   r>   )r?   r7   r8   r  rA   rB   rC   rD   r9   rE   rF   rG   rH   r	   rI   )	rS   r"   r   r   r7   r8   rL   r9   rM   s	            r    icreate_animationsr     s=    @
FHgy
AC&$Hb)fn-**,F	FJ	'--/FM#ZZ8M'$jj37M(DmG$% "%]7%;!<t!CgFmH%& #&mH&=">"Eh;;s,m,, 	"  	" s$   4D D$ D! D!$D65D6c                 0    	 ddl m}  ||        y #  Y y xY w)Nr   )r  )r  r  )rL   wbopens     r    rq   rq   H  s    -ss    r  )TFNr  r
  )r   )F)   )NrW   )NrX   T)NrX   F)Kr  
__future__r   base64r#   r   r4  r  re   r  r   	six.movesr  _plotly_utils.utilsr   _plotly_utils.exceptions_plotly_utils.basevalidatorsr   r   r   chart_studior   r   r	   r
   r   chart_studio.apir   chart_studio.plotlyr   r  r   chart_studio.dashboard_objsr   r  chart_studio.configr   r   __all__FILE_CONTENTCONFIG_FILEr%   rk   r   update_session_plot_optionsupdate_plot_optionsr4   rN   r@   r   r   r   r   r   r   r  r&   r   r   ri   rm   rZ  r^  r  r  rp   rY  r  r  r  rl   ro   r  r  rq   r
  r   r    <module>r	     s    '    	    
     D 1 A A  0 ' C <
 (():):;<LM##E$5$56{C!!%"3"34Y?	  U F 99 D8-vFR&D%D"(V	rAj "!!<$9E$9$9$;<D D =DNZ Zz- -`B' B'J
8? 8?v&R>%"=@>BGB GBT2 2j+z;|48hQV%-Pr   