python类display()的实例源码

widget.py 文件源码 项目:altair_widgets 作者: altair-viz 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def interact_with(df, ndims=3, **kwargs):
    """
    Interactively view a DataFrame.

    Parameters
    ----------
    df : DataFrame
        The DataFrame to interact with

    ndims : int, optional
        The number of dimensions wished to encode at start (the number of rows
        with encoding/data/function/data_type).

    Notes
    -----
    In the Jupyter notebook, display a widget to allow you to selectively plot
    columns to plot/encode/etc.

    Use a smaller value if ndims if less dimensions and controls are desired.

    """
    return Interact(df, ndims=ndims, **kwargs)
widget.py 文件源码 项目:altair_widgets 作者: altair-viz 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __init__(self, df, ndims=3, show=True):
        if not isinstance(df, pd.core.frame.DataFrame):
            raise ValueError('Interact takes a DataFrame as input')
        columns = [None] + _get_columns(df)
        self.columns = columns
        encodings = _get_encodings()
        self.df = df
        encodings = [{'encoding': encoding}
                     for encoding in encodings[:ndims]]
        self.settings = {'mark': {'mark': 'mark_point'},
                         'encodings': encodings}

        self.controller = self._generate_controller(ndims)
        self.show = show
        if self.show:
            display(self.controller)

        self.plot(show=show)
notebook_utils.py 文件源码 项目:magenta 作者: tensorflow 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def play_sequence(sequence,
                  synth=midi_synth.synthesize,
                  sample_rate=_DEFAULT_SAMPLE_RATE,
                  colab_ephemeral=True,
                  **synth_args):
  """Creates an interactive player for a synthesized note sequence.

  This function should only be called from a Jupyter or Colab notebook.

  Args:
    sequence: A music_pb2.NoteSequence to synthesize and play.
    synth: A synthesis function that takes a sequence and sample rate as input.
    sample_rate: The sample rate at which to synthesize.
    colab_ephemeral: If set to True, the widget will be ephemeral in Colab, and
      disappear on reload (and it won't be counted against realtime document
      size).
    **synth_args: Additional keyword arguments to pass to the synth function.
  """
  array_of_floats = synth(sequence, sample_rate=sample_rate, **synth_args)

  try:
    import google.colab  # pylint: disable=unused-import,unused-variable,g-import-not-at-top
    colab_play(array_of_floats, sample_rate, colab_ephemeral)
  except ImportError:
    display.display(display.Audio(array_of_floats, rate=sample_rate))
df_analyzer.py 文件源码 项目:Optimus 作者: ironmussa 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def general_description(self):
        # General data description:
        # Filename:
        if self._path_file is None:
            file_name = "file with no path"
        else:
            file_name = self._path_file.split('/')[-1]
        # Counting the number of columns:
        row_number = self._df.count()
        # Counting the number of rows:
        col_number = len(self._df.columns)
        # Writting General Description table:
        temp_obj = GeneralDescripTable(file_name, col_number, row_number)
        display(temp_obj)

        data_types = len(set([x[1] for x in self._df.dtypes]))

        return self._create_dict(["filename", "size", "columns", "rows", "datatypes"],
                                 [file_name, 500, col_number, row_number, data_types])

    # Funtion to analize column datatypes, it also plot proportion datatypes and histograms:
geometry_viewer.py 文件源码 项目:notebook-molecular-visualization 作者: Autodesk 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, mol, style=None, display=False, width='100%', height='400px',
                 **kwargs):
        kwargs.update(width=width, height=height)
        super().__init__(**kwargs)
        self.height = in_pixels(height)
        self.width = in_pixels(width)
        self.atom_colors = {}

        # current state
        self.atom_highlights = []
        self._axis_objects = None
        self._colored_as = {}

        self.add_molecule(mol)
        if style is None:
            self.autostyle()
        else:
            self.set_style(style)

        if display:
            dsp.display(self)
geometry_viewer.py 文件源码 项目:notebook-molecular-visualization 作者: Autodesk 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def set_positions(self, positions=None):
        """ Set positions of atoms in the 3D display

        Args:
            positions (Matrix[length, shape=(*,3)]): positions to set atoms to - optional.
               If not provided, positions are taken from current positions of the molecule.

        Returns:

        """
        if positions is None:
            pos = self.mol.positions
        else:
            pos = positions

        self.positions = pos.value_in(u.angstrom).tolist()
        self._update_clipping(np.abs(pos.value_in(self.DISTANCE_UNITS)).max())
drilsdown.py 文件源码 项目:ipython-IDV 作者: Unidata 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def make_movie(line, cell=None):
    toks = shlex.split(line)
    skip = 0
    publish = False
    display_id = None
    caption = None
    cptr = None;
    for i in range(len(toks)):
        if skip > 0:
            skip = skip-1
            continue
        tok = toks[i]
        if tok == "-publish":
            publish = True
        elif tok == "-caption":
            skip = 1
            caption = toks[i+1]
        elif tok == "-capture":
            skip = 1
            cptr = toks[i+1]
        elif tok == "-display":
            skip = 1
            display_id = toks[i+1]

    return Idv.make_movie(publish, caption, display_id=display_id, capture=cptr)
drilsdown.py 文件源码 项目:ipython-IDV 作者: Unidata 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def view_url_clicked(b):
        DrilsdownUI.do_display(HTML("<a target=ramadda href=" + b.url + ">" + b.name + "</a>"))
        display(IFrame(src=b.url, width=800, height=400))
drilsdown.py 文件源码 项目:ipython-IDV 作者: Unidata 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def publish_notebook(extra=None):
        # If we do this then the Javascript object shows up in the notebook
        # js = Javascript('IPython.notebook.save_checkpoint();')
        # display(js)
        file = Idv.getname()
        if file is None:
            return
        isl = '<isl><publish file="' + file + '"/></isl>'
        DrilsdownUI.status("Make sure you do 'File->Save and Checkpoint'. Check your IDV to publish the file")
        result = Idv.run_isl(isl);
        if not result.ok():
            print("Publication failed")
            return
        if result.get_results().strip()!="":
            print("Publication successful")
            print("URL: " + result.get_results())
            return
        print("Publication failed")
drilsdown.py 文件源码 项目:ipython-IDV 作者: Unidata 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def export_data(filename=None, display_id=None, load_data = False):
        DrilsdownUI.status("Exporting data ...")
        extra = ""
        if display_id is not None:
            extra += ' display="' + display_id + '" '
        if filename is  None:
            f = NamedTemporaryFile(suffix='.gif', delete=False) 
            filename = f.name;
        isl = '<isl><export file="' + f.name + '"' \
            + extra + '/></isl>'
        result = Idv.run_isl(isl)
        if not result.ok():
            return;
        if load_data:
            placeholder = false;
            #                return load_data(filename);
            # img = '<img src="data:image/gif;base64,{0}">'
        DrilsdownUI.status("data exported to: " + filename)
drilsdown.py 文件源码 项目:ipython-IDV 作者: Unidata 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def do_list(self, dir=None, display=False, label="Entries"):
        """make a list of RamaddaEntry objects that are children of the given entryId"""
        if dir is None:
            dir = self.dir
        files = os.listdir(dir)
        entries = []
        prefix = dir+"/"
        if prefix == "./":
            prefix = ""
        for i in range(len(files)):
            if files[i].startswith(".") is not True:
                entries.append(FileEntry(self, prefix + files[i]))

        if display:
            self.display_entries(label, entries)
        else:
            return entries
display.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def update_display(obj, *, display_id, **kwargs):
    """Update an existing display by id

    Parameters
    ----------

    obj:
        The object with which to update the display
    display_id: keyword-only
        The id of the display to update

    See Also
    --------

    :func:`display`
    """
    kwargs['update'] = True
    display(obj, display_id=display_id, **kwargs)
display.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def display_markdown(*objs, **kwargs):
    """Displays the Markdown representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw markdown data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """

    _display_mimetype('text/markdown', objs, **kwargs)
display.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def display_pdf(*objs, **kwargs):
    """Display the PDF representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw javascript data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """
    _display_mimetype('application/pdf', objs, **kwargs)


#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
display.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs):
        """Create a JSON display object given raw data.

        Parameters
        ----------
        data : dict or list
            JSON data to display. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        expanded : boolean
            Metadata to control whether a JSON display component is expanded.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """
        self.metadata = {'expanded': expanded}
        if metadata:
            self.metadata.update(metadata)
        if kwargs:
            self.metadata.update(kwargs)
        super(JSON, self).__init__(data=data, url=url, filename=filename)
PhaseRetrieval.py 文件源码 项目:chxanalys 作者: yugangzhang 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def displayResult(self):
        fig = plt.figure(101)
        plt.subplot(221)
        plt.imshow(np.abs(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Magnitude')
        plt.subplot(222)
        plt.imshow(np.angle(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Phase')
        plt.subplot(223)
        plt.imshow(np.abs(self.aperture),origin='lower')
        plt.title("Aperture Magnitude")
        plt.draw()
        plt.subplot(224)
        plt.imshow(np.angle(self.aperture),origin='lower')
        plt.title("Aperture Phase")
        plt.draw()
        fig.canvas.draw()


        #fig.tight_layout()
        # display.display(fig)
        # display.clear_output(wait=True)
        # time.sleep(.00001)
__init__.py 文件源码 项目:paramnb 作者: ioam 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def run_next_cells(n):
    if n=='all':
        n = 'NaN'
    elif n<1:
        return

    js_code = """
       var num = {0};
       var run = false;
       var current = $(this)[0];
       $.each(IPython.notebook.get_cells(), function (idx, cell) {{
          if ((cell.output_area === current) && !run) {{
             run = true;
          }} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{
             cell.execute();
             num = num - 1;
          }}
       }});
    """.format(n)

    display(Javascript(js_code))
pipewidgets.py 文件源码 项目:berrl 作者: murphy214 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def make_legend(title,colors,labels):
    colorhashs=[]
    for row in colors:
        colorhashs.append(get_colors(row))
    return '''
<div id='legend' style='display:none;'>
  <strong>%s</strong>
  <nav class='legend clearfix'>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <small>Source: <a href="https://github.com/murphy214/berrl">Made using Berrl</a></small>
</div>
''' % (title,colorhashs[0],colorhashs[1],colorhashs[2],colorhashs[3],colorhashs[4],labels[0],labels[1],labels[2],labels[3],labels[4])


# returns the blocks of color backgrounds for a given list of colors
pipewidgets.py 文件源码 项目:berrl 作者: murphy214 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def make_top2(rangelist):
    widthpercentage = 100.0 / float(len(rangelist))
    return '''<style>
.legend label,
.legend span {
  display:block;
  float:left;
  height:15px;
  width:xx%;
  text-align:center;
  font-size:9px;
  color:#808080;
  }
</style>'''.replace('xx',str(widthpercentage))



# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
pipewidgets.py 文件源码 项目:berrl 作者: murphy214 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def make_top2(rangelist):
    widthpercentage = 100.0 / float(len(rangelist))
    return '''<style>
.legend label,
.legend span {
  display:block;
  float:left;
  height:15px;
  width:xx%;
  text-align:center;
  font-size:9px;
  color:#808080;
  }
</style>'''.replace('xx',str(widthpercentage))



# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
profile_plotter.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def show(self):
        r"""This will send any existing plots to the IPython notebook.

        If yt is being run from within an IPython session, and it is able to
        determine this, this function will send any existing plots to the
        notebook for display.

        If yt can't determine if it's inside an IPython session, it will raise
        YTNotInsideNotebook.

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>> pp = ProfilePlot(ds.all_data(), 'density', 'temperature')
        >>> pp.show()

        """
        if "__IPYTHON__" in dir(builtins):
            from IPython.display import display
            display(self)
        else:
            raise YTNotInsideNotebook
profile_plotter.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _repr_html_(self):
        """Return an html representation of the plot object. Will display as a
        png for each WindowPlotMPL instance in self.plots"""
        ret = ''
        unique = set(self.plots.values())
        if len(unique) < len(self.plots):
            iters = izip(range(len(unique)), sorted(unique))
        else:
            iters = iteritems(self.plots)
        for uid, plot in iters:
            with matplotlib_style_context():
                img = plot._repr_png_()
            img = base64.b64encode(img).decode()
            ret += r'<img style="max-width:100%%;max-height:100%%;" ' \
                   r'src="data:image/png;base64,{0}"><br>'.format(img)
        return ret
kendall_triangles.py 文件源码 项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self, mode = 'whole sphere', resolution = (45, 90) ):
        "mode = 'whole sphere' | 'spherical blackboard'"
        self.mode = mode
        if self.mode == 'whole sphere' :
            thetas = linspace(0,   pi, resolution[0] + 1)
            phis   = linspace(-pi, pi, resolution[1] + 1)
        elif self.mode == 'spherical blackboard' :
            thetas = linspace(0,.5*pi, resolution[0] + 1)
            phis   = linspace(-pi/3, 0, resolution[1] + 1)

        (self.theta_grid, self.phi_grid) = meshgrid(thetas, phis)
        self.theta_centers = (self.theta_grid[0:-1,0:-1] + self.theta_grid[0:-1,1:] + self.theta_grid[1:,0:-1] + self.theta_grid[1:,1:]) / 4.
        self.phi_centers   = (self.phi_grid[0:-1,0:-1]   + self.phi_grid[0:-1,1:]   + self.phi_grid[1:,0:-1]   + self.phi_grid[1:,1:] ) / 4.

        areas_thetas = (phis[1]-phis[0]) * ( -cos(thetas[1:]) + cos(thetas[0:-1]))
        self.cell_areas = vstack( (areas_thetas,)*(resolution[1]) ).T

        # Setup routines for the interactive "Plot.ly" display
        self.setup_layout()
        self.current_axis = []
14_DeepDream.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_image(image):
    # Assume the pixel-values are scaled between 0 and 255.

    if False:
        # Convert the pixel-values to the range between 0.0 and 1.0
        image = np.clip(image/255.0, 0.0, 1.0)

        # Plot using matplotlib.
        plt.imshow(image, interpolation='lanczos')
        plt.show()
    else:
        # Ensure the pixel-values are between 0 and 255.
        image = np.clip(image, 0.0, 255.0)

        # Convert pixels to bytes.
        image = image.astype(np.uint8)

        # Convert to a PIL-image and display it.
        display(PIL.Image.fromarray(image))


# Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient.

# In[13]:
__init__.py 文件源码 项目:jupyter_vega 作者: altair-viz 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
        """Create a VegaLite display object given raw data.

        Parameters
        ----------
        spec : dict
            VegaLite spec. Not an already-serialized JSON string.
        data : dict or list
            VegaLite data. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """

        super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
__init__.py 文件源码 项目:jupyter_vega 作者: altair-viz 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
        """Create a VegaLite display object given raw data.

        Parameters
        ----------
        spec : dict
            VegaLite spec. Not an already-serialized JSON string.
        data : dict or list
            VegaLite data. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """

        super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
snowballing.py 文件源码 项目:snowballing 作者: JoaoFelipe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def show_site(self, article, nwork, info):
        """Display site citation"""
        text = "# Temp\n"
        text += "insert('''"
        text += citation_text(
            self.citation_var, info,
            ref=article.get('citation_id', ''),
            backward=self.backward
        ) + "\n"
        text += "''', citations='{}');".format(self.citation_file)
        display_cell(text)
        self.output_widget.clear_output()
        with self.output_widget:
            if self.to_display:
                display("\n".join(self.to_display))
            if 'div' in article:
                display(HTML(repr(article['div'])))
            elif 'name' in article:
                print(article['name'])
        self.to_display = []
graph.py 文件源码 项目:snowballing 作者: JoaoFelipe 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def update_r_widget(self, *args):
        """Callback for updating r_widget value"""
        self._display_stack += 1
        r_value = self.r_widget.value
        dist_min = 2 * r_value + 2
        letters_max = int(r_value / 3.6)
        self.margin_left_widget.min = -1
        self.margin_left_widget.value = max(r_value, self.margin_left_widget.value)
        self.margin_left_widget.min = r_value
        self.dist_x_widget.min = -1
        self.dist_x_widget.value = max(dist_min, self.dist_x_widget.value)
        self.dist_x_widget.min = dist_min
        self.dist_y_widget.min = -1
        self.dist_y_widget.value = max(dist_min, self.dist_y_widget.value)
        self.dist_y_widget.min = dist_min
        self.letters_widget.max = 5000
        self.letters_widget.value = min(letters_max, self.letters_widget.value)
        self.letters_widget.max = letters_max
        self.display()
graph.py 文件源码 项目:snowballing 作者: JoaoFelipe 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def create_category(self, name, attr, value, color, font_color):
        """Create category widget"""
        VIS = ['none', '']
        widget = self.toggle_widgets[attr] = ToggleButton(value=value, description=name)
        wcolor = self.color_widgets[attr] = ColorPicker(value=color, description=name, width="180px")
        wfont_color = self.font_color_widgets[attr] = ColorPicker(value=font_color, width="110px")
        def visibility(*args):
            """" Toggles visibility of category """
            self._display_stack += 1
            wcolor.layout.display = VIS[int(widget.value)]
            wfont_color.layout.display = VIS[int(widget.value)]
            self.display()
        widget.observe(visibility, "value")
        wcolor.observe(self.update_widget, "value")
        wfont_color.observe(self.update_widget, "value")
        visibility()
KA_data_exploration.py 文件源码 项目:Kaggle_Buddy 作者: NickYi1990 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def ka_display_muti_tables_summary(tables, table_names, n=5):
    '''display multi tables' summary

        Parameters
        ----------
        tables: list_like
                Pandas dataframes
        table_names: list_like
                     names of each dataframe

        Return
        ------
        1. show head of data
        2. show column types of data
        3. show summary of data
    '''
    for t, t_name in zip(tables, table_names):
        print(t_name + ":", t.shape)
        ka_display_side_by_side(t.head(n=n), _ka_display_col_type(t), DataFrameSummary(t).summary())


问题


面经


文章

微信
公众号

扫码关注公众号