Given a plot instance, an output format and an optional bokeh
        document, return the corresponding data. If as_script is True,
        the content will be split in an HTML and a JS component.
762457
def _figure_data(self, plot, fmt='html', doc=None, as_script=False, **kwargs):
        
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True

        if fmt == 'png':
            from bokeh.io.export import get_screenshot_as_png
            img = get_screenshot_as_png(plot.state, None)
            imgByteArr = BytesIO()
            img.save(imgByteArr, format='PNG')
            data = imgByteArr.getvalue()
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
        else:
            try:
                with silence_warnings(EMPTY_LAYOUT, MISSING_RENDERERS):
                    js, div, _ = notebook_content(model)
                html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
                data = encode_utf8(html)
                doc.hold()
            except:
                logger.disabled = False
                raise
            logger.disabled = False

        plot.document = doc
        if as_script:
            return div, js
        return data
720990
def server_doc(self_or_cls, obj, doc=None):
        
        if not isinstance(obj, (Plot, BokehServerWidgets)):
            if not isinstance(self_or_cls, BokehRenderer) or self_or_cls.mode != 'server':
                renderer = self_or_cls.instance(mode='server')
            else:
                renderer = self_or_cls
            plot, _ =  renderer._validate(obj, 'auto')
        else:
            plot = obj

        root = plot.state
        if isinstance(plot, BokehServerWidgets):
            plot = plot.plot

        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        plot.traverse(lambda x: attach_periodic(x), [GenericElementPlot])
        doc.add_root(root)
        return doc
1124094
def output(data, **kwargs):  # pylint: disable=unused-argument
    '''
    
    '''
    if isinstance(data, Exception):
        data = six.text_type(data)
    if 'output_indent' in __opts__ and __opts__['output_indent'] >= 0:
        return pprint.pformat(data, indent=__opts__['output_indent'])
    return pprint.pformat(data)
1010045
def plot(self):
        

        # if we're disabled or have no data columns, clear everything!
        if not self.button_enabled.is_checked() or len(self) == 0:
            self._set_number_of_plots(0)
            return self

        # if there is no script, create a default
        if not self.combo_autoscript.get_index()==0:
            self.script.set_text(self._autoscript())

        ##### Try the script and make the curves / plots match

        try:
            # get globals for sin, cos etc
            g = _n.__dict__
            g.update(dict(d=self))
            g.update(dict(xlabels='x', ylabels='y'))

            # run the script.
            exec(self.script.get_text(), g)

            # x & y should now be data arrays, lists of data arrays or Nones
            x = g['x']
            y = g['y']

            # make it the right shape
            if x == None: x = [None]
            if y == None: y = [None]
            if not _spinmob.fun.is_iterable(x[0]) and not x[0] == None: x = [x]
            if not _spinmob.fun.is_iterable(y[0]) and not y[0] == None: y = [y]
            if len(x) == 1 and not len(y) == 1: x = x*len(y)
            if len(y) == 1 and not len(x) == 1: y = y*len(x)


            # xlabels and ylabels should be strings or lists of strings
            xlabels = g['xlabels']
            ylabels = g['ylabels']

            # make sure we have exactly the right number of plots
            self._set_number_of_plots(len(x))
            self._update_linked_axes()

            # return if there is nothing.
            if len(x) == 0: return

            # now plot everything
            for n in range(max(len(x),len(y))-1,-1,-1):

                # Create data for "None" cases.
                if x[n] is None: x[n] = list(range(len(y[n])))
                if y[n] is None: y[n] = list(range(len(x[n])))
                self._curves[n].setData(x[n],y[n])

                # get the labels for the curves

                # if it's a string, use the same label for all axes
                if type(xlabels) in [str,type(None)]: xlabel = xlabels
                elif n < len(xlabels):                xlabel = xlabels[n]
                else:                                 xlabel = ''

                if type(ylabels) in [str,type(None)]: ylabel = ylabels
                elif n < len(ylabels):                ylabel = ylabels[n]
                else:                                 ylabel = ''

                # set the labels
                i = min(n, len(self.plot_widgets)-1)
                self.plot_widgets[i].setLabel('left',   ylabel)
                self.plot_widgets[i].setLabel('bottom', xlabel)

                # special case: hide if None
                if xlabel == None: self.plot_widgets[i].getAxis('bottom').showLabel(False)
                if ylabel == None: self.plot_widgets[i].getAxis('left')  .showLabel(False)

            # unpink the script, since it seems to have worked
            self.script.set_colors('black','white')

        # otherwise, look angry and don't autosave
        except: self.script.set_colors('black','pink')

        return self
898964
def save_plot(cls, data, columns, plottype, fmt='json', **kwargs):
        
        cls._verify_export_dir()
        plot = {"use_visavis_type": plottype, "payload": {}}

        if isinstance(data, pd.DataFrame):
            iter_data = data.iterrows
            pointers = columns
        else:
            iter_data = lambda: enumerate(data)
            pointers = range(len(data[0]))

        if fmt == 'csv':
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".csv")
            f_export = open(fmt_export, "w")
            f_export.write("%s\n" % ",".join(map(str, columns)))
            for _, row in iter_data():
                f_export.write("%s\n" % ",".join([str(row[i]) for i in pointers]))
            f_export.close()

        else:
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".json")
            f_export = open(fmt_export, "w")

            if plottype == 'bar':

                plot["payload"] = {"x": [], "y": [], "xtitle": cls._get_title(columns[0]), "ytitle": cls._get_title(columns[1])}

                for _, row in iter_data():
                    plot["payload"]["x"].append(row[pointers[0]])
                    plot["payload"]["y"].append(row[pointers[1]])

            elif plottype == 'plot3d':

                plot["payload"]["points"] = {"x": [], "y": [], "z": [], "labels": []}
                plot["payload"]["meshes"] = []
                plot["payload"]["xtitle"] = cls._get_title(columns[0])
                plot["payload"]["ytitle"] = cls._get_title(columns[1])
                plot["payload"]["ztitle"] = cls._get_title(columns[2])
                recent_mesh = 0

                for _, row in iter_data():
                    plot["payload"]["points"]["x"].append(row[pointers[0]])
                    plot["payload"]["points"]["y"].append(row[pointers[1]])
                    plot["payload"]["points"]["z"].append(row[pointers[2]])
                    plot["payload"]["points"]["labels"].append(row[pointers[3]])

                    if row[4] != recent_mesh:
                        plot["payload"]["meshes"].append({"x": [], "y": [], "z": []})
                    recent_mesh = row[4]

                    if plot["payload"]["meshes"]:
                        plot["payload"]["meshes"][-1]["x"].append(row[pointers[0]])
                        plot["payload"]["meshes"][-1]["y"].append(row[pointers[1]])
                        plot["payload"]["meshes"][-1]["z"].append(row[pointers[2]])

            if kwargs:
                plot["payload"].update(kwargs)

            else: raise RuntimeError("\r\nError: %s is an unknown plot type" % plottype)

            f_export.write(json.dumps(plot, escape_forward_slashes=False, indent=4))
            f_export.close()

        return fmt_export
949749
def _compile_mothur_script(self):
        """"""
        def format_opts(*opts):
            """Formats a series of options for a Mothur script"""
            return ', '.join(filter(None, map(str, opts)))
        vars = {
            'in': self._input_filename,
            'unique': self._derive_unique_path(),
            'dist': self._derive_dist_path(),
            'names': self._derive_names_path(),
            'cluster_opts': format_opts(
                self.Parameters['method'],
                self.Parameters['cutoff'],
                self.Parameters['precision'],
            ),
        }
        script = (
            '#'
            'unique.seqs(fasta=%(in)s); '
            'dist.seqs(fasta=%(unique)s); '
            'read.dist(column=%(dist)s, name=%(names)s); '
            'cluster(%(cluster_opts)s)' % vars
        )
        return script
1130878
def plot(self, data, w=800, h=420):
        """"""
        return HTML(
            self.iframe.format(
                source=self.render(
                    data=data, div_id="chart", head=self.head),
                w=w,
                h=h))
1180500
def make_op_return_script(data, format='bin'):
    
    if format == 'hex':
        assert(is_hex(data))
        hex_data = data
    elif format == 'bin':
        hex_data = hexlify(data)
    else:
        raise Exception("Format must be either 'hex' or 'bin'")

    num_bytes = count_bytes(hex_data)
    if num_bytes > MAX_BYTES_AFTER_OP_RETURN:
        raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes)

    script_string = 'OP_RETURN %s' % hex_data
    return script_to_hex(script_string)
1154923
def getscript(self, name):
        
        code, data, content = self.__send_command(
            "GETSCRIPT", [name.encode("utf-8")], withcontent=True)
        if code == "OK":
            lines = content.splitlines()
            if self.__size_expr.match(lines[0]) is not None:
                lines = lines[1:]
            return u"\n".join([line.decode("utf-8") for line in lines])
        return None
843045
def to_html(self):
        '''
        

        '''
        javascript_to_insert = '\n'.join([
            PackedDataUtils.full_content_of_javascript_files(),
            self.category_scatterplot_structure._visualization_data.to_javascript('getCategoryDataAndInfo'),
            self.category_scatterplot_structure.get_js_to_call_build_scatterplot(self.category_plot_interface),
            self.term_scatterplot_structure._visualization_data.to_javascript('getTermDataAndInfo'),
            self.term_scatterplot_structure.get_js_to_call_build_scatterplot(self.term_plot_interface),
        ])
        html_template = self._get_html_template()
        html_content = (
            html_template
                .replace('<!-- INSERT SCRIPT -->', javascript_to_insert, 1)
                .replace('<!--D3URL-->', self.d3_url_struct.get_d3_url(), 1)
                .replace('<!--D3SCALECHROMATIC-->', self.d3_url_struct.get_d3_scale_chromatic_url())
            # .replace('<!-- INSERT D3 -->', self._get_packaged_file_content('d3.min.js'), 1)
        )
        html_content = (html_content.replace('http://', self.protocol + '://'))
        if self.show_halo:
            axes_labels = self.category_projection.get_nearest_terms(
                num_terms=self.num_terms
            )
            for position, terms in axes_labels.items():
                html_content = html_content.replace('{%s}' % position, self._get_lexicon_html(terms))
        return html_content.replace('{width}', str(self.category_width)).replace('{height}', str(self.category_height))
620189
function getScript(url) {
		
		var script = scripts[url.name || url];
		if (script) { return script; }
		
		if (typeof url == 'object') {
			for (var key in url) {
				if (url[key]) {
					script = { name: key, url: url[key] };
				}
			}
		} else {


			var els = url.split("/"),
				 name = els[els.length -1],
				 i = name.indexOf("?");
				 
			script = {
				name: i != -1 ? name.substring(0, i) : name, 
				url: url 
			}; 
		}
		
		scripts[script.name] = script;
		return script;
	}
301265
def format_output(data, fmt='table'):  # pylint: disable=R0911,R0912
    
    if isinstance(data, utils.string_types):
        if fmt in ('json', 'jsonraw'):
            return json.dumps(data)
        return data

    # responds to .prettytable()
    if hasattr(data, 'prettytable'):
        if fmt == 'table':
            return str(format_prettytable(data))
        elif fmt == 'raw':
            return str(format_no_tty(data))

    # responds to .to_python()
    if hasattr(data, 'to_python'):
        if fmt == 'json':
            return json.dumps(
                format_output(data, fmt='python'),
                indent=4,
                cls=CLIJSONEncoder)
        elif fmt == 'jsonraw':
            return json.dumps(format_output(data, fmt='python'),
                              cls=CLIJSONEncoder)
        elif fmt == 'python':
            return data.to_python()

    # responds to .formatted
    if hasattr(data, 'formatted'):
        if fmt == 'table':
            return data.formatted

    # responds to .separator
    if hasattr(data, 'separator'):
        output = [format_output(d, fmt=fmt) for d in data if d]
        return str(SequentialOutput(data.separator, output))

    # is iterable
    if isinstance(data, list) or isinstance(data, tuple):
        output = [format_output(d, fmt=fmt) for d in data]
        if fmt == 'python':
            return output
        return format_output(listing(output, separator=os.linesep))

    # fallback, convert this odd object to a string
    return data
918821
def save_html(out_file, plot_html):
    

    internal_open = False
    if type(out_file) == str:
        out_file = open(out_file, "w")
        internal_open = True
    out_file.write("<html><head><script>\n")

    # dump the js code
    bundle_path = os.path.join(os.path.split(__file__)[0], "resources", "bundle.js")
    with io.open(bundle_path, encoding="utf-8") as f:
        bundle_data = f.read()
    out_file.write(bundle_data)
    out_file.write("</script></head><body>\n")

    out_file.write(plot_html.data)

    out_file.write("</body></html>\n")

    if internal_open:
        out_file.close()
1082815
def to_js
      js = "var data_table = new google.visualization.DataTable();"

      @cols.each do |column|
        js << "data_table.addColumn("
        js << display(column)
        js << ");"
      end

      @rows.each do |row|
        js << "data_table.addRow("
        js << "[#{row.map(&:to_js).join(", ")}]" unless row.empty?
        js << ");"
      end

      if @formatters
        @formatters.each do |formatter|
          js << formatter.to_js
        end
      end

      js
    end
1200274
def output_notebook(inline=True, logo=False):
    
    try:
        import hvplot
    except ImportError:
        raise ImportError("The intake plotting API requires hvplot."
                          "hvplot may be installed with:\n\n"
                          "`conda install -c pyviz hvplot` or "
                          "`pip install hvplot`.")
    import holoviews as hv
    return hv.extension('bokeh', inline=inline, logo=logo)
605039
def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
        
        if info or key:
            raise Exception('Renderer does not support saving metadata to file.')

        if isinstance(obj, (Plot, NdWidget)):
            plot = obj
        else:
            with StoreOptions.options(obj, options, **kwargs):
                plot = self_or_cls.get_plot(obj)

        if (fmt in list(self_or_cls.widgets.keys())+['auto']) and len(plot) > 1:
            with StoreOptions.options(obj, options, **kwargs):
                if isinstance(basename, basestring):
                    basename = basename+'.html'
                self_or_cls.export_widgets(plot, basename, fmt)
            return

        rendered = self_or_cls(plot, fmt)
        if rendered is None: return
        (data, info) = rendered
        encoded = self_or_cls.encode(rendered)
        prefix = self_or_cls._save_prefix(info['file-ext'])
        if prefix:
            encoded = prefix + encoded
        if isinstance(basename, (BytesIO, StringIO)):
            basename.write(encoded)
            basename.seek(0)
        else:
            filename ='%s.%s' % (basename, info['file-ext'])
            with open(filename, 'wb') as f:
                f.write(encoded)
599467
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
                 show_examples):
        """"""
        # leave out the first argument
        example_call = ', '.join(map(str.strip, example_call.split(',')[1:]))
        ret = docstrings.dedents("""
            %s

            This plotting method adds data arrays and plots them via
            :class:`%s` plotters

            To plot a variable in this dataset, type::

                >>> ds.psy.plot.%s(%s)

            %s""" % (summary, full_name, identifier, example_call, doc_str))

        if show_examples:
            ret += '\n\n' + cls._gen_examples(identifier)
        return ret