python类display()的实例源码

KA_data_exploration.py 文件源码 项目:Kaggle_Buddy 作者: NickYi1990 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def ka_C_Binary_ratio(y, positive=1):
    '''Find the positive ration of dependent variable

        Parameters
        ----------
        y: pandas series
           binary dependent variable
        positive: 1 or 0
                  identify which value is positive

        Return
        ------
        float value display positive rate
    '''
    return y.value_counts()[positive] / (y.value_counts().sum())

####################################################################################
##                              NUMERICAL BLOCK
####################################################################################
PlayCatchGame.py 文件源码 项目:CatchGame-QLearningExample-TensorFlow 作者: solaris33 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
ui.py 文件源码 项目:ray 作者: ray-project 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def task_search_bar():
    task_search = widgets.Text(
        value="",
        placeholder="Task ID",
        description="Search for a task:",
        disabled=False
        )
    display(task_search)

    def handle_submit(sender):
        pp = pprint.PrettyPrinter()
        pp.pprint(ray.global_state.task_table(task_search.value))

    task_search.on_submit(handle_submit)


# Hard limit on the number of tasks to return to the UI client at once
ipython_notebook.py 文件源码 项目:tap 作者: mfouesneau 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_input_toggle():
    from IPython.display import HTML, display

    r = HTML('''
    <script>

    $( document ).ready(function () {
        IPython.CodeCell.options_default['cm_config']['lineWrapping'] = true;
        IPython.notebook.get_selected_cell()

        IPython.toolbar.add_buttons_group([
                {
                    'label'   : 'toggle all input cells',
                    'icon'    : 'fa-eye-slash',
                    'callback': function(){ $('div.input').slideToggle(); }
                }
            ]);
    });
    </script>
    ''')
    display(r)
    return r
amazon_gui.py 文件源码 项目:scikit-discovery 作者: MITHaystack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def drawGUI():
    '''
    Draw the GUI on the screen
    '''
    display(widget_dict['aws_id_widget'])
    display(widget_dict['aws_secret_widget'])
    display(widget_dict['aws_region_widget'])
    display(widget_dict['aws_security_widget'])
    display(widget_dict['aws_keyname_widget'])
    display(widget_dict['aws_pem_widget'])
    display(widget_dict['aws_image_id'])    
    display(widget_dict['instance_type_widget'])
    display(widgets.HBox([widget_dict['initialize_button'], widget_dict['cache_button'],widget_dict['restore_button']]))

    # display(widgets.HBox([widget_dict['label_num_instances'], widget_dict['new_num_instances_widget']]))
    # display(widgets.HBox([widget_dict['run_label'], widget_dict['aws_status_widget']]))

    display(widget_dict['new_num_instances_widget'])
    display(widget_dict['aws_status_widget'])
    display(widget_dict['execute_instances_button'])
PlayCatchGame.py 文件源码 项目:TensorFlow_Examples 作者: solaris33 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
functions.py 文件源码 项目:ro_sgns 作者: AlexGrinch 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def plot_dynamics(vecs, vec2, n=5, MAX_ITER=100):
    """
    Plot how the distances between pairs change with each n
    iterations of the optimization method.
    """

    for i in xrange(MAX_ITER):
        if (i%n==0):
            plt.clf()
            plt.xlim([-0.01, 1.2])
            plt.plot(vecs[i], vec2, 'ro', color='blue')
            plt.grid()
            display.clear_output(wait=True)
            display.display(plt.gcf())
    plt.clf()

    fig, ax = plt.subplots(1, 2, figsize=(13, 4))
    for i in xrange(2):
        ax[i].set_xlim([-0.01, 1.2])
        ax[i].plot(vecs[-i], vec2, 'ro', color='blue')
        ax[i].set_title(str(i*MAX_ITER)+' iterations')
        ax[i].set_xlabel('Cosine distance', fontsize=14)
        ax[i].set_ylabel('Assesor grade', fontsize=14)
        ax[i].grid()
jobs.py 文件源码 项目:jupyterlib 作者: cybergis 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(self):
        #user=widgets.Text(value=USERNAME,placeholder='Your ROGER Account name', description='Username',disabled=False)
        #display(user)
        #pw=getpass(prompt='Password')

        #paramiko.util.log_to_file("ssh.log")
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.homeDir = '%s/%s'%(JUPYTER_HOME,USERNAME)
        self.jobDir = self.homeDir + '/.jobs'
        if not os.path.exists(self.jobDir):
            os.makedirs(self.jobDir)
        self.userName = USERNAME
        self.rogerRoot = '%s/%s'%(ROGER_PRJ, self.userName)
        self.rogerJobDir = self.rogerRoot + '/.jobs'
        self.relPath = os.path.relpath(os.getcwd(), self.homeDir)
        self.rogerPath = self.rogerRoot + '/' + self.relPath
        self.editMode = True
        self.jobId = None
        with open(os.path.dirname(__file__)+'/qsub.template') as input:
            self.job_template=Template(input.read())
        self.login()
reinforcement_q_learning.py 文件源码 项目:tutorials 作者: pytorch 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))
        return self.head(x.view(x.size(0), -1))


######################################################################
# Input extraction
# ^^^^^^^^^^^^^^^^
#
# The code below are utilities for extracting and processing rendered
# images from the environment. It uses the ``torchvision`` package, which
# makes it easy to compose image transforms. Once you run the cell it will
# display an example patch that it extracted.
#
drawTopicModel.py 文件源码 项目:CheTo 作者: rdkit 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, tableHeader='', maxMols=100):

    result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\
                                                              molSize=molSize, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return

    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))

    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label),
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules of a certain label and highlights the most probable topic
drawTopicModel.py 文件源码 项目:CheTo 作者: rdkit 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, color=(.0,.0, 1.), maxMols=100):
    result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \
                                             topicProbThreshold = topicProbThreshold, baseRad=baseRad,\
                                             molSize=molSize,color=color, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return

    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))

    tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)'

    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules
capture.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __enter__(self):
        from IPython.core.getipython import get_ipython
        from IPython.core.displaypub import CapturingDisplayPublisher

        self.sys_stdout = sys.stdout
        self.sys_stderr = sys.stderr

        if self.display:
            self.shell = get_ipython()
            if self.shell is None:
                self.save_display_pub = None
                self.display = False

        stdout = stderr = outputs = None
        if self.stdout:
            stdout = sys.stdout = StringIO()
        if self.stderr:
            stderr = sys.stderr = StringIO()
        if self.display:
            self.save_display_pub = self.shell.display_pub
            self.shell.display_pub = CapturingDisplayPublisher()
            outputs = self.shell.display_pub.outputs


        return CapturedIO(stdout, stderr, outputs)
display.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 24 收藏 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 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 21 收藏 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 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 20 收藏 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
#-----------------------------------------------------------------------------
widget.py 文件源码 项目:altair_widgets 作者: altair-viz 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def plot(self, show=True):
        """ Assumes nothing in self.settings is None (i.e., there are no keys
        in settings such that settings[key] == None"""

        kwargs = {e['encoding']: _get_plot_command(e)
                  for e in self.settings['encodings']}

        mark_opts = {k: v for k, v in self.settings['mark'].items()}
        mark = mark_opts.pop('mark')
        Chart_mark = getattr(altair.Chart(self.df), mark)
        self.chart = Chart_mark(**mark_opts).encode(**kwargs)
        if show and self.show:
            clear_output()
            display(self.chart)
widget.py 文件源码 项目:altair_widgets 作者: altair-viz 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _add_dim(self, button):
        i = len(self.controller.children) - 1
        encoding = _get_encodings()[i]
        shelf = self._create_shelf(i=i)
        kids = self.controller.children
        teens = list(kids)[:-1] + [shelf] + [list(kids)[-1]]
        self.controller.children = teens

        # clear_output()
        # display(self.controller)
        self.settings['encodings'] += [{'encoding': encoding}]
        self.plot(self.settings)
utility_belt.py 文件源码 项目:SQLCell 作者: tmthyjames 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def display(self, columns=[], msg=None):
        data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:]
        table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data))
        table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','')
        display(
            HTML(
                """
                <script type="text/Javascript">
                $('#dbinfo{id}').append('{msg}');
                $('#table{id}').append('{table}');
                </script>
                """.format(msg=str(msg), table=table_str, id=self.id_)
            )
        )
utility_belt.py 文件源码 项目:SQLCell 作者: tmthyjames 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def build_node(id_, node, xPos):
        _node = {
            'name': id_,
            'nodetype': node.get('Plan', node).get('Node Type'),
            'starttime': node.get('Plan', node).get('Actual Startup Time'),
            'endtime': node.get('Plan', node).get('Actual Total Time'),
            'subplan': node.get('Plan', node).get('Subplan Name'),
            'display': str(node.get('Plan', node).get('Join Filter', 
                                                  node.get('Filter', 
                                                           node.get('Index Cond', 
                                                                    node.get('Hash Cond', 
                                                                             node.get('One-Time Filter',
                                                                                     node.get('Recheck Cond',
                                                                                             node.get('Group Key')
                                                                                             )
                                                                                     )
                                                                            )
                                                                   )
                                                          )
                                                 ) or '') + (' using ' 
                                            + str(node.get('Index Name', 
                                                           node.get('Relation Name',
                                                                   node.get('Schema')))) + ' ' + str(node.get('Alias')or'')
                                                if node.get('Index Name', 
                                                            node.get('Relation Name',
                                                                    node.get('Schema'))) 
                                                else ''),
            'rows': node.get('Plan', node).get('Plan Rows'),
            'xPos': xPos
        }
        return _node
utility_belt.py 文件源码 项目:SQLCell 作者: tmthyjames 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def load_js_files():
    display(Javascript(
        load_js_scripts()
    ))
    return None


问题


面经


文章

微信
公众号

扫码关注公众号