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

Issue:
Exception before prompting for password during ssh connection
### Setup

Win 7 x64

ipython==0.12.1
paramiko==1.7.7.2
pyzmq==2.2.0
### Issue

I want to connect an IPython qtconsole on Windows to an IPython kernel on a remote linux box through ssh2.

I made the following changes in `ipython_qtconsole_config.py`:

``` python
#### Path to the ssh key to use for logging in to the ssh server.
import os
c.IPythonQtConsoleApp.sshkey = os.path.expanduser('~')+'\\.ssh\\id_dsa'
```

When I run
`ipython qtconsole --IPythonQtConsoleApp.sshserver='user@hostname' --existing kernel-21449.json`

I receive:

```
[IPythonQtConsoleApp] Could not setup tunnels
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\frontend\consoleapp.py", line 289, in init_ssh
    newports = tunnel_to_kernel(info, self.sshserver, self.sshkey)
  File "C:\Python27\lib\site-packages\IPython\lib\kernel.py", line 248, in tunnel_to_kernel
    password = getpass("SSH Password for %s: "%sshserver)
  File "C:\Python27\lib\getpass.py", line 95, in win_getpass
    msvcrt.putch(c)
TypeError: must be char, not unicode
```

For now, I edited IPython/lib/kernel.py:248 as a temporary workaround in the following way:

``` python
password = getpass("SSH Password for %s: "%sshserver.encode('ascii','ignore'))
```



Discussion:

Resolving patch:
diff --git a/IPython/kernel/connect.py b/IPython/kernel/connect.py
--- a/IPython/kernel/connect.py
+++ b/IPython/kernel/connect.py
@@ -38,7 +38,7 @@
 from IPython.core.profiledir import ProfileDir
 from IPython.utils.localinterfaces import LOCALHOST
 from IPython.utils.path import filefind, get_ipython_dir
-from IPython.utils.py3compat import str_to_bytes, bytes_to_str
+from IPython.utils.py3compat import str_to_bytes, bytes_to_str, cast_bytes_py2
 from IPython.utils.traitlets import (
     Bool, Integer, Unicode, CaselessStrEnum,
 )
@@ -360,7 +360,7 @@ def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
     if tunnel.try_passwordless_ssh(sshserver, sshkey):
         password=False
     else:
-        password = getpass("SSH Password for %s: "%sshserver)
+        password = getpass("SSH Password for %s: " % cast_bytes_py2(sshserver))
     
     for lp,rp in zip(lports, rports):
         tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password)


Test patch:
Repository: ipython/ipython

Issue:
ipython profile locate should also work
I know we have `ipython locate` and from it stems `ipython locate profile foo`, but this is awkward, because you get informed of the latter and want to use it when you look at `ipython profile --help` and it would make sense to have locating a profile work as a sub-command of profile.

currently: `ipython locate profile foo`
I want to: `ipython profile locate foo` , since we already have `ipython profile create` and `ipython profile list`.
#1762 originally implemented `locate`, so pinging @minrk - like I always do :) Hi Min! :beers:



Discussion:
Min originally implemented it with both `ipython locate profile` and `ipython profile locate`. It was me who complained that we should just have one command for it, though I remain ambivalent about which is better.

Personally, I would prefer adding 'profile locate' as an undocumented entry point, just for those who prefer to think hierarchically rather than grammatically.


Resolving patch:
diff --git a/IPython/core/profileapp.py b/IPython/core/profileapp.py
--- a/IPython/core/profileapp.py
+++ b/IPython/core/profileapp.py
@@ -121,7 +121,7 @@ def list_bundled_profiles():
 
 
 class ProfileLocate(BaseIPythonApplication):
-    description = """print the path an IPython profile dir"""
+    description = """print the path to an IPython profile dir"""
     
     def parse_command_line(self, argv=None):
         super(ProfileLocate, self).parse_command_line(argv)
@@ -299,6 +299,7 @@ class ProfileApp(Application):
     subcommands = Dict(dict(
         create = (ProfileCreate, ProfileCreate.description.splitlines()[0]),
         list = (ProfileList, ProfileList.description.splitlines()[0]),
+        locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]),
     ))
 
     def start(self):
@@ -310,4 +311,3 @@ def start(self):
             self.exit(1)
         else:
             return self.subapp.start()
-


Test patch:
Repository: ipython/ipython

Issue:
Always checkpoint al least once ?
When downloading notebook directly to hard drive, we should probably do a checkpoint on first open, always.



Discussion:
An interesting question. I think that probably makes sense.

Yep, I agree...


Resolving patch:
diff --git a/IPython/html/services/notebooks/filenbmanager.py b/IPython/html/services/notebooks/filenbmanager.py
--- a/IPython/html/services/notebooks/filenbmanager.py
+++ b/IPython/html/services/notebooks/filenbmanager.py
@@ -222,6 +222,10 @@ def save_notebook_model(self, model, name='', path=''):
 
         if 'content' not in model:
             raise web.HTTPError(400, u'No notebook JSON data provided')
+        
+        # One checkpoint should always exist
+        if self.notebook_exists(name, path) and not self.list_checkpoints(name, path):
+            self.create_checkpoint(name, path)
 
         new_path = model.get('path', path).strip('/')
         new_name = model.get('name', name)
@@ -326,8 +330,9 @@ def rename_notebook(self, old_name, old_path, new_name, new_path):
     def get_checkpoint_path(self, checkpoint_id, name, path=''):
         """find the path to a checkpoint"""
         path = path.strip('/')
+        basename, _ = os.path.splitext(name)
         filename = u"{name}-{checkpoint_id}{ext}".format(
-            name=name,
+            name=basename,
             checkpoint_id=checkpoint_id,
             ext=self.filename_ext,
         )
diff --git a/IPython/html/services/notebooks/nbmanager.py b/IPython/html/services/notebooks/nbmanager.py
--- a/IPython/html/services/notebooks/nbmanager.py
+++ b/IPython/html/services/notebooks/nbmanager.py
@@ -117,7 +117,7 @@ def delete_notebook_model(self, name, path=''):
         raise NotImplementedError('must be implemented in a subclass')
 
     def create_notebook_model(self, model=None, path=''):
-        """Create a new untitled notebook and return its model with no content."""
+        """Create a new notebook and return its model with no content."""
         path = path.strip('/')
         if model is None:
             model = {}


Test patch:
Repository: ipython/ipython

Issue:
Error on empty c.Session.key
Adding `c.Session.key = ''` to the default (i.e. empty except for `c = get_config()`) `ipython_config.py` results in the following error when starting `ipython console`:

```
[ZMQTerminalIPythonApp] CRITICAL | Bad config encountered during initialization:
[ZMQTerminalIPythonApp] CRITICAL | The 'key' trait of a Session instance must be a string, but a value of '' <class 'str'> was specified.
```

I [originally](https://github.com/gibiansky/IHaskell/issues/15) opened this issue on IHaskell, but it seems to be a problem with IPython itself. Some more info:

```
{'codename': 'Work in Progress',
 'commit_hash': b'6fcfc4d',
 'commit_source': 'repository',
 'default_encoding': 'UTF-8',
 'ipython_path': '/home/koomi/ipython/IPython',
 'ipython_version': '2.0.0-dev',
 'os_name': 'posix',
 'platform': 'Linux-3.11.5-1-ARCH-x86_64-with-arch',
 'sys_executable': '/usr/bin/python',
 'sys_platform': 'linux',
 'sys_version': '3.3.2 (default, Sep  6 2013, 09:30:10) \n[GCC 4.8.1 20130725 (prerelease)]'}
```



Discussion:
It should actually be bytes, i.e. `b''`. That error message isn't very helpful, especially under Python 3. I'll see if I can do something about it.


Resolving patch:
diff --git a/IPython/utils/traitlets.py b/IPython/utils/traitlets.py
--- a/IPython/utils/traitlets.py
+++ b/IPython/utils/traitlets.py
@@ -996,7 +996,7 @@ class Bytes(TraitType):
     """A trait for byte strings."""
 
     default_value = b''
-    info_text = 'a string'
+    info_text = 'a bytes object'
 
     def validate(self, obj, value):
         if isinstance(value, bytes):


Test patch:
Repository: ipython/ipython

Issue:
Test for whether inside virtualenv does not work if directory is symlinked
The following test for whether IPython is running inside a virtualenv does not work if the python executable and the VIRTUAL_ENV variable are at the same place but one is at a symlinked path to the other: https://github.com/ipython/ipython/blob/5bf4949fbd30de6211226e4b27e8680c4b199fc9/IPython/core/interactiveshell.py#L719

Discovered when using invewrapper, but problem appears more generic: https://github.com/berdario/invewrapper/issues/8

```
tcorbettclark@cmed1:~$ python -c "import IPython; print(IPython.sys_info())"
{'codename': 'An Afternoon Hack',
 'commit_hash': '7c2ea3a',
 'commit_source': 'installation',
 'default_encoding': 'UTF-8',
 'ipython_path': '/home/tcorbettclark/.virtualenvs/ice/local/lib/python2.7/site-packages/IPython',
 'ipython_version': '1.1.0',
 'os_name': 'posix',
 'platform': 'Linux-3.5.0-42-generic-x86_64-with-Ubuntu-12.10-quantal',
 'sys_executable': '/home/tcorbettclark/.virtualenvs/ice/bin/python',
 'sys_platform': 'linux2',
 'sys_version': '2.7.3 (default, Sep 26 2013, 16:35:25) \n[GCC 4.7.2]'}
tcorbettclark@cmed1:~$ 
```



Discussion:

Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -716,7 +716,9 @@ def init_virtualenv(self):
             # Not in a virtualenv
             return
         
-        if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
+        if os.path.realpath(sys.executable).startswith(
+            os.path.realpath(os.environ['VIRTUAL_ENV'])
+        ):
             # Running properly in the virtualenv, don't need to do anything
             return
         


Test patch:
Repository: ipython/ipython

Issue:
`ipython console` doesn't send a `shutdown_request`
When shutting down in any method, `ipython console` does not send the `shutdown_request` message to the language kernel. 

According to the [documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#kernel-shutdown), this should be sending the `shutdown_request` message.

As a result, it's difficult in an external language kernel to detect when the kernel should shut down, and the kernel process just ends up hanging around in the background forever.



Discussion:

Resolving patch:
diff --git a/IPython/terminal/console/interactiveshell.py b/IPython/terminal/console/interactiveshell.py
--- a/IPython/terminal/console/interactiveshell.py
+++ b/IPython/terminal/console/interactiveshell.py
@@ -121,7 +121,7 @@ def init_completer(self):
 
         This creates completion machinery that can be used by client code,
         either interactively in-process (typically triggered by the readline
-        library), programatically (such as in test suites) or out-of-prcess
+        library), programmatically (such as in test suites) or out-of-process
         (typically over the network by remote frontends).
         """
         from IPython.core.completerlib import (module_completer,
@@ -141,6 +141,11 @@ def init_completer(self):
         if self.has_readline:
             self.set_readline_completer()
     
+    def ask_exit(self):
+        super(ZMQTerminalInteractiveShell, self).ask_exit()
+        if self.exit_now and self.manager:
+            self.client.shutdown()
+    
     def run_cell(self, cell, store_history=True):
         """Run a complete IPython cell.
         


Test patch:
Repository: ipython/ipython

Issue:
Fix bug with non ascii passwords in notebook login
When a password is entered with non ascii characters, a `500: Internal Server Error` is returned.
I don't think non ascii passwords should be supported, but a 'Invalid password' message should be returned.

```
2013-11-12 11:43:19.608 [tornado.application] ERROR | Uncaught exception POST /login?next=%2F (127.0.0.1)
HTTPRequest(protocol='http', host='127.0.0.1:8888', method='POST', uri='/login?next=%2F', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Origin': 'http://127.0.0.1:8888', 'Content-Length': '63', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip,deflate,sdch', 'Host': '127.0.0.1:8888', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36', 'Connection': 'keep-alive', 'Referer': 'http://127.0.0.1:8888/login', 'Content-Type': 'application/x-www-form-urlencoded'})
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1141, in _when_complete
    callback()
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1162, in _execute_method
    self._when_complete(method(*self.path_args, **self.path_kwargs),
  File "C:\Python27\lib\site-packages\IPython\html\auth\login.py", line 48, in post
    if passwd_check(self.password, pwd):
  File "C:\Python27\lib\site-packages\IPython\lib\security.py", line 116, in passwd_check
    h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)
```



Discussion:
I think we should aim to support non-ascii passwords properly. I'll look into it.


Resolving patch:
diff --git a/IPython/lib/security.py b/IPython/lib/security.py
--- a/IPython/lib/security.py
+++ b/IPython/lib/security.py
@@ -113,6 +113,6 @@ def passwd_check(hashed_passphrase, passphrase):
     if len(pw_digest) == 0:
         return False
 
-    h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
+    h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii'))
 
     return h.hexdigest() == pw_digest


Test patch:
diff --git a/IPython/lib/tests/test_security.py b/IPython/lib/tests/test_security.py
--- a/IPython/lib/tests/test_security.py
+++ b/IPython/lib/tests/test_security.py
@@ -1,3 +1,4 @@
+# coding: utf-8
 from IPython.lib import passwd
 from IPython.lib.security import passwd_check, salt_len
 import nose.tools as nt
@@ -19,3 +20,7 @@ def test_bad():
     nt.assert_equal(passwd_check(p, 'a:b:c:d'), False)
     nt.assert_equal(passwd_check(p, 'a:b'), False)
 
+def test_passwd_check_unicode():
+    # GH issue #4524
+    phash = u'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f'
+    assert passwd_check(phash, u"łe¶ŧ←↓→")
\ No newline at end of file
Repository: ipython/ipython

Issue:
remove `Configurable.created` ?
What is the point of `Configurable.created` ? it does not seem to be use anywhere : 

```
$ ack '\.created' **/*.py
IPython/config/configurable.py 105:        self.created = datetime.datetime.now()
IPython/nbformat/v2/nbbase.py 159:        metadata.created = unicode_type(created)
IPython/nbformat/v2/tests/test_nbbase.py 109:        self.assertEqual(md.created, u'today')
IPython/nbformat/v3/nbbase.py 195:        metadata.created = cast_unicode(created)
IPython/nbformat/v3/tests/test_nbbase.py 139:        self.assertEqual(md.created, u'today')
```



Discussion:

Resolving patch:
diff --git a/IPython/config/configurable.py b/IPython/config/configurable.py
--- a/IPython/config/configurable.py
+++ b/IPython/config/configurable.py
@@ -26,7 +26,6 @@
 # Imports
 #-----------------------------------------------------------------------------
 
-import datetime
 from copy import deepcopy
 
 from .loader import Config, LazyConfigValue
@@ -55,7 +54,6 @@ class Configurable(HasTraits):
 
     config = Instance(Config, (), {})
     parent = Instance('IPython.config.configurable.Configurable')
-    created = None
 
     def __init__(self, **kwargs):
         """Create a configurable given a config config.
@@ -102,7 +100,6 @@ def __init__(self, config=None):
         # This should go second so individual keyword arguments override
         # the values in config.
         super(Configurable, self).__init__(**kwargs)
-        self.created = datetime.datetime.now()
 
     #-------------------------------------------------------------------------
     # Static trait notifiations


Test patch:
Repository: ipython/ipython

Issue:
IOStream IP address configurable
Hi,

I am running in an environment where I can not bind to 127.0.0.1 ... possible to make this configurable?

https://github.com/ipython/ipython/blob/master/IPython/kernel/zmq/iostream.py#L68



Discussion:
I think I will go with disabling subprocess output forwarding, rather than a configurable address. What environment are you in where binding to localhost is not allowed?


Resolving patch:
diff --git a/IPython/kernel/zmq/iostream.py b/IPython/kernel/zmq/iostream.py
--- a/IPython/kernel/zmq/iostream.py
+++ b/IPython/kernel/zmq/iostream.py
@@ -20,6 +20,7 @@
 
 from IPython.utils import py3compat
 from IPython.utils.py3compat import unicode_type
+from IPython.utils.warn import warn
 
 #-----------------------------------------------------------------------------
 # Globals
@@ -65,7 +66,16 @@ def _setup_pipe_in(self):
         
         self._pipe_in = ctx.socket(zmq.PULL)
         self._pipe_in.linger = 0
-        self._pipe_port = self._pipe_in.bind_to_random_port("tcp://127.0.0.1")
+        try:
+            self._pipe_port = self._pipe_in.bind_to_random_port("tcp://127.0.0.1")
+        except zmq.ZMQError as e:
+            warn("Couldn't bind IOStream to 127.0.0.1: %s" % e +
+                "\nsubprocess output will be unavailable."
+            )
+            self._pipe_flag = False
+            self._pipe_in.close()
+            del self._pipe_in
+            return
         self._pipe_poller = zmq.Poller()
         self._pipe_poller.register(self._pipe_in, zmq.POLLIN)
     
@@ -89,7 +99,7 @@ def _have_pipe_out(self):
     def _check_mp_mode(self):
         """check for forks, and switch to zmq pipeline if necessary"""
         if not self._pipe_flag or self._is_master_process():
-                return MASTER
+            return MASTER
         else:
             if not self._have_pipe_out():
                 self._flush_buffer()


Test patch:
Repository: ipython/ipython

Issue:
Missing "if __name__ == '__main__':" check in /usr/bin/ipython
When executed, the top level ipython script always launches a new instance, even if the module is not being executed as `__main__`.

This is currently being worked around in the standard library (by special casing IPython), but the correct fix is for IPython to not launch a new instance when the module is being run as anything other than `__main__`.



Discussion:
/usr/bin/Ipython is not ment to be imported it should only be used to run ipython from the command line, so it has no reason to check for **main** , or I'm missing something. 

Also what are you refering to when you speak of standard lib?  What are you trying to achieve ?

Envoyé de mon iPhone

> Le 15 déc. 2013 à 12:47, ncoghlan notifications@github.com a écrit :
> 
> When executed, the top level ipython script always launches a new instance, even if the module is not being executed as main.
> 
> This is currently being worked around in the standard library (by special casing IPython), but the correct fix is for IPython to not launch a new instance when the module is being run as anything other than main.
> 
> —
> Reply to this email directly or view it on GitHub.

All scripts should use the `if __name__ == '__main__':` boilerplate even if you never intend them to be imported. `multiprocessing` on Windows, due to the lack of a proper OS `fork()`, imports the main module as non-`__main__` to set up the environment for the subprocesses. If the executable stuff is not guarded by the `if __name__ == '__main__':` boilerplate, then each subprocess will start executing the usual main process stuff and never let the `multiprocessing` subprocess stuff run. Here is the stdlib workaround Nick is referring to, I believe:

http://hg.python.org/cpython/file/51dddfead80a/Lib/multiprocessing/spawn.py#l230

I've run into that - I wish they had decided against supporting multiprocessing on Windows, given its many inconsistencies with other platforms.


Resolving patch:
diff --git a/setupbase.py b/setupbase.py
--- a/setupbase.py
+++ b/setupbase.py
@@ -336,8 +336,9 @@ def find_entry_points():
 
 script_src = """#!{executable}
 # This script was automatically generated by setup.py
-from {mod} import {func}
-{func}()
+if __name__ == '__main__':
+    from {mod} import {func}
+    {func}()
 """
 
 class build_scripts_entrypt(build_scripts):


Test patch:
Repository: ipython/ipython

Issue:
Static URLs are not auto-versioned
In master, static URLs are not auto-versioned; Ej:

``` html
    <script src="/static/components/requirejs/require.js" type="text/javascript" charset="utf-8"></script>
```

on #ipython@freenode,  _minrk_ sayd 

> I think it's a regression from when we switched to jinja templates

thanks



Discussion:

Resolving patch:
diff --git a/IPython/html/base/handlers.py b/IPython/html/base/handlers.py
--- a/IPython/html/base/handlers.py
+++ b/IPython/html/base/handlers.py
@@ -193,8 +193,9 @@ def template_namespace(self):
             logged_in=self.logged_in,
             login_available=self.login_available,
             use_less=self.use_less,
+            static_url=self.static_url,
         )
-
+    
     def get_json_body(self):
         """Return the body of the request as JSON data."""
         if not self.request.body:
@@ -329,13 +330,16 @@ def get_absolute_path(cls, roots, path):
                 abspath = os.path.abspath(filefind(path, roots))
             except IOError:
                 # IOError means not found
-                raise web.HTTPError(404)
+                return ''
             
             cls._static_paths[path] = abspath
             return abspath
     
     def validate_absolute_path(self, root, absolute_path):
         """check if the file should be served (raises 404, 403, etc.)"""
+        if absolute_path == '':
+            raise web.HTTPError(404)
+        
         for root in self.root:
             if (absolute_path + os.sep).startswith(root):
                 break


Test patch: