internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: googleapis/google-cloud-python

Issue:
Error fetching results from a BigQuery asynchronous call in 0.19.0
Referring to the [doc](https://googlecloudplatform.github.io/google-cloud-python/stable/bigquery-usage.html#querying-data-asynchronous), calling `QueryResults.fetch_data` raises an exception since `self.name` is `None`:

``` python
if self.name is None:
    raise ValueError("Query not yet executed:  call 'run()'")
```

However, if `QueryResults.run` is called, an exception is also raised since `self._job` already exists:

``` python
if self._job is not None:
    raise ValueError("Query job is already running.")
```



Discussion:

Resolving patch:
diff --git a/google/cloud/bigquery/query.py b/google/cloud/bigquery/query.py
--- a/google/cloud/bigquery/query.py
+++ b/google/cloud/bigquery/query.py
@@ -77,6 +77,8 @@ def from_query_job(cls, job):
         """
         instance = cls(job.query, job._client, job.udf_resources)
         instance._job = job
+        job_ref = instance._properties.setdefault('jobReference', {})
+        job_ref['jobId'] = job.name
         if job.default_dataset is not None:
             instance.default_dataset = job.default_dataset
         if job.use_query_cache is not None:


Test patch:
diff --git a/unit_tests/bigquery/test_query.py b/unit_tests/bigquery/test_query.py
--- a/unit_tests/bigquery/test_query.py
+++ b/unit_tests/bigquery/test_query.py
@@ -155,6 +155,7 @@ def test_from_query_job(self):
 
         query = klass.from_query_job(job)
 
+        self.assertEqual(query.name, self.JOB_NAME)
         self.assertEqual(query.query, self.QUERY)
         self.assertIs(query._client, client)
         self.assertIs(query._job, job)
Repository: googleapis/google-cloud-python

Issue:
CORS documentation missing setter
https://googlecloudplatform.github.io/gcloud-python/stable/storage-buckets.html#gcloud.storage.bucket.Bucket.cors

> Retrieve CORS policies configured for this bucket.

It doesn't mention that it can also be set.



Discussion:
(I think this also applies to a few other properties.)

@tseaver [https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/gcloud/storage/bucket.py#L509](https://github.com/GoogleCloudPlatform/gcloud-python/blob/b27907be562e81a10abe258ee32d039146e65768/gcloud/storage/bucket.py#L509) is it just not showing up in the docs because of the decorator?

@daspecster Docstrings for `@property` objects are derived from their getters:

``` python
>>> class Foo(object):
...     @property
...     def bar(self):
...         """bar getter"""
...     @bar.setter
...     def bar(self, value):
...         """bar setter"""
...     @bar.deleter
...     def bar(self):
...         """bar deleter"""
... 
>>> Foo.bar
<property object at 0x7f8fe9a856d8>
>>> Foo.bar.__doc__
'bar getter'
```

Cool, what if we just combine the docs in some way that makes sense in the getter?

``` python
    @property
    def cors(self):
        """Get/Set CORS policies configured for this bucket.
        See: http://www.w3.org/TR/cors/ and
             https://cloud.google.com/storage/docs/json_api/v1/buckets

        :setter: Set CORS policies for this bucket.
        :getter: Gets the CORS policies for this bucket.

        """
        return [copy.deepcopy(policy)
                for policy in self._properties.get('cors', ())]

    @cors.setter
    def cors(self, entries):
        """Set CORS policies configured for this bucket.
        See: http://www.w3.org/TR/cors/ and
             https://cloud.google.com/storage/docs/json_api/v1/buckets
        :type entries: list of dictionaries
        :param entries: A sequence of mappings describing each CORS policy.
        """
        self._patch_property('cors', entries)
```

I filed #2610 where the same issue applies to the setter for `lifecycle_rules`. Seems like a very simple solution here is what @daspecster proposed. It's not perfect, but if it had been done back in June when it was proposed, I would have been a happier customer.


Resolving patch:
diff --git a/storage/google/cloud/storage/bucket.py b/storage/google/cloud/storage/bucket.py
--- a/storage/google/cloud/storage/bucket.py
+++ b/storage/google/cloud/storage/bucket.py
@@ -511,11 +511,14 @@ def rename_blob(self, blob, new_name, client=None):
 
     @property
     def cors(self):
-        """Retrieve CORS policies configured for this bucket.
+        """Retrieve or set CORS policies configured for this bucket.
 
         See: http://www.w3.org/TR/cors/ and
              https://cloud.google.com/storage/docs/json_api/v1/buckets
 
+        :setter: Set CORS policies for this bucket.
+        :getter: Gets the CORS policies for this bucket.
+
         :rtype: list of dictionaries
         :returns: A sequence of mappings describing each CORS policy.
         """


Test patch:
Repository: googleapis/google-cloud-python

Issue:
If AutoAck pull returns empty then exception raised on context exit
If the subscription pull returns 0 messages in the __enter__ method in the AutoAck class then on __exit__ the acknowledge call raises an exception on the HTTP call: https://github.com/GoogleCloudPlatform/google-cloud-python/blob/pubsub-0.22.0/pubsub/google/cloud/pubsub/subscription.py#L512

Currently the way a deal with this is to wrap the context manager in try/except or override __exit__ to check for an empty list. The former is messy and the latter can just be fixed at source.



Discussion:

Resolving patch:
diff --git a/pubsub/google/cloud/pubsub/subscription.py b/pubsub/google/cloud/pubsub/subscription.py
--- a/pubsub/google/cloud/pubsub/subscription.py
+++ b/pubsub/google/cloud/pubsub/subscription.py
@@ -509,4 +509,5 @@ def __enter__(self):
         return self
 
     def __exit__(self, exc_type, exc_val, exc_tb):
-        self._subscription.acknowledge(list(self), self._client)
+        if self:
+            self._subscription.acknowledge(list(self), self._client)


Test patch:
diff --git a/pubsub/unit_tests/test_subscription.py b/pubsub/unit_tests/test_subscription.py
--- a/pubsub/unit_tests/test_subscription.py
+++ b/pubsub/unit_tests/test_subscription.py
@@ -14,6 +14,8 @@
 
 import unittest
 
+import mock
+
 
 class TestSubscription(unittest.TestCase):
     PROJECT = 'PROJECT'
@@ -745,6 +747,16 @@ def test___exit___(self):
                          [ACK_ID1, ACK_ID2])
         self.assertIs(subscription._ack_client, CLIENT)
 
+    def test_empty_ack_no_acknowledge(self):
+        subscription = mock.Mock(_FauxSubscription)
+        subscription.pull = lambda *args: []
+
+        auto_ack = self._make_one(subscription)
+        with auto_ack:
+            pass
+
+        subscription.acknowledge.assert_not_called()
+
 
 class _FauxIAMPolicy(object):
Repository: googleapis/google-cloud-python

Issue:
gRPC pubsub missing scope error
It appears that something changed in gRPC.

```
Exception google.auth.exceptions.RefreshError: RefreshError('invalid_scope: Empty or missing scope not allowed.', u'{\n  "error" : "invalid_scope",\n  "error_description" : "Empty or missing scope not allowed."\n}') in 'grpc._cython.cygrpc.plugin_get_metadata' ignored
```

Reference: https://travis-ci.org/GoogleCloudPlatform/google-cloud-python/builds/187483537#L2101

Running `$ tox -e system-tests -- pubsub` yields the same results.

However running `$ GOOGLE_CLOUD_DISABLE_GRPC=true tox -e system-tests -- pubsub` allows the tests to pass.


Discussion:
That error is not in gRPC, it's in the auth code. For some reason the credentials aren't scoped. Might be related to #2870 or #2874 (I am author of both)

Resolving patch:
diff --git a/pubsub/google/cloud/pubsub/client.py b/pubsub/google/cloud/pubsub/client.py
--- a/pubsub/google/cloud/pubsub/client.py
+++ b/pubsub/google/cloud/pubsub/client.py
@@ -96,7 +96,7 @@ def publisher_api(self):
                         host=self._connection.host)
                 else:
                     generated = make_gax_publisher_api(
-                        credentials=self._credentials)
+                        credentials=self._connection._credentials)
                 self._publisher_api = GAXPublisherAPI(generated, self)
             else:
                 self._publisher_api = JSONPublisherAPI(self)
@@ -112,7 +112,7 @@ def subscriber_api(self):
                         host=self._connection.host)
                 else:
                     generated = make_gax_subscriber_api(
-                        credentials=self._credentials)
+                        credentials=self._connection._credentials)
                 self._subscriber_api = GAXSubscriberAPI(generated, self)
             else:
                 self._subscriber_api = JSONSubscriberAPI(self)


Test patch:
Repository: googleapis/google-cloud-python

Issue:
Cloud speech veneer should not provide a default sample rate
Default sample rates should be removed.  For audio types with a header the server can automatically determine the sample rate. (We are implementing this for V1.)  For audio types without a header the default causes more harm than good because if it is incorrect the results could be empty or wildly inaccurate, which causes user confusion.


Discussion:
The same applies to language code.

Resolving patch:
diff --git a/speech/google/cloud/speech/sample.py b/speech/google/cloud/speech/sample.py
--- a/speech/google/cloud/speech/sample.py
+++ b/speech/google/cloud/speech/sample.py
@@ -53,7 +53,6 @@ class Sample(object):
     :param client: (Optional) The client that owns this instance of sample.
     """
     default_encoding = Encoding.FLAC
-    default_sample_rate = 16000
 
     def __init__(self, content=None, source_uri=None, stream=None,
                  encoding=None, sample_rate=None, client=None):
@@ -72,7 +71,7 @@ def __init__(self, content=None, source_uri=None, stream=None,
         if sample_rate is not None and not 8000 <= sample_rate <= 48000:
             raise ValueError('The value of sample_rate must be between 8000'
                              ' and 48000.')
-        self._sample_rate = sample_rate or self.default_sample_rate
+        self._sample_rate = sample_rate
 
         if encoding is not None and getattr(Encoding, encoding, False):
             self._encoding = getattr(Encoding, encoding)


Test patch:
diff --git a/speech/unit_tests/test_sample.py b/speech/unit_tests/test_sample.py
--- a/speech/unit_tests/test_sample.py
+++ b/speech/unit_tests/test_sample.py
@@ -93,10 +93,6 @@ def test_sample_rates(self):
         self.assertEqual(sample.sample_rate, self.SAMPLE_RATE)
         self.assertEqual(sample.encoding, Encoding.FLAC)
 
-        sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI,
-                                encoding=Encoding.FLAC)
-        self.assertEqual(sample.sample_rate, self.SAMPLE_RATE)
-
     def test_encoding(self):
         from google.cloud.speech.encoding import Encoding
Repository: googleapis/google-cloud-python

Issue:
Check query's run status using property, not attribute
Split out from #3001, where @amirshavit reported:

> The run method checks if `self._job is not None`: to prevent a double invocation. It should however run that check with `self.job` instead (no underscore), as `self._job` is only set if you previously used `self.job`.



Discussion:

Resolving patch:
diff --git a/bigquery/google/cloud/bigquery/query.py b/bigquery/google/cloud/bigquery/query.py
--- a/bigquery/google/cloud/bigquery/query.py
+++ b/bigquery/google/cloud/bigquery/query.py
@@ -351,7 +351,7 @@ def run(self, client=None):
         :param client: the client to use.  If not passed, falls back to the
                        ``client`` stored on the current dataset.
         """
-        if self._job is not None:
+        if self.job is not None:
             raise ValueError("Query job is already running.")
 
         client = self._require_client(client)


Test patch:
diff --git a/bigquery/unit_tests/test_query.py b/bigquery/unit_tests/test_query.py
--- a/bigquery/unit_tests/test_query.py
+++ b/bigquery/unit_tests/test_query.py
@@ -274,6 +274,15 @@ def test_run_w_already_has_job(self):
         with self.assertRaises(ValueError):
             query.run()
 
+    def test_run_w_already_has_job_in_properties(self):
+        JOB_ID = 'JOB_ID'
+        conn = _Connection()
+        client = _Client(project=self.PROJECT, connection=conn)
+        query = self._make_one(self.QUERY, client)
+        query._properties['jobReference'] = {'jobId': JOB_ID}
+        with self.assertRaises(ValueError):
+            query.run()
+
     def test_run_w_bound_client(self):
         PATH = 'projects/%s/queries' % self.PROJECT
         RESOURCE = self._makeResource(complete=False)
Repository: googleapis/google-cloud-python

Issue:
[pubSub] tell when to use subscription.reload()
The [api docs](https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/pubsub/google/cloud/pubsub/subscription.py#L217) don't mention when one should use this api (when is my local config out of sync), e.g. is there are exception I should react to?


Discussion:
@ensonic Thanks for the report!

The two bits of state which `Subscription.reload()` fetches from the server are the `ack_deadline` and `push_endpoint` attributes.  "Normal" use of the subscription (pulling events) isn't affected by those variables.  Any time your app *does* need to know their values for some reason (e.g., before calling `modify_push_endpoint()` to see what the current state is), then it is best to call `reload()` first.
Thanks for the info. Adding this bit to the docs would be nice.

The reason I looked at the API was that I wonder if a subscription can go 'stale'. I have a case where a subscriber seems to be getting 'old' messages. The subscriber is ack'ing the messages. By 'old', I mean the message.service_timestamp is e.g. 3 hours behind. E.g.
```
[2017-02-22 14:13:14,361] INFO:root:msg-id: 110510709003979, ts: 2017-02-22T11:42:14.299000Z, topic: topic1
[2017-02-22 14:13:16,981] INFO:root:msg-id: 110519798495214, ts: 2017-02-22T14:11:24.310000Z, topic: topic1
```
Each topic is published by a gke instance. When I log into each instance the clock is looking alright. The service_timestamp is set here:
https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/pubsub/google/cloud/pubsub/message.py#L90

Edit: I think I am bitten by the default 'max_messages=1' for subscription.pull(). Unfortunately there is no easy way to 'flush' a topic :/.

Resolving patch:
diff --git a/pubsub/google/cloud/pubsub/subscription.py b/pubsub/google/cloud/pubsub/subscription.py
--- a/pubsub/google/cloud/pubsub/subscription.py
+++ b/pubsub/google/cloud/pubsub/subscription.py
@@ -220,6 +220,10 @@ def reload(self, client=None):
         See
         https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/get
 
+        :attr:`ack_deadline` and :attr:`push_endpoint` might never have
+        been set locally, or might have been updated by another client.  This
+        method fetches their values from the server.
+
         Example:
 
         .. literalinclude:: pubsub_snippets.py


Test patch:
Repository: googleapis/google-cloud-python

Issue:
RTD build is broken
Can look at this, leaving as note as reminder.


Discussion:
I'm not sure what this means?

They appear to be populated?
https://googlecloudplatform.github.io/google-cloud-python/latest/storage-client.html
Sorry opened issue with customer next to me. 

@daspecster realizing its' the read the docs docs that are missing.

https://google-cloud-python.readthedocs.io/en/latest/storage-client.html

Indeed, another example: https://google-cloud-python.readthedocs.io/en/latest/datastore-transactions.html

Latest build is green (but must be secretly not green): https://readthedocs.org/projects/google-cloud-python/builds/5028739/
@tseaver @daspecster We should tackle this. I'm not sure if there is another issue, but the RTD build has been b0rken for a few days:

https://readthedocs.org/projects/google-cloud-python/builds/

e.g.

https://readthedocs.org/projects/google-cloud-python/builds/5060236/
OK the fix is easy, we just need to get all subpackages on the same version of `google-cloud-core`. DERP!

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -52,7 +52,7 @@
 REQUIREMENTS = [
     'google-cloud-bigquery >= 0.22.1, < 0.23dev',
     'google-cloud-bigtable >= 0.22.0, < 0.23dev',
-    'google-cloud-core >= 0.22.1, < 0.23dev',
+    'google-cloud-core >= 0.23.0, < 0.24dev',
     'google-cloud-datastore >= 0.22.0, < 0.23dev',
     'google-cloud-dns >= 0.22.0, < 0.23dev',
     'google-cloud-error-reporting >= 0.22.0, < 0.23dev',


Test patch:
Repository: googleapis/google-cloud-python

Issue:
Error reporting accessing client.project instead of client._project.
[Originally](https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2687#issuecomment-286703711) from @DizzeePascall. 

When running the examples from the documentation, I get the following error:

```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/laurence/miniconda3/envs/sonalytic/lib/python3.5/site-packages/google/cloud/error_reporting/client.py", line 320, in report
    report_location=report_location)
  File "/home/laurence/miniconda3/envs/sonalytic/lib/python3.5/site-packages/google/cloud/error_reporting/client.py", line 277, in _send_error_report
    self.report_errors_api.report_error_event(error_report)
  File "/home/laurence/miniconda3/envs/sonalytic/lib/python3.5/site-packages/google/cloud/error_reporting/client.py", line 162, in report_errors_api
    self._report_errors_api = make_report_error_api(self)
  File "/home/laurence/miniconda3/envs/sonalytic/lib/python3.5/site-packages/google/cloud/error_reporting/_gax.py", line 44, in make_report_error_api
    return _ErrorReportingGaxApi(gax_client, client.project)
AttributeError: 'Client' object has no attribute 'project'
```

Disabling GRPC via the `GOOGLE_CLOUD_DISABLE_GRPC` environment variable fixes this.

I'm running on an Ubuntu 14.04 compute instance with python 3.5.3 and version 023.1 of the google-cloud-error-reporting project


Discussion:

Resolving patch:
diff --git a/error_reporting/google/cloud/error_reporting/_gax.py b/error_reporting/google/cloud/error_reporting/_gax.py
--- a/error_reporting/google/cloud/error_reporting/_gax.py
+++ b/error_reporting/google/cloud/error_reporting/_gax.py
@@ -41,7 +41,7 @@ def make_report_error_api(client):
         report_errors_service_client.ReportErrorsServiceClient.SERVICE_ADDRESS)
     gax_client = report_errors_service_client.ReportErrorsServiceClient(
         channel=channel, lib_name='gccl', lib_version=__version__)
-    return _ErrorReportingGaxApi(gax_client, client.project)
+    return _ErrorReportingGaxApi(gax_client, client._project)
 
 
 class _ErrorReportingGaxApi(object):


Test patch:
diff --git a/error_reporting/unit_tests/test__gax.py b/error_reporting/unit_tests/test__gax.py
--- a/error_reporting/unit_tests/test__gax.py
+++ b/error_reporting/unit_tests/test__gax.py
@@ -30,8 +30,8 @@ def test_make_report_error_api(self):
 
         client = mock.Mock(
             _credentials=mock.sentinel.credentials,
-            project='prahj-ekt',
-            spec=['project', '_credentials'],
+            _project='prahj-ekt',
+            spec=['_project', '_credentials'],
         )
 
         # Mock out the constructor for the GAPIC client.
@@ -52,7 +52,7 @@ def test_make_report_error_api(self):
 
         # Assert that the final error client has the project in
         # the expected location.
-        self.assertIs(report_error_client._project, client.project)
+        self.assertIs(report_error_client._project, client._project)
 
 
 class Test_ErrorReportingGaxApi(unittest.TestCase):
Repository: googleapis/google-cloud-python

Issue:
Raise exception with helpful error on Client pickle.
Based on the discussion in #3191, raise an exception with a helpful error stating that `Client` classes are not pickleable.

Note to self: We probably want this in GAX also.


Discussion:
```python

_PICKLE_MSG = """\
Pickling client objects is explicitly not supported.

Clients have a large amount of state that is local and unpickleable.
"""

class Client(...):
    ...
    def __getstate__(self):
        raise NotImplementedError(_PICKLE_MSG)
```

Resolving patch:
diff --git a/core/google/cloud/client.py b/core/google/cloud/client.py
--- a/core/google/cloud/client.py
+++ b/core/google/cloud/client.py
@@ -14,6 +14,8 @@
 
 """Base classes for client used to interact with Google Cloud APIs."""
 
+from pickle import PicklingError
+
 import google.auth.credentials
 from google.oauth2 import service_account
 import google_auth_httplib2
@@ -126,6 +128,13 @@ def __init__(self, credentials=None, http=None):
             credentials, self.SCOPE)
         self._http_internal = http
 
+    def __getstate__(self):
+        """Explicitly state that clients are not pickleable."""
+        raise PicklingError('\n'.join([
+            'Pickling client objects is explicitly not supported.',
+            'Clients have non-trivial state that is local and unpickleable.',
+        ]))
+
     @property
     def _http(self):
         """Getter for object used for HTTP transport.


Test patch:
diff --git a/core/tests/unit/test_client.py b/core/tests/unit/test_client.py
--- a/core/tests/unit/test_client.py
+++ b/core/tests/unit/test_client.py
@@ -47,6 +47,16 @@ def _get_target_class():
     def _make_one(self, *args, **kw):
         return self._get_target_class()(*args, **kw)
 
+    def test_unpickleable(self):
+        import pickle
+
+        CREDENTIALS = _make_credentials()
+        HTTP = object()
+
+        client_obj = self._make_one(credentials=CREDENTIALS, http=HTTP)
+        with self.assertRaises(pickle.PicklingError):
+            pickle.dumps(client_obj)
+
     def test_ctor_defaults(self):
         from google.cloud._testing import _Monkey
         from google.cloud import client
Repository: googleapis/google-cloud-python

Issue:
Error in NL API, 'Sentiment' object has no attribute 'score'
Upon executing the following code on GCE & locally I'm getting 'score' not found error locally while it works on GCE.

```
def analyze_text(text):
    language_client = language.Client()
    document = language_client.document_from_text(text)
    annotations = document.annotate_text(include_sentiment=True)
    print(annotations.sentiment.score)
    print (annotations.sentiment.magnitude)
```

Only difference I can find is on GCE, the gcloud version is different than the local
**GCE gcloud**
gcloud --version
Google Cloud SDK 145.0.0
alpha 2017.02.21
app-engine-python 1.9.50
beta 2017.02.21
bq 2.0.24
bq-nix 2.0.24
core 2017.02.21
core-nix 2017.02.21
gcloud 
gcloud-deps 2017.02.21
gcloud-deps-linux-x86_64 2017.02.21
gsutil 4.22
gsutil-nix 4.22

**Local gcloud**
gcloud --version
Google Cloud SDK 148.0.1
bq 2.0.24
bq-nix 2.0.24
core 2017.03.24
core-nix 2016.11.07
gcloud 
gcloud-deps 2017.03.17
gcloud-deps-darwin-x86_64 2017.02.21
gsutil 4.23
gsutil-nix 4.19

Debugging locally, the response from NL API consist of polarity property and not score.

<img width="761" alt="image" src="https://cloud.githubusercontent.com/assets/1888535/24331449/62cbdbee-1252-11e7-9d29-8699df078fcf.png">




Discussion:
So, any idea about this?
That most likely means that the API is inconsistent. I can make it not `KeyError`; you will just get a `None`. I will do that now while I am thinking about it.

Resolving patch:
diff --git a/language/google/cloud/language/sentiment.py b/language/google/cloud/language/sentiment.py
--- a/language/google/cloud/language/sentiment.py
+++ b/language/google/cloud/language/sentiment.py
@@ -52,6 +52,6 @@ def from_api_repr(cls, payload):
         :rtype: :class:`Sentiment`
         :returns: The sentiment parsed from the API representation.
         """
-        score = payload['score']
+        score = payload.get('score', None)
         magnitude = payload['magnitude']
         return cls(score, magnitude)


Test patch: