Check to see if we are in an IPython or Jypyter notebook.

    Returns
    -----------
    in_notebook : bool
      Returns True if we are in a notebook
540977
def in_notebook():
    
    try:
        # function returns IPython context, but only in IPython
        ipy = get_ipython()  # NOQA
        # we only want to render rich output in notebooks
        # in terminals we definitely do not want to output HTML
        name = str(ipy.__class__).lower()
        terminal = 'terminal' in name

        # spyder uses ZMQshell, and can appear to be a notebook
        spyder = '_' in os.environ and 'spyder' in os.environ['_']

        # assume we are in a notebook if we are not in
        # a terminal and we haven't been run by spyder
        notebook = (not terminal) and (not spyder)

        return notebook

    except BaseException:
        return False
776136
def _CheckIsDevice(self, file_entry):
    
    if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
      return False
    return file_entry.IsDevice()
800227
def is_in_pythonpath(self, dirname):
        """"""
        return fixpath(dirname) in [fixpath(_p) for _p in self.pythonpath]
860154
def same_notebook_code(nb1, nb2):
    

    # Notebooks do not match of the number of cells differ
    if len(nb1['cells']) != len(nb2['cells']):
        return False

    # Iterate over cells in nb1
    for n in range(len(nb1['cells'])):
        # Notebooks do not match if corresponding cells have different
        # types
        if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']:
            return False
        # Notebooks do not match if source of corresponding code cells
        # differ
        if nb1['cells'][n]['cell_type'] == 'code' and \
                nb1['cells'][n]['source'] != nb2['cells'][n]['source']:
            return False

    return True
179891
def is_defined(self, objtxt, force_import=False):
        """"""
        if self._reading:
            return
        wait_loop = QEventLoop()
        self.sig_got_reply.connect(wait_loop.quit)
        self.silent_exec_method(
            "get_ipython().kernel.is_defined('%s', force_import=%s)"
            % (objtxt, force_import))
        wait_loop.exec_()

        # Remove loop connection and loop
        self.sig_got_reply.disconnect(wait_loop.quit)
        wait_loop = None

        return self._kernel_reply
961959
def run_ipython_notebook(notebook_str):
    
    from runipy.notebook_runner import NotebookRunner
    import nbformat
    import logging
    log_format = '%(asctime)s %(levelname)s: %(message)s'
    log_datefmt = '%m/%d/%Y %I:%M:%S %p'
    logging.basicConfig(
        level=logging.INFO, format=log_format, datefmt=log_datefmt
    )
    #fpath = 'tmp.ipynb'
    #notebook_str = ut.readfrom(fpath)
    #nb3 = IPython.nbformat.reads(notebook_str, 3)
    #cell = nb4.cells[1]
    #self = runner
    #runner = NotebookRunner(nb3, mpl_inline=True)
    print('Executing IPython notebook')
    nb4 = nbformat.reads(notebook_str, 4)
    runner = NotebookRunner(nb4)
    runner.run_notebook(skip_exceptions=False)
    run_nb = runner.nb
    return run_nb
233616
def get_notebook_name() -> str:
    
    kernel_id = re.search(  # type: ignore
        'kernel-(.*).json',
        ipykernel.connect.get_connection_file()
    ).group(1)
    servers = list_running_servers()
    for server in servers:
        response = requests.get(urljoin(server['url'], 'api/sessions'),
                                params={'token': server.get('token', '')})
        for session in json.loads(response.text):
            if session['kernel']['id'] == kernel_id:
                relative_path = session['notebook']['path']
                return pjoin(server['notebook_dir'], relative_path)
    raise Exception('Noteboook not found.')
533828
def find_notebook(fullname, path=None):
    
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        # let import Notebook_Name find "Notebook Name.ipynb"
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path
1245714
def checkCursor(self):
        ''
        # keep cursor within actual available rowset
        if self.nRows == 0 or self.cursorRowIndex <= 0:
            self.cursorRowIndex = 0
        elif self.cursorRowIndex >= self.nRows:
            self.cursorRowIndex = self.nRows-1

        if self.cursorVisibleColIndex <= 0:
            self.cursorVisibleColIndex = 0
        elif self.cursorVisibleColIndex >= self.nVisibleCols:
            self.cursorVisibleColIndex = self.nVisibleCols-1

        if self.topRowIndex <= 0:
            self.topRowIndex = 0
        elif self.topRowIndex > self.nRows-1:
            self.topRowIndex = self.nRows-1

        # (x,y) is relative cell within screen viewport
        x = self.cursorVisibleColIndex - self.leftVisibleColIndex
        y = self.cursorRowIndex - self.topRowIndex + 1  # header

        # check bounds, scroll if necessary
        if y < 1:
            self.topRowIndex = self.cursorRowIndex
        elif y > self.nVisibleRows:
            self.topRowIndex = self.cursorRowIndex-self.nVisibleRows+1

        if x <= 0:
            self.leftVisibleColIndex = self.cursorVisibleColIndex
        else:
            while True:
                if self.leftVisibleColIndex == self.cursorVisibleColIndex:  # not much more we can do
                    break
                self.calcColLayout()
                mincolidx, maxcolidx = min(self.visibleColLayout.keys()), max(self.visibleColLayout.keys())
                if self.cursorVisibleColIndex < mincolidx:
                    self.leftVisibleColIndex -= max((self.cursorVisibleColIndex - mincolid)//2, 1)
                    continue
                elif self.cursorVisibleColIndex > maxcolidx:
                    self.leftVisibleColIndex += max((maxcolidx - self.cursorVisibleColIndex)//2, 1)
                    continue

                cur_x, cur_w = self.visibleColLayout[self.cursorVisibleColIndex]
                if cur_x+cur_w < self.vd.windowWidth:  # current columns fit entirely on screen
                    break
                self.leftVisibleColIndex += 1
498307
def _save_nb(nb_name):
    
    display(Javascript('IPython.notebook.save_checkpoint();'))
    display(Javascript('IPython.notebook.save_notebook();'))
    print('Saving notebook...', end=' ')

    if _wait_for_save(nb_name):
        print("Saved '{}'.".format(nb_name))
    else:
        logging.warning(
            "Could not save your notebook (timed out waiting for "
            "IPython save). Make sure your notebook is saved "
            "and export again."
        )
481030
def show_in_notebook(self,
                         labels=None,
                         predict_proba=True,
                         show_predicted_value=True,
                         **kwargs):
        """"""

        from IPython.core.display import display, HTML
        display(HTML(self.as_html(labels=labels,
                                  predict_proba=predict_proba,
                                  show_predicted_value=show_predicted_value,
                                  **kwargs)))
1027878
def contains_if(self, include_loop=True):
        
        if include_loop:
            return self.type in [NodeType.IF, NodeType.IFLOOP]
        return self.type == NodeType.IF
164014
def jupyter_notebook(script_blocks, gallery_conf):
    
    first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
    work_notebook = jupyter_notebook_skeleton()
    if first_cell is not None:
        add_code_cell(work_notebook, first_cell)
    fill_notebook(work_notebook, script_blocks)

    return work_notebook
465231
def _in(x, y):
    
    try:
        return x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return y.isin(x)
            except AttributeError:
                pass
        return x in y
1204473
def is_ipynb():
    
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':  # Jupyter notebook or qtconsole?
            return True
        elif shell == 'TerminalInteractiveShell':  # Terminal running IPython?
            return False
        else:
            return False  # Other type (?)
    except NameError:
        return False
649232
def is_stored(self, i):
        
        if i in self.stored:
            return True

        try:
            with self._read_context(i):
                return True
        except (AngrVaultError, EOFError):
            return False
801911
def _get_notebook_node(self):                   # pragma: no cover
        ""
        size = len(self._notebook_data)
        if size == 0:
            raise Exception("Captured buffer size for notebook node is zero.")
        node = reader.reads(self._notebook_data)
        self.nbversion = reader.get_version(node)
        return node