We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
setp() issue in ipython notebook with figure references
In IPython notebook, when I run `setp()` to change parameters of a figure created in another cell and accessed with its reference, an exception occurs

``` python
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-82-54a641ac28e1> in <module>()
----> 1 setp(axis.lines[0], linewidth=2)

/home/amir/virtualenv/cr/local/lib/python2.7/site-packages/matplotlib/pyplot.pyc in setp(*args, **kwargs)
    238 def setp(*args, **kwargs):
    239     ret = _setp(*args, **kwargs)
--> 240     draw_if_interactive()
    241     return ret
    242 

/home/amir/virtualenv/cr/local/lib/python2.7/site-packages/IPython/zmq/pylab/backend_inline.py in draw_if_interactive()
    123     # flush_figures() will act upon these values
    124 
--> 125     fig = Gcf.get_active().canvas.figure
    126 
    127     # Hack: matplotlib FigureManager objects in interacive backends (at least

AttributeError: 'NoneType' object has no attribute 'canvas'
```

Nevertheless, `setp()` successfully does its job but since IPython notebook by default closes the figures of previous cells the exception occurs.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/kernel/zmq/pylab/backend_inline.py`
Content:
```
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 """
3 #-----------------------------------------------------------------------------
4 # Imports
5 #-----------------------------------------------------------------------------
6 from __future__ import print_function
7 
8 # Third-party imports
9 import matplotlib
10 from matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg
11 from matplotlib._pylab_helpers import Gcf
12 
13 # Local imports.
14 from IPython.config.configurable import SingletonConfigurable
15 from IPython.core.display import display
16 from IPython.core.displaypub import publish_display_data
17 from IPython.core.pylabtools import print_figure, select_figure_format
18 from IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, Bool
19 from IPython.utils.warn import warn
20 
21 #-----------------------------------------------------------------------------
22 # Configurable for inline backend options
23 #-----------------------------------------------------------------------------
24 # inherit from InlineBackendConfig for deprecation purposes
25 class InlineBackendConfig(SingletonConfigurable):
26     pass
27 
28 class InlineBackend(InlineBackendConfig):
29     """An object to store configuration of the inline backend."""
30 
31     def _config_changed(self, name, old, new):
32         # warn on change of renamed config section
33         if new.InlineBackendConfig != old.InlineBackendConfig:
34             warn("InlineBackendConfig has been renamed to InlineBackend")
35         super(InlineBackend, self)._config_changed(name, old, new)
36 
37     # The typical default figure size is too large for inline use,
38     # so we shrink the figure size to 6x4, and tweak fonts to
39     # make that fit.
40     rc = Dict({'figure.figsize': (6.0,4.0),
41         # play nicely with white background in the Qt and notebook frontend
42         'figure.facecolor': 'white',
43         'figure.edgecolor': 'white',
44         # 12pt labels get cutoff on 6x4 logplots, so use 10pt.
45         'font.size': 10,
46         # 72 dpi matches SVG/qtconsole
47         # this only affects PNG export, as SVG has no dpi setting
48         'savefig.dpi': 72,
49         # 10pt still needs a little more room on the xlabel:
50         'figure.subplot.bottom' : .125
51         }, config=True,
52         help="""Subset of matplotlib rcParams that should be different for the
53         inline backend."""
54     )
55 
56     figure_format = CaselessStrEnum(['svg', 'png', 'retina'], default_value='png', config=True,
57         help="The image format for figures with the inline backend.")
58 
59     def _figure_format_changed(self, name, old, new):
60         if self.shell is None:
61             return
62         else:
63             select_figure_format(self.shell, new)
64     
65     close_figures = Bool(True, config=True,
66         help="""Close all figures at the end of each cell.
67         
68         When True, ensures that each cell starts with no active figures, but it
69         also means that one must keep track of references in order to edit or
70         redraw figures in subsequent cells. This mode is ideal for the notebook,
71         where residual plots from other cells might be surprising.
72         
73         When False, one must call figure() to create new figures. This means
74         that gcf() and getfigs() can reference figures created in other cells,
75         and the active figure can continue to be edited with pylab/pyplot
76         methods that reference the current active figure. This mode facilitates
77         iterative editing of figures, and behaves most consistently with
78         other matplotlib backends, but figure barriers between cells must
79         be explicit.
80         """)
81 
82     shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
83 
84 
85 #-----------------------------------------------------------------------------
86 # Functions
87 #-----------------------------------------------------------------------------
88 
89 def show(close=None):
90     """Show all figures as SVG/PNG payloads sent to the IPython clients.
91 
92     Parameters
93     ----------
94     close : bool, optional
95       If true, a ``plt.close('all')`` call is automatically issued after
96       sending all the figures. If this is set, the figures will entirely
97       removed from the internal list of figures.
98     """
99     if close is None:
100         close = InlineBackend.instance().close_figures
101     try:
102         for figure_manager in Gcf.get_all_fig_managers():
103             display(figure_manager.canvas.figure)
104     finally:
105         show._to_draw = []
106         if close:
107             matplotlib.pyplot.close('all')
108 
109 
110 
111 # This flag will be reset by draw_if_interactive when called
112 show._draw_called = False
113 # list of figures to draw when flush_figures is called
114 show._to_draw = []
115 
116 
117 def draw_if_interactive():
118     """
119     Is called after every pylab drawing command
120     """
121     # signal that the current active figure should be sent at the end of
122     # execution.  Also sets the _draw_called flag, signaling that there will be
123     # something to send.  At the end of the code execution, a separate call to
124     # flush_figures() will act upon these values
125 
126     fig = Gcf.get_active().canvas.figure
127 
128     # Hack: matplotlib FigureManager objects in interacive backends (at least
129     # in some of them) monkeypatch the figure object and add a .show() method
130     # to it.  This applies the same monkeypatch in order to support user code
131     # that might expect `.show()` to be part of the official API of figure
132     # objects.
133     # For further reference:
134     # https://github.com/ipython/ipython/issues/1612
135     # https://github.com/matplotlib/matplotlib/issues/835
136     
137     if not hasattr(fig, 'show'):
138         # Queue up `fig` for display
139         fig.show = lambda *a: display(fig)
140 
141     # If matplotlib was manually set to non-interactive mode, this function
142     # should be a no-op (otherwise we'll generate duplicate plots, since a user
143     # who set ioff() manually expects to make separate draw/show calls).
144     if not matplotlib.is_interactive():
145         return
146 
147     # ensure current figure will be drawn, and each subsequent call
148     # of draw_if_interactive() moves the active figure to ensure it is
149     # drawn last
150     try:
151         show._to_draw.remove(fig)
152     except ValueError:
153         # ensure it only appears in the draw list once
154         pass
155     # Queue up the figure for drawing in next show() call
156     show._to_draw.append(fig)
157     show._draw_called = True
158 
159 
160 def flush_figures():
161     """Send all figures that changed
162 
163     This is meant to be called automatically and will call show() if, during
164     prior code execution, there had been any calls to draw_if_interactive.
165     
166     This function is meant to be used as a post_execute callback in IPython,
167     so user-caused errors are handled with showtraceback() instead of being
168     allowed to raise.  If this function is not called from within IPython,
169     then these exceptions will raise.
170     """
171     if not show._draw_called:
172         return
173     
174     if InlineBackend.instance().close_figures:
175         # ignore the tracking, just draw and close all figures
176         try:
177             return show(True)
178         except Exception as e:
179             # safely show traceback if in IPython, else raise
180             try:
181                 get_ipython
182             except NameError:
183                 raise e
184             else:
185                 get_ipython().showtraceback()
186                 return
187     try:
188         # exclude any figures that were closed:
189         active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
190         for fig in [ fig for fig in show._to_draw if fig in active ]:
191             try:
192                 display(fig)
193             except Exception as e:
194                 # safely show traceback if in IPython, else raise
195                 try:
196                     get_ipython
197                 except NameError:
198                     raise e
199                 else:
200                     get_ipython().showtraceback()
201                     break
202     finally:
203         # clear flags for next round
204         show._to_draw = []
205         show._draw_called = False
206 
207 
208 # Changes to matplotlib in version 1.2 requires a mpl backend to supply a default
209 # figurecanvas. This is set here to a Agg canvas
210 # See https://github.com/matplotlib/matplotlib/pull/1125
211 FigureCanvas = FigureCanvasAgg
212 
213
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/IPython/kernel/zmq/pylab/backend_inline.py b/IPython/kernel/zmq/pylab/backend_inline.py
--- a/IPython/kernel/zmq/pylab/backend_inline.py
+++ b/IPython/kernel/zmq/pylab/backend_inline.py
@@ -122,8 +122,10 @@
     # execution.  Also sets the _draw_called flag, signaling that there will be
     # something to send.  At the end of the code execution, a separate call to
     # flush_figures() will act upon these values
-
-    fig = Gcf.get_active().canvas.figure
+    manager = Gcf.get_active()
+    if manager is None:
+        return
+    fig = manager.canvas.figure
 
     # Hack: matplotlib FigureManager objects in interacive backends (at least
     # in some of them) monkeypatch the figure object and add a .show() method

{"golden_diff": "diff --git a/IPython/kernel/zmq/pylab/backend_inline.py b/IPython/kernel/zmq/pylab/backend_inline.py\n--- a/IPython/kernel/zmq/pylab/backend_inline.py\n+++ b/IPython/kernel/zmq/pylab/backend_inline.py\n@@ -122,8 +122,10 @@\n     # execution.  Also sets the _draw_called flag, signaling that there will be\n     # something to send.  At the end of the code execution, a separate call to\n     # flush_figures() will act upon these values\n-\n-    fig = Gcf.get_active().canvas.figure\n+    manager = Gcf.get_active()\n+    if manager is None:\n+        return\n+    fig = manager.canvas.figure\n \n     # Hack: matplotlib FigureManager objects in interacive backends (at least\n     # in some of them) monkeypatch the figure object and add a .show() method\n", "issue": "setp() issue in ipython notebook with figure references\nIn IPython notebook, when I run `setp()` to change parameters of a figure created in another cell and accessed with its reference, an exception occurs\n\n``` python\n---------------------------------------------------------------------------\nAttributeError                            Traceback (most recent call last)\n<ipython-input-82-54a641ac28e1> in <module>()\n----> 1 setp(axis.lines[0], linewidth=2)\n\n/home/amir/virtualenv/cr/local/lib/python2.7/site-packages/matplotlib/pyplot.pyc in setp(*args, **kwargs)\n    238 def setp(*args, **kwargs):\n    239     ret = _setp(*args, **kwargs)\n--> 240     draw_if_interactive()\n    241     return ret\n    242 \n\n/home/amir/virtualenv/cr/local/lib/python2.7/site-packages/IPython/zmq/pylab/backend_inline.py in draw_if_interactive()\n    123     # flush_figures() will act upon these values\n    124 \n--> 125     fig = Gcf.get_active().canvas.figure\n    126 \n    127     # Hack: matplotlib FigureManager objects in interacive backends (at least\n\nAttributeError: 'NoneType' object has no attribute 'canvas'\n```\n\nNevertheless, `setp()` successfully does its job but since IPython notebook by default closes the figures of previous cells the exception occurs.\n\n", "before_files": [{"content": "\"\"\"Produce SVG versions of active plots for display by the rich Qt frontend.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import print_function\n\n# Third-party imports\nimport matplotlib\nfrom matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg\nfrom matplotlib._pylab_helpers import Gcf\n\n# Local imports.\nfrom IPython.config.configurable import SingletonConfigurable\nfrom IPython.core.display import display\nfrom IPython.core.displaypub import publish_display_data\nfrom IPython.core.pylabtools import print_figure, select_figure_format\nfrom IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, Bool\nfrom IPython.utils.warn import warn\n\n#-----------------------------------------------------------------------------\n# Configurable for inline backend options\n#-----------------------------------------------------------------------------\n# inherit from InlineBackendConfig for deprecation purposes\nclass InlineBackendConfig(SingletonConfigurable):\n    pass\n\nclass InlineBackend(InlineBackendConfig):\n    \"\"\"An object to store configuration of the inline backend.\"\"\"\n\n    def _config_changed(self, name, old, new):\n        # warn on change of renamed config section\n        if new.InlineBackendConfig != old.InlineBackendConfig:\n            warn(\"InlineBackendConfig has been renamed to InlineBackend\")\n        super(InlineBackend, self)._config_changed(name, old, new)\n\n    # The typical default figure size is too large for inline use,\n    # so we shrink the figure size to 6x4, and tweak fonts to\n    # make that fit.\n    rc = Dict({'figure.figsize': (6.0,4.0),\n        # play nicely with white background in the Qt and notebook frontend\n        'figure.facecolor': 'white',\n        'figure.edgecolor': 'white',\n        # 12pt labels get cutoff on 6x4 logplots, so use 10pt.\n        'font.size': 10,\n        # 72 dpi matches SVG/qtconsole\n        # this only affects PNG export, as SVG has no dpi setting\n        'savefig.dpi': 72,\n        # 10pt still needs a little more room on the xlabel:\n        'figure.subplot.bottom' : .125\n        }, config=True,\n        help=\"\"\"Subset of matplotlib rcParams that should be different for the\n        inline backend.\"\"\"\n    )\n\n    figure_format = CaselessStrEnum(['svg', 'png', 'retina'], default_value='png', config=True,\n        help=\"The image format for figures with the inline backend.\")\n\n    def _figure_format_changed(self, name, old, new):\n        if self.shell is None:\n            return\n        else:\n            select_figure_format(self.shell, new)\n    \n    close_figures = Bool(True, config=True,\n        help=\"\"\"Close all figures at the end of each cell.\n        \n        When True, ensures that each cell starts with no active figures, but it\n        also means that one must keep track of references in order to edit or\n        redraw figures in subsequent cells. This mode is ideal for the notebook,\n        where residual plots from other cells might be surprising.\n        \n        When False, one must call figure() to create new figures. This means\n        that gcf() and getfigs() can reference figures created in other cells,\n        and the active figure can continue to be edited with pylab/pyplot\n        methods that reference the current active figure. This mode facilitates\n        iterative editing of figures, and behaves most consistently with\n        other matplotlib backends, but figure barriers between cells must\n        be explicit.\n        \"\"\")\n\n    shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')\n\n\n#-----------------------------------------------------------------------------\n# Functions\n#-----------------------------------------------------------------------------\n\ndef show(close=None):\n    \"\"\"Show all figures as SVG/PNG payloads sent to the IPython clients.\n\n    Parameters\n    ----------\n    close : bool, optional\n      If true, a ``plt.close('all')`` call is automatically issued after\n      sending all the figures. If this is set, the figures will entirely\n      removed from the internal list of figures.\n    \"\"\"\n    if close is None:\n        close = InlineBackend.instance().close_figures\n    try:\n        for figure_manager in Gcf.get_all_fig_managers():\n            display(figure_manager.canvas.figure)\n    finally:\n        show._to_draw = []\n        if close:\n            matplotlib.pyplot.close('all')\n\n\n\n# This flag will be reset by draw_if_interactive when called\nshow._draw_called = False\n# list of figures to draw when flush_figures is called\nshow._to_draw = []\n\n\ndef draw_if_interactive():\n    \"\"\"\n    Is called after every pylab drawing command\n    \"\"\"\n    # signal that the current active figure should be sent at the end of\n    # execution.  Also sets the _draw_called flag, signaling that there will be\n    # something to send.  At the end of the code execution, a separate call to\n    # flush_figures() will act upon these values\n\n    fig = Gcf.get_active().canvas.figure\n\n    # Hack: matplotlib FigureManager objects in interacive backends (at least\n    # in some of them) monkeypatch the figure object and add a .show() method\n    # to it.  This applies the same monkeypatch in order to support user code\n    # that might expect `.show()` to be part of the official API of figure\n    # objects.\n    # For further reference:\n    # https://github.com/ipython/ipython/issues/1612\n    # https://github.com/matplotlib/matplotlib/issues/835\n    \n    if not hasattr(fig, 'show'):\n        # Queue up `fig` for display\n        fig.show = lambda *a: display(fig)\n\n    # If matplotlib was manually set to non-interactive mode, this function\n    # should be a no-op (otherwise we'll generate duplicate plots, since a user\n    # who set ioff() manually expects to make separate draw/show calls).\n    if not matplotlib.is_interactive():\n        return\n\n    # ensure current figure will be drawn, and each subsequent call\n    # of draw_if_interactive() moves the active figure to ensure it is\n    # drawn last\n    try:\n        show._to_draw.remove(fig)\n    except ValueError:\n        # ensure it only appears in the draw list once\n        pass\n    # Queue up the figure for drawing in next show() call\n    show._to_draw.append(fig)\n    show._draw_called = True\n\n\ndef flush_figures():\n    \"\"\"Send all figures that changed\n\n    This is meant to be called automatically and will call show() if, during\n    prior code execution, there had been any calls to draw_if_interactive.\n    \n    This function is meant to be used as a post_execute callback in IPython,\n    so user-caused errors are handled with showtraceback() instead of being\n    allowed to raise.  If this function is not called from within IPython,\n    then these exceptions will raise.\n    \"\"\"\n    if not show._draw_called:\n        return\n    \n    if InlineBackend.instance().close_figures:\n        # ignore the tracking, just draw and close all figures\n        try:\n            return show(True)\n        except Exception as e:\n            # safely show traceback if in IPython, else raise\n            try:\n                get_ipython\n            except NameError:\n                raise e\n            else:\n                get_ipython().showtraceback()\n                return\n    try:\n        # exclude any figures that were closed:\n        active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])\n        for fig in [ fig for fig in show._to_draw if fig in active ]:\n            try:\n                display(fig)\n            except Exception as e:\n                # safely show traceback if in IPython, else raise\n                try:\n                    get_ipython\n                except NameError:\n                    raise e\n                else:\n                    get_ipython().showtraceback()\n                    break\n    finally:\n        # clear flags for next round\n        show._to_draw = []\n        show._draw_called = False\n\n\n# Changes to matplotlib in version 1.2 requires a mpl backend to supply a default\n# figurecanvas. This is set here to a Agg canvas\n# See https://github.com/matplotlib/matplotlib/pull/1125\nFigureCanvas = FigureCanvasAgg\n\n", "path": "IPython/kernel/zmq/pylab/backend_inline.py"}], "after_files": [{"content": "\"\"\"Produce SVG versions of active plots for display by the rich Qt frontend.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import print_function\n\n# Third-party imports\nimport matplotlib\nfrom matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg\nfrom matplotlib._pylab_helpers import Gcf\n\n# Local imports.\nfrom IPython.config.configurable import SingletonConfigurable\nfrom IPython.core.display import display\nfrom IPython.core.displaypub import publish_display_data\nfrom IPython.core.pylabtools import print_figure, select_figure_format\nfrom IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, Bool\nfrom IPython.utils.warn import warn\n\n#-----------------------------------------------------------------------------\n# Configurable for inline backend options\n#-----------------------------------------------------------------------------\n# inherit from InlineBackendConfig for deprecation purposes\nclass InlineBackendConfig(SingletonConfigurable):\n    pass\n\nclass InlineBackend(InlineBackendConfig):\n    \"\"\"An object to store configuration of the inline backend.\"\"\"\n\n    def _config_changed(self, name, old, new):\n        # warn on change of renamed config section\n        if new.InlineBackendConfig != old.InlineBackendConfig:\n            warn(\"InlineBackendConfig has been renamed to InlineBackend\")\n        super(InlineBackend, self)._config_changed(name, old, new)\n\n    # The typical default figure size is too large for inline use,\n    # so we shrink the figure size to 6x4, and tweak fonts to\n    # make that fit.\n    rc = Dict({'figure.figsize': (6.0,4.0),\n        # play nicely with white background in the Qt and notebook frontend\n        'figure.facecolor': 'white',\n        'figure.edgecolor': 'white',\n        # 12pt labels get cutoff on 6x4 logplots, so use 10pt.\n        'font.size': 10,\n        # 72 dpi matches SVG/qtconsole\n        # this only affects PNG export, as SVG has no dpi setting\n        'savefig.dpi': 72,\n        # 10pt still needs a little more room on the xlabel:\n        'figure.subplot.bottom' : .125\n        }, config=True,\n        help=\"\"\"Subset of matplotlib rcParams that should be different for the\n        inline backend.\"\"\"\n    )\n\n    figure_format = CaselessStrEnum(['svg', 'png', 'retina'], default_value='png', config=True,\n        help=\"The image format for figures with the inline backend.\")\n\n    def _figure_format_changed(self, name, old, new):\n        if self.shell is None:\n            return\n        else:\n            select_figure_format(self.shell, new)\n    \n    close_figures = Bool(True, config=True,\n        help=\"\"\"Close all figures at the end of each cell.\n        \n        When True, ensures that each cell starts with no active figures, but it\n        also means that one must keep track of references in order to edit or\n        redraw figures in subsequent cells. This mode is ideal for the notebook,\n        where residual plots from other cells might be surprising.\n        \n        When False, one must call figure() to create new figures. This means\n        that gcf() and getfigs() can reference figures created in other cells,\n        and the active figure can continue to be edited with pylab/pyplot\n        methods that reference the current active figure. This mode facilitates\n        iterative editing of figures, and behaves most consistently with\n        other matplotlib backends, but figure barriers between cells must\n        be explicit.\n        \"\"\")\n\n    shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')\n\n\n#-----------------------------------------------------------------------------\n# Functions\n#-----------------------------------------------------------------------------\n\ndef show(close=None):\n    \"\"\"Show all figures as SVG/PNG payloads sent to the IPython clients.\n\n    Parameters\n    ----------\n    close : bool, optional\n      If true, a ``plt.close('all')`` call is automatically issued after\n      sending all the figures. If this is set, the figures will entirely\n      removed from the internal list of figures.\n    \"\"\"\n    if close is None:\n        close = InlineBackend.instance().close_figures\n    try:\n        for figure_manager in Gcf.get_all_fig_managers():\n            display(figure_manager.canvas.figure)\n    finally:\n        show._to_draw = []\n        if close:\n            matplotlib.pyplot.close('all')\n\n\n\n# This flag will be reset by draw_if_interactive when called\nshow._draw_called = False\n# list of figures to draw when flush_figures is called\nshow._to_draw = []\n\n\ndef draw_if_interactive():\n    \"\"\"\n    Is called after every pylab drawing command\n    \"\"\"\n    # signal that the current active figure should be sent at the end of\n    # execution.  Also sets the _draw_called flag, signaling that there will be\n    # something to send.  At the end of the code execution, a separate call to\n    # flush_figures() will act upon these values\n    manager = Gcf.get_active()\n    if manager is None:\n        return\n    fig = manager.canvas.figure\n\n    # Hack: matplotlib FigureManager objects in interacive backends (at least\n    # in some of them) monkeypatch the figure object and add a .show() method\n    # to it.  This applies the same monkeypatch in order to support user code\n    # that might expect `.show()` to be part of the official API of figure\n    # objects.\n    # For further reference:\n    # https://github.com/ipython/ipython/issues/1612\n    # https://github.com/matplotlib/matplotlib/issues/835\n    \n    if not hasattr(fig, 'show'):\n        # Queue up `fig` for display\n        fig.show = lambda *a: display(fig)\n\n    # If matplotlib was manually set to non-interactive mode, this function\n    # should be a no-op (otherwise we'll generate duplicate plots, since a user\n    # who set ioff() manually expects to make separate draw/show calls).\n    if not matplotlib.is_interactive():\n        return\n\n    # ensure current figure will be drawn, and each subsequent call\n    # of draw_if_interactive() moves the active figure to ensure it is\n    # drawn last\n    try:\n        show._to_draw.remove(fig)\n    except ValueError:\n        # ensure it only appears in the draw list once\n        pass\n    # Queue up the figure for drawing in next show() call\n    show._to_draw.append(fig)\n    show._draw_called = True\n\n\ndef flush_figures():\n    \"\"\"Send all figures that changed\n\n    This is meant to be called automatically and will call show() if, during\n    prior code execution, there had been any calls to draw_if_interactive.\n    \n    This function is meant to be used as a post_execute callback in IPython,\n    so user-caused errors are handled with showtraceback() instead of being\n    allowed to raise.  If this function is not called from within IPython,\n    then these exceptions will raise.\n    \"\"\"\n    if not show._draw_called:\n        return\n    \n    if InlineBackend.instance().close_figures:\n        # ignore the tracking, just draw and close all figures\n        try:\n            return show(True)\n        except Exception as e:\n            # safely show traceback if in IPython, else raise\n            try:\n                get_ipython\n            except NameError:\n                raise e\n            else:\n                get_ipython().showtraceback()\n                return\n    try:\n        # exclude any figures that were closed:\n        active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])\n        for fig in [ fig for fig in show._to_draw if fig in active ]:\n            try:\n                display(fig)\n            except Exception as e:\n                # safely show traceback if in IPython, else raise\n                try:\n                    get_ipython\n                except NameError:\n                    raise e\n                else:\n                    get_ipython().showtraceback()\n                    break\n    finally:\n        # clear flags for next round\n        show._to_draw = []\n        show._draw_called = False\n\n\n# Changes to matplotlib in version 1.2 requires a mpl backend to supply a default\n# figurecanvas. This is set here to a Agg canvas\n# See https://github.com/matplotlib/matplotlib/pull/1125\nFigureCanvas = FigureCanvasAgg\n\n", "path": "IPython/kernel/zmq/pylab/backend_inline.py"}]}