internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: aio-libs-abandoned/aioredis-py

Issue:
socket_keepalive_options typing issue
### Describe the bug

#960 has set the type annotation for `socket_keepalive_options` to `Optional[Dict[str, Any]]` but it should be actually `Optional[Dict[int, Any]]` because the underlying `socket.setsockopt()` API accepts the second argument as only the flag values (e.g., `socket.TCP_KEEPIDLE`) instead of the stringified symbol names (e.g., `"TCP_KEEPIDLE"`).

### To Reproduce

```python3
import asyncio
import aioredis

async def main():
    r = aioredis.from_url(
        "redis://localhost:6379",
        socket_keepalive=True,
        socket_keepalive_options={"TCP_KEEPIDLE": 20},
    )
    await r.ping()

asyncio.run(main())
```
raises
```text
aioredis.exceptions.ConnectionError: an integer is required (got type str)
```

Changing the code to
```python3
import asyncio
import aioredis
import socket

async def main():
    r = aioredis.from_url(
        "redis://localhost:6379",
        socket_keepalive=True,
        socket_keepalive_options={socket.TCP_KEEPIDLE: 20},
    )
    await r.ping()

asyncio.run(main())
```
works fine.

### Expected behavior

The type annotation for `socket_keepalive_options` should be `Optional[Dict[int, str]]`.

### Logs/tracebacks

```python-traceback
See the description.
```


### Python Version

```console
$ python --version
Python 3.9.5
```


### aioredis Version

```console
$ python -m pip show aioredis
Name: aioredis
Version: 2.0.0
Summary: asyncio (PEP 3156) Redis support
Home-page: https://github.com/aio-libs/aioredis
Author:
Author-email:
License: MIT
Location: /home/joongi/.pyenv/versions/3.9.5/envs/venv-dev2109-common/lib/python3.9/site-packages
Requires: typing-extensions, async-timeout
Required-by: backend.ai-common
```


### Additional context

_No response_

### Code of Conduct

- [X] I agree to follow the aio-libs Code of Conduct


Discussion:

Resolving patch:
diff --git a/aioredis/client.py b/aioredis/client.py
--- a/aioredis/client.py
+++ b/aioredis/client.py
@@ -824,7 +824,7 @@ def __init__(
         socket_timeout: Optional[float] = None,
         socket_connect_timeout: Optional[float] = None,
         socket_keepalive: Optional[bool] = None,
-        socket_keepalive_options: Optional[Dict[str, Any]] = None,
+        socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
         connection_pool: Optional[ConnectionPool] = None,
         unix_socket_path: Optional[str] = None,
         encoding: str = "utf-8",
diff --git a/aioredis/connection.py b/aioredis/connection.py
--- a/aioredis/connection.py
+++ b/aioredis/connection.py
@@ -573,7 +573,7 @@ def __init__(
         socket_timeout: Optional[float] = None,
         socket_connect_timeout: Optional[float] = None,
         socket_keepalive: bool = False,
-        socket_keepalive_options: Optional[dict] = None,
+        socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
         socket_type: int = 0,
         retry_on_timeout: bool = False,
         encoding: str = "utf-8",


Test patch:
Repository: aio-libs-abandoned/aioredis-py

Issue:
AttributeError on `_lock`  with Unix socket connection
### Describe the bug

I use aioredis to connect to a Redis instance via Unix socket. Since I've bumped to the version 2.0.1 of the lib I encounter an error.
This seems related to this [commit](https://github.com/aio-libs/aioredis-py/commit/65d95e5640eb51b801d443ce56a91b47ddb27dcb). After digging a bit in the code, I've noticed that on `UnixDomainSocketConnection` instantiation doesn't perform a `super().__init__` nor refrence a `self._lock`.  Adding a `self._lock = asyncio.Lock()` solves my issue.

If this is this the only thing to fix I could do a PR.

### To Reproduce

```python
import asyncio
import aioredis

client = aioredis.from_url("unix://@/a/path/to/redis.sock")
loop = asyncio.get_event_loop()
loop.run_until_complete(client.ping())
```

### Expected behavior

A simple command such as `ping` should pass.

### Logs/tracebacks

```python-traceback
Traceback (most recent call last):
  File "/home/code/retrieve_cancel.py", line 60, in <module>
    loop.run_until_complete(client.ping())
  File "/home/code/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/code/python/lib/python3.9/site-packages/aioredis/client.py", line 1085, in execute_command
    return await self.parse_response(conn, command_name, **options)
  File "/home/code/python/lib/python3.9/site-packages/aioredis/client.py", line 1101, in parse_response
    response = await connection.read_response()
  File "/home/code/python/lib/python3.9/site-packages/aioredis/connection.py", line 898, in read_response
    async with self._lock:
AttributeError: _lock
```


### Python Version

```console
Python 3.9.7
```


### aioredis Version

```console
Version: 2.0.1
```


### Additional context

_No response_

### Code of Conduct

- [X] I agree to follow the aio-libs Code of Conduct


Discussion:
Please create the necessary PR for this. I'm not sure if we test on Unix socket connection; if we don't, then a simple addition without a test case will do. Thank you!

Resolving patch:
diff --git a/aioredis/connection.py b/aioredis/connection.py
--- a/aioredis/connection.py
+++ b/aioredis/connection.py
@@ -1122,6 +1122,7 @@ def __init__(
         self._parser = parser_class(socket_read_size=socket_read_size)
         self._connect_callbacks = []
         self._buffer_cutoff = 6000
+        self._lock = asyncio.Lock()
 
     def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
         pieces = [


Test patch:
Repository: googleapis/google-auth-library-python

Issue:
Support `GCLOUD_PROJECT` environment variable



Discussion:

Resolving patch:
diff --git a/google/auth/_default.py b/google/auth/_default.py
--- a/google/auth/_default.py
+++ b/google/auth/_default.py
@@ -254,7 +254,9 @@ def default(request=None):
             If no credentials were found, or if the credentials found were
             invalid.
     """
-    explicit_project_id = os.environ.get(environment_vars.PROJECT)
+    explicit_project_id = os.environ.get(
+        environment_vars.PROJECT,
+        os.environ.get(environment_vars.LEGACY_PROJECT))
 
     checkers = (
         _get_explicit_environ_credentials,
diff --git a/google/auth/environment_vars.py b/google/auth/environment_vars.py
--- a/google/auth/environment_vars.py
+++ b/google/auth/environment_vars.py
@@ -22,6 +22,13 @@
 environment variable is also used by the Google Cloud Python Library.
 """
 
+LEGACY_PROJECT = 'GCLOUD_PROJECT'
+"""Previously used environment variable defining the default project.
+
+This environment variable is used instead of the current one in some
+situations (such as Google App Engine).
+"""
+
 CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
 """Environment variable defining the location of Google application default
 credentials."""


Test patch:
diff --git a/tests/test__default.py b/tests/test__default.py
--- a/tests/test__default.py
+++ b/tests/test__default.py
@@ -266,6 +266,15 @@ def test_default_explict_project_id(get_mock, monkeypatch):
         mock.sentinel.credentials, 'explicit-env')
 
 
+@mock.patch(
+    'google.auth._default._get_explicit_environ_credentials',
+    return_value=(mock.sentinel.credentials, mock.sentinel.project_id))
+def test_default_explict_legacy_project_id(get_mock, monkeypatch):
+    monkeypatch.setenv(environment_vars.LEGACY_PROJECT, 'explicit-env')
+    assert _default.default() == (
+        mock.sentinel.credentials, 'explicit-env')
+
+
 @mock.patch(
     'google.auth._default._get_explicit_environ_credentials',
     return_value=(None, None))
Repository: googleapis/google-auth-library-python

Issue:
secure_authorized_channel should pass **kwargs to grpc.secure_channel
This will enable us to completely replace google-cloud-python's [similar function](https://github.com/GoogleCloudPlatform/google-cloud-python/blob/115748814bf6a59d99c13e070dfdcfbdec5e865d/core/google/cloud/_helpers.py#L659)

/cc @dhermes 


Discussion:

Resolving patch:
diff --git a/google/auth/transport/grpc.py b/google/auth/transport/grpc.py
--- a/google/auth/transport/grpc.py
+++ b/google/auth/transport/grpc.py
@@ -62,7 +62,7 @@ def __call__(self, context, callback):
 
 
 def secure_authorized_channel(
-        credentials, request, target, ssl_credentials=None):
+        credentials, request, target, ssl_credentials=None, **kwargs):
     """Creates a secure authorized gRPC channel.
 
     This creates a channel with SSL and :class:`AuthMetadataPlugin`. This
@@ -98,6 +98,7 @@ def secure_authorized_channel(
         target (str): The host and port of the service.
         ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
             credentials. This can be used to specify different certificates.
+        kwargs: Additional arguments to pass to :func:`grpc.secure_channel`.
 
     Returns:
         grpc.Channel: The created gRPC channel.
@@ -115,4 +116,4 @@ def secure_authorized_channel(
     composite_credentials = grpc.composite_channel_credentials(
         ssl_credentials, google_auth_credentials)
 
-    return grpc.secure_channel(target, composite_credentials)
+    return grpc.secure_channel(target, composite_credentials, **kwargs)


Test patch:
diff --git a/tests/transport/test_grpc.py b/tests/transport/test_grpc.py
--- a/tests/transport/test_grpc.py
+++ b/tests/transport/test_grpc.py
@@ -82,7 +82,7 @@ def test_secure_authorized_channel(
     target = 'example.com:80'
 
     channel = google.auth.transport.grpc.secure_authorized_channel(
-        credentials, request, target)
+        credentials, request, target, options=mock.sentinel.options)
 
     # Check the auth plugin construction.
     auth_plugin = metadata_call_credentials.call_args[0][0]
@@ -101,7 +101,8 @@ def test_secure_authorized_channel(
 
     # Check the channel call.
     secure_channel.assert_called_once_with(
-        target, composite_channel_credentials.return_value)
+        target, composite_channel_credentials.return_value,
+        options=mock.sentinel.options)
     assert channel == secure_channel.return_value
Repository: googleapis/google-auth-library-python

Issue:
Add `connections` to `httplib2.AuthorizedHttp`
/cc @dhermes


Discussion:
Just as a proxy?

Ja

On Fri, Nov 11, 2016 at 4:06 PM Danny Hermes notifications@github.com
wrote:

> Just as a proxy?
> 
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/86#issuecomment-260084206,
> or mute the thread
> https://github.com/notifications/unsubscribe-auth/AAPUc38-zEX1TNdmSt7PKLp5-EP-Y41Hks5q9QL_gaJpZM4KwQXr
> .


Resolving patch:
diff --git a/httplib2_transport/google_auth_httplib2.py b/httplib2_transport/google_auth_httplib2.py
--- a/httplib2_transport/google_auth_httplib2.py
+++ b/httplib2_transport/google_auth_httplib2.py
@@ -223,3 +223,13 @@ def request(self, uri, method='GET', body=None, headers=None,
                 **kwargs)
 
         return response, content
+
+    @property
+    def connections(self):
+        """Proxy to httplib2.Http.connections."""
+        return self.http.connections
+
+    @connections.setter
+    def connections(self, value):
+        """Proxy to httplib2.Http.connections."""
+        self.http.connections = value
diff --git a/httplib2_transport/setup.py b/httplib2_transport/setup.py
--- a/httplib2_transport/setup.py
+++ b/httplib2_transport/setup.py
@@ -30,7 +30,7 @@
 
 setup(
     name='google-auth-httplib2',
-    version='0.0.1',
+    version='0.0.2',
     author='Google Cloud Platform',
     author_email='jonwayne+google-auth@google.com',
     description='Google Authentication Library',


Test patch:
diff --git a/httplib2_transport/tests/test_google_auth_httplib2.py b/httplib2_transport/tests/test_google_auth_httplib2.py
--- a/httplib2_transport/tests/test_google_auth_httplib2.py
+++ b/httplib2_transport/tests/test_google_auth_httplib2.py
@@ -86,6 +86,15 @@ def test_authed_http_defaults(self):
         assert authed_http.credentials == mock.sentinel.credentials
         assert isinstance(authed_http.http, httplib2.Http)
 
+    def test_connections(self):
+        authed_http = google_auth_httplib2.AuthorizedHttp(
+            mock.sentinel.credentials)
+
+        assert authed_http.connections == authed_http.http.connections
+
+        authed_http.connections = mock.sentinel.connections
+        assert authed_http.http.connections == mock.sentinel.connections
+
     def test_request_no_refresh(self):
         mock_credentials = mock.Mock(wraps=MockCredentials())
         mock_response = MockResponse()
Repository: googleapis/google-auth-library-python

Issue:
Make creating a Signer from a JSON keyfile easier.



Discussion:

Resolving patch:
diff --git a/google/auth/crypt.py b/google/auth/crypt.py
--- a/google/auth/crypt.py
+++ b/google/auth/crypt.py
@@ -227,3 +227,18 @@ def from_string(cls, key, key_id=None):
             raise ValueError('No key could be detected.')
 
         return cls(private_key, key_id=key_id)
+
+    @classmethod
+    def from_service_account_file(cls, filename):
+        """Creates a Signer instance from a service account .json file
+        in Google format.
+
+        Args:
+            filename (str): The path to the service account .json file.
+
+        Returns:
+            Signer: The constructed signer.
+        """
+        from google.auth import _service_account_info
+        _, signer = _service_account_info.from_filename(filename)
+        return signer


Test patch:
diff --git a/tests/test_crypt.py b/tests/test_crypt.py
--- a/tests/test_crypt.py
+++ b/tests/test_crypt.py
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 import os
+import json
 
 import mock
 from pyasn1_modules import pem
@@ -59,6 +60,12 @@
 with open(os.path.join(DATA_DIR, 'privatekey.p12'), 'rb') as fh:
     PKCS12_KEY_BYTES = fh.read()
 
+# The service account JSON file can be generated from the Google Cloud Console.
+SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json')
+
+with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh:
+    SERVICE_ACCOUNT_INFO = json.load(fh)
+
 
 def test_verify_signature():
     to_sign = b'foo'
@@ -191,3 +198,10 @@ def test_from_string_bogus_key(self):
         key_bytes = 'bogus-key'
         with pytest.raises(ValueError):
             crypt.Signer.from_string(key_bytes)
+
+    def test_from_service_account_file(self):
+        signer = crypt.Signer.from_service_account_file(
+            SERVICE_ACCOUNT_JSON_FILE)
+
+        assert signer.key_id == SERVICE_ACCOUNT_INFO['private_key_id']
+        assert isinstance(signer._key, rsa.key.PrivateKey)
Repository: googleapis/google-auth-library-python

Issue:
Add GAE Signer



Discussion:

Resolving patch:
diff --git a/google/auth/app_engine.py b/google/auth/app_engine.py
--- a/google/auth/app_engine.py
+++ b/google/auth/app_engine.py
@@ -12,10 +12,10 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-"""Google App Engine standard environment credentials.
+"""Google App Engine standard environment support.
 
-This module provides authentication for application running on App Engine in
-the standard environment using the `App Identity API`_.
+This module provides authentication and signing for applications running on App
+Engine in the standard environment using the `App Identity API`_.
 
 
 .. _App Identity API:
@@ -33,6 +33,29 @@
     app_identity = None
 
 
+class Signer(object):
+    """Signs messages using the App Engine app identity service.
+
+    This can be used in place of :class:`google.auth.crypt.Signer` when
+    running in the App Engine standard environment.
+    """
+    def __init__(self):
+        self.key_id = None
+
+    @staticmethod
+    def sign(message):
+        """Signs a message.
+
+        Args:
+            message (Union[str, bytes]): The message to be signed.
+
+        Returns:
+            bytes: The signature of the message.
+        """
+        message = _helpers.to_bytes(message)
+        return app_identity.sign_blob(message)
+
+
 def get_project_id():
     """Gets the project ID for the current App Engine application.
 
@@ -109,7 +132,7 @@ def with_scopes(self, scopes):
 
     @_helpers.copy_docstring(credentials.Signing)
     def sign_bytes(self, message):
-        return app_identity.sign_blob(message)
+        return Signer().sign(message)
 
     @property
     @_helpers.copy_docstring(credentials.Signing)
diff --git a/google/auth/crypt.py b/google/auth/crypt.py
--- a/google/auth/crypt.py
+++ b/google/auth/crypt.py
@@ -186,7 +186,7 @@ def sign(self, message):
             message (Union[str, bytes]): The message to be signed.
 
         Returns:
-            bytes: The signature of the message for the given key.
+            bytes: The signature of the message.
         """
         message = _helpers.to_bytes(message)
         return rsa.pkcs1.sign(message, self._key, 'SHA-256')


Test patch:
Repository: googleapis/google-auth-library-python

Issue:
Add public properties to google.oauth2.credentials.Credentials
Resolves #124 


Discussion:

Resolving patch:
diff --git a/google/oauth2/credentials.py b/google/oauth2/credentials.py
--- a/google/oauth2/credentials.py
+++ b/google/oauth2/credentials.py
@@ -68,6 +68,27 @@ def __init__(self, token, refresh_token=None, token_uri=None,
         self._client_id = client_id
         self._client_secret = client_secret
 
+    @property
+    def refresh_token(self):
+        """Optional[str]: The OAuth 2.0 refresh token."""
+        return self._refresh_token
+
+    @property
+    def token_uri(self):
+        """Optional[str]: The OAuth 2.0 authorization server's token endpoint
+        URI."""
+        return self._token_uri
+
+    @property
+    def client_id(self):
+        """Optional[str]: The OAuth 2.0 client ID."""
+        return self._client_id
+
+    @property
+    def client_secret(self):
+        """Optional[str]: The OAuth 2.0 client secret."""
+        return self._client_secret
+
     @property
     def requires_scopes(self):
         """False: OAuth 2.0 credentials have their scopes set when


Test patch:
diff --git a/tests/oauth2/test_credentials.py b/tests/oauth2/test_credentials.py
--- a/tests/oauth2/test_credentials.py
+++ b/tests/oauth2/test_credentials.py
@@ -41,6 +41,11 @@ def test_default_state(self):
         assert not self.credentials.expired
         # Scopes aren't required for these credentials
         assert not self.credentials.requires_scopes
+        # Test properties
+        assert self.credentials.refresh_token == self.REFRESH_TOKEN
+        assert self.credentials.token_uri == self.TOKEN_URI
+        assert self.credentials.client_id == self.CLIENT_ID
+        assert self.credentials.client_secret == self.CLIENT_SECRET
 
     def test_create_scoped(self):
         with pytest.raises(NotImplementedError):
Repository: googleapis/google-auth-library-python

Issue:
Docs: compute_engine.credentials doesn't render note for service_account_email
On this doc item: https://google-auth.readthedocs.io/en/latest/reference/google.auth.compute_engine.credentials.html#google.auth.compute_engine.credentials.Credentials.service_account_email

The rendered docs say simply `The service account email.`

However, the [docstring](https://google-auth.readthedocs.io/en/latest/_modules/google/auth/compute_engine/credentials.html#Credentials.refresh) has more information:

```
        """The service account email.

        .. note: This is not guaranteed to be set until :meth`refresh` has been
            called.
        """
```

Why is this important note not rendered?


Discussion:

Resolving patch:
diff --git a/google/auth/compute_engine/credentials.py b/google/auth/compute_engine/credentials.py
--- a/google/auth/compute_engine/credentials.py
+++ b/google/auth/compute_engine/credentials.py
@@ -105,7 +105,7 @@ def refresh(self, request):
     def service_account_email(self):
         """The service account email.
 
-        .. note: This is not guaranteed to be set until :meth`refresh` has been
+        .. note:: This is not guaranteed to be set until :meth:`refresh` has been
             called.
         """
         return self._service_account_email


Test patch:
Repository: googleapis/google-auth-library-python

Issue:
Failure with Python 3.9 due to use of deprecated collections.Mapping
#### Environment details

  - OS: Linux
  - Python version: 3.9 alpha 2
  - pip version: 19.3.1
  - `google-auth` version: 1.10.0

#### Steps to reproduce

  1. Use Python 3.9
  2. Attempt to decode an ID Token:
    google.oauth2.id_token.verify_oauth2_token()...

Expected results:
decoded ID token

Actual results:
AttributeError: module 'collections' has no attribute 'Mapping'
see full crash at:
AttributeError: module 'collections' has no attribute 'Mapping'

Further details:
collections.Mapping was moved to collections.abc.Mapping in Python 3.3 but mapped back to collections up to Python 3.8. In Python 3.9 the legacy mapping is removed so we break. See:
https://docs.python.org/3/library/collections.html#

Failure with Python 3.9 due to use of deprecated collections.Mapping
#### Environment details

  - OS: Linux
  - Python version: 3.9 alpha 2
  - pip version: 19.3.1
  - `google-auth` version: 1.10.0

#### Steps to reproduce

  1. Use Python 3.9
  2. Attempt to decode an ID Token:
    google.oauth2.id_token.verify_oauth2_token()...

Expected results:
decoded ID token

Actual results:
AttributeError: module 'collections' has no attribute 'Mapping'
see full crash at:
AttributeError: module 'collections' has no attribute 'Mapping'

Further details:
collections.Mapping was moved to collections.abc.Mapping in Python 3.3 but mapped back to collections up to Python 3.8. In Python 3.9 the legacy mapping is removed so we break. See:
https://docs.python.org/3/library/collections.html#



Discussion:

Resolving patch:
diff --git a/google/auth/jwt.py b/google/auth/jwt.py
--- a/google/auth/jwt.py
+++ b/google/auth/jwt.py
@@ -40,7 +40,10 @@
 
 """
 
-import collections
+try:
+    from collections.abc import Mapping
+except ImportError: # Python 2.7 compatibility
+    from collections import Mapping
 import copy
 import datetime
 import json
@@ -215,7 +218,7 @@ def decode(token, certs=None, verify=True, audience=None):
 
     # If certs is specified as a dictionary of key IDs to certificates, then
     # use the certificate identified by the key ID in the token header.
-    if isinstance(certs, collections.Mapping):
+    if isinstance(certs, Mapping):
         key_id = header.get("kid")
         if key_id:
             if key_id not in certs:


Test patch: