internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: ipython/ipython

Issue:
IPython.core.debugger.Tracer tab-complete
In the iPython 4.2.x series calling 

from IPython.core.debugger import Tracer; Tracer()()

allows  tab-completion .. This feature seems to have disappeared in iPython 5.x

Thanks

Carlos 



Discussion:
Can you try with `IPython.terminal.debugger` instead of `IPython.core.debugger`?

I've just noticed that there's no convenient way to start the debugger by importing from `IPython.terminal.debugger`. We should make something like a `set_trace()` function or a `Tracer()` class.

https://github.com/ipython/ipython/pull/9731 also will remove the Tracer() class for a simple API, that you can alredy use. 


Resolving patch:
diff --git a/IPython/core/debugger.py b/IPython/core/debugger.py
--- a/IPython/core/debugger.py
+++ b/IPython/core/debugger.py
@@ -82,7 +82,10 @@ def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
 
 
 class Tracer(object):
-    """Class for local debugging, similar to pdb.set_trace.
+    """
+    DEPRECATED
+
+    Class for local debugging, similar to pdb.set_trace.
 
     Instances of this class, when called, behave like pdb.set_trace, but
     providing IPython's enhanced capabilities.
@@ -96,7 +99,10 @@ class Tracer(object):
 
     @skip_doctest
     def __init__(self, colors=None):
-        """Create a local debugger instance.
+        """
+        DEPRECATED
+
+        Create a local debugger instance.
 
         Parameters
         ----------
@@ -197,7 +203,12 @@ def _file_lines(fname):
 
 
 class Pdb(OldPdb, object):
-    """Modified Pdb class, does not load readline."""
+    """Modified Pdb class, does not load readline.
+
+    for a standalone version that uses promtp_toolkit, see
+    `IPython.terminal.debugger.TerminalPdb` and
+    `IPython.terminal.debugger.set_trace()`
+    """
 
     def __init__(self, color_scheme=None, completekey=None,
                  stdin=None, stdout=None, context=5):
diff --git a/IPython/terminal/debugger.py b/IPython/terminal/debugger.py
--- a/IPython/terminal/debugger.py
+++ b/IPython/terminal/debugger.py
@@ -71,3 +71,7 @@ def cmdloop(self, intro=None):
             self.postloop()
         except Exception:
             raise
+
+def set_trace():
+    TerminalPdb().set_trace()
+


Test patch:
Repository: ipython/ipython

Issue:
IPython 5 shell does not react to SIGQUIT (CTRL + \)
In previous IPython versions it was possible to terminate an IPython session quickly by sending an `SIGQUIT`, i.e., by pressing <kbd>CTRL</kbd>+<kbd> \ </kbd>. This is useful when having an `embed()` in a loop with a large number of iterations. Pressing <kbd>CTRL</kbd>+<kbd>d</kbd> followed by <kbd>y</kbd> is not practical. Since `%kill_embedded` is currently also broken there is no convenient way to terminate the process.



Discussion:

Resolving patch:
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -26,6 +26,8 @@ def register_ipython_shortcuts(registry, shell):
                                  & insert_mode
                         ))(newline_or_execute_outer(shell))
 
+    registry.add_binding(Keys.ControlBackslash)(force_exit)
+
     registry.add_binding(Keys.ControlP,
                          filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
                         ))(previous_history_or_previous_completion)
@@ -145,6 +147,12 @@ def reset_search_buffer(event):
 def suspend_to_bg(event):
     event.cli.suspend_to_background()
 
+def force_exit(event):
+    """
+    Force exit (with a non-zero return value)
+    """
+    sys.exit("Quit")
+
 def indent_buffer(event):
     event.current_buffer.insert_text(' ' * 4)
 


Test patch:
Repository: ipython/ipython

Issue:
tools/github_stats.py still fails on two factor auth with app
See #9179. I think #9186 fixed it only for SMS codes, not for OTPs generated from a smartphone app.



Discussion:
Are you in the process of making a release ?


Resolving patch:
diff --git a/tools/gh_api.py b/tools/gh_api.py
--- a/tools/gh_api.py
+++ b/tools/gh_api.py
@@ -66,13 +66,13 @@ def get_auth_token():
     response = requests.post('https://api.github.com/authorizations',
                             auth=(user, pw), data=json.dumps(auth_request))
     if response.status_code == 401 and \
-       response.headers.get('X-GitHub-OTP') == 'required; sms':
-        print("Your login API resquest a SMS one time password", file=sys.stderr)
-        sms_pw = getpass.getpass("SMS password: ", stream=sys.stderr)
+            'required;' in response.headers.get('X-GitHub-OTP', ''):
+        print("Your login API requested a one time password", file=sys.stderr)
+        otp = getpass.getpass("One Time Password: ", stream=sys.stderr)
         response = requests.post('https://api.github.com/authorizations',
                             auth=(user, pw), 
                             data=json.dumps(auth_request),
-                            headers={'X-GitHub-OTP':sms_pw})
+                            headers={'X-GitHub-OTP':otp})
     response.raise_for_status()
     token = json.loads(response.text)['token']
     keyring.set_password('github', fake_username, token)


Test patch:
Repository: ipython/ipython

Issue:
impossible to exit debugger traces
I like to set traces, and from what I understand from the docs, The Right Way is to use `TerminalPdb`.
However, I can not find out how to quit the `TerminalPdb` debugger---maybe I'm just daft.
Say I set a trace in a long loop:

``` python
from IPython.terminal.debugger import TerminalPdb
pdb = TerminalPdb()

while True:
    pdb.set_trace()
```

The only way to exit this program that I found is to kill it.

My questions are:
- Is TerminalPdb the best way to set traces?
- Is this expected behavior?
- How do I quit?

Thanks!

(I'm on IPython 5.1.0)



Discussion:
> Is TerminalPdb the best way to set traces?

Likely. We added from `IPython.terminal.debugger:set_trace()` recently. There might better packages on PyPI that have more advance features. 

> Is this expected behavior?

I'm unsure. 

> How do I quit?

`IPython.embed()` have a `kill embed` that prevent a specific instance to be re-entered and add an ability to raise on exit. I'm still unsure why TerminalPdb  does not raise on exit like normal Pdb. 

Thanks for your quick reply.

My intuition would have been that `Ctrl + D` quits and `Ctrl + Z` suspends. `Ctrl + Z` does nothing, `Ctrl + D` skips to the next iteration, I think.

Being compatible with `pdb` would probably be the most intuitive for most users. I'm happy to work on it if it's something that should be reasonably easy.

> Thanks for your quick reply.
> 
> My intuition would have been that Ctrl + D quits and Ctrl + Z suspends. Ctrl + Z does nothing, Ctrl + D skips to the next iteration, I think.
> 
> Being compatible with pdb would probably be the most intuitive for most users. I'm happy to work on it if it's something that should be reasonably easy.

Yeah, that should not be too hard. 

It seem to be `IPython.core.debugger:Pdb.trace_dispatch` which explicitly silence `BdbQuit` since ec2d023d. I see why one would like to not raise on exit and vice-versa, so we can try to fing a compromise. 


Resolving patch:
diff --git a/IPython/core/debugger.py b/IPython/core/debugger.py
--- a/IPython/core/debugger.py
+++ b/IPython/core/debugger.py
@@ -283,12 +283,6 @@ def set_colors(self, scheme):
         self.color_scheme_table.set_active_scheme(scheme)
         self.parser.style = scheme
 
-    def trace_dispatch(self, frame, event, arg):
-        try:
-            return super(Pdb, self).trace_dispatch(frame, event, arg)
-        except bdb.BdbQuit:
-            pass
-
     def interaction(self, frame, traceback):
         try:
             OldPdb.interaction(self, frame, traceback)


Test patch:
Repository: ipython/ipython

Issue:
Autocompletion with Init-Signatures of C extension classes
I don't quite get the autocompletion to work with C extension classes. These classes have a Signature (at least since python 3.4 by utilizing `__text_signature__`) but it seems IPython cannot autocomplete the parameters in `__text_signature__`.

For example:

```
>>> import pickle
>>> import inspect
>>> inspect.Signature.from_callable(pickle.Pickler)
<Signature (file, protocol=None, fix_imports=True)>
```

Note that the signature is saved as `__text_signature__`-attribute on ``pickle.Pickle``.

I would expect that after printing`pickle.Pickler(` and then hitting TAB it would show:
```
file=
protocol=
fix_imports=
# other stuff
```
but it doesn't. 

Classes seem to be special in this regard - IPython is definitly able to get the parameters for functions and methods! It just doesn't work for classes.


Discussion:
Thank you for your report. I have a patch I'll try to put up later on today that should solve this issue.


Resolving patch:
diff --git a/IPython/utils/dir2.py b/IPython/utils/dir2.py
--- a/IPython/utils/dir2.py
+++ b/IPython/utils/dir2.py
@@ -41,6 +41,9 @@ def dir2(obj):
         # TypeError: dir(obj) does not return a list
         words = set()
 
+    if safe_hasattr(obj, '__class__'):
+        words |= set(dir(obj.__class__))
+
     # filter out non-string attributes which may be stuffed by dir() calls
     # and poor coding in third-party modules
 


Test patch:
Repository: ipython/ipython

Issue:
Importing pyplot causes bouncing dock icon on mac
This is illustrated by the following gif:

![image](http://g.recordit.co/ARO7Maic0K.gif)

Importing pyplot in the normal python repl causes the python rocket icon to appear but not bounce distractingly. Importing it inside IPython causes the icon to bounce annoyingly for almost a minute.

This is using a framework build of Python from Homebrew.



Discussion:
which backend are you using?  Does running `plt.ion()` or `%matplotlib` help?

My knee-jerk / making this up as I go guess is: When IPython de-coupled from readline, it also decoupled from the `PyOS_InputHook` machinery.   In the plain python case, the GUI is starting up (starting the bouncing), the GUI code installs the hook, and when it finishes starting up some how phones home to let the rocket know to stop bouncing because the gui main loop runs intercolated with the repl.  In IPython, that hook is still installed, but does not matter because IPython is running through prompt toolkit.  If you start up the IPython event loop integration the GUI will phone home and stop the bouncing.

Or I could be wildly off base.
This is using the `MacOSX` backend. Using `plt.ion()` or `%matplotlib` after the `pyplot` import doesn't stop the bouncing and using `%matplotlib` before doing the pyplot import just causes the icon to start bouncing.
Does it happen with the tk backend?
Nope, no rocket icon at all with `TkAgg`.
I'm going to stay that's linked to #9312 
I'm going to try to understand it. Ping  @minrk.
I'm going to say that [this](https://github.com/ipython/ipython/blob/efc9e7678bdb10b47f60289f47c355d6b8be4048/IPython/terminal/pt_inputhooks/osx.py#L134-L135):

```python
    if not window_count:
        return
```

Need to be removed as the eventloop integration need to run even if there is no windows... it appears to be working for me. 
Alternative would be to make sure  `inputhook(context)` does at least one loop even if no windows.. so along:

```python
    global at_least_once
    if not window_count and not at_least_once:
        at_least_once = True
        return
```
@ngoldbaum would you mind trying ? 
Also I suppose it stop bouncing as soon as you have your first window ? 


The screen recording also make me happy because it is realistic in its typing, and make me feel less guilty about my horrendous typing. 
Indeed, removing that 

```
if not window_count:
    return
```

block fixes the issue for me. And as you suspected, creating a plot stops the bouncing.

Resolving patch:
diff --git a/IPython/terminal/pt_inputhooks/osx.py b/IPython/terminal/pt_inputhooks/osx.py
--- a/IPython/terminal/pt_inputhooks/osx.py
+++ b/IPython/terminal/pt_inputhooks/osx.py
@@ -127,12 +127,6 @@ def _stop_on_read(fd):
 def inputhook(context):
     """Inputhook for Cocoa (NSApp)"""
     NSApp = _NSApp()
-    window_count = msg(
-        msg(NSApp, n('windows')),
-        n('count')
-    )
-    if not window_count:
-        return
     _stop_on_read(context.fileno())
     msg(NSApp, n('run'))
     if not _triggered.is_set():


Test patch:
Repository: ipython/ipython

Issue:
End of multiline string that contains a backslash-terminated line is not recognized
IPython 5.0/PTK1.0.5 does not recognize that

```
"""
foo\
bar
"""
```

is a full string and that it should execute the typed-in string after that point.



Discussion:
You can use Esc-Enter in the meantime to force execution. 


Resolving patch:
diff --git a/IPython/core/inputtransformer.py b/IPython/core/inputtransformer.py
--- a/IPython/core/inputtransformer.py
+++ b/IPython/core/inputtransformer.py
@@ -120,25 +120,18 @@ class TokenInputTransformer(InputTransformer):
     """
     def __init__(self, func):
         self.func = func
-        self.current_line = ""
-        self.line_used = False
+        self.buf = []
         self.reset_tokenizer()
-    
+
     def reset_tokenizer(self):
-        self.tokenizer = generate_tokens(self.get_line)
-    
-    def get_line(self):
-        if self.line_used:
-            raise TokenError
-        self.line_used = True
-        return self.current_line
-    
+        it = iter(self.buf)
+        self.tokenizer = generate_tokens(it.__next__)
+
     def push(self, line):
-        self.current_line += line + "\n"
-        if self.current_line.isspace():
+        self.buf.append(line + '\n')
+        if all(l.isspace() for l in self.buf):
             return self.reset()
-        
-        self.line_used = False
+
         tokens = []
         stop_at_NL = False
         try:
@@ -158,13 +151,13 @@ def push(self, line):
         return self.output(tokens)
     
     def output(self, tokens):
-        self.current_line = ""
+        self.buf.clear()
         self.reset_tokenizer()
         return untokenize(self.func(tokens)).rstrip('\n')
     
     def reset(self):
-        l = self.current_line
-        self.current_line = ""
+        l = ''.join(self.buf)
+        self.buf.clear()
         self.reset_tokenizer()
         if l:
             return l.rstrip('\n')


Test patch:
diff --git a/IPython/core/tests/test_inputtransformer.py b/IPython/core/tests/test_inputtransformer.py
--- a/IPython/core/tests/test_inputtransformer.py
+++ b/IPython/core/tests/test_inputtransformer.py
@@ -389,6 +389,11 @@ def test_assemble_python_lines():
        (u"2,", None),
        (None, u"a = [1,\n2,"),
       ],
+      [(u"a = '''", None),  # Test line continuation within a multi-line string
+       (u"abc\\", None),
+       (u"def", None),
+       (u"'''", u"a = '''\nabc\\\ndef\n'''"),
+      ],
     ] + syntax_ml['multiline_datastructure']
     for example in tests:
         transform_checker(example, ipt.assemble_python_lines)
Repository: ipython/ipython

Issue:
remove usage of backports.shutil_get_terminal_size
This is for pre-3.3 Python.

Pretty easy it should only require deleting lines. 
Maybe a few need to be dedented.


Discussion:

Resolving patch:
diff --git a/IPython/utils/terminal.py b/IPython/utils/terminal.py
--- a/IPython/utils/terminal.py
+++ b/IPython/utils/terminal.py
@@ -15,11 +15,7 @@
 import os
 import sys
 import warnings
-try:
-    from shutil import get_terminal_size as _get_terminal_size
-except ImportError:
-    # use backport on Python 2
-    from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
+from shutil import get_terminal_size as _get_terminal_size
 
 from . import py3compat
 


Test patch:
Repository: ipython/ipython

Issue:
Jedi: Protect against crash on property access
Jedi Completions object can raise on attribute access (eg `completion.type`).

Completer.py ~ line 1520 should protect arount that:

```
       for jm in jedi_matches:
            delta = len(jm.name_with_symbols) - len(jm.complete)
            try:
                yield Completion(start=offset - delta, end=offset, text=jm.name_with_symbols, type=jm.type, _origin='jedi')
            except Exception:
                print('crash with jm:',jm)

````


Reproducible with 

```
## foo.py
def foo():pass
```

```
In[1]: from foo import foo
In[2] foo.__co<tab>
```

Log an error when debug is on would be a plus.


Discussion:

Resolving patch:
diff --git a/IPython/core/completer.py b/IPython/core/completer.py
--- a/IPython/core/completer.py
+++ b/IPython/core/completer.py
@@ -1554,11 +1554,17 @@ def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Compl
         iter_jm = iter(jedi_matches)
         if _timeout:
             for jm in iter_jm:
+                try:
+                    type_ = jm.type
+                except Exception:
+                    if self.debug:
+                        print("Error in Jedi getting type of ", jm)
+                    type_ = None
                 delta = len(jm.name_with_symbols) - len(jm.complete)
                 yield Completion(start=offset - delta,
                                  end=offset,
                                  text=jm.name_with_symbols,
-                                 type=jm.type,
+                                 type=type_,
                                  _origin='jedi')
 
                 if time.monotonic() > deadline:


Test patch:
Repository: ipython/ipython

Issue:
TAB key does not indent
In the git version of IPython, type

```
def foo(a):
    pass<ENTER>
```

The new line is not correctly indented, and the tab key does not insert 4 spaces.

/cc @Carreau @takluyver 



Discussion:
Note that tab also try to complete, so we might want to indent only on empty line. 

Hi Stefan!

The auto-dedenting is correct, I think - when you use something like `return`, `continue`, `break`, or `pass`, it dedents, because that normally means you've finished the indented block.

Good catch on using the tab key for indentation as well as completion, though - that should work.

Better description of @stefanv problem, `|` is the cursor `<enter>` mean pressing enter.

```
In [1]: def foo():|<enter>
   ...:     1
   ...:
```

result: 

```
In [1]: def foo():
   ...:|
   ...:     1
   ...:
```


Resolving patch:
diff --git a/IPython/terminal/shortcuts.py b/IPython/terminal/shortcuts.py
--- a/IPython/terminal/shortcuts.py
+++ b/IPython/terminal/shortcuts.py
@@ -100,12 +100,14 @@ def newline_or_execute(event):
                 b.cancel_completion()
             return
 
-        if not (d.on_last_line or d.cursor_position_row >= d.line_count
-            - d.empty_line_count_at_the_end()):
-            b.newline()
-            return
+        before_text = d.text[:d.cursor_position]
+        status, indent = shell.input_splitter.check_complete(before_text + '\n')
 
-        status, indent = shell.input_splitter.check_complete(d.text + '\n')
+        if not (d.on_last_line or
+                d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
+                ):
+            b.insert_text('\n' + (' ' * (indent or 0)))
+            return
 
         if (status != 'incomplete') and b.accept_action.is_returnable:
             b.accept_action.validate_and_handle(event.cli, b)


Test patch:
Repository: ipython/ipython

Issue:
typing should not be a dependency for python>=3.5
https://github.com/ipython/ipython/commit/3ff1be2ea8ef180a6f17a6a03a3f8452303b9abe added `typing` as an `install_requires`.  This package is builtin for python>=3.5, so it should be protected by an environment marker (just like `pathlib2`) in setup.py.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -202,7 +202,6 @@ def run(self):
 install_requires = [
     'setuptools>=18.5',
     'jedi>=0.10',
-    'typing',
     'decorator',
     'pickleshare',
     'simplegeneric>0.8',
@@ -218,6 +217,7 @@ def run(self):
 extras_require.update({
     'test:python_version >= "3.4"': ['numpy'],
     ':python_version == "3.3"': ['pathlib2'],
+    ':python_version <= "3.4"': ['typing'],
     ':sys_platform != "win32"': ['pexpect'],
     ':sys_platform == "darwin"': ['appnope'],
     ':sys_platform == "win32"': ['colorama'],


Test patch:
Repository: ipython/ipython

Issue:
Add help string for xmode
When an exception occurs, IPython displays it with its own fancy traceback formatter. I don't mind the coloured output, but the visually expanded display feels much more cumbersome to me with long tracebacks. I would therefore like to revert to the standard Python excepthook

Unfortunately, setting `__excepthook__` from the console doesn't work (IPython overrides the newly-set value), therefore it would be nice to get a configuration option for it.



Discussion:
Ok, it looks like it's already there as `TerminalInteractiveShell.xmode`. The documentation (https://ipython.org/ipython-doc/dev/config/options/terminal.html) doesn't provide any description for it, so it's not easy to find.


Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -389,7 +389,9 @@ def _prompt_trait_changed(self, change):
     separate_out2 = SeparateUnicode('').tag(config=True)
     wildcards_case_sensitive = Bool(True).tag(config=True)
     xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
-                            default_value='Context').tag(config=True)
+                            default_value='Context',
+                            help="Switch modes for the IPython exception handlers."
+                            ).tag(config=True)
 
     # Subcomponents of InteractiveShell
     alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)


Test patch:
Repository: ipython/ipython

Issue:
BUG: (Unintended?) Interaction between -n and -i arguments to %run
The documentation states that `-i` would run the script in the present notebook's namespace while `-n` would prevent the `__name__` in the script from being set to `__main__`, thereby preventing execution of code hidden behind the `if __name__ == '__main__':` check.

However, [the code](https://github.com/ipython/ipython/blob/master/IPython/core/magics/execution.py#L665) only takes the `-n` into account only if `-i` is NOT passed to the `%run` (i.e. in the `else` branch).

Shouldn't it be handled before checking for `-i`?

Or is it necessary to change the `__name__` of the program set to `__main__` to run it in the namespace of the notebook?


Discussion:

Resolving patch:
diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py
--- a/IPython/core/magics/execution.py
+++ b/IPython/core/magics/execution.py
@@ -649,23 +649,24 @@ def run(self, parameter_s='', runner=None,
 
         sys.argv = [filename] + args  # put in the proper filename
 
+        if 'n' in opts:
+            name = os.path.splitext(os.path.basename(filename))[0]
+        else:
+            name = '__main__'
+
         if 'i' in opts:
             # Run in user's interactive namespace
             prog_ns = self.shell.user_ns
             __name__save = self.shell.user_ns['__name__']
-            prog_ns['__name__'] = '__main__'
+            prog_ns['__name__'] = name
             main_mod = self.shell.user_module
-            
+
             # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
             # set the __file__ global in the script's namespace
             # TK: Is this necessary in interactive mode?
             prog_ns['__file__'] = filename
         else:
             # Run in a fresh, empty namespace
-            if 'n' in opts:
-                name = os.path.splitext(os.path.basename(filename))[0]
-            else:
-                name = '__main__'
 
             # The shell MUST hold a reference to prog_ns so after %run
             # exits, the python deletion mechanism doesn't zero it out


Test patch: