lines = []<EOL>enc = None<EOL>for line in code.splitlines():<EOL><INDENT>coding_match = coding_declaration.match(line)<EOL>if coding_match:<EOL><INDENT>enc = coding_match.group(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>lines.append(line)<EOL><DEDENT><DEDENT>code = "<STR_LIT:\n>".join(lines)<EOL>if isinstance(code, bytes):<EOL><INDENT>code = code.decode(enc or DEFAULT_ENCODING)<EOL><DEDENT>self.value = code + '<STR_LIT:\n>'<EOL>

store the macro value, as a single string which can be executed


return {'<STR_LIT:value>': self.value}<EOL>


@magic_arguments()<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def magic_foo1(self, args):

return parse_argstring(magic_foo1, args)<EOL>


return parse_argstring(magic_foo2, args)<EOL>


@magic_arguments()<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>@argument_group('<STR_LIT>')<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>@argument_group('<STR_LIT>')<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def magic_foo3(self, args):

return parse_argstring(magic_foo3, args)<EOL>


@magic_arguments()<EOL>@kwds(argument_default=argparse.SUPPRESS)<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def magic_foo4(self, args):

return parse_argstring(magic_foo4, args)<EOL>


@magic_arguments('<STR_LIT>')<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def magic_foo5(self, args):

return parse_argstring(magic_foo5, args)<EOL>


@magic_arguments()<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def magic_magic_foo(self, args):

return parse_argstring(magic_magic_foo, args)<EOL>


@magic_arguments()<EOL>@argument('<STR_LIT>', '<STR_LIT>', help="<STR_LIT>")<EOL>def foo(self, args):

return parse_argstring(foo, args)<EOL>


from IPython.core.inputsplitter import InputSplitter<EOL>isp = InputSplitter()<EOL>while isp.push_accepts_more():<EOL><INDENT>indent = '<STR_LIT:U+0020>'*isp.indent_spaces<EOL>prompt = '<STR_LIT>' + indent<EOL>line = indent + input_func(prompt)<EOL>isp.push(line)<EOL><DEDENT>src = isp.source_reset()<EOL>return src<EOL>

Minimal example of the logic of an interactive interpreter loop.

    This serves as an example, and it is used by the test system with a fake
    raw_input that simulates interactive input.


return ['<STR_LIT:\n>'.join(sub_block)+'<STR_LIT:\n>' for sub_block in block]<EOL>

Assemble a block into multi-line sub-blocks.


ilines = iter(lines)<EOL>def raw_in(prompt):<EOL><INDENT>try:<EOL><INDENT>return next(ilines)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>return raw_in<EOL>

Return a function that acts like raw_input but feeds the input list.


src = mini_interactive_loop(pseudo_input(lines))<EOL>test_ns = {}<EOL>exec(src, test_ns)<EOL>for k,v in ns.items():<EOL><INDENT>self.assertEqual(test_ns[k], v)<EOL><DEDENT>

Validate that the given input lines produce the resulting namespace.

        Note: the input lines are given exactly as they would be typed in an
        auto-indenting environment, as mini_interactive_loop above already does
        auto-indenting and prepends spaces to the input.


ip.user_ns['<STR_LIT>'] = False<EOL>src = StringIO()<EOL>if not hasattr(src, '<STR_LIT>'):<EOL><INDENT>src.encoding = None<EOL><DEDENT>src.write(code)<EOL>src.write('<STR_LIT>')<EOL>src.seek(<NUM_LIT:0>)<EOL>stdin_save = sys.stdin<EOL>sys.stdin = src<EOL>try:<EOL><INDENT>context = tt.AssertPrints if should_fail else tt.AssertNotPrints<EOL>with context("<STR_LIT>"):<EOL><INDENT>ip.magic('<STR_LIT>')<EOL><DEDENT>if not should_fail:<EOL><INDENT>assert ip.user_ns['<STR_LIT>']<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>sys.stdin = stdin_save<EOL><DEDENT>

Execute code via 'cpaste' and ensure it was executed, unless
    should_fail is set.


def paste(self, txt, flags='<STR_LIT>'):

ip.hooks.clipboard_get = lambda : txt<EOL>ip.magic('<STR_LIT>'+flags)<EOL>

Paste input text, by default in quiet mode


pass<EOL>


@cell_magic("<STR_LIT:foo>")<EOL><INDENT>def cell_foo(self, line, cell):<DEDENT>

pass<EOL>


x = <NUM_LIT:1><EOL>y = <NUM_LIT:0><EOL>x/y<EOL>


if mode=='<STR_LIT>':<EOL><INDENT>div0()<EOL><DEDENT>elif mode=='<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>stat = int(sys.argv[<NUM_LIT:2>])<EOL><DEDENT>except:<EOL><INDENT>stat = <NUM_LIT:1><EOL><DEDENT>sysexit(stat, mode)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>


def check_calltip(obj, name, call, docstring):

info = inspector.info(obj, name)<EOL>call_line, ds = oinspect.call_tip(info)<EOL>nt.assert_equal(call_line, call)<EOL>nt.assert_equal(ds, docstring)<EOL>

Generic check pattern all calltip tests will use


@cell_magic<EOL><INDENT>def Ccmagic(self, cline, ccell):<DEDENT>


@line_cell_magic<EOL><INDENT>def Clcmagic(self, cline, ccell=None):<DEDENT>


Setup test environment for the module:

            - Adds dummy home dir tree


Teardown test environment for the module:

            - Remove dummy home dir tree


from IPython.config.loader import Config<EOL>configurables = [ c for c in self.shell.configurables<EOL>if c.__class__.class_traits(config=True) ]<EOL>classnames = [ c.__class__.__name__ for c in configurables ]<EOL>line = s.strip()<EOL>if not line:<EOL><INDENT>print("<STR_LIT>")<EOL>for name in classnames:<EOL><INDENT>print("<STR_LIT:U+0020>", name)<EOL><DEDENT>return<EOL><DEDENT>elif line in classnames:<EOL><INDENT>c = configurables[classnames.index(line)]<EOL>cls = c.__class__<EOL>help = cls.class_get_help(c)<EOL>help = re.sub(re.compile(r'<STR_LIT>', re.MULTILINE), '<STR_LIT>', help)<EOL>print(help)<EOL>return<EOL><DEDENT>elif '<STR_LIT:=>' not in line:<EOL><INDENT>raise UsageError("<STR_LIT>"<EOL>"<STR_LIT>" % line)<EOL><DEDENT>cfg = Config()<EOL>exec("<STR_LIT>"+line, locals(), self.shell.user_ns)<EOL>for configurable in configurables:<EOL><INDENT>try:<EOL><INDENT>configurable.update_config(cfg)<EOL><DEDENT>except Exception as e:<EOL><INDENT>error(e)<EOL><DEDENT><DEDENT>

configure IPython

            %config Class[.trait=value]

        This magic exposes most of the IPython config system. Any
        Configurable class should be able to be configured with the simple
        line::

            %config Class.trait=value

        Where `value` will be resolved in the user's namespace, if it is an
        expression or variable name.

        Examples
        --------

        To see what classes are available for config, pass no arguments::

            In [1]: %config
            Available objects for config:
                TerminalInteractiveShell
                HistoryManager
                PrefilterManager
                AliasManager
                IPCompleter
                PromptManager
                DisplayFormatter

        To view what is configurable on a given class, just pass the class
        name::

            In [2]: %config IPCompleter
            IPCompleter options
            -----------------
            IPCompleter.omit__names=<Enum>
                Current: 2
                Choices: (0, 1, 2)
                Instruct the completer to omit private method names
                Specifically, when completing on ``object.<tab>``.
                When 2 [default]: all names that start with '_' will be excluded.
                When 1: all 'magic' names (``__foo__``) will be excluded.
                When 0: nothing will be excluded.
            IPCompleter.merge_completions=<CBool>
                Current: True
                Whether to merge completion results into a single list
                If False, only the completion results from the first non-empty
                completer will be returned.
            IPCompleter.limit_to__all__=<CBool>
                Current: False
                Instruct the completer to use __all__ for the completion
                Specifically, when completing on ``object.<tab>``.
                When True: only those names in obj.__all__ will be included.
                When False [default]: the __all__ attribute is ignored
            IPCompleter.greedy=<CBool>
                Current: False
                Activate greedy completion
                This will enable completion on elements of lists, results of
                function calls, etc., but can be unsafe because the code is
                actually evaluated on TAB.

        but the real use is in setting values::

            In [3]: %config IPCompleter.greedy = True

        and these values are read from the user_ns if they are variables::

            In [4]: feeling_greedy=False

            In [5]: %config IPCompleter.greedy = feeling_greedy


opts,par = self.parse_options(parameter_s,'<STR_LIT>')<EOL>log_output = '<STR_LIT:o>' in opts<EOL>log_raw_input = '<STR_LIT:r>' in opts<EOL>timestamp = '<STR_LIT:t>' in opts<EOL>logger = self.shell.logger<EOL>if par:<EOL><INDENT>try:<EOL><INDENT>logfname,logmode = par.split()<EOL><DEDENT>except:<EOL><INDENT>logfname = par<EOL>logmode = '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logfname = logger.logfname<EOL>logmode = logger.logmode<EOL><DEDENT>old_logfile = self.shell.logfile<EOL>if logfname:<EOL><INDENT>logfname = os.path.expanduser(logfname)<EOL><DEDENT>self.shell.logfile = logfname<EOL>loghead = u'<STR_LIT>'<EOL>try:<EOL><INDENT>logger.logstart(logfname, loghead, logmode, log_output, timestamp,<EOL>log_raw_input)<EOL><DEDENT>except:<EOL><INDENT>self.shell.logfile = old_logfile<EOL>warn("<STR_LIT>" % sys.exc_info()[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>if timestamp:<EOL><INDENT>logger.timestamp = False<EOL><DEDENT>if log_raw_input:<EOL><INDENT>input_hist = self.shell.history_manager.input_hist_raw<EOL><DEDENT>else:<EOL><INDENT>input_hist = self.shell.history_manager.input_hist_parsed<EOL><DEDENT>if log_output:<EOL><INDENT>log_write = logger.log_write<EOL>output_hist = self.shell.history_manager.output_hist<EOL>for n in range(<NUM_LIT:1>,len(input_hist)-<NUM_LIT:1>):<EOL><INDENT>log_write(input_hist[n].rstrip() + u'<STR_LIT:\n>')<EOL>if n in output_hist:<EOL><INDENT>log_write(str_to_unicode(repr(output_hist[n])),'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>logger.log_write(u'<STR_LIT:\n>'.join(input_hist[<NUM_LIT:1>:]))<EOL>logger.log_write(u'<STR_LIT:\n>')<EOL><DEDENT>if timestamp:<EOL><INDENT>logger.timestamp = True<EOL><DEDENT>print ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>logger.logstate()<EOL><DEDENT>

Start logging anywhere in a session.

        %logstart [-o|-r|-t] [log_name [log_mode]]

        If no name is given, it defaults to a file named 'ipython_log.py' in your
        current directory, in 'rotate' mode (see below).

        '%logstart name' saves to file 'name' in 'backup' mode.  It saves your
        history up to that point and then continues logging.

        %logstart takes a second optional parameter: logging mode. This can be one
        of (note that the modes are given unquoted):\\
          append: well, that says it.\\
          backup: rename (if exists) to name~ and start name.\\
          global: single logfile in your home dir, appended to.\\
          over  : overwrite existing log.\\
          rotate: create rotating logs name.1~, name.2~, etc.

        Options:

          -o: log also IPython's output.  In this mode, all commands which
          generate an Out[NN] prompt are recorded to the logfile, right after
          their corresponding input line.  The output lines are always
          prepended with a '#[Out]# ' marker, so that the log remains valid
          Python code.

          Since this marker is always the same, filtering only the output from
          a log is very easy, using for example a simple awk call::

            awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py

          -r: log 'raw' input.  Normally, IPython's logs contain the processed
          input, so that user lines are logged in their final form, converted
          into valid Python.  For example, %Exit is logged as
          _ip.magic("Exit").  If the -r flag is given, all input is logged
          exactly as typed, with no transformations applied.

          -t: put timestamps before each input line logged (these are put in
          comments).


self.shell.logger.logstop()<EOL>

Fully stop logging and close log file.

        In order to start logging again, a new %logstart call needs to be made,
        possibly (though not necessarily) with a new filename, mode and other
        options.


self.shell.logger.switch_log(<NUM_LIT:0>)<EOL>

Temporarily stop logging.

        You must have previously started logging.


self.shell.logger.switch_log(<NUM_LIT:1>)<EOL>

Restart logging.

        This function is for restarting logging which you've temporarily
        stopped with %logoff. For starting logging for the first time, you
        must use the %logstart function, which allows you to specify an
        optional log filename.


self.shell.logger.logstate()<EOL>


args = [<EOL>magic_arguments.argument(<EOL>'<STR_LIT>', type=str,<EOL>help="""<STR_LIT>"""<EOL>),<EOL>magic_arguments.argument(<EOL>'<STR_LIT>', type=str,<EOL>help="""<STR_LIT>"""<EOL>),<EOL>magic_arguments.argument(<EOL>'<STR_LIT>', action="<STR_LIT:store_true>",<EOL>help="""<STR_LIT>"""<EOL>),<EOL>magic_arguments.argument(<EOL>'<STR_LIT>', type=str,<EOL>help="""<STR_LIT>"""<EOL>),<EOL>]<EOL>for arg in args:<EOL><INDENT>f = arg(f)<EOL><DEDENT>return f<EOL>


defaults = []<EOL>to_try = []<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>defaults.append('<STR_LIT>')<EOL>to_try.append('<STR_LIT>')<EOL><DEDENT>to_try.extend([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>])<EOL>for cmd in to_try:<EOL><INDENT>if cmd in self.script_paths:<EOL><INDENT>defaults.append(cmd)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>find_cmd(cmd)<EOL><DEDENT>except FindCmdError:<EOL><INDENT>pass<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>defaults.append(cmd)<EOL><DEDENT><DEDENT><DEDENT>return defaults<EOL>

default to a common list of programs if we find them


<EOL>script = self.script_paths.get(name, name)<EOL>@magic_arguments.magic_arguments()<EOL>@script_args<EOL>def named_script_magic(line, cell):<EOL><INDENT>if line:<EOL><INDENT>line = "<STR_LIT>" % (script, line)<EOL><DEDENT>else:<EOL><INDENT>line = script<EOL><DEDENT>return self.shebang(line, cell)<EOL><DEDENT>named_script_magic.__doc__ ="""<STR_LIT>""".format(**locals())<EOL>return named_script_magic<EOL>

make a named magic, that calls %%script with a particular program


argv = arg_split(line, posix = not sys.platform.startswith('<STR_LIT>'))<EOL>args, cmd = self.shebang.parser.parse_known_args(argv)<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)<EOL>cell = cell.encode('<STR_LIT:utf8>', '<STR_LIT:replace>')<EOL>if args.bg:<EOL><INDENT>self.bg_processes.append(p)<EOL>self._gc_bg_processes()<EOL>if args.out:<EOL><INDENT>self.shell.user_ns[args.out] = p.stdout<EOL><DEDENT>if args.err:<EOL><INDENT>self.shell.user_ns[args.err] = p.stderr<EOL><DEDENT>self.job_manager.new(self._run_script, p, cell, daemon=True)<EOL>if args.proc:<EOL><INDENT>self.shell.user_ns[args.proc] = p<EOL><DEDENT>return<EOL><DEDENT>try:<EOL><INDENT>out, err = p.communicate(cell)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>try:<EOL><INDENT>p.send_signal(signal.SIGINT)<EOL>time.sleep(<NUM_LIT:0.1>)<EOL>if p.poll() is not None:<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>p.terminate()<EOL>time.sleep(<NUM_LIT:0.1>)<EOL>if p.poll() is not None:<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>p.kill()<EOL>print("<STR_LIT>")<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>except Exception as e:<EOL><INDENT>print("<STR_LIT>"% (p.pid, e))<EOL><DEDENT>return<EOL><DEDENT>out = py3compat.bytes_to_str(out)<EOL>err = py3compat.bytes_to_str(err)<EOL>if args.out:<EOL><INDENT>self.shell.user_ns[args.out] = out<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write(out)<EOL>sys.stdout.flush()<EOL><DEDENT>if args.err:<EOL><INDENT>self.shell.user_ns[args.err] = err<EOL><DEDENT>else:<EOL><INDENT>sys.stderr.write(err)<EOL>sys.stderr.flush()<EOL><DEDENT>

Run a cell via a shell command

        The `%%script` line is like the #! line of script,
        specifying a program (bash, perl, ruby, etc.) with which to run.

        The rest of the cell is run by that program.

        Examples
        --------
        ::

            In [1]: %%script bash
               ...: for i in 1 2 3; do
               ...:   echo $i
               ...: done
            1
            2
            3


p.stdin.write(cell)<EOL>p.stdin.close()<EOL>p.wait()<EOL>

callback for running the script in the background


self.kill_bg_processes()<EOL>print("<STR_LIT>")<EOL>

Kill all BG processes started by %%script and its family.


for p in self.bg_processes:<EOL><INDENT>if p.poll() is None:<EOL><INDENT>try:<EOL><INDENT>p.send_signal(signal.SIGINT)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>time.sleep(<NUM_LIT:0.1>)<EOL>for p in self.bg_processes:<EOL><INDENT>if p.poll() is None:<EOL><INDENT>try:<EOL><INDENT>p.terminate()<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>time.sleep(<NUM_LIT:0.1>)<EOL>for p in self.bg_processes:<EOL><INDENT>if p.poll() is None:<EOL><INDENT>try:<EOL><INDENT>p.kill()<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>self._gc_bg_processes()<EOL>

Kill all BG processes which are still running.


args = magic_arguments.parse_argstring(self.alias_magic, line)<EOL>shell = self.shell<EOL>escs = '<STR_LIT>'.join(magic_escapes.values())<EOL>target = args.target.lstrip(escs)<EOL>name = args.name.lstrip(escs)<EOL>m_line = shell.find_magic(target, '<STR_LIT>')<EOL>m_cell = shell.find_magic(target, '<STR_LIT>')<EOL>if args.line and m_line is None:<EOL><INDENT>raise UsageError('<STR_LIT>' %<EOL>(magic_escapes['<STR_LIT>'], target))<EOL><DEDENT>if args.cell and m_cell is None:<EOL><INDENT>raise UsageError('<STR_LIT>' %<EOL>(magic_escapes['<STR_LIT>'], target))<EOL><DEDENT>if not args.line and not args.cell:<EOL><INDENT>if not m_line and not m_cell:<EOL><INDENT>raise UsageError(<EOL>'<STR_LIT>' % target<EOL>)<EOL><DEDENT>args.line = bool(m_line)<EOL>args.cell = bool(m_cell)<EOL><DEDENT>if args.line:<EOL><INDENT>def wrapper(line): return m_line(line)<EOL>wrapper.__name__ = str(name)<EOL>wrapper.__doc__ = "<STR_LIT>" %(magic_escapes['<STR_LIT>'], target)<EOL>shell.register_magic_function(wrapper, '<STR_LIT>', name)<EOL><DEDENT>if args.cell:<EOL><INDENT>def wrapper(line, cell): return m_cell(line, cell)<EOL>wrapper.__name__ = str(name)<EOL>wrapper.__doc__ = "<STR_LIT>" %(magic_escapes['<STR_LIT>'], target)<EOL>shell.register_magic_function(wrapper, '<STR_LIT>', name)<EOL><DEDENT>

Create an alias for an existing line or cell magic.

        Examples
        --------
        ::
          In [1]: %alias_magic t timeit

          In [2]: %t -n1 pass
          1 loops, best of 3: 954 ns per loop

          In [3]: %%t -n1
             ...: pass
             ...:
          1 loops, best of 3: 954 ns per loop

          In [4]: %alias_magic --cell whereami pwd
          UsageError: Cell magic function `%%pwd` not found.
          In [5]: %alias_magic --line whereami pwd

          In [6]: %whereami
          Out[6]: u'/home/testuser'


List currently available magic functions.


def _magic_docs(self, brief=False, rest=False):

mman = self.shell.magics_manager<EOL>docs = mman.lsmagic_docs(brief, missing='<STR_LIT>')<EOL>if rest:<EOL><INDENT>format_string = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>format_string = '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'.join(<EOL>[format_string % (magic_escapes['<STR_LIT>'], fname, fndoc)<EOL>for fname, fndoc in sorted(docs['<STR_LIT>'].items())]<EOL>+<EOL>[format_string % (magic_escapes['<STR_LIT>'], fname, fndoc)<EOL>for fname, fndoc in sorted(docs['<STR_LIT>'].items())]<EOL>)<EOL>


mode = '<STR_LIT>'<EOL>try:<EOL><INDENT>mode = parameter_s.split()[<NUM_LIT:0>][<NUM_LIT:1>:]<EOL>if mode == '<STR_LIT>':<EOL><INDENT>rest_docs = []<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>brief = (mode == '<STR_LIT>')<EOL>rest = (mode == '<STR_LIT>')<EOL>magic_docs = self._magic_docs(brief, rest)<EOL>if mode == '<STR_LIT>':<EOL><INDENT>print(self.format_latex(magic_docs))<EOL>return<EOL><DEDENT>else:<EOL><INDENT>magic_docs = format_screen(magic_docs)<EOL><DEDENT>out = ["""<STR_LIT>""",<EOL>agic_docs,<EOL>Summary of magic functions (from %slsmagic):",<EOL>elf._lsmagic(),<EOL>page.page('<STR_LIT:\n>'.join(out))<EOL>

Print information about the magic function system.

        Supported formats: -latex, -brief, -rest


<EOL>opts, args = self.parse_options(parameter_s, '<STR_LIT:r>')<EOL>raw = '<STR_LIT:r>' in opts<EOL>oname = args and args or '<STR_LIT:_>'<EOL>info = self.shell._ofind(oname)<EOL>if info['<STR_LIT>']:<EOL><INDENT>txt = (raw and str or pformat)( info['<STR_LIT>'] )<EOL>page.page(txt)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % oname)<EOL><DEDENT>

Pretty print the object and display it through a pager.

        %page [options] OBJECT

        If no object is given, use _ (last output).

        Options:

          -r: page str(object), don't pretty-print it.


from IPython.core.application import BaseIPythonApplication<EOL>if BaseIPythonApplication.initialized():<EOL><INDENT>print(BaseIPythonApplication.instance().profile)<EOL><DEDENT>else:<EOL><INDENT>error("<STR_LIT>")<EOL><DEDENT>

Print your currently active IPython profile.


ptformatter = self.shell.display_formatter.formatters['<STR_LIT>']<EOL>ptformatter.pprint = bool(<NUM_LIT:1> - ptformatter.pprint)<EOL>print('<STR_LIT>',<EOL>['<STR_LIT>','<STR_LIT>'][ptformatter.pprint])<EOL>


def color_switch_err(name):<EOL><INDENT>warn('<STR_LIT>' %<EOL>(name, sys.exc_info()[<NUM_LIT:1>]))<EOL><DEDENT>new_scheme = parameter_s.strip()<EOL>if not new_scheme:<EOL><INDENT>raise UsageError(<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>shell = self.shell<EOL>import IPython.utils.rlineimpl as readline<EOL>if not shell.colors_force andnot readline.have_readline and sys.platform == "<STR_LIT:win32>":<EOL><INDENT>msg = """<STR_LIT>"""<EOL>new_scheme = '<STR_LIT>'<EOL>warn(msg)<EOL><DEDENT>if not shell.colors_force and not shell.has_readline:<EOL><INDENT>new_scheme = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>shell.prompt_manager.color_scheme = new_scheme<EOL><DEDENT>except:<EOL><INDENT>color_switch_err('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>shell.colors =shell.prompt_manager.color_scheme_table.active_scheme_name<EOL><DEDENT>try:<EOL><INDENT>shell.InteractiveTB.set_colors(scheme = new_scheme)<EOL>shell.SyntaxTB.set_colors(scheme = new_scheme)<EOL><DEDENT>except:<EOL><INDENT>color_switch_err('<STR_LIT>')<EOL><DEDENT>if shell.color_info:<EOL><INDENT>try:<EOL><INDENT>shell.inspector.set_active_scheme(new_scheme)<EOL><DEDENT>except:<EOL><INDENT>color_switch_err('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>shell.inspector.set_active_scheme('<STR_LIT>')<EOL><DEDENT>

Switch color scheme for prompts, info system and exception handlers.

        Currently implemented schemes: NoColor, Linux, LightBG.

        Color scheme names are not case-sensitive.

        Examples
        --------
        To get a plain black and white terminal::

          %colors nocolor


Switch modes for the exception handlers.

        Valid modes: Plain, Context and Verbose.

        If called without arguments, acts as a toggle.


from IPython.core.usage import quick_reference<EOL>qr = quick_reference + self._magic_docs(brief=True)<EOL>page.page(qr)<EOL>


opts, arg = self.parse_options(parameter_s, '<STR_LIT>')<EOL>if arg=='<STR_LIT>': arg = None<EOL>try:<EOL><INDENT>return self.shell.enable_gui(arg)<EOL><DEDENT>except Exception as e:<EOL><INDENT>error(str(e))<EOL><DEDENT>

Enable or disable IPython GUI event loop integration.

        %gui [GUINAME]

        This magic replaces IPython's threaded shells that were activated
        using the (pylab/wthread/etc.) command line flags.  GUI toolkits
        can now be enabled at runtime and keyboard
        interrupts should work without any problems.  The following toolkits
        are supported:  wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::

            %gui wx      # enable wxPython event loop integration
            %gui qt4|qt  # enable PyQt4 event loop integration
            %gui gtk     # enable PyGTK event loop integration
            %gui gtk3    # enable Gtk3 event loop integration
            %gui tk      # enable Tk event loop integration
            %gui osx     # enable Cocoa event loop integration
                         # (requires %matplotlib 1.1)
            %gui         # disable all event loop integration

        WARNING:  after any of these has been called you can simply create
        an application object, but DO NOT start the event loop yourself, as
        we have already handled that.


args = magic_arguments.parse_argstring(self.notebook, s)<EOL>from IPython.nbformat import current<EOL>args.filename = unquote_filename(args.filename)<EOL>if args.export:<EOL><INDENT>fname, name, format = current.parse_filename(args.filename)<EOL>cells = []<EOL>hist = list(self.shell.history_manager.get_range())<EOL>for session, prompt_number, input in hist[:-<NUM_LIT:1>]:<EOL><INDENT>cells.append(current.new_code_cell(prompt_number=prompt_number,<EOL>input=input))<EOL><DEDENT>worksheet = current.new_worksheet(cells=cells)<EOL>nb = current.new_notebook(name=name,worksheets=[worksheet])<EOL>with io.open(fname, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>current.write(nb, f, format);<EOL><DEDENT><DEDENT>elif args.format is not None:<EOL><INDENT>old_fname, old_name, old_format = current.parse_filename(args.filename)<EOL>new_format = args.format<EOL>if new_format == u'<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>elif new_format == u'<STR_LIT>' or new_format == u'<STR_LIT>':<EOL><INDENT>new_fname = old_name + u'<STR_LIT>'<EOL>new_format = u'<STR_LIT>'<EOL><DEDENT>elif new_format == u'<STR_LIT>':<EOL><INDENT>new_fname = old_name + u'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % new_format)<EOL><DEDENT>with io.open(old_fname, '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>nb = current.read(f, old_format)<EOL><DEDENT>with io.open(new_fname, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>current.write(nb, f, new_format)<EOL><DEDENT><DEDENT>

Export and convert IPython notebooks.

        This function can export the current IPython history to a notebook file
        or can convert an existing notebook file into a different format. For
        example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
        To export the history to "foo.py" do "%notebook -e foo.py". To convert
        "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
        formats include (json/ipynb, py).


arg = parameter_s.lower()<EOL>mman = self.shell.magics_manager<EOL>if arg in ('<STR_LIT>', '<STR_LIT:1>', '<STR_LIT:true>'):<EOL><INDENT>val = True<EOL><DEDENT>elif arg in ('<STR_LIT>', '<STR_LIT:0>', '<STR_LIT:false>'):<EOL><INDENT>val = False<EOL><DEDENT>else:<EOL><INDENT>val = not mman.auto_magic<EOL><DEDENT>mman.auto_magic = val<EOL>print('<STR_LIT:\n>' + self.shell.magics_manager.auto_status())<EOL>

Make magic functions callable without having to type the initial %.

        Without argumentsl toggles on/off (when off, you must call it as
        %automagic, of course).  With arguments it sets the value, and you can
        use any of (case insensitive):

         - on, 1, True: to activate

         - off, 0, False: to deactivate.

        Note that magic functions have lowest priority, so if there's a
        variable whose name collides with that of a magic fn, automagic won't
        work for that function (you get the variable instead). However, if you
        delete the variable (del var), the previously shadowed magic function
        becomes visible to automagic again.


print('<STR_LIT:\n>'.join([<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]))<EOL>


print('<STR_LIT:\n>'.join([<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]))<EOL>

%install_default_config has been deprecated.


aname = parameter_s.strip()<EOL>self.shell.alias_manager.undefine_alias(aname)<EOL>stored = self.shell.db.get('<STR_LIT>', {} )<EOL>if aname in stored:<EOL><INDENT>print("<STR_LIT>",aname)<EOL>del stored[aname]<EOL>self.shell.db['<STR_LIT>'] = stored<EOL><DEDENT>


from IPython.core.alias import InvalidAliasError<EOL>del self.shell.db['<STR_LIT>']<EOL>path = [os.path.abspath(os.path.expanduser(p)) for p in<EOL>os.environ.get('<STR_LIT>','<STR_LIT>').split(os.pathsep)]<EOL>path = list(filter(os.path.isdir,path))<EOL>syscmdlist = []<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>isexec = lambda fname:os.path.isfile(fname) andos.access(fname,os.X_OK)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>winext = os.environ['<STR_LIT>'].replace('<STR_LIT:;>','<STR_LIT:|>').replace('<STR_LIT:.>','<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>winext = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in winext:<EOL><INDENT>winext += '<STR_LIT>'<EOL><DEDENT>execre = re.compile(r'<STR_LIT>' % winext,re.IGNORECASE)<EOL>isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)<EOL><DEDENT>savedir = os.getcwd()<EOL>try:<EOL><INDENT>if os.name == '<STR_LIT>':<EOL><INDENT>for pdir in path:<EOL><INDENT>os.chdir(pdir)<EOL>for ff in os.listdir(pdir):<EOL><INDENT>if isexec(ff):<EOL><INDENT>try:<EOL><INDENT>self.shell.alias_manager.define_alias(<EOL>ff.replace('<STR_LIT:.>','<STR_LIT>'), ff)<EOL><DEDENT>except InvalidAliasError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>syscmdlist.append(ff)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>no_alias = self.shell.alias_manager.no_alias<EOL>for pdir in path:<EOL><INDENT>os.chdir(pdir)<EOL>for ff in os.listdir(pdir):<EOL><INDENT>base, ext = os.path.splitext(ff)<EOL>if isexec(ff) and base.lower() not in no_alias:<EOL><INDENT>if ext.lower() == '<STR_LIT>':<EOL><INDENT>ff = base<EOL>try:<EOL><INDENT>self.shell.alias_manager.define_alias(<EOL>base.lower().replace('<STR_LIT:.>','<STR_LIT>'), ff)<EOL><DEDENT>except InvalidAliasError:<EOL><INDENT>pass<EOL><DEDENT>syscmdlist.append(ff)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>self.shell.db['<STR_LIT>'] = syscmdlist<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(savedir)<EOL><DEDENT>

Update the alias table with all executable files in $PATH.

        This version explicitly checks that every entry in $PATH is a file
        with execute access (os.X_OK), so it is much slower than %rehash.

        Under Windows, it checks executability as a match against a
        '|'-separated string of extensions, stored in the IPython config
        variable win_exec_ext.  This defaults to 'exe|com|bat'.

        This function also resets the root module cache of module completer,
        used on slow filesystems.


return dict(os.environ)<EOL>


dir_s = self.shell.dir_stack<EOL>tgt = os.path.expanduser(unquote_filename(parameter_s))<EOL>cwd = os.getcwd().replace(self.shell.home_dir,'<STR_LIT>')<EOL>if tgt:<EOL><INDENT>self.cd(parameter_s)<EOL><DEDENT>dir_s.insert(<NUM_LIT:0>,cwd)<EOL>return self.shell.magic('<STR_LIT>')<EOL>

Place the current dir on stack and change directory.

        Usage:\\
          %pushd ['dirname']


if not self.shell.dir_stack:<EOL><INDENT>raise UsageError("<STR_LIT>")<EOL><DEDENT>top = self.shell.dir_stack.pop(<NUM_LIT:0>)<EOL>self.cd(top)<EOL>print("<STR_LIT>",top)<EOL>

Change to directory popped off the top of the stack.


return self.shell.dir_stack<EOL>


dh = self.shell.user_ns['<STR_LIT>']<EOL>if parameter_s:<EOL><INDENT>try:<EOL><INDENT>args = list(map(int,parameter_s.split()))<EOL><DEDENT>except:<EOL><INDENT>self.arg_err(self.dhist)<EOL>return<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>ini,fin = max(len(dh)-(args[<NUM_LIT:0>]),<NUM_LIT:0>),len(dh)<EOL><DEDENT>elif len(args) == <NUM_LIT:2>:<EOL><INDENT>ini,fin = args<EOL><DEDENT>else:<EOL><INDENT>self.arg_err(self.dhist)<EOL>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ini,fin = <NUM_LIT:0>,len(dh)<EOL><DEDENT>nlprint(dh,<EOL>header = '<STR_LIT>',<EOL>start=ini,stop=fin)<EOL>

Print your history of visited directories.

        %dhist       -> print full history\\
        %dhist n     -> print last n entries only\\
        %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\

        This history is automatically maintained by the %cd command, and
        always available as the global list variable _dh. You can use %cd -<n>
        to go to directory number <n>.

        Note that most of time, you should view directory history by entering
        cd -<TAB>.


@line_cell_magic<EOL><INDENT>def sx(self, line='<STR_LIT>', cell=None):<DEDENT>

if cell is None:<EOL><INDENT>return self.shell.getoutput(line)<EOL><DEDENT>else:<EOL><INDENT>opts,args = self.parse_options(line, '<STR_LIT>', '<STR_LIT>')<EOL>output = self.shell.getoutput(cell)<EOL>out_name = opts.get('<STR_LIT>', opts.get('<STR_LIT:o>'))<EOL>if out_name:<EOL><INDENT>self.shell.user_ns[out_name] = output<EOL><DEDENT>else:<EOL><INDENT>return output<EOL><DEDENT><DEDENT>

Shell execute - run shell command and capture output (!! is short-hand).

        %sx command

        IPython will run the given command using commands.getoutput(), and
        return the result formatted as a list (split on '\\n').  Since the
        output is _returned_, it will be stored in ipython's regular output
        cache Out[N] and in the '_N' automatic variables.

        Notes:

        1) If an input line begins with '!!', then %sx is automatically
        invoked.  That is, while::

          !ls

        causes ipython to simply issue system('ls'), typing::

          !!ls

        is a shorthand equivalent to::

          %sx ls

        2) %sx differs from %sc in that %sx automatically splits into a list,
        like '%sc -l'.  The reason for this is to make it as easy as possible
        to process line-oriented shell output via further python commands.
        %sc is meant to provide much finer control, but requires more
        typing.

        3) Just like %sc -l, this is a list with special attributes:
        ::

          .l (or .list) : value as list.
          .n (or .nlstr): value as newline-separated string.
          .s (or .spstr): value as whitespace-separated string.

        This is very useful when trying to use such lists as arguments to
        system commands.


opts,args = self.parse_options(parameter_s,'<STR_LIT>',mode='<STR_LIT:list>')<EOL>if len(args) > <NUM_LIT:2>:<EOL><INDENT>raise UsageError("<STR_LIT>")<EOL><DEDENT>bkms = self.shell.db.get('<STR_LIT>',{})<EOL>if '<STR_LIT:d>' in opts:<EOL><INDENT>try:<EOL><INDENT>todel = args[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>raise UsageError(<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>del bkms[todel]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise UsageError(<EOL>"<STR_LIT>" % todel)<EOL><DEDENT><DEDENT><DEDENT>elif '<STR_LIT:r>' in opts:<EOL><INDENT>bkms = {}<EOL><DEDENT>elif '<STR_LIT:l>' in opts:<EOL><INDENT>bks = list(bkms.keys())<EOL>bks.sort()<EOL>if bks:<EOL><INDENT>size = max(list(map(len, bks)))<EOL><DEDENT>else:<EOL><INDENT>size = <NUM_LIT:0><EOL><DEDENT>fmt = '<STR_LIT>'+str(size)+'<STR_LIT>'<EOL>print('<STR_LIT>')<EOL>for bk in bks:<EOL><INDENT>print(fmt % (bk, bkms[bk]))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not args:<EOL><INDENT>raise UsageError("<STR_LIT>")<EOL><DEDENT>elif len(args)==<NUM_LIT:1>:<EOL><INDENT>bkms[args[<NUM_LIT:0>]] = os.getcwd()<EOL><DEDENT>elif len(args)==<NUM_LIT:2>:<EOL><INDENT>bkms[args[<NUM_LIT:0>]] = args[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>self.shell.db['<STR_LIT>'] = bkms<EOL>

Manage IPython's bookmark system.

        %bookmark <name>       - set bookmark to current dir
        %bookmark <name> <dir> - set bookmark to <dir>
        %bookmark -l           - list all bookmarks
        %bookmark -d <name>    - remove bookmark
        %bookmark -r           - remove all bookmarks

        You can later on access a bookmarked folder with::

          %cd -b <name>

        or simply '%cd <name>' if there is no directory called <name> AND
        there is such a bookmark defined.

        Your bookmarks persist through IPython sessions, but they are
        associated with each profile.


try :<EOL><INDENT>cont = self.shell.find_user_code(parameter_s)<EOL><DEDENT>except (ValueError, IOError):<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>page.page(self.shell.pycolorize(cont))<EOL>

Show a syntax-highlighted file through a pager.

        This magic is similar to the cat utility, but it will assume the file
        to be Python source and will show it with syntax highlighting.

        This magic command can either take a local filename, an url,
        an history range (see %history) or a macro as argument ::

        %pycat myscript.py
        %pycat 7-27
        %pycat myMacro
        %pycat http://www.example.com/myscript.py


args = magic_arguments.parse_argstring(self.file, line)<EOL>filename = unquote_filename(args.filename)<EOL>if os.path.exists(filename):<EOL><INDENT>if args.amend:<EOL><INDENT>print("<STR_LIT>" % filename)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % filename)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % filename)<EOL><DEDENT>mode = '<STR_LIT:a>' if args.amend else '<STR_LIT:w>'<EOL>with io.open(filename, mode, encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>f.write(cell)<EOL><DEDENT>

Write the contents of the cell to a file.

        For frontends that do not support stdin (Notebook), -f is implied.


opts,args = self.parse_options(parameter_s,'<STR_LIT>',mode='<STR_LIT:list>')<EOL>raw = '<STR_LIT:r>' in opts<EOL>force = '<STR_LIT:f>' in opts<EOL>ext = '<STR_LIT>' if raw else '<STR_LIT>'<EOL>fname, codefrom = unquote_filename(args[<NUM_LIT:0>]), "<STR_LIT:U+0020>".join(args[<NUM_LIT:1>:])<EOL>if not fname.endswith(('<STR_LIT>','<STR_LIT>')):<EOL><INDENT>fname += ext<EOL><DEDENT>if os.path.isfile(fname) and not force:<EOL><INDENT>try:<EOL><INDENT>overwrite = self.shell.ask_yes_no('<STR_LIT>' % fname, default='<STR_LIT:n>')<EOL><DEDENT>except StdinNotImplementedError:<EOL><INDENT>print("<STR_LIT>" % (fname, parameter_s))<EOL>return<EOL><DEDENT>if not overwrite :<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT><DEDENT>try:<EOL><INDENT>cmds = self.shell.find_user_code(codefrom,raw)<EOL><DEDENT>except (TypeError, ValueError) as e:<EOL><INDENT>print(e.args[<NUM_LIT:0>])<EOL>return<EOL><DEDENT>with io.open(fname,'<STR_LIT:w>', encoding="<STR_LIT:utf-8>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL>f.write(py3compat.cast_unicode(cmds))<EOL><DEDENT>print('<STR_LIT>' % fname)<EOL>print(cmds)<EOL>

Save a set of lines or a macro to a given filename.

        Usage:\\
          %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...

        Options:

          -r: use 'raw' input.  By default, the 'processed' history is used,
          so that magics are loaded in their transformed version to valid
          Python.  If this option is given, the raw input as typed as the
          command line is used instead.

          -f: force overwrite.  If file exists, %save will prompt for overwrite
          unless -f is given.

        This function uses the same syntax as %history for input ranges,
        then saves the lines to the filename you specify.

        It adds a '.py' extension to the file if you don't do so yourself, and
        it asks for confirmation before overwriting existing files.

        If `-r` option is used, the default extension is `.ipy`.


opts, args = self.parse_options(parameter_s, '<STR_LIT>')<EOL>try:<EOL><INDENT>code = self.shell.find_user_code(args)<EOL><DEDENT>except (ValueError, TypeError) as e:<EOL><INDENT>print(e.args[<NUM_LIT:0>])<EOL>return<EOL><DEDENT>post_data = json.dumps({<EOL>"<STR_LIT:description>": opts.get('<STR_LIT:d>', "<STR_LIT>"),<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:content>": code<EOL>}<EOL>}<EOL>}).encode('<STR_LIT:utf-8>')<EOL>response = urlopen("<STR_LIT>", post_data)<EOL>response_data = json.loads(response.read().decode('<STR_LIT:utf-8>'))<EOL>return response_data['<STR_LIT>']<EOL>

Upload code to Github's Gist paste bin, returning the URL.

        Usage:\\
          %pastebin [-d "Custom description"] 1-7

        The argument can be an input history range, a filename, or the name of a
        string or macro.

        Options:

          -d: Pass a custom description for the gist. The default will say
              "Pasted from IPython".


Alias of `%load`

        `%loadpy` has gained some flexibility and droped the requirement of a `.py`
        extension. So it has been renamed simply into %load. You can look at
        `%load`'s docstring for more info.


opts,args = self.parse_options(arg_s,'<STR_LIT:y>')<EOL>contents = self.shell.find_user_code(args)<EOL>l = len(contents)<EOL>if l > <NUM_LIT> and '<STR_LIT:y>' not in opts:<EOL><INDENT>try:<EOL><INDENT>ans = self.shell.ask_yes_no(("<STR_LIT>""<STR_LIT>" % l), default='<STR_LIT:n>' )<EOL><DEDENT>except StdinNotImplementedError:<EOL><INDENT>ans = True<EOL><DEDENT>if ans is False :<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT><DEDENT>self.shell.set_next_input(contents)<EOL>

Load code into the current frontend.

        Usage:\\
          %load [options] source

          where source can be a filename, URL, input history range or macro

        Options:
        --------
          -y : Don't ask confirmation for loading source above 200 000 characters.

        This magic command can either take a local filename, a URL, an history
        range (see %history) or a macro as argument, it will prompt for
        confirmation before loading source with more than 200 000 characters, unless
        -y flag is passed or if the frontend does not support raw_input::

        %load myscript.py
        %load 7-27
        %load myMacro
        %load http://www.example.com/myscript.py


@staticmethod<EOL><INDENT>def _find_edit_target(shell, args, opts, last_call):<DEDENT>

def make_filename(arg):<EOL><INDENT>"<STR_LIT>"<EOL>arg = unquote_filename(arg)<EOL>try:<EOL><INDENT>filename = get_py_filename(arg)<EOL><DEDENT>except IOError:<EOL><INDENT>if arg.endswith('<STR_LIT>'):<EOL><INDENT>filename = arg<EOL><DEDENT>else:<EOL><INDENT>filename = None<EOL><DEDENT><DEDENT>return filename<EOL><DEDENT>opts_prev = '<STR_LIT:p>' in opts<EOL>opts_raw = '<STR_LIT:r>' in opts<EOL>class DataIsObject(Exception): pass<EOL>lineno = opts.get('<STR_LIT:n>',None)<EOL>if opts_prev:<EOL><INDENT>args = '<STR_LIT>' % last_call[<NUM_LIT:0>]<EOL>if args not in shell.user_ns:<EOL><INDENT>args = last_call[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>try:<EOL><INDENT>last_call[<NUM_LIT:0>] = shell.displayhook.prompt_count<EOL>if not opts_prev:<EOL><INDENT>last_call[<NUM_LIT:1>] = args<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>use_temp = True<EOL>data = '<STR_LIT>'<EOL>filename = make_filename(args)<EOL>if filename:<EOL><INDENT>use_temp = False<EOL><DEDENT>elif args:<EOL><INDENT>data = shell.extract_input_lines(args, opts_raw)<EOL>if not data:<EOL><INDENT>try:<EOL><INDENT>data = eval(args, shell.user_ns)<EOL>if not isinstance(data, str):<EOL><INDENT>raise DataIsObject<EOL><DEDENT><DEDENT>except (NameError,SyntaxError):<EOL><INDENT>filename = make_filename(args)<EOL>if filename is None:<EOL><INDENT>warn("<STR_LIT>"<EOL>"<STR_LIT>" % args)<EOL>return<EOL><DEDENT>use_temp = False<EOL><DEDENT>except DataIsObject:<EOL><INDENT>if isinstance(data, Macro):<EOL><INDENT>raise MacroToEdit(data)<EOL><DEDENT>filename = find_file(data)<EOL>if filename:<EOL><INDENT>if '<STR_LIT>' in filename.lower() andinspect.isclass(data):<EOL><INDENT>attrs = [getattr(data, aname) for aname in dir(data)]<EOL>for attr in attrs:<EOL><INDENT>if not inspect.ismethod(attr):<EOL><INDENT>continue<EOL><DEDENT>filename = find_file(attr)<EOL>if filename and'<STR_LIT>' not in filename.lower():<EOL><INDENT>data = attr<EOL>break<EOL><DEDENT><DEDENT><DEDENT>datafile = <NUM_LIT:1><EOL><DEDENT>if filename is None:<EOL><INDENT>filename = make_filename(args)<EOL>datafile = <NUM_LIT:1><EOL>warn('<STR_LIT>'<EOL>'<STR_LIT>' % (args, filename))<EOL><DEDENT>if datafile:<EOL><INDENT>if lineno is None:<EOL><INDENT>lineno = find_source_lines(data)<EOL><DEDENT>if lineno is None:<EOL><INDENT>filename = make_filename(args)<EOL>if filename is None:<EOL><INDENT>warn('<STR_LIT>'<EOL>'<STR_LIT>' % (filename, data))<EOL>return<EOL><DEDENT><DEDENT><DEDENT>use_temp = False<EOL><DEDENT><DEDENT><DEDENT>if use_temp:<EOL><INDENT>filename = shell.mktempfile(data)<EOL>print('<STR_LIT>',filename)<EOL><DEDENT>return filename, lineno, use_temp<EOL>

Utility method used by magic_edit to find what to edit.


filename = self.shell.mktempfile(macro.value)<EOL>self.shell.hooks.editor(filename)<EOL>mfile = open(filename)<EOL>mvalue = mfile.read()<EOL>mfile.close()<EOL>self.shell.user_ns[mname] = Macro(mvalue)<EOL>

open an editor with the macro data in a file


return self.edit(parameter_s)<EOL>


@line_magic<EOL><INDENT>def pinfo(self, parameter_s='<STR_LIT>', namespaces=None):<DEDENT>

<EOL>detail_level = <NUM_LIT:0><EOL>pinfo,qmark1,oname,qmark2 =re.match('<STR_LIT>',parameter_s).groups()<EOL>if pinfo or qmark1 or qmark2:<EOL><INDENT>detail_level = <NUM_LIT:1><EOL><DEDENT>if "<STR_LIT:*>" in oname:<EOL><INDENT>self.psearch(oname)<EOL><DEDENT>else:<EOL><INDENT>self.shell._inspect('<STR_LIT>', oname, detail_level=detail_level,<EOL>namespaces=namespaces)<EOL><DEDENT>

Provide detailed information about an object.

        '%pinfo object' is just a synonym for object? or ?object.


@line_magic<EOL><INDENT>def pinfo2(self, parameter_s='<STR_LIT>', namespaces=None):<DEDENT>

self.shell._inspect('<STR_LIT>', parameter_s, detail_level=<NUM_LIT:1>,<EOL>namespaces=namespaces)<EOL>

Provide extra detailed information about an object.

        '%pinfo2 object' is just a synonym for object?? or ??object.


@line_magic<EOL><INDENT>def pdoc(self, parameter_s='<STR_LIT>', namespaces=None):<DEDENT>

self.shell._inspect('<STR_LIT>',parameter_s, namespaces)<EOL>

Print the docstring for an object.

        If the given object is a class, it will print both the class and the
        constructor docstrings.


@line_magic<EOL><INDENT>def psource(self, parameter_s='<STR_LIT>', namespaces=None):<DEDENT>

Print (or run through pager) the source code for an object.


<EOL>out = self.shell._inspect('<STR_LIT>',parameter_s)<EOL>if out == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>filename = get_py_filename(parameter_s)<EOL><DEDENT>except IOError as msg:<EOL><INDENT>print(msg)<EOL>return<EOL><DEDENT>page.page(self.shell.inspector.format(open(filename).read()))<EOL><DEDENT>

Print (or run through pager) the file where an object is defined.

        The file opens at the line where the object definition begins. IPython
        will honor the environment variable PAGER if set, and otherwise will
        do its best to print the file in a convenient form.

        If the given argument is not an object currently defined, IPython will
        try to interpret it as a filename (automatically adding a .py extension
        if needed). You can thus use %pfile as a syntax highlighting code
        viewer.


try:<EOL><INDENT>parameter_s.encode('<STR_LIT:ascii>')<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>def_search = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>opts,args = self.parse_options(parameter_s,'<STR_LIT>',list_all=True)<EOL>opt = opts.get<EOL>shell = self.shell<EOL>psearch = shell.inspector.psearch<EOL>if '<STR_LIT:i>' in opts:<EOL><INDENT>ignore_case = True<EOL><DEDENT>elif '<STR_LIT:c>' in opts:<EOL><INDENT>ignore_case = False<EOL><DEDENT>else:<EOL><INDENT>ignore_case = not shell.wildcards_case_sensitive<EOL><DEDENT>def_search.extend(opt('<STR_LIT:s>',[]))<EOL>ns_exclude = ns_exclude=opt('<STR_LIT:e>',[])<EOL>ns_search = [nm for nm in def_search if nm not in ns_exclude]<EOL>try:<EOL><INDENT>psearch(args,shell.ns_table,ns_search,<EOL>show_all=opt('<STR_LIT:a>'),ignore_case=ignore_case)<EOL><DEDENT>except:<EOL><INDENT>shell.showtraceback()<EOL><DEDENT>

Search for object in namespaces by wildcard.

        %psearch [options] PATTERN [OBJECT TYPE]

        Note: ? can be used as a synonym for %psearch, at the beginning or at
        the end: both a*? and ?a* are equivalent to '%psearch a*'.  Still, the
        rest of the command line must be unchanged (options come first), so
        for example the following forms are equivalent

        %psearch -i a* function
        -i a* function?
        ?-i a* function

        Arguments:

          PATTERN

          where PATTERN is a string containing * as a wildcard similar to its
          use in a shell.  The pattern is matched in all namespaces on the
          search path. By default objects starting with a single _ are not
          matched, many IPython generated objects have a single
          underscore. The default is case insensitive matching. Matching is
          also done on the attributes of objects and not only on the objects
          in a module.

          [OBJECT TYPE]

          Is the name of a python type from the types module. The name is
          given in lowercase without the ending type, ex. StringType is
          written string. By adding a type here only objects matching the
          given type are matched. Using all here makes the pattern match all
          types (this is the default).

        Options:

          -a: makes the pattern match even objects whose names start with a
          single underscore.  These names are normally omitted from the
          search.

          -i/-c: make the pattern case insensitive/sensitive.  If neither of
          these options are given, the default is read from your configuration
          file, with the option ``InteractiveShell.wildcards_case_sensitive``.
          If this option is not specified in your configuration file, IPython's
          internal default is to do a case sensitive search.

          -e/-s NAMESPACE: exclude/search a given namespace.  The pattern you
          specify can be searched in any of the following namespaces:
          'builtin', 'user', 'user_global','internal', 'alias', where
          'builtin' and 'user' are the search defaults.  Note that you should
          not use quotes when specifying namespaces.

          'Builtin' contains the python module builtin, 'user' contains all
          user data, 'alias' only contain the shell aliases and no python
          objects, 'internal' contains objects used by IPython.  The
          'user_global' namespace is only used by embedded IPython instances,
          and it contains module-level globals.  You can add namespaces to the
          search with -s or exclude them with -e (these options can be given
          more than once).

        Examples
        --------
        ::

          %psearch a*            -> objects beginning with an a
          %psearch -e builtin a* -> objects NOT in the builtin space starting in a
          %psearch a* function   -> all functions beginning with an a
          %psearch re.e*         -> objects beginning with an e in module re
          %psearch r*.e*         -> objects that start with e in modules starting in r
          %psearch r*.* string   -> all strings in modules beginning with r

        Case sensitive search::

          %psearch -c a*         list all object beginning with lower case a

        Show objects beginning with a single _::

          %psearch -a _*         list objects beginning with a single underscore


opts, args = self.parse_options(parameter_s,'<STR_LIT>', mode='<STR_LIT:list>')<EOL>if '<STR_LIT:f>' in opts:<EOL><INDENT>ans = True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>ans = self.shell.ask_yes_no(<EOL>"<STR_LIT>",<EOL>default='<STR_LIT:n>')<EOL><DEDENT>except StdinNotImplementedError:<EOL><INDENT>ans = True<EOL><DEDENT><DEDENT>if not ans:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>if '<STR_LIT:s>' in opts:                     <EOL><INDENT>user_ns = self.shell.user_ns<EOL>for i in self.who_ls():<EOL><INDENT>del(user_ns[i])<EOL><DEDENT><DEDENT>elif len(args) == <NUM_LIT:0>:                <EOL><INDENT>self.shell.reset(new_session = False)<EOL><DEDENT>ip = self.shell<EOL>user_ns = self.shell.user_ns  <EOL>for target in args:<EOL><INDENT>target = target.lower() <EOL>if target == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>" % len(user_ns['<STR_LIT>']))<EOL>self.shell.displayhook.flush()<EOL><DEDENT>elif target == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>")<EOL>pc = self.shell.displayhook.prompt_count + <NUM_LIT:1><EOL>for n in range(<NUM_LIT:1>, pc):<EOL><INDENT>key = '<STR_LIT>'+repr(n)<EOL>user_ns.pop(key,None)<EOL><DEDENT>user_ns.update(dict(_i='<STR_LIT>',_ii='<STR_LIT>',_iii='<STR_LIT>'))<EOL>hm = ip.history_manager<EOL>hm.input_hist_parsed[:] = ['<STR_LIT>'] * pc<EOL>hm.input_hist_raw[:] = ['<STR_LIT>'] * pc<EOL>hm._i = hm._ii = hm._iii = hm._i00 =  '<STR_LIT>'<EOL><DEDENT>elif target == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>from numpy import ndarray<EOL>for x,val in list(user_ns.items()):<EOL><INDENT>if isinstance(val,ndarray):<EOL><INDENT>del user_ns[x]<EOL><DEDENT><DEDENT><DEDENT>except ImportError:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>elif target == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>")<EOL>del user_ns['<STR_LIT>'][:]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print(target + "<STR_LIT>")<EOL><DEDENT><DEDENT>gc.collect()<EOL>

Resets the namespace by removing all names defined by the user, if
        called without arguments, or by removing some types of objects, such
        as everything currently in IPython's In[] and Out[] containers (see
        the parameters for details).

        Parameters
        ----------
        -f : force reset without asking for confirmation.

        -s : 'Soft' reset: Only clears your namespace, leaving history intact.
            References to objects may be kept. By default (without this option),
            we do a 'hard' reset, giving you a new session and removing all
            references to objects from the current session.

        in : reset input history

        out : reset output history

        dhist : reset directory history

        array : reset only variables that are NumPy arrays

        See Also
        --------
        magic_reset_selective : invoked as ``%reset_selective``

        Examples
        --------
        ::

          In [6]: a = 1

          In [7]: a
          Out[7]: 1

          In [8]: 'a' in _ip.user_ns
          Out[8]: True

          In [9]: %reset -f

          In [1]: 'a' in _ip.user_ns
          Out[1]: False

          In [2]: %reset -f in
          Flushing input history

          In [3]: %reset -f dhist in
          Flushing directory history
          Flushing input history

        Notes
        -----
        Calling this magic from clients that do not implement standard input,
        such as the ipython notebook interface, will reset the namespace
        without confirmation.


opts, regex = self.parse_options(parameter_s,'<STR_LIT:f>')<EOL>if '<STR_LIT:f>' in opts:<EOL><INDENT>ans = True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>ans = self.shell.ask_yes_no(<EOL>"<STR_LIT>",<EOL>default='<STR_LIT:n>')<EOL><DEDENT>except StdinNotImplementedError:<EOL><INDENT>ans = True<EOL><DEDENT><DEDENT>if not ans:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>user_ns = self.shell.user_ns<EOL>if not regex:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>m = re.compile(regex)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for i in self.who_ls():<EOL><INDENT>if m.search(i):<EOL><INDENT>del(user_ns[i])<EOL><DEDENT><DEDENT><DEDENT>

Resets the namespace by removing names defined by the user.

        Input/Output history are left around in case you need them.

        %reset_selective [-f] regex

        No action is taken if regex is not included

        Options
          -f : force reset without asking for confirmation.

        See Also
        --------
        magic_reset : invoked as ``%reset``

        Examples
        --------

        We first fully reset the namespace so your output looks identical to
        this example for pedagogical reasons; in practice you do not need a
        full reset::

          In [1]: %reset -f

        Now, with a clean namespace we can make a few variables and use
        ``%reset_selective`` to only delete names that match our regexp::

          In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8

          In [3]: who_ls
          Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']

          In [4]: %reset_selective -f b[2-3]m

          In [5]: who_ls
          Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']

          In [6]: %reset_selective -f d

          In [7]: who_ls
          Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']

          In [8]: %reset_selective -f c

          In [9]: who_ls
          Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']

          In [10]: %reset_selective -f b

          In [11]: who_ls
          Out[11]: ['a']

        Notes
        -----
        Calling this magic from clients that do not implement standard input,
        such as the ipython notebook interface, will reset the namespace
        without confirmation.


opts, varname = self.parse_options(parameter_s,'<STR_LIT:n>')<EOL>try:<EOL><INDENT>self.shell.del_var(varname, ('<STR_LIT:n>' in opts))<EOL><DEDENT>except (NameError, ValueError) as e:<EOL><INDENT>print(type(e).__name__ +"<STR_LIT>"+ str(e))<EOL><DEDENT>

Delete a variable, trying to clear it from anywhere that
        IPython's machinery has references to it. By default, this uses
        the identity of the named object in the user namespace to remove
        references held under other names. The object is also removed
        from the output history.

        Options
          -n : Delete the specified name from all namespaces, without
          checking their identity.


opts, args = self.parse_options(parameter_s, '<STR_LIT>')<EOL>try:<EOL><INDENT>filename = self.shell.extension_manager.install_extension(args,<EOL>opts.get('<STR_LIT:n>'))<EOL><DEDENT>except ValueError as e:<EOL><INDENT>print(e)<EOL>return<EOL><DEDENT>filename = os.path.basename(filename)<EOL>print("<STR_LIT>" % filename)<EOL>print("<STR_LIT>" % os.path.splitext(filename)[<NUM_LIT:0>])<EOL>

Download and install an extension from a URL, e.g.::

            %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py

        The URL should point to an importable Python module - either a .py file
        or a .zip file.

        Parameters:

          -n filename : Specify a name for the file, rather than taking it from
                        the URL.


return self.shell.extension_manager.load_extension(module_str)<EOL>

Load an IPython extension by its module name.


self.shell.extension_manager.unload_extension(module_str)<EOL>

Unload an IPython extension by its module name.


self.shell.extension_manager.reload_extension(module_str)<EOL>

Reload an IPython extension by its module name.


if not arg:                 <EOL><INDENT>self.shell.set_next_input(str(self.shell.user_ns["<STR_LIT:_>"]))<EOL>return<EOL><DEDENT>histlines = self.shell.history_manager.get_range_by_str(arg)<EOL>cmd = "<STR_LIT:\n>".join(x[<NUM_LIT:2>] for x in histlines)<EOL>if cmd:<EOL><INDENT>self.shell.set_next_input(cmd.rstrip())<EOL>return<EOL><DEDENT>try:                        <EOL><INDENT>cmd = str(eval(arg, self.shell.user_ns))<EOL><DEDENT>except Exception:           <EOL><INDENT>histlines = self.shell.history_manager.search("<STR_LIT:*>"+arg+"<STR_LIT:*>")<EOL>for h in reversed([x[<NUM_LIT:2>] for x in histlines]):<EOL><INDENT>if '<STR_LIT>' in h:<EOL><INDENT>continue<EOL><DEDENT>self.shell.set_next_input(h.rstrip())<EOL>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.shell.set_next_input(cmd.rstrip())<EOL><DEDENT>print("<STR_LIT>", arg)<EOL>

r"""Repeat a command, or get command to input line for editing.

        %recall and %rep are equivalent.

        - %recall (no arguments):

        Place a string version of last computation result (stored in the
        special '_' variable) to the next input prompt. Allows you to create
        elaborate command lines without using copy-paste::

             In[1]: l = ["hei", "vaan"]
             In[2]: "".join(l)
            Out[2]: heivaan
             In[3]: %rep
             In[4]: heivaan_ <== cursor blinking

        %recall 45

        Place history line 45 on the next input prompt. Use %hist to find
        out the number.

        %recall 1-4

        Combine the specified lines into one cell, and place it on the next
        input prompt. See %history for the slice syntax.

        %recall foo+bar

        If foo+bar can be evaluated in the user namespace, the result is
        placed at the next input prompt. Otherwise, the history is searched
        for lines which contain that substring, and the most recent one is
        placed at the next input prompt.


opts, args = self.parse_options(parameter_s, '<STR_LIT>', mode='<STR_LIT:string>')<EOL>if "<STR_LIT:l>" in opts:         <EOL><INDENT>n = int(opts['<STR_LIT:l>'])<EOL>hist = self.shell.history_manager.get_tail(n)<EOL><DEDENT>elif "<STR_LIT:g>" in opts:       <EOL><INDENT>p = "<STR_LIT:*>"+opts['<STR_LIT:g>']+"<STR_LIT:*>"<EOL>hist = list(self.shell.history_manager.search(p))<EOL>for l in reversed(hist):<EOL><INDENT>if "<STR_LIT>" not in l[<NUM_LIT:2>]:<EOL><INDENT>hist = [l]     <EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>hist = []          <EOL><DEDENT><DEDENT>elif args:              <EOL><INDENT>hist = self.shell.history_manager.get_range_by_str(args)<EOL><DEDENT>else:                   <EOL><INDENT>hist = self.shell.history_manager.get_tail(<NUM_LIT:1>)<EOL><DEDENT>hist = [x[<NUM_LIT:2>] for x in hist]<EOL>if not hist:<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>histlines = "<STR_LIT:\n>".join(hist)<EOL>print("<STR_LIT>")<EOL>print(histlines)<EOL>print("<STR_LIT>")<EOL>self.shell.run_cell("<STR_LIT:\n>".join(hist), store_history=False)<EOL>

Re-run previous input

        By default, you can specify ranges of input history to be repeated
        (as with %history). With no arguments, it will repeat the last line.

        Options:

          -l <n> : Repeat the last n lines of input, not including the
          current command.

          -g foo : Repeat the most recent line which contains foo


par = parameter_s.strip().lower()<EOL>if par:<EOL><INDENT>try:<EOL><INDENT>new_pdb = {'<STR_LIT>':<NUM_LIT:0>,'<STR_LIT:0>':<NUM_LIT:0>,'<STR_LIT>':<NUM_LIT:1>,'<STR_LIT:1>':<NUM_LIT:1>}[par]<EOL><DEDENT>except KeyError:<EOL><INDENT>print ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>new_pdb = not self.shell.call_pdb<EOL><DEDENT>self.shell.call_pdb = new_pdb<EOL>print('<STR_LIT>',on_off(new_pdb))<EOL>

Control the automatic calling of the pdb interactive debugger.

        Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
        argument it works as a toggle.

        When an exception is triggered, IPython can optionally call the
        interactive pdb debugger after the traceback printout. %pdb toggles
        this feature on and off.

        The initial state of this feature is set in your configuration
        file (the option is ``InteractiveShell.pdb``).

        If you want to just activate the debugger AFTER an exception has fired,
        without having to type '%pdb on' and rerunning your code, you can use
        the %debug magic.


self.shell.debugger(force=True)<EOL>

Activate the interactive debugger in post-mortem mode.

        If an exception has just occurred, this lets you inspect its stack
        frames interactively.  Note that this will always work only on the last
        traceback that occurred, so you must call this quickly after an
        exception that you wish to inspect has fired, because if another one
        occurs, it clobbers the previous one.

        If you want IPython to automatically do this on every exception, see
        the %pdb magic for more details.


self.shell.showtraceback()<EOL>

Print the last traceback with the currently active exception mode.

        See %xmode for changing exception reporting modes.


args = magic_arguments.parse_argstring(self.capture, line)<EOL>out = not args.no_stdout<EOL>err = not args.no_stderr<EOL>with capture_output(out, err) as io:<EOL><INDENT>self.shell.run_cell(cell)<EOL><DEDENT>if args.output:<EOL><INDENT>self.shell.user_ns[args.output] = io<EOL><DEDENT>


<EOL>regex = re.compile("<STR_LIT>" % "<STR_LIT:|>".join(map(re.escape, dict.keys())))<EOL>return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)<EOL>

Replace in 'text' all occurences of any key in the given
    dictionary by its corresponding value.  Returns the new string.


cwd = os.getcwdu().replace(HOME,"<STR_LIT>")<EOL>out = os.sep.join(cwd.split(os.sep)[-depth:])<EOL>return out or os.sep<EOL>

Return the last depth elements of the current working directory.

    $HOME is always replaced with '~'.
    If depth==0, the full path is returned.


full_cwd = os.getcwdu()<EOL>cwd = full_cwd.replace(HOME,"<STR_LIT>").split(os.sep)<EOL>if '<STR_LIT>' in cwd and len(cwd) == depth+<NUM_LIT:1>:<EOL><INDENT>depth += <NUM_LIT:1><EOL><DEDENT>drivepart = '<STR_LIT>'<EOL>if sys.platform == '<STR_LIT:win32>' and len(cwd) > depth:<EOL><INDENT>drivepart = os.path.splitdrive(full_cwd)[<NUM_LIT:0>]<EOL><DEDENT>out = drivepart + '<STR_LIT:/>'.join(cwd[-depth:])<EOL>return out or os.sep<EOL>


if not s or s.endswith(('<STR_LIT:\n>', '<STR_LIT:\r>')):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return len(s.splitlines()[-<NUM_LIT:1>])<EOL>

Get the length of the last line. More intelligent than
    len(s.splitlines()[-1]).


def update_prompt(self, name, new_template=None):

if new_template is not None:<EOL><INDENT>self.templates[name] = multiple_replace(prompt_abbreviations, new_template)<EOL><DEDENT>invis_chars = _lenlastline(self._render(name, color=True)) -_lenlastline(self._render(name, color=False))<EOL>self.invisible_chars[name] = invis_chars<EOL>

This is called when a prompt template is updated. It processes
        abbreviations used in the prompt template (like \#) and calculates how
        many invisible characters (ANSI colour escapes) the resulting prompt
        contains.

        It is also called for each prompt on changing the colour scheme. In both
        cases, traitlets should take care of calling this automatically.


def _render(self, name, color=True, **kwargs):

if name == '<STR_LIT>':<EOL><INDENT>return self._render_rewrite(color=color)<EOL><DEDENT>if color:<EOL><INDENT>scheme = self.color_scheme_table.active_colors<EOL>if name=='<STR_LIT>':<EOL><INDENT>colors = color_lists['<STR_LIT>']<EOL>colors.number, colors.prompt, colors.normal =scheme.out_number, scheme.out_prompt, scheme.normal<EOL><DEDENT>else:<EOL><INDENT>colors = color_lists['<STR_LIT>']<EOL>colors.number, colors.prompt, colors.normal =scheme.in_number, scheme.in_prompt, scheme.in_normal<EOL>if name=='<STR_LIT>':<EOL><INDENT>colors.prompt = scheme.in_prompt2<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>colors = color_lists['<STR_LIT>']<EOL>colors.number, colors.prompt, colors.normal = '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'<EOL><DEDENT>count = self.shell.execution_count    <EOL>fmtargs = dict(color=colors, count=count,<EOL>dots="<STR_LIT:.>"*len(str(count)),<EOL>width=self.width, txtwidth=self.txtwidth )<EOL>fmtargs.update(self.lazy_evaluate_fields)<EOL>fmtargs.update(kwargs)<EOL>prompt = colors.prompt + self.templates[name] + colors.normal<EOL>return self._formatter.format(prompt, **fmtargs)<EOL>

Render but don't justify, or update the width or txtwidth attributes.


if color:<EOL><INDENT>scheme = self.color_scheme_table.active_colors<EOL>color_prompt = scheme.in_prompt.replace("<STR_LIT>","<STR_LIT>").replace("<STR_LIT>","<STR_LIT>")<EOL>color_normal = scheme.normal<EOL><DEDENT>else:<EOL><INDENT>color_prompt, color_normal = '<STR_LIT>', '<STR_LIT>'<EOL><DEDENT>return color_prompt + "<STR_LIT>".rjust(self.txtwidth, "<STR_LIT:->") + color_normal<EOL>


def render(self, name, color=True, just=None, **kwargs):

res = self._render(name, color=color, **kwargs)<EOL>invis_chars = self.invisible_chars[name] if color else <NUM_LIT:0><EOL>self.txtwidth = _lenlastline(res) - invis_chars<EOL>just = self.justify if (just is None) else just<EOL>if just and name != '<STR_LIT>' and ('<STR_LIT:\n>' not in res) and ('<STR_LIT:\r>' not in res):<EOL><INDENT>res = res.rjust(self.width + invis_chars)<EOL><DEDENT>self.width = _lenlastline(res) - invis_chars<EOL>return res<EOL>

Render the selected prompt.

Parameters
----------
name : str
  Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
  If True (default), include ANSI escape sequences for a coloured prompt.
just : bool
  If True, justify the prompt to the width of the last prompt. The
  default is stored in self.justify.
**kwargs :
  Additional arguments will be passed to the string formatting operation,
  so they can override the values that would otherwise fill in the
  template.

Returns
-------
A string containing the rendered prompt.


def crash_handler_lite(etype, evalue, tb):

traceback.print_exception(etype, evalue, tb)<EOL>from IPython.core.interactiveshell import InteractiveShell<EOL>if InteractiveShell.initialized():<EOL><INDENT>config = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>config = "<STR_LIT>"<EOL><DEDENT>print >> sys.stderr, _lite_message_template.format(email=author_email, config=config)<EOL>

a light excepthook, adding a small message to the usual traceback


def __init__(self, app, contact_name=None, contact_email=None,<EOL>bug_tracker=None, show_crash_traceback=True, call_pdb=False):

self.crash_report_fname = "<STR_LIT>" % app.name<EOL>self.app = app<EOL>self.call_pdb = call_pdb<EOL>self.show_crash_traceback = show_crash_traceback<EOL>self.info = dict(app_name = app.name,<EOL>contact_name = contact_name,<EOL>contact_email = contact_email,<EOL>bug_tracker = bug_tracker,<EOL>crash_report_fname = self.crash_report_fname)<EOL>

Create a new crash handler

        Parameters
        ----------
        app :  Application
            A running :class:`Application` instance, which will be queried at
            crash time for internal information.

        contact_name : str
            A string with the name of the person to contact.

        contact_email : str
            A string with the email address of the contact.

        bug_tracker : str
            A string with the URL for your project's bug tracker.

        show_crash_traceback : bool
            If false, don't print the crash traceback on stderr, only generate
            the on-disk report

        Non-argument instance attributes:

        These instances contain some non-argument attributes which allow for
        further customization of the crash handler's behavior. Please see the
        source for further details.


<EOL>sys.excepthook = sys.__excepthook__<EOL>color_scheme = '<STR_LIT>'<EOL>try:<EOL><INDENT>rptdir = self.app.ipython_dir<EOL><DEDENT>except:<EOL><INDENT>rptdir = os.getcwdu()<EOL><DEDENT>if rptdir is None or not os.path.isdir(rptdir):<EOL><INDENT>rptdir = os.getcwdu()<EOL><DEDENT>report_name = os.path.join(rptdir,self.crash_report_fname)<EOL>self.crash_report_fname = report_name<EOL>self.info['<STR_LIT>'] = report_name<EOL>TBhandler = ultratb.VerboseTB(<EOL>color_scheme=color_scheme,<EOL>long_header=<NUM_LIT:1>,<EOL>call_pdb=self.call_pdb,<EOL>)<EOL>if self.call_pdb:<EOL><INDENT>TBhandler(etype,evalue,etb)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>traceback = TBhandler.text(etype,evalue,etb,context=<NUM_LIT>)<EOL><DEDENT>if self.show_crash_traceback:<EOL><INDENT>print >> sys.stderr, traceback<EOL><DEDENT>try:<EOL><INDENT>report = open(report_name,'<STR_LIT:w>')<EOL><DEDENT>except:<EOL><INDENT>print >> sys.stderr, '<STR_LIT>'<EOL>return<EOL><DEDENT>print >> sys.stderr, '<STR_LIT:\n>'+'<STR_LIT:*>'*<NUM_LIT>+'<STR_LIT:\n>'<EOL>print >> sys.stderr, self.message_template.format(**self.info)<EOL>report.write(self.make_report(traceback))<EOL>report.close()<EOL>raw_input("<STR_LIT>")<EOL>

Handle an exception, call for compatible with sys.excepthook


sec_sep = self.section_sep<EOL>report = ['<STR_LIT:*>'*<NUM_LIT>+'<STR_LIT>'+'<STR_LIT>']<EOL>rpt_add = report.append<EOL>rpt_add(sys_info())<EOL>try:<EOL><INDENT>config = pformat(self.app.config)<EOL>rpt_add(sec_sep)<EOL>rpt_add('<STR_LIT>' % self.app_name)<EOL>rpt_add('<STR_LIT>')<EOL>rpt_add(config)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>rpt_add(sec_sep+'<STR_LIT>' + traceback)<EOL>return '<STR_LIT>'.join(report)<EOL>

Return a string containing a crash report.


def copy_config_file(self, config_file, path=None, overwrite=False):

dst = os.path.join(self.location, config_file)<EOL>if os.path.isfile(dst) and not overwrite:<EOL><INDENT>return False<EOL><DEDENT>if path is None:<EOL><INDENT>path = os.path.join(get_ipython_package_dir(), '<STR_LIT>', '<STR_LIT>', '<STR_LIT:default>')<EOL><DEDENT>src = os.path.join(path, config_file)<EOL>shutil.copy(src, dst)<EOL>return True<EOL>

Copy a default config file into the active profile directory.

        Default configuration files are kept in :mod:`IPython.config.default`.
        This function moves these from that location to the working profile
        directory.


@classmethod<EOL><INDENT>def create_profile_dir(cls, profile_dir, config=None):<DEDENT>

return cls(location=profile_dir, config=config)<EOL>

Create a new profile directory given a full path.

        Parameters
        ----------
        profile_dir : str
            The full path to the profile directory.  If it does exist, it will
            be used.  If not, it will be created.


@classmethod<EOL><INDENT>def create_profile_dir_by_name(cls, path, name='<STR_LIT:default>', config=None):<DEDENT>

if not os.path.isdir(path):<EOL><INDENT>raise ProfileDirError('<STR_LIT>' % path)<EOL><DEDENT>profile_dir = os.path.join(path, '<STR_LIT>' + name)<EOL>return cls(location=profile_dir, config=config)<EOL>

Create a profile dir by profile name and path.

        Parameters
        ----------
        path : unicode
            The path (directory) to put the profile directory in.
        name : unicode
            The name of the profile.  The name of the profile directory will
            be "profile_<profile>".


@classmethod<EOL><INDENT>def find_profile_dir_by_name(cls, ipython_dir, name='<STR_LIT:default>', config=None):<DEDENT>

dirname = '<STR_LIT>' + name<EOL>paths = [os.getcwd(), ipython_dir]<EOL>for p in paths:<EOL><INDENT>profile_dir = os.path.join(p, dirname)<EOL>if os.path.isdir(profile_dir):<EOL><INDENT>return cls(location=profile_dir, config=config)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ProfileDirError('<STR_LIT>' % dirname)<EOL><DEDENT>

Find an existing profile dir by profile name, return its ProfileDir.

        This searches through a sequence of paths for a profile dir.  If it
        is not found, a :class:`ProfileDirError` exception will be raised.

        The search path algorithm is:
        1. ``os.getcwdu()``
        2. ``ipython_dir``

        Parameters
        ----------
        ipython_dir : unicode or str
            The IPython directory to use.
        name : unicode or str
            The name of the profile.  The name of the profile directory
            will be "profile_<profile>".


@classmethod<EOL><INDENT>def find_profile_dir(cls, profile_dir, config=None):<DEDENT>

profile_dir = expand_path(profile_dir)<EOL>if not os.path.isdir(profile_dir):<EOL><INDENT>raise ProfileDirError('<STR_LIT>' % profile_dir)<EOL><DEDENT>return cls(location=profile_dir, config=config)<EOL>

Find/create a profile dir and return its ProfileDir.

        This will create the profile directory if it doesn't exist.

        Parameters
        ----------
        profile_dir : unicode or str
            The path of the profile directory.  This is expanded using
            :func:`IPython.utils.genutils.expand_path`.


oldvalue = <NUM_LIT:0><EOL>try:<EOL><INDENT>oldvalue = file.softspace<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>file.softspace = newvalue<EOL><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>pass<EOL><DEDENT>return oldvalue<EOL>

Copied from code.py, to remove the dependency


end = self.shell.readline.get_current_history_length() + <NUM_LIT:1><EOL>start = max(end-n, <NUM_LIT:1>)<EOL>ghi = self.shell.readline.get_history_item<EOL>return [ghi(x) for x in range(start, end)]<EOL>

Get the last n items in readline history.


return self<EOL>

Return the currently running IPython instance.


if value != <NUM_LIT:0> and not self.has_readline:<EOL><INDENT>if os.name == '<STR_LIT>':<EOL><INDENT>warn("<STR_LIT>")<EOL><DEDENT>self.autoindent = <NUM_LIT:0><EOL>return<EOL><DEDENT>if value is None:<EOL><INDENT>self.autoindent = not self.autoindent<EOL><DEDENT>else:<EOL><INDENT>self.autoindent = value<EOL><DEDENT>

Set the autoindent flag, checking for readline support.

        If called with no arguments, it acts as a toggle.


pass<EOL>

Any changes we need to make to the user's environment.


if self.logappend:<EOL><INDENT>self.magic('<STR_LIT>' % self.logappend)<EOL><DEDENT>elif self.logfile:<EOL><INDENT>self.magic('<STR_LIT>' % self.logfile)<EOL><DEDENT>elif self.logstart:<EOL><INDENT>self.magic('<STR_LIT>')<EOL><DEDENT>

Initialize logging in case it was requested at the command line.


if '<STR_LIT>' not in os.environ:<EOL><INDENT>return<EOL><DEDENT>if sys.executable.startswith(os.environ['<STR_LIT>']):<EOL><INDENT>return<EOL><DEDENT>warn("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>virtual_env = os.path.join(os.environ['<STR_LIT>'], '<STR_LIT>', '<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>virtual_env = os.path.join(os.environ['<STR_LIT>'], '<STR_LIT>',<EOL>'<STR_LIT>' % sys.version_info[:<NUM_LIT:2>], '<STR_LIT>')<EOL><DEDENT>import site<EOL>sys.path.insert(<NUM_LIT:0>, virtual_env)<EOL>site.addsitedir(virtual_env)<EOL>

Add a virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv


self._orig_sys_module_state = {}<EOL>self._orig_sys_module_state['<STR_LIT>'] = sys.stdin<EOL>self._orig_sys_module_state['<STR_LIT>'] = sys.stdout<EOL>self._orig_sys_module_state['<STR_LIT>'] = sys.stderr<EOL>self._orig_sys_module_state['<STR_LIT>'] = sys.excepthook<EOL>self._orig_sys_modules_main_name = self.user_module.__name__<EOL>self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)<EOL>

Save the state of hooks in the sys module.

        This has to be called after self.user_module is created.


try:<EOL><INDENT>for k, v in self._orig_sys_module_state.items():<EOL><INDENT>setattr(sys, k, v)<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if self._orig_sys_modules_main_mod is not None:<EOL><INDENT>sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod<EOL><DEDENT>


def set_hook(self,name,hook, priority = <NUM_LIT:50>, str_key = None, re_key = None):

<EOL>f = types.MethodType(hook,self)<EOL>if str_key is not None:<EOL><INDENT>sdp = self.strdispatchers.get(name, StrDispatch())<EOL>sdp.add_s(str_key, f, priority )<EOL>self.strdispatchers[name] = sdp<EOL>return<EOL><DEDENT>if re_key is not None:<EOL><INDENT>sdp = self.strdispatchers.get(name, StrDispatch())<EOL>sdp.add_re(re.compile(re_key), f, priority )<EOL>self.strdispatchers[name] = sdp<EOL>return<EOL><DEDENT>dp = getattr(self.hooks, name, None)<EOL>if name not in IPython.core.hooks.__all__:<EOL><INDENT>print("<STR_LIT>" %(name, IPython.core.hooks.__all__ ))<EOL><DEDENT>if not dp:<EOL><INDENT>dp = IPython.core.hooks.CommandChainDispatcher()<EOL><DEDENT>try:<EOL><INDENT>dp.add(f,priority)<EOL><DEDENT>except AttributeError:<EOL><INDENT>dp = f<EOL><DEDENT>setattr(self.hooks,name, dp)<EOL>

set_hook(name,hook) -> sets an internal IPython hook.

        IPython exposes some of its internal API as user-modifiable hooks.  By
        adding your function to one of these hooks, you can modify IPython's
        behavior to call at runtime your own routines.


if not callable(func):<EOL><INDENT>raise ValueError('<STR_LIT>' % func)<EOL><DEDENT>self._post_execute[func] = True<EOL>

Register a function for calling after code execution.


main_mod = self._user_main_module<EOL>init_fakemod_dict(main_mod,ns)<EOL>return main_mod<EOL>

Return a new 'main' module object for user code execution.


self._main_ns_cache[os.path.abspath(fname)] = ns.copy()<EOL>

Cache a main module's namespace.

        When scripts are executed via %run, we must keep a reference to the
        namespace of their __main__ module (a FakeModule instance) around so
        that Python doesn't clear it, rendering objects defined therein
        useless.

        This method keeps said reference in a private dict, keyed by the
        absolute path of the module object (which corresponds to the script
        path).  This way, for multiple executions of the same script we only
        keep one copy of the namespace (the last one), thus preventing memory
        leaks from old references while allowing the objects from the last
        execution to be accessible.

        Note: we can not allow the actual FakeModule instances to be deleted,
        because of how Python tears down modules (it hard-sets all their
        references to None without regard for reference counts).  This method
        must therefore make a *copy* of the given namespace, to allow the
        original module's __dict__ to be cleared and reused.

        Parameters
        ----------
          ns : a namespace (a dict, typically)

          fname : str
            Filename associated with the namespace.

        Examples
        --------

        In [10]: import IPython

        In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)

        In [12]: IPython.__file__ in _ip._main_ns_cache
        Out[12]: True


Clear the cache of main modules.

        Mainly for use by utilities like %reset.

        Examples
        --------

        In [15]: import IPython

        In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)

        In [17]: len(_ip._main_ns_cache) > 0
        Out[17]: True

        In [18]: _ip.clear_main_mod_cache()

        In [19]: len(_ip._main_ns_cache) == 0
        Out[19]: True


if not (force or self.call_pdb):<EOL><INDENT>return<EOL><DEDENT>if not hasattr(sys,'<STR_LIT>'):<EOL><INDENT>error('<STR_LIT>')<EOL>return<EOL><DEDENT>if debugger.has_pydb:<EOL><INDENT>from pydb import pm<EOL><DEDENT>else:<EOL><INDENT>pm = lambda : self.InteractiveTB.debugger(force=True)<EOL><DEDENT>with self.readline_no_record:<EOL><INDENT>pm()<EOL><DEDENT>

Call the pydb/pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
          flag and does not actually invoke the debugger if the flag is false.
          The 'force' option forces the debugger to activate even if the flag
          is false.


def prepare_user_module(self, user_module=None, user_ns=None):

if user_module is None and user_ns is not None:<EOL><INDENT>user_ns.setdefault("<STR_LIT>", "<STR_LIT:__main__>")<EOL>class DummyMod(object):<EOL><INDENT>"<STR_LIT>"<EOL>pass<EOL><DEDENT>user_module = DummyMod()<EOL>user_module.__dict__ = user_ns<EOL><DEDENT>if user_module is None:<EOL><INDENT>user_module = types.ModuleType("<STR_LIT:__main__>",<EOL>doc="<STR_LIT>")<EOL><DEDENT>user_module.__dict__.setdefault('<STR_LIT>', builtin_mod)<EOL>user_module.__dict__.setdefault('<STR_LIT>', builtin_mod)<EOL>if user_ns is None:<EOL><INDENT>user_ns = user_module.__dict__<EOL><DEDENT>return user_module, user_ns<EOL>

Prepare the module and namespace in which user code will be run.

        When IPython is started normally, both parameters are None: a new module
        is created automatically, and its __dict__ used as the namespace.

        If only user_module is provided, its __dict__ is used as the namespace.
        If only user_ns is provided, a dummy module is created, and user_ns
        becomes the global namespace. If both are provided (as they may be
        when embedding), user_ns is the local namespace, and user_module
        provides the global namespace.

        Parameters
        ----------
        user_module : module, optional
            The current user module in which IPython is being run. If None,
            a clean module will be created.
        user_ns : dict, optional
            A namespace in which to run interactive commands.

        Returns
        -------
        A tuple of user_module and user_ns, each properly initialised.


<EOL>ns = dict()<EOL>try:<EOL><INDENT>from site import _Helper<EOL>ns['<STR_LIT>'] = _Helper()<EOL><DEDENT>except ImportError:<EOL><INDENT>warn('<STR_LIT>')<EOL><DEDENT>ns['<STR_LIT>'] = self.history_manager.input_hist_parsed<EOL>ns['<STR_LIT>'] = self.history_manager.output_hist<EOL>ns['<STR_LIT>'] = self.history_manager.dir_hist<EOL>ns['<STR_LIT>'] = shadowns<EOL>ns['<STR_LIT>']  = self.history_manager.input_hist_parsed<EOL>ns['<STR_LIT>'] = self.history_manager.output_hist<EOL>ns['<STR_LIT>'] = self.get_ipython<EOL>ns['<STR_LIT>'] = self.exiter<EOL>ns['<STR_LIT>'] = self.exiter<EOL>self.user_ns_hidden.update(ns)<EOL>self.user_ns.update(ns)<EOL>

Initialize all user-visible namespaces to their minimum defaults.

        Certain history lists are also initialized here, as they effectively
        act as user namespaces.

        Notes
        -----
        All data structures here are only filled in, they are NOT reset by this
        method.  If they were not empty before, data will simply be added to
        therm.


return [self.user_ns, self.user_global_ns,<EOL>self._user_main_module.__dict__] + list(self._main_ns_cache.values())<EOL>

Get a list of references to all the namespace dictionaries in which
        IPython might store a user-created object.

        Note that this does not include the displayhook, which also caches
        objects from the output.


<EOL>self.history_manager.reset(new_session)<EOL>if new_session:<EOL><INDENT>self.execution_count = <NUM_LIT:1><EOL><DEDENT>if self.displayhook.do_full_cache:<EOL><INDENT>self.displayhook.flush()<EOL><DEDENT>if self.user_ns is not self.user_global_ns:<EOL><INDENT>self.user_ns.clear()<EOL><DEDENT>ns = self.user_global_ns<EOL>drop_keys = set(ns.keys())<EOL>drop_keys.discard('<STR_LIT>')<EOL>drop_keys.discard('<STR_LIT>')<EOL>drop_keys.discard('<STR_LIT>')<EOL>for k in drop_keys:<EOL><INDENT>del ns[k]<EOL><DEDENT>self.user_ns_hidden.clear()<EOL>self.init_user_ns()<EOL>self.alias_manager.clear_aliases()<EOL>self.alias_manager.init_aliases()<EOL>self.clear_main_mod_cache()<EOL>self.new_main_mod()<EOL>

Clear all internal namespaces, and attempt to release references to
        user objects.

        If new_session is True, a new history session will be opened.


def del_var(self, varname, by_name=False):

if varname in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>" % varname)<EOL><DEDENT>ns_refs = self.all_ns_refs<EOL>if by_name:                    <EOL><INDENT>for ns in ns_refs:<EOL><INDENT>try:<EOL><INDENT>del ns[varname]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>else:                         <EOL><INDENT>try:<EOL><INDENT>obj = self.user_ns[varname]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NameError("<STR_LIT>" % varname)<EOL><DEDENT>ns_refs.append(self.history_manager.output_hist)<EOL>for ns in ns_refs:<EOL><INDENT>to_delete = [n for n, o in ns.items() if o is obj]<EOL>for name in to_delete:<EOL><INDENT>del ns[name]<EOL><DEDENT><DEDENT>for name in ('<STR_LIT:_>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if getattr(self.displayhook, name) is obj:<EOL><INDENT>setattr(self.displayhook, name, None)<EOL><DEDENT><DEDENT><DEDENT>

Delete a variable from the various namespaces, so that, as
        far as possible, we're not keeping any hidden references to it.

        Parameters
        ----------
        varname : str
            The name of the variable to delete.
        by_name : bool
            If True, delete variables with the given name in each
            namespace. If False (default), find the variable in the user
            namespace, and delete references to it.


if regex is not None:<EOL><INDENT>try:<EOL><INDENT>m = re.compile(regex)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for ns in self.all_ns_refs:<EOL><INDENT>for var in ns:<EOL><INDENT>if m.search(var):<EOL><INDENT>del ns[var]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Clear selective variables from internal namespaces based on a
        specified regular expression.

        Parameters
        ----------
        regex : string or compiled pattern, optional
            A regular expression pattern that will be used in searching
            variable names in the users namespaces.


def push(self, variables, interactive=True):

vdict = None<EOL>if isinstance(variables, dict):<EOL><INDENT>vdict = variables<EOL><DEDENT>elif isinstance(variables, (str, list, tuple)):<EOL><INDENT>if isinstance(variables, str):<EOL><INDENT>vlist = variables.split()<EOL><DEDENT>else:<EOL><INDENT>vlist = variables<EOL><DEDENT>vdict = {}<EOL>cf = sys._getframe(<NUM_LIT:1>)<EOL>for name in vlist:<EOL><INDENT>try:<EOL><INDENT>vdict[name] = eval(name, cf.f_globals, cf.f_locals)<EOL><DEDENT>except:<EOL><INDENT>print(('<STR_LIT>' %<EOL>(name,cf.f_code.co_name)))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.user_ns.update(vdict)<EOL>user_ns_hidden = self.user_ns_hidden<EOL>if interactive:<EOL><INDENT>user_ns_hidden.difference_update(vdict)<EOL><DEDENT>else:<EOL><INDENT>user_ns_hidden.update(vdict)<EOL><DEDENT>

Inject a group of variables into the IPython user namespace.

        Parameters
        ----------
        variables : dict, str or list/tuple of str
            The variables to inject into the user's namespace.  If a dict, a
            simple update is done.  If a str, the string is assumed to have
            variable names separated by spaces.  A list/tuple of str can also
            be used to give the variable names.  If just the variable names are
            give (list/tuple/str) then the variable values looked up in the
            callers frame.
        interactive : bool
            If True (default), the variables will be listed with the ``who``
            magic.


for name, obj in variables.items():<EOL><INDENT>if name in self.user_ns and self.user_ns[name] is obj:<EOL><INDENT>del self.user_ns[name]<EOL>self.user_ns_hidden.discard(name)<EOL><DEDENT><DEDENT>

Remove a dict of variables from the user namespace, if they are the
        same as the values in the dictionary.

        This is intended for use by extensions: variables that they've added can
        be taken back out if they are unloaded, without removing any that the
        user has overwritten.

        Parameters
        ----------
        variables : dict
          A dictionary mapping object names (as strings) to the objects.


def _ofind(self, oname, namespaces=None):

oname = oname.strip()<EOL>if not oname.startswith(ESC_MAGIC) andnot oname.startswith(ESC_MAGIC2) andnot py3compat.isidentifier(oname, dotted=True):<EOL><INDENT>return dict(found=False)<EOL><DEDENT>alias_ns = None<EOL>if namespaces is None:<EOL><INDENT>namespaces = [ ('<STR_LIT>', self.user_ns),<EOL>('<STR_LIT>', self.user_global_ns),<EOL>('<STR_LIT>', builtin_mod.__dict__),<EOL>('<STR_LIT>', self.alias_manager.alias_table),<EOL>]<EOL>alias_ns = self.alias_manager.alias_table<EOL><DEDENT>found = False; obj = None;  ospace = None;  ds = None;<EOL>ismagic = False; isalias = False; parent = None<EOL>if (oname == '<STR_LIT>' and not py3compat.PY3 and not(self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):<EOL><INDENT>return {'<STR_LIT>':found, '<STR_LIT>':obj, '<STR_LIT>':ospace,<EOL>'<STR_LIT>':ismagic, '<STR_LIT>':isalias, '<STR_LIT>':parent}<EOL><DEDENT>oname_parts = oname.split('<STR_LIT:.>')<EOL>oname_head, oname_rest = oname_parts[<NUM_LIT:0>],oname_parts[<NUM_LIT:1>:]<EOL>for nsname,ns in namespaces:<EOL><INDENT>try:<EOL><INDENT>obj = ns[oname_head]<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>for part in oname_rest:<EOL><INDENT>try:<EOL><INDENT>parent = obj<EOL>obj = getattr(obj,part)<EOL><DEDENT>except:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>found = True<EOL>ospace = nsname<EOL>if ns == alias_ns:<EOL><INDENT>isalias = True<EOL><DEDENT>break  <EOL><DEDENT><DEDENT><DEDENT>if not found:<EOL><INDENT>obj = None<EOL>if oname.startswith(ESC_MAGIC2):<EOL><INDENT>oname = oname.lstrip(ESC_MAGIC2)<EOL>obj = self.find_cell_magic(oname)<EOL><DEDENT>elif oname.startswith(ESC_MAGIC):<EOL><INDENT>oname = oname.lstrip(ESC_MAGIC)<EOL>obj = self.find_line_magic(oname)<EOL><DEDENT>else:<EOL><INDENT>obj = self.find_line_magic(oname)<EOL>if obj is None:<EOL><INDENT>obj = self.find_cell_magic(oname)<EOL><DEDENT><DEDENT>if obj is not None:<EOL><INDENT>found = True<EOL>ospace = '<STR_LIT>'<EOL>ismagic = True<EOL><DEDENT><DEDENT>if not found and oname_head in ["<STR_LIT>",'<STR_LIT>','<STR_LIT>','<STR_LIT:{}>','<STR_LIT>']:<EOL><INDENT>obj = eval(oname_head)<EOL>found = True<EOL>ospace = '<STR_LIT>'<EOL><DEDENT>return {'<STR_LIT>':found, '<STR_LIT>':obj, '<STR_LIT>':ospace,<EOL>'<STR_LIT>':ismagic, '<STR_LIT>':isalias, '<STR_LIT>':parent}<EOL>

Find an object in the available namespaces.

        self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic

        Has special code to detect magic functions.


if info.found:<EOL><INDENT>path = oname.split('<STR_LIT:.>')<EOL>root = '<STR_LIT:.>'.join(path[:-<NUM_LIT:1>])<EOL>if info.parent is not None:<EOL><INDENT>try:<EOL><INDENT>target = getattr(info.parent, '<STR_LIT>')<EOL>try:<EOL><INDENT>target = getattr(target, path[-<NUM_LIT:1>])<EOL>if isinstance(target, property):<EOL><INDENT>oname = root + '<STR_LIT>' + path[-<NUM_LIT:1>]<EOL>info = Struct(self._ofind(oname))<EOL><DEDENT><DEDENT>except AttributeError: pass<EOL><DEDENT>except AttributeError: pass<EOL><DEDENT><DEDENT>return info<EOL>

Second part of object finding, to look for property details.


def _object_find(self, oname, namespaces=None):

inf = Struct(self._ofind(oname, namespaces))<EOL>return Struct(self._ofind_property(oname, inf))<EOL>

Find an object and return a struct with info about it.


def _inspect(self, meth, oname, namespaces=None, **kw):

info = self._object_find(oname, namespaces)<EOL>if info.found:<EOL><INDENT>pmethod = getattr(self.inspector, meth)<EOL>formatter = format_screen if info.ismagic else None<EOL>if meth == '<STR_LIT>':<EOL><INDENT>pmethod(info.obj, oname, formatter)<EOL><DEDENT>elif meth == '<STR_LIT>':<EOL><INDENT>pmethod(info.obj, oname, formatter, info, **kw)<EOL><DEDENT>else:<EOL><INDENT>pmethod(info.obj, oname)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % oname)<EOL>return '<STR_LIT>'<EOL><DEDENT>

Generic interface to the inspector system.

        This function is meant to be called by pdef, pdoc & friends.


self.history_manager = HistoryManager(shell=self, config=self.config)<EOL>self.configurables.append(self.history_manager)<EOL>

Sets up the command history, and starts regular autosaves.


def set_custom_exc(self, exc_tuple, handler):

assert type(exc_tuple)==type(()) ,"<STR_LIT>"<EOL>def dummy_handler(self,etype,value,tb,tb_offset=None):<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>',etype)<EOL>print('<STR_LIT>',value)<EOL>print('<STR_LIT>',tb)<EOL><DEDENT>def validate_stb(stb):<EOL><INDENT>"""<STR_LIT>"""<EOL>msg = "<STR_LIT>" % stb<EOL>if stb is None:<EOL><INDENT>return []<EOL><DEDENT>elif isinstance(stb, str):<EOL><INDENT>return [stb]<EOL><DEDENT>elif not isinstance(stb, list):<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT>for line in stb:<EOL><INDENT>if not isinstance(line, str):<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT><DEDENT>return stb<EOL><DEDENT>if handler is None:<EOL><INDENT>wrapped = dummy_handler<EOL><DEDENT>else:<EOL><INDENT>def wrapped(self,etype,value,tb,tb_offset=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>stb = handler(self,etype,value,tb,tb_offset=tb_offset)<EOL>return validate_stb(stb)<EOL><DEDENT>except:<EOL><INDENT>self.set_custom_exc((), None)<EOL>print("<STR_LIT>", file=io.stderr)<EOL>stb = self.InteractiveTB.structured_traceback(*sys.exc_info())<EOL>print(self.InteractiveTB.stb2text(stb), file=io.stdout)<EOL>print("<STR_LIT>", file=io.stdout)<EOL>stb = self.InteractiveTB.structured_traceback(<EOL>(etype,value,tb), tb_offset=tb_offset<EOL>)<EOL><DEDENT>return stb<EOL><DEDENT><DEDENT>self.CustomTB = types.MethodType(wrapped,self)<EOL>self.custom_exceptions = exc_tuple<EOL>

set_custom_exc(exc_tuple,handler)

        Set a custom exception handler, which will be called if any of the
        exceptions in exc_tuple occur in the mainloop (specifically, in the
        run_code() method).

        Parameters
        ----------

        exc_tuple : tuple of exception classes
            A *tuple* of exception classes, for which to call the defined
            handler.  It is very important that you use a tuple, and NOT A
            LIST here, because of the way Python's except statement works.  If
            you only want to trap a single exception, use a singleton tuple::

                exc_tuple == (MyCustomException,)

        handler : callable
            handler must have the following signature::

                def my_handler(self, etype, value, tb, tb_offset=None):
                    ...
                    return structured_traceback

            Your handler must return a structured traceback (a list of strings),
            or None.

            This will be made into an instance method (via types.MethodType)
            of IPython itself, and it will be called if any of the exceptions
            listed in the exc_tuple are caught. If the handler is None, an
            internal basic one is used, which just prints basic info.

            To protect IPython from crashes, if your handler ever raises an
            exception or returns an invalid result, it will be immediately
            disabled.

        WARNING: by putting in your own exception handler into IPython's main
        execution loop, you run a very good chance of nasty crashes.  This
        facility should only be used if you really know what you are doing.