diff --git a/PythonDataset/dev/eNMS-task-instances.jsonl.all b/PythonDataset/dev/eNMS-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..f984451b8713d69830a803085ddb8ef29dbe885c --- /dev/null +++ b/PythonDataset/dev/eNMS-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "eNMS-automation/eNMS", "pull_number": 12, "instance_id": "eNMS-automation__eNMS-12", "issue_numbers": "", "base_commit": "4420e32e0e593b9bd1f904fa467e467ad1c5a149", "patch": "diff --git a/models.py b/models.py\n--- a/models.py\n+++ b/models.py\n@@ -1,4 +1,4 @@\n-from napalm_base import get_network_driver\n+from napalm import get_network_driver\n from netmiko import ConnectHandler\n from sqlalchemy.ext.declarative import declarative_base\n from sqlalchemy import Column, Integer, String\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2017-11-30T20:49:06Z"} diff --git a/PythonDataset/dev/flask-github-task-instances.jsonl.all b/PythonDataset/dev/flask-github-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..e0bc51d1ab97437fe9fc2f959e28dde1abe89875 --- /dev/null +++ b/PythonDataset/dev/flask-github-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "jarodl/flask-github", "pull_number": 3, "instance_id": "jarodl__flask-github-3", "issue_numbers": "", "base_commit": "985887fd227a07c424c2f953dc2d285bcc67b0ab", "patch": "diff --git a/flaskext/github.py b/flask_github.py\nsimilarity index 81%\nrename from flaskext/github.py\nrename to flask_github.py\n--- a/flaskext/github.py\n+++ b/flask_github.py\n@@ -5,14 +5,14 @@\n \n Authenticate users in your Flask app with Github.\n \"\"\"\n-import json\n-import oauth2\n-from httplib2 import Http\n from functools import wraps\n from urllib import urlencode\n from urlparse import parse_qs\n+\n+import requests\n from flask import redirect, request\n \n+\n class GithubAuth(object):\n \"\"\"\n Provides decorators for authenticating users with Github within a Flask\n@@ -37,6 +37,7 @@ def __init__(self, client_id, client_secret, session_key):\n self.get_access_token = lambda: None\n self.base_url = 'https://api.github.com/'\n self.base_auth_url = 'https://github.com/login/oauth/'\n+ self.session = requests.session()\n \n def access_token_getter(self, f):\n \"\"\"\n@@ -62,25 +63,26 @@ def authorize(self, callback_url=None, scope=None):\n auth_url = self.base_auth_url + 'authorize?' + urlencode(params)\n return redirect(auth_url)\n \n- def raw_request(self, base_url, resource, params, method, accept='json'):\n+ def raw_request(self, base_url, resource, params, method,\n+ access_token=None):\n \"\"\"\n Makes a raw HTTP request and returns the response and content.\n \"\"\"\n- http = Http(disable_ssl_certificate_validation=True)\n- params.update({'access_token': self.get_access_token()})\n- headers = {\n- \"Content-type\": \"application/x-www-form-urlencoded\",\n- \"Accept\": accept\n- }\n- url = base_url + resource + '?' + urlencode(params)\n- resp, content = http.request(url, method)\n- return resp, content\n+ url = base_url + resource\n+ if params is None:\n+ params = {}\n+ if access_token is None:\n+ access_token = self.get_access_token()\n+ params.update({'access_token': access_token})\n+ return self.session.request(method, url, params)\n \n- def get_resource(self, resource, params={}):\n+ def get_resource(self, resource, params=None, access_token=None):\n \"\"\"\n Makes a raw HTTP GET request and returns the response and content.\n \"\"\"\n- return self.raw_request(self.base_url, resource, params, \"GET\")\n+ response = self.raw_request(\n+ self.base_url, resource, params, \"GET\", access_token)\n+ return response, response.json()\n \n def handle_response(self):\n \"\"\"\n@@ -94,18 +96,16 @@ def handle_response(self):\n 'client_id': self.client_id,\n 'client_secret': self.client_secret\n }\n- resp, content = self.raw_request(self.base_auth_url, 'access_token',\n- params, \"POST\")\n- data = parse_qs(content)\n+ response = self.raw_request(\n+ self.base_auth_url, 'access_token', params, \"POST\")\n+ data = parse_qs(response.content)\n for k, v in data.items():\n if len(v) == 1:\n data[k] = v[0]\n return data\n \n def handle_invalid_response(self):\n- \"\"\"\n- \"\"\"\n- return None\n+ pass\n \n def authorized_handler(self, f):\n \"\"\"\n@@ -136,8 +136,7 @@ def get_github_user(self):\n Requests the authenticated user's data from Github.\n \"\"\"\n path = 'user'\n- resp, content = self.get_resource(path)\n- user = json.loads(content)\n+ resp, user = self.get_resource(path)\n return user\n \n def has_org_access(self, organization):\n@@ -146,8 +145,7 @@ def has_org_access(self, organization):\n organization.\n \"\"\"\n path = 'orgs/' + organization + '/members'\n- resp, content = self.get_resource(path)\n- org_members = json.loads(content)\n+ resp, org_members = self.get_resource(path)\n user = self.github_user()\n for member in org_members:\n if member['login'] == user['login']:\ndiff --git a/flaskext/__init__.py b/flaskext/__init__.py\ndeleted file mode 100644\n--- a/flaskext/__init__.py\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-__import__('pkg_resources').declare_namespace(__name__)\n-\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -16,13 +16,13 @@\n author_email='jarodluebbert@gmail.com',\n description='Adds support for authorizing users with Github to Flask',\n long_description=__doc__,\n- packages=['flaskext'],\n- namespace_packages=['flaskext'],\n+ py_modules=['flask_github'],\n zip_safe=False,\n+ include_package_data=True,\n platforms='any',\n install_requires=[\n 'Flask',\n- 'oauth2'\n+ 'requests',\n ],\n classifiers=[\n 'Environment :: Web Environment',\n@@ -33,4 +33,3 @@\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n )\n-\n", "test_patch": "diff --git a/tests.py b/tests.py\ndeleted file mode 100644\n", "problem_statement": "", "hints_text": "", "created_at": "2013-05-26T10:44:46Z"} diff --git a/PythonDataset/dev/glue-task-instances.jsonl.all b/PythonDataset/dev/glue-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..852b08481b343cd47839bcf050c61ed594189060 --- /dev/null +++ b/PythonDataset/dev/glue-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "glue-viz/glue", "pull_number": 99, "instance_id": "glue-viz__glue-99", "issue_numbers": "", "base_commit": "8b026e8681873d0b4408eba96360576ef37b56a9", "patch": "diff --git a/glue/core/coordinates.py b/glue/core/coordinates.py\n--- a/glue/core/coordinates.py\n+++ b/glue/core/coordinates.py\n@@ -1,10 +1,7 @@\n import logging\n \n-import pywcs\n import numpy as np\n \n-import pyfits.core\n-\n __all__ = ['Coordinates', 'WCSCoordinates', 'WCSCube']\n \n \n@@ -43,12 +40,14 @@ class WCSCoordinates(Coordinates):\n def __init__(self, header):\n super(WCSCoordinates, self).__init__()\n self._header = header\n- self._wcs = pywcs.WCS(header)\n+ from astropy import wcs\n+ self._wcs = wcs.WCS(header)\n \n def __setstate__(self, state):\n self.__dict__ = state\n # wcs object doesn't seem to unpickle properly. reconstruct it\n- self._wcs = pywcs.WCS(self._header)\n+ from astropy import wcs\n+ self._wcs = wcs.WCS(self._header)\n \n def pixel2world(self, xpix, ypix):\n '''\n@@ -145,8 +144,9 @@ class WCSCubeCoordinates(WCSCoordinates):\n \n def __init__(self, header):\n super(WCSCubeCoordinates, self).__init__(header)\n- if not isinstance(header, pyfits.core.Header):\n- raise TypeError(\"Header must by a pyfits header instance\")\n+ from astropy.io import fits\n+ if not isinstance(header, fits.Header):\n+ raise TypeError(\"Header must by an astropy.io.fits.Header instance\")\n \n if 'NAXIS' not in header or header['NAXIS'] != 3:\n raise AttributeError(\"Header must describe a 3D array\")\n@@ -173,10 +173,12 @@ def __init__(self, header):\n \"%s = %s\" %\n (k, header[k]))\n self._fix_header_for_2d()\n- self._wcs = pywcs.WCS(header)\n+\n+ from astropy import wcs\n+ self._wcs = wcs.WCS(header)\n \n def _fix_header_for_2d(self):\n- #workaround for pywcs -- need to remove 3D header keywords\n+ #workaround for astropy.wcs -- need to remove 3D header keywords\n self._header['NAXIS'] = 2\n for tag in ['NAXIS3', 'CDELT3', 'CD3_3', 'CRPIX3', 'CRVAL3', 'CTYPE3']:\n if tag in self._header:\n@@ -208,7 +210,7 @@ def coordinates_from_header(header):\n \"\"\" Convert a FITS header into a glue Coordinates object\n \n :param header: Header to convert\n- :type header: :class:`pyfits.Header`\n+ :type header: :class:`astropy.io.fits.Header`\n \n :rtype: :class:`~glue.core.coordinates.Coordinates`\n \"\"\"\ndiff --git a/glue/core/data.py b/glue/core/data.py\n--- a/glue/core/data.py\n+++ b/glue/core/data.py\n@@ -2,7 +2,6 @@\n import logging\n \n import numpy as np\n-import pyfits\n \n from .io import extract_data_fits, extract_data_hdf5\n from .coordinates import Coordinates, coordinates_from_header\n@@ -673,8 +672,9 @@ def read_data(self, filename, format='auto', **kwargs):\n \n # Read in the data\n if format in ['fits', 'fit']:\n+ from astropy.io import fits\n arrays = extract_data_fits(filename, **kwargs)\n- header = pyfits.open(filename, memmap=True)[0].header\n+ header = fits.open(filename, memmap=True)[0].header\n self.coords = coordinates_from_header(header)\n elif format in ['hdf', 'hdf5', 'h5']:\n arrays = extract_data_hdf5(filename, **kwargs)\ndiff --git a/glue/core/io.py b/glue/core/io.py\n--- a/glue/core/io.py\n+++ b/glue/core/io.py\n@@ -7,10 +7,10 @@ def extract_data_fits(filename, use_hdu='all'):\n Exception is raised.\n '''\n \n- import pyfits\n+ from astropy.io import fits\n \n # Read in all HDUs\n- hdulist = pyfits.open(filename, memmap=True)\n+ hdulist = fits.open(filename, memmap=True)\n \n # If only a subset are requested, extract those\n if use_hdu != 'all':\n@@ -18,8 +18,8 @@ def extract_data_fits(filename, use_hdu='all'):\n \n # Now only keep HDUs that are not tables\n for hdu in hdulist:\n- if not isinstance(hdu, pyfits.PrimaryHDU) and \\\n- not isinstance(hdu, pyfits.ImageHDU):\n+ if not isinstance(hdu, fits.PrimaryHDU) and \\\n+ not isinstance(hdu, fits.ImageHDU):\n hdulist.remove(hdu)\n \n # Check that dimensions of all HDU are the same\ndiff --git a/glue/core/subset.py b/glue/core/subset.py\n--- a/glue/core/subset.py\n+++ b/glue/core/subset.py\n@@ -1,6 +1,5 @@\n import operator\n import numpy as np\n-import pyfits\n \n from .visual import VisualAttributes, RED\n from .decorators import memoize_attr_check\n@@ -194,13 +193,15 @@ def write_mask(self, file_name, format=\"fits\"):\n \"\"\"\n mask = np.short(self.to_mask())\n if format == 'fits':\n- pyfits.writeto(file_name, mask, clobber=True)\n+ from astropy.io import fits\n+ fits.writeto(file_name, mask, clobber=True)\n else:\n raise AttributeError(\"format not supported: %s\" % format)\n \n def read_mask(self, file_name):\n try:\n- mask = pyfits.open(file_name)[0].data\n+ from astropy.io import fits\n+ mask = fits.open(file_name)[0].data\n except IOError:\n raise IOError(\"Could not read %s (not a fits file?)\" % file_name)\n ind = np.where(mask.flat)[0]\n", "test_patch": "diff --git a/glue/core/tests/test_coordinates.py b/glue/core/tests/test_coordinates.py\n--- a/glue/core/tests/test_coordinates.py\n+++ b/glue/core/tests/test_coordinates.py\n@@ -1,7 +1,6 @@\n #pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103\n import pytest\n \n-from pyfits import Header, Card\n from mock import patch\n import numpy as np\n from numpy.testing import assert_almost_equal\n@@ -12,7 +11,8 @@\n class TestWcsCoordinates(object):\n \n def default_header(self):\n- hdr = Header()\n+ from astropy.io import fits\n+ hdr = fits.Header()\n hdr.update('NAXIS', 2)\n hdr.update('CRVAL1', 0)\n hdr.update('CRVAL2', 5)\n@@ -235,6 +235,7 @@ def test_attribute_error(self):\n \n \n def header_from_string(string):\n+ from astropy.io import fits\n cards = []\n for s in string.splitlines():\n try:\n@@ -247,8 +248,8 @@ def header_from_string(string):\n pass\n except ValueError:\n continue\n- cards.append(Card(key, value))\n- return Header(cards)\n+ cards.append(fits.Card(key, value))\n+ return fits.Header(cards)\n \n \n @pytest.mark.parametrize(('hdr'), (HDR_2D_VALID, HDR_3D_VALID_NOWCS))\ndiff --git a/glue/core/tests/test_subset.py b/glue/core/tests/test_subset.py\n--- a/glue/core/tests/test_subset.py\n+++ b/glue/core/tests/test_subset.py\n@@ -5,7 +5,6 @@\n import pytest\n import numpy as np\n from mock import MagicMock\n-import pyfits\n \n from ..data import Data, ComponentID, Component\n from ..subset import Subset, SubsetState, ElementSubsetState\n@@ -308,7 +307,8 @@ def setup_method(self, method):\n def test_write(self):\n with tempfile.NamedTemporaryFile() as tmp:\n self.subset.write_mask(tmp.name)\n- data = pyfits.open(tmp.name)[0].data\n+ from astropy.io import fits\n+ data = fits.open(tmp.name)[0].data\n expected = np.array([[0, 1, 1, 1],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n", "problem_statement": "", "hints_text": "", "created_at": "2012-09-23T15:03:37Z"} diff --git a/PythonDataset/dev/gwells-task-instances.jsonl.all b/PythonDataset/dev/gwells-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..f2de5c2c59bc7c4ed211a9a1d694e0e34add3821 --- /dev/null +++ b/PythonDataset/dev/gwells-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "bcgov/gwells", "pull_number": 1031, "instance_id": "bcgov__gwells-1031", "issue_numbers": "", "base_commit": "23f8a27ee1da1673fb8522056ca1d0168fd051c2", "patch": "diff --git a/app/backend/wells/management/__init__.py b/app/backend/wells/management/__init__.py\nnew file mode 100644\ndiff --git a/app/backend/wells/management/commands/__init__.py b/app/backend/wells/management/commands/__init__.py\nnew file mode 100644\ndiff --git a/app/backend/wells/management/commands/export.py b/app/backend/wells/management/commands/export.py\nnew file mode 100644\n--- /dev/null\n+++ b/app/backend/wells/management/commands/export.py\n@@ -0,0 +1,228 @@\n+import csv\n+import zipfile\n+import os\n+import logging\n+import string\n+\n+from django.core.management.base import BaseCommand\n+from django.db import models\n+from django.db import connection\n+\n+from minio import Minio\n+from openpyxl import Workbook\n+\n+from gwells.settings.base import get_env_variable\n+\n+# Run from command line :\n+# python manage.py export\n+\n+logger = logging.getLogger(__name__)\n+\n+\n+class Command(BaseCommand):\n+\n+ def handle(self, *args, **options):\n+ logger.info('starting export')\n+ zip_filename = 'gwells.zip'\n+ spreadsheet_filename = 'gwells.xlsx'\n+ self.generate_files(zip_filename, spreadsheet_filename)\n+ self.upload_files(zip_filename, spreadsheet_filename)\n+ logger.info('cleaning up')\n+ for filename in (zip_filename, spreadsheet_filename):\n+ if os.path.exists(filename):\n+ os.remove(filename)\n+ logger.info('export complete')\n+\n+ def upload_files(self, zip_filename, spreadsheet_filename):\n+ minioClient = Minio(get_env_variable('S3_HOST'),\n+ access_key=get_env_variable('S3_PUBLIC_ACCESS_KEY'),\n+ secret_key=get_env_variable('S3_PUBLIC_SECRET_KEY'),\n+ secure=True)\n+ for filename in (zip_filename, spreadsheet_filename):\n+ logger.info('uploading {}'.format(filename))\n+ with open(filename, 'rb') as file_data:\n+ file_stat = os.stat(filename)\n+ # Do we need to remove the existing files 1st?\n+ minioClient.put_object(get_env_variable('S3_WELL_EXPORT_BUCKET'),\n+ filename,\n+ file_data,\n+ file_stat.st_size)\n+\n+ def export(self, workbook, gwells_zip, worksheet_name, cursor):\n+ logger.info('exporting {}'.format(worksheet_name))\n+ worksheet = workbook.create_sheet(worksheet_name)\n+ csv_file = '{}.csv'.format(worksheet_name)\n+ if os.path.exists(csv_file):\n+ os.remove(csv_file)\n+ with open(csv_file, 'w') as csvfile:\n+ csvwriter = csv.writer(csvfile, dialect='excel')\n+\n+ values = []\n+ # Write the headings\n+ for index, field in enumerate(cursor.description):\n+ values.append(field.name)\n+ worksheet.append(values)\n+ csvwriter.writerow(values)\n+\n+ # Write the values\n+ row_index = 0\n+ for row, record in enumerate(cursor.fetchall()):\n+ values = []\n+ num_values = 0\n+ for col, value in enumerate(record):\n+ if not (value == \"\" or value is None):\n+ num_values += 1\n+ if type(value) is str:\n+ # There are lots of non-printable characters in the source data that can cause\n+ # issues in the export, so we have to clear them out.\n+ v = ''.join([s for s in value if s in string.printable])\n+ # We can't have something starting with an = sign,\n+ # it would be interpreted as a formula in excel.\n+ if v.startswith('='):\n+ v = '\\'{}'.format(v)\n+ values.append(v)\n+ else:\n+ values.append(value)\n+ if num_values > 1:\n+ csvwriter.writerow(values)\n+ worksheet.append(values)\n+ gwells_zip.write(csv_file)\n+ if os.path.exists(csv_file):\n+ os.remove(csv_file)\n+\n+ def generate_files(self, zip_filename, spreadsheet_filename):\n+ #######\n+ # WELL\n+ #######\n+ well_sql = (\"\"\"select well_tag_number, identification_plate_number,\n+ well_identification_plate_attached,\n+ well_status_code, well.well_class_code,\n+ wsc.well_class_code as well_subclass,\n+ intended_water_use_code, licenced_status_code,\n+ observation_well_number, obs_well_status_code, water_supply_system_name,\n+ water_supply_system_well_name,\n+ street_address, city, legal_lot, legal_plan, legal_district_lot, legal_block,\n+ legal_section, legal_township, legal_range,\n+ land_district_code,\n+ legal_pid,\n+ well_location_description,\n+ latitude, longitude, utm_zone_code, utm_northing, utm_easting,\n+ utm_accuracy_code, bcgs_id,\n+ construction_start_date, construction_end_date, alteration_start_date,\n+ alteration_end_date, decommission_start_date, decommission_end_date,\n+ driller_name, consultant_name, consultant_company,\n+ diameter, total_depth_drilled, finished_well_depth, final_casing_stick_up,\n+ bedrock_depth, ground_elevation, ground_elevation_method_code, static_water_level,\n+ well_yield,\n+ well_yield_unit_code,\n+ artesian_flow, artesian_pressure, well_cap_type, well_disinfected,\n+ drilling_method_code, other_drilling_method, well_orientation,\n+ alternative_specs_submitted,\n+ surface_seal_material_code, surface_seal_method_code, surface_seal_length,\n+ backfill_type,\n+ backfill_depth,\n+ liner_material_code, liner_diameter, liner_thickness, surface_seal_thickness,\n+ liner_from, liner_to,\n+ screen_intake_method_code, screen_type_code, screen_material_code,\n+ other_screen_material,\n+ screen_opening_code, screen_bottom_code, other_screen_bottom, development_method_code,\n+ filter_pack_from,\n+ filter_pack_to, filter_pack_material_code,\n+ filter_pack_thickness,\n+ filter_pack_material_size_code,\n+ development_hours, development_notes,\n+ water_quality_colour, water_quality_odour, ems_id,\n+ decommission_reason, decommission_method_code, decommission_details, sealant_material,\n+ backfill_material,\n+ comments, aquifer_id,\n+ drilling_company.drilling_company_code,\n+ ems,\n+ aquifer_id,\n+ registries_person.surname as driller_responsible\n+ from well\n+ left join well_subclass_code as wsc on wsc.well_subclass_guid = well.well_subclass_guid\n+ left join drilling_company on\n+ drilling_company.drilling_company_guid = well.drilling_company_guid\n+ left join registries_person on\n+ registries_person.person_guid = well.driller_responsible_guid\n+ order by well_tag_number\"\"\")\n+ ###########\n+ # LITHOLOGY\n+ ###########\n+ lithology_sql = (\"\"\"select well_tag_number, lithology_from, lithology_to, lithology_raw_data,\n+ ldc.description as lithology_description_code,\n+ lmc.description as lithology_material_code,\n+ lhc.description as lithology_hardness_code,\n+ lcc.description as lithology_colour_code,\n+ water_bearing_estimated_flow,\n+ well_yield_unit_code, lithology_observation\n+ from lithology_description\n+ left join lithology_description_code as ldc on\n+ ldc.lithology_description_code = lithology_description.lithology_description_code\n+ left join lithology_material_code as lmc on\n+ lmc.lithology_material_code = lithology_description.lithology_material_code\n+ left join lithology_hardness_code as lhc on\n+ lhc.lithology_hardness_code = lithology_description.lithology_hardness_code\n+ left join lithology_colour_code as lcc on\n+ lcc.lithology_colour_code = lithology_description.lithology_colour_code\n+ order by well_tag_number\"\"\")\n+ ########\n+ # CASING\n+ ########\n+ casing_sql = (\"\"\"select well_tag_number, casing_from, casing_to, diameter, casing_code,\n+ casing_material_code, wall_thickness, drive_shoe from casing\n+ order by well_tag_number\"\"\")\n+ ########\n+ # SCREEN\n+ ########\n+ screen_sql = (\"\"\"select well_tag_number, screen_from, screen_to, internal_diameter,\n+ screen_assembly_type_code, slot_size from screen\n+ order by well_tag_number\"\"\")\n+ ############\n+ # PRODUCTION\n+ ############\n+ production_sql = (\"\"\"select well_tag_number, yield_estimation_method_code, well_yield_unit_code,\n+ yield_estimation_rate,\n+ yield_estimation_duration, static_level, drawdown,\n+ hydro_fracturing_performed, hydro_fracturing_yield_increase from production_data\n+ order by well_tag_number\"\"\")\n+ ##############\n+ # PERFORATIONS\n+ ##############\n+ perforation_sql = (\"\"\"select well_tag_number, liner_from, liner_to, liner_diameter,\n+ liner_perforation_from, liner_perforation_to, liner_thickness\n+ from\n+ perforation\n+ order by well_tag_number\"\"\")\n+\n+ if os.path.exists(zip_filename):\n+ os.remove(zip_filename)\n+ with zipfile.ZipFile(zip_filename, 'w') as gwells_zip:\n+ if os.path.exists(spreadsheet_filename):\n+ os.remove(spreadsheet_filename)\n+ workbook = Workbook(write_only=True)\n+ # Well\n+ with connection.cursor() as cursor:\n+ cursor.execute(well_sql)\n+ self.export(workbook, gwells_zip, 'well', cursor)\n+ # Lithology\n+ with connection.cursor() as cursor:\n+ cursor.execute(lithology_sql)\n+ self.export(workbook, gwells_zip, 'lithology', cursor)\n+ # Casing\n+ with connection.cursor() as cursor:\n+ cursor.execute(casing_sql)\n+ self.export(workbook, gwells_zip, 'casing', cursor)\n+ # Screen\n+ with connection.cursor() as cursor:\n+ cursor.execute(screen_sql)\n+ self.export(workbook, gwells_zip, 'screen', cursor)\n+ # Production\n+ with connection.cursor() as cursor:\n+ cursor.execute(production_sql)\n+ self.export(workbook, gwells_zip, 'production', cursor)\n+ # Perforation\n+ with connection.cursor() as cursor:\n+ cursor.execute(perforation_sql)\n+ self.export(workbook, gwells_zip, 'perforation', cursor)\n+ workbook.save(filename=spreadsheet_filename)\ndiff --git a/app/backend/wells/urls.py b/app/backend/wells/urls.py\n--- a/app/backend/wells/urls.py\n+++ b/app/backend/wells/urls.py\n@@ -36,6 +36,9 @@\n url(r'^api/v1/wells/(?P[0-9]+)/files$',\n never_cache(views.ListFiles.as_view()), name='file-list'),\n \n+ # Extract files\n+ url(r'^api/v1/wells/extracts$', views.ListExtracts.as_view(), name='extract-list'),\n+\n # Well list\n url(r'^api/v1/wells/$',\n never_cache(views.WellListAPIView.as_view()), name='well-list'),\ndiff --git a/app/backend/wells/views.py b/app/backend/wells/views.py\n--- a/app/backend/wells/views.py\n+++ b/app/backend/wells/views.py\n@@ -11,6 +11,7 @@\n See the License for the specific language governing permissions and\n limitations under the License.\n \"\"\"\n+from urllib.parse import quote\n \n from django.db.models import Prefetch\n from django.http import Http404\n@@ -24,10 +25,13 @@\n \n from drf_yasg.utils import swagger_auto_schema\n \n+from minio import Minio\n+\n from gwells import settings\n from gwells.models import Survey\n from gwells.roles import WELLS_VIEWER_ROLE, WELLS_EDIT_ROLE\n from gwells.pagination import APILimitOffsetPagination\n+from gwells.settings.base import get_env_variable\n \n from wells.models import Well\n from wells.documents import MinioClient\n@@ -65,6 +69,45 @@ def get_serializer(self, data):\n lookup_field = 'well_tag_number'\n \n \n+class ListExtracts(APIView):\n+ \"\"\"\n+ List well extracts\n+\n+ get: list well extracts\n+ \"\"\"\n+ @swagger_auto_schema(auto_schema=None)\n+ def get(self, request):\n+ host = get_env_variable('S3_HOST')\n+ minioClient = Minio(host,\n+ access_key=get_env_variable('S3_PUBLIC_ACCESS_KEY'),\n+ secret_key=get_env_variable('S3_PUBLIC_SECRET_KEY'),\n+ secure=True)\n+ objects = minioClient.list_objects(get_env_variable('S3_WELL_EXPORT_BUCKET'))\n+ urls = list(\n+ map(\n+ lambda document: {\n+ 'url': 'https://{}/{}/{}'.format(host,\n+ quote(document.bucket_name),\n+ quote(document.object_name)),\n+ 'name': document.object_name,\n+ 'size': document.size,\n+ 'last_modified': document.last_modified,\n+ 'description': self.create_description(document.object_name)\n+ }, objects)\n+ )\n+ return Response(urls)\n+\n+ def create_description(self, name):\n+ extension = name[name.rfind('.')+1:]\n+ print(extension)\n+ if extension == 'zip':\n+ return 'ZIP, CSV'\n+ elif extension == 'xlsx':\n+ return 'XLSX'\n+ else:\n+ return None\n+\n+\n class ListFiles(APIView):\n \"\"\"\n List documents associated with a well (e.g. well construction report)\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2018-11-20T23:25:57Z"} diff --git a/PythonDataset/dev/inky-task-instances.jsonl.all b/PythonDataset/dev/inky-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..3617c03f3de844adf18eb0e6f933c3e9fd86c1c0 --- /dev/null +++ b/PythonDataset/dev/inky-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "pimoroni/inky", "pull_number": 24, "instance_id": "pimoroni__inky-24", "issue_numbers": "", "base_commit": "5f70ca8db69d8bcea79cb5faf1f0d59f358d555e", "patch": "diff --git a/library/inky/eeprom.py b/library/inky/eeprom.py\n--- a/library/inky/eeprom.py\n+++ b/library/inky/eeprom.py\n@@ -4,7 +4,7 @@\n \n import datetime\n import struct\n-import smbus\n+from smbus2 import SMBus\n \n EEP_ADRESS = 0x50\n EEP_WP = 12\n@@ -95,7 +95,7 @@ def get_color(self):\n def read_eeprom():\n \"\"\"Return a class representing EEPROM contents, or none.\"\"\"\n try:\n- i2c = smbus.SMBus(1)\n+ i2c = SMBus(1)\n i2c.write_i2c_block_data(EEP_ADRESS, 0x00, [0x00])\n return EPDType.from_bytes(i2c.read_i2c_block_data(0x50, 0, 29))\n except IOError:\ndiff --git a/library/inky/inky.py b/library/inky/inky.py\n--- a/library/inky/inky.py\n+++ b/library/inky/inky.py\n@@ -13,7 +13,7 @@\n sys.exit('This library requires the RPi.GPIO module\\nInstall with: sudo apt install python-rpi.gpio')\n \n try:\n- import smbus\n+ from smbus2 import SMBus\n except ImportError:\n sys.exit('This library requires the SMBus module\\nInstall with: sudo apt install python-smbus')\n \ndiff --git a/library/setup.py b/library/setup.py\n--- a/library/setup.py\n+++ b/library/setup.py\n@@ -53,5 +53,5 @@\n py_modules=[],\n packages=['inky'],\n include_package_data=True,\n- install_requires=['numpy', 'spidev', 'RPi.GPIO']\n+ install_requires=['numpy', 'spidev', 'RPi.GPIO', 'smbus2']\n )\n", "test_patch": "diff --git a/library/tests/test_init.py b/library/tests/test_init.py\n--- a/library/tests/test_init.py\n+++ b/library/tests/test_init.py\n@@ -9,8 +9,8 @@ def mockery():\n sys.modules['RPi'] = mock.Mock()\n sys.modules['RPi.GPIO'] = mock.Mock()\n sys.modules['spidev'] = mock.Mock()\n- sys.modules['smbus'] = mock.Mock()\n- sys.modules['smbus'].SMBus = MockSMBus\n+ sys.modules['smbus2'] = mock.Mock()\n+ sys.modules['smbus2'].SMBus = MockSMBus\n \n \n def test_init_phat_black():\n", "problem_statement": "", "hints_text": "", "created_at": "2019-03-03T02:30:46Z"} diff --git a/PythonDataset/dev/kinto-task-instances.jsonl.all b/PythonDataset/dev/kinto-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..6664e273f9adcec020d1a0e495422ee3c87384a8 --- /dev/null +++ b/PythonDataset/dev/kinto-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "Kinto/kinto", "pull_number": 2737, "instance_id": "Kinto__kinto-2737", "issue_numbers": "", "base_commit": "6102cf98e3246b44532432df61275858653d9323", "patch": "diff --git a/kinto/core/initialization.py b/kinto/core/initialization.py\n--- a/kinto/core/initialization.py\n+++ b/kinto/core/initialization.py\n@@ -47,11 +47,11 @@ def setup_json_serializer(config):\n import requests\n import webob\n \n- # Monkey patch to use ujson\n+ # Monkey patch to use rapidjson\n webob.request.json = utils.json\n requests.models.json = utils.json\n \n- # Override json renderer using ujson\n+ # Override json renderer using rapidjson\n renderer = JSONRenderer(serializer=utils.json_serializer)\n config.add_renderer(\"ultrajson\", renderer) # See `kinto.core.Service`\n \ndiff --git a/kinto/core/utils.py b/kinto/core/utils.py\n--- a/kinto/core/utils.py\n+++ b/kinto/core/utils.py\n@@ -11,7 +11,7 @@\n from urllib.parse import unquote\n \n import jsonpatch\n-import ujson as json\n+import rapidjson\n from colander import null\n from cornice import cors\n from pyramid import httpexceptions\n@@ -32,8 +32,21 @@\n memcache = None\n \n \n-def json_serializer(v, **kw):\n- return json.dumps(v, escape_forward_slashes=False)\n+class json:\n+ def dumps(v, **kw):\n+ kw.setdefault(\"bytes_mode\", rapidjson.BM_NONE)\n+ return rapidjson.dumps(v, **kw)\n+\n+ def load(v, **kw):\n+ kw.setdefault(\"number_mode\", rapidjson.NM_NATIVE)\n+ return rapidjson.load(v, **kw)\n+\n+ def loads(v, **kw):\n+ kw.setdefault(\"number_mode\", rapidjson.NM_NATIVE)\n+ return rapidjson.loads(v, **kw)\n+\n+\n+json_serializer = json.dumps\n \n \n def strip_whitespace(v):\ndiff --git a/kinto/plugins/quotas/utils.py b/kinto/plugins/quotas/utils.py\n--- a/kinto/plugins/quotas/utils.py\n+++ b/kinto/plugins/quotas/utils.py\n@@ -2,6 +2,6 @@\n \n \n def record_size(record):\n- # We cannot use ultrajson here, since the `separator` option is not available.\n+ # We cannot use rapidjson here, since the `separator` option is not available.\n canonical_json = json.dumps(record, sort_keys=True, separators=(\",\", \":\"))\n return len(canonical_json)\n", "test_patch": "diff --git a/tests/test_views_schema_record.py b/tests/test_views_schema_record.py\n--- a/tests/test_views_schema_record.py\n+++ b/tests/test_views_schema_record.py\n@@ -385,3 +385,27 @@ def setUp(self):\n \n def test_records_are_valid_if_match_schema(self):\n self.app.post_json(RECORDS_URL, {\"data\": {\"title\": \"b\"}}, headers=self.headers, status=400)\n+\n+\n+class RecordsWithLargeNumbers(BaseWebTestWithSchema, unittest.TestCase):\n+ def setUp(self):\n+ super().setUp()\n+ self.app.put_json(COLLECTION_URL, {\"data\": {\"schema\": SCHEMA}}, headers=self.headers)\n+\n+ def test_record_with_number_less_than_64_bits(self):\n+ size = 2 ** 63\n+ self.app.post_json(\n+ RECORDS_URL,\n+ {\"data\": {\"title\": \"Very large file\", \"file\": {\"size\": size}}},\n+ headers=self.headers,\n+ status=201,\n+ )\n+\n+ def test_record_with_number_greater_than_64_bits(self):\n+ size = 2 ** 65\n+ self.app.post_json(\n+ RECORDS_URL,\n+ {\"data\": {\"title\": \"Very large file\", \"file\": {\"size\": size}}},\n+ headers=self.headers,\n+ status=201,\n+ )\n", "problem_statement": "", "hints_text": "", "created_at": "2021-03-04T16:32:35Z"} diff --git a/PythonDataset/test/NeMo-task-instances.jsonl.all b/PythonDataset/test/NeMo-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..19710f7cec68ce64512558017f94605188da5220 --- /dev/null +++ b/PythonDataset/test/NeMo-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "NVIDIA/NeMo", "pull_number": 162, "instance_id": "NVIDIA__NeMo-162", "issue_numbers": "", "base_commit": "f5f09838b96ab48f40d97c100fbcfc5b7f1ac59e", "patch": "diff --git a/collections/nemo_nlp/nemo_nlp/data/data_layers.py b/collections/nemo_nlp/nemo_nlp/data/data_layers.py\n--- a/collections/nemo_nlp/nemo_nlp/data/data_layers.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/data_layers.py\n@@ -683,9 +683,9 @@ def _collate_fn(self, x):\n [np.stack(x, axis=0) for x in components]\n src_ids = torch.Tensor(src_ids).long().to(self._device)\n src_segment_ids = torch.Tensor(src_segment_ids).long().to(self._device)\n- src_mask = torch.Tensor(src_mask).float().to(self._device)\n+ src_mask = torch.Tensor(src_mask).long().to(self._device)\n tgt_ids = torch.Tensor(tgt_ids).long().to(self._device)\n- tgt_mask = torch.Tensor(tgt_mask).float().to(self._device)\n+ tgt_mask = torch.Tensor(tgt_mask).long().to(self._device)\n sent_ids = torch.Tensor(sent_ids).long().to(self._device)\n return src_ids, src_segment_ids, src_mask, tgt_ids, tgt_mask, sent_ids\n \ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/bert_pretraining.py b/collections/nemo_nlp/nemo_nlp/data/datasets/bert_pretraining.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/bert_pretraining.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/bert_pretraining.py\n@@ -249,7 +249,7 @@ def truncate_seq_pair(a, b, max_num_tokens):\n \n input_ids, output_mask = self.mask_ids(output_ids)\n \n- input_mask = np.zeros(self.max_seq_length, dtype=np.float32)\n+ input_mask = np.zeros(self.max_seq_length, dtype=np.long)\n input_mask[:len(input_ids)] = 1\n \n input_type_ids = np.zeros(self.max_seq_length, dtype=np.int)\n@@ -263,7 +263,7 @@ def truncate_seq_pair(a, b, max_num_tokens):\n \n # TODO: wrap the return value with () for consistent style.\n return np.array(input_ids), input_type_ids,\\\n- np.array(input_mask, dtype=np.float32), np.array(output_ids),\\\n+ np.array(input_mask, dtype=np.long), np.array(output_ids),\\\n np.array(output_mask, dtype=np.float32), is_next\n \n def mask_ids(self, ids):\ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/glue.py b/collections/nemo_nlp/nemo_nlp/data/datasets/glue.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/glue.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/glue.py\n@@ -55,7 +55,7 @@ def __getitem__(self, idx):\n feature = self.features[idx]\n return (np.array(feature.input_ids),\n np.array(feature.segment_ids),\n- np.array(feature.input_mask, dtype=np.float32),\n+ np.array(feature.input_mask, dtype=np.long),\n np.array(feature.label_id))\n \n \ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/joint_intent_slot.py b/collections/nemo_nlp/nemo_nlp/data/datasets/joint_intent_slot.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/joint_intent_slot.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/joint_intent_slot.py\n@@ -214,7 +214,7 @@ def __len__(self):\n def __getitem__(self, idx):\n return (np.array(self.all_input_ids[idx]),\n np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx]),\n+ np.array(self.all_input_mask[idx], dtype=np.long),\n np.array(self.all_loss_mask[idx]),\n np.array(self.all_subtokens_mask[idx]),\n self.all_intents[idx],\n@@ -263,6 +263,6 @@ def __len__(self):\n def __getitem__(self, idx):\n return (np.array(self.all_input_ids[idx]),\n np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.float32),\n+ np.array(self.all_input_mask[idx], dtype=np.long),\n np.array(self.all_loss_mask[idx]),\n np.array(self.all_subtokens_mask[idx]))\ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/punctuation_capitalization.py b/collections/nemo_nlp/nemo_nlp/data/datasets/punctuation_capitalization.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/punctuation_capitalization.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/punctuation_capitalization.py\n@@ -386,7 +386,7 @@ def __len__(self):\n def __getitem__(self, idx):\n return (np.array(self.all_input_ids[idx]),\n np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.float32),\n+ np.array(self.all_input_mask[idx], dtype=np.long),\n np.array(self.all_loss_mask[idx]),\n np.array(self.all_subtokens_mask[idx]),\n np.array(self.punct_all_labels[idx]),\ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/sentence_classification.py b/collections/nemo_nlp/nemo_nlp/data/datasets/sentence_classification.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/sentence_classification.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/sentence_classification.py\n@@ -115,7 +115,7 @@ def __getitem__(self, idx):\n \n return (np.array(feature.input_ids),\n np.array(feature.segment_ids),\n- np.array(feature.input_mask, dtype=np.float32),\n+ np.array(feature.input_mask, dtype=np.long),\n feature.sent_label)\n \n def convert_sequences_to_features(self,\ndiff --git a/collections/nemo_nlp/nemo_nlp/data/datasets/token_classification.py b/collections/nemo_nlp/nemo_nlp/data/datasets/token_classification.py\n--- a/collections/nemo_nlp/nemo_nlp/data/datasets/token_classification.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/datasets/token_classification.py\n@@ -333,7 +333,7 @@ def __len__(self):\n def __getitem__(self, idx):\n return (np.array(self.all_input_ids[idx]),\n np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.float32),\n+ np.array(self.all_input_mask[idx], dtype=np.long),\n np.array(self.all_loss_mask[idx]),\n np.array(self.all_subtokens_mask[idx]),\n np.array(self.all_labels[idx]))\n@@ -377,6 +377,6 @@ def __len__(self):\n def __getitem__(self, idx):\n return (np.array(self.all_input_ids[idx]),\n np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.float32),\n+ np.array(self.all_input_mask[idx], dtype=np.long),\n np.array(self.all_loss_mask[idx]),\n np.array(self.all_subtokens_mask[idx]))\ndiff --git a/collections/nemo_nlp/nemo_nlp/data/tokenizers/bert_tokenizer.py b/collections/nemo_nlp/nemo_nlp/data/tokenizers/bert_tokenizer.py\n--- a/collections/nemo_nlp/nemo_nlp/data/tokenizers/bert_tokenizer.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/tokenizers/bert_tokenizer.py\n@@ -1,5 +1,5 @@\n from .tokenizer_spec import TokenizerSpec\n-from pytorch_transformers import BertTokenizer\n+from transformers import BertTokenizer\n import re\n \n \ndiff --git a/collections/nemo_nlp/nemo_nlp/data/tokenizers/gpt2_tokenizer.py b/collections/nemo_nlp/nemo_nlp/data/tokenizers/gpt2_tokenizer.py\n--- a/collections/nemo_nlp/nemo_nlp/data/tokenizers/gpt2_tokenizer.py\n+++ b/collections/nemo_nlp/nemo_nlp/data/tokenizers/gpt2_tokenizer.py\n@@ -1,5 +1,5 @@\n from .tokenizer_spec import TokenizerSpec\n-from pytorch_transformers import GPT2Tokenizer\n+from transformers import GPT2Tokenizer\n \n \n class NemoGPT2Tokenizer(TokenizerSpec):\ndiff --git a/collections/nemo_nlp/nemo_nlp/huggingface/bert.py b/collections/nemo_nlp/nemo_nlp/huggingface/bert.py\n--- a/collections/nemo_nlp/nemo_nlp/huggingface/bert.py\n+++ b/collections/nemo_nlp/nemo_nlp/huggingface/bert.py\n@@ -1,10 +1,10 @@\n # Copyright (c) 2019 NVIDIA Corporation\n from typing import Optional, List\n \n-from pytorch_transformers import (BertConfig,\n- BertModel,\n- BERT_PRETRAINED_MODEL_ARCHIVE_MAP,\n- BERT_PRETRAINED_CONFIG_ARCHIVE_MAP)\n+from transformers import (BertConfig,\n+ BertModel,\n+ BERT_PRETRAINED_MODEL_ARCHIVE_MAP,\n+ BERT_PRETRAINED_CONFIG_ARCHIVE_MAP)\n \n from nemo.backends.pytorch.nm import TrainableNM\n from nemo.core.neural_modules import PretrainedModelInfo\n@@ -18,7 +18,7 @@\n class BERT(TrainableNM):\n \"\"\"\n BERT wraps around the Huggingface implementation of BERT from their\n- pytorch-transformers repository for easy use within NeMo.\n+ transformers repository for easy use within NeMo.\n \n Args:\n pretrained_model_name (str): If using a pretrained model, this should\ndiff --git a/collections/nemo_nlp/setup.py b/collections/nemo_nlp/setup.py\n--- a/collections/nemo_nlp/setup.py\n+++ b/collections/nemo_nlp/setup.py\n@@ -25,7 +25,7 @@\n 'python-dateutil<2.8.1,>=2.1',\n 'boto3',\n 'unidecode',\n- 'pytorch-transformers',\n+ 'transformers',\n 'matplotlib',\n 'h5py',\n 'youtokentome'\ndiff --git a/examples/nlp/joint_intent_slot_infer.py b/examples/nlp/joint_intent_slot_infer.py\n--- a/examples/nlp/joint_intent_slot_infer.py\n+++ b/examples/nlp/joint_intent_slot_infer.py\n@@ -2,7 +2,7 @@\n import os\n \n import numpy as np\n-from pytorch_transformers import BertTokenizer\n+from transformers import BertTokenizer\n from sklearn.metrics import confusion_matrix, classification_report\n \n import nemo\ndiff --git a/examples/nlp/joint_intent_slot_infer_b1.py b/examples/nlp/joint_intent_slot_infer_b1.py\n--- a/examples/nlp/joint_intent_slot_infer_b1.py\n+++ b/examples/nlp/joint_intent_slot_infer_b1.py\n@@ -1,7 +1,7 @@\n import argparse\n \n import numpy as np\n-from pytorch_transformers import BertTokenizer\n+from transformers import BertTokenizer\n \n import nemo\n import nemo_nlp\ndiff --git a/examples/nlp/joint_intent_slot_with_bert.py b/examples/nlp/joint_intent_slot_with_bert.py\n--- a/examples/nlp/joint_intent_slot_with_bert.py\n+++ b/examples/nlp/joint_intent_slot_with_bert.py\n@@ -3,7 +3,7 @@\n import os\n \n import numpy as np\n-from pytorch_transformers import BertTokenizer\n+from transformers import BertTokenizer\n \n import nemo\n from nemo.utils.lr_policies import get_lr_policy\ndiff --git a/examples/nlp/sentence_classification_with_bert.py b/examples/nlp/sentence_classification_with_bert.py\n--- a/examples/nlp/sentence_classification_with_bert.py\n+++ b/examples/nlp/sentence_classification_with_bert.py\n@@ -2,7 +2,7 @@\n import math\n \n import numpy as np\n-from pytorch_transformers import BertTokenizer\n+from transformers import BertTokenizer\n from torch import nn\n import torch\n \ndiff --git a/nemo/nemo/backends/pytorch/nm.py b/nemo/nemo/backends/pytorch/nm.py\n--- a/nemo/nemo/backends/pytorch/nm.py\n+++ b/nemo/nemo/backends/pytorch/nm.py\n@@ -36,7 +36,7 @@ def __init__(self, **kwargs):\n nn.Module.__init__(self) # For PyTorch API\n self._device = get_cuda_device(self.placement)\n \n- def __call__(self, force_pt=False, *input, **kwargs):\n+ def __call__(self, *input, force_pt=False, **kwargs):\n pt_call = len(input) > 0 or force_pt\n if pt_call:\n return nn.Module.__call__(self, *input, **kwargs)\ndiff --git a/scripts/get_decoder_params_from_bert.py b/scripts/get_decoder_params_from_bert.py\n--- a/scripts/get_decoder_params_from_bert.py\n+++ b/scripts/get_decoder_params_from_bert.py\n@@ -1,6 +1,6 @@\n import torch\n-from pytorch_transformers import BERT_PRETRAINED_MODEL_ARCHIVE_MAP\n-from pytorch_transformers.file_utils import cached_path\n+from transformers import BERT_PRETRAINED_MODEL_ARCHIVE_MAP\n+from transformers.file_utils import cached_path\n import argparse\n \n state_dict_mappings = {\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2019-12-03T01:19:14Z"} diff --git a/PythonDataset/test/PypeIt-task-instances.jsonl.all b/PythonDataset/test/PypeIt-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..0807f48caf7a63591e97b7827a0ca5e9a9c70489 --- /dev/null +++ b/PythonDataset/test/PypeIt-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "pypeit/PypeIt", "pull_number": 1121, "instance_id": "pypeit__PypeIt-1121", "issue_numbers": "", "base_commit": "c755167f5b1b09fdffa8b22ebdcccc6521fdd564", "patch": "diff --git a/pypeit/datamodel.py b/pypeit/datamodel.py\n--- a/pypeit/datamodel.py\n+++ b/pypeit/datamodel.py\n@@ -946,7 +946,7 @@ def _parse(cls, hdu, ext=None, transpose_table_arrays=False, hdu_prefix=None):\n dm_version_passed &= hdu[hduindx].header['DMODVER'] == cls.version\n # Grab it\n _d[e] = _hdu[hduindx].data if isinstance(hdu[hduindx], fits.ImageHDU) \\\n- else Table.read(hdu[hduindx])\n+ else Table.read(hdu[hduindx]).copy()\n \n for e in _ext:\n if 'DMODCLS' not in _hdu[e].header.keys() or 'DMODVER' not in _hdu[e].header.keys() \\\ndiff --git a/pypeit/scripts/run_pypeit.py b/pypeit/scripts/run_pypeit.py\n--- a/pypeit/scripts/run_pypeit.py\n+++ b/pypeit/scripts/run_pypeit.py\n@@ -117,6 +117,7 @@ def main(args):\n # QA HTML\n msgs.info('Generating QA HTML')\n pypeIt.build_qa()\n+ msgs.close()\n \n return 0\n \ndiff --git a/pypeit/scripts/show_1dspec.py b/pypeit/scripts/show_1dspec.py\n--- a/pypeit/scripts/show_1dspec.py\n+++ b/pypeit/scripts/show_1dspec.py\n@@ -28,7 +28,7 @@ def main(args):\n import sys\n import numpy as np\n \n- from PySide2.QtWidgets import QApplication\n+ from qtpy.QtWidgets import QApplication\n \n from linetools.guis.xspecgui import XSpecGui\n \n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2021-01-07T20:52:53Z"} diff --git a/PythonDataset/test/Userge-Plugins-task-instances.jsonl.all b/PythonDataset/test/Userge-Plugins-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..de307be3b1ddc8b5d6b782d7e0ffcf4e481a5407 --- /dev/null +++ b/PythonDataset/test/Userge-Plugins-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "UsergeTeam/Userge-Plugins", "pull_number": 186, "instance_id": "UsergeTeam__Userge-Plugins-186", "issue_numbers": "", "base_commit": "1969de7afbe06cc3b0248b09f48fe9f85ffef07c", "patch": "diff --git a/plugins/info.py b/plugins/info.py\n--- a/plugins/info.py\n+++ b/plugins/info.py\n@@ -3,7 +3,8 @@\n # By @Krishna_Singhal\n \n import spamwatch\n-import requests\n+import aiohttp\n+import json\n from datetime import datetime\n \n from userge import userge, Config, Message, get_collection\n@@ -55,27 +56,41 @@ async def info(msg: Message):\n user_info += \"\\n**SpamWatch Banned** : `False`\\n\"\n else:\n user_info += \"\\n**SpamWatch Banned** : `True`\\n\"\n- user_info += f\"**\u2022Reason** : `{status.reason or None}`\\n\"\n- user_info += f\"**\u2022Message** : `{status.message or None}`\\n\"\n+ user_info += f\" **\u25cf Reason** : `{status.reason or None}`\\n\"\n+ user_info += f\" **\u25cf Message** : `{status.message or None}`\\n\"\n else:\n- user_info += \"\\n**SpamWatch Banned** : `To get this Info, Set Var`\\n\"\n- cas_banned = requests.get(f'https://api.cas.chat/check?user_id={user.id}').json()\n+ user_info += \"\\n**SpamWatch Banned** : `to get this Info, set var`\\n\"\n+\n+ async with aiohttp.ClientSession() as ses:\n+ async with ses.get(\n+ f\"https://api.intellivoid.net/spamprotection/v1/lookup?query={user_id}\"\n+ ) as i_v:\n+ iv = json.loads(await i_v.text)\n+ async with ses.get(f'https://api.cas.chat/check?user_id={user.id}') as c_s:\n+ cas_banned = json.loads(await c_s.text)\n+ user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})\n+ user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})\n+\n+ if iv['success'] and iv['results']['attributes']['is_blacklisted'] is True:\n+ reason = iv['results']['attributes']['blacklist_reason']\n+ user_info += \"**Intellivoid SpamProtection** : `True`\\n\"\n+ user_info += f\" **\u25cf Reason** : `{reason}`\\n\"\n+ else:\n+ user_info += \"**Intellivoid SpamProtection** : `False`\\n\"\n if cas_banned['ok']:\n reason = cas_banned['result']['messages'][0] or None\n user_info += \"**AntiSpam Banned** : `True`\\n\"\n- user_info += f\"**\u2022Reason** : `{reason}`\\n\"\n+ user_info += f\" **\u25cf Reason** : `{reason}`\\n\"\n else:\n user_info += \"**AntiSpam Banned** : `False`\\n\"\n- user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})\n if user_gmuted:\n user_info += \"**User GMuted** : `True`\\n\"\n- user_info += f\"**\u2022Reason** : `{user_gmuted['reason'] or None}`\\n\"\n+ user_info += f\" **\u25cf Reason** : `{user_gmuted['reason'] or None}`\\n\"\n else:\n user_info += \"**User GMuted** : `False`\\n\"\n- user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})\n if user_gbanned:\n user_info += \"**User GBanned** : `True`\\n\"\n- user_info += f\"**\u2022Reason** : `{user_gbanned['reason'] or None}`\"\n+ user_info += f\" **\u25cf Reason** : `{user_gbanned['reason'] or None}`\"\n else:\n user_info += \"**User Gbanned** : `False`\"\n await msg.edit_or_send_as_file(text=user_info, disable_web_page_preview=True)\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2021-02-17T06:03:59Z"} diff --git a/PythonDataset/test/decomp-permuter-task-instances.jsonl.all b/PythonDataset/test/decomp-permuter-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..805692fa8170edaea3e0552c048b6452c2317ee1 --- /dev/null +++ b/PythonDataset/test/decomp-permuter-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "simonlindholm/decomp-permuter", "pull_number": 97, "instance_id": "simonlindholm__decomp-permuter-97", "issue_numbers": "", "base_commit": "939c92b0b093ab0290a94d882b19c5f8a186b2a1", "patch": "diff --git a/pah.py b/pah.py\nnew file mode 100755\n--- /dev/null\n+++ b/pah.py\n@@ -0,0 +1,4 @@\n+#!/usr/bin/env python3\n+from src.net.cmd.main import main\n+\n+main()\ndiff --git a/src/candidate.py b/src/candidate.py\n--- a/src/candidate.py\n+++ b/src/candidate.py\n@@ -19,15 +19,13 @@\n \n @dataclass\n class CandidateResult:\n- \"\"\"\n- Represents the result of scoring a candidate, and is sent from child to\n- parent processes.\n- \"\"\"\n+ \"\"\"Represents the result of scoring a candidate, and is sent from child to\n+ parent processes, or server to client with p@h.\"\"\"\n \n score: int\n- hash: str\n+ hash: Optional[str]\n source: Optional[str]\n- profiler: Profiler = field(default_factory=Profiler)\n+ profiler: Optional[Profiler] = None\n \n \n @dataclass\ndiff --git a/src/error.py b/src/error.py\n--- a/src/error.py\n+++ b/src/error.py\n@@ -1,6 +1,11 @@\n from dataclasses import dataclass\n \n \n+@dataclass\n+class ServerError(Exception):\n+ message: str\n+\n+\n @dataclass\n class CandidateConstructionFailure(Exception):\n message: str\ndiff --git a/src/helpers.py b/src/helpers.py\n--- a/src/helpers.py\n+++ b/src/helpers.py\n@@ -1,4 +1,13 @@\n import os\n+from typing import NoReturn\n+\n+\n+def exception_to_string(e: object) -> str:\n+ return str(e) or e.__class__.__name__\n+\n+\n+def static_assert_unreachable(x: NoReturn) -> NoReturn:\n+ raise Exception(\"Unreachable! \" + repr(x))\n \n \n def try_remove(path: str) -> None:\ndiff --git a/src/main.py b/src/main.py\n--- a/src/main.py\n+++ b/src/main.py\n@@ -2,9 +2,13 @@\n from dataclasses import dataclass, field\n import itertools\n import multiprocessing\n+from multiprocessing import Queue\n import os\n+import queue\n+import random\n from random import Random\n import sys\n+import threading\n import time\n from typing import (\n Callable,\n@@ -16,14 +20,27 @@\n Tuple,\n )\n \n-from .error import CandidateConstructionFailure\n-from .preprocess import preprocess\n from .candidate import CandidateResult\n from .compiler import Compiler\n-from .scorer import Scorer\n-from .permuter import EvalError, EvalResult, Permuter\n+from .error import CandidateConstructionFailure\n+from .helpers import static_assert_unreachable\n+from .net.client import start_client\n+from .net.core import ServerError, connect, enable_debug_mode, MAX_PRIO, MIN_PRIO\n+from .permuter import (\n+ EvalError,\n+ EvalResult,\n+ Feedback,\n+ Finished,\n+ Message,\n+ NeedMoreWork,\n+ Permuter,\n+ Task,\n+ WorkDone,\n+)\n+from .preprocess import preprocess\n from .printer import Printer\n from .profiler import Profiler\n+from .scorer import Scorer\n \n # The probability that the randomizer continues transforming the output it\n # generated last time.\n@@ -44,6 +61,9 @@ class Options:\n keep_prob: float = DEFAULT_RAND_KEEP_PROB\n force_seed: Optional[str] = None\n threads: int = 1\n+ use_network: bool = False\n+ network_debug: bool = False\n+ network_priority: float = 1.0\n \n \n def restricted_float(lo: float, hi: float) -> Callable[[str], float]:\n@@ -62,6 +82,11 @@ def convert(x: str) -> float:\n return convert\n \n \n+def plural(n: int, noun: str) -> str:\n+ s = \"s\" if n != 1 else \"\"\n+ return f\"{n} {noun}{s}\"\n+\n+\n @dataclass\n class EvalContext:\n options: Options\n@@ -94,11 +119,13 @@ def write_candidate(perm: Permuter, result: CandidateResult) -> None:\n print(f\"wrote to {output_dir}\")\n \n \n-def post_score(context: EvalContext, permuter: Permuter, result: EvalResult) -> bool:\n+def post_score(\n+ context: EvalContext, permuter: Permuter, result: EvalResult, who: Optional[str]\n+) -> bool:\n if isinstance(result, EvalError):\n if result.exc_str is not None:\n context.printer.print(\n- \"internal permuter failure.\", permuter, keep_progress=True\n+ \"internal permuter failure.\", permuter, who, keep_progress=True\n )\n print(result.exc_str)\n if result.seed is not None:\n@@ -119,7 +146,10 @@ def post_score(context: EvalContext, permuter: Permuter, result: EvalResult) ->\n \n profiler = result.profiler\n score_value = result.score\n- score_hash = result.hash\n+\n+ if profiler is not None:\n+ for stattype in profiler.time_stats:\n+ context.overall_profiler.add_stat(stattype, profiler.time_stats[stattype])\n \n context.iteration += 1\n if score_value == permuter.scorer.PENALTY_INF:\n@@ -129,29 +159,16 @@ def post_score(context: EvalContext, permuter: Permuter, result: EvalResult) ->\n disp_score = str(score_value)\n timings = \"\"\n if context.options.show_timings:\n- for stattype in profiler.time_stats:\n- context.overall_profiler.add_stat(stattype, profiler.time_stats[stattype])\n timings = \" \\t\" + context.overall_profiler.get_str_stats()\n status_line = f\"iteration {context.iteration}, {context.errors} errors, score = {disp_score}{timings}\"\n \n- # Note: when updating this if condition, Permuter._need_to_send_source may\n- # also need to be updated, or else assertion failures will result.\n- if (\n- score_value is not None\n- and score_hash is not None\n- and not (score_value > permuter.best_score and context.options.best_only)\n- and (\n- score_value < permuter.base_score\n- or (score_value == permuter.base_score and not context.options.better_only)\n- )\n- and score_hash not in permuter.hashes\n- ):\n- if score_value != 0:\n- permuter.hashes.add(score_hash)\n- if score_value < permuter.best_score:\n+ if permuter.should_output(result):\n+ former_best = permuter.best_score\n+ permuter.record_result(result)\n+ if score_value < former_best:\n color = \"\\u001b[32;1m\"\n msg = f\"found new best score! ({score_value} vs {permuter.base_score})\"\n- elif score_value == permuter.best_score:\n+ elif score_value == former_best:\n color = \"\\u001b[32;1m\"\n msg = f\"tied best score! ({score_value} vs {permuter.base_score})\"\n elif score_value < permuter.base_score:\n@@ -160,8 +177,8 @@ def post_score(context: EvalContext, permuter: Permuter, result: EvalResult) ->\n else:\n color = \"\\u001b[33m\"\n msg = f\"found different asm with same score ({score_value})\"\n- permuter.best_score = min(permuter.best_score, score_value)\n- context.printer.print(msg, permuter, color=color)\n+ context.printer.print(msg, permuter, who, color=color)\n+\n write_candidate(permuter, result)\n context.printer.progress(status_line)\n return score_value == 0\n@@ -191,26 +208,39 @@ def cycle_seeds(permuters: List[Permuter]) -> Iterable[Tuple[int, int]]:\n \n def multiprocess_worker(\n permuters: List[Permuter],\n- input_queue: \"multiprocessing.Queue[Optional[Tuple[int, int]]]\",\n- output_queue: \"multiprocessing.Queue[Tuple[int, EvalResult]]\",\n+ input_queue: \"Queue[Task]\",\n+ output_queue: \"Queue[Feedback]\",\n ) -> None:\n- input_queue.cancel_join_thread()\n- output_queue.cancel_join_thread()\n-\n try:\n while True:\n- queue_item = input_queue.get()\n- if queue_item is None:\n+ # Read a work item from the queue. If none is immediately available,\n+ # tell the main thread to fill the queues more, and then block on\n+ # the queue.\n+ queue_item: Task\n+ try:\n+ queue_item = input_queue.get(block=False)\n+ except queue.Empty:\n+ output_queue.put((NeedMoreWork(), -1, None))\n+ queue_item = input_queue.get()\n+ if isinstance(queue_item, Finished):\n+ output_queue.put((queue_item, -1, None))\n+ output_queue.close()\n break\n permuter_index, seed = queue_item\n permuter = permuters[permuter_index]\n result = permuter.try_eval_candidate(seed)\n- output_queue.put((permuter_index, result))\n+ if isinstance(result, CandidateResult) and permuter.should_output(result):\n+ permuter.record_result(result)\n+ output_queue.put((WorkDone(permuter_index, result), -1, None))\n+ output_queue.put((NeedMoreWork(), -1, None))\n except KeyboardInterrupt:\n # Don't clutter the output with stack traces; Ctrl+C is the expected\n # way to quit and sends KeyboardInterrupt to all processes.\n # A heartbeat thing here would be good but is too complex.\n- pass\n+ # Don't join the queue background thread -- thread joins in relation\n+ # to KeyboardInterrupt usually result in deadlocks.\n+ input_queue.cancel_join_thread()\n+ output_queue.cancel_join_thread()\n \n \n def run(options: Options) -> List[int]:\n@@ -285,8 +315,11 @@ def run_inner(options: Options, heartbeat: Callable[[], None]) -> List[int]:\n force_seed=force_seed,\n force_rng_seed=force_rng_seed,\n keep_prob=options.keep_prob,\n+ need_profiler=options.show_timings,\n need_all_sources=options.print_diffs,\n show_errors=options.show_errors,\n+ best_only=options.best_only,\n+ better_only=options.better_only,\n )\n except CandidateConstructionFailure as e:\n print(e.message, file=sys.stderr)\n@@ -296,72 +329,180 @@ def run_inner(options: Options, heartbeat: Callable[[], None]) -> List[int]:\n name_counts[permuter.fn_name] = name_counts.get(permuter.fn_name, 0) + 1\n print()\n \n+ if not context.permuters:\n+ print(\"No permuters!\")\n+ return []\n+\n for permuter in context.permuters:\n if name_counts[permuter.fn_name] > 1:\n permuter.unique_name += f\" ({permuter.dir})\"\n print(f\"[{permuter.unique_name}] base score = {permuter.best_score}\")\n \n found_zero = False\n- perm_seed_iter = iter(cycle_seeds(context.permuters))\n- if options.threads == 1:\n- for permuter_index, seed in perm_seed_iter:\n+ if options.threads == 1 and not options.use_network:\n+ # Simple single-threaded mode. This is not technically needed, but\n+ # makes the permuter easier to debug.\n+ for permuter_index, seed in cycle_seeds(context.permuters):\n heartbeat()\n permuter = context.permuters[permuter_index]\n result = permuter.try_eval_candidate(seed)\n- if post_score(context, permuter, result):\n+ if post_score(context, permuter, result, None):\n found_zero = True\n if options.stop_on_zero:\n break\n else:\n- # Create queues\n- task_queue: \"multiprocessing.Queue[Optional[Tuple[int, int]]]\" = (\n- multiprocessing.Queue()\n- )\n- results_queue: \"multiprocessing.Queue[Tuple[int, EvalResult]]\" = (\n- multiprocessing.Queue()\n- )\n- task_queue.cancel_join_thread()\n- results_queue.cancel_join_thread()\n-\n- def wait_for_result() -> bool:\n- heartbeat()\n- permuter_index, result = results_queue.get()\n- permuter = context.permuters[permuter_index]\n- return post_score(context, permuter, result)\n-\n- # Begin workers\n+ seed_iterators: List[Optional[Iterator[int]]] = [\n+ itertools.repeat(perm_ind)\n+ for perm_ind, permuter in enumerate(context.permuters)\n+ ]\n+ seed_iterators_remaining = len(seed_iterators)\n+ next_iterator_index = 0\n+\n+ # Create queues.\n+ worker_task_queue: \"Queue[Task]\" = Queue()\n+ feedback_queue: \"Queue[Feedback]\" = Queue()\n+\n+ # Connect to network and create client threads and queues.\n+ net_conns: \"List[Tuple[threading.Thread, Queue[Task]]]\" = []\n+ if options.use_network:\n+ print(\"Connecting to permuter@home...\")\n+ if options.network_debug:\n+ enable_debug_mode()\n+ first_stats: Optional[Tuple[int, int, float]] = None\n+ for perm_index in range(len(context.permuters)):\n+ try:\n+ port = connect()\n+ except (EOFError, ServerError) as e:\n+ print(\"Error:\", e)\n+ sys.exit(1)\n+ thread, queue, stats = start_client(\n+ port,\n+ context.permuters[perm_index],\n+ perm_index,\n+ feedback_queue,\n+ options.network_priority,\n+ )\n+ net_conns.append((thread, queue))\n+ if first_stats is None:\n+ first_stats = stats\n+ assert first_stats is not None, \"has at least one permuter\"\n+ clients_str = plural(first_stats[0], \"other client\")\n+ servers_str = plural(first_stats[1], \"server\")\n+ cores_str = plural(int(first_stats[2]), \"core\")\n+ print(f\"Connected! {servers_str} online ({cores_str}, {clients_str})\")\n+\n+ # Start local worker threads\n processes: List[multiprocessing.Process] = []\n for i in range(options.threads):\n p = multiprocessing.Process(\n target=multiprocess_worker,\n- args=(context.permuters, task_queue, results_queue),\n+ args=(context.permuters, worker_task_queue, feedback_queue),\n )\n p.start()\n processes.append(p)\n \n- # Feed the task queue with work, but not too much work at a time\n- active_tasks = 0\n- for perm_seed in perm_seed_iter:\n- if active_tasks >= options.threads + 2:\n- active_tasks -= 1\n- if wait_for_result():\n+ active_workers = len(processes)\n+\n+ if not active_workers and not net_conns:\n+ print(\"No workers available! Exiting.\")\n+ sys.exit(1)\n+\n+ def process_finish(finish: Finished, source: int) -> None:\n+ nonlocal active_workers\n+\n+ if finish.reason:\n+ permuter: Optional[Permuter] = None\n+ if source != -1 and len(context.permuters) > 1:\n+ permuter = context.permuters[source]\n+ context.printer.print(finish.reason, permuter, None, keep_progress=True)\n+\n+ if source == -1:\n+ active_workers -= 1\n+\n+ def process_result(work: WorkDone, who: Optional[str]) -> bool:\n+ permuter = context.permuters[work.perm_index]\n+ return post_score(context, permuter, work.result, who)\n+\n+ def get_task(perm_index: int) -> Optional[Tuple[int, int]]:\n+ nonlocal next_iterator_index, seed_iterators_remaining\n+ if perm_index == -1:\n+ while seed_iterators_remaining > 0:\n+ task = get_task(next_iterator_index)\n+ next_iterator_index += 1\n+ next_iterator_index %= len(seed_iterators)\n+ if task is not None:\n+ return task\n+ else:\n+ it = seed_iterators[perm_index]\n+ if it is not None:\n+ seed = next(it, None)\n+ if seed is None:\n+ seed_iterators[perm_index] = None\n+ seed_iterators_remaining -= 1\n+ else:\n+ return (perm_index, seed)\n+ return None\n+\n+ # Feed the task queue with work and read from results queue.\n+ # We generally match these up one-by-one to avoid overfilling queues,\n+ # but workers can ask us to add more tasks into the system if they run\n+ # out of work. (This will happen e.g. at the very beginning, when the\n+ # queues are empty.)\n+ while seed_iterators_remaining > 0:\n+ heartbeat()\n+ feedback, source, who = feedback_queue.get()\n+ if isinstance(feedback, Finished):\n+ process_finish(feedback, source)\n+ elif isinstance(feedback, Message):\n+ context.printer.print(feedback.text, None, who, keep_progress=True)\n+ elif isinstance(feedback, WorkDone):\n+ if process_result(feedback, who):\n # Found score 0!\n found_zero = True\n if options.stop_on_zero:\n break\n- task_queue.put(perm_seed)\n- active_tasks += 1\n-\n- # Await final results\n- for i in range(active_tasks):\n- wait_for_result()\n-\n- # Stop workers\n- for i in range(options.threads):\n- task_queue.put(None)\n+ elif isinstance(feedback, NeedMoreWork):\n+ task = get_task(source)\n+ if task is not None:\n+ if source == -1:\n+ worker_task_queue.put(task)\n+ else:\n+ net_conns[source][1].put(task)\n+ else:\n+ static_assert_unreachable(feedback)\n+\n+ # Signal workers to stop.\n+ for i in range(active_workers):\n+ worker_task_queue.put(Finished())\n+\n+ for conn in net_conns:\n+ conn[1].put(Finished())\n+\n+ # Await final results.\n+ while active_workers > 0 or net_conns:\n+ heartbeat()\n+ feedback, source, who = feedback_queue.get()\n+ if isinstance(feedback, Finished):\n+ process_finish(feedback, source)\n+ elif isinstance(feedback, Message):\n+ context.printer.print(feedback.text, None, who, keep_progress=True)\n+ elif isinstance(feedback, WorkDone):\n+ if not (options.stop_on_zero and found_zero):\n+ if process_result(feedback, who):\n+ found_zero = True\n+ elif isinstance(feedback, NeedMoreWork):\n+ pass\n+ else:\n+ static_assert_unreachable(feedback)\n+\n+ # Wait for workers to finish.\n for p in processes:\n p.join()\n \n+ # Wait for network connections to close (currently does not happen).\n+ for conn in net_conns:\n+ conn[0].join()\n+\n if found_zero:\n print(\"\\nFound zero score! Exiting.\")\n return [permuter.best_score for permuter in context.permuters]\n@@ -372,7 +513,7 @@ def main() -> None:\n sys.setrecursionlimit(10000)\n \n # Ideally we would do:\n- # multiprocessing.set_start_method('spawn')\n+ # multiprocessing.set_start_method(\"spawn\")\n # here, to make multiprocessing behave the same across operating systems.\n # However, that means that arguments to Process are passed across using\n # pickling, which mysteriously breaks with pycparser...\n@@ -443,19 +584,49 @@ def main() -> None:\n metavar=\"PROB\",\n type=restricted_float(0.0, 1.0),\n default=DEFAULT_RAND_KEEP_PROB,\n- help=\"Continue randomizing the previous output with the given probability \"\n- f\"(float in 0..1, default %(default)s).\",\n+ help=\"\"\"Continue randomizing the previous output with the given probability\n+ (float in 0..1, default %(default)s).\"\"\",\n )\n parser.add_argument(\"--seed\", dest=\"force_seed\", type=str, help=argparse.SUPPRESS)\n parser.add_argument(\n \"-j\",\n dest=\"threads\",\n type=int,\n- default=1,\n- help=\"Number of threads (default: %(default)s).\",\n+ default=0,\n+ help=\"Number of own threads to use (default: 1 without -J, 0 with -J).\",\n )\n+ parser.add_argument(\n+ \"-J\",\n+ dest=\"use_network\",\n+ action=\"store_true\",\n+ help=\"Harness extra compute power through cyberspace (permuter@home).\",\n+ )\n+ parser.add_argument(\n+ \"--pah-debug\",\n+ dest=\"network_debug\",\n+ action=\"store_true\",\n+ help=\"Enable debug prints for permuter@home.\",\n+ )\n+ parser.add_argument(\n+ \"--priority\",\n+ dest=\"network_priority\",\n+ metavar=\"PRIORITY\",\n+ type=restricted_float(MIN_PRIO, MAX_PRIO),\n+ default=1.0,\n+ help=f\"\"\"Proportion of server resources to use when multiple people\n+ are using -J at the same time.\n+ Defaults to 1.0, meaning resources are split equally, but can be\n+ set to any value within [{MIN_PRIO}, {MAX_PRIO}].\n+ Each server runs with a priority threshold, which defaults to 0.1,\n+ below which they will not run permuter jobs at all.\"\"\",\n+ )\n+\n args = parser.parse_args()\n \n+ threads = args.threads\n+ if not threads and not args.use_network:\n+ threads = 1\n+\n options = Options(\n directories=args.directories,\n show_errors=args.show_errors,\n@@ -468,7 +639,10 @@ def main() -> None:\n stop_on_zero=args.stop_on_zero,\n keep_prob=args.keep_prob,\n force_seed=args.force_seed,\n- threads=args.threads,\n+ threads=threads,\n+ use_network=args.use_network,\n+ network_debug=args.network_debug,\n+ network_priority=args.network_priority,\n )\n \n run(options)\ndiff --git a/src/net/__init__.py b/src/net/__init__.py\nnew file mode 100644\ndiff --git a/src/net/client.py b/src/net/client.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/client.py\n@@ -0,0 +1,279 @@\n+from dataclasses import dataclass\n+import json\n+from multiprocessing import Queue\n+import re\n+import socket\n+import struct\n+import threading\n+from typing import List, Optional, Tuple, TypeVar\n+import zlib\n+\n+from ..candidate import CandidateResult\n+from ..helpers import exception_to_string\n+from ..permuter import (\n+ EvalError,\n+ EvalResult,\n+ Feedback,\n+ FeedbackItem,\n+ Finished,\n+ Message,\n+ NeedMoreWork,\n+ Permuter,\n+ Task,\n+ WorkDone,\n+)\n+from ..profiler import Profiler\n+from .core import (\n+ PermuterData,\n+ Port,\n+ SocketPort,\n+ json_array,\n+ json_prop,\n+ permuter_data_to_json,\n+)\n+\n+\n+def _profiler_from_json(obj: dict) -> Profiler:\n+ ret = Profiler()\n+ for key in obj:\n+ assert isinstance(key, str), \"json properties are strings\"\n+ stat = Profiler.StatType[key]\n+ time = json_prop(obj, key, float)\n+ ret.add_stat(stat, time)\n+ return ret\n+\n+\n+def _result_from_json(obj: dict, source: Optional[str]) -> EvalResult:\n+ if \"error\" in obj:\n+ return EvalError(exc_str=json_prop(obj, \"error\", str), seed=None)\n+\n+ profiler: Optional[Profiler] = None\n+ if \"profiler\" in obj:\n+ profiler = _profiler_from_json(json_prop(obj, \"profiler\", dict))\n+ return CandidateResult(\n+ score=json_prop(obj, \"score\", int),\n+ hash=json_prop(obj, \"hash\", str) if \"hash\" in obj else None,\n+ source=source,\n+ profiler=profiler,\n+ )\n+\n+\n+def _make_script_portable(source: str) -> str:\n+ \"\"\"Parse a shell script and get rid of the machine-specific parts that\n+ import.py introduces. The resulting script must be run in an environment\n+ that has the right binaries in its $PATH, and with a current working\n+ directory similar to where import.py found its target's make root.\"\"\"\n+ lines = []\n+ for line in source.split(\"\\n\"):\n+ if re.match(\"cd '?/\", line):\n+ # Skip cd's to absolute directory paths. Note that shlex quotes\n+ # its argument with ' if it contains spaces/single quotes.\n+ continue\n+ if re.match(\"'?/\", line):\n+ quote = \"'\" if line[0] == \"'\" else \"\"\n+ ind = line.find(quote + \" \")\n+ if ind == -1:\n+ ind = len(line)\n+ else:\n+ ind += len(quote)\n+ lastind = line.rfind(\"/\", 0, ind)\n+ assert lastind != -1\n+ # Emit a call to \"which\" as the first part, to ensure the called\n+ # binary still sees an absolute path. qemu-irix requires this,\n+ # for some reason.\n+ line = \"$(which \" + quote + line[lastind + 1 : ind] + \")\" + line[ind:]\n+ lines.append(line)\n+ return \"\\n\".join(lines)\n+\n+\n+def make_portable_permuter(permuter: Permuter) -> PermuterData:\n+ with open(permuter.scorer.target_o, \"rb\") as f:\n+ target_o_bin = f.read()\n+\n+ with open(permuter.compiler.compile_cmd, \"r\") as f2:\n+ compile_script = _make_script_portable(f2.read())\n+\n+ return PermuterData(\n+ base_score=permuter.base_score,\n+ base_hash=permuter.base_hash,\n+ fn_name=permuter.fn_name,\n+ filename=permuter.source_file,\n+ keep_prob=permuter.keep_prob,\n+ need_profiler=permuter.need_profiler,\n+ stack_differences=permuter.scorer.stack_differences,\n+ compile_script=compile_script,\n+ source=permuter.source,\n+ target_o_bin=target_o_bin,\n+ )\n+\n+\n+class Connection:\n+ _port: SocketPort\n+ _permuter_data: PermuterData\n+ _perm_index: int\n+ _task_queue: \"Queue[Task]\"\n+ _feedback_queue: \"Queue[Feedback]\"\n+\n+ def __init__(\n+ self,\n+ port: SocketPort,\n+ permuter_data: PermuterData,\n+ perm_index: int,\n+ task_queue: \"Queue[Task]\",\n+ feedback_queue: \"Queue[Feedback]\",\n+ ) -> None:\n+ self._port = port\n+ self._permuter_data = permuter_data\n+ self._perm_index = perm_index\n+ self._task_queue = task_queue\n+ self._feedback_queue = feedback_queue\n+\n+ def _send_permuter(self) -> None:\n+ data = self._permuter_data\n+ self._port.send_json(permuter_data_to_json(data))\n+ self._port.send(zlib.compress(data.source.encode(\"utf-8\")))\n+ self._port.send(zlib.compress(data.target_o_bin))\n+\n+ def _feedback(self, feedback: FeedbackItem, server_nick: Optional[str]) -> None:\n+ self._feedback_queue.put((feedback, self._perm_index, server_nick))\n+\n+ def _receive_one(self) -> bool:\n+ \"\"\"Receive a result/progress message and send it on. Returns true if\n+ more work should be requested.\"\"\"\n+ msg = self._port.receive_json()\n+ msg_type = json_prop(msg, \"type\", str)\n+ if msg_type == \"need_work\":\n+ return True\n+\n+ server_nick = json_prop(msg, \"server\", str)\n+ if msg_type == \"init_done\":\n+ base_hash = json_prop(msg, \"hash\", str)\n+ my_base_hash = self._permuter_data.base_hash\n+ text = \"connected\"\n+ if base_hash != my_base_hash:\n+ text += \" (note: mismatching hash)\"\n+ self._feedback(Message(text), server_nick)\n+ return True\n+\n+ if msg_type == \"init_failed\":\n+ text = \"failed to initialize: \" + json_prop(msg, \"reason\", str)\n+ self._feedback(Message(text), server_nick)\n+ return False\n+\n+ if msg_type == \"disconnect\":\n+ self._feedback(Message(\"disconnected\"), server_nick)\n+ return False\n+\n+ if msg_type == \"result\":\n+ source: Optional[str] = None\n+ if msg.get(\"has_source\") == True:\n+ # Source is sent separately, compressed, since it can be\n+ # large (hundreds of kilobytes is not uncommon).\n+ compressed_source = self._port.receive()\n+ try:\n+ source = zlib.decompress(compressed_source).decode(\"utf-8\")\n+ except Exception as e:\n+ text = \"failed to decompress: \" + exception_to_string(e)\n+ self._feedback(Message(text), server_nick)\n+ return True\n+ try:\n+ result = _result_from_json(msg, source)\n+ self._feedback(WorkDone(self._perm_index, result), server_nick)\n+ except Exception as e:\n+ text = \"failed to parse result message: \" + exception_to_string(e)\n+ self._feedback(Message(text), server_nick)\n+ return True\n+\n+ raise ValueError(f\"Invalid message type {msg_type}\")\n+\n+ def run(self) -> None:\n+ finish_reason: Optional[str] = None\n+ try:\n+ self._send_permuter()\n+ self._port.receive_json()\n+\n+ finished = False\n+\n+ # Main loop: send messages from the queue on to the server, and\n+ # vice versa. Currently we are being lazy and alternate between\n+ # sending and receiving; this is nicely simple and keeps us on a\n+ # single thread, however it could cause deadlocks if the server\n+ # receiver stops reading because we aren't reading fast enough.\n+ while True:\n+ if not self._receive_one():\n+ continue\n+ self._feedback(NeedMoreWork(), None)\n+\n+ # Read a task and send it on, unless there are no more tasks.\n+ if not finished:\n+ task = self._task_queue.get()\n+ if isinstance(task, Finished):\n+ # We don't have a way of indicating to the server that\n+ # all is done: the server currently doesn't track\n+ # outstanding work so it doesn't know when to close\n+ # the connection. (Even with this fixed we'll have the\n+ # problem that servers may disconnect, losing work, so\n+ # the task never truly finishes. But it might work well\n+ # enough in practice.)\n+ finished = True\n+ else:\n+ work = {\n+ \"type\": \"work\",\n+ \"work\": {\n+ \"seed\": task[1],\n+ },\n+ }\n+ self._port.send_json(work)\n+\n+ except EOFError:\n+ finish_reason = \"disconnected from permuter@home\"\n+\n+ except Exception as e:\n+ errmsg = exception_to_string(e)\n+ finish_reason = f\"permuter@home error: {errmsg}\"\n+\n+ finally:\n+ self._feedback(Finished(reason=finish_reason), None)\n+ self._port.shutdown()\n+ self._port.close()\n+\n+\n+def start_client(\n+ port: SocketPort,\n+ permuter: Permuter,\n+ perm_index: int,\n+ feedback_queue: \"Queue[Feedback]\",\n+ priority: float,\n+) -> \"Tuple[threading.Thread, Queue[Task], Tuple[int, int, float]]\":\n+ port.send_json(\n+ {\n+ \"method\": \"connect_client\",\n+ \"priority\": priority,\n+ }\n+ )\n+ obj = port.receive_json()\n+ if \"error\" in obj:\n+ err = json_prop(obj, \"error\", str)\n+ # TODO use another exception type\n+ raise Exception(f\"Failed to connect: {err}\")\n+ num_servers = json_prop(obj, \"servers\", int)\n+ num_clients = json_prop(obj, \"clients\", int)\n+ num_cores = json_prop(obj, \"cores\", float)\n+ permuter_data = make_portable_permuter(permuter)\n+ task_queue: \"Queue[Task]\" = Queue()\n+\n+ conn = Connection(\n+ port,\n+ permuter_data,\n+ perm_index,\n+ task_queue,\n+ feedback_queue,\n+ )\n+\n+ thread = threading.Thread(target=conn.run)\n+ thread.daemon = True\n+ thread.start()\n+\n+ stats = (num_clients, num_servers, num_cores)\n+\n+ return thread, task_queue, stats\ndiff --git a/src/net/cmd/__init__.py b/src/net/cmd/__init__.py\nnew file mode 100644\ndiff --git a/src/net/cmd/base.py b/src/net/cmd/base.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/base.py\n@@ -0,0 +1,17 @@\n+import abc\n+from argparse import ArgumentParser, Namespace\n+\n+\n+class Command(abc.ABC):\n+ command: str\n+ help: str\n+\n+ @staticmethod\n+ @abc.abstractmethod\n+ def add_arguments(parser: ArgumentParser) -> None:\n+ ...\n+\n+ @staticmethod\n+ @abc.abstractmethod\n+ def run(args: Namespace) -> None:\n+ ...\ndiff --git a/src/net/cmd/main.py b/src/net/cmd/main.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/main.py\n@@ -0,0 +1,61 @@\n+from argparse import ArgumentParser, RawDescriptionHelpFormatter\n+import sys\n+\n+from ..core import ServerError, enable_debug_mode\n+from .run_server import RunServerCommand\n+from .setup import SetupCommand\n+from .ping import PingCommand\n+from .vouch import VouchCommand\n+\n+\n+def main() -> None:\n+ parser = ArgumentParser(\n+ description=\"permuter@home - run the permuter across the Internet!\\n\\n\"\n+ \"To use p@h as a client, just pass -J when running the permuter. \"\n+ \"This script is\\nonly necessary for configuration or when running a server.\",\n+ formatter_class=RawDescriptionHelpFormatter,\n+ )\n+\n+ commands = [\n+ PingCommand,\n+ RunServerCommand,\n+ SetupCommand,\n+ VouchCommand,\n+ ]\n+\n+ parser.add_argument(\n+ \"--debug\",\n+ dest=\"debug\",\n+ action=\"store_true\",\n+ help=\"Enable debug logging.\",\n+ )\n+\n+ subparsers = parser.add_subparsers(metavar=\"\")\n+ for command in commands:\n+ subparser = subparsers.add_parser(\n+ command.command,\n+ help=command.help,\n+ description=command.help,\n+ )\n+ command.add_arguments(subparser)\n+ subparser.set_defaults(subcommand_handler=command.run)\n+\n+ args = parser.parse_args()\n+ if args.debug:\n+ enable_debug_mode()\n+\n+ if \"subcommand_handler\" in args:\n+ try:\n+ args.subcommand_handler(args)\n+ except EOFError as e:\n+ print(\"Network error:\", e)\n+ sys.exit(1)\n+ except ServerError as e:\n+ print(\"Error:\", e.message)\n+ sys.exit(1)\n+ else:\n+ parser.print_help()\n+\n+\n+if __name__ == \"__main__\":\n+ main()\ndiff --git a/src/net/cmd/ping.py b/src/net/cmd/ping.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/ping.py\n@@ -0,0 +1,27 @@\n+from argparse import ArgumentParser, Namespace\n+import time\n+\n+from ..core import connect\n+from .base import Command\n+\n+\n+class PingCommand(Command):\n+ command = \"ping\"\n+ help = \"Check server connectivity.\"\n+\n+ @staticmethod\n+ def add_arguments(parser: ArgumentParser) -> None:\n+ pass\n+\n+ @staticmethod\n+ def run(args: Namespace) -> None:\n+ run_ping()\n+\n+\n+def run_ping() -> None:\n+ port = connect()\n+ t0 = time.time()\n+ port.send_json({\"method\": \"ping\"})\n+ port.receive_json()\n+ rtt = (time.time() - t0) * 1000\n+ print(f\"Connected successfully! Round-trip time: {rtt:.1f} ms\")\ndiff --git a/src/net/cmd/run_server.py b/src/net/cmd/run_server.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/run_server.py\n@@ -0,0 +1,382 @@\n+from argparse import ArgumentParser, Namespace\n+from dataclasses import dataclass\n+from functools import partial\n+import os\n+import queue\n+import random\n+import sys\n+import time\n+import threading\n+import traceback\n+from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING\n+\n+if TYPE_CHECKING:\n+ import pystray\n+\n+from ...helpers import static_assert_unreachable\n+from ..core import CancelToken, ServerError\n+from ..server import (\n+ Client,\n+ IoActivity,\n+ IoConnect,\n+ IoDisconnect,\n+ IoGlobalMessage,\n+ IoImmediateDisconnect,\n+ IoReconnect,\n+ IoServerFailed,\n+ IoShutdown,\n+ IoUserRemovePermuter,\n+ IoWillSleep,\n+ IoWorkDone,\n+ PermuterHandle,\n+ Server,\n+ ServerOptions,\n+)\n+from .base import Command\n+\n+\n+SYSTRAY_UPDATE_INTERVAL = 20.0\n+\n+\n+class RunServerCommand(Command):\n+ command = \"run-server\"\n+ help = \"\"\"Run a permuter server, allowing anyone with access to the central\n+ server to run sandboxed permuter jobs on your machine. Requires docker.\"\"\"\n+\n+ @staticmethod\n+ def add_arguments(parser: ArgumentParser) -> None:\n+ parser.add_argument(\n+ \"--cores\",\n+ dest=\"num_cores\",\n+ metavar=\"CORES\",\n+ type=float,\n+ required=True,\n+ help=\"Number of cores to use (float).\",\n+ )\n+ parser.add_argument(\n+ \"--memory\",\n+ dest=\"max_memory_gb\",\n+ metavar=\"MEMORY_GB\",\n+ type=float,\n+ required=True,\n+ help=\"\"\"Restrict the sandboxed process to the given amount of memory in\n+ gigabytes (float). If this limit is hit, the permuter will crash\n+ horribly, but at least your system won't lock up.\"\"\",\n+ )\n+ parser.add_argument(\n+ \"--systray\",\n+ dest=\"systray\",\n+ action=\"store_true\",\n+ help=\"\"\"Make the server controllable through the system tray.\n+ Warning: buggy!\"\"\",\n+ )\n+ parser.add_argument(\n+ \"--min-priority\",\n+ dest=\"min_priority\",\n+ metavar=\"PRIORITY\",\n+ type=float,\n+ default=0.1,\n+ help=\"\"\"Only accept jobs from clients who pass --priority with a number\n+ higher or equal to this value. (default: %(default)s)\"\"\",\n+ )\n+\n+ @staticmethod\n+ def run(args: Namespace) -> None:\n+ options = ServerOptions(\n+ num_cores=args.num_cores,\n+ max_memory_gb=args.max_memory_gb,\n+ min_priority=args.min_priority,\n+ )\n+\n+ server_main(options, args.systray)\n+\n+\n+class SystrayState:\n+ def connect(self, handle: PermuterHandle, nickname: str, fn_name: str) -> None:\n+ pass\n+\n+ def disconnect(self, handle: PermuterHandle) -> None:\n+ pass\n+\n+ def work_done(self, handle: PermuterHandle, is_improvement: bool) -> None:\n+ pass\n+\n+ def will_sleep(self) -> None:\n+ pass\n+\n+ def server_failed(self) -> None:\n+ pass\n+\n+\n+@dataclass\n+class Permuter:\n+ nickname: str\n+ fn_name: str\n+ iterations: int = 0\n+ improvements: int = 0\n+ last_systray_update: float = 0.0\n+\n+\n+class RealSystrayState(SystrayState):\n+ _permuters: Dict[PermuterHandle, Permuter]\n+\n+ def __init__(\n+ self,\n+ io_queue: \"queue.Queue[IoActivity]\",\n+ update_menu: \"Callable[[List[pystray.MenuItem], bool], None]\",\n+ ) -> None:\n+ self._io_queue = io_queue\n+ self._update_menu = update_menu\n+ self._permuters = {}\n+\n+ def _remove_permuter(self, handle: PermuterHandle, *_: Any) -> None:\n+ self._io_queue.put((None, (handle, IoUserRemovePermuter())))\n+\n+ def _quit(self) -> None:\n+ self._io_queue.put((None, IoShutdown()))\n+\n+ def _update(self, flush: bool = True) -> None:\n+ import pystray\n+\n+ title = \"Currently permuting:\" if self._permuters else \"\"\n+ items: List[pystray.MenuItem] = [\n+ pystray.MenuItem(title, None, enabled=False),\n+ ]\n+\n+ for handle, perm in self._permuters.items():\n+ items.append(\n+ pystray.MenuItem(\n+ f\"{perm.fn_name} ({perm.nickname})\",\n+ pystray.Menu(\n+ pystray.MenuItem(\n+ f\"Iterations: {perm.iterations}\", None, enabled=False\n+ ),\n+ pystray.MenuItem(\n+ f\"Improvements found: {perm.improvements}\",\n+ None,\n+ enabled=False,\n+ ),\n+ pystray.MenuItem(\n+ \"Stop\", partial(self._remove_permuter, handle)\n+ ),\n+ ),\n+ ),\n+ )\n+\n+ items.append(pystray.MenuItem(\"Quit\", self._quit))\n+\n+ self._update_menu(items, flush)\n+\n+ def initial_update(self) -> None:\n+ self._update()\n+\n+ def connect(self, handle: PermuterHandle, nickname: str, fn_name: str) -> None:\n+ self._permuters[handle] = Permuter(nickname, fn_name)\n+ self._update()\n+\n+ def disconnect(self, handle: PermuterHandle) -> None:\n+ del self._permuters[handle]\n+ self._update()\n+\n+ def work_done(self, handle: PermuterHandle, is_improvement: bool) -> None:\n+ perm = self._permuters[handle]\n+ perm.iterations += 1\n+ if is_improvement:\n+ perm.improvements += 1\n+ flush = time.time() > perm.last_systray_update + SYSTRAY_UPDATE_INTERVAL\n+ if flush:\n+ perm.last_systray_update = time.time()\n+ self._update(flush)\n+\n+ def will_sleep(self) -> None:\n+ self._update()\n+\n+ def server_failed(self) -> None:\n+ self._permuters = {}\n+ self._update()\n+\n+\n+def run_with_systray(\n+ io_queue: \"queue.Queue[IoActivity]\",\n+ loop: Callable[[SystrayState], None],\n+) -> None:\n+ try:\n+ from PIL import Image\n+ import pystray\n+ except Exception:\n+ print(\n+ \"Systray requires the pystray and Pillow packages to be installed.\\n\"\n+ \"Run `python3 -m pip install --upgrade pystray Pillow`.\"\n+ )\n+ sys.exit(1)\n+\n+ menu_items: List[pystray.MenuItem] = []\n+\n+ icon = pystray.Icon(\n+ name=\"permuter@home\",\n+ title=\"permuter@home\",\n+ icon=Image.open(os.path.join(os.path.dirname(__file__), \"icon.png\")),\n+ menu=pystray.Menu(lambda: menu_items),\n+ )\n+\n+ def update_menu(items: List[pystray.MenuItem], flush: bool) -> None:\n+ nonlocal menu_items\n+ menu_items = items\n+ if flush:\n+ icon.update_menu()\n+\n+ systray = RealSystrayState(io_queue, update_menu)\n+ systray.initial_update()\n+\n+ def inner(icon: pystray.Icon) -> None:\n+ icon.visible = True\n+ loop(systray)\n+ icon.stop()\n+\n+ icon.run(inner)\n+\n+\n+class Reconnector:\n+ _RESET_BACKOFF_AFTER_UPTIME: float = 60.0\n+ _RANDOM_ADDEND_MAX: float = 60.0\n+ _BACKOFF_MULTIPLIER: float = 2.0\n+ _INITIAL_DELAY: float = 5.0\n+\n+ _io_queue: \"queue.Queue[IoActivity]\"\n+ _reconnect_token: CancelToken\n+ _reconnect_delay: float\n+ _reconnect_timer: Optional[threading.Timer]\n+ _start_time: float\n+ _stop_time: float\n+\n+ def __init__(self, io_queue: \"queue.Queue[IoActivity]\") -> None:\n+ self._io_queue = io_queue\n+ self._reconnect_token = CancelToken()\n+ self._reconnect_delay = self._INITIAL_DELAY\n+ self._reconnect_timer = None\n+ self._start_time = self._stop_time = time.time()\n+\n+ def mark_start(self) -> None:\n+ self._start_time = time.time()\n+\n+ def mark_stop(self) -> None:\n+ self._stop_time = time.time()\n+\n+ def stop(self) -> None:\n+ self._reconnect_token.cancelled = True\n+ if self._reconnect_timer is not None:\n+ self._reconnect_timer.cancel()\n+ self._reconnect_timer.join()\n+ self._reconnect_timer = None\n+\n+ def reconnect_eventually(self) -> int:\n+ if self._stop_time - self._start_time > self._RESET_BACKOFF_AFTER_UPTIME:\n+ delay = self._reconnect_delay = self._INITIAL_DELAY\n+ else:\n+ delay = self._reconnect_delay\n+ self._reconnect_delay = (\n+ self._reconnect_delay * self._BACKOFF_MULTIPLIER\n+ + random.uniform(1.0, self._RANDOM_ADDEND_MAX)\n+ )\n+ token = CancelToken()\n+ self._reconnect_token = token\n+ self._reconnect_timer = threading.Timer(\n+ delay, lambda: self._io_queue.put((token, IoReconnect()))\n+ )\n+ self._reconnect_timer.daemon = True\n+ self._reconnect_timer.start()\n+ return int(delay)\n+\n+\n+def main_loop(\n+ io_queue: \"queue.Queue[IoActivity]\",\n+ server: Server,\n+ systray: SystrayState,\n+) -> None:\n+ reconnector = Reconnector(io_queue)\n+ handle_clients: Dict[PermuterHandle, Client] = {}\n+ while True:\n+ token, activity = io_queue.get()\n+ if token and token.cancelled:\n+ continue\n+\n+ if not isinstance(activity, tuple):\n+ if isinstance(activity, IoWillSleep):\n+ systray.will_sleep()\n+\n+ elif isinstance(activity, IoShutdown):\n+ break\n+\n+ elif isinstance(activity, IoReconnect):\n+ print(\"reconnecting...\")\n+ try:\n+ reconnector.mark_start()\n+ server.start()\n+ except EOFError:\n+ delay = reconnector.reconnect_eventually()\n+ print(f\"failed again, reconnecting in {delay} seconds...\")\n+ except ServerError as e:\n+ print(\"failed!\", e.message)\n+ except Exception:\n+ print(\"failed!\")\n+ traceback.print_exc()\n+\n+ elif isinstance(activity, IoServerFailed):\n+ print(\"disconnected from permuter@home\")\n+ server.stop()\n+ reconnector.mark_stop()\n+ systray.server_failed()\n+\n+ if activity.graceful:\n+ delay = reconnector.reconnect_eventually()\n+ print(f\"will reconnect in {delay} seconds...\")\n+\n+ else:\n+ static_assert_unreachable(activity)\n+\n+ else:\n+ handle, msg = activity\n+\n+ if isinstance(msg, IoConnect):\n+ client = msg.client\n+ handle_clients[handle] = client\n+ systray.connect(handle, client.nickname, msg.fn_name)\n+ print(f\"{client.nickname} connected ({msg.fn_name})\")\n+\n+ elif isinstance(msg, IoDisconnect):\n+ systray.disconnect(handle)\n+ nickname = handle_clients[handle].nickname\n+ del handle_clients[handle]\n+ print(f\"[{nickname}] {msg.reason}\")\n+\n+ elif isinstance(msg, IoImmediateDisconnect):\n+ print(f\"[{msg.client.nickname}] {msg.reason}\")\n+\n+ elif isinstance(msg, IoWorkDone):\n+ # TODO: statistics\n+ systray.work_done(handle, msg.is_improvement)\n+\n+ elif isinstance(msg, IoUserRemovePermuter):\n+ server.remove_permuter(handle)\n+\n+ else:\n+ static_assert_unreachable(msg)\n+\n+\n+def server_main(options: ServerOptions, use_systray: bool) -> None:\n+ io_queue: \"queue.Queue[IoActivity]\" = queue.Queue()\n+\n+ server = Server(options, io_queue)\n+ server.start()\n+\n+ try:\n+\n+ def cmdline_ui(systray: SystrayState) -> None:\n+ main_loop(io_queue, server, systray)\n+\n+ if use_systray:\n+ run_with_systray(io_queue, cmdline_ui)\n+ else:\n+ cmdline_ui(SystrayState())\n+ finally:\n+ server.stop()\ndiff --git a/src/net/cmd/setup.py b/src/net/cmd/setup.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/setup.py\n@@ -0,0 +1,87 @@\n+from argparse import ArgumentParser, Namespace\n+import base64\n+import os\n+import random\n+import string\n+import sys\n+import time\n+from typing import Optional\n+\n+from nacl.public import SealedBox\n+from nacl.signing import SigningKey, VerifyKey\n+\n+from .base import Command\n+from ..core import connect, Config, read_config, sign_with_magic, write_config\n+from .util import ask\n+\n+\n+class SetupCommand(Command):\n+ command = \"setup\"\n+ help = \"\"\"Set up permuter@home. This will require someone else to grant you\n+ access to the central server.\"\"\"\n+\n+ @staticmethod\n+ def add_arguments(parser: ArgumentParser) -> None:\n+ pass\n+\n+ @staticmethod\n+ def run(args: Namespace) -> None:\n+ _run_initial_setup()\n+\n+\n+def _random_name() -> str:\n+ return \"\".join(random.choice(string.ascii_lowercase) for _ in range(5))\n+\n+\n+def _run_initial_setup() -> None:\n+ config = read_config()\n+ signing_key: Optional[SigningKey] = config.signing_key\n+ if not signing_key or not ask(\"Keep previous secret key\", default=True):\n+ signing_key = SigningKey.generate()\n+ config.signing_key = signing_key\n+ write_config(config)\n+ verify_key = signing_key.verify_key\n+\n+ nickname: Optional[str] = config.initial_setup_nickname\n+ if not nickname or not ask(f\"Keep previous nickname [{nickname}]\", default=True):\n+ default_nickname = os.environ.get(\"USER\") or _random_name()\n+ nickname = (\n+ input(f\"Nickname [default: {default_nickname}]: \") or default_nickname\n+ )\n+ config.initial_setup_nickname = nickname\n+ write_config(config)\n+\n+ signed_nickname = sign_with_magic(b\"NAME\", signing_key, nickname.encode(\"utf-8\"))\n+\n+ vouch_data = verify_key.encode() + signed_nickname\n+ vouch_text = base64.b64encode(vouch_data).decode(\"utf-8\")\n+ print(\"Ask someone to run the following command:\")\n+ print(f\"./pah.py vouch {vouch_text}\")\n+ print()\n+ print(\"They should give you a token back in return. Paste that here:\")\n+ inp = input().strip()\n+\n+ try:\n+ token = base64.b64decode(inp.encode(\"utf-8\"))\n+ data = SealedBox(signing_key.to_curve25519_private_key()).decrypt(token)\n+ config.server_address = data[32:].decode(\"utf-8\")\n+ config.server_verify_key = VerifyKey(data[:32])\n+ config.initial_setup_nickname = None\n+ except Exception:\n+ print(\"Invalid token!\")\n+ sys.exit(1)\n+\n+ print(f\"Server: {config.server_address}\")\n+ print(\"Testing connection...\")\n+\n+ port = connect(config)\n+ port.send_json({\"method\": \"ping\"})\n+ port.receive_json()\n+\n+ try:\n+ write_config(config)\n+ except Exception as e:\n+ print(\"Failed to write config:\", e)\n+ sys.exit(1)\n+\n+ print(\"permuter@home successfully set up!\")\ndiff --git a/src/net/cmd/util.py b/src/net/cmd/util.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/util.py\n@@ -0,0 +1,15 @@\n+import sys\n+\n+\n+def ask(msg: str, *, default: bool) -> bool:\n+ if default:\n+ msg += \" (Y/n)? \"\n+ else:\n+ msg += \" (y/N)? \"\n+ res = input(msg).strip().lower()\n+ if not res:\n+ return default\n+ if res in [\"y\", \"yes\", \"n\", \"no\"]:\n+ return res[0] == \"y\"\n+ print(\"Bad response!\")\n+ sys.exit(1)\ndiff --git a/src/net/cmd/vouch.py b/src/net/cmd/vouch.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/cmd/vouch.py\n@@ -0,0 +1,73 @@\n+from argparse import ArgumentParser, Namespace\n+import base64\n+import sys\n+\n+from nacl.encoding import HexEncoder\n+from nacl.public import SealedBox\n+from nacl.signing import VerifyKey\n+\n+from ..core import connect, read_config, verify_with_magic\n+from .base import Command\n+from .util import ask\n+\n+\n+class VouchCommand(Command):\n+ command = \"vouch\"\n+ help = \"Give someone access to the central server.\"\n+\n+ @staticmethod\n+ def add_arguments(parser: ArgumentParser) -> None:\n+ parser.add_argument(\n+ \"magic\",\n+ help=\"Opaque hex string generated by 'setup'.\",\n+ )\n+\n+ @staticmethod\n+ def run(args: Namespace) -> None:\n+ run_vouch(args.magic)\n+\n+\n+def run_vouch(magic: str) -> None:\n+ try:\n+ vouch_data = base64.b64decode(magic.encode(\"utf-8\"))\n+ verify_key = VerifyKey(vouch_data[:32])\n+ signed_nickname = vouch_data[32:]\n+ msg = verify_with_magic(b\"NAME\", verify_key, signed_nickname)\n+ nickname = msg.decode(\"utf-8\")\n+ except Exception:\n+ print(\"Could not parse data!\")\n+ sys.exit(1)\n+\n+ try:\n+ config = read_config()\n+ port = connect(config)\n+ port.send_json(\n+ {\n+ \"method\": \"vouch\",\n+ \"who\": verify_key.encode(HexEncoder).decode(\"utf-8\"),\n+ \"signed_name\": HexEncoder.encode(signed_nickname).decode(\"utf-8\"),\n+ }\n+ )\n+ port.receive_json()\n+ except Exception as e:\n+ print(f\"Error: {e}\")\n+ sys.exit(1)\n+\n+ if not ask(f\"Grant permuter server access to {nickname}\", default=True):\n+ return\n+\n+ try:\n+ port.send_json({})\n+ port.receive_json()\n+ except Exception as e:\n+ print(f\"Failed to grant access: {e}\")\n+ sys.exit(1)\n+\n+ assert config.server_address, \"checked by connect\"\n+ assert config.server_verify_key, \"checked by connect\"\n+ data = config.server_verify_key.encode() + config.server_address.encode(\"utf-8\")\n+ token = SealedBox(verify_key.to_curve25519_public_key()).encrypt(data)\n+ print(\"Granted!\")\n+ print()\n+ print(\"Send them the following token:\")\n+ print(base64.b64encode(token).decode(\"utf-8\"))\ndiff --git a/src/net/core.py b/src/net/core.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/core.py\n@@ -0,0 +1,391 @@\n+import abc\n+from dataclasses import dataclass\n+import datetime\n+import json\n+import socket\n+import struct\n+import sys\n+import toml\n+import traceback\n+import typing\n+from typing import BinaryIO, List, Optional, Tuple, Type, TypeVar, Union\n+\n+from nacl.encoding import HexEncoder\n+from nacl.public import Box, PrivateKey, PublicKey\n+from nacl.secret import SecretBox\n+from nacl.signing import SigningKey, VerifyKey\n+\n+from ..error import ServerError\n+from ..helpers import exception_to_string\n+\n+T = TypeVar(\"T\")\n+AnyBox = Union[Box, SecretBox]\n+\n+PERMUTER_VERSION = 1\n+\n+CONFIG_FILENAME = \"pah.conf\"\n+\n+MIN_PRIO = 0.01\n+MAX_PRIO = 2.0\n+\n+DEBUG_MODE = False\n+\n+\n+def enable_debug_mode() -> None:\n+ \"\"\"Enable debug logging.\"\"\"\n+ global DEBUG_MODE\n+ DEBUG_MODE = True\n+\n+\n+def debug_print(message: str) -> None:\n+ if DEBUG_MODE:\n+ time = datetime.datetime.now().strftime(\"%H:%M:%S:%f\")\n+ print(f\"\\n{time} debug: {message}\")\n+\n+\n+@dataclass(eq=False)\n+class CancelToken:\n+ cancelled: bool = False\n+\n+\n+@dataclass\n+class PermuterData:\n+ base_score: int\n+ base_hash: str\n+ fn_name: str\n+ filename: str\n+ keep_prob: float\n+ need_profiler: bool\n+ stack_differences: bool\n+ compile_script: str\n+ source: str\n+ target_o_bin: bytes\n+\n+\n+def permuter_data_from_json(\n+ obj: dict, source: str, target_o_bin: bytes\n+) -> PermuterData:\n+ return PermuterData(\n+ base_score=json_prop(obj, \"base_score\", int),\n+ base_hash=json_prop(obj, \"base_hash\", str),\n+ fn_name=json_prop(obj, \"fn_name\", str),\n+ filename=json_prop(obj, \"filename\", str),\n+ keep_prob=json_prop(obj, \"keep_prob\", float),\n+ need_profiler=json_prop(obj, \"need_profiler\", bool),\n+ stack_differences=json_prop(obj, \"stack_differences\", bool),\n+ compile_script=json_prop(obj, \"compile_script\", str),\n+ source=source,\n+ target_o_bin=target_o_bin,\n+ )\n+\n+\n+def permuter_data_to_json(perm: PermuterData) -> dict:\n+ return {\n+ \"base_score\": perm.base_score,\n+ \"base_hash\": perm.base_hash,\n+ \"fn_name\": perm.fn_name,\n+ \"filename\": perm.filename,\n+ \"keep_prob\": perm.keep_prob,\n+ \"need_profiler\": perm.need_profiler,\n+ \"stack_differences\": perm.stack_differences,\n+ \"compile_script\": perm.compile_script,\n+ }\n+\n+\n+@dataclass\n+class Config:\n+ server_address: Optional[str] = None\n+ server_verify_key: Optional[VerifyKey] = None\n+ signing_key: Optional[SigningKey] = None\n+ initial_setup_nickname: Optional[str] = None\n+\n+\n+def read_config() -> Config:\n+ config = Config()\n+ try:\n+ with open(CONFIG_FILENAME) as f:\n+ obj = toml.load(f)\n+\n+ def read(key: str, t: Type[T]) -> Optional[T]:\n+ ret = obj.get(key)\n+ return ret if isinstance(ret, t) else None\n+\n+ temp = read(\"server_public_key\", str)\n+ if temp:\n+ config.server_verify_key = VerifyKey(HexEncoder.decode(temp))\n+ temp = read(\"secret_key\", str)\n+ if temp:\n+ config.signing_key = SigningKey(HexEncoder.decode(temp))\n+ config.initial_setup_nickname = read(\"initial_setup_nickname\", str)\n+ config.server_address = read(\"server_address\", str)\n+ except FileNotFoundError:\n+ pass\n+ except Exception:\n+ print(f\"Malformed configuration file {CONFIG_FILENAME}.\\n\")\n+ raise\n+ return config\n+\n+\n+def write_config(config: Config) -> None:\n+ obj = {}\n+\n+ def write(key: str, val: Union[None, str, int]) -> None:\n+ if val is not None:\n+ obj[key] = val\n+\n+ write(\"initial_setup_nickname\", config.initial_setup_nickname)\n+ write(\"server_address\", config.server_address)\n+\n+ key_hex: bytes\n+ if config.server_verify_key:\n+ key_hex = config.server_verify_key.encode(HexEncoder)\n+ write(\"server_public_key\", key_hex.decode(\"utf-8\"))\n+ if config.signing_key:\n+ key_hex = config.signing_key.encode(HexEncoder)\n+ write(\"secret_key\", key_hex.decode(\"utf-8\"))\n+\n+ with open(CONFIG_FILENAME, \"w\") as f:\n+ toml.dump(obj, f)\n+\n+\n+def file_read_fixed(inf: BinaryIO, n: int) -> bytes:\n+ try:\n+ ret = []\n+ while n > 0:\n+ data = inf.read(n)\n+ if not data:\n+ raise EOFError\n+ ret.append(data)\n+ n -= len(data)\n+ return b\"\".join(ret)\n+ except EOFError:\n+ raise\n+ except Exception as e:\n+ raise EOFError from e\n+\n+\n+def socket_read_fixed(sock: socket.socket, n: int) -> bytes:\n+ try:\n+ ret = []\n+ while n > 0:\n+ data = sock.recv(min(n, 4096))\n+ if not data:\n+ raise EOFError\n+ ret.append(data)\n+ n -= len(data)\n+ return b\"\".join(ret)\n+ except EOFError:\n+ raise\n+ except Exception as e:\n+ raise EOFError from e\n+\n+\n+def socket_shutdown(sock: socket.socket, how: int) -> None:\n+ try:\n+ sock.shutdown(how)\n+ except Exception:\n+ pass\n+\n+\n+def json_prop(obj: dict, prop: str, t: Type[T]) -> T:\n+ ret = obj.get(prop)\n+ if not isinstance(ret, t):\n+ if t is float and isinstance(ret, int):\n+ return typing.cast(T, float(ret))\n+ found_type = type(ret).__name__\n+ if prop not in obj:\n+ raise ValueError(f\"Member {prop} does not exist\")\n+ raise ValueError(f\"Member {prop} must have type {t.__name__}; got {found_type}\")\n+ return ret\n+\n+\n+def json_array(obj: list, t: Type[T]) -> List[T]:\n+ for elem in obj:\n+ if not isinstance(elem, t):\n+ found_type = type(elem).__name__\n+ raise ValueError(\n+ f\"Array elements must have type {t.__name__}; got {found_type}\"\n+ )\n+ return obj\n+\n+\n+def sign_with_magic(magic: bytes, signing_key: SigningKey, data: bytes) -> bytes:\n+ signature: bytes = signing_key.sign(magic + b\":\" + data).signature\n+ return signature + data\n+\n+\n+def verify_with_magic(magic: bytes, verify_key: VerifyKey, data: bytes) -> bytes:\n+ if len(data) < 64:\n+ raise ValueError(\"String is too small to contain a signature\")\n+ signature = data[:64]\n+ data = data[64:]\n+ verify_key.verify(magic + b\":\" + data, signature)\n+ return data\n+\n+\n+class Port(abc.ABC):\n+ def __init__(self, box: AnyBox, who: str, *, is_client: bool) -> None:\n+ self._box = box\n+ self._who = who\n+ self._send_nonce = 0 if is_client else 1\n+ self._receive_nonce = 1 if is_client else 0\n+\n+ @abc.abstractmethod\n+ def _send(self, data: bytes) -> None:\n+ ...\n+\n+ @abc.abstractmethod\n+ def _receive(self, length: int) -> bytes:\n+ ...\n+\n+ def send(self, msg: bytes) -> None:\n+ \"\"\"Send a binary message, potentially blocking.\"\"\"\n+ if DEBUG_MODE:\n+ if len(msg) <= 300:\n+ debug_print(f\"Send to {self._who}: {msg!r}\")\n+ else:\n+ debug_print(f\"Send to {self._who}: {len(msg)} bytes\")\n+ nonce = struct.pack(\">16xQ\", self._send_nonce)\n+ self._send_nonce += 2\n+ data = self._box.encrypt(msg, nonce).ciphertext\n+ length_data = struct.pack(\">Q\", len(data))\n+ self._send(length_data + data)\n+\n+ def send_json(self, msg: dict) -> None:\n+ \"\"\"Send a message in the form of a JSON dict, potentially blocking.\"\"\"\n+ self.send(json.dumps(msg).encode(\"utf-8\"))\n+\n+ def receive(self) -> bytes:\n+ \"\"\"Read a binary message, blocking.\"\"\"\n+ length_data = self._receive(8)\n+ if length_data[0]:\n+ # Lengths above 2^56 are unreasonable, so if we get one someone is\n+ # sending us bad data. Raise an exception to help debugging.\n+ raise Exception(\"Got unexpected data: \" + repr(length_data))\n+ length = struct.unpack(\">Q\", length_data)[0]\n+ data = self._receive(length)\n+ nonce = struct.pack(\">16xQ\", self._receive_nonce)\n+ self._receive_nonce += 2\n+ msg: bytes = self._box.decrypt(data, nonce)\n+ if DEBUG_MODE:\n+ if len(msg) <= 300:\n+ debug_print(f\"Receive from {self._who}: {msg!r}\")\n+ else:\n+ debug_print(f\"Receive from {self._who}: {len(msg)} bytes\")\n+ return msg\n+\n+ def receive_json(self) -> dict:\n+ \"\"\"Read a message in the form of a JSON dict, blocking.\"\"\"\n+ ret = json.loads(self.receive())\n+ if isinstance(ret, str):\n+ # Raw strings indicate errors.\n+ raise ServerError(ret)\n+ if not isinstance(ret, dict):\n+ # We always pass dictionaries as messages and no other data types,\n+ # to ensure future extensibility. (Other types are rare in\n+ # practice, anyway.)\n+ raise ValueError(\"Top-level JSON value must be a dictionary\")\n+ return ret\n+\n+\n+class SocketPort(Port):\n+ def __init__(\n+ self, sock: socket.socket, box: AnyBox, who: str, *, is_client: bool\n+ ) -> None:\n+ self._sock = sock\n+ super().__init__(box, who, is_client=is_client)\n+\n+ def _send(self, data: bytes) -> None:\n+ self._sock.sendall(data)\n+\n+ def _receive(self, length: int) -> bytes:\n+ return socket_read_fixed(self._sock, length)\n+\n+ def shutdown(self, how: int = socket.SHUT_RDWR) -> None:\n+ socket_shutdown(self._sock, how)\n+\n+ def close(self) -> None:\n+ self._sock.close()\n+\n+\n+class FilePort(Port):\n+ def __init__(\n+ self, inf: BinaryIO, outf: BinaryIO, box: AnyBox, who: str, *, is_client: bool\n+ ) -> None:\n+ self._inf = inf\n+ self._outf = outf\n+ super().__init__(box, who, is_client=is_client)\n+\n+ def _send(self, data: bytes) -> None:\n+ self._outf.write(data)\n+ self._outf.flush()\n+\n+ def _receive(self, length: int) -> bytes:\n+ return file_read_fixed(self._inf, length)\n+\n+\n+def _do_connect(config: Config) -> SocketPort:\n+ if (\n+ not config.server_verify_key\n+ or not config.signing_key\n+ or not config.server_address\n+ ):\n+ print(\n+ \"Using permuter@home requires someone to give you access to a central -J server.\\n\"\n+ \"Run `./pah.py setup` to set this up.\"\n+ )\n+ print()\n+ sys.exit(1)\n+\n+ host, port_str = config.server_address.split(\":\")\n+ try:\n+ sock = socket.create_connection((host, int(port_str)))\n+ except ConnectionRefusedError:\n+ raise EOFError(\"connection refused\") from None\n+ except socket.gaierror as e:\n+ raise EOFError(f\"DNS lookup failed: {e}\") from None\n+ except Exception as e:\n+ raise EOFError(\"unable to connect: \" + exception_to_string(e)) from None\n+\n+ # Send over the protocol version and an ephemeral encryption key which we\n+ # are going to use for all communication.\n+ ephemeral_key = PrivateKey.generate()\n+ ephemeral_key_data = ephemeral_key.public_key.encode()\n+ sock.sendall(b\"p@h0\" + ephemeral_key_data)\n+\n+ # Receive the server's encryption key, plus a signature of it and our own\n+ # ephemeral key -- this guarantees that we are talking to the server and\n+ # aren't victim to a replay attack. Use it to set up a communication port.\n+ msg = socket_read_fixed(sock, 32 + 64)\n+ server_enc_key_data = msg[:32]\n+ config.server_verify_key.verify(\n+ b\"HELLO:\" + ephemeral_key_data + server_enc_key_data, msg[32:]\n+ )\n+ box = Box(ephemeral_key, PublicKey(server_enc_key_data))\n+ port = SocketPort(sock, box, \"controller\", is_client=True)\n+\n+ # Use the encrypted port to send over our public key, proof that we are\n+ # able to sign new things with it, as well as permuter version.\n+ signature: bytes = config.signing_key.sign(\n+ b\"WORLD:\" + server_enc_key_data\n+ ).signature\n+ port.send(\n+ config.signing_key.verify_key.encode()\n+ + signature\n+ + struct.pack(\">I\", PERMUTER_VERSION)\n+ )\n+\n+ # Get an acknowledgement that the server wants to talk to us.\n+ obj = port.receive_json()\n+\n+ if \"message\" in obj:\n+ print(obj[\"message\"])\n+\n+ return port\n+\n+\n+def connect(config: Optional[Config] = None) -> SocketPort:\n+ \"\"\"Authenticate and connect to the permuter@home controller server.\"\"\"\n+ if not config:\n+ config = read_config()\n+ return _do_connect(config)\ndiff --git a/src/net/evaluator.py b/src/net/evaluator.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/evaluator.py\n@@ -0,0 +1,396 @@\n+\"\"\"This file runs as a free-standing program within a sandbox, and processes\n+permutation requests. It communicates with the outside world on stdin/stdout.\"\"\"\n+import base64\n+from dataclasses import dataclass\n+import math\n+from multiprocessing import Process, Queue\n+import os\n+import queue\n+import struct\n+import sys\n+from tempfile import mkstemp\n+import threading\n+import time\n+import traceback\n+from typing import BinaryIO, Counter, Dict, List, Optional, Set, Tuple, Union\n+import zlib\n+\n+from nacl.secret import SecretBox\n+\n+from ..candidate import CandidateResult\n+from ..compiler import Compiler\n+from ..error import CandidateConstructionFailure\n+from ..helpers import exception_to_string, static_assert_unreachable\n+from ..permuter import EvalError, EvalResult, Permuter\n+from ..profiler import Profiler\n+from ..scorer import Scorer\n+from .core import (\n+ FilePort,\n+ PermuterData,\n+ Port,\n+ json_prop,\n+ permuter_data_from_json,\n+)\n+\n+\n+def _fix_stdout() -> None:\n+ \"\"\"Redirect stdout to stderr to make print() debugging work. This function\n+ *must* be called at startup for each (sub)process, since we use stdout for\n+ our own communication purposes.\"\"\"\n+ sys.stdout = sys.stderr\n+\n+ # In addition, we set stderr to flush on newlines, which not happen by\n+ # default when it is piped. (Requires Python 3.7, but we can assume that's\n+ # available inside the sandbox.)\n+ sys.stdout.reconfigure(line_buffering=True) # type: ignore\n+\n+\n+def _setup_port(secret: bytes) -> Port:\n+ \"\"\"Set up communication with the outside world.\"\"\"\n+ port = FilePort(\n+ sys.stdin.buffer,\n+ sys.stdout.buffer,\n+ SecretBox(secret),\n+ \"server\",\n+ is_client=False,\n+ )\n+\n+ # Follow the controlling process's sanity check protocol.\n+ magic = port.receive()\n+ port.send(magic)\n+\n+ return port\n+\n+\n+def _create_permuter(data: PermuterData) -> Permuter:\n+ fd, path = mkstemp(suffix=\".o\", prefix=\"permuter\", text=False)\n+ try:\n+ with os.fdopen(fd, \"wb\") as f:\n+ f.write(data.target_o_bin)\n+ scorer = Scorer(target_o=path, stack_differences=data.stack_differences)\n+ finally:\n+ os.unlink(path)\n+\n+ fd, path = mkstemp(suffix=\".sh\", prefix=\"permuter\", text=True)\n+ try:\n+ os.chmod(fd, 0o755)\n+ with os.fdopen(fd, \"w\") as f2:\n+ f2.write(data.compile_script)\n+ compiler = Compiler(compile_cmd=path, show_errors=False)\n+\n+ return Permuter(\n+ dir=\"unused\",\n+ fn_name=data.fn_name,\n+ compiler=compiler,\n+ scorer=scorer,\n+ source_file=data.filename,\n+ source=data.source,\n+ force_seed=None,\n+ force_rng_seed=None,\n+ keep_prob=data.keep_prob,\n+ need_profiler=data.need_profiler,\n+ need_all_sources=False,\n+ show_errors=False,\n+ better_only=False,\n+ best_only=False,\n+ )\n+ except:\n+ os.unlink(path)\n+ raise\n+\n+\n+def _remove_permuter(perm: Permuter) -> None:\n+ os.unlink(perm.compiler.compile_cmd)\n+\n+\n+def _send_result(perm_id: str, time_us: float, res: EvalResult, port: Port) -> None:\n+ if isinstance(res, EvalError):\n+ port.send_json(\n+ {\n+ \"type\": \"result\",\n+ \"id\": perm_id,\n+ \"time_us\": time_us,\n+ \"error\": res.exc_str,\n+ }\n+ )\n+ return\n+\n+ compressed_source = getattr(res, \"compressed_source\")\n+\n+ obj = {\n+ \"type\": \"result\",\n+ \"id\": perm_id,\n+ \"time_us\": time_us,\n+ \"score\": res.score,\n+ \"has_source\": compressed_source is not None,\n+ }\n+ if res.hash is not None:\n+ obj[\"hash\"] = res.hash\n+ if res.profiler is not None:\n+ obj[\"profiler\"] = {\n+ st.name: res.profiler.time_stats[st] for st in Profiler.StatType\n+ }\n+\n+ port.send_json(obj)\n+\n+ if compressed_source is not None:\n+ port.send(compressed_source)\n+\n+\n+@dataclass\n+class AddPermuter:\n+ perm_id: str\n+ data: PermuterData\n+\n+\n+@dataclass\n+class AddPermuterLocal:\n+ perm_id: str\n+ permuter: Permuter\n+\n+\n+@dataclass\n+class RemovePermuter:\n+ perm_id: str\n+\n+\n+@dataclass\n+class WorkDone:\n+ perm_id: str\n+ time_us: float\n+ result: EvalResult\n+\n+\n+@dataclass\n+class Work:\n+ perm_id: str\n+ seed: int\n+\n+\n+class NeedMoreWork:\n+ pass\n+\n+\n+LocalWork = Tuple[Union[AddPermuterLocal, RemovePermuter], int]\n+GlobalWork = Tuple[Work, int]\n+Task = Union[AddPermuter, RemovePermuter, Work, WorkDone, NeedMoreWork]\n+\n+\n+def multiprocess_worker(\n+ worker_queue: \"Queue[GlobalWork]\",\n+ local_queue: \"Queue[LocalWork]\",\n+ task_queue: \"Queue[Task]\",\n+) -> None:\n+ _fix_stdout()\n+\n+ permuters: Dict[str, Permuter] = {}\n+ timestamp = 0\n+\n+ while True:\n+ try:\n+ work, required_timestamp = worker_queue.get(block=False)\n+ except queue.Empty:\n+ task_queue.put(NeedMoreWork())\n+ work, required_timestamp = worker_queue.get()\n+ while True:\n+ try:\n+ block = timestamp < required_timestamp\n+ task, timestamp = local_queue.get(block=block)\n+ except queue.Empty:\n+ break\n+ if isinstance(task, AddPermuterLocal):\n+ permuters[task.perm_id] = task.permuter\n+ elif isinstance(task, RemovePermuter):\n+ del permuters[task.perm_id]\n+ else:\n+ static_assert_unreachable(task)\n+\n+ time_before = time.time()\n+\n+ permuter = permuters[work.perm_id]\n+ result = permuter.try_eval_candidate(work.seed)\n+ if isinstance(result, CandidateResult) and permuter.should_output(result):\n+ permuter.record_result(result)\n+\n+ # Compress the source within the worker. (Why waste a free\n+ # multi-threading opportunity?)\n+ if isinstance(result, CandidateResult):\n+ compressed_source: Optional[bytes] = None\n+ if result.source is not None:\n+ compressed_source = zlib.compress(result.source.encode(\"utf-8\"))\n+ setattr(result, \"compressed_source\", compressed_source)\n+ result.source = None\n+\n+ time_us = int((time.time() - time_before) * 10 ** 6)\n+ task_queue.put(WorkDone(perm_id=work.perm_id, time_us=time_us, result=result))\n+\n+\n+def read_loop(task_queue: \"Queue[Task]\", port: Port) -> None:\n+ try:\n+ while True:\n+ item = port.receive_json()\n+ msg_type = json_prop(item, \"type\", str)\n+ if msg_type == \"add\":\n+ perm_id = json_prop(item, \"id\", str)\n+ source = port.receive().decode(\"utf-8\")\n+ target_o_bin = port.receive()\n+ data = permuter_data_from_json(item, source, target_o_bin)\n+ task_queue.put(AddPermuter(perm_id=perm_id, data=data))\n+\n+ elif msg_type == \"remove\":\n+ perm_id = json_prop(item, \"id\", str)\n+ task_queue.put(RemovePermuter(perm_id=perm_id))\n+\n+ elif msg_type == \"work\":\n+ perm_id = json_prop(item, \"id\", str)\n+ seed = json_prop(item, \"seed\", int)\n+ task_queue.put(Work(perm_id=perm_id, seed=seed))\n+\n+ else:\n+ raise Exception(f\"Invalid message type {msg_type}\")\n+\n+ except EOFError:\n+ # Port closed from the other side. Silently exit, to avoid ugly error\n+ # messages and to ensure that the Docker container really stops and\n+ # gets removed. (The parent server has a \"finally:\" that does that, but\n+ # it's evidently not 100% trustworthy. I'm speculating that pystray\n+ # might be to blame, by reverting the signal handler for SIGINT to\n+ # the default, making Ctrl+C kill the program directly without firing\n+ # \"finally\"s. Either way, defense in depth here doesn't hurt, since\n+ # leaking Docker containers is pretty bad.)\n+ os._exit(1)\n+\n+ except Exception:\n+ traceback.print_exc()\n+ os._exit(1)\n+\n+\n+def main() -> None:\n+ secret = base64.b64decode(os.environ[\"SECRET\"])\n+ del os.environ[\"SECRET\"]\n+ os.environ[\"PERMUTER_IS_REMOTE\"] = \"1\"\n+\n+ port = _setup_port(secret)\n+ _fix_stdout()\n+\n+ obj = port.receive_json()\n+ num_cores = json_prop(obj, \"num_cores\", float)\n+ num_threads = math.ceil(num_cores)\n+\n+ worker_queue: \"Queue[GlobalWork]\" = Queue()\n+ task_queue: \"Queue[Task]\" = Queue()\n+ local_queues: \"List[Queue[LocalWork]]\" = []\n+\n+ for i in range(num_threads):\n+ local_queue: \"Queue[LocalWork]\" = Queue()\n+ p = Process(\n+ target=multiprocess_worker,\n+ args=(worker_queue, local_queue, task_queue),\n+ )\n+ p.start()\n+ local_queues.append(local_queue)\n+\n+ reader_thread = threading.Thread(target=read_loop, args=(task_queue, port))\n+ reader_thread.start()\n+\n+ remaining_work: Counter[str] = Counter()\n+ should_remove: Set[str] = set()\n+ permuters: Dict[str, Permuter] = {}\n+ timestamp = 0\n+\n+ def try_remove(perm_id: str) -> None:\n+ nonlocal timestamp\n+ assert perm_id in permuters\n+ if perm_id not in should_remove or remaining_work[perm_id] != 0:\n+ return\n+ del remaining_work[perm_id]\n+ should_remove.remove(perm_id)\n+ timestamp += 1\n+ for queue in local_queues:\n+ queue.put((RemovePermuter(perm_id=perm_id), timestamp))\n+ _remove_permuter(permuters[perm_id])\n+ del permuters[perm_id]\n+\n+ while True:\n+ item = task_queue.get()\n+\n+ if isinstance(item, AddPermuter):\n+ assert item.perm_id not in permuters\n+\n+ msg: Dict[str, object] = {\n+ \"type\": \"init\",\n+ \"id\": item.perm_id,\n+ }\n+\n+ time_before = time.time()\n+ try:\n+ # Construct a permuter. This involves a compilation on the main\n+ # thread, which isn't great but we can live with it for now.\n+ permuter = _create_permuter(item.data)\n+\n+ if permuter.base_score != item.data.base_score:\n+ _remove_permuter(permuter)\n+ score_str = f\"{permuter.base_score} vs {item.data.base_score}\"\n+ if permuter.base_hash == item.data.base_hash:\n+ hash_str = \"same hash; different Python or permuter versions?\"\n+ else:\n+ hash_str = \"different hash; different objdump versions?\"\n+ raise CandidateConstructionFailure(\n+ f\"mismatching score: {score_str} ({hash_str})\"\n+ )\n+\n+ permuters[item.perm_id] = permuter\n+\n+ msg[\"success\"] = True\n+ msg[\"base_score\"] = permuter.base_score\n+ msg[\"base_hash\"] = permuter.base_hash\n+\n+ # Tell all the workers about the new permuter.\n+ # TODO: ideally we would also seed their Candidate lru_cache's\n+ # to avoid all workers having to parse the source...\n+ timestamp += 1\n+ for queue in local_queues:\n+ queue.put(\n+ (\n+ AddPermuterLocal(perm_id=item.perm_id, permuter=permuter),\n+ timestamp,\n+ )\n+ )\n+ except Exception as e:\n+ # This shouldn't practically happen, since the client compiled\n+ # the code successfully. Print a message if it does.\n+ msg[\"success\"] = False\n+ msg[\"error\"] = exception_to_string(e)\n+ if isinstance(e, CandidateConstructionFailure):\n+ print(e.message)\n+ else:\n+ traceback.print_exc()\n+\n+ msg[\"time_us\"] = int((time.time() - time_before) * 10 ** 6)\n+ port.send_json(msg)\n+\n+ elif isinstance(item, RemovePermuter):\n+ # Silently ignore requests to remove permuters that have already\n+ # been removed, which can occur when AddPermuter fails.\n+ if item.perm_id in permuters:\n+ should_remove.add(item.perm_id)\n+ try_remove(item.perm_id)\n+\n+ elif isinstance(item, WorkDone):\n+ remaining_work[item.perm_id] -= 1\n+ try_remove(item.perm_id)\n+ _send_result(item.perm_id, item.time_us, item.result, port)\n+\n+ elif isinstance(item, Work):\n+ remaining_work[item.perm_id] += 1\n+ worker_queue.put((item, timestamp))\n+\n+ elif isinstance(item, NeedMoreWork):\n+ port.send_json({\"type\": \"need_work\"})\n+\n+ else:\n+ static_assert_unreachable(item)\n+\n+\n+if __name__ == \"__main__\":\n+ main()\ndiff --git a/src/net/server.py b/src/net/server.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/net/server.py\n@@ -0,0 +1,917 @@\n+import abc\n+import base64\n+from dataclasses import dataclass, field\n+from enum import Enum\n+import json\n+import os\n+import pathlib\n+import queue\n+import socket\n+import socketserver\n+import struct\n+import subprocess\n+import sys\n+import threading\n+import time\n+import traceback\n+from typing import BinaryIO, Dict, List, Optional, Set, Tuple, Union\n+import uuid\n+import zlib\n+\n+import docker\n+from nacl.public import Box, PrivateKey, PublicKey\n+from nacl.secret import SecretBox\n+from nacl.signing import SigningKey, VerifyKey\n+import nacl.utils\n+\n+from ..helpers import exception_to_string, static_assert_unreachable\n+from .core import (\n+ CancelToken,\n+ PermuterData,\n+ Port,\n+ SocketPort,\n+ connect,\n+ file_read_fixed,\n+ json_prop,\n+ permuter_data_from_json,\n+ permuter_data_to_json,\n+)\n+\n+\n+_HEARTBEAT_INTERVAL_SLACK: float = 50.0\n+\n+\n+@dataclass\n+class Client:\n+ id: str\n+ nickname: str\n+\n+\n+class InitState(Enum):\n+ UNINIT = 0\n+ WAITING = 1\n+ READY = 2\n+\n+\n+@dataclass\n+class ClientState:\n+ handle: int\n+ client: Client\n+ init_state: InitState = InitState.UNINIT\n+\n+\n+@dataclass\n+class AddPermuter:\n+ handle: int\n+ client: Client\n+ permuter_data: PermuterData\n+\n+\n+@dataclass\n+class RemovePermuter:\n+ handle: int\n+\n+\n+@dataclass\n+class Work:\n+ handle: int\n+ seed: int\n+\n+\n+@dataclass\n+class ImmediateDisconnect:\n+ handle: int\n+ client: Client\n+ reason: str\n+\n+\n+@dataclass\n+class Disconnect:\n+ handle: int\n+\n+\n+@dataclass\n+class PermInitFail:\n+ perm_id: str\n+ error: str\n+\n+\n+@dataclass\n+class PermInitSuccess:\n+ perm_id: str\n+ base_score: int\n+ base_hash: str\n+ time_us: float\n+\n+\n+@dataclass\n+class WorkDone:\n+ perm_id: str\n+ obj: dict\n+ time_us: float\n+ compressed_source: Optional[bytes]\n+\n+\n+class NeedMoreWork:\n+ pass\n+\n+\n+@dataclass\n+class NetThreadDisconnected:\n+ graceful: bool\n+\n+\n+class Heartbeat:\n+ pass\n+\n+\n+class Shutdown:\n+ pass\n+\n+\n+Activity = Union[\n+ AddPermuter,\n+ RemovePermuter,\n+ Work,\n+ ImmediateDisconnect,\n+ Disconnect,\n+ PermInitFail,\n+ PermInitSuccess,\n+ WorkDone,\n+ NeedMoreWork,\n+ NetThreadDisconnected,\n+ Heartbeat,\n+ Shutdown,\n+]\n+\n+\n+@dataclass\n+class OutputInitFail:\n+ handle: int\n+ error: str\n+\n+\n+@dataclass\n+class OutputInitSuccess:\n+ handle: int\n+ base_score: int\n+ base_hash: str\n+ time_us: float\n+\n+\n+@dataclass\n+class OutputDisconnect:\n+ handle: int\n+\n+\n+@dataclass\n+class OutputNeedMoreWork:\n+ pass\n+\n+\n+@dataclass\n+class OutputWork:\n+ handle: int\n+ time_us: float\n+ obj: dict\n+ compressed_source: Optional[bytes]\n+\n+\n+Output = Union[\n+ OutputDisconnect,\n+ OutputInitFail,\n+ OutputInitSuccess,\n+ OutputNeedMoreWork,\n+ OutputWork,\n+ Shutdown,\n+]\n+\n+\n+@dataclass\n+class IoConnect:\n+ fn_name: str\n+ client: Client\n+\n+\n+@dataclass\n+class IoDisconnect:\n+ reason: str\n+\n+\n+@dataclass\n+class IoImmediateDisconnect:\n+ reason: str\n+ client: Client\n+\n+\n+class IoUserRemovePermuter:\n+ pass\n+\n+\n+@dataclass\n+class IoServerFailed:\n+ graceful: bool\n+\n+\n+class IoReconnect:\n+ pass\n+\n+\n+class IoShutdown:\n+ pass\n+\n+\n+class IoWillSleep:\n+ pass\n+\n+\n+@dataclass\n+class IoWorkDone:\n+ score: Optional[int]\n+ is_improvement: bool\n+\n+\n+PermuterHandle = Tuple[int, CancelToken]\n+IoMessage = Union[\n+ IoConnect, IoDisconnect, IoImmediateDisconnect, IoUserRemovePermuter, IoWorkDone\n+]\n+IoGlobalMessage = Union[IoReconnect, IoShutdown, IoServerFailed, IoWillSleep]\n+IoActivity = Tuple[\n+ Optional[CancelToken], Union[Tuple[PermuterHandle, IoMessage], IoGlobalMessage]\n+]\n+\n+\n+@dataclass\n+class ServerOptions:\n+ num_cores: float\n+ max_memory_gb: float\n+ min_priority: float\n+\n+\n+class NetThread:\n+ _port: Optional[SocketPort]\n+ _main_queue: \"queue.Queue[Activity]\"\n+ _controller_queue: \"queue.Queue[Output]\"\n+ _read_thread: \"threading.Thread\"\n+ _write_thread: \"threading.Thread\"\n+\n+ def __init__(\n+ self,\n+ port: SocketPort,\n+ main_queue: \"queue.Queue[Activity]\",\n+ ) -> None:\n+ self._port = port\n+ self._main_queue = main_queue\n+ self._controller_queue = queue.Queue()\n+\n+ self._read_thread = threading.Thread(target=self.read_loop)\n+ self._read_thread.daemon = True\n+ self._read_thread.start()\n+\n+ self._write_thread = threading.Thread(target=self.write_loop)\n+ self._write_thread.daemon = True\n+ self._write_thread.start()\n+\n+ def stop(self) -> None:\n+ if self._port is None:\n+ return\n+ try:\n+ self._controller_queue.put(Shutdown())\n+ self._port.shutdown()\n+ self._read_thread.join()\n+ self._write_thread.join()\n+ self._port.close()\n+ self._port = None\n+ except Exception:\n+ print(\"Failed to stop net thread.\")\n+ traceback.print_exc()\n+\n+ def send_controller(self, msg: Output) -> None:\n+ self._controller_queue.put(msg)\n+\n+ def _read_one(self) -> Activity:\n+ assert self._port is not None\n+\n+ msg = self._port.receive_json()\n+\n+ msg_type = json_prop(msg, \"type\", str)\n+\n+ if msg_type == \"heartbeat\":\n+ return Heartbeat()\n+\n+ handle = json_prop(msg, \"permuter\", int)\n+\n+ if msg_type == \"work\":\n+ seed = json_prop(msg, \"seed\", int)\n+ return Work(handle=handle, seed=seed)\n+\n+ elif msg_type == \"add\":\n+ client_id = json_prop(msg, \"client_id\", str)\n+ client_name = json_prop(msg, \"client_name\", str)\n+ client = Client(client_id, client_name)\n+ data = json_prop(msg, \"data\", dict)\n+ compressed_source = self._port.receive()\n+ compressed_target_o_bin = self._port.receive()\n+\n+ try:\n+ source = zlib.decompress(compressed_source).decode(\"utf-8\")\n+ target_o_bin = zlib.decompress(compressed_target_o_bin)\n+ permuter = permuter_data_from_json(data, source, target_o_bin)\n+ except Exception as e:\n+ # Client sent something illegible. This can legitimately happen if the\n+ # client runs another version, but it's interesting to log.\n+ traceback.print_exc()\n+ return ImmediateDisconnect(\n+ handle=handle,\n+ client=client,\n+ reason=f\"Failed to parse permuter: {exception_to_string(e)}\",\n+ )\n+\n+ return AddPermuter(\n+ handle=handle,\n+ client=client,\n+ permuter_data=permuter,\n+ )\n+\n+ elif msg_type == \"remove\":\n+ return RemovePermuter(handle=handle)\n+\n+ else:\n+ raise Exception(f\"Bad message type: {msg_type}\")\n+\n+ def read_loop(self) -> None:\n+ try:\n+ while True:\n+ msg = self._read_one()\n+ self._main_queue.put(msg)\n+ except EOFError:\n+ self._main_queue.put(NetThreadDisconnected(graceful=True))\n+ except Exception:\n+ traceback.print_exc()\n+ self._main_queue.put(NetThreadDisconnected(graceful=False))\n+\n+ def _write_one(self, item: Output) -> None:\n+ assert self._port is not None\n+\n+ if isinstance(item, Shutdown):\n+ # Handled by caller\n+ pass\n+\n+ elif isinstance(item, OutputInitFail):\n+ self._port.send_json(\n+ {\n+ \"type\": \"update\",\n+ \"permuter\": item.handle,\n+ \"time_us\": 0,\n+ \"update\": {\"type\": \"init_failed\", \"reason\": item.error},\n+ }\n+ )\n+\n+ elif isinstance(item, OutputInitSuccess):\n+ self._port.send_json(\n+ {\n+ \"type\": \"update\",\n+ \"permuter\": item.handle,\n+ \"time_us\": item.time_us,\n+ \"update\": {\"type\": \"init_done\", \"hash\": item.base_hash},\n+ }\n+ )\n+\n+ elif isinstance(item, OutputDisconnect):\n+ self._port.send_json(\n+ {\n+ \"type\": \"update\",\n+ \"permuter\": item.handle,\n+ \"time_us\": 0,\n+ \"update\": {\"type\": \"disconnect\"},\n+ }\n+ )\n+\n+ elif isinstance(item, OutputNeedMoreWork):\n+ self._port.send_json({\"type\": \"need_work\"})\n+\n+ elif isinstance(item, OutputWork):\n+ self._port.send_json(\n+ {\n+ \"type\": \"update\",\n+ \"permuter\": item.handle,\n+ \"time_us\": item.time_us,\n+ \"update\": {\n+ \"type\": \"work\",\n+ **item.obj,\n+ },\n+ }\n+ )\n+ if item.compressed_source is not None:\n+ self._port.send(item.compressed_source)\n+\n+ else:\n+ static_assert_unreachable(item)\n+\n+ def write_loop(self) -> None:\n+ try:\n+ while True:\n+ item = self._controller_queue.get()\n+ if isinstance(item, Shutdown):\n+ break\n+ self._write_one(item)\n+ except EOFError:\n+ self._main_queue.put(NetThreadDisconnected(graceful=True))\n+ except Exception:\n+ traceback.print_exc()\n+ self._main_queue.put(NetThreadDisconnected(graceful=False))\n+\n+\n+class ServerInner:\n+ \"\"\"This class represents an up-and-running server, connected to the controller and\n+ to the evaluator.\"\"\"\n+\n+ _evaluator_port: \"DockerPort\"\n+ _main_queue: \"queue.Queue[Activity]\"\n+ _io_queue: \"queue.Queue[IoActivity]\"\n+ _net_thread: NetThread\n+ _read_eval_thread: threading.Thread\n+ _main_thread: threading.Thread\n+ _heartbeat_interval: float\n+ _last_heartbeat: float\n+ _last_heartbeat_lock: threading.Lock\n+ _active: Set[int]\n+ _token: CancelToken\n+\n+ def __init__(\n+ self,\n+ net_port: SocketPort,\n+ evaluator_port: \"DockerPort\",\n+ io_queue: \"queue.Queue[IoActivity]\",\n+ heartbeat_interval: float,\n+ ) -> None:\n+ self._evaluator_port = evaluator_port\n+ self._main_queue = queue.Queue()\n+ self._io_queue = io_queue\n+ self._active = set()\n+ self._token = CancelToken()\n+\n+ self._net_thread = NetThread(net_port, self._main_queue)\n+\n+ # Start a thread for checking heartbeats.\n+ self._heartbeat_interval = heartbeat_interval\n+ self._last_heartbeat = time.time()\n+ self._last_heartbeat_lock = threading.Lock()\n+ self._heartbeat_stop = threading.Event()\n+ self._heartbeat_thread = threading.Thread(target=self._heartbeat_loop)\n+ self._heartbeat_thread.daemon = True\n+ self._heartbeat_thread.start()\n+\n+ # Start a thread for reading evaluator results and sending them on to\n+ # the main loop queue.\n+ self._read_eval_thread = threading.Thread(target=self._read_eval_loop)\n+ self._read_eval_thread.daemon = True\n+ self._read_eval_thread.start()\n+\n+ # Start a thread for the main loop.\n+ self._main_thread = threading.Thread(target=self._main_loop)\n+ self._main_thread.daemon = True\n+ self._main_thread.start()\n+\n+ def _send_controller(self, msg: Output) -> None:\n+ self._net_thread.send_controller(msg)\n+\n+ def _send_io(self, handle: int, io_msg: IoMessage) -> None:\n+ self._io_queue.put((self._token, ((handle, self._token), io_msg)))\n+\n+ def _send_io_global(self, io_msg: IoGlobalMessage) -> None:\n+ self._io_queue.put((self._token, io_msg))\n+\n+ def _handle_message(self, msg: Activity) -> None:\n+ if isinstance(msg, Shutdown):\n+ # Handled by caller\n+ pass\n+\n+ elif isinstance(msg, Heartbeat):\n+ with self._last_heartbeat_lock:\n+ self._last_heartbeat = time.time()\n+\n+ elif isinstance(msg, Work):\n+ if msg.handle not in self._active:\n+ self._need_work()\n+ return\n+\n+ self._evaluator_port.send_json(\n+ {\n+ \"type\": \"work\",\n+ \"id\": str(msg.handle),\n+ \"seed\": msg.seed,\n+ }\n+ )\n+\n+ elif isinstance(msg, AddPermuter):\n+ if msg.handle in self._active:\n+ raise Exception(\"Repeated AddPermuter!\")\n+\n+ self._active.add(msg.handle)\n+ self._send_permuter(str(msg.handle), msg.permuter_data)\n+ fn_name = msg.permuter_data.fn_name\n+ self._send_io(msg.handle, IoConnect(fn_name, msg.client))\n+\n+ elif isinstance(msg, RemovePermuter):\n+ if msg.handle not in self._active:\n+ return\n+\n+ self._remove(msg.handle)\n+ self._send_io(msg.handle, IoDisconnect(\"disconnected\"))\n+\n+ elif isinstance(msg, Disconnect):\n+ if msg.handle not in self._active:\n+ return\n+\n+ self._remove(msg.handle)\n+ self._send_io(msg.handle, IoDisconnect(\"kicked\"))\n+ self._send_controller(OutputDisconnect(handle=msg.handle))\n+\n+ elif isinstance(msg, ImmediateDisconnect):\n+ if msg.handle in self._active:\n+ raise Exception(\"ImmediateDisconnect is not immediate\")\n+\n+ self._send_io(\n+ msg.handle, IoImmediateDisconnect(\"sent garbage message\", msg.client)\n+ )\n+ self._send_controller(OutputDisconnect(handle=msg.handle))\n+\n+ elif isinstance(msg, PermInitFail):\n+ handle = int(msg.perm_id)\n+ if handle not in self._active:\n+ self._need_work()\n+ return\n+\n+ self._active.remove(handle)\n+ self._send_io(handle, IoDisconnect(\"failed to compile\"))\n+ self._send_controller(\n+ OutputInitFail(\n+ handle=handle,\n+ error=msg.error,\n+ )\n+ )\n+\n+ elif isinstance(msg, PermInitSuccess):\n+ handle = int(msg.perm_id)\n+ if handle not in self._active:\n+ self._need_work()\n+ return\n+\n+ self._send_controller(\n+ OutputInitSuccess(\n+ handle=handle,\n+ time_us=msg.time_us,\n+ base_score=msg.base_score,\n+ base_hash=msg.base_hash,\n+ )\n+ )\n+\n+ elif isinstance(msg, WorkDone):\n+ handle = int(msg.perm_id)\n+ if handle not in self._active:\n+ self._need_work()\n+ return\n+\n+ obj = msg.obj\n+ obj[\"permuter\"] = handle\n+ score = json_prop(obj, \"score\", int) if \"score\" in obj else None\n+ is_improvement = msg.compressed_source is not None\n+ self._send_io(\n+ handle,\n+ IoWorkDone(score=score, is_improvement=is_improvement),\n+ )\n+ self._send_controller(\n+ OutputWork(\n+ handle=handle,\n+ time_us=msg.time_us,\n+ obj=obj,\n+ compressed_source=msg.compressed_source,\n+ )\n+ )\n+\n+ elif isinstance(msg, NeedMoreWork):\n+ self._need_work()\n+\n+ elif isinstance(msg, NetThreadDisconnected):\n+ self._send_io_global(IoServerFailed(msg.graceful))\n+\n+ else:\n+ static_assert_unreachable(msg)\n+\n+ def _need_work(self) -> None:\n+ self._send_controller(OutputNeedMoreWork())\n+\n+ def _remove(self, handle: int) -> None:\n+ self._evaluator_port.send_json({\"type\": \"remove\", \"id\": str(handle)})\n+ self._active.remove(handle)\n+\n+ def _send_permuter(self, id: str, perm: PermuterData) -> None:\n+ self._evaluator_port.send_json(\n+ {\"type\": \"add\", \"id\": id, **permuter_data_to_json(perm)}\n+ )\n+ self._evaluator_port.send(perm.source.encode(\"utf-8\"))\n+ self._evaluator_port.send(perm.target_o_bin)\n+\n+ def _do_read_eval_loop(self) -> None:\n+ while True:\n+ msg = self._evaluator_port.receive_json()\n+ msg_type = json_prop(msg, \"type\", str)\n+\n+ if msg_type == \"init\":\n+ perm_id = json_prop(msg, \"id\", str)\n+ time_us = json_prop(msg, \"time_us\", float)\n+ resp: Activity\n+ if json_prop(msg, \"success\", bool):\n+ resp = PermInitSuccess(\n+ perm_id=perm_id,\n+ base_score=json_prop(msg, \"base_score\", int),\n+ base_hash=json_prop(msg, \"base_hash\", str),\n+ time_us=time_us,\n+ )\n+ else:\n+ resp = PermInitFail(\n+ perm_id=perm_id,\n+ error=json_prop(msg, \"error\", str),\n+ )\n+ self._main_queue.put(resp)\n+\n+ elif msg_type == \"result\":\n+ compressed_source: Optional[bytes] = None\n+ if msg.get(\"has_source\") == True:\n+ compressed_source = self._evaluator_port.receive()\n+ perm_id = json_prop(msg, \"id\", str)\n+ time_us = json_prop(msg, \"time_us\", float)\n+ del msg[\"id\"]\n+ del msg[\"time_us\"]\n+ self._main_queue.put(\n+ WorkDone(\n+ perm_id=perm_id,\n+ obj=msg,\n+ time_us=time_us,\n+ compressed_source=compressed_source,\n+ )\n+ )\n+\n+ elif msg_type == \"need_work\":\n+ self._main_queue.put(NeedMoreWork())\n+\n+ else:\n+ raise Exception(f\"Unknown message type from evaluator: {msg_type}\")\n+\n+ def _read_eval_loop(self) -> None:\n+ try:\n+ self._do_read_eval_loop()\n+ except EOFError:\n+ # Silence errors from shutdown.\n+ pass\n+\n+ def _main_loop(self) -> None:\n+ while True:\n+ msg = self._main_queue.get()\n+ if isinstance(msg, Shutdown):\n+ break\n+\n+ self._handle_message(msg)\n+\n+ if not self._active and self._main_queue.empty():\n+ self._send_io_global(IoWillSleep())\n+\n+ def _heartbeat_loop(self) -> None:\n+ second_attempt = False\n+ while True:\n+ with self._last_heartbeat_lock:\n+ delay = (\n+ self._last_heartbeat\n+ + self._heartbeat_interval\n+ + _HEARTBEAT_INTERVAL_SLACK / 2\n+ - time.time()\n+ )\n+ if delay <= 0:\n+ if second_attempt:\n+ self._main_queue.put(NetThreadDisconnected(graceful=True))\n+ return\n+ # Handle clock skew or computer going to sleep by waiting a bit\n+ # longer before giving up.\n+ second_attempt = True\n+ if self._heartbeat_stop.wait(_HEARTBEAT_INTERVAL_SLACK / 2):\n+ return\n+ else:\n+ second_attempt = False\n+ if self._heartbeat_stop.wait(delay):\n+ return\n+\n+ def remove_permuter(self, handle: int) -> None:\n+ assert not self._token.cancelled\n+ self._main_queue.put(Disconnect(handle=handle))\n+\n+ def stop(self) -> None:\n+ assert not self._token.cancelled\n+ self._token.cancelled = True\n+ self._main_queue.put(Shutdown())\n+ self._heartbeat_stop.set()\n+ self._net_thread.stop()\n+ self._evaluator_port.shutdown()\n+ self._main_thread.join()\n+ self._heartbeat_thread.join()\n+\n+\n+class DockerPort(Port):\n+ \"\"\"Port for communicating with Docker. Communication is encrypted for a few\n+ not-very-good reasons:\n+ - it allows code reuse\n+ - it adds error-checking\n+ - it was fun to implement\"\"\"\n+\n+ _sock: BinaryIO\n+ _container: docker.models.containers.Container\n+ _stdout_buffer: bytes\n+ _closed: bool\n+\n+ def __init__(\n+ self, container: docker.models.containers.Container, secret: bytes\n+ ) -> None:\n+ self._container = container\n+ self._stdout_buffer = b\"\"\n+ self._closed = False\n+\n+ # Set up a socket for reading from stdout/stderr and writing to\n+ # stdin for the container. The docker package does not seem to\n+ # expose an API for writing the stdin, but we can do so directly\n+ # by attaching a socket and poking at internal state. (See\n+ # https://github.com/docker/docker-py/issues/983.) For stdout/\n+ # stderr, we use the format described at\n+ # https://docs.docker.com/engine/api/v1.24/#attach-to-a-container.\n+ #\n+ # Hopefully this will keep working for at least a while...\n+ try:\n+ self._sock = container.attach_socket(\n+ params={\"stdout\": True, \"stdin\": True, \"stderr\": True, \"stream\": True}\n+ )\n+ self._sock._writing = True # type: ignore\n+ except:\n+ try:\n+ container.remove(force=True)\n+ except Exception:\n+ pass\n+ raise\n+\n+ super().__init__(SecretBox(secret), \"docker\", is_client=True)\n+\n+ def shutdown(self) -> None:\n+ if self._closed:\n+ return\n+ self._closed = True\n+ try:\n+ self._sock.close()\n+ self._container.remove(force=True)\n+ except Exception as e:\n+ print(\"Failed to shut down Docker\")\n+ traceback.print_exc()\n+\n+ def _read_one(self) -> None:\n+ header = file_read_fixed(self._sock, 8)\n+ stream, length = struct.unpack(\">BxxxI\", header)\n+ if stream not in [1, 2]:\n+ raise Exception(\"Unexpected output from Docker: \" + repr(header))\n+ data = file_read_fixed(self._sock, length)\n+ if stream == 1:\n+ self._stdout_buffer += data\n+ else:\n+ sys.stderr.buffer.write(b\"Docker stderr: \" + data)\n+ sys.stderr.buffer.flush()\n+\n+ def _receive(self, length: int) -> bytes:\n+ while len(self._stdout_buffer) < length:\n+ self._read_one()\n+ ret = self._stdout_buffer[:length]\n+ self._stdout_buffer = self._stdout_buffer[length:]\n+ return ret\n+\n+ def _send(self, data: bytes) -> None:\n+ while data:\n+ written = self._sock.write(data)\n+ data = data[written:]\n+ self._sock.flush()\n+\n+\n+def _start_evaluator(docker_image: str, options: ServerOptions) -> DockerPort:\n+ \"\"\"Spawn a docker container and set it up to evaluate permutations in,\n+ returning a handle that we can use to communicate with it.\n+\n+ We do this for a few reasons:\n+ - enforcing a known Linux environment, all while the outside server can run\n+ on e.g. Windows and display a systray\n+ - enforcing resource limits\n+ - sandboxing\n+\n+ Docker does have the downside of requiring root access, so ideally we would\n+ also have a Docker-less mode, where we leave the sandboxing to some other\n+ tool, e.g. https://github.com/ioi/isolate/.\"\"\"\n+ print(\"Starting docker...\")\n+ command = [\"python3\", \"-m\", \"src.net.evaluator\"]\n+ secret = nacl.utils.random(32)\n+ box = SecretBox(secret)\n+ enc_secret = base64.b64encode(secret).decode(\"utf-8\")\n+ src_path = pathlib.Path(__file__).parent.parent.absolute()\n+\n+ try:\n+ client = docker.from_env()\n+ client.info()\n+ except Exception:\n+ print(\n+ \"Failed to start docker. Make sure you have docker installed, \"\n+ \"and either run the permuter with sudo or add yourself to the \"\n+ '\"docker\" UNIX group.'\n+ )\n+ sys.exit(1)\n+\n+ try:\n+ container = client.containers.run(\n+ docker_image,\n+ command,\n+ detach=True,\n+ remove=True,\n+ stdin_open=True,\n+ stdout=True,\n+ environment={\"SECRET\": enc_secret},\n+ volumes={src_path: {\"bind\": \"/src\", \"mode\": \"ro\"}},\n+ tmpfs={\"/tmp\": \"size=1G,exec\"},\n+ nano_cpus=int(options.num_cores * 1e9),\n+ mem_limit=int(options.max_memory_gb * 2 ** 30),\n+ read_only=True,\n+ network_disabled=True,\n+ )\n+ except Exception as e:\n+ print(f\"Failed to start docker container: {e}\")\n+ sys.exit(1)\n+\n+ port = DockerPort(container, secret)\n+\n+ try:\n+ # Sanity-check that the Docker container started successfully and can\n+ # be communicated with.\n+ magic = b\"\\0\" * 1000\n+ port.send(magic)\n+ r = port.receive()\n+ if r != magic:\n+ raise Exception(\"Failed initial sanity check.\")\n+\n+ port.send_json({\"num_cores\": options.num_cores})\n+ except:\n+ port.shutdown()\n+ raise\n+\n+ print(\"Started.\")\n+ return port\n+\n+\n+class Server:\n+ \"\"\"This class represents a server that may or may not be connected to the\n+ controller and the evaluator.\"\"\"\n+\n+ _server: Optional[ServerInner]\n+ _options: ServerOptions\n+ _io_queue: \"queue.Queue[IoActivity]\"\n+\n+ def __init__(\n+ self, options: ServerOptions, io_queue: \"queue.Queue[IoActivity]\"\n+ ) -> None:\n+ self._server = None\n+ self._options = options\n+ self._io_queue = io_queue\n+\n+ def start(self) -> None:\n+ assert self._server is None\n+\n+ net_port = connect()\n+ net_port.send_json(\n+ {\n+ \"method\": \"connect_server\",\n+ \"min_priority\": self._options.min_priority,\n+ \"num_cores\": self._options.num_cores,\n+ }\n+ )\n+ obj = net_port.receive_json()\n+ docker_image = json_prop(obj, \"docker_image\", str)\n+ heartbeat_interval = json_prop(obj, \"heartbeat_interval\", float)\n+\n+ evaluator_port = _start_evaluator(docker_image, self._options)\n+\n+ try:\n+ self._server = ServerInner(\n+ net_port, evaluator_port, self._io_queue, heartbeat_interval\n+ )\n+ except:\n+ evaluator_port.shutdown()\n+ raise\n+\n+ def stop(self) -> None:\n+ if self._server is None:\n+ return\n+ self._server.stop()\n+ self._server = None\n+\n+ def remove_permuter(self, handle: PermuterHandle) -> None:\n+ if self._server is not None and not handle[1].cancelled:\n+ self._server.remove_permuter(handle[0])\ndiff --git a/src/permuter.py b/src/permuter.py\n--- a/src/permuter.py\n+++ b/src/permuter.py\n@@ -33,10 +33,35 @@ class EvalError:\n EvalResult = Union[CandidateResult, EvalError]\n \n \n+@dataclass\n+class Finished:\n+ reason: Optional[str] = None\n+\n+\n+@dataclass\n+class Message:\n+ text: str\n+\n+\n+class NeedMoreWork:\n+ pass\n+\n+\n class _CompileFailure(Exception):\n pass\n \n \n+@dataclass\n+class WorkDone:\n+ perm_index: int\n+ result: EvalResult\n+\n+\n+Task = Union[Finished, Tuple[int, int]]\n+FeedbackItem = Union[Finished, Message, NeedMoreWork, WorkDone]\n+Feedback = Tuple[FeedbackItem, int, Optional[str]]\n+\n+\n class Permuter:\n \"\"\"\n Represents a single source from which permutation candidates can be generated,\n@@ -55,13 +80,17 @@ def __init__(\n force_seed: Optional[int],\n force_rng_seed: Optional[int],\n keep_prob: float,\n+ need_profiler: bool,\n need_all_sources: bool,\n show_errors: bool,\n+ best_only: bool,\n+ better_only: bool,\n ) -> None:\n self.dir = dir\n self.compiler = compiler\n self.scorer = scorer\n self.source_file = source_file\n+ self.source = source\n \n if fn_name is None:\n # Semi-legacy codepath; all functions imported through import.py have a\n@@ -88,8 +117,11 @@ def __init__(\n self._cur_seed: Optional[Tuple[int, int]] = None\n \n self.keep_prob = keep_prob\n+ self.need_profiler = need_profiler\n self._need_all_sources = need_all_sources\n self._show_errors = show_errors\n+ self._best_only = best_only\n+ self._better_only = better_only\n \n (\n self.base_score,\n@@ -110,16 +142,11 @@ def _create_and_score_base(self) -> Tuple[int, str, str]:\n if not o_file:\n raise CandidateConstructionFailure(f\"Unable to compile {self.source_file}\")\n base_result = base_cand.score(self.scorer, o_file)\n+ assert base_result.hash is not None\n return base_result.score, base_result.hash, base_cand.get_source()\n \n def _need_to_send_source(self, result: CandidateResult) -> bool:\n- if self._need_all_sources:\n- return True\n- if result.score < self.base_score:\n- return True\n- if result.score == self.base_score:\n- return result.hash != self.base_hash\n- return False\n+ return self._need_all_sources or self.should_output(result)\n \n def _eval_candidate(self, seed: int) -> CandidateResult:\n t0 = time.time()\n@@ -168,19 +195,45 @@ def _eval_candidate(self, seed: int) -> CandidateResult:\n \n t4 = time.time()\n \n- profiler: Profiler = result.profiler\n- profiler.add_stat(Profiler.StatType.perm, t1 - t0)\n- profiler.add_stat(Profiler.StatType.stringify, t2 - t1)\n- profiler.add_stat(Profiler.StatType.compile, t3 - t2)\n- profiler.add_stat(Profiler.StatType.score, t4 - t3)\n+ if self.need_profiler:\n+ profiler = Profiler()\n+ profiler.add_stat(Profiler.StatType.perm, t1 - t0)\n+ profiler.add_stat(Profiler.StatType.stringify, t2 - t1)\n+ profiler.add_stat(Profiler.StatType.compile, t3 - t2)\n+ profiler.add_stat(Profiler.StatType.score, t4 - t3)\n+ result.profiler = profiler\n \n self._last_score = result.score\n \n if not self._need_to_send_source(result):\n result.source = None\n+ result.hash = None\n \n return result\n \n+ def should_output(self, result: CandidateResult) -> bool:\n+ \"\"\"Check whether a result should be outputted. This must be more liberal\n+ in child processes than in parent ones, or else sources will be missing.\"\"\"\n+ return (\n+ result.score <= self.base_score\n+ and result.hash is not None\n+ and result.source is not None\n+ and not (result.score > self.best_score and self._best_only)\n+ and (\n+ result.score < self.base_score\n+ or (result.score == self.base_score and not self._better_only)\n+ )\n+ and result.hash not in self.hashes\n+ )\n+\n+ def record_result(self, result: CandidateResult) -> None:\n+ \"\"\"Record a new result, updating the best score and adding the hash to\n+ the set of hashes we have already seen. No hash is recorded for score\n+ 0, since we are interested in all score 0's, not just the first.\"\"\"\n+ self.best_score = min(self.best_score, result.score)\n+ if result.score != 0 and result.hash is not None:\n+ self.hashes.add(result.hash)\n+\n def seed_iterator(self) -> Iterator[int]:\n \"\"\"Create an iterator over all seeds for this permuter. The iterator\n will be infinite if we are randomizing.\"\"\"\ndiff --git a/src/printer.py b/src/printer.py\n--- a/src/printer.py\n+++ b/src/printer.py\n@@ -25,6 +25,7 @@ def print(\n self,\n message: str,\n permuter: Optional[Permuter],\n+ who: Optional[str],\n *,\n color: str = \"\",\n keep_progress: bool = False,\n@@ -37,6 +38,8 @@ def print(\n print(\"\\r\" + \" \" * pad + \"\\r\", end=\"\")\n if permuter is not None:\n message = f\"[{permuter.unique_name}] {message}\"\n+ if who is not None:\n+ message = f\"[{who}] {message}\"\n if color:\n message = f\"{color}{message}\\u001b[0m\"\n print(message)\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2021-04-12T21:43:23Z"} diff --git a/PythonDataset/test/faucet-task-instances.jsonl.all b/PythonDataset/test/faucet-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..580d72e203f363212384e9c89f14be71791611db --- /dev/null +++ b/PythonDataset/test/faucet-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "faucetsdn/faucet", "pull_number": 469, "instance_id": "faucetsdn__faucet-469", "issue_numbers": "", "base_commit": "0e0ebac27ba98d0eaa88b24e645216489161305a", "patch": "diff --git a/src/ryu_faucet/org/onfsdn/faucet/config_parser.py b/src/ryu_faucet/org/onfsdn/faucet/config_parser.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/config_parser.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/config_parser.py\n@@ -112,7 +112,7 @@ def _dp_parser_v2(logger, acls_conf, dps_conf, routers_conf, vlans_conf):\n except AssertionError as err:\n logger.exception('Error in config file: %s', err)\n return None\n- for port in ports.itervalues():\n+ for port in ports.values():\n dp.add_port(port)\n for acl_ident, acl in acls:\n dp.add_acl(acl_ident, acl)\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/faucet.py b/src/ryu_faucet/org/onfsdn/faucet/faucet.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/faucet.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/faucet.py\n@@ -22,7 +22,7 @@\n import random\n import signal\n \n-import ipaddr\n+import ipaddress\n \n from config_parser import dp_parser\n from config_parser_util import config_file_hash\n@@ -216,8 +216,8 @@ def _bgp_route_handler(self, path_change, vlan):\n path_change (ryu.services.protocols.bgp.bgpspeaker.EventPrefix): path change\n vlan (vlan): Valve VLAN this path change was received for.\n \"\"\"\n- prefix = ipaddr.IPNetwork(path_change.prefix)\n- nexthop = ipaddr.IPAddress(path_change.nexthop)\n+ prefix = ipaddress.ip_network(unicode(path_change.prefix))\n+ nexthop = ipaddress.ip_address(unicode(path_change.nexthop))\n withdraw = path_change.is_withdraw\n flowmods = []\n valve = self.valves[vlan.dp_id]\n@@ -235,8 +235,7 @@ def _bgp_route_handler(self, path_change, vlan):\n \n if withdraw:\n self.logger.info(\n- 'BGP withdraw %s nexthop %s',\n- prefix, nexthop)\n+ 'BGP withdraw %s nexthop %s', prefix, nexthop)\n flowmods = valve.del_route(vlan, prefix)\n else:\n self.logger.info(\n@@ -260,9 +259,8 @@ def _create_bgp_speaker_for_vlan(self, vlan):\n bgp_server_port=vlan.bgp_port,\n best_path_change_handler=handler)\n for faucet_vip in vlan.faucet_vips:\n- prefix = ipaddr.IPNetwork(faucet_vip.exploded)\n bgp_speaker.prefix_add(\n- prefix=str(prefix), next_hop=str(faucet_vip.ip))\n+ prefix=str(faucet_vip), next_hop=str(faucet_vip.ip))\n for route_table in (vlan.ipv4_routes, vlan.ipv6_routes):\n for ip_dst, ip_gw in route_table.items():\n bgp_speaker.prefix_add(\n@@ -284,9 +282,9 @@ def _reset_bgp(self):\n if dp_id not in self.dp_bgp_speakers:\n self.dp_bgp_speakers[dp_id] = {}\n bgp_speakers = self.dp_bgp_speakers[dp_id]\n- for bgp_speaker in bgp_speakers.itervalues():\n+ for bgp_speaker in bgp_speakers.values():\n bgp_speaker.shutdown()\n- for vlan in valve.dp.vlans.itervalues():\n+ for vlan in valve.dp.vlans.values():\n if vlan.bgp_as:\n bgp_speakers[vlan] = self._create_bgp_speaker_for_vlan(vlan)\n \ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/valve.py b/src/ryu_faucet/org/onfsdn/faucet/valve.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/valve.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/valve.py\n@@ -514,7 +514,7 @@ def _add_ports_and_vlans(self, discovered_port_nums):\n all_port_nums.add(port.number)\n \n # add vlan ports\n- for vlan in self.dp.vlans.itervalues():\n+ for vlan in self.dp.vlans.values():\n ofmsgs.extend(self._add_vlan(vlan, all_port_nums))\n \n # add any ports discovered but not configured\n@@ -955,7 +955,7 @@ def host_expire(self):\n if not self.dp.running:\n return\n now = time.time()\n- for vlan in self.dp.vlans.itervalues():\n+ for vlan in self.dp.vlans.values():\n self.host_manager.expire_hosts_from_vlan(vlan, now)\n \n def _get_config_changes(self, new_dp):\n@@ -1107,7 +1107,7 @@ def resolve_gateways(self):\n return []\n ofmsgs = []\n now = time.time()\n- for vlan in self.dp.vlans.itervalues():\n+ for vlan in self.dp.vlans.values():\n ofmsgs.extend(self.ipv4_route_manager.resolve_gateways(vlan, now))\n ofmsgs.extend(self.ipv6_route_manager.resolve_gateways(vlan, now))\n return ofmsgs\n@@ -1122,7 +1122,7 @@ def get_config_dict(self):\n self.dp.name: self.dp.to_conf()\n }\n vlans_dict = {}\n- for vlan in self.dp.vlans.itervalues():\n+ for vlan in self.dp.vlans.values():\n vlans_dict[vlan.name] = vlan.to_conf()\n acls_dict = {}\n for acl_id, acl in self.dp.acls.items():\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/valve_flood.py b/src/ryu_faucet/org/onfsdn/faucet/valve_flood.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/valve_flood.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/valve_flood.py\n@@ -45,7 +45,7 @@ def __init__(self, flood_table, flood_priority,\n self.stack = dp_stack\n self.use_group_table = use_group_table\n self.stack_ports = [\n- port for port in dp_ports.itervalues() if port.stack is not None]\n+ port for port in dp_ports.values() if port.stack is not None]\n self.towards_root_stack_ports = []\n self.away_from_root_stack_ports = []\n my_root_distance = dp_shortest_path_to_root()\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/valve_of.py b/src/ryu_faucet/org/onfsdn/faucet/valve_of.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/valve_of.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/valve_of.py\n@@ -17,6 +17,7 @@\n # limitations under the License.\n \n from collections import namedtuple\n+import ipaddress\n \n from ryu.lib import ofctl_v1_3 as ofctl\n from ryu.ofproto import ether\n@@ -244,6 +245,13 @@ def match_from_dict(match_dict):\n return acl_match\n \n \n+def _match_ip_masked(ip):\n+ if isinstance(ip, ipaddress.IPv4Network) or isinstance(ip, ipaddress.IPv6Network):\n+ return (str(ip.network_address), str(ip.netmask))\n+ else:\n+ return (str(ip.ip), str(ip.netmask))\n+\n+\n def build_match_dict(in_port=None, vlan=None,\n eth_type=None, eth_src=None,\n eth_dst=None, eth_dst_mask=None,\n@@ -270,13 +278,13 @@ def build_match_dict(in_port=None, vlan=None,\n if nw_proto is not None:\n match_dict['ip_proto'] = nw_proto\n if nw_src is not None:\n- match_dict['ipv4_src'] = (str(nw_src.ip), str(nw_src.netmask))\n+ match_dict['ipv4_src'] = _match_ip_masked(nw_src)\n if icmpv6_type is not None:\n match_dict['icmpv6_type'] = icmpv6_type\n if ipv6_nd_target is not None:\n match_dict['ipv6_nd_target'] = str(ipv6_nd_target.ip)\n if nw_dst is not None:\n- nw_dst_masked = (str(nw_dst.ip), str(nw_dst.netmask))\n+ nw_dst_masked = _match_ip_masked(nw_dst)\n if eth_type == ether.ETH_TYPE_ARP:\n match_dict['arp_tpa'] = nw_dst_masked\n elif eth_type == ether.ETH_TYPE_IP:\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/valve_packet.py b/src/ryu_faucet/org/onfsdn/faucet/valve_packet.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/valve_packet.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/valve_packet.py\n@@ -16,7 +16,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-import ipaddr\n+import ipaddress\n \n from ryu.lib import mac\n from ryu.lib.packet import arp, ethernet, icmp, icmpv6, ipv4, ipv6, packet, vlan\n@@ -78,8 +78,8 @@ def arp_request(eth_src, vid, src_ip, dst_ip):\n Args:\n eth_src (str): Ethernet source address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv4Address): source IPv4 address.\n- dst_ip (ipaddr.IPv4Address): requested IPv4 address.\n+ src_ip (ipaddress.IPv4Address): source IPv4 address.\n+ dst_ip (ipaddress.IPv4Address): requested IPv4 address.\n Returns:\n ryu.lib.packet.arp: serialized ARP request packet.\n \"\"\"\n@@ -99,8 +99,8 @@ def arp_reply(eth_src, eth_dst, vid, src_ip, dst_ip):\n eth_src (str): Ethernet source address.\n eth_dst (str): destination Ethernet MAC address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv4Address): source IPv4 address.\n- dst_ip (ipaddr.IPv4Address): destination IPv4 address.\n+ src_ip (ipaddress.IPv4Address): source IPv4 address.\n+ dst_ip (ipaddress.IPv4Address): destination IPv4 address.\n Returns:\n ryu.lib.packet.arp: serialized ARP reply packet.\n \"\"\"\n@@ -120,8 +120,8 @@ def echo_reply(eth_src, eth_dst, vid, src_ip, dst_ip, data):\n eth_src (str): Ethernet source address.\n eth_dst (str): destination Ethernet MAC address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv4Address): source IPv4 address.\n- dst_ip (ipaddr.IPv4Address): destination IPv4 address.\n+ src_ip (ipaddress.IPv4Address): source IPv4 address.\n+ dst_ip (ipaddress.IPv4Address): destination IPv4 address.\n Returns:\n ryu.lib.packet.icmp: serialized ICMP echo reply packet.\n \"\"\"\n@@ -143,11 +143,11 @@ def ipv6_link_eth_mcast(dst_ip):\n See RFC 2464 section 7.\n \n Args:\n- dst_ip (ipaddr.IPv6Address): IPv6 address.\n+ dst_ip (ipaddress.IPv6Address): IPv6 address.\n Returns:\n str: Ethernet multicast address.\n \"\"\"\n- mcast_mac_bytes = ipaddr.Bytes('\\x33\\x33') + dst_ip.packed[-4:]\n+ mcast_mac_bytes = b'\\x33\\x33' + dst_ip.packed[-4:]\n mcast_mac = ':'.join(['%02X' % ord(x) for x in mcast_mac_bytes])\n return mcast_mac\n \n@@ -158,14 +158,13 @@ def ipv6_solicited_node_from_ucast(ucast):\n See RFC 3513 section 2.7.1.\n \n Args:\n- ucast (ipaddr.IPv6Address): IPv6 unicast address.\n+ ucast (ipaddress.IPv6Address): IPv6 unicast address.\n Returns:\n- ipaddr.IPv6Address: IPv6 solicited node multicast address.\n+ ipaddress.IPv6Address: IPv6 solicited node multicast address.\n \"\"\"\n- link_mcast_prefix = ipaddr.IPv6Network('ff02::1:ff00:0/104')\n- mcast_bytes = ipaddr.Bytes(\n- link_mcast_prefix.packed[:13] + ucast.packed[-3:])\n- link_mcast = ipaddr.IPv6Address(mcast_bytes)\n+ link_mcast_prefix = ipaddress.ip_interface(u'ff02::1:ff00:0/104')\n+ mcast_bytes = link_mcast_prefix.packed[:13] + ucast.packed[-3:]\n+ link_mcast = ipaddress.IPv6Address(mcast_bytes)\n return link_mcast\n \n \n@@ -175,8 +174,8 @@ def nd_request(eth_src, vid, src_ip, dst_ip):\n Args:\n eth_src (str): source Ethernet MAC address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv6Address): source IPv6 address.\n- dst_ip (ipaddr.IPv6Address): requested IPv6 address.\n+ src_ip (ipaddress.IPv6Address): source IPv6 address.\n+ dst_ip (ipaddress.IPv6Address): requested IPv6 address.\n Returns:\n ryu.lib.packet.ethernet: Serialized IPv6 neighbor discovery packet.\n \"\"\"\n@@ -203,8 +202,8 @@ def nd_reply(eth_src, eth_dst, vid, src_ip, dst_ip, hop_limit):\n eth_src (str): source Ethernet MAC address.\n eth_dst (str): destination Ethernet MAC address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv6Address): source IPv6 address.\n- dst_ip (ipaddr.IPv6Address): destination IPv6 address.\n+ src_ip (ipaddress.IPv6Address): source IPv6 address.\n+ dst_ip (ipaddress.IPv6Address): destination IPv6 address.\n hop_limit (int): IPv6 hop limit.\n Returns:\n ryu.lib.packet.ethernet: Serialized IPv6 neighbor discovery packet.\n@@ -235,8 +234,8 @@ def icmpv6_echo_reply(eth_src, eth_dst, vid, src_ip, dst_ip, hop_limit,\n eth_src (str): source Ethernet MAC address.\n eth_dst (str): destination Ethernet MAC address.\n vid (int or None): VLAN VID to use (or None).\n- src_ip (ipaddr.IPv6Address): source IPv6 address.\n- dst_ip (ipaddr.IPv6Address): destination IPv6 address.\n+ src_ip (ipaddress.IPv6Address): source IPv6 address.\n+ dst_ip (ipaddress.IPv6Address): destination IPv6 address.\n hop_limit (int): IPv6 hop limit.\n id_ (int): identifier for echo reply.\n seq (int): sequence number for echo reply.\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/valve_route.py b/src/ryu_faucet/org/onfsdn/faucet/valve_route.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/valve_route.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/valve_route.py\n@@ -18,7 +18,7 @@\n \n import time\n \n-import ipaddr\n+import ipaddress\n \n from ryu.lib.packet import arp, icmp, icmpv6, ipv4, ipv6\n from ryu.ofproto import ether\n@@ -131,7 +131,7 @@ def _add_resolved_route(self, vlan, ip_gw, ip_dst, eth_dst, is_updated):\n in_match = self.valve_in_match(\n self.fib_table, vlan=vlan,\n eth_type=self._eth_type(), nw_dst=ip_dst)\n- prefixlen = ipaddr.IPNetwork(ip_dst).prefixlen\n+ prefixlen = ipaddress.ip_network(ip_dst).prefixlen\n priority = self.route_priority + prefixlen\n if is_updated:\n self.logger.info(\n@@ -227,7 +227,7 @@ def _vlan_ip_gws(self, vlan):\n ip_gws = []\n for ip_gw in set(routes.values()):\n for faucet_vip in vlan.faucet_vips:\n- if ip_gw in faucet_vip:\n+ if ip_gw in faucet_vip.network:\n ip_gws.append((ip_gw, faucet_vip))\n return ip_gws\n \n@@ -282,7 +282,7 @@ def _is_host_fib_route(self, vlan, host_ip):\n \n Args:\n vlan (vlan): VLAN containing this RIB/FIB.\n- ip_gw (ipaddr.IPAddress): potential host FIB route.\n+ ip_gw (ipaddress.ip_address): potential host FIB route.\n Returns:\n True if a host FIB route (and not used as a gateway).\n \"\"\"\n@@ -348,13 +348,18 @@ def _cached_nexthop_eth_dst(self, vlan, ip_gw):\n return nexthop_cache_entry.eth_src\n return None\n \n+ def _host_from_faucet_vip(self, faucet_vip):\n+ max_prefixlen = faucet_vip.ip.max_prefixlen\n+ return ipaddress.ip_interface(\n+ u'/'.join((faucet_vip.ip.exploded, str(max_prefixlen))))\n+\n def add_route(self, vlan, ip_gw, ip_dst):\n \"\"\"Add a route to the RIB.\n \n Args:\n vlan (vlan): VLAN containing this RIB.\n- ip_gw (ipaddr.IPAddress): IP address of nexthop.\n- ip_dst (ipaddr.IPNetwork): destination IP network.\n+ ip_gw (ipaddress.ip_address): IP address of nexthop.\n+ ip_dst (ipaddress.ip_network): destination IP network.\n Returns:\n list: OpenFlow messages.\n \"\"\"\n@@ -376,11 +381,11 @@ def _add_host_fib_route(self, vlan, host_ip):\n \n Args:\n vlan (vlan): VLAN containing this RIB.\n- host_ip (ipaddr.IPAddress): IP address of host.\n+ host_ip (ipaddress.ip_address): IP address of host.\n Returns:\n list: OpenFlow messages.\n \"\"\"\n- host_route = ipaddr.IPNetwork(host_ip.exploded)\n+ host_route = ipaddress.ip_network(host_ip.exploded)\n return self.add_route(vlan, host_ip, host_route)\n \n def _del_host_fib_route(self, vlan, host_ip):\n@@ -388,11 +393,11 @@ def _del_host_fib_route(self, vlan, host_ip):\n \n Args:\n vlan (vlan): VLAN containing this RIB.\n- host_ip (ipaddr.IPAddress): IP address of host.\n+ host_ip (ipaddress.ip_address): IP address of host.\n Returns:\n list: OpenFlow messages.\n \"\"\"\n- host_route = ipaddr.IPNetwork(host_ip.exploded)\n+ host_route = ipaddress.ip_network(host_ip.exploded)\n return self.del_route(vlan, host_route)\n \n def _ip_pkt(self, pkt):\n@@ -426,7 +431,7 @@ def add_host_fib_route_from_pkt(self, pkt_meta):\n ip_pkt = self._ip_pkt(pkt_meta.pkt)\n ofmsgs = []\n if ip_pkt:\n- src_ip = ipaddr.IPAddress(ip_pkt.src)\n+ src_ip = ipaddress.ip_address(unicode(ip_pkt.src))\n if src_ip and pkt_meta.vlan.ip_in_vip_subnet(src_ip):\n now = time.time()\n nexthop_fresh = self._nexthop_fresh(pkt_meta.vlan, src_ip, now)\n@@ -444,7 +449,7 @@ def del_route(self, vlan, ip_dst):\n \n Args:\n vlan (vlan): VLAN containing this RIB.\n- ip_dst (ipaddr.IPNetwork): destination IP network.\n+ ip_dst (ipaddress.ip_network): destination IP network.\n Returns:\n list: OpenFlow messages.\n \"\"\"\n@@ -485,9 +490,8 @@ def _ip_pkt(self, pkt):\n \n def add_faucet_vip(self, vlan, faucet_vip):\n ofmsgs = []\n- faucet_vip_net = ipaddr.IPNetwork(faucet_vip.exploded)\n- faucet_vip_host = ipaddr.IPNetwork(faucet_vip.ip)\n- max_prefixlen = faucet_vip_host.prefixlen\n+ max_prefixlen = faucet_vip.ip.max_prefixlen\n+ faucet_vip_host = self._host_from_faucet_vip(faucet_vip)\n priority = self.route_priority + max_prefixlen\n ofmsgs.append(self.valve_flowmod(\n self.eth_src_table,\n@@ -516,14 +520,14 @@ def add_faucet_vip(self, vlan, faucet_vip):\n vlan=vlan,\n eth_type=self._eth_type(),\n nw_proto=inet.IPPROTO_ICMP,\n- nw_src=faucet_vip_net,\n+ nw_src=faucet_vip,\n nw_dst=faucet_vip_host),\n priority=priority))\n return ofmsgs\n \n def _control_plane_arp_handler(self, pkt_meta, arp_pkt):\n- src_ip = ipaddr.IPv4Address(arp_pkt.src_ip)\n- dst_ip = ipaddr.IPv4Address(arp_pkt.dst_ip)\n+ src_ip = ipaddress.IPv4Address(unicode(arp_pkt.src_ip))\n+ dst_ip = ipaddress.IPv4Address(unicode(arp_pkt.dst_ip))\n vlan = pkt_meta.vlan\n opcode = arp_pkt.opcode\n ofmsgs = []\n@@ -550,8 +554,8 @@ def _control_plane_arp_handler(self, pkt_meta, arp_pkt):\n return ofmsgs\n \n def _control_plane_icmp_handler(self, pkt_meta, ipv4_pkt, icmp_pkt):\n- src_ip = ipaddr.IPv4Address(ipv4_pkt.src)\n- dst_ip = ipaddr.IPv4Address(ipv4_pkt.dst)\n+ src_ip = ipaddress.IPv4Address(unicode(ipv4_pkt.src))\n+ dst_ip = ipaddress.IPv4Address(unicode(ipv4_pkt.dst))\n vlan = pkt_meta.vlan\n icmpv4_type = icmp_pkt.type\n ofmsgs = []\n@@ -601,8 +605,8 @@ def _ip_pkt(self, pkt):\n \n def add_faucet_vip(self, vlan, faucet_vip):\n ofmsgs = []\n- faucet_vip_host = ipaddr.IPNetwork(faucet_vip.ip)\n- max_prefixlen = faucet_vip_host.prefixlen\n+ max_prefixlen = faucet_vip.ip.max_prefixlen\n+ faucet_vip_host = self._host_from_faucet_vip(faucet_vip)\n priority = self.route_priority + max_prefixlen\n ofmsgs.append(self.valve_flowmod(\n self.eth_src_table,\n@@ -652,8 +656,8 @@ def add_faucet_vip(self, vlan, faucet_vip):\n \n def _control_plane_icmpv6_handler(self, pkt_meta, ipv6_pkt, icmpv6_pkt):\n vlan = pkt_meta.vlan\n- src_ip = ipaddr.IPv6Address(ipv6_pkt.src)\n- dst_ip = ipaddr.IPv6Address(ipv6_pkt.dst)\n+ src_ip = ipaddress.IPv6Address(unicode(ipv6_pkt.src))\n+ dst_ip = ipaddress.IPv6Address(unicode(ipv6_pkt.dst))\n icmpv6_type = icmpv6_pkt.type_\n ofmsgs = []\n if vlan.ip_in_vip_subnet(src_ip):\n@@ -661,8 +665,8 @@ def _control_plane_icmpv6_handler(self, pkt_meta, ipv6_pkt, icmpv6_pkt):\n vid = self._vlan_vid(vlan, in_port)\n eth_src = pkt_meta.eth_src\n if icmpv6_type == icmpv6.ND_NEIGHBOR_SOLICIT:\n- solicited_ip = icmpv6_pkt.data.dst\n- if vlan.is_faucet_vip(ipaddr.IPAddress(solicited_ip)):\n+ solicited_ip = unicode(icmpv6_pkt.data.dst)\n+ if vlan.is_faucet_vip(ipaddress.ip_address(solicited_ip)):\n ofmsgs.extend(\n self._add_host_fib_route(vlan, src_ip))\n nd_reply = valve_packet.nd_reply(\ndiff --git a/src/ryu_faucet/org/onfsdn/faucet/vlan.py b/src/ryu_faucet/org/onfsdn/faucet/vlan.py\n--- a/src/ryu_faucet/org/onfsdn/faucet/vlan.py\n+++ b/src/ryu_faucet/org/onfsdn/faucet/vlan.py\n@@ -13,7 +13,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-import ipaddr\n+import ipaddress\n \n from conf import Conf\n \n@@ -80,20 +80,20 @@ def __init__(self, _id, dp_id, conf=None):\n \n if self.faucet_vips:\n self.faucet_vips = [\n- ipaddr.IPNetwork(ip) for ip in self.faucet_vips]\n+ ipaddress.ip_interface(unicode(ip)) for ip in self.faucet_vips]\n \n if self.bgp_as:\n assert self.bgp_port\n- assert ipaddr.IPv4Address(self.bgp_routerid)\n+ assert ipaddress.IPv4Address(unicode(self.bgp_routerid))\n for neighbor_ip in self.bgp_neighbor_addresses:\n- assert ipaddr.IPAddress(neighbor_ip)\n+ assert ipaddress.ip_address(unicode(neighbor_ip))\n assert self.bgp_neighbor_as\n \n if self.routes:\n self.routes = [route['route'] for route in self.routes]\n for route in self.routes:\n- ip_gw = ipaddr.IPAddress(route['ip_gw'])\n- ip_dst = ipaddr.IPNetwork(route['ip_dst'])\n+ ip_gw = ipaddress.ip_address(unicode(route['ip_gw']))\n+ ip_dst = ipaddress.ip_network(unicode(route['ip_dst']))\n assert ip_gw.version == ip_dst.version\n if ip_gw.version == 4:\n self.ipv4_routes[ip_dst] = ip_gw\n@@ -201,7 +201,7 @@ def is_faucet_vip(self, ip):\n \n def ip_in_vip_subnet(self, ip):\n for faucet_vip in self.faucet_vips:\n- if ip in faucet_vip:\n+ if ip in faucet_vip.network:\n return True\n return False\n \n@@ -215,8 +215,8 @@ def from_connected_to_vip(self, src_ip, dst_ip):\n \"\"\"Return True if src_ip in connected network and dst_ip is a VIP.\n \n Args:\n- src_ip (ipaddr.IPAddress): source IP.\n- dst_ip (ipaddr.IPAddress): destination IP\n+ src_ip (ipaddress.ip_address): source IP.\n+ dst_ip (ipaddress.ip_address): destination IP\n Returns:\n True if local traffic for a VIP.\n \"\"\"\n", "test_patch": "diff --git a/tests/faucet_mininet_test.py b/tests/faucet_mininet_test.py\n--- a/tests/faucet_mininet_test.py\n+++ b/tests/faucet_mininet_test.py\n@@ -43,7 +43,7 @@\n from SimpleHTTPServer import SimpleHTTPRequestHandler\n from BaseHTTPServer import HTTPServer\n \n-import ipaddr\n+import ipaddress\n import yaml\n \n from concurrencytest import ConcurrentTestSuite, fork_for_tests\n@@ -881,13 +881,13 @@ def test_untagged(self):\n first_host, second_host = self.net.hosts[:2]\n # wait until 10.0.0.1 has been resolved\n self.wait_for_route_as_flow(\n- first_host.MAC(), ipaddr.IPv4Network('10.99.99.0/24'))\n+ first_host.MAC(), ipaddress.IPv4Network(u'10.99.99.0/24'))\n self.wait_bgp_up(self.exabgp_log)\n self.wait_exabgp_sent_updates(self.exabgp_log)\n self.verify_invalid_bgp_route('10.0.0.4/24 cannot be us')\n self.verify_invalid_bgp_route('10.0.0.5/24 is not a connected network')\n self.wait_for_route_as_flow(\n- second_host.MAC(), ipaddr.IPv4Network('10.0.3.0/24'))\n+ second_host.MAC(), ipaddress.IPv4Network(u'10.0.3.0/24'))\n self.verify_ipv4_routing_mesh()\n self.flap_all_switch_ports()\n self.verify_ipv4_routing_mesh()\n@@ -1600,8 +1600,8 @@ class FaucetTaggedIPv4RouteTest(FaucetTaggedTest):\n def test_tagged(self):\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_routed_ip = ipaddr.IPv4Network('10.0.1.1/24')\n- second_host_routed_ip = ipaddr.IPv4Network('10.0.2.1/24')\n+ first_host_routed_ip = ipaddress.ip_interface(u'10.0.1.1/24')\n+ second_host_routed_ip = ipaddress.ip_interface(u'10.0.2.1/24')\n for _ in range(3):\n self.verify_ipv4_routing(\n first_host, first_host_routed_ip,\n@@ -1643,15 +1643,15 @@ class FaucetUntaggedIPv4InterVLANRouteTest(FaucetUntaggedTest):\n \"\"\"\n \n def test_untagged(self):\n- first_host_ip = ipaddr.IPv4Network('10.100.0.1/24')\n- first_faucet_vip = ipaddr.IPv4Network('10.100.0.254/24')\n- second_host_ip = ipaddr.IPv4Network('10.200.0.1/24')\n- second_faucet_vip = ipaddr.IPv4Network('10.200.0.254/24')\n+ first_host_ip = ipaddress.ip_interface(u'10.100.0.1/24')\n+ first_faucet_vip = ipaddress.ip_interface(u'10.100.0.254/24')\n+ second_host_ip = ipaddress.ip_interface(u'10.200.0.1/24')\n+ second_faucet_vip = ipaddress.ip_interface(u'10.200.0.254/24')\n first_host, second_host = self.net.hosts[:2]\n first_host.setIP(str(first_host_ip.ip))\n second_host.setIP(str(second_host_ip.ip))\n- self.add_host_ipv4_route(first_host, second_host_ip, first_faucet_vip.ip)\n- self.add_host_ipv4_route(second_host, first_host_ip, second_faucet_vip.ip)\n+ self.add_host_route(first_host, second_host_ip, first_faucet_vip.ip)\n+ self.add_host_route(second_host, first_host_ip, second_faucet_vip.ip)\n self.one_ipv4_ping(first_host, first_faucet_vip.ip)\n self.one_ipv4_ping(second_host, second_faucet_vip.ip)\n self.one_ipv4_ping(first_host, second_host_ip.ip)\n@@ -1688,15 +1688,15 @@ class FaucetUntaggedMixedIPv4RouteTest(FaucetUntaggedTest):\n def test_untagged(self):\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_net = ipaddr.IPv4Network('10.0.0.1/24')\n- second_host_net = ipaddr.IPv4Network('172.16.0.1/24')\n+ first_host_net = ipaddress.ip_interface(u'10.0.0.1/24')\n+ second_host_net = ipaddress.ip_interface(u'172.16.0.1/24')\n second_host.setIP(str(second_host_net.ip))\n self.one_ipv4_ping(first_host, self.FAUCET_VIPV4.ip)\n self.one_ipv4_ping(second_host, self.FAUCET_VIPV4_2.ip)\n- self.add_host_ipv4_route(\n- first_host, second_host_net.masked(), self.FAUCET_VIPV4.ip)\n- self.add_host_ipv4_route(\n- second_host, first_host_net.masked(), self.FAUCET_VIPV4_2.ip)\n+ self.add_host_route(\n+ first_host, second_host_net, self.FAUCET_VIPV4.ip)\n+ self.add_host_route(\n+ second_host, first_host_net, self.FAUCET_VIPV4_2.ip)\n self.one_ipv4_ping(first_host, second_host_net.ip)\n self.one_ipv4_ping(second_host, first_host_net.ip)\n \n@@ -1731,16 +1731,16 @@ class FaucetUntaggedMixedIPv6RouteTest(FaucetUntaggedTest):\n def test_untagged(self):\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_net = ipaddr.IPv6Network('fc00::1:1/64')\n- second_host_net = ipaddr.IPv6Network('fc01::1:1/64')\n+ first_host_net = ipaddress.ip_interface(u'fc00::1:1/64')\n+ second_host_net = ipaddress.ip_interface(u'fc01::1:1/64')\n self.add_host_ipv6_address(first_host, first_host_net)\n self.one_ipv6_ping(first_host, self.FAUCET_VIPV6.ip)\n self.add_host_ipv6_address(second_host, second_host_net)\n self.one_ipv6_ping(second_host, self.FAUCET_VIPV6_2.ip)\n- self.add_host_ipv6_route(\n- first_host, second_host_net.masked(), self.FAUCET_VIPV6.ip)\n- self.add_host_ipv6_route(\n- second_host, first_host_net.masked(), self.FAUCET_VIPV6_2.ip)\n+ self.add_host_route(\n+ first_host, second_host_net, self.FAUCET_VIPV6.ip)\n+ self.add_host_route(\n+ second_host, first_host_net, self.FAUCET_VIPV6_2.ip)\n self.one_ipv6_ping(first_host, second_host_net.ip)\n self.one_ipv6_ping(second_host, first_host_net.ip)\n \n@@ -1847,20 +1847,20 @@ class FaucetUntaggedSameVlanIPv6RouteTest(FaucetUntaggedTest):\n \n def test_untagged(self):\n first_host, second_host = self.net.hosts[:2]\n- first_host_ip = ipaddr.IPv6Network('fc00::10:2/112')\n- first_host_ctrl_ip = ipaddr.IPv6Address('fc00::10:1')\n- second_host_ip = ipaddr.IPv6Network('fc00::20:2/112')\n- second_host_ctrl_ip = ipaddr.IPv6Address('fc00::20:1')\n+ first_host_ip = ipaddress.ip_interface(u'fc00::10:2/112')\n+ first_host_ctrl_ip = ipaddress.ip_address(u'fc00::10:1')\n+ second_host_ip = ipaddress.ip_interface(u'fc00::20:2/112')\n+ second_host_ctrl_ip = ipaddress.ip_address(u'fc00::20:1')\n self.add_host_ipv6_address(first_host, first_host_ip)\n self.add_host_ipv6_address(second_host, second_host_ip)\n- self.add_host_ipv6_route(\n+ self.add_host_route(\n first_host, second_host_ip, first_host_ctrl_ip)\n- self.add_host_ipv6_route(\n+ self.add_host_route(\n second_host, first_host_ip, second_host_ctrl_ip)\n self.wait_for_route_as_flow(\n- first_host.MAC(), first_host_ip)\n+ first_host.MAC(), first_host_ip.network)\n self.wait_for_route_as_flow(\n- second_host.MAC(), second_host_ip)\n+ second_host.MAC(), second_host_ip.network)\n self.one_ipv6_ping(first_host, second_host_ip.ip)\n self.one_ipv6_ping(first_host, second_host_ctrl_ip)\n self.one_ipv6_ping(second_host, first_host_ip.ip)\n@@ -1936,7 +1936,7 @@ def test_untagged(self):\n second_host = self.net.hosts[1]\n self.flap_all_switch_ports()\n self.wait_for_route_as_flow(\n- second_host.MAC(), ipaddr.IPv6Network('fc00::30:0/112'))\n+ second_host.MAC(), ipaddress.IPv6Network(u'fc00::30:0/112'))\n self.verify_ipv6_routing_mesh()\n self.wait_bgp_up(self.exabgp_log)\n updates = self.exabgp_updates(self.exabgp_log)\n@@ -1986,10 +1986,10 @@ def test_tagged(self):\n \"\"\"Test IPv6 routing works.\"\"\"\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_ip = ipaddr.IPv6Network('fc00::1:1/112')\n- second_host_ip = ipaddr.IPv6Network('fc00::1:2/112')\n- first_host_routed_ip = ipaddr.IPv6Network('fc00::10:1/112')\n- second_host_routed_ip = ipaddr.IPv6Network('fc00::20:1/112')\n+ first_host_ip = ipaddress.ip_interface(u'fc00::1:1/112')\n+ second_host_ip = ipaddress.ip_interface(u'fc00::1:2/112')\n+ first_host_routed_ip = ipaddress.ip_interface(u'fc00::10:1/112')\n+ second_host_routed_ip = ipaddress.ip_interface(u'fc00::20:1/112')\n for _ in range(5):\n self.verify_ipv6_routing_pair(\n first_host, first_host_ip, first_host_routed_ip,\n@@ -2484,8 +2484,8 @@ class FaucetSingleGroupTableUntaggedIPv4RouteTest(FaucetUntaggedTest):\n def test_untagged(self):\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_routed_ip = ipaddr.IPv4Network('10.0.1.1/24')\n- second_host_routed_ip = ipaddr.IPv4Network('10.0.2.1/24')\n+ first_host_routed_ip = ipaddress.ip_interface(u'10.0.1.1/24')\n+ second_host_routed_ip = ipaddress.ip_interface(u'10.0.2.1/24')\n self.verify_ipv4_routing(\n first_host, first_host_routed_ip,\n second_host, second_host_routed_ip,\n@@ -2538,10 +2538,10 @@ class FaucetSingleGroupUntaggedIPv6RouteTest(FaucetUntaggedTest):\n def test_untagged(self):\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_ip = ipaddr.IPv6Network('fc00::1:1/112')\n- second_host_ip = ipaddr.IPv6Network('fc00::1:2/112')\n- first_host_routed_ip = ipaddr.IPv6Network('fc00::10:1/112')\n- second_host_routed_ip = ipaddr.IPv6Network('fc00::20:1/112')\n+ first_host_ip = ipaddress.ip_interface(u'fc00::1:1/112')\n+ second_host_ip = ipaddress.ip_interface(u'fc00::1:2/112')\n+ first_host_routed_ip = ipaddress.ip_interface(u'fc00::10:1/112')\n+ second_host_routed_ip = ipaddress.ip_interface(u'fc00::20:1/112')\n self.verify_ipv6_routing_pair(\n first_host, first_host_ip, first_host_routed_ip,\n second_host, second_host_ip, second_host_routed_ip,\ndiff --git a/tests/faucet_mininet_test_base.py b/tests/faucet_mininet_test_base.py\n--- a/tests/faucet_mininet_test_base.py\n+++ b/tests/faucet_mininet_test_base.py\n@@ -11,7 +11,7 @@\n import unittest\n import yaml\n \n-import ipaddr\n+import ipaddress\n import requests\n \n from mininet.node import Controller\n@@ -207,10 +207,10 @@ class FaucetTestBase(unittest.TestCase):\n \"\"\"Base class for all FAUCET unit tests.\"\"\"\n \n ONE_GOOD_PING = '1 packets transmitted, 1 received, 0% packet loss'\n- FAUCET_VIPV4 = ipaddr.IPv4Network('10.0.0.254/24')\n- FAUCET_VIPV4_2 = ipaddr.IPv4Network('172.16.0.254/24')\n- FAUCET_VIPV6 = ipaddr.IPv6Network('fc00::1:254/64')\n- FAUCET_VIPV6_2 = ipaddr.IPv6Network('fc01::1:254/64')\n+ FAUCET_VIPV4 = ipaddress.ip_interface(u'10.0.0.254/24')\n+ FAUCET_VIPV4_2 = ipaddress.ip_interface(u'172.16.0.254/24')\n+ FAUCET_VIPV6 = ipaddress.ip_interface(u'fc00::1:254/64')\n+ FAUCET_VIPV6_2 = ipaddress.ip_interface(u'fc01::1:254/64')\n OFCTL = 'ovs-ofctl -OOpenFlow13'\n BOGUS_MAC = '01:02:03:04:05:06'\n FAUCET_MAC = '0e:00:00:00:00:01'\n@@ -445,7 +445,7 @@ def require_host_learned(self, host, retries=3):\n ping_cmd = 'ping'\n if not host_ip_net:\n host_ip_net = self.host_ipv6(host)\n- broadcast = (ipaddr.IPNetwork(host_ip_net).broadcast)\n+ broadcast = (ipaddress.ip_interface(unicode(host_ip_net)).network.broadcast_address)\n if broadcast.version == 6:\n ping_cmd = 'ping6'\n for _ in range(retries):\n@@ -521,19 +521,14 @@ def add_host_ipv6_address(self, host, ip_v6):\n '',\n host.cmd('ip -6 addr add %s dev %s' % (ip_v6, host.intf())))\n \n- def add_host_ipv6_route(self, host, ip_dst, ip_gw):\n- \"\"\"Add an IPv6 route to a Mininet host.\"\"\"\n- host.cmd('ip -6 route del %s' % ip_dst.masked())\n+ def add_host_route(self, host, ip_dst, ip_gw):\n+ \"\"\"Add an IP route to a Mininet host.\"\"\"\n+ host.cmd('ip -%u route del %s' % (\n+ ip_dst.version, ip_dst.network.with_prefixlen))\n self.assertEquals(\n '',\n- host.cmd('ip -6 route add %s via %s' % (ip_dst.masked(), ip_gw)))\n-\n- def add_host_ipv4_route(self, host, ip_dst, ip_gw):\n- \"\"\"Add an IPv4 route to a Mininet host.\"\"\"\n- host.cmd('ip -4 route del %s' % ip_dst.masked())\n- self.assertEquals(\n- '',\n- host.cmd('ip -4 route add %s via %s' % (ip_dst.masked(), ip_gw)))\n+ host.cmd('ip -%u route add %s via %s' % (\n+ ip_dst.version, ip_dst.network.with_prefixlen, ip_gw)))\n \n def one_ipv4_ping(self, host, dst, retries=3, require_host_learned=True):\n \"\"\"Ping an IPv4 destination from a host.\"\"\"\n@@ -679,12 +674,11 @@ def ping_all_when_learned(self, retries=3):\n def wait_for_route_as_flow(self, nexthop, prefix, timeout=10,\n with_group_table=False):\n \"\"\"Verify a route has been added as a flow.\"\"\"\n+ exp_prefix = '%s/%s' % (\n+ prefix.network_address, prefix.netmask)\n if prefix.version == 6:\n- exp_prefix = '/'.join(\n- (str(prefix.masked().ip), str(prefix.netmask)))\n nw_dst_match = '\"ipv6_dst\": \"%s\"' % exp_prefix\n else:\n- exp_prefix = prefix.masked().with_netmask\n nw_dst_match = '\"nw_dst\": \"%s\"' % exp_prefix\n if with_group_table:\n group_id = self.get_group_id_for_matching_flow(nw_dst_match)\n@@ -697,17 +691,17 @@ def wait_for_route_as_flow(self, nexthop, prefix, timeout=10,\n \n def host_ipv4_alias(self, host, alias_ip):\n \"\"\"Add an IPv4 alias address to a host.\"\"\"\n- del_cmd = 'ip addr del %s/%s dev %s' % (\n- alias_ip.ip, alias_ip.prefixlen, host.intf())\n- add_cmd = 'ip addr add %s/%s dev %s label %s:1' % (\n- alias_ip.ip, alias_ip.prefixlen, host.intf(), host.intf())\n+ del_cmd = 'ip addr del %s dev %s' % (\n+ alias_ip.with_prefixlen, host.intf())\n+ add_cmd = 'ip addr add %s dev %s label %s:1' % (\n+ alias_ip.with_prefixlen, host.intf(), host.intf())\n host.cmd(del_cmd)\n self.assertEquals('', host.cmd(add_cmd))\n \n- def verify_ipv4_host_learned_mac(self, host, ip, mac, retries=3):\n+ def _verify_host_learned_mac(self, host, ip, ip_ver, mac, retries):\n for _ in range(retries):\n learned_mac = host.cmd(\n- \"arp -n %s | grep %s | awk '{ print $3 }'\" % (ip, ip)).strip()\n+ \"ip -%u neighbor show %s | awk '{ print $5 }'\" % (ip_ver, ip)).strip()\n if learned_mac:\n break\n time.sleep(1)\n@@ -716,24 +710,18 @@ def verify_ipv4_host_learned_mac(self, host, ip, mac, retries=3):\n msg='MAC learned on host mismatch (expected %s found %s)' % (\n mac, learned_mac))\n \n+ def verify_ipv4_host_learned_mac(self, host, ip, mac, retries=3):\n+ self._verify_host_learned_mac(host, ip, 4, mac, retries)\n+\n def verify_ipv4_host_learned_host(self, host, learned_host):\n- learned_ip = ipaddr.IPNetwork(self.host_ipv4(learned_host))\n+ learned_ip = ipaddress.ip_interface(unicode(self.host_ipv4(learned_host)))\n self.verify_ipv4_host_learned_mac(host, learned_ip.ip, learned_host.MAC())\n \n def verify_ipv6_host_learned_mac(self, host, ip6, mac, retries=3):\n- for _ in range(retries):\n- learned_mac = host.cmd(\n- \"ip -6 neighbor show %s | awk '{ print $5 }'\" % ip6).strip()\n- if learned_mac:\n- break\n- time.sleep(1)\n- self.assertEqual(\n- mac, learned_mac,\n- msg='MAC learned on host mismatch (expected %s found %s)' % (\n- mac, learned_mac))\n+ self._verify_host_learned_mac(host, ip6, 6, mac, retries)\n \n def verify_ipv6_host_learned_host(self, host, learned_host):\n- learned_ip6 = ipaddr.IPNetwork(self.host_ipv6(learned_host))\n+ learned_ip6 = ipaddress.ip_interface(unicode(self.host_ipv6(learned_host)))\n self.verify_ipv6_host_learned_mac(host, learned_ip6.ip, learned_host.MAC())\n \n def verify_ipv4_routing(self, first_host, first_host_routed_ip,\n@@ -742,16 +730,16 @@ def verify_ipv4_routing(self, first_host, first_host_routed_ip,\n \"\"\"Verify one host can IPV4 route to another via FAUCET.\"\"\"\n self.host_ipv4_alias(first_host, first_host_routed_ip)\n self.host_ipv4_alias(second_host, second_host_routed_ip)\n- self.add_host_ipv4_route(\n+ self.add_host_route(\n first_host, second_host_routed_ip, self.FAUCET_VIPV4.ip)\n- self.add_host_ipv4_route(\n+ self.add_host_route(\n second_host, first_host_routed_ip, self.FAUCET_VIPV4.ip)\n self.net.ping(hosts=(first_host, second_host))\n self.wait_for_route_as_flow(\n- first_host.MAC(), first_host_routed_ip,\n+ first_host.MAC(), first_host_routed_ip.network,\n with_group_table=with_group_table)\n self.wait_for_route_as_flow(\n- second_host.MAC(), second_host_routed_ip,\n+ second_host.MAC(), second_host_routed_ip.network,\n with_group_table=with_group_table)\n self.one_ipv4_ping(first_host, second_host_routed_ip.ip)\n self.one_ipv4_ping(second_host, first_host_routed_ip.ip)\n@@ -762,9 +750,9 @@ def verify_ipv4_routing_mesh(self, with_group_table=False):\n \"\"\"Verify hosts can route to each other via FAUCET.\"\"\"\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_routed_ip = ipaddr.IPv4Network('10.0.1.1/24')\n- second_host_routed_ip = ipaddr.IPv4Network('10.0.2.1/24')\n- second_host_routed_ip2 = ipaddr.IPv4Network('10.0.3.1/24')\n+ first_host_routed_ip = ipaddress.ip_interface(u'10.0.1.1/24')\n+ second_host_routed_ip = ipaddress.ip_interface(u'10.0.2.1/24')\n+ second_host_routed_ip2 = ipaddress.ip_interface(u'10.0.3.1/24')\n self.verify_ipv4_routing(\n first_host, first_host_routed_ip,\n second_host, second_host_routed_ip,\n@@ -803,15 +791,15 @@ def verify_ipv6_routing(self, first_host, first_host_ip,\n \"\"\"Verify one host can IPV6 route to another via FAUCET.\"\"\"\n self.one_ipv6_ping(first_host, second_host_ip.ip)\n self.one_ipv6_ping(second_host, first_host_ip.ip)\n- self.add_host_ipv6_route(\n+ self.add_host_route(\n first_host, second_host_routed_ip, self.FAUCET_VIPV6.ip)\n- self.add_host_ipv6_route(\n+ self.add_host_route(\n second_host, first_host_routed_ip, self.FAUCET_VIPV6.ip)\n self.wait_for_route_as_flow(\n- first_host.MAC(), first_host_routed_ip,\n+ first_host.MAC(), first_host_routed_ip.network,\n with_group_table=with_group_table)\n self.wait_for_route_as_flow(\n- second_host.MAC(), second_host_routed_ip,\n+ second_host.MAC(), second_host_routed_ip.network,\n with_group_table=with_group_table)\n self.one_ipv6_controller_ping(first_host)\n self.one_ipv6_controller_ping(second_host)\n@@ -839,11 +827,11 @@ def verify_ipv6_routing_mesh(self, with_group_table=False):\n \"\"\"Verify IPv6 routing between hosts and multiple subnets.\"\"\"\n host_pair = self.net.hosts[:2]\n first_host, second_host = host_pair\n- first_host_ip = ipaddr.IPv6Network('fc00::1:1/112')\n- second_host_ip = ipaddr.IPv6Network('fc00::1:2/112')\n- first_host_routed_ip = ipaddr.IPv6Network('fc00::10:1/112')\n- second_host_routed_ip = ipaddr.IPv6Network('fc00::20:1/112')\n- second_host_routed_ip2 = ipaddr.IPv6Network('fc00::30:1/112')\n+ first_host_ip = ipaddress.ip_interface(u'fc00::1:1/112')\n+ second_host_ip = ipaddress.ip_interface(u'fc00::1:2/112')\n+ first_host_routed_ip = ipaddress.ip_interface(u'fc00::10:1/112')\n+ second_host_routed_ip = ipaddress.ip_interface(u'fc00::20:1/112')\n+ second_host_routed_ip2 = ipaddress.ip_interface(u'fc00::30:1/112')\n self.verify_ipv6_routing_pair(\n first_host, first_host_ip, first_host_routed_ip,\n second_host, second_host_ip, second_host_routed_ip,\ndiff --git a/tests/test_api.py b/tests/test_api.py\n--- a/tests/test_api.py\n+++ b/tests/test_api.py\n@@ -1,6 +1,6 @@\n import os\n import sys\n-import ipaddr\n+import ipaddress\n \n from ryu.base import app_manager\n from ryu.lib import hub\ndiff --git a/tests/test_config.py b/tests/test_config.py\n--- a/tests/test_config.py\n+++ b/tests/test_config.py\n@@ -19,7 +19,7 @@\n import logging\n import sys\n import os\n-import ipaddr\n+import ipaddress\n \n testdir = os.path.dirname(__file__)\n srcdir = '../src/ryu_faucet/org/onfsdn/faucet'\n@@ -181,7 +181,7 @@ def test_routing(self):\n for dp in (self.v2_dp,):\n vlan = dp.vlans[41]\n self.assertIn(\n- ipaddr.IPNetwork('10.0.0.253/24'),\n+ ipaddress.ip_interface(u'10.0.0.253/24'),\n vlan.faucet_vips\n )\n self.assertEquals(vlan.bgp_port, 9179)\n@@ -190,15 +190,15 @@ def test_routing(self):\n self.assertIn('127.0.0.1', vlan.bgp_neighbor_addresses)\n self.assertEquals(vlan.bgp_neighbor_as, 2)\n self.assertIn(\n- ipaddr.IPNetwork('10.0.1.0/24'),\n+ ipaddress.ip_network(u'10.0.1.0/24'),\n vlan.ipv4_routes\n )\n self.assertIn(\n- ipaddr.IPNetwork('10.0.2.0/24'),\n+ ipaddress.ip_network(u'10.0.2.0/24'),\n vlan.ipv4_routes\n )\n self.assertIn(\n- ipaddr.IPNetwork('10.0.3.0/24'),\n+ ipaddress.ip_network(u'10.0.3.0/24'),\n vlan.ipv4_routes\n )\n \n", "problem_statement": "", "hints_text": "", "created_at": "2017-03-15T09:44:02Z"} diff --git a/PythonDataset/test/gcloud-aio-task-instances.jsonl.all b/PythonDataset/test/gcloud-aio-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..22ebd936f45469f9bbb8c45b23fea3af3c4217ad --- /dev/null +++ b/PythonDataset/test/gcloud-aio-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "talkiq/gcloud-aio", "pull_number": 24, "instance_id": "talkiq__gcloud-aio-24", "issue_numbers": "", "base_commit": "02d7ce2526855c16a36d7cced824a9c7b7d9bd6b", "patch": "diff --git a/auth/gcloud/aio/auth/auth.py b/auth/gcloud/aio/auth/auth.py\n--- a/auth/gcloud/aio/auth/auth.py\n+++ b/auth/gcloud/aio/auth/auth.py\n@@ -1,15 +1,16 @@\n \"\"\"\n Google Cloud auth via service account file\n \"\"\"\n+import asyncio\n import datetime\n import json\n import time\n import typing\n+from urllib.parse import quote_plus\n+from urllib.parse import urlencode\n \n import aiohttp\n import jwt\n-from gcloud.aio.core.aio import auto\n-from gcloud.aio.core.http import post\n \n \n ScopeList = typing.List[str]\n@@ -20,29 +21,24 @@\n 'project_id.'\n \n \n-async def acquire_token(session: aiohttp.ClientSession,\n- service_data: dict,\n+async def acquire_token(session: aiohttp.ClientSession, service_data: dict,\n scopes: ScopeList = None):\n-\n url, assertion = generate_assertion(service_data, scopes)\n \n- payload = {\n- 'grant_type': JWT_GRANT_TYPE,\n- 'assertion': assertion\n+ headers = {\n+ 'Content-Type': 'application/x-www-form-urlencoded',\n }\n+ payload = urlencode({\n+ 'assertion': assertion,\n+ 'grant_type': JWT_GRANT_TYPE,\n+ }, quote_via=quote_plus)\n \n- _status, content = await post(\n- url,\n- payload,\n- headers={'content-type': 'application/x-www-form-urlencoded'},\n- timeout=60,\n- urlencoded=True,\n- json_response=True,\n- session=session\n- )\n+ response = await session.post(url, data=payload, headers=headers,\n+ params=None, timeout=60)\n+ content = await response.json()\n \n if 'error' in content:\n- raise Exception('{}'.format(content))\n+ raise Exception(f'got error acquiring token: {content}')\n \n return {\n 'access_token': str(content['access_token']),\n@@ -100,7 +96,7 @@ def __init__(self, project: str, service_file: str,\n \n self.scopes = scopes or []\n \n- self.session = session\n+ self.session = session or aiohttp.ClientSession()\n self.access_token = None\n self.access_token_duration = None\n self.access_token_acquired_at = None\n@@ -121,7 +117,7 @@ async def ensure_token(self):\n \n elif not self.access_token:\n \n- self.acquiring = self.acquire_access_token()\n+ self.acquiring = asyncio.ensure_future(self.acquire_access_token())\n \n await self.acquiring\n \n@@ -132,11 +128,11 @@ async def ensure_token(self):\n \n if delta > self.access_token_duration / 2:\n \n- self.acquiring = self.acquire_access_token()\n+ self.acquiring = asyncio.ensure_future(\n+ self.acquire_access_token())\n \n await self.acquiring\n \n- @auto\n async def acquire_access_token(self):\n \n data = await acquire_token(\ndiff --git a/auth/nox.py b/auth/nox.py\n--- a/auth/nox.py\n+++ b/auth/nox.py\n@@ -4,16 +4,13 @@\n import nox\n \n \n-LOCAL_DEPS = ('../core/',)\n-\n-\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n- session.install('pytest', 'pytest-cov', *LOCAL_DEPS)\n+ session.install('pytest', 'pytest-cov')\n session.install('-e', '.')\n \n session.run(\n@@ -23,7 +20,7 @@ def unit_tests(session, python_version):\n '--cov=tests.unit',\n '--cov-append',\n '--cov-report=',\n- '--cov-fail-under=39',\n+ '--cov-fail-under=38',\n os.path.join('tests', 'unit'),\n *session.posargs)\n \n@@ -34,10 +31,10 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n- session.install('aiohttp', 'pytest', *LOCAL_DEPS)\n+ session.install('aiohttp', 'pytest')\n session.install('.')\n \n session.run('py.test', '--quiet', 'tests/integration')\n@@ -46,7 +43,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -61,7 +58,7 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\ndiff --git a/bigquery/gcloud/aio/bigquery/bigquery.py b/bigquery/gcloud/aio/bigquery/bigquery.py\n--- a/bigquery/gcloud/aio/bigquery/bigquery.py\n+++ b/bigquery/gcloud/aio/bigquery/bigquery.py\n@@ -2,9 +2,12 @@\n import logging\n import uuid\n \n-import ujson\n+import aiohttp\n from gcloud.aio.auth import Token\n-from gcloud.aio.core.http import post\n+try:\n+ import ujson as json\n+except ModuleNotFoundError:\n+ import json\n \n \n API_ROOT = 'https://www.googleapis.com/bigquery/v2'\n@@ -63,51 +66,43 @@ async def headers(self):\n token = await self.token.get()\n \n return {\n- 'Authorization': 'Bearer {}'.format(token)\n+ 'Authorization': f'Bearer {token}',\n }\n \n async def insert(self, rows, skip_invalid=False, ignore_unknown=True,\n session=None):\n-\n session = session or self.session\n \n- body = make_insert_body(\n- rows,\n- skip_invalid=skip_invalid,\n- ignore_unknown=ignore_unknown\n- )\n-\n- headers = await self.headers()\n-\n- url = '{}/{}'.format(\n- API_ROOT,\n- INSERT_TEMPLATE.format(\n- proj=self.project,\n- dataset=self.dataset_name,\n- table=self.table_name\n- )\n- )\n-\n+ insert_url = INSERT_TEMPLATE.format(proj=self.project,\n+ dataset=self.dataset_name,\n+ table=self.table_name)\n+ url = f'{API_ROOT}/{insert_url}'\n log.info('Inserting %d rows to %s', len(rows), url)\n \n- status, content = await post(\n- url,\n- payload=body,\n- headers=headers\n- )\n+ body = make_insert_body(rows, skip_invalid=skip_invalid,\n+ ignore_unknown=ignore_unknown)\n+ payload = json.dumps(body).encode('utf-8')\n+\n+ headers = await self.headers()\n+ headers.update({\n+ 'Content-Length': str(len(payload)),\n+ 'Content-Type': 'application/json'\n+ })\n \n- success = 299 >= status >= 200 and 'insertErrors' not in content\n+ async with aiohttp.ClientSession() as s:\n+ response = await s.post(url, data=payload, headers=headers,\n+ params=None, timeout=60)\n+ content = await response.json()\n \n- if success:\n- return success\n+ if 299 >= response.status >= 200 and 'insertErrors' not in content:\n+ return True\n \n- log.debug('response code: %d', status)\n+ log.debug('response code: %d', response.status)\n log.debug('url: %s', url)\n- log.debug('body:\\n%s\\n', body)\n+ log.debug('body:\\n%s\\n', payload)\n \n- raise Exception('Could not insert: {}'.format(ujson.dumps(\n- content, sort_keys=True\n- )))\n+ content_blob = json.dumps(content, sort_keys=True)\n+ raise Exception(f'could not insert: {content_blob}')\n \n \n async def stream_insert(table, rows):\ndiff --git a/bigquery/nox.py b/bigquery/nox.py\n--- a/bigquery/nox.py\n+++ b/bigquery/nox.py\n@@ -4,14 +4,14 @@\n import nox\n \n \n-LOCAL_DEPS = ('../core/', '../auth/')\n+LOCAL_DEPS = ('../auth/', )\n \n \n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n session.install('pytest', 'pytest-cov', *LOCAL_DEPS)\n session.install('-e', '.')\n@@ -23,7 +23,7 @@ def unit_tests(session, python_version):\n '--cov=tests.unit',\n '--cov-append',\n '--cov-report=',\n- '--cov-fail-under=47',\n+ '--cov-fail-under=46',\n os.path.join('tests', 'unit'),\n *session.posargs)\n \n@@ -34,8 +34,8 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n session.install('aiohttp', 'pytest', *LOCAL_DEPS)\n session.install('.')\n@@ -46,7 +46,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -61,11 +61,11 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\n \n- session.run('coverage', 'report', '--show-missing', '--fail-under=47')\n+ session.run('coverage', 'report', '--show-missing', '--fail-under=46')\n session.run('codecov')\n session.run('coverage', 'erase')\ndiff --git a/core/gcloud/__init__.py b/core/gcloud/__init__.py\ndeleted file mode 100644\n--- a/core/gcloud/__init__.py\n+++ /dev/null\n@@ -1,6 +0,0 @@\n-try:\n- import pkg_resources\n- pkg_resources.declare_namespace(__name__)\n-except ImportError:\n- import pkgutil\n- __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/core/gcloud/aio/__init__.py b/core/gcloud/aio/__init__.py\ndeleted file mode 100644\n--- a/core/gcloud/aio/__init__.py\n+++ /dev/null\n@@ -1,6 +0,0 @@\n-try:\n- import pkg_resources\n- pkg_resources.declare_namespace(__name__)\n-except ImportError:\n- import pkgutil\n- __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/core/gcloud/aio/core/__init__.py b/core/gcloud/aio/core/__init__.py\ndeleted file mode 100644\n--- a/core/gcloud/aio/core/__init__.py\n+++ /dev/null\n@@ -1,5 +0,0 @@\n-from pkg_resources import get_distribution\n-__version__ = get_distribution('gcloud-aio-core').version\n-\n-\n-__all__ = ['__version__']\ndiff --git a/core/gcloud/aio/core/aio.py b/core/gcloud/aio/core/aio.py\ndeleted file mode 100644\n--- a/core/gcloud/aio/core/aio.py\n+++ /dev/null\n@@ -1,66 +0,0 @@\n-import asyncio\n-import functools\n-\n-\n-def maybe_async(callable_, *args, **kwargs):\n-\n- \"\"\"\n- Turn a callable into a coroutine if it isn't\n- \"\"\"\n-\n- if asyncio.iscoroutine(callable_):\n- return callable_\n-\n- return asyncio.coroutine(callable_)(*args, **kwargs)\n-\n-\n-def fire(callable_, *args, **kwargs):\n-\n- \"\"\"\n- Start a callable as a coroutine, and return it's future. The cool thing\n- about this function is that (via maybe_async) it lets you treat synchronous\n- and asynchronous callables the same (both as async), which simplifies code.\n- \"\"\"\n-\n- return asyncio.ensure_future(maybe_async(callable_, *args, **kwargs))\n-\n-\n-def auto(fn):\n-\n- \"\"\"\n- Decorate a function or method with this, and it will become a callable\n- that can be scheduled in the event loop just by calling it. Normally you'd\n- have to do an `asyncio.ensure_future(my_callable())`. Not you can just do\n- `my_callable()`. Twisted has always let you do this, and now you can let\n- asyncio do it as well (with a decorator, albeit...)\n- \"\"\"\n-\n- @functools.wraps(fn)\n- def wrapper(*args, **kwargs):\n-\n- return fire(fn, *args, **kwargs)\n-\n- return wrapper\n-\n-\n-async def _call_later(delay, callable_, *args, **kwargs):\n-\n- \"\"\"\n- The bus stop, where we wait.\n- \"\"\"\n-\n- await asyncio.sleep(delay)\n-\n- fire(callable_, *args, **kwargs)\n-\n-\n-def call_later(delay, callable_, *args, **kwargs):\n-\n- \"\"\"\n- After :delay seconds, call :callable with :args and :kwargs; :callable can\n- be a synchronous or asynchronous callable (a coroutine). Note that _this_\n- function is synchronous - mission accomplished - it can be used from within\n- any synchronous or asynchronous callable.\n- \"\"\"\n-\n- return fire(_call_later, delay, callable_, *args, **kwargs)\ndiff --git a/core/gcloud/aio/core/astate.py b/core/gcloud/aio/core/astate.py\ndeleted file mode 100644\n--- a/core/gcloud/aio/core/astate.py\n+++ /dev/null\n@@ -1,83 +0,0 @@\n-import asyncio\n-import logging\n-\n-from gcloud.aio.core.aio import fire\n-\n-\n-log = logging.getLogger(__name__)\n-\n-\n-class AwaitableState:\n- # pylint: disable=too-few-public-methods\n-\n- \"\"\"\n- Wrap a :future with a name and data. If :future is a coroutine, turn it\n- into a future by firing it.\n-\n- Use instances of AwaitableState as named states in state machines. Use\n- :data for arbitrary context beyond :name.\n- \"\"\"\n-\n- def __init__(self, name, future, data=None):\n-\n- self.name = name\n- self.future = future\n- self.data = data\n-\n- if asyncio.iscoroutine(self.future):\n- self.future = fire(self.future)\n-\n- def __await__(self):\n-\n- return self.future.__await__()\n-\n- def __str__(self):\n-\n- return self.__repr__()\n-\n- def __repr__(self):\n-\n- return ''.format(\n- self.name,\n- id(self)\n- )\n-\n- def __getattr__(self, attr):\n-\n- return getattr(self.future, attr)\n-\n- def __hash__(self):\n-\n- return hash(self.name)\n-\n- def __eq__(self, other):\n-\n- return hash(self) == hash(other)\n-\n-\n-def make_stepper(default_step, state_step, name='sm'):\n-\n- \"\"\"\n- `default_step`: a callable that takes no args\n- `state_step`: a mapping between AwaitableState.name -> callable\n- \"\"\"\n-\n- async def step(state, args):\n-\n- state_name = getattr(state, 'name', None)\n- step = state_step.get(state_name, default_step)\n- next_state = step(args) if args is not None else step()\n-\n- if next_state:\n- args = await next_state\n- else:\n- args = tuple()\n-\n- if next_state != state:\n- log.debug('%s state change: %s -> %s', name,\n- getattr(state, 'name', None),\n- getattr(next_state, 'name', None))\n-\n- return next_state, args\n-\n- return step\ndiff --git a/core/gcloud/aio/core/http.py b/core/gcloud/aio/core/http.py\ndeleted file mode 100644\n--- a/core/gcloud/aio/core/http.py\n+++ /dev/null\n@@ -1,140 +0,0 @@\n-from urllib.parse import quote_plus\n-from urllib.parse import urlencode\n-\n-import aiohttp\n-import ujson\n-from asyncio_extras.contextmanager import async_contextmanager\n-\n-\n-class HttpError(Exception):\n- pass\n-\n-\n-@async_contextmanager\n-async def ensure_session(session):\n-\n- if session:\n- yield session\n- else:\n- async with aiohttp.ClientSession() as session:\n- yield session\n-\n-\n-async def delete(url, headers=None, params=None, timeout=60, session=None):\n-\n- async with ensure_session(session) as s: # pylint: disable=not-async-context-manager\n-\n- response = await s.delete(\n- url,\n- headers=headers,\n- params=params,\n- timeout=timeout\n- )\n-\n- phrase = await response.text()\n-\n- return response.status, phrase\n-\n-\n-async def post(url, payload=None, timeout=60, urlencoded=False,\n- json_response=True, session=None, headers=None, params=None):\n- # pylint: disable=too-many-arguments\n-\n- headers = headers or {}\n-\n- if urlencoded:\n-\n- if payload:\n- payload = urlencode(payload, quote_via=quote_plus)\n-\n- headers['content-type'] = 'application/x-www-form-urlencoded'\n-\n- else:\n-\n- if payload:\n- payload = ujson.dumps(payload)\n- payload = payload.encode('utf-8')\n- content_length = str(len(payload))\n- else:\n- content_length = '0'\n-\n- headers.update({\n- 'content-length': content_length,\n- 'content-type': 'application/json'\n- })\n-\n- async with ensure_session(session) as s: # pylint: disable=not-async-context-manager\n-\n- response = await s.post(\n- url,\n- data=payload,\n- headers=headers,\n- params=params,\n- timeout=timeout\n- )\n-\n- if json_response:\n- content = await response.json()\n- else:\n- content = await response.text()\n-\n- return response.status, content\n-\n-\n-async def get(url, timeout=60, json_response=True, session=None, headers=None,\n- params=None):\n- # pylint: disable=too-many-arguments\n-\n- async with ensure_session(session) as s: # pylint: disable=not-async-context-manager\n-\n- response = await s.get(\n- url,\n- headers=headers,\n- params=params,\n- timeout=timeout\n- )\n-\n- if json_response:\n- content = await response.json()\n- else:\n- content = await response.text()\n-\n- return response.status, content\n-\n-\n-async def put(*args, **kwargs): # pylint: disable=unused-argument\n-\n- raise Exception('Not implemented.')\n-\n-\n-async def patch(url, payload=None, timeout=60, session=None, headers=None,\n- params=None):\n- # pylint: disable=too-many-arguments\n-\n- headers = headers or {}\n-\n- if payload:\n- payload = ujson.dumps(payload)\n- payload = payload.encode('utf-8')\n- content_length = str(len(payload))\n- else:\n- content_length = '0'\n-\n- headers.update({\n- 'content-length': content_length,\n- 'content-type': 'application/json'\n- })\n-\n- async with ensure_session(session) as s: # pylint: disable=not-async-context-manager\n-\n- response = await s.patch(\n- url,\n- data=payload,\n- headers=headers,\n- params=params,\n- timeout=timeout\n- )\n-\n- phrase = await response.text()\n-\n- return response.status, phrase\ndiff --git a/core/nox.py b/core/nox.py\ndeleted file mode 100644\n--- a/core/nox.py\n+++ /dev/null\n@@ -1,53 +0,0 @@\n-# pylint: disable=import-self,no-member\n-import os\n-\n-import nox\n-\n-\n-@nox.session\n-@nox.parametrize('python_version', ['3.6'])\n-def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n-\n- session.install('pytest', 'pytest-cov')\n- session.install('-e', '.')\n-\n- session.run(\n- 'py.test',\n- '--quiet',\n- '--cov=gcloud.aio.core',\n- '--cov=tests.unit',\n- '--cov-append',\n- '--cov-report=',\n- '--cov-fail-under=37',\n- os.path.join('tests', 'unit'),\n- *session.posargs)\n-\n-\n-@nox.session\n-@nox.parametrize('python_version', ['3.6'])\n-def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'setup'\n-\n- session.install('docutils', 'Pygments')\n- session.run(\n- 'python',\n- 'setup.py',\n- 'check',\n- '--restructuredtext',\n- '--strict')\n-\n-\n-@nox.session\n-@nox.parametrize('python_version', ['3.6'])\n-def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'cover'\n-\n- session.install('codecov', 'coverage', 'pytest-cov')\n-\n- session.run('coverage', 'report', '--show-missing', '--fail-under=37')\n- session.run('codecov')\n- session.run('coverage', 'erase')\ndiff --git a/core/setup.py b/core/setup.py\ndeleted file mode 100644\n--- a/core/setup.py\n+++ /dev/null\n@@ -1,41 +0,0 @@\n-import os\n-\n-import setuptools\n-\n-\n-PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))\n-with open(os.path.join(PACKAGE_ROOT, 'README.rst')) as f:\n- README = f.read()\n-\n-with open(os.path.join(PACKAGE_ROOT, 'requirements.txt')) as f:\n- REQUIREMENTS = [r.strip() for r in f.readlines()]\n-\n-\n-setuptools.setup(\n- name='gcloud-aio-core',\n- version='0.7.2',\n- description='Core Helpers for Asyncio Google Cloud Library',\n- long_description=README,\n- namespace_packages=[\n- 'gcloud',\n- 'gcloud.aio',\n- ],\n- packages=setuptools.find_packages(exclude=('tests',)),\n- install_requires=REQUIREMENTS,\n- author='TalkIQ',\n- author_email='engineering@talkiq.com',\n- url='https://github.com/talkiq/gcloud-aio',\n- platforms='Posix; MacOS X; Windows',\n- include_package_data=True,\n- zip_safe=False,\n- license='MIT License',\n- classifiers=[\n- 'Development Status :: 4 - Beta',\n- 'Intended Audience :: Developers',\n- 'License :: OSI Approved :: MIT License',\n- 'Operating System :: OS Independent',\n- 'Programming Language :: Python :: 3',\n- 'Programming Language :: Python :: 3.6',\n- 'Topic :: Internet',\n- ],\n-)\ndiff --git a/datastore/gcloud/aio/datastore/datastore.py b/datastore/gcloud/aio/datastore/datastore.py\n--- a/datastore/gcloud/aio/datastore/datastore.py\n+++ b/datastore/gcloud/aio/datastore/datastore.py\n@@ -1,11 +1,15 @@\n import datetime\n import logging\n \n+import aiohttp\n from gcloud.aio.auth import Token\n-from gcloud.aio.core.http import post\n from gcloud.aio.datastore.constants import Mode\n from gcloud.aio.datastore.constants import Operation\n from gcloud.aio.datastore.constants import TypeName\n+try:\n+ import ujson as json\n+except ModuleNotFoundError:\n+ import json\n \n \n API_ROOT = 'https://datastore.googleapis.com/v1/projects'\n@@ -30,9 +34,7 @@ def infer_type(value):\n }.get(type(value))\n \n if not type_name:\n- raise Exception('Type {} not supported for DS insert. :('.format(\n- type(value)\n- ))\n+ raise Exception(f'type {type(value)} not supported for DS insert')\n \n return type_name\n \n@@ -109,45 +111,54 @@ async def headers(self):\n token = await self.token.get()\n \n return {\n- 'Authorization': 'Bearer {}'.format(token),\n+ 'Authorization': f'Bearer {token}',\n }\n \n async def transact(self):\n- url = '{}/{}:beginTransaction'.format(API_ROOT, self.project)\n+ url = f'{API_ROOT}/{self.project}:beginTransaction'\n headers = await self.headers()\n- body = {}\n+ headers.update({\n+ 'Content-Length': '0',\n+ 'Content-Type': 'application/json'\n+ })\n \n- status, content = await post(url, payload={}, headers=headers)\n+ async with aiohttp.ClientSession() as s:\n+ response = await s.post(url, data={}, headers=headers, params=None,\n+ timeout=60)\n+ content = await response.json()\n \n # TODO: make this raise_for_status-able.\n- success = 299 >= status >= 200\n-\n- if success:\n+ if 299 >= response.status >= 200:\n transaction = content['transaction']\n return transaction\n \n- log.debug('response code: %d', status)\n+ log.debug('response code: %d', response.status)\n log.debug('url: %s', url)\n- log.debug('body:\\n%s\\n', body)\n \n- raise Exception('Could not transact: {}'.format(content))\n+ raise Exception(f'could not transact: {content}')\n \n async def commit(self, transaction, mutations, mode=Mode.TRANSACTIONAL):\n- url = '{}/{}:commit'.format(API_ROOT, self.project)\n+ url = f'{API_ROOT}/{self.project}:commit'\n \n body = make_commit_body(transaction, mode, mutations)\n+ payload = json.dumps(body).encode('utf-8')\n \n headers = await self.headers()\n+ headers.update({\n+ 'Content-Length': str(len(payload)),\n+ 'Content-Type': 'application/json'\n+ })\n \n- status, content = await post(url, payload=body, headers=headers)\n+ async with aiohttp.ClientSession() as s:\n+ response = await s.post(url, data=payload, headers=headers,\n+ params=None, timeout=60)\n+ content = await response.json()\n \n # TODO: make this raise_for_status-able.\n- success = 299 >= status >= 200 and 'insertErrors' not in content\n-\n- if success:\n- return success\n+ if 299 >= response.status >= 200 and 'insertErrors' not in content:\n+ return True\n \n- raise Exception('{}: {} > {}'.format(status, url, content))\n+ raise Exception(f'{response.status}: {url} > {content}')\n \n # TODO: look into deletion payload format\n \ndiff --git a/datastore/nox.py b/datastore/nox.py\n--- a/datastore/nox.py\n+++ b/datastore/nox.py\n@@ -4,14 +4,14 @@\n import nox\n \n \n-LOCAL_DEPS = ('../core/', '../auth/')\n+LOCAL_DEPS = ('../auth/', )\n \n \n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n session.install('pytest', 'pytest-cov', *LOCAL_DEPS)\n session.install('-e', '.')\n@@ -34,8 +34,8 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n session.install('pytest', *LOCAL_DEPS)\n session.install('.')\n@@ -46,7 +46,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -61,7 +61,7 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\ndiff --git a/pubsub/nox.py b/pubsub/nox.py\n--- a/pubsub/nox.py\n+++ b/pubsub/nox.py\n@@ -7,8 +7,8 @@\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n session.install('pytest', 'pytest-cov')\n session.install('-e', '.')\n@@ -31,8 +31,8 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n session.install('pytest')\n session.install('.')\n@@ -43,7 +43,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -58,7 +58,7 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\ndiff --git a/storage/gcloud/aio/storage/__init__.py b/storage/gcloud/aio/storage/__init__.py\n--- a/storage/gcloud/aio/storage/__init__.py\n+++ b/storage/gcloud/aio/storage/__init__.py\n@@ -1,10 +1,10 @@\n from pkg_resources import get_distribution\n __version__ = get_distribution('gcloud-aio-storage').version\n \n-from gcloud.aio.storage.storage import Blob\n-from gcloud.aio.storage.storage import Bucket\n-from gcloud.aio.storage.storage import make_download\n+from gcloud.aio.storage.blob import Blob\n+from gcloud.aio.storage.bucket import Bucket\n from gcloud.aio.storage.storage import Storage\n+from gcloud.aio.storage.utils import make_download\n \n \n-__all__ = ['__version__', 'Blob', 'Bucket', 'make_download', 'Storage']\n+__all__ = ['__version__', 'Blob', 'Bucket', 'Storage', 'make_download']\ndiff --git a/storage/gcloud/aio/storage/blob.py b/storage/gcloud/aio/storage/blob.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/gcloud/aio/storage/blob.py\n@@ -0,0 +1,33 @@\n+try:\n+ import ujson as json\n+except ModuleNotFoundError:\n+ import json\n+\n+\n+class Blob:\n+ def __init__(self, bucket, name, data):\n+ self.__dict__.update(**data)\n+\n+ self.bucket = bucket\n+ self.name = name\n+ self.size = int(self.size)\n+\n+ @property\n+ def chunk_size(self):\n+ return self.size + (262144 - (self.size % 262144))\n+\n+ async def download_as_string(self, session=None):\n+ return await self.bucket.storage.download_as_string(self.bucket.name,\n+ self.name,\n+ session=session)\n+\n+ async def upload_from_string(self, data, session=None):\n+ status, content = await self.bucket.storage.upload(self.bucket.name,\n+ self.name, data,\n+ session=session)\n+\n+ if status < 200 or status >= 300:\n+ raise Exception(f'{status}: {json.dumps(content)}')\n+\n+ self.__dict__.update(content)\n+ return content\ndiff --git a/storage/gcloud/aio/storage/bucket.py b/storage/gcloud/aio/storage/bucket.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/gcloud/aio/storage/bucket.py\n@@ -0,0 +1,47 @@\n+import logging\n+\n+from gcloud.aio.storage.blob import Blob\n+try:\n+ import ujson as json\n+except ModuleNotFoundError:\n+ import json\n+\n+\n+log = logging.getLogger(__name__)\n+\n+\n+class Bucket:\n+ def __init__(self, storage, name):\n+ self.storage = storage\n+ self.name = name\n+\n+ async def get_blob(self, blob_name, session=None):\n+ blob_name = blob_name.replace('/', '%2F')\n+\n+ status, content = await self.storage.download(self.name, blob_name,\n+ session=session)\n+\n+ if status < 200 or status >= 300:\n+ log.error('Could not download %s/%s: %s', self.name, blob_name,\n+ content)\n+ return\n+\n+ content = json.loads(content)\n+\n+ return Blob(self, blob_name, content)\n+\n+ async def list_blobs(self, prefix='', session=None):\n+ params = {'prefix': prefix}\n+\n+ status, content = await self.storage.list_objects(self.name,\n+ params=params,\n+ session=session)\n+\n+ if status < 200 or status >= 300:\n+ log.error('Could not list %s/%s: %s', self.name, prefix, content)\n+ return\n+\n+ return [x['name'] for x in content.get('items', list())]\n+\n+ def new_blob(self, blob_name):\n+ return Blob(self, blob_name, {'size': 0})\ndiff --git a/storage/gcloud/aio/storage/storage.py b/storage/gcloud/aio/storage/storage.py\n--- a/storage/gcloud/aio/storage/storage.py\n+++ b/storage/gcloud/aio/storage/storage.py\n@@ -1,18 +1,16 @@\n-import functools\n import logging\n-import mimetypes\n \n import aiohttp\n-import ujson\n from gcloud.aio.auth import Token\n-from gcloud.aio.core.http import get\n-from gcloud.aio.core.http import HttpError\n-from gcloud.aio.core.http import post\n+from gcloud.aio.storage.bucket import Bucket\n+try:\n+ import ujson as json\n+except ModuleNotFoundError:\n+ import json\n \n \n STORAGE_API_ROOT = 'https://www.googleapis.com/storage/v1/b'\n STORAGE_UPLOAD_API_ROOT = 'https://www.googleapis.com/upload/storage/v1/b'\n-READ_ONLY_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_only'\n READ_WRITE_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_write'\n \n log = logging.getLogger(__name__)\n@@ -28,64 +26,68 @@ def __init__(self, project, service_file, token=None, session=None):\n scopes=[READ_WRITE_SCOPE])\n \n async def download(self, bucket, object_name, params=None, session=None):\n- session = session or self.session\n-\n token = await self.token.get()\n- url = '{}/{}/o/{}'.format(STORAGE_API_ROOT, bucket, object_name)\n+ url = f'{STORAGE_API_ROOT}/{bucket}/o/{object_name}'\n headers = {\n- 'Authorization': 'Bearer {}'.format(token),\n+ 'Authorization': f'Bearer {token}',\n }\n \n- return await get(url, params=params or {}, headers=headers,\n- session=self.session, json_response=False)\n-\n- async def list_objects(self, bucket, params=None, session=None):\n session = session or self.session\n+ response = await session.get(url, headers=headers, params=params or {},\n+ timeout=60)\n+ content = await response.text()\n+\n+ return response.status, content\n \n+ async def list_objects(self, bucket, params=None, session=None):\n token = await self.token.get()\n- url = '{}/{}/o'.format(STORAGE_API_ROOT, bucket)\n+ url = f'{STORAGE_API_ROOT}/{bucket}/o'\n headers = {\n- 'Authorization': 'Bearer {}'.format(token),\n+ 'Authorization': f'Bearer {token}',\n }\n \n- return await get(url, params=params or {}, headers=headers,\n- session=self.session, json_response=True)\n+ session = session or self.session\n+ response = await session.get(url, headers=headers, params=params or {},\n+ timeout=60)\n+ content = await response.json()\n+\n+ return response.status, content\n \n async def upload(self, bucket, object_name, file_data, headers=None,\n session=None):\n # pylint: disable=too-many-arguments\n # https://cloud.google.com/storage/docs/json_api/v1/how-tos/simple-upload\n- session = session or self.session\n-\n token = await self.token.get()\n- url = '{}/{}/o'.format(STORAGE_UPLOAD_API_ROOT, bucket)\n+ url = f'{STORAGE_UPLOAD_API_ROOT}/{bucket}/o'\n headers = headers or {}\n \n- # TODO: verify this\n- if not isinstance(file_data, bytes):\n- body = file_data.encode('utf-8')\n- else:\n- body = file_data\n-\n- body_length = str(len(body))\n-\n params = {\n 'name': object_name,\n 'uploadType': 'media',\n }\n \n- content_type = mimetypes.guess_type(object_name)[0]\n- content_type = content_type or 'application/octet-stream'\n+ if not isinstance(file_data, bytes):\n+ file_data = file_data.encode('utf-8')\n+\n+ if file_data:\n+ file_data = json.dumps(file_data).encode('utf-8')\n+ content_length = str(len(file_data))\n+ else:\n+ content_length = '0'\n \n headers.update({\n- 'accept': 'application/json',\n- 'Authorization': 'Bearer {}'.format(token),\n- 'Content-Length': body_length,\n- 'Content-Type': content_type,\n+ 'Accept': 'application/json',\n+ 'Authorization': f'Bearer {token}',\n+ 'Content-Length': content_length,\n+ 'Content-Type': 'application/json',\n })\n \n- return await post(url, params=params, payload=body, headers=headers,\n- timeout=120, session=session)\n+ session = session or self.session\n+ response = await session.post(url, data=file_data, headers=headers,\n+ params=params, timeout=120)\n+ content = await response.json()\n+\n+ return response.status, content\n \n async def download_as_string(self, bucket, object_name, session=None):\n object_name = object_name.replace('/', '%2F')\n@@ -98,88 +100,3 @@ async def download_as_string(self, bucket, object_name, session=None):\n \n def get_bucket(self, bucket_name):\n return Bucket(self, bucket_name)\n-\n-\n-class Bucket:\n- def __init__(self, storage, name):\n- self.storage = storage\n- self.name = name\n-\n- async def get_blob(self, blob_name, session=None):\n- blob_name = blob_name.replace('/', '%2F')\n-\n- status, content = await self.storage.download(self.name, blob_name,\n- session=session)\n-\n- if status < 200 or status >= 300:\n- log.error('Could not download %s/%s: %s', self.name, blob_name,\n- content)\n- return\n-\n- content = ujson.loads(content)\n-\n- return Blob(self, blob_name, content)\n-\n- async def list_blobs(self, prefix='', session=None):\n- params = {'prefix': prefix}\n-\n- status, content = await self.storage.list_objects(self.name,\n- params=params,\n- session=session)\n-\n- if status < 200 or status >= 300:\n- log.error('Could not list %s/%s: %s', self.name, prefix, content)\n- return\n-\n- return [x['name'] for x in content.get('items', list())]\n-\n- def new_blob(self, blob_name):\n- return Blob(self, blob_name, {'size': 0})\n-\n-\n-class Blob:\n- def __init__(self, bucket, name, data):\n- self.__dict__.update(**data)\n-\n- self.bucket = bucket\n- self.name = name\n- self.size = int(self.size)\n-\n- @property\n- def chunk_size(self):\n- return self.size + (262144 - (self.size % 262144))\n-\n- async def download_as_string(self, session=None):\n- return await self.bucket.storage.download_as_string(self.bucket.name,\n- self.name,\n- session=session)\n-\n- async def upload_from_string(self, data, session=None):\n- status, content = await self.bucket.storage.upload(self.bucket.name,\n- self.name, data,\n- session=session)\n-\n- if status < 200 or status >= 300:\n- raise HttpError('{}: {}'.format(status, ujson.dumps(content)))\n-\n- self.__dict__.update(content)\n- return content\n-\n-\n-async def download(bucket, object_name):\n- blob = await bucket.get_blob(object_name)\n- if not blob:\n- raise Exception('No such object \"{}/{}\"'.format(bucket.name,\n- object_name))\n-\n- return await blob.download_as_string()\n-\n-\n-def make_download(project, service_file, bucket_name, session=None,\n- token=None):\n- token = token or Token(project, service_file, scopes=[READ_ONLY_SCOPE])\n-\n- storage = Storage(project, service_file, session=session, token=token)\n- bucket = storage.get_bucket(bucket_name)\n-\n- return functools.partial(download, bucket)\ndiff --git a/storage/gcloud/aio/storage/utils.py b/storage/gcloud/aio/storage/utils.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/gcloud/aio/storage/utils.py\n@@ -0,0 +1,25 @@\n+import functools\n+\n+from gcloud.aio.auth import Token\n+from gcloud.aio.storage.storage import Storage\n+\n+\n+READ_ONLY_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_only'\n+\n+\n+async def download(bucket, object_name):\n+ blob = await bucket.get_blob(object_name)\n+ if not blob:\n+ raise Exception(f'No such object \"{bucket.name}/{object_name}\"')\n+\n+ return await blob.download_as_string()\n+\n+\n+def make_download(project, service_file, bucket_name, session=None,\n+ token=None):\n+ token = token or Token(project, service_file, scopes=[READ_ONLY_SCOPE])\n+\n+ storage = Storage(project, service_file, session=session, token=token)\n+ bucket = storage.get_bucket(bucket_name)\n+\n+ return functools.partial(download, bucket)\ndiff --git a/storage/nox.py b/storage/nox.py\n--- a/storage/nox.py\n+++ b/storage/nox.py\n@@ -4,14 +4,14 @@\n import nox\n \n \n-LOCAL_DEPS = ('../core/', '../auth/')\n+LOCAL_DEPS = ('../auth/', )\n \n \n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n session.install('pytest', 'pytest-cov', *LOCAL_DEPS)\n session.install('-e', '.')\n@@ -34,8 +34,8 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n session.install('aiohttp', 'pytest', *LOCAL_DEPS)\n session.install('.')\n@@ -46,7 +46,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -61,7 +61,7 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\ndiff --git a/taskqueue/gcloud/aio/taskqueue/taskmanager.py b/taskqueue/gcloud/aio/taskqueue/taskmanager.py\n--- a/taskqueue/gcloud/aio/taskqueue/taskmanager.py\n+++ b/taskqueue/gcloud/aio/taskqueue/taskmanager.py\n@@ -59,9 +59,9 @@ async def stop(self):\n \n @staticmethod\n def autorenew(event, headers, task, lease_seconds):\n- url = '{}/{}:renewLease'.format(API_ROOT, task['name'])\n+ url = f'{API_ROOT}/{task[\"name\"]}:renewLease'\n body = {\n- 'leaseDuration': '{}s'.format(lease_seconds),\n+ 'leaseDuration': f'{lease_seconds}s',\n 'responseView': 'FULL',\n }\n \ndiff --git a/taskqueue/gcloud/aio/taskqueue/taskqueue.py b/taskqueue/gcloud/aio/taskqueue/taskqueue.py\n--- a/taskqueue/gcloud/aio/taskqueue/taskqueue.py\n+++ b/taskqueue/gcloud/aio/taskqueue/taskqueue.py\n@@ -28,21 +28,22 @@ def __init__(self, project, service_file, taskqueue, location=LOCATION,\n self.session = session or aiohttp.ClientSession(conn_timeout=10,\n read_timeout=10)\n \n- self.api_root = '{}/projects/{}/locations/{}/queues/{}'.format(\n- API_ROOT, project, location, taskqueue)\n+ self.api_root = (f'{API_ROOT}/projects/{project}/'\n+ f'locations/{location}/queues/{taskqueue}')\n \n self.token = token or Token(project, service_file, scopes=SCOPES,\n session=self.session)\n \n async def headers(self):\n+ token = await self.token.get()\n return {\n- 'Authorization': 'Bearer {}'.format(await self.token.get()),\n+ 'Authorization': f'Bearer {token}',\n 'Content-Type': 'application/json',\n }\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/acknowledge\n async def ack(self, task, session=None):\n- url = '{}/{}:acknowledge'.format(API_ROOT, task['name'])\n+ url = f'{API_ROOT}/{task[\"name\"]}:acknowledge'\n body = {\n 'scheduleTime': task['scheduleTime'],\n }\n@@ -55,7 +56,7 @@ async def ack(self, task, session=None):\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/cancelLease\n async def cancel(self, task, session=None):\n- url = '{}/{}:cancelLease'.format(API_ROOT, task['name'])\n+ url = f'{API_ROOT}/{task[\"name\"]}:cancelLease'\n body = {\n 'scheduleTime': task['scheduleTime'],\n 'responseView': 'BASIC',\n@@ -69,7 +70,7 @@ async def cancel(self, task, session=None):\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/delete\n async def delete(self, tname, session=None):\n- url = '{}/{}'.format(API_ROOT, tname)\n+ url = f'{API_ROOT}/{tname}'\n \n s = session or self.session\n resp = await retry(s.delete(url, headers=await self.headers()))\n@@ -84,7 +85,7 @@ async def drain(self):\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/get\n async def get(self, tname, full=False, session=None):\n- url = '{}/{}'.format(API_ROOT, tname)\n+ url = f'{API_ROOT}/{tname}'\n params = {\n 'responseView': 'FULL' if full else 'BASIC',\n }\n@@ -97,7 +98,7 @@ async def get(self, tname, full=False, session=None):\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/create\n async def insert(self, payload, tag=None, session=None):\n- url = '{}/tasks'.format(self.api_root)\n+ url = f'{self.api_root}/tasks'\n body = {\n 'task': {\n 'pullMessage': {\n@@ -117,10 +118,10 @@ async def insert(self, payload, tag=None, session=None):\n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/lease\n async def lease(self, num_tasks=1, lease_seconds=60, task_filter=None,\n session=None):\n- url = '{}/tasks:lease'.format(self.api_root)\n+ url = f'{self.api_root}/tasks:lease'\n body = {\n 'maxTasks': min(num_tasks, 1000),\n- 'leaseDuration': '{}s'.format(lease_seconds),\n+ 'leaseDuration': f'{lease_seconds}s',\n 'responseView': 'FULL',\n }\n if task_filter:\n@@ -135,7 +136,7 @@ async def lease(self, num_tasks=1, lease_seconds=60, task_filter=None,\n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/list\n async def list(self, full=False, page_size=1000, page_token='',\n session=None):\n- url = '{}/tasks'.format(self.api_root)\n+ url = f'{self.api_root}/tasks'\n params = {\n 'responseView': 'FULL' if full else 'BASIC',\n 'pageSize': page_size,\n@@ -150,10 +151,10 @@ async def list(self, full=False, page_size=1000, page_token='',\n \n # https://cloud.google.com/cloud-tasks/docs/reference/rest/v2beta2/projects.locations.queues.tasks/renewLease\n async def renew(self, task, lease_seconds=60, session=None):\n- url = '{}/{}:renewLease'.format(API_ROOT, task['name'])\n+ url = f'{API_ROOT}/{task[\"name\"]}:renewLease'\n body = {\n 'scheduleTime': task['scheduleTime'],\n- 'leaseDuration': '{}s'.format(lease_seconds),\n+ 'leaseDuration': f'{lease_seconds}s',\n 'responseView': 'FULL',\n }\n \ndiff --git a/taskqueue/nox.py b/taskqueue/nox.py\n--- a/taskqueue/nox.py\n+++ b/taskqueue/nox.py\n@@ -10,8 +10,8 @@\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def unit_tests(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'unit-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'unit-{python_version}'\n \n session.install('pytest', 'pytest-cov', *LOCAL_DEPS)\n session.install('-e', '.')\n@@ -34,8 +34,8 @@ def integration_tests(session, python_version):\n if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):\n session.skip('Credentials must be set via environment variable.')\n \n- session.interpreter = 'python{}'.format(python_version)\n- session.virtualenv_dirname = 'integration-' + python_version\n+ session.interpreter = f'python{python_version}'\n+ session.virtualenv_dirname = f'integration-{python_version}'\n \n session.install('pytest', 'pytest-mock', *LOCAL_DEPS)\n session.install('.')\n@@ -46,7 +46,7 @@ def integration_tests(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def lint_setup_py(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'setup'\n \n session.install('docutils', 'Pygments')\n@@ -61,7 +61,7 @@ def lint_setup_py(session, python_version):\n @nox.session\n @nox.parametrize('python_version', ['3.6'])\n def cover(session, python_version):\n- session.interpreter = 'python{}'.format(python_version)\n+ session.interpreter = f'python{python_version}'\n session.virtualenv_dirname = 'cover'\n \n session.install('codecov', 'coverage', 'pytest-cov')\n", "test_patch": "diff --git a/core/tests/__init__.py b/core/tests/__init__.py\ndeleted file mode 100644\ndiff --git a/core/tests/unit/__init__.py b/core/tests/unit/__init__.py\ndeleted file mode 100644\ndiff --git a/core/tests/unit/aio_test.py b/core/tests/unit/aio_test.py\ndeleted file mode 100644\n--- a/core/tests/unit/aio_test.py\n+++ /dev/null\n@@ -1,5 +0,0 @@\n-import gcloud.aio.core.aio as aio # pylint: disable=unused-import\n-\n-\n-def test_importable():\n- assert True\ndiff --git a/core/tests/unit/astate_test.py b/core/tests/unit/astate_test.py\ndeleted file mode 100644\n--- a/core/tests/unit/astate_test.py\n+++ /dev/null\n@@ -1,5 +0,0 @@\n-import gcloud.aio.core.astate as astate # pylint: disable=unused-import\n-\n-\n-def test_importable():\n- assert True\ndiff --git a/core/tests/unit/http_test.py b/core/tests/unit/http_test.py\ndeleted file mode 100644\n--- a/core/tests/unit/http_test.py\n+++ /dev/null\n@@ -1,5 +0,0 @@\n-import gcloud.aio.core.http as http # pylint: disable=unused-import\n-\n-\n-def test_importable():\n- assert True\ndiff --git a/datastore/tests/integration/smoke_test.py b/datastore/tests/integration/smoke_test.py\n--- a/datastore/tests/integration/smoke_test.py\n+++ b/datastore/tests/integration/smoke_test.py\n@@ -24,7 +24,7 @@ def test_item_lifecycle():\n creds = os.environ['GOOGLE_APPLICATION_CREDENTIALS']\n \n kind_name = 'gcloud-aio-test'\n- object_name = 'test_record_{}'.format(uuid.uuid4())\n+ object_name = f'test_record_{uuid.uuid4()}'\n \n loop = asyncio.get_event_loop()\n loop.run_until_complete(\ndiff --git a/storage/tests/integration/smoke_test.py b/storage/tests/integration/smoke_test.py\n--- a/storage/tests/integration/smoke_test.py\n+++ b/storage/tests/integration/smoke_test.py\n@@ -21,7 +21,7 @@ def test_object_is_downloaded():\n call_id = '07fbe0cc-7f87-1235-06b0-0cc47a392728'\n side = 'callee'\n link = 0\n- object_name = '{}/{}/{}/rtp.pcap.wav.ctm'.format(call_id, side, link)\n+ object_name = f'{call_id}/{side}/{link}/rtp.pcap.wav.ctm'\n \n loop = asyncio.get_event_loop()\n loop.run_until_complete(\ndiff --git a/storage/tests/unit/blob_test.py b/storage/tests/unit/blob_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/tests/unit/blob_test.py\n@@ -0,0 +1,5 @@\n+import gcloud.aio.storage.blob as blob # pylint: disable=unused-import\n+\n+\n+def test_importable():\n+ assert True\ndiff --git a/storage/tests/unit/bucket_test.py b/storage/tests/unit/bucket_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/tests/unit/bucket_test.py\n@@ -0,0 +1,5 @@\n+import gcloud.aio.storage.bucket as bucket # pylint: disable=unused-import\n+\n+\n+def test_importable():\n+ assert True\ndiff --git a/storage/tests/unit/storage_test.py b/storage/tests/unit/storage_test.py\n--- a/storage/tests/unit/storage_test.py\n+++ b/storage/tests/unit/storage_test.py\n@@ -1,4 +1,4 @@\n-import gcloud.aio.storage as storage # pylint: disable=unused-import\n+import gcloud.aio.storage.storage as storage # pylint: disable=unused-import\n \n \n def test_importable():\ndiff --git a/storage/tests/unit/utils_test.py b/storage/tests/unit/utils_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/storage/tests/unit/utils_test.py\n@@ -0,0 +1,5 @@\n+import gcloud.aio.storage.utils as utils # pylint: disable=unused-import\n+\n+\n+def test_importable():\n+ assert True\ndiff --git a/taskqueue/tests/integration/taskqueue_test.py b/taskqueue/tests/integration/taskqueue_test.py\n--- a/taskqueue/tests/integration/taskqueue_test.py\n+++ b/taskqueue/tests/integration/taskqueue_test.py\n@@ -26,8 +26,7 @@ async def do_task_lifecycle(project, creds, task_queue):\n assert inserted\n \n # GET\n- got = await tq.get(inserted['name'], full=True)\n- assert got == inserted\n+ assert inserted == await tq.get(inserted['name'], full=True)\n \n # LIST\n listed = await tq.list(full=True)\n@@ -36,14 +35,12 @@ async def do_task_lifecycle(project, creds, task_queue):\n \n # LEASE\n leased = await tq.lease(num_tasks=1, lease_seconds=10,\n- task_filter='tag={}'.format(encode(tag)))\n+ task_filter=f'tag={encode(tag)}')\n assert leased.get('tasks') and len(leased['tasks']) == 1\n \n leased_message = leased['tasks'][0]['pullMessage']\n- leased_payload = json.loads(decode(leased_message['payload']))\n- leased_tag = decode(leased_message['tag'])\n- assert leased_payload == payload\n- assert leased_tag == tag\n+ assert payload == json.loads(decode(leased_message['payload']))\n+ assert tag == decode(leased_message['tag'])\n \n # RENEW\n renewed = await tq.renew(leased['tasks'][0], lease_seconds=10)\n@@ -57,8 +54,7 @@ async def do_task_lifecycle(project, creds, task_queue):\n # cancel?\n \n # DELETE\n- result = await tq.delete(renewed['name'])\n- assert not result\n+ assert not await tq.delete(renewed['name'])\n \n \n def test_task_lifecycle():\n", "problem_statement": "", "hints_text": "", "created_at": "2018-05-01T17:56:36Z"} diff --git a/PythonDataset/test/google-cloud-python-task-instances.jsonl.all b/PythonDataset/test/google-cloud-python-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..786e439e47d2564328859296ecc10d8b32de3929 --- /dev/null +++ b/PythonDataset/test/google-cloud-python-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "googleapis/google-cloud-python", "pull_number": 2223, "instance_id": "googleapis__google-cloud-python-2223", "issue_numbers": "", "base_commit": "89eed0e4251f44b0ae1b0e33d3d9ffdac1d3c330", "patch": "diff --git a/docs/bigquery_snippets.py b/docs/bigquery_snippets.py\n--- a/docs/bigquery_snippets.py\n+++ b/docs/bigquery_snippets.py\n@@ -15,8 +15,8 @@\n \"\"\"Testable usage examples for Google Cloud BigQuery API wrapper\n \n Each example function takes a ``client`` argument (which must be an instance\n-of :class:`gcloud.bigquery.client.Client`) and uses it to perform a task with\n-the API.\n+of :class:`google.cloud.bigquery.client.Client`) and uses it to perform a task\n+with the API.\n \n To facilitate running the examples as system tests, each example is also passed\n a ``to_delete`` list; the function adds to the list any objects created which\n@@ -26,8 +26,8 @@\n import operator\n import time\n \n-from gcloud.bigquery import SchemaField\n-from gcloud.bigquery.client import Client\n+from google.cloud.bigquery import SchemaField\n+from google.cloud.bigquery.client import Client\n \n ORIGINAL_FRIENDLY_NAME = 'Original friendly name'\n ORIGINAL_DESCRIPTION = 'Original description'\n@@ -162,7 +162,7 @@ def dataset_update(client, to_delete):\n dataset.reload()\n \n # [START dataset_update]\n- from gcloud.bigquery import AccessGrant\n+ from google.cloud.bigquery import AccessGrant\n assert dataset.description == ORIGINAL_DESCRIPTION\n assert dataset.default_table_expiration_ms is None\n grant = AccessGrant(\ndiff --git a/docs/conf.py b/docs/conf.py\n--- a/docs/conf.py\n+++ b/docs/conf.py\n@@ -1,6 +1,6 @@\n # -*- coding: utf-8 -*-\n #\n-# gcloud documentation build configuration file, created by\n+# google-cloud documentation build configuration file, created by\n # sphinx-quickstart on Tue Jan 21 22:24:47 2014.\n #\n # This file is execfile()d with the current directory set to its containing dir.\n@@ -56,7 +56,7 @@\n master_doc = 'index'\n \n # General information about the project.\n-project = u'gcloud'\n+project = u'google-cloud'\n copyright = u'2014, Google'\n \n # The version info for the project you're documenting, acts as replacement for\n@@ -64,7 +64,7 @@\n # built documents.\n #\n # The short X.Y version.\n-distro = get_distribution('gcloud')\n+distro = get_distribution('google-cloud')\n release = os.getenv('SPHINX_RELEASE', distro.version)\n \n # The language for content autogenerated by Sphinx. Refer to documentation\n@@ -184,7 +184,7 @@\n #html_file_suffix = None\n \n # Output file base name for HTML help builder.\n-htmlhelp_basename = 'gclouddoc'\n+htmlhelp_basename = 'google-cloud-doc'\n \n html_context = {}\n \n@@ -207,7 +207,7 @@\n # Grouping the document tree into LaTeX files. List of tuples\n # (source start file, target name, title, author, documentclass [howto/manual]).\n latex_documents = [\n- ('index', 'gcloud.tex', u'gCloud Documentation',\n+ ('index', 'google-cloud.tex', u'google-cloud Documentation',\n author, 'manual'),\n ]\n \n@@ -237,7 +237,7 @@\n # One entry per manual page. List of tuples\n # (source start file, name, description, authors, manual section).\n man_pages = [\n- ('index', 'gcloud', u'gCloud Documentation',\n+ ('index', 'google-cloud', u'google-cloud Documentation',\n [author], 1)\n ]\n \n@@ -251,8 +251,8 @@\n # (source start file, target name, title, author,\n # dir menu entry, description, category)\n texinfo_documents = [\n- ('index', 'gcloud', u'gCloud Documentation',\n- author, 'gcloud', 'Python API for Google Cloud.',\n+ ('index', 'google-cloud', u'google-cloud Documentation',\n+ author, 'google-cloud', 'Python API for Google Cloud.',\n 'Miscellaneous'),\n ]\n \n@@ -269,7 +269,7 @@\n # and parameter definitions from the __init__ docstring.\n autoclass_content = 'both'\n \n-issue_uri = ('https://github.com/GoogleCloudPlatform/gcloud-python/issues/'\n+issue_uri = ('https://github.com/GoogleCloudPlatform/google-cloud-python/issues/'\n 'new?' + urllib.urlencode({'title': '[Documentation Issue] '}))\n issue_uri_template = (\n issue_uri + '&' + urllib.urlencode({'body': 'Page Name: '}) + '{0}' +\ndiff --git a/docs/pubsub_snippets.py b/docs/pubsub_snippets.py\n--- a/docs/pubsub_snippets.py\n+++ b/docs/pubsub_snippets.py\n@@ -15,8 +15,8 @@\n \"\"\"Testable usage examples for Google Cloud Pubsub API wrapper\n \n Each example function takes a ``client`` argument (which must be an instance\n-of :class:`gcloud.pubsub.client.Client`) and uses it to perform a task with\n-the API.\n+of :class:`google.cloud.pubsub.client.Client`) and uses it to perform a task\n+with the API.\n \n To facilitate running the examples as system tests, each example is also passed\n a ``to_delete`` list; the function adds to the list any objects created which\n@@ -25,7 +25,7 @@\n \n import time\n \n-from gcloud.pubsub.client import Client\n+from google.cloud.pubsub.client import Client\n \n \n def snippet(func):\n@@ -154,7 +154,7 @@ def topic_check_iam_permissions(client, to_delete):\n to_delete.append(topic)\n \n # [START topic_check_iam_permissions]\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n TO_CHECK = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE]\n ALLOWED = topic.check_iam_permissions(TO_CHECK)\n assert set(ALLOWED) == set(TO_CHECK)\n@@ -376,7 +376,7 @@ def do_something_with(message): # pylint: disable=unused-argument\n extras.append(message.attributes)\n \n # [START subscription_pull_autoack]\n- from gcloud.pubsub.subscription import AutoAck\n+ from google.cloud.pubsub.subscription import AutoAck\n with AutoAck(subscription, max_messages=10) as ack:\n for ack_id, message in list(ack.items()):\n try:\n@@ -436,7 +436,7 @@ def subscription_check_iam_permissions(client, to_delete):\n to_delete.append(subscription)\n \n # [START subscription_check_iam_permissions]\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n TO_CHECK = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE]\n ALLOWED = subscription.check_iam_permissions(TO_CHECK)\n assert set(ALLOWED) == set(TO_CHECK)\ndiff --git a/google/__init__.py b/google/__init__.py\nnew file mode 100644\n--- /dev/null\n+++ b/google/__init__.py\n@@ -0,0 +1,22 @@\n+# Copyright 2016 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"Base ``google`` namespace package.\"\"\"\n+\n+try:\n+ import pkg_resources\n+ pkg_resources.declare_namespace(__name__)\n+except ImportError:\n+ import pkgutil\n+ __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/gcloud/__init__.py b/google/cloud/__init__.py\nsimilarity index 73%\nrename from gcloud/__init__.py\nrename to google/cloud/__init__.py\n--- a/gcloud/__init__.py\n+++ b/google/cloud/__init__.py\n@@ -12,8 +12,11 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"GCloud API access in idiomatic Python.\"\"\"\n+\"\"\"Google Cloud API access in idiomatic Python.\"\"\"\n \n-from pkg_resources import get_distribution\n-\n-__version__ = get_distribution('gcloud').version\n+try:\n+ import pkg_resources\n+ pkg_resources.declare_namespace(__name__)\n+except ImportError:\n+ import pkgutil\n+ __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/gcloud/_helpers.py b/google/cloud/_helpers.py\nsimilarity index 97%\nrename from gcloud/_helpers.py\nrename to google/cloud/_helpers.py\n--- a/gcloud/_helpers.py\n+++ b/google/cloud/_helpers.py\n@@ -11,9 +11,10 @@\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n-\"\"\"Thread-local resource stack.\n \n-This module is not part of the public API surface of `gcloud`.\n+\"\"\"Shared helpers for Google Cloud packages.\n+\n+This module is not part of the public API surface.\n \"\"\"\n \n import calendar\n@@ -41,8 +42,10 @@\n from six.moves.http_client import HTTPConnection\n from six.moves import configparser\n \n-from gcloud.environment_vars import PROJECT\n-from gcloud.environment_vars import CREDENTIALS\n+# pylint: disable=ungrouped-imports\n+from google.cloud.environment_vars import PROJECT\n+from google.cloud.environment_vars import CREDENTIALS\n+# pylint: enable=ungrouped-imports\n \n \n _NOW = datetime.datetime.utcnow # To be replaced by tests.\n@@ -72,8 +75,8 @@\n class _LocalStack(Local):\n \"\"\"Manage a thread-local LIFO stack of resources.\n \n- Intended for use in :class:`gcloud.datastore.batch.Batch.__enter__`,\n- :class:`gcloud.storage.batch.Batch.__enter__`, etc.\n+ Intended for use in :class:`google.cloud.datastore.batch.Batch.__enter__`,\n+ :class:`google.cloud.storage.batch.Batch.__enter__`, etc.\n \"\"\"\n def __init__(self):\n super(_LocalStack, self).__init__()\n@@ -290,7 +293,7 @@ def _determine_default_project(project=None):\n In implicit case, supports three environments. In order of precedence, the\n implicit environments are:\n \n- * GCLOUD_PROJECT environment variable\n+ * GOOGLE_CLOUD_PROJECT environment variable\n * GOOGLE_APPLICATION_CREDENTIALS JSON file\n * Get default service project from\n ``$ gcloud beta auth application-default login``\ndiff --git a/gcloud/bigquery/__init__.py b/google/cloud/bigquery/__init__.py\nsimilarity index 59%\nrename from gcloud/bigquery/__init__.py\nrename to google/cloud/bigquery/__init__.py\n--- a/gcloud/bigquery/__init__.py\n+++ b/google/cloud/bigquery/__init__.py\n@@ -16,17 +16,19 @@\n \n The main concepts with this API are:\n \n-- :class:`gcloud.bigquery.dataset.Dataset` represents an collection of tables.\n+- :class:`~google.cloud.bigquery.dataset.Dataset` represents a\n+ collection of tables.\n \n-- :class:`gcloud.bigquery.table.Table` represents a single \"relation\".\n+- :class:`~google.cloud.bigquery.table.Table` represents a single \"relation\".\n \"\"\"\n \n-from gcloud.bigquery.client import Client\n-from gcloud.bigquery.connection import Connection\n-from gcloud.bigquery.dataset import AccessGrant\n-from gcloud.bigquery.dataset import Dataset\n-from gcloud.bigquery.schema import SchemaField\n-from gcloud.bigquery.table import Table\n+\n+from google.cloud.bigquery.client import Client\n+from google.cloud.bigquery.connection import Connection\n+from google.cloud.bigquery.dataset import AccessGrant\n+from google.cloud.bigquery.dataset import Dataset\n+from google.cloud.bigquery.schema import SchemaField\n+from google.cloud.bigquery.table import Table\n \n \n SCOPE = Connection.SCOPE\ndiff --git a/gcloud/bigquery/_helpers.py b/google/cloud/bigquery/_helpers.py\nsimilarity index 98%\nrename from gcloud/bigquery/_helpers.py\nrename to google/cloud/bigquery/_helpers.py\n--- a/gcloud/bigquery/_helpers.py\n+++ b/google/cloud/bigquery/_helpers.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Shared helper functions for BigQuery API classes.\"\"\"\n \n-from gcloud._helpers import _datetime_from_microseconds\n+from google.cloud._helpers import _datetime_from_microseconds\n \n \n def _not_null(value, field):\ndiff --git a/gcloud/bigquery/client.py b/google/cloud/bigquery/client.py\nsimilarity index 85%\nrename from gcloud/bigquery/client.py\nrename to google/cloud/bigquery/client.py\n--- a/gcloud/bigquery/client.py\n+++ b/google/cloud/bigquery/client.py\n@@ -15,14 +15,14 @@\n \"\"\"Client for interacting with the Google BigQuery API.\"\"\"\n \n \n-from gcloud.client import JSONClient\n-from gcloud.bigquery.connection import Connection\n-from gcloud.bigquery.dataset import Dataset\n-from gcloud.bigquery.job import CopyJob\n-from gcloud.bigquery.job import ExtractTableToStorageJob\n-from gcloud.bigquery.job import LoadTableFromStorageJob\n-from gcloud.bigquery.job import QueryJob\n-from gcloud.bigquery.query import QueryResults\n+from google.cloud.client import JSONClient\n+from google.cloud.bigquery.connection import Connection\n+from google.cloud.bigquery.dataset import Dataset\n+from google.cloud.bigquery.job import CopyJob\n+from google.cloud.bigquery.job import ExtractTableToStorageJob\n+from google.cloud.bigquery.job import LoadTableFromStorageJob\n+from google.cloud.bigquery.job import QueryJob\n+from google.cloud.bigquery.query import QueryResults\n \n \n class Client(JSONClient):\n@@ -68,8 +68,8 @@ def list_datasets(self, include_all=False, max_results=None,\n datasets.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.bigquery.dataset.Dataset`, plus a\n- \"next page token\" string: if the token is not None,\n+ :returns: list of :class:`~google.cloud.bigquery.dataset.Dataset`,\n+ plus a \"next page token\" string: if the token is not None,\n indicates that more datasets can be retrieved with another\n call (pass that value as ``page_token``).\n \"\"\"\n@@ -97,7 +97,7 @@ def dataset(self, dataset_name):\n :type dataset_name: str\n :param dataset_name: Name of the dataset.\n \n- :rtype: :class:`gcloud.bigquery.dataset.Dataset`\n+ :rtype: :class:`google.cloud.bigquery.dataset.Dataset`\n :returns: a new ``Dataset`` instance\n \"\"\"\n return Dataset(dataset_name, client=self)\n@@ -109,11 +109,11 @@ def job_from_resource(self, resource):\n :param resource: one job resource from API response\n \n :rtype: One of:\n- :class:`gcloud.bigquery.job.LoadTableFromStorageJob`,\n- :class:`gcloud.bigquery.job.CopyJob`,\n- :class:`gcloud.bigquery.job.ExtractTableToStorageJob`,\n- :class:`gcloud.bigquery.job.QueryJob`,\n- :class:`gcloud.bigquery.job.RunSyncQueryJob`\n+ :class:`google.cloud.bigquery.job.LoadTableFromStorageJob`,\n+ :class:`google.cloud.bigquery.job.CopyJob`,\n+ :class:`google.cloud.bigquery.job.ExtractTableToStorageJob`,\n+ :class:`google.cloud.bigquery.job.QueryJob`,\n+ :class:`google.cloud.bigquery.job.RunSyncQueryJob`\n :returns: the job instance, constructed via the resource\n \"\"\"\n config = resource['configuration']\n@@ -191,14 +191,14 @@ def load_table_from_storage(self, job_name, destination, *source_uris):\n :type job_name: str\n :param job_name: Name of the job.\n \n- :type destination: :class:`gcloud.bigquery.table.Table`\n+ :type destination: :class:`google.cloud.bigquery.table.Table`\n :param destination: Table into which data is to be loaded.\n \n :type source_uris: sequence of string\n :param source_uris: URIs of data files to be loaded; in format\n ``gs:///``.\n \n- :rtype: :class:`gcloud.bigquery.job.LoadTableFromStorageJob`\n+ :rtype: :class:`google.cloud.bigquery.job.LoadTableFromStorageJob`\n :returns: a new ``LoadTableFromStorageJob`` instance\n \"\"\"\n return LoadTableFromStorageJob(job_name, destination, source_uris,\n@@ -213,13 +213,13 @@ def copy_table(self, job_name, destination, *sources):\n :type job_name: str\n :param job_name: Name of the job.\n \n- :type destination: :class:`gcloud.bigquery.table.Table`\n+ :type destination: :class:`google.cloud.bigquery.table.Table`\n :param destination: Table into which data is to be copied.\n \n- :type sources: sequence of :class:`gcloud.bigquery.table.Table`\n+ :type sources: sequence of :class:`google.cloud.bigquery.table.Table`\n :param sources: tables to be copied.\n \n- :rtype: :class:`gcloud.bigquery.job.CopyJob`\n+ :rtype: :class:`google.cloud.bigquery.job.CopyJob`\n :returns: a new ``CopyJob`` instance\n \"\"\"\n return CopyJob(job_name, destination, sources, client=self)\n@@ -233,7 +233,7 @@ def extract_table_to_storage(self, job_name, source, *destination_uris):\n :type job_name: str\n :param job_name: Name of the job.\n \n- :type source: :class:`gcloud.bigquery.table.Table`\n+ :type source: :class:`google.cloud.bigquery.table.Table`\n :param source: table to be extracted.\n \n :type destination_uris: sequence of string\n@@ -241,7 +241,7 @@ def extract_table_to_storage(self, job_name, source, *destination_uris):\n table data is to be extracted; in format\n ``gs:///``.\n \n- :rtype: :class:`gcloud.bigquery.job.ExtractTableToStorageJob`\n+ :rtype: :class:`google.cloud.bigquery.job.ExtractTableToStorageJob`\n :returns: a new ``ExtractTableToStorageJob`` instance\n \"\"\"\n return ExtractTableToStorageJob(job_name, source, destination_uris,\n@@ -259,7 +259,7 @@ def run_async_query(self, job_name, query):\n :type query: str\n :param query: SQL query to be executed\n \n- :rtype: :class:`gcloud.bigquery.job.QueryJob`\n+ :rtype: :class:`google.cloud.bigquery.job.QueryJob`\n :returns: a new ``QueryJob`` instance\n \"\"\"\n return QueryJob(job_name, query, client=self)\n@@ -270,7 +270,7 @@ def run_sync_query(self, query):\n :type query: str\n :param query: SQL query to be executed\n \n- :rtype: :class:`gcloud.bigquery.query.QueryResults`\n+ :rtype: :class:`google.cloud.bigquery.query.QueryResults`\n :returns: a new ``QueryResults`` instance\n \"\"\"\n return QueryResults(query, client=self)\ndiff --git a/gcloud/bigquery/connection.py b/google/cloud/bigquery/connection.py\nsimilarity index 91%\nrename from gcloud/bigquery/connection.py\nrename to google/cloud/bigquery/connection.py\n--- a/gcloud/bigquery/connection.py\n+++ b/google/cloud/bigquery/connection.py\n@@ -12,9 +12,9 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud bigquery connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud BigQuery connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/bigquery/dataset.py b/google/cloud/bigquery/dataset.py\nsimilarity index 93%\nrename from gcloud/bigquery/dataset.py\nrename to google/cloud/bigquery/dataset.py\n--- a/gcloud/bigquery/dataset.py\n+++ b/google/cloud/bigquery/dataset.py\n@@ -15,9 +15,9 @@\n \"\"\"Define API Datasets.\"\"\"\n import six\n \n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud.exceptions import NotFound\n-from gcloud.bigquery.table import Table\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud.exceptions import NotFound\n+from google.cloud.bigquery.table import Table\n \n \n class AccessGrant(object):\n@@ -94,7 +94,7 @@ class Dataset(object):\n :type name: string\n :param name: the name of the dataset\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \n@@ -298,11 +298,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: dataset resource representation returned from the API\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: Client which holds credentials and project\n configuration for the dataset.\n \n- :rtype: :class:`gcloud.bigquery.dataset.Dataset`\n+ :rtype: :class:`google.cloud.bigquery.dataset.Dataset`\n :returns: Dataset parsed from ``resource``.\n \"\"\"\n if ('datasetReference' not in resource or\n@@ -317,11 +317,12 @@ def from_api_repr(cls, resource, client):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n- :rtype: :class:`gcloud.bigquery.client.Client`\n+ :rtype: :class:`google.cloud.bigquery.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -413,7 +414,8 @@ def create(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/tables/insert\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -429,7 +431,8 @@ def exists(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/datasets/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -452,7 +455,8 @@ def reload(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/datasets/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -468,7 +472,8 @@ def patch(self, client=None, **kw):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -506,7 +511,8 @@ def update(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/datasets/update\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -521,7 +527,8 @@ def delete(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/tables/delete\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -544,7 +551,7 @@ def list_tables(self, max_results=None, page_token=None):\n datasets.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.bigquery.table.Table`, plus a\n+ :returns: list of :class:`google.cloud.bigquery.table.Table`, plus a\n \"next page token\" string: if not ``None``, indicates that\n more tables can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -571,10 +578,10 @@ def table(self, name, schema=()):\n :type name: string\n :param name: Name of the table.\n \n- :type schema: list of :class:`gcloud.bigquery.table.SchemaField`\n+ :type schema: list of :class:`google.cloud.bigquery.table.SchemaField`\n :param schema: The table's schema\n \n- :rtype: :class:`gcloud.bigquery.table.Table`\n+ :rtype: :class:`google.cloud.bigquery.table.Table`\n :returns: a new ``Table`` instance\n \"\"\"\n return Table(name, dataset=self, schema=schema)\ndiff --git a/gcloud/bigquery/job.py b/google/cloud/bigquery/job.py\nsimilarity index 93%\nrename from gcloud/bigquery/job.py\nrename to google/cloud/bigquery/job.py\n--- a/gcloud/bigquery/job.py\n+++ b/google/cloud/bigquery/job.py\n@@ -16,15 +16,15 @@\n \n import six\n \n-from gcloud.exceptions import NotFound\n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud.bigquery.dataset import Dataset\n-from gcloud.bigquery.schema import SchemaField\n-from gcloud.bigquery.table import Table\n-from gcloud.bigquery.table import _build_schema_resource\n-from gcloud.bigquery.table import _parse_schema_resource\n-from gcloud.bigquery._helpers import _EnumProperty\n-from gcloud.bigquery._helpers import _TypedProperty\n+from google.cloud.exceptions import NotFound\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud.bigquery.dataset import Dataset\n+from google.cloud.bigquery.schema import SchemaField\n+from google.cloud.bigquery.table import Table\n+from google.cloud.bigquery.table import _build_schema_resource\n+from google.cloud.bigquery.table import _parse_schema_resource\n+from google.cloud.bigquery._helpers import _EnumProperty\n+from google.cloud.bigquery._helpers import _TypedProperty\n \n \n class UDFResource(object):\n@@ -66,7 +66,7 @@ def _build_udf_resources(resources):\n class UDFResourcesProperty(object):\n \"\"\"Custom property type for :class:`QueryJob`.\n \n- Also used by :class:`~gcloud.bigquery.query.Query`.\n+ Also used by :class:`~google.cloud.bigquery.query.Query`.\n \"\"\"\n def __get__(self, instance, owner):\n \"\"\"Descriptor protocol: accessor\"\"\"\n@@ -136,7 +136,7 @@ class WriteDisposition(_EnumProperty):\n class _BaseJob(object):\n \"\"\"Base class for jobs.\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \"\"\"\n@@ -156,11 +156,12 @@ def project(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n- :rtype: :class:`gcloud.bigquery.client.Client`\n+ :rtype: :class:`google.cloud.bigquery.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -174,7 +175,7 @@ class _AsyncJob(_BaseJob):\n :type name: string\n :param name: the name of the job\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \"\"\"\n@@ -354,7 +355,8 @@ def begin(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/jobs/insert\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -370,7 +372,8 @@ def exists(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/jobs/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -393,7 +396,8 @@ def reload(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/jobs/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -409,7 +413,8 @@ def cancel(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/jobs/cancel\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -444,18 +449,18 @@ class LoadTableFromStorageJob(_AsyncJob):\n :type name: string\n :param name: the name of the job\n \n- :type destination: :class:`gcloud.bigquery.table.Table`\n+ :type destination: :class:`google.cloud.bigquery.table.Table`\n :param destination: Table into which data is to be loaded.\n \n :type source_uris: sequence of string\n :param source_uris: URIs of one or more data files to be loaded, in\n format ``gs:///``.\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \n- :type schema: list of :class:`gcloud.bigquery.table.SchemaField`\n+ :type schema: list of :class:`google.cloud.bigquery.table.SchemaField`\n :param schema: The job's schema\n \"\"\"\n \n@@ -661,11 +666,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: dataset job representation returned from the API\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: Client which holds credentials and project\n configuration for the dataset.\n \n- :rtype: :class:`gcloud.bigquery.job.LoadTableFromStorageJob`\n+ :rtype: :class:`google.cloud.bigquery.job.LoadTableFromStorageJob`\n :returns: Job parsed from ``resource``.\n \"\"\"\n name, config = cls._get_resource_config(resource)\n@@ -693,13 +698,13 @@ class CopyJob(_AsyncJob):\n :type name: string\n :param name: the name of the job\n \n- :type destination: :class:`gcloud.bigquery.table.Table`\n+ :type destination: :class:`google.cloud.bigquery.table.Table`\n :param destination: Table into which data is to be loaded.\n \n- :type sources: list of :class:`gcloud.bigquery.table.Table`\n+ :type sources: list of :class:`google.cloud.bigquery.table.Table`\n :param sources: Table into which data is to be loaded.\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \"\"\"\n@@ -771,11 +776,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: dataset job representation returned from the API\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: Client which holds credentials and project\n configuration for the dataset.\n \n- :rtype: :class:`gcloud.bigquery.job.CopyJob`\n+ :rtype: :class:`google.cloud.bigquery.job.CopyJob`\n :returns: Job parsed from ``resource``.\n \"\"\"\n name, config = cls._get_resource_config(resource)\n@@ -808,7 +813,7 @@ class ExtractTableToStorageJob(_AsyncJob):\n :type name: string\n :param name: the name of the job\n \n- :type source: :class:`gcloud.bigquery.table.Table`\n+ :type source: :class:`google.cloud.bigquery.table.Table`\n :param source: Table into which data is to be loaded.\n \n :type destination_uris: list of string\n@@ -816,7 +821,7 @@ class ExtractTableToStorageJob(_AsyncJob):\n extracted data will be written, in format\n ``gs:///``.\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \"\"\"\n@@ -897,11 +902,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: dataset job representation returned from the API\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: Client which holds credentials and project\n configuration for the dataset.\n \n- :rtype: :class:`gcloud.bigquery.job.ExtractTableToStorageJob`\n+ :rtype: :class:`google.cloud.bigquery.job.ExtractTableToStorageJob`\n :returns: Job parsed from ``resource``.\n \"\"\"\n name, config = cls._get_resource_config(resource)\n@@ -939,13 +944,13 @@ class QueryJob(_AsyncJob):\n :type query: string\n :param query: SQL query string\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \n :type udf_resources: tuple\n :param udf_resources: An iterable of\n- :class:`gcloud.bigquery.job.UDFResource`\n+ :class:`google.cloud.bigquery.job.UDFResource`\n (empty by default)\n \"\"\"\n _JOB_TYPE = 'query'\n@@ -1092,11 +1097,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: dataset job representation returned from the API\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: Client which holds credentials and project\n configuration for the dataset.\n \n- :rtype: :class:`gcloud.bigquery.job.RunAsyncQueryJob`\n+ :rtype: :class:`google.cloud.bigquery.job.RunAsyncQueryJob`\n :returns: Job parsed from ``resource``.\n \"\"\"\n name, config = cls._get_resource_config(resource)\ndiff --git a/gcloud/bigquery/query.py b/google/cloud/bigquery/query.py\nsimilarity index 92%\nrename from gcloud/bigquery/query.py\nrename to google/cloud/bigquery/query.py\n--- a/gcloud/bigquery/query.py\n+++ b/google/cloud/bigquery/query.py\n@@ -16,13 +16,13 @@\n \n import six\n \n-from gcloud.bigquery._helpers import _TypedProperty\n-from gcloud.bigquery._helpers import _rows_from_json\n-from gcloud.bigquery.dataset import Dataset\n-from gcloud.bigquery.job import QueryJob\n-from gcloud.bigquery.job import UDFResourcesProperty\n-from gcloud.bigquery.job import _build_udf_resources\n-from gcloud.bigquery.table import _parse_schema_resource\n+from google.cloud.bigquery._helpers import _TypedProperty\n+from google.cloud.bigquery._helpers import _rows_from_json\n+from google.cloud.bigquery.dataset import Dataset\n+from google.cloud.bigquery.job import QueryJob\n+from google.cloud.bigquery.job import UDFResourcesProperty\n+from google.cloud.bigquery.job import _build_udf_resources\n+from google.cloud.bigquery.table import _parse_schema_resource\n \n \n class _SyncQueryConfiguration(object):\n@@ -45,13 +45,13 @@ class QueryResults(object):\n :type query: string\n :param query: SQL query string\n \n- :type client: :class:`gcloud.bigquery.client.Client`\n+ :type client: :class:`google.cloud.bigquery.client.Client`\n :param client: A client which holds credentials and project configuration\n for the dataset (which requires a project).\n \n :type udf_resources: tuple\n :param udf_resources: An iterable of\n- :class:`gcloud.bigquery.job.UDFResource`\n+ :class:`google.cloud.bigquery.job.UDFResource`\n (empty by default)\n \"\"\"\n \n@@ -77,11 +77,12 @@ def project(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n- :rtype: :class:`gcloud.bigquery.client.Client`\n+ :rtype: :class:`google.cloud.bigquery.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -144,7 +145,7 @@ def name(self):\n def job(self):\n \"\"\"Job instance used to run the query.\n \n- :rtype: :class:`gcloud.bigquery.job.QueryJob`, or ``NoneType``\n+ :rtype: :class:`google.cloud.bigquery.job.QueryJob`, or ``NoneType``\n :returns: Job instance used to run the query (None until\n ``jobReference`` property is set by the server).\n \"\"\"\n@@ -301,7 +302,8 @@ def run(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/jobs/query\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -331,7 +333,8 @@ def fetch_data(self, max_results=None, page_token=None, start_index=None,\n :param timeout_ms: timeout, in milliseconds, to wait for query to\n complete\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \ndiff --git a/gcloud/bigquery/schema.py b/google/cloud/bigquery/schema.py\nsimilarity index 100%\nrename from gcloud/bigquery/schema.py\nrename to google/cloud/bigquery/schema.py\ndiff --git a/gcloud/bigquery/table.py b/google/cloud/bigquery/table.py\nsimilarity index 92%\nrename from gcloud/bigquery/table.py\nrename to google/cloud/bigquery/table.py\n--- a/gcloud/bigquery/table.py\n+++ b/google/cloud/bigquery/table.py\n@@ -20,16 +20,16 @@\n \n import six\n \n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud._helpers import _microseconds_from_datetime\n-from gcloud._helpers import _millis_from_datetime\n-from gcloud.exceptions import NotFound\n-from gcloud.streaming.http_wrapper import Request\n-from gcloud.streaming.http_wrapper import make_api_request\n-from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n-from gcloud.streaming.transfer import Upload\n-from gcloud.bigquery.schema import SchemaField\n-from gcloud.bigquery._helpers import _rows_from_json\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud._helpers import _microseconds_from_datetime\n+from google.cloud._helpers import _millis_from_datetime\n+from google.cloud.exceptions import NotFound\n+from google.cloud.streaming.http_wrapper import Request\n+from google.cloud.streaming.http_wrapper import make_api_request\n+from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n+from google.cloud.streaming.transfer import Upload\n+from google.cloud.bigquery.schema import SchemaField\n+from google.cloud.bigquery._helpers import _rows_from_json\n \n \n _MARKER = object()\n@@ -44,7 +44,7 @@ class Table(object):\n :type name: str\n :param name: the name of the table\n \n- :type dataset: :class:`gcloud.bigquery.dataset.Dataset`\n+ :type dataset: :class:`google.cloud.bigquery.dataset.Dataset`\n :param dataset: The dataset which contains the table.\n \n :type schema: list of :class:`SchemaField`\n@@ -368,7 +368,8 @@ def view_query(self):\n def list_partitions(self, client=None):\n \"\"\"List the partitions in a table.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -388,10 +389,10 @@ def from_api_repr(cls, resource, dataset):\n :type resource: dict\n :param resource: table resource representation returned from the API\n \n- :type dataset: :class:`gcloud.bigquery.dataset.Dataset`\n+ :type dataset: :class:`google.cloud.bigquery.dataset.Dataset`\n :param dataset: The dataset containing the table.\n \n- :rtype: :class:`gcloud.bigquery.table.Table`\n+ :rtype: :class:`google.cloud.bigquery.table.Table`\n :returns: Table parsed from ``resource``.\n \"\"\"\n if ('tableReference' not in resource or\n@@ -406,11 +407,12 @@ def from_api_repr(cls, resource, dataset):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n- :rtype: :class:`gcloud.bigquery.client.Client`\n+ :rtype: :class:`google.cloud.bigquery.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -477,7 +479,8 @@ def create(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/tables/insert\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -494,7 +497,8 @@ def exists(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/tables/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -517,7 +521,8 @@ def reload(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/tables/get\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -540,7 +545,8 @@ def patch(self,\n See\n https://cloud.google.com/bigquery/docs/reference/v2/tables/patch\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -606,7 +612,8 @@ def update(self, client=None):\n See\n https://cloud.google.com/bigquery/docs/reference/v2/tables/update\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -621,7 +628,8 @@ def delete(self, client=None):\n See:\n https://cloud.google.com/bigquery/docs/reference/v2/tables/delete\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \"\"\"\n@@ -648,7 +656,8 @@ def fetch_data(self, max_results=None, page_token=None, client=None):\n :type page_token: str or ``NoneType``\n :param page_token: token representing a cursor into the table's rows.\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -714,7 +723,8 @@ def insert_data(self,\n schema of the template table. See:\n https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables\n \n- :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.bigquery.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current dataset.\n \n@@ -796,7 +806,7 @@ def upload_from_file(self,\n :type source_format: str\n :param source_format: one of 'CSV' or 'NEWLINE_DELIMITED_JSON'.\n job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`\n+ :meth:`google.cloud.bigquery.job.LoadJob`\n \n :type rewind: boolean\n :param rewind: If True, seek to the beginning of the file handle before\n@@ -813,49 +823,50 @@ def upload_from_file(self,\n \n :type allow_jagged_rows: boolean\n :param allow_jagged_rows: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type allow_quoted_newlines: boolean\n :param allow_quoted_newlines: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type create_disposition: str\n :param create_disposition: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type encoding: str\n :param encoding: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type field_delimiter: str\n :param field_delimiter: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type ignore_unknown_values: boolean\n :param ignore_unknown_values: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type max_bad_records: integer\n :param max_bad_records: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type quote_character: str\n :param quote_character: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type skip_leading_rows: integer\n :param skip_leading_rows: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n :type write_disposition: str\n :param write_disposition: job configuration option; see\n- :meth:`gcloud.bigquery.job.LoadJob`.\n+ :meth:`google.cloud.bigquery.job.LoadJob`.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current dataset.\n \n- :rtype: :class:`gcloud.bigquery.jobs.LoadTableFromStorageJob`\n+ :rtype: :class:`google.cloud.bigquery.jobs.LoadTableFromStorageJob`\n :returns: the job instance used to load the data (e.g., for\n querying status).\n :raises: :class:`ValueError` if ``size`` is not passed in and can not\ndiff --git a/gcloud/bigtable/__init__.py b/google/cloud/bigtable/__init__.py\nsimilarity index 96%\nrename from gcloud/bigtable/__init__.py\nrename to google/cloud/bigtable/__init__.py\n--- a/gcloud/bigtable/__init__.py\n+++ b/google/cloud/bigtable/__init__.py\n@@ -15,7 +15,7 @@\n \"\"\"Google Cloud Bigtable API package.\"\"\"\n \n \n-from gcloud.bigtable.client import Client\n+from google.cloud.bigtable.client import Client\n \n \n _ERR_MSG = \"\"\"\\\ndiff --git a/gcloud/bigtable/_generated/__init__.py b/google/cloud/bigtable/_generated/__init__.py\nsimilarity index 100%\nrename from gcloud/bigtable/_generated/__init__.py\nrename to google/cloud/bigtable/_generated/__init__.py\ndiff --git a/gcloud/bigtable/_generated/bigtable_instance_admin_pb2.py b/google/cloud/bigtable/_generated/bigtable_instance_admin_pb2.py\nsimilarity index 99%\nrename from gcloud/bigtable/_generated/bigtable_instance_admin_pb2.py\nrename to google/cloud/bigtable/_generated/bigtable_instance_admin_pb2.py\n--- a/gcloud/bigtable/_generated/bigtable_instance_admin_pb2.py\n+++ b/google/cloud/bigtable/_generated/bigtable_instance_admin_pb2.py\n@@ -14,7 +14,7 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.bigtable._generated import instance_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_instance__pb2\n+from google.cloud.bigtable._generated import instance_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_instance__pb2\n from google.longrunning import operations_pb2 as google_dot_longrunning_dot_operations__pb2\n from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2\n from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2\ndiff --git a/gcloud/bigtable/_generated/bigtable_pb2.py b/google/cloud/bigtable/_generated/bigtable_pb2.py\nsimilarity index 99%\nrename from gcloud/bigtable/_generated/bigtable_pb2.py\nrename to google/cloud/bigtable/_generated/bigtable_pb2.py\n--- a/gcloud/bigtable/_generated/bigtable_pb2.py\n+++ b/google/cloud/bigtable/_generated/bigtable_pb2.py\n@@ -14,7 +14,7 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.bigtable._generated import data_pb2 as google_dot_bigtable_dot_v2_dot_data__pb2\n+from google.cloud.bigtable._generated import data_pb2 as google_dot_bigtable_dot_v2_dot_data__pb2\n from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2\n from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2\n \ndiff --git a/gcloud/bigtable/_generated/bigtable_table_admin_pb2.py b/google/cloud/bigtable/_generated/bigtable_table_admin_pb2.py\nsimilarity index 99%\nrename from gcloud/bigtable/_generated/bigtable_table_admin_pb2.py\nrename to google/cloud/bigtable/_generated/bigtable_table_admin_pb2.py\n--- a/gcloud/bigtable/_generated/bigtable_table_admin_pb2.py\n+++ b/google/cloud/bigtable/_generated/bigtable_table_admin_pb2.py\n@@ -14,7 +14,7 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.bigtable._generated import table_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_table__pb2\n+from google.cloud.bigtable._generated import table_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_table__pb2\n from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2\n \n \ndiff --git a/gcloud/bigtable/_generated/common_pb2.py b/google/cloud/bigtable/_generated/common_pb2.py\nsimilarity index 100%\nrename from gcloud/bigtable/_generated/common_pb2.py\nrename to google/cloud/bigtable/_generated/common_pb2.py\ndiff --git a/gcloud/bigtable/_generated/data_pb2.py b/google/cloud/bigtable/_generated/data_pb2.py\nsimilarity index 100%\nrename from gcloud/bigtable/_generated/data_pb2.py\nrename to google/cloud/bigtable/_generated/data_pb2.py\ndiff --git a/gcloud/bigtable/_generated/instance_pb2.py b/google/cloud/bigtable/_generated/instance_pb2.py\nsimilarity index 98%\nrename from gcloud/bigtable/_generated/instance_pb2.py\nrename to google/cloud/bigtable/_generated/instance_pb2.py\n--- a/gcloud/bigtable/_generated/instance_pb2.py\n+++ b/google/cloud/bigtable/_generated/instance_pb2.py\n@@ -14,7 +14,7 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.bigtable._generated import common_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_common__pb2\n+from google.cloud.bigtable._generated import common_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_common__pb2\n \n \n DESCRIPTOR = _descriptor.FileDescriptor(\ndiff --git a/gcloud/bigtable/_generated/operations_grpc_pb2.py b/google/cloud/bigtable/_generated/operations_grpc_pb2.py\nsimilarity index 100%\nrename from gcloud/bigtable/_generated/operations_grpc_pb2.py\nrename to google/cloud/bigtable/_generated/operations_grpc_pb2.py\ndiff --git a/gcloud/bigtable/_generated/table_pb2.py b/google/cloud/bigtable/_generated/table_pb2.py\nsimilarity index 100%\nrename from gcloud/bigtable/_generated/table_pb2.py\nrename to google/cloud/bigtable/_generated/table_pb2.py\ndiff --git a/gcloud/bigtable/client.py b/google/cloud/bigtable/client.py\nsimilarity index 92%\nrename from gcloud/bigtable/client.py\nrename to google/cloud/bigtable/client.py\n--- a/gcloud/bigtable/client.py\n+++ b/google/cloud/bigtable/client.py\n@@ -19,27 +19,27 @@\n In the hierarchy of API concepts\n \n * a :class:`Client` owns an :class:`.Instance`\n-* a :class:`.Instance` owns a :class:`Table `\n-* a :class:`Table ` owns a\n- :class:`ColumnFamily <.column_family.ColumnFamily>`\n-* a :class:`Table ` owns a :class:`Row <.row.Row>`\n+* a :class:`.Instance` owns a :class:`~google.cloud.bigtable.table.Table`\n+* a :class:`~google.cloud.bigtable.table.Table` owns a\n+ :class:`~.column_family.ColumnFamily`\n+* a :class:`~google.cloud.bigtable.table.Table` owns a :class:`~.row.Row`\n (and all the cells in the row)\n \"\"\"\n \n \n from pkg_resources import get_distribution\n \n-from gcloud._helpers import make_stub\n-from gcloud.bigtable._generated import bigtable_instance_admin_pb2\n-from gcloud.bigtable._generated import bigtable_pb2\n-from gcloud.bigtable._generated import bigtable_table_admin_pb2\n-from gcloud.bigtable._generated import operations_grpc_pb2\n-from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n-from gcloud.bigtable.instance import Instance\n-from gcloud.bigtable.instance import _EXISTING_INSTANCE_LOCATION_ID\n-from gcloud.client import _ClientFactoryMixin\n-from gcloud.client import _ClientProjectMixin\n-from gcloud.credentials import get_credentials\n+from google.cloud._helpers import make_stub\n+from google.cloud.bigtable._generated import bigtable_instance_admin_pb2\n+from google.cloud.bigtable._generated import bigtable_pb2\n+from google.cloud.bigtable._generated import bigtable_table_admin_pb2\n+from google.cloud.bigtable._generated import operations_grpc_pb2\n+from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+from google.cloud.bigtable.instance import Instance\n+from google.cloud.bigtable.instance import _EXISTING_INSTANCE_LOCATION_ID\n+from google.cloud.client import _ClientFactoryMixin\n+from google.cloud.client import _ClientProjectMixin\n+from google.cloud.credentials import get_credentials\n \n \n TABLE_ADMIN_HOST = 'bigtableadmin.googleapis.com'\n@@ -67,8 +67,8 @@\n READ_ONLY_SCOPE = 'https://www.googleapis.com/auth/bigtable.data.readonly'\n \"\"\"Scope for reading table data.\"\"\"\n \n-DEFAULT_USER_AGENT = 'gcloud-python/{0}'.format(\n- get_distribution('gcloud').version)\n+DEFAULT_USER_AGENT = 'google-cloud-python/{0}'.format(\n+ get_distribution('google-cloud').version)\n \"\"\"The default user agent for API requests.\"\"\"\n \n \ndiff --git a/gcloud/bigtable/cluster.py b/google/cloud/bigtable/cluster.py\nsimilarity index 97%\nrename from gcloud/bigtable/cluster.py\nrename to google/cloud/bigtable/cluster.py\n--- a/gcloud/bigtable/cluster.py\n+++ b/google/cloud/bigtable/cluster.py\n@@ -17,13 +17,13 @@\n \n import re\n \n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n-from gcloud.operation import Operation\n-from gcloud.operation import _compute_type_url\n-from gcloud.operation import _register_type_url\n+from google.cloud.operation import Operation\n+from google.cloud.operation import _compute_type_url\n+from google.cloud.operation import _register_type_url\n \n \n _CLUSTER_NAME_RE = re.compile(r'^projects/(?P[^/]+)/'\ndiff --git a/gcloud/bigtable/column_family.py b/google/cloud/bigtable/column_family.py\nsimilarity index 98%\nrename from gcloud/bigtable/column_family.py\nrename to google/cloud/bigtable/column_family.py\n--- a/gcloud/bigtable/column_family.py\n+++ b/google/cloud/bigtable/column_family.py\n@@ -19,9 +19,9 @@\n \n from google.protobuf import duration_pb2\n \n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n \n \n@@ -206,7 +206,7 @@ class ColumnFamily(object):\n :param column_family_id: The ID of the column family. Must be of the\n form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the column family.\n \n :type gc_rule: :class:`GarbageCollectionRule`\ndiff --git a/gcloud/bigtable/instance.py b/google/cloud/bigtable/instance.py\nsimilarity index 94%\nrename from gcloud/bigtable/instance.py\nrename to google/cloud/bigtable/instance.py\n--- a/gcloud/bigtable/instance.py\n+++ b/google/cloud/bigtable/instance.py\n@@ -17,18 +17,18 @@\n \n import re\n \n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_messages_v2_pb2)\n-from gcloud.bigtable.cluster import Cluster\n-from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n-from gcloud.bigtable.table import Table\n-from gcloud.operation import Operation\n-from gcloud.operation import _compute_type_url\n-from gcloud.operation import _register_type_url\n+from google.cloud.bigtable.cluster import Cluster\n+from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+from google.cloud.bigtable.table import Table\n+from google.cloud.operation import Operation\n+from google.cloud.operation import _compute_type_url\n+from google.cloud.operation import _register_type_url\n \n \n _EXISTING_INSTANCE_LOCATION_ID = 'see-existing-cluster'\n@@ -85,7 +85,7 @@ class Instance(object):\n :type instance_id: str\n :param instance_id: The ID of the instance.\n \n- :type client: :class:`Client `\n+ :type client: :class:`Client `\n :param client: The client that owns the instance. Provides\n authorization and a project ID.\n \n@@ -131,7 +131,7 @@ def from_pb(cls, instance_pb, client):\n :type instance_pb: :class:`instance_pb2.Instance`\n :param instance_pb: A instance protobuf object.\n \n- :type client: :class:`Client `\n+ :type client: :class:`Client `\n :param client: The client that owns the instance.\n \n :rtype: :class:`Instance`\n@@ -327,7 +327,7 @@ def table(self, table_id):\n :type table_id: str\n :param table_id: The ID of the table.\n \n- :rtype: :class:`Table `\n+ :rtype: :class:`Table `\n :returns: The table owned by this instance.\n \"\"\"\n return Table(table_id, self)\n@@ -335,7 +335,7 @@ def table(self, table_id):\n def list_tables(self):\n \"\"\"List the tables in this instance.\n \n- :rtype: list of :class:`Table `\n+ :rtype: list of :class:`Table `\n :returns: The list of tables owned by the instance.\n :raises: :class:`ValueError ` if one of the\n returned tables has a name that is not of the expected format.\ndiff --git a/gcloud/bigtable/row.py b/google/cloud/bigtable/row.py\nsimilarity index 98%\nrename from gcloud/bigtable/row.py\nrename to google/cloud/bigtable/row.py\n--- a/gcloud/bigtable/row.py\n+++ b/google/cloud/bigtable/row.py\n@@ -19,12 +19,12 @@\n \n import six\n \n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud._helpers import _microseconds_from_datetime\n-from gcloud._helpers import _to_bytes\n-from gcloud.bigtable._generated import (\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud._helpers import _microseconds_from_datetime\n+from google.cloud._helpers import _to_bytes\n+from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n \n \n@@ -47,7 +47,7 @@ class Row(object):\n :type row_key: bytes\n :param row_key: The key for the current row.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the row.\n \"\"\"\n \n@@ -69,7 +69,7 @@ class _SetDeleteRow(Row):\n :type row_key: bytes\n :param row_key: The key for the current row.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the row.\n \"\"\"\n \n@@ -244,7 +244,7 @@ class DirectRow(_SetDeleteRow):\n :type row_key: bytes\n :param row_key: The key for the current row.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the row.\n \"\"\"\n \n@@ -434,7 +434,7 @@ class ConditionalRow(_SetDeleteRow):\n :type row_key: bytes\n :param row_key: The key for the current row.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the row.\n \n :type filter_: :class:`.RowFilter`\n@@ -662,7 +662,7 @@ class AppendRow(Row):\n :type row_key: bytes\n :param row_key: The key for the current row.\n \n- :type table: :class:`Table `\n+ :type table: :class:`Table `\n :param table: The table that owns the row.\n \"\"\"\n \ndiff --git a/gcloud/bigtable/row_data.py b/google/cloud/bigtable/row_data.py\nsimilarity index 99%\nrename from gcloud/bigtable/row_data.py\nrename to google/cloud/bigtable/row_data.py\n--- a/gcloud/bigtable/row_data.py\n+++ b/google/cloud/bigtable/row_data.py\n@@ -18,8 +18,8 @@\n import copy\n import six\n \n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud._helpers import _to_bytes\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud._helpers import _to_bytes\n \n \n class Cell(object):\ndiff --git a/gcloud/bigtable/row_filters.py b/google/cloud/bigtable/row_filters.py\nsimilarity index 99%\nrename from gcloud/bigtable/row_filters.py\nrename to google/cloud/bigtable/row_filters.py\n--- a/gcloud/bigtable/row_filters.py\n+++ b/google/cloud/bigtable/row_filters.py\n@@ -15,9 +15,9 @@\n \"\"\"Filters for Google Cloud Bigtable Row classes.\"\"\"\n \n \n-from gcloud._helpers import _microseconds_from_datetime\n-from gcloud._helpers import _to_bytes\n-from gcloud.bigtable._generated import (\n+from google.cloud._helpers import _microseconds_from_datetime\n+from google.cloud._helpers import _to_bytes\n+from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n \n \ndiff --git a/gcloud/bigtable/table.py b/google/cloud/bigtable/table.py\nsimilarity index 96%\nrename from gcloud/bigtable/table.py\nrename to google/cloud/bigtable/table.py\n--- a/gcloud/bigtable/table.py\n+++ b/google/cloud/bigtable/table.py\n@@ -14,19 +14,19 @@\n \n \"\"\"User friendly container for Google Cloud Bigtable Table.\"\"\"\n \n-from gcloud._helpers import _to_bytes\n-from gcloud.bigtable._generated import (\n+from google.cloud._helpers import _to_bytes\n+from google.cloud.bigtable._generated import (\n bigtable_pb2 as data_messages_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_messages_v2_pb2)\n-from gcloud.bigtable._generated import (\n+from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n-from gcloud.bigtable.column_family import _gc_rule_from_pb\n-from gcloud.bigtable.column_family import ColumnFamily\n-from gcloud.bigtable.row import AppendRow\n-from gcloud.bigtable.row import ConditionalRow\n-from gcloud.bigtable.row import DirectRow\n-from gcloud.bigtable.row_data import PartialRowsData\n+from google.cloud.bigtable.column_family import _gc_rule_from_pb\n+from google.cloud.bigtable.column_family import ColumnFamily\n+from google.cloud.bigtable.row import AppendRow\n+from google.cloud.bigtable.row import ConditionalRow\n+from google.cloud.bigtable.row import DirectRow\n+from google.cloud.bigtable.row_data import PartialRowsData\n \n \n class Table(object):\ndiff --git a/gcloud/client.py b/google/cloud/client.py\nsimilarity index 96%\nrename from gcloud/client.py\nrename to google/cloud/client.py\n--- a/gcloud/client.py\n+++ b/google/cloud/client.py\n@@ -17,9 +17,9 @@\n from oauth2client.service_account import ServiceAccountCredentials\n import six\n \n-from gcloud._helpers import _determine_default_project\n-from gcloud.connection import Connection\n-from gcloud.credentials import get_credentials\n+from google.cloud._helpers import _determine_default_project\n+from google.cloud.connection import Connection\n+from google.cloud.credentials import get_credentials\n \n \n class _ClientFactoryMixin(object):\n@@ -48,7 +48,7 @@ def from_service_account_json(cls, json_credentials_path, *args, **kwargs):\n :type kwargs: dict\n :param kwargs: Remaining keyword arguments to pass to constructor.\n \n- :rtype: :class:`gcloud.pubsub.client.Client`\n+ :rtype: :class:`google.cloud.pubsub.client.Client`\n :returns: The client created with the retrieved JSON credentials.\n :raises: :class:`TypeError` if there is a conflict with the kwargs\n and the credentials created by the factory.\n@@ -83,7 +83,7 @@ def from_service_account_p12(cls, client_email, private_key_path,\n :type kwargs: dict\n :param kwargs: Remaining keyword arguments to pass to constructor.\n \n- :rtype: :class:`gcloud.client.Client`\n+ :rtype: :class:`google.cloud.client.Client`\n :returns: The client created with the retrieved P12 credentials.\n :raises: :class:`TypeError` if there is a conflict with the kwargs\n and the credentials created by the factory.\ndiff --git a/gcloud/connection.py b/google/cloud/connection.py\nsimilarity index 98%\nrename from gcloud/connection.py\nrename to google/cloud/connection.py\n--- a/gcloud/connection.py\n+++ b/google/cloud/connection.py\n@@ -21,7 +21,7 @@\n \n import httplib2\n \n-from gcloud.exceptions import make_exception\n+from google.cloud.exceptions import make_exception\n \n \n API_BASE_URL = 'https://www.googleapis.com'\n@@ -63,8 +63,9 @@ class Connection(object):\n :param http: An optional HTTP object to make requests.\n \"\"\"\n \n- USER_AGENT = \"gcloud-python/{0}\".format(get_distribution('gcloud').version)\n- \"\"\"The user agent for gcloud-python requests.\"\"\"\n+ USER_AGENT = \"google-cloud-python/{0}\".format(\n+ get_distribution('google-cloud').version)\n+ \"\"\"The user agent for google-cloud-python requests.\"\"\"\n \n SCOPE = None\n \"\"\"The scopes required for authenticating with a service.\n@@ -310,7 +311,7 @@ def api_request(self, method, path, query_params=None,\n you shouldn't provide this and instead use\n the default for the library. Default is the\n latest API version supported by\n- gcloud-python.\n+ google-cloud-python.\n \n :type expect_json: bool\n :param expect_json: If True, this method will try to parse the\ndiff --git a/gcloud/credentials.py b/google/cloud/credentials.py\nsimilarity index 94%\nrename from gcloud/credentials.py\nrename to google/cloud/credentials.py\n--- a/gcloud/credentials.py\n+++ b/google/cloud/credentials.py\n@@ -21,9 +21,9 @@\n \n from oauth2client import client\n \n-from gcloud._helpers import UTC\n-from gcloud._helpers import _NOW\n-from gcloud._helpers import _microseconds_from_datetime\n+from google.cloud._helpers import UTC\n+from google.cloud._helpers import _NOW\n+from google.cloud._helpers import _microseconds_from_datetime\n \n \n def get_credentials():\n@@ -102,12 +102,12 @@ def _get_signed_query_params(credentials, expiration, string_to_sign):\n signed payload.\n \"\"\"\n if not hasattr(credentials, 'sign_blob'):\n+ auth_uri = ('http://gcloud-python.readthedocs.io/en/latest/'\n+ 'gcloud-auth.html#setting-up-a-service-account')\n raise AttributeError('you need a private key to sign credentials.'\n 'the credentials you are currently using %s '\n- 'just contains a token. see https://googlecloud'\n- 'platform.github.io/gcloud-python/stable/gcloud-'\n- 'auth.html#setting-up-a-service-account for more '\n- 'details.' % type(credentials))\n+ 'just contains a token. see %s for more '\n+ 'details.' % (type(credentials), auth_uri))\n \n _, signature_bytes = credentials.sign_blob(string_to_sign)\n signature = base64.b64encode(signature_bytes)\n@@ -172,7 +172,7 @@ def generate_signed_url(credentials, resource, expiration,\n See headers `reference`_ for more details on optional arguments.\n \n .. _Issue 922: https://github.com/GoogleCloudPlatform/\\\n- gcloud-python/issues/922\n+ google-cloud-python/issues/922\n .. _reference: https://cloud.google.com/storage/docs/reference-headers\n \n :type credentials: :class:`oauth2client.appengine.AppAssertionCredentials`\ndiff --git a/gcloud/datastore/__init__.py b/google/cloud/datastore/__init__.py\nsimilarity index 70%\nrename from gcloud/datastore/__init__.py\nrename to google/cloud/datastore/__init__.py\n--- a/gcloud/datastore/__init__.py\n+++ b/google/cloud/datastore/__init__.py\n@@ -16,7 +16,7 @@\n \n You'll typically use these to get started with the API::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>>\n >>> client = datastore.Client()\n >>> key = client.key('EntityKind', 1234)\n@@ -25,38 +25,39 @@\n \n The main concepts with this API are:\n \n-- :class:`gcloud.datastore.connection.Connection`\n+- :class:`google.cloud.datastore.connection.Connection`\n which represents a connection between your machine and the Cloud Datastore\n API.\n \n-- :class:`gcloud.datastore.client.Client`\n+- :class:`google.cloud.datastore.client.Client`\n which represents a project (string) and namespace (string) bundled with\n a connection and has convenience methods for constructing objects with that\n project / namespace.\n \n-- :class:`gcloud.datastore.entity.Entity`\n+- :class:`google.cloud.datastore.entity.Entity`\n which represents a single entity in the datastore\n (akin to a row in relational database world).\n \n-- :class:`gcloud.datastore.key.Key`\n+- :class:`google.cloud.datastore.key.Key`\n which represents a pointer to a particular entity in the datastore\n (akin to a unique identifier in relational database world).\n \n-- :class:`gcloud.datastore.query.Query`\n+- :class:`google.cloud.datastore.query.Query`\n which represents a lookup or search over the rows in the datastore.\n \n-- :class:`gcloud.datastore.transaction.Transaction`\n+- :class:`google.cloud.datastore.transaction.Transaction`\n which represents an all-or-none transaction and enables consistency\n when race conditions may occur.\n \"\"\"\n \n-from gcloud.datastore.batch import Batch\n-from gcloud.datastore.connection import Connection\n-from gcloud.datastore.client import Client\n-from gcloud.datastore.entity import Entity\n-from gcloud.datastore.key import Key\n-from gcloud.datastore.query import Query\n-from gcloud.datastore.transaction import Transaction\n+\n+from google.cloud.datastore.batch import Batch\n+from google.cloud.datastore.connection import Connection\n+from google.cloud.datastore.client import Client\n+from google.cloud.datastore.entity import Entity\n+from google.cloud.datastore.key import Key\n+from google.cloud.datastore.query import Query\n+from google.cloud.datastore.transaction import Transaction\n \n \n SCOPE = Connection.SCOPE\ndiff --git a/gcloud/datastore/_generated/__init__.py b/google/cloud/datastore/_generated/__init__.py\nsimilarity index 100%\nrename from gcloud/datastore/_generated/__init__.py\nrename to google/cloud/datastore/_generated/__init__.py\ndiff --git a/gcloud/datastore/_generated/datastore_grpc_pb2.py b/google/cloud/datastore/_generated/datastore_grpc_pb2.py\nsimilarity index 91%\nrename from gcloud/datastore/_generated/datastore_grpc_pb2.py\nrename to google/cloud/datastore/_generated/datastore_grpc_pb2.py\n--- a/gcloud/datastore/_generated/datastore_grpc_pb2.py\n+++ b/google/cloud/datastore/_generated/datastore_grpc_pb2.py\n@@ -1,19 +1,19 @@\n # BEGIN: Imports from datastore_pb2\n-from gcloud.datastore._generated.datastore_pb2 import AllocateIdsRequest\n-from gcloud.datastore._generated.datastore_pb2 import AllocateIdsResponse\n-from gcloud.datastore._generated.datastore_pb2 import BeginTransactionRequest\n-from gcloud.datastore._generated.datastore_pb2 import BeginTransactionResponse\n-from gcloud.datastore._generated.datastore_pb2 import CommitRequest\n-from gcloud.datastore._generated.datastore_pb2 import CommitResponse\n-from gcloud.datastore._generated.datastore_pb2 import LookupRequest\n-from gcloud.datastore._generated.datastore_pb2 import LookupResponse\n-from gcloud.datastore._generated.datastore_pb2 import Mutation\n-from gcloud.datastore._generated.datastore_pb2 import MutationResult\n-from gcloud.datastore._generated.datastore_pb2 import ReadOptions\n-from gcloud.datastore._generated.datastore_pb2 import RollbackRequest\n-from gcloud.datastore._generated.datastore_pb2 import RollbackResponse\n-from gcloud.datastore._generated.datastore_pb2 import RunQueryRequest\n-from gcloud.datastore._generated.datastore_pb2 import RunQueryResponse\n+from google.cloud.datastore._generated.datastore_pb2 import AllocateIdsRequest\n+from google.cloud.datastore._generated.datastore_pb2 import AllocateIdsResponse\n+from google.cloud.datastore._generated.datastore_pb2 import BeginTransactionRequest\n+from google.cloud.datastore._generated.datastore_pb2 import BeginTransactionResponse\n+from google.cloud.datastore._generated.datastore_pb2 import CommitRequest\n+from google.cloud.datastore._generated.datastore_pb2 import CommitResponse\n+from google.cloud.datastore._generated.datastore_pb2 import LookupRequest\n+from google.cloud.datastore._generated.datastore_pb2 import LookupResponse\n+from google.cloud.datastore._generated.datastore_pb2 import Mutation\n+from google.cloud.datastore._generated.datastore_pb2 import MutationResult\n+from google.cloud.datastore._generated.datastore_pb2 import ReadOptions\n+from google.cloud.datastore._generated.datastore_pb2 import RollbackRequest\n+from google.cloud.datastore._generated.datastore_pb2 import RollbackResponse\n+from google.cloud.datastore._generated.datastore_pb2 import RunQueryRequest\n+from google.cloud.datastore._generated.datastore_pb2 import RunQueryResponse\n # END: Imports from datastore_pb2\n import grpc\n from grpc.beta import implementations as beta_implementations\ndiff --git a/gcloud/datastore/_generated/datastore_pb2.py b/google/cloud/datastore/_generated/datastore_pb2.py\nsimilarity index 99%\nrename from gcloud/datastore/_generated/datastore_pb2.py\nrename to google/cloud/datastore/_generated/datastore_pb2.py\n--- a/gcloud/datastore/_generated/datastore_pb2.py\n+++ b/google/cloud/datastore/_generated/datastore_pb2.py\n@@ -14,8 +14,8 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.datastore._generated import entity_pb2 as google_dot_datastore_dot_v1_dot_entity__pb2\n-from gcloud.datastore._generated import query_pb2 as google_dot_datastore_dot_v1_dot_query__pb2\n+from google.cloud.datastore._generated import entity_pb2 as google_dot_datastore_dot_v1_dot_entity__pb2\n+from google.cloud.datastore._generated import query_pb2 as google_dot_datastore_dot_v1_dot_query__pb2\n \n \n DESCRIPTOR = _descriptor.FileDescriptor(\ndiff --git a/gcloud/datastore/_generated/entity_pb2.py b/google/cloud/datastore/_generated/entity_pb2.py\nsimilarity index 100%\nrename from gcloud/datastore/_generated/entity_pb2.py\nrename to google/cloud/datastore/_generated/entity_pb2.py\ndiff --git a/gcloud/datastore/_generated/query_pb2.py b/google/cloud/datastore/_generated/query_pb2.py\nsimilarity index 99%\nrename from gcloud/datastore/_generated/query_pb2.py\nrename to google/cloud/datastore/_generated/query_pb2.py\n--- a/gcloud/datastore/_generated/query_pb2.py\n+++ b/google/cloud/datastore/_generated/query_pb2.py\n@@ -14,7 +14,7 @@\n \n \n from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2\n-from gcloud.datastore._generated import entity_pb2 as google_dot_datastore_dot_v1_dot_entity__pb2\n+from google.cloud.datastore._generated import entity_pb2 as google_dot_datastore_dot_v1_dot_entity__pb2\n from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2\n from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2\n \ndiff --git a/gcloud/datastore/batch.py b/google/cloud/datastore/batch.py\nsimilarity index 91%\nrename from gcloud/datastore/batch.py\nrename to google/cloud/datastore/batch.py\n--- a/gcloud/datastore/batch.py\n+++ b/google/cloud/datastore/batch.py\n@@ -21,8 +21,8 @@\n https://cloud.google.com/datastore/docs/concepts/entities#Datastore_Batch_operations\n \"\"\"\n \n-from gcloud.datastore import helpers\n-from gcloud.datastore._generated import datastore_pb2 as _datastore_pb2\n+from google.cloud.datastore import helpers\n+from google.cloud.datastore._generated import datastore_pb2 as _datastore_pb2\n \n \n class Batch(object):\n@@ -34,7 +34,7 @@ class Batch(object):\n operations and the ``delete`` operation into the same mutation, and send\n them to the server in a single API request::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> batch = client.batch()\n >>> batch.put(entity1)\n@@ -57,7 +57,7 @@ class Batch(object):\n ... do_some_work(batch)\n ... raise Exception() # rolls back\n \n- :type client: :class:`gcloud.datastore.client.Client`\n+ :type client: :class:`google.cloud.datastore.client.Client`\n :param client: The client used to connect to datastore.\n \"\"\"\n \n@@ -107,7 +107,7 @@ def namespace(self):\n def connection(self):\n \"\"\"Getter for connection over which the batch will run.\n \n- :rtype: :class:`gcloud.datastore.connection.Connection`\n+ :rtype: :class:`google.cloud.datastore.connection.Connection`\n :returns: The connection over which the batch will run.\n \"\"\"\n return self._client.connection\n@@ -115,7 +115,7 @@ def connection(self):\n def _add_partial_key_entity_pb(self):\n \"\"\"Adds a new mutation for an entity with a partial key.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n :returns: The newly created entity protobuf that will be\n updated and sent with a commit.\n \"\"\"\n@@ -125,7 +125,7 @@ def _add_partial_key_entity_pb(self):\n def _add_complete_key_entity_pb(self):\n \"\"\"Adds a new mutation for an entity with a completed key.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n :returns: The newly created entity protobuf that will be\n updated and sent with a commit.\n \"\"\"\n@@ -138,7 +138,7 @@ def _add_complete_key_entity_pb(self):\n def _add_delete_key_pb(self):\n \"\"\"Adds a new mutation for a key to be deleted.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Key`\n :returns: The newly created key protobuf that will be\n deleted when sent with a commit.\n \"\"\"\n@@ -180,7 +180,7 @@ def put(self, entity):\n the key for the ``entity`` passed in is updated to match the key ID\n assigned by the server.\n \n- :type entity: :class:`gcloud.datastore.entity.Entity`\n+ :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: the entity to be saved.\n \n :raises: ValueError if entity has no key assigned, or if the key's\n@@ -203,7 +203,7 @@ def put(self, entity):\n def delete(self, key):\n \"\"\"Remember a key to be deleted during :meth:`commit`.\n \n- :type key: :class:`gcloud.datastore.key.Key`\n+ :type key: :class:`google.cloud.datastore.key.Key`\n :param key: the key to be deleted.\n \n :raises: ValueError if key is not complete, or if the key's\n@@ -225,7 +225,7 @@ def begin(self):\n statement, however it can be called explicitly if you don't want\n to use a context manager.\n \n- Overridden by :class:`gcloud.datastore.transaction.Transaction`.\n+ Overridden by :class:`google.cloud.datastore.transaction.Transaction`.\n \n :raises: :class:`ValueError` if the batch has already begun.\n \"\"\"\n@@ -266,7 +266,7 @@ def rollback(self):\n \n Marks the batch as aborted (can't be used again).\n \n- Overridden by :class:`gcloud.datastore.transaction.Transaction`.\n+ Overridden by :class:`google.cloud.datastore.transaction.Transaction`.\n \"\"\"\n self._status = self._ABORTED\n \n@@ -290,10 +290,10 @@ def _assign_entity_to_pb(entity_pb, entity):\n \n Helper method for ``Batch.put``.\n \n- :type entity_pb: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :type entity_pb: :class:`.datastore._generated.entity_pb2.Entity`\n :param entity_pb: The entity owned by a mutation.\n \n- :type entity: :class:`gcloud.datastore.entity.Entity`\n+ :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity being updated within the batch / transaction.\n \"\"\"\n bare_entity_pb = helpers.entity_to_protobuf(entity)\ndiff --git a/gcloud/datastore/client.py b/google/cloud/datastore/client.py\nsimilarity index 84%\nrename from gcloud/datastore/client.py\nrename to google/cloud/datastore/client.py\n--- a/gcloud/datastore/client.py\n+++ b/google/cloud/datastore/client.py\n@@ -15,18 +15,19 @@\n \n import os\n \n-from gcloud._helpers import _LocalStack\n-from gcloud._helpers import _determine_default_project as _base_default_project\n-from gcloud.client import _ClientProjectMixin\n-from gcloud.client import Client as _BaseClient\n-from gcloud.datastore import helpers\n-from gcloud.datastore.connection import Connection\n-from gcloud.datastore.batch import Batch\n-from gcloud.datastore.entity import Entity\n-from gcloud.datastore.key import Key\n-from gcloud.datastore.query import Query\n-from gcloud.datastore.transaction import Transaction\n-from gcloud.environment_vars import GCD_DATASET\n+from google.cloud._helpers import _LocalStack\n+from google.cloud._helpers import (\n+ _determine_default_project as _base_default_project)\n+from google.cloud.client import _ClientProjectMixin\n+from google.cloud.client import Client as _BaseClient\n+from google.cloud.datastore import helpers\n+from google.cloud.datastore.connection import Connection\n+from google.cloud.datastore.batch import Batch\n+from google.cloud.datastore.entity import Entity\n+from google.cloud.datastore.key import Key\n+from google.cloud.datastore.query import Query\n+from google.cloud.datastore.transaction import Transaction\n+from google.cloud.environment_vars import GCD_DATASET\n \n \n _MAX_LOOPS = 128\n@@ -45,7 +46,7 @@ def _determine_default_project(project=None):\n implicit environments are:\n \n * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)\n- * GCLOUD_PROJECT environment variable\n+ * GOOGLE_CLOUD_PROJECT environment variable\n * Google App Engine application ID\n * Google Compute Engine project ID (from metadata server)\n \n@@ -71,13 +72,13 @@ def _extended_lookup(connection, project, key_pbs,\n \n Helper function for :meth:`Client.get_multi`.\n \n- :type connection: :class:`gcloud.datastore.connection.Connection`\n+ :type connection: :class:`google.cloud.datastore.connection.Connection`\n :param connection: The connection used to connect to datastore.\n \n :type project: string\n :param project: The project to make the request for.\n \n- :type key_pbs: list of :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :type key_pbs: list of :class:`.datastore._generated.entity_pb2.Key`\n :param key_pbs: The keys to retrieve from the datastore.\n \n :type missing: list\n@@ -99,7 +100,7 @@ def _extended_lookup(connection, project, key_pbs,\n the given transaction. Incompatible with\n ``eventual==True``.\n \n- :rtype: list of :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :rtype: list of :class:`.datastore._generated.entity_pb2.Entity`\n :returns: The requested entities.\n :raises: :class:`ValueError` if missing / deferred are not null or\n empty list.\n@@ -182,7 +183,7 @@ def _push_batch(self, batch):\n \n \"Protected\", intended for use by batch / transaction context mgrs.\n \n- :type batch: :class:`gcloud.datastore.batch.Batch`, or an object\n+ :type batch: :class:`google.cloud.datastore.batch.Batch`, or an object\n implementing its API.\n :param batch: newly-active batch/transaction.\n \"\"\"\n@@ -194,7 +195,7 @@ def _pop_batch(self):\n \"Protected\", intended for use by batch / transaction context mgrs.\n \n :raises: IndexError if the stack is empty.\n- :rtype: :class:`gcloud.datastore.batch.Batch`, or an object\n+ :rtype: :class:`google.cloud.datastore.batch.Batch`, or an object\n implementing its API.\n :returns: the top-most batch/transaction, after removing it.\n \"\"\"\n@@ -204,7 +205,7 @@ def _pop_batch(self):\n def current_batch(self):\n \"\"\"Currently-active batch.\n \n- :rtype: :class:`gcloud.datastore.batch.Batch`, or an object\n+ :rtype: :class:`google.cloud.datastore.batch.Batch`, or an object\n implementing its API, or ``NoneType`` (if no batch is active).\n :returns: The batch/transaction at the top of the batch stack.\n \"\"\"\n@@ -214,9 +215,9 @@ def current_batch(self):\n def current_transaction(self):\n \"\"\"Currently-active transaction.\n \n- :rtype: :class:`gcloud.datastore.transaction.Transaction`, or an object\n- implementing its API, or ``NoneType`` (if no transaction is\n- active).\n+ :rtype: :class:`google.cloud.datastore.transaction.Transaction`, or an\n+ object implementing its API, or ``NoneType`` (if no transaction\n+ is active).\n :returns: The transaction at the top of the batch stack.\n \"\"\"\n transaction = self.current_batch\n@@ -232,7 +233,7 @@ def get(self, key, missing=None, deferred=None, transaction=None):\n The backend API does not make a distinction between a single key or\n multiple keys in a lookup request.\n \n- :type key: :class:`gcloud.datastore.key.Key`\n+ :type key: :class:`google.cloud.datastore.key.Key`\n :param key: The key to be retrieved from the datastore.\n \n :type missing: list\n@@ -244,11 +245,11 @@ def get(self, key, missing=None, deferred=None, transaction=None):\n :param deferred: (Optional) If a list is passed, the keys returned\n by the backend as \"deferred\" will be copied into it.\n \n- :type transaction: :class:`gcloud.datastore.transaction.Transaction`\n+ :type transaction: :class:`~.datastore.transaction.Transaction`\n :param transaction: (Optional) Transaction to use for read consistency.\n If not passed, uses current transaction, if set.\n \n- :rtype: :class:`gcloud.datastore.entity.Entity` or ``NoneType``\n+ :rtype: :class:`google.cloud.datastore.entity.Entity` or ``NoneType``\n :returns: The requested entity if it exists.\n \"\"\"\n entities = self.get_multi(keys=[key], missing=missing,\n@@ -259,7 +260,7 @@ def get(self, key, missing=None, deferred=None, transaction=None):\n def get_multi(self, keys, missing=None, deferred=None, transaction=None):\n \"\"\"Retrieve entities, along with their attributes.\n \n- :type keys: list of :class:`gcloud.datastore.key.Key`\n+ :type keys: list of :class:`google.cloud.datastore.key.Key`\n :param keys: The keys to be retrieved from the datastore.\n \n :type missing: list\n@@ -272,11 +273,11 @@ def get_multi(self, keys, missing=None, deferred=None, transaction=None):\n by the backend as \"deferred\" will be copied into it.\n If the list is not empty, an error will occur.\n \n- :type transaction: :class:`gcloud.datastore.transaction.Transaction`\n+ :type transaction: :class:`~.datastore.transaction.Transaction`\n :param transaction: (Optional) Transaction to use for read consistency.\n If not passed, uses current transaction, if set.\n \n- :rtype: list of :class:`gcloud.datastore.entity.Entity`\n+ :rtype: list of :class:`google.cloud.datastore.entity.Entity`\n :returns: The requested entities.\n :raises: :class:`ValueError` if one or more of ``keys`` has a project\n which does not match our project.\n@@ -323,7 +324,7 @@ def put(self, entity):\n The backend API does not make a distinction between a single\n entity or multiple entities in a commit request.\n \n- :type entity: :class:`gcloud.datastore.entity.Entity`\n+ :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity to be saved to the datastore.\n \"\"\"\n self.put_multi(entities=[entity])\n@@ -331,7 +332,7 @@ def put(self, entity):\n def put_multi(self, entities):\n \"\"\"Save entities in the Cloud Datastore.\n \n- :type entities: list of :class:`gcloud.datastore.entity.Entity`\n+ :type entities: list of :class:`google.cloud.datastore.entity.Entity`\n :param entities: The entities to be saved to the datastore.\n \n :raises: :class:`ValueError` if ``entities`` is a single entity.\n@@ -363,7 +364,7 @@ def delete(self, key):\n The backend API does not make a distinction between a single key or\n multiple keys in a commit request.\n \n- :type key: :class:`gcloud.datastore.key.Key`\n+ :type key: :class:`google.cloud.datastore.key.Key`\n :param key: The key to be deleted from the datastore.\n \"\"\"\n self.delete_multi(keys=[key])\n@@ -371,7 +372,7 @@ def delete(self, key):\n def delete_multi(self, keys):\n \"\"\"Delete keys from the Cloud Datastore.\n \n- :type keys: list of :class:`gcloud.datastore.key.Key`\n+ :type keys: list of :class:`google.cloud.datastore.key.Key`\n :param keys: The keys to be deleted from the Datastore.\n \"\"\"\n if not keys:\n@@ -393,13 +394,13 @@ def delete_multi(self, keys):\n def allocate_ids(self, incomplete_key, num_ids):\n \"\"\"Allocate a list of IDs from a partial key.\n \n- :type incomplete_key: :class:`gcloud.datastore.key.Key`\n+ :type incomplete_key: :class:`google.cloud.datastore.key.Key`\n :param incomplete_key: Partial key to use as base for allocated IDs.\n \n :type num_ids: int\n :param num_ids: The number of IDs to allocate.\n \n- :rtype: list of :class:`gcloud.datastore.key.Key`\n+ :rtype: list of :class:`google.cloud.datastore.key.Key`\n :returns: The (complete) keys allocated with ``incomplete_key`` as\n root.\n :raises: :class:`ValueError` if ``incomplete_key`` is not a\n@@ -420,7 +421,7 @@ def allocate_ids(self, incomplete_key, num_ids):\n for allocated_id in allocated_ids]\n \n def key(self, *path_args, **kwargs):\n- \"\"\"Proxy to :class:`gcloud.datastore.key.Key`.\n+ \"\"\"Proxy to :class:`google.cloud.datastore.key.Key`.\n \n Passes our ``project``.\n \"\"\"\n@@ -432,27 +433,27 @@ def key(self, *path_args, **kwargs):\n return Key(*path_args, **kwargs)\n \n def batch(self):\n- \"\"\"Proxy to :class:`gcloud.datastore.batch.Batch`.\"\"\"\n+ \"\"\"Proxy to :class:`google.cloud.datastore.batch.Batch`.\"\"\"\n return Batch(self)\n \n def transaction(self):\n- \"\"\"Proxy to :class:`gcloud.datastore.transaction.Transaction`.\"\"\"\n+ \"\"\"Proxy to :class:`google.cloud.datastore.transaction.Transaction`.\"\"\"\n return Transaction(self)\n \n def query(self, **kwargs):\n- \"\"\"Proxy to :class:`gcloud.datastore.query.Query`.\n+ \"\"\"Proxy to :class:`google.cloud.datastore.query.Query`.\n \n Passes our ``project``.\n \n Using query to search a datastore::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> query = client.query(kind='MyKind')\n >>> query.add_filter('property', '=', 'val')\n \n Using the query iterator's\n- :meth:`next_page() ` method:\n+ :meth:`~google.cloud.datastore.query.Iterator.next_page` method:\n \n >>> query_iter = query.fetch()\n >>> entities, more_results, cursor = query_iter.next_page()\n@@ -470,10 +471,10 @@ def query(self, **kwargs):\n \n :type kwargs: dict\n :param kwargs: Parameters for initializing and instance of\n- :class:`gcloud.datastore.query.Query`.\n+ :class:`google.cloud.datastore.query.Query`.\n \n- :rtype: :class:`gcloud.datastore.query.Query`\n- :returns: An instance of :class:`gcloud.datastore.query.Query`\n+ :rtype: :class:`google.cloud.datastore.query.Query`\n+ :returns: An instance of :class:`google.cloud.datastore.query.Query`\n \"\"\"\n if 'client' in kwargs:\n raise TypeError('Cannot pass client')\ndiff --git a/gcloud/datastore/connection.py b/google/cloud/datastore/connection.py\nsimilarity index 93%\nrename from gcloud/datastore/connection.py\nrename to google/cloud/datastore/connection.py\n--- a/gcloud/datastore/connection.py\n+++ b/google/cloud/datastore/connection.py\n@@ -12,23 +12,23 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Connections to gcloud datastore API servers.\"\"\"\n+\"\"\"Connections to Google Cloud Datastore API servers.\"\"\"\n \n import os\n \n from google.rpc import status_pb2\n \n-from gcloud._helpers import make_stub\n-from gcloud import connection as connection_module\n-from gcloud.environment_vars import GCD_HOST\n-from gcloud.exceptions import Conflict\n-from gcloud.exceptions import make_exception\n-from gcloud.datastore._generated import datastore_pb2 as _datastore_pb2\n+from google.cloud._helpers import make_stub\n+from google.cloud import connection as connection_module\n+from google.cloud.environment_vars import GCD_HOST\n+from google.cloud.exceptions import Conflict\n+from google.cloud.exceptions import make_exception\n+from google.cloud.datastore._generated import datastore_pb2 as _datastore_pb2\n # pylint: disable=ungrouped-imports\n try:\n from grpc import StatusCode\n from grpc._channel import _Rendezvous\n- from gcloud.datastore._generated import datastore_grpc_pb2\n+ from google.cloud.datastore._generated import datastore_grpc_pb2\n except ImportError: # pragma: NO COVER\n _HAVE_GRPC = False\n datastore_grpc_pb2 = None\n@@ -53,7 +53,7 @@ class _DatastoreAPIOverHttp(object):\n Methods make bare API requests without any helpers for constructing\n the requests or parsing the responses.\n \n- :type connection: :class:`gcloud.datastore.connection.Connection`\n+ :type connection: :class:`google.cloud.datastore.connection.Connection`\n :param connection: A connection object that contains helpful\n information for making requests.\n \"\"\"\n@@ -77,8 +77,8 @@ def _request(self, project, method, data):\n \n :rtype: string\n :returns: The string response content from the API call.\n- :raises: :class:`gcloud.exceptions.GCloudError` if the response\n- code is not 200 OK.\n+ :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the\n+ response code is not 200 OK.\n \"\"\"\n headers = {\n 'Content-Type': 'application/x-protobuf',\n@@ -227,7 +227,7 @@ class _DatastoreAPIOverGRPC(object):\n Methods make bare API requests without any helpers for constructing\n the requests or parsing the responses.\n \n- :type connection: :class:`gcloud.datastore.connection.Connection`\n+ :type connection: :class:`google.cloud.datastore.connection.Connection`\n :param connection: A connection object that contains helpful\n information for making requests.\n \"\"\"\n@@ -423,12 +423,12 @@ def lookup(self, project, key_pbs,\n Maps the ``DatastoreService.Lookup`` protobuf RPC.\n \n This uses mostly protobufs\n- (:class:`gcloud.datastore._generated.entity_pb2.Key` as input and\n- :class:`gcloud.datastore._generated.entity_pb2.Entity` as output). It\n- is used under the hood in\n+ (:class:`google.cloud.datastore._generated.entity_pb2.Key` as input\n+ and :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n+ as output). It is used under the hood in\n :meth:`Client.get() <.datastore.client.Client.get>`:\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client(project='project')\n >>> key = client.key('MyKind', 1234)\n >>> client.get(key)\n@@ -443,7 +443,7 @@ def lookup(self, project, key_pbs,\n :param project: The project to look up the keys in.\n \n :type key_pbs: list of\n- :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :class:`google.cloud.datastore._generated.entity_pb2.Key`\n :param key_pbs: The keys to retrieve from the datastore.\n \n :type eventual: bool\n@@ -459,9 +459,9 @@ def lookup(self, project, key_pbs,\n :rtype: tuple\n :returns: A triple of (``results``, ``missing``, ``deferred``) where\n both ``results`` and ``missing`` are lists of\n- :class:`gcloud.datastore._generated.entity_pb2.Entity` and\n- ``deferred`` is a list of\n- :class:`gcloud.datastore._generated.entity_pb2.Key`.\n+ :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n+ and ``deferred`` is a list of\n+ :class:`google.cloud.datastore._generated.entity_pb2.Key`.\n \"\"\"\n lookup_request = _datastore_pb2.LookupRequest()\n _set_read_options(lookup_request, eventual, transaction_id)\n@@ -485,15 +485,15 @@ def run_query(self, project, query_pb, namespace=None,\n matching the query.\n \n You typically wouldn't use this method directly, in favor of the\n- :meth:`gcloud.datastore.query.Query.fetch` method.\n+ :meth:`google.cloud.datastore.query.Query.fetch` method.\n \n- Under the hood, the :class:`gcloud.datastore.query.Query` class\n+ Under the hood, the :class:`google.cloud.datastore.query.Query` class\n uses this method to fetch data.\n \n :type project: string\n :param project: The project over which to run the query.\n \n- :type query_pb: :class:`gcloud.datastore._generated.query_pb2.Query`\n+ :type query_pb: :class:`.datastore._generated.query_pb2.Query`\n :param query_pb: The Protobuf representing the query to run.\n \n :type namespace: string\n@@ -604,10 +604,10 @@ def allocate_ids(self, project, key_pbs):\n :param project: The project to which the transaction belongs.\n \n :type key_pbs: list of\n- :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :class:`google.cloud.datastore._generated.entity_pb2.Key`\n :param key_pbs: The keys for which the backend should allocate IDs.\n \n- :rtype: list of :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :rtype: list of :class:`.datastore._generated.entity_pb2.Key`\n :returns: An equal number of keys, with IDs filled in by the backend.\n \"\"\"\n request = _datastore_pb2.AllocateIdsRequest()\n@@ -641,7 +641,7 @@ def _add_keys_to_request(request_field_pb, key_pbs):\n :type request_field_pb: `RepeatedCompositeFieldContainer`\n :param request_field_pb: A repeated proto field that contains keys.\n \n- :type key_pbs: list of :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :type key_pbs: list of :class:`.datastore._generated.entity_pb2.Key`\n :param key_pbs: The keys to add to a request.\n \"\"\"\n for key_pb in key_pbs:\ndiff --git a/gcloud/datastore/entity.py b/google/cloud/datastore/entity.py\nsimilarity index 91%\nrename from gcloud/datastore/entity.py\nrename to google/cloud/datastore/entity.py\n--- a/gcloud/datastore/entity.py\n+++ b/google/cloud/datastore/entity.py\n@@ -15,7 +15,7 @@\n \"\"\"Class for representing a single entity in the Cloud Datastore.\"\"\"\n \n \n-from gcloud._helpers import _ensure_tuple_or_list\n+from google.cloud._helpers import _ensure_tuple_or_list\n \n \n class Entity(dict):\n@@ -24,7 +24,7 @@ class Entity(dict):\n An entity storing the actual instance of data.\n \n Each entity is officially represented with a\n- :class:`gcloud.datastore.key.Key` class, however it is possible that\n+ :class:`google.cloud.datastore.key.Key` class, however it is possible that\n you might create an Entity with only a partial Key (that is, a Key\n with a Kind, and possibly a parent, but without an ID). In such a\n case, the datastore service will automatically assign an ID to the\n@@ -37,9 +37,9 @@ class Entity(dict):\n This means you could take an existing entity and change the key\n to duplicate the object.\n \n- Use :func:`gcloud.datastore.get` to retrieve an existing entity.\n+ Use :func:`google.cloud.datastore.get` to retrieve an existing entity.\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> client.get(key)\n \n@@ -68,7 +68,7 @@ class Entity(dict):\n Python3), will be saved using the 'blob_value' field, without\n any decoding / encoding step.\n \n- :type key: :class:`gcloud.datastore.key.Key`\n+ :type key: :class:`google.cloud.datastore.key.Key`\n :param key: Optional key to be set on entity.\n \n :type exclude_from_indexes: tuple of string\n@@ -82,7 +82,7 @@ def __init__(self, key=None, exclude_from_indexes=()):\n self._exclude_from_indexes = set(_ensure_tuple_or_list(\n 'exclude_from_indexes', exclude_from_indexes))\n # NOTE: This will be populated when parsing a protobuf in\n- # gcloud.datastore.helpers.entity_from_protobuf.\n+ # google.cloud.datastore.helpers.entity_from_protobuf.\n self._meanings = {}\n \n def __eq__(self, other):\n@@ -118,7 +118,7 @@ def kind(self):\n \"\"\"Get the kind of the current entity.\n \n .. note::\n- This relies entirely on the :class:`gcloud.datastore.key.Key`\n+ This relies entirely on the :class:`google.cloud.datastore.key.Key`\n set on the entity. That means that we're not storing the kind\n of the entity at all, just the properties and a pointer to a\n Key which knows its Kind.\ndiff --git a/gcloud/datastore/helpers.py b/google/cloud/datastore/helpers.py\nsimilarity index 90%\nrename from gcloud/datastore/helpers.py\nrename to google/cloud/datastore/helpers.py\n--- a/gcloud/datastore/helpers.py\n+++ b/google/cloud/datastore/helpers.py\n@@ -24,11 +24,13 @@\n from google.type import latlng_pb2\n import six\n \n-from gcloud._helpers import _datetime_to_pb_timestamp\n-from gcloud._helpers import _pb_timestamp_to_datetime\n-from gcloud.datastore._generated import entity_pb2 as _entity_pb2\n-from gcloud.datastore.entity import Entity\n-from gcloud.datastore.key import Key\n+# pylint: disable=ungrouped-imports\n+from google.cloud._helpers import _datetime_to_pb_timestamp\n+from google.cloud._helpers import _pb_timestamp_to_datetime\n+from google.cloud.datastore._generated import entity_pb2 as _entity_pb2\n+from google.cloud.datastore.entity import Entity\n+from google.cloud.datastore.key import Key\n+# pylint: enable=ungrouped-imports\n \n __all__ = ('entity_from_protobuf', 'key_from_protobuf')\n \n@@ -36,7 +38,7 @@\n def _get_meaning(value_pb, is_list=False):\n \"\"\"Get the meaning from a protobuf value.\n \n- :type value_pb: :class:`gcloud.datastore._generated.entity_pb2.Value`\n+ :type value_pb: :class:`google.cloud.datastore._generated.entity_pb2.Value`\n :param value_pb: The protobuf value to be checked for an\n associated meaning.\n \n@@ -77,13 +79,13 @@ def _get_meaning(value_pb, is_list=False):\n def _new_value_pb(entity_pb, name):\n \"\"\"Add (by name) a new ``Value`` protobuf to an entity protobuf.\n \n- :type entity_pb: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :type entity_pb: :class:`.datastore._generated.entity_pb2.Entity`\n :param entity_pb: An entity protobuf to add a new property to.\n \n :type name: string\n :param name: The name of the new property.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Value`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Value`\n :returns: The new ``Value`` protobuf that was added to the entity.\n \"\"\"\n return entity_pb.properties.get_or_create(name)\n@@ -92,7 +94,7 @@ def _new_value_pb(entity_pb, name):\n def _property_tuples(entity_pb):\n \"\"\"Iterator of name, ``Value`` tuples from entity properties.\n \n- :type entity_pb: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :type entity_pb: :class:`.datastore._generated.entity_pb2.Entity`\n :param entity_pb: An entity protobuf to add a new property to.\n \n :rtype: :class:`generator`\n@@ -108,10 +110,10 @@ def entity_from_protobuf(pb):\n The protobuf should be one returned from the Cloud Datastore\n Protobuf API.\n \n- :type pb: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :type pb: :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n :param pb: The Protobuf representing the entity.\n \n- :rtype: :class:`gcloud.datastore.entity.Entity`\n+ :rtype: :class:`google.cloud.datastore.entity.Entity`\n :returns: The entity derived from the protobuf.\n \"\"\"\n key = None\n@@ -159,7 +161,7 @@ def _set_pb_meaning_from_entity(entity, name, value, value_pb,\n is_list=False):\n \"\"\"Add meaning information (from an entity) to a protobuf.\n \n- :type entity: :class:`gcloud.datastore.entity.Entity`\n+ :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity to be turned into a protobuf.\n \n :type name: string\n@@ -168,7 +170,7 @@ def _set_pb_meaning_from_entity(entity, name, value, value_pb,\n :type value: object\n :param value: The current value stored as property ``name``.\n \n- :type value_pb: :class:`gcloud.datastore._generated.entity_pb2.Value`\n+ :type value_pb: :class:`google.cloud.datastore._generated.entity_pb2.Value`\n :param value_pb: The protobuf value to add meaning / meanings to.\n \n :type is_list: bool\n@@ -200,10 +202,10 @@ def _set_pb_meaning_from_entity(entity, name, value, value_pb,\n def entity_to_protobuf(entity):\n \"\"\"Converts an entity into a protobuf.\n \n- :type entity: :class:`gcloud.datastore.entity.Entity`\n+ :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity to be turned into a protobuf.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Entity`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Entity`\n :returns: The protobuf representing the entity.\n \"\"\"\n entity_pb = _entity_pb2.Entity()\n@@ -241,10 +243,10 @@ def key_from_protobuf(pb):\n The protobuf should be one returned from the Cloud Datastore\n Protobuf API.\n \n- :type pb: :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :type pb: :class:`google.cloud.datastore._generated.entity_pb2.Key`\n :param pb: The Protobuf representing the key.\n \n- :rtype: :class:`gcloud.datastore.key.Key`\n+ :rtype: :class:`google.cloud.datastore.key.Key`\n :returns: a new `Key` instance\n \"\"\"\n path_args = []\n@@ -277,7 +279,7 @@ def _pb_attr_value(val):\n \n Certain value types need to be coerced into a different type (such\n as a `datetime.datetime` into an integer timestamp, or a\n- `gcloud.datastore.key.Key` into a Protobuf representation. This\n+ `google.cloud.datastore.key.Key` into a Protobuf representation. This\n function handles that for you.\n \n .. note::\n@@ -292,7 +294,7 @@ def _pb_attr_value(val):\n >>> _pb_attr_value('my_string')\n ('string_value', 'my_string')\n \n- :type val: `datetime.datetime`, :class:`gcloud.datastore.key.Key`,\n+ :type val: `datetime.datetime`, :class:`google.cloud.datastore.key.Key`,\n bool, float, integer, string\n :param val: The value to be scrutinized.\n \n@@ -339,7 +341,7 @@ def _get_value_from_value_pb(value_pb):\n Some work is done to coerce the return value into a more useful type\n (particularly in the case of a timestamp value, or a key value).\n \n- :type value_pb: :class:`gcloud.datastore._generated.entity_pb2.Value`\n+ :type value_pb: :class:`google.cloud.datastore._generated.entity_pb2.Value`\n :param value_pb: The Value Protobuf.\n \n :rtype: object\n@@ -399,12 +401,12 @@ def _set_protobuf_value(value_pb, val):\n Some value types (entities, keys, lists) cannot be directly\n assigned; this function handles them correctly.\n \n- :type value_pb: :class:`gcloud.datastore._generated.entity_pb2.Value`\n+ :type value_pb: :class:`google.cloud.datastore._generated.entity_pb2.Value`\n :param value_pb: The value protobuf to which the value is being assigned.\n \n :type val: :class:`datetime.datetime`, boolean, float, integer, string,\n- :class:`gcloud.datastore.key.Key`,\n- :class:`gcloud.datastore.entity.Entity`\n+ :class:`google.cloud.datastore.key.Key`,\n+ :class:`google.cloud.datastore.entity.Entity`\n :param val: The value to be assigned.\n \"\"\"\n attr, val = _pb_attr_value(val)\ndiff --git a/gcloud/datastore/key.py b/google/cloud/datastore/key.py\nsimilarity index 95%\nrename from gcloud/datastore/key.py\nrename to google/cloud/datastore/key.py\n--- a/gcloud/datastore/key.py\n+++ b/google/cloud/datastore/key.py\n@@ -12,12 +12,12 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud datastore keys.\"\"\"\n+\"\"\"Create / interact with Google Cloud Datastore keys.\"\"\"\n \n import copy\n import six\n \n-from gcloud.datastore._generated import entity_pb2 as _entity_pb2\n+from google.cloud.datastore._generated import entity_pb2 as _entity_pb2\n \n \n class Key(object):\n@@ -53,7 +53,7 @@ class Key(object):\n \n * namespace (string): A namespace identifier for the key.\n * project (string): The project associated with the key.\n- * parent (:class:`gcloud.datastore.key.Key`): The parent of the key.\n+ * parent (:class:`google.cloud.datastore.key.Key`): The parent of the key.\n \n The project argument is required unless it has been set implicitly.\n \"\"\"\n@@ -193,7 +193,7 @@ def _clone(self):\n Most attributes are simple types, so don't require copying. Other\n attributes like ``parent`` are long-lived and so we re-use them.\n \n- :rtype: :class:`gcloud.datastore.key.Key`\n+ :rtype: :class:`google.cloud.datastore.key.Key`\n :returns: A new ``Key`` instance with the same data as the current one.\n \"\"\"\n cloned_self = self.__class__(*self.flat_path,\n@@ -210,7 +210,7 @@ def completed_key(self, id_or_name):\n :type id_or_name: string or integer\n :param id_or_name: ID or name to be added to the key.\n \n- :rtype: :class:`gcloud.datastore.key.Key`\n+ :rtype: :class:`google.cloud.datastore.key.Key`\n :returns: A new ``Key`` instance with the same data as the current one\n and an extra ID or name added.\n :raises: :class:`ValueError` if the current key is not partial or if\n@@ -235,7 +235,7 @@ def completed_key(self, id_or_name):\n def to_protobuf(self):\n \"\"\"Return a protobuf corresponding to the key.\n \n- :rtype: :class:`gcloud.datastore._generated.entity_pb2.Key`\n+ :rtype: :class:`google.cloud.datastore._generated.entity_pb2.Key`\n :returns: The protobuf representing the key.\n \"\"\"\n key = _entity_pb2.Key()\n@@ -346,7 +346,7 @@ def _make_parent(self):\n Extracts all but the last element in the key path and creates a new\n key, while still matching the namespace and the project.\n \n- :rtype: :class:`gcloud.datastore.key.Key` or :class:`NoneType`\n+ :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`\n :returns: A new ``Key`` instance, whose path consists of all but the\n last element of current path. If the current key has only\n one path element, returns ``None``.\n@@ -363,7 +363,7 @@ def _make_parent(self):\n def parent(self):\n \"\"\"The parent of the current key.\n \n- :rtype: :class:`gcloud.datastore.key.Key` or :class:`NoneType`\n+ :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`\n :returns: A new ``Key`` instance, whose path consists of all but the\n last element of current path. If the current key has only\n one path element, returns ``None``.\n@@ -388,7 +388,7 @@ def _validate_project(project, parent):\n :type project: string\n :param project: A project.\n \n- :type parent: :class:`gcloud.datastore.key.Key` or ``NoneType``\n+ :type parent: :class:`google.cloud.datastore.key.Key` or ``NoneType``\n :param parent: The parent of the key or ``None``.\n \n :rtype: string\ndiff --git a/gcloud/datastore/query.py b/google/cloud/datastore/query.py\nsimilarity index 94%\nrename from gcloud/datastore/query.py\nrename to google/cloud/datastore/query.py\n--- a/gcloud/datastore/query.py\n+++ b/google/cloud/datastore/query.py\n@@ -12,14 +12,14 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud datastore queries.\"\"\"\n+\"\"\"Create / interact with Google Cloud Datastore queries.\"\"\"\n \n import base64\n \n-from gcloud._helpers import _ensure_tuple_or_list\n-from gcloud.datastore._generated import query_pb2 as _query_pb2\n-from gcloud.datastore import helpers\n-from gcloud.datastore.key import Key\n+from google.cloud._helpers import _ensure_tuple_or_list\n+from google.cloud.datastore._generated import query_pb2 as _query_pb2\n+from google.cloud.datastore import helpers\n+from google.cloud.datastore.key import Key\n \n \n class Query(object):\n@@ -28,7 +28,7 @@ class Query(object):\n This class serves as an abstraction for creating a query over data\n stored in the Cloud Datastore.\n \n- :type client: :class:`gcloud.datastore.client.Client`\n+ :type client: :class:`google.cloud.datastore.client.Client`\n :param client: The client used to connect to Datastore.\n \n :type kind: string\n@@ -42,7 +42,7 @@ class Query(object):\n :param namespace: The namespace to which to restrict results. If not\n passed, uses the client's value.\n \n- :type ancestor: :class:`gcloud.datastore.key.Key` or None\n+ :type ancestor: :class:`google.cloud.datastore.key.Key` or None\n :param ancestor: key of the ancestor to which this query's results are\n restricted.\n \n@@ -197,7 +197,7 @@ def add_filter(self, property_name, operator, value):\n and operator is one of ``OPERATORS``\n (ie, ``=``, ``<``, ``<=``, ``>``, ``>=``)::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> query = client.query(kind='Person')\n >>> query.add_filter('name', '=', 'James')\n@@ -212,7 +212,7 @@ def add_filter(self, property_name, operator, value):\n :type value: :class:`int`, :class:`str`, :class:`bool`,\n :class:`float`, :class:`NoneType`,\n :class:`datetime.datetime`,\n- :class:`gcloud.datastore.key.Key`\n+ :class:`google.cloud.datastore.key.Key`\n :param value: The value to filter on.\n \n :raises: :class:`ValueError` if ``operation`` is not one of the\n@@ -257,7 +257,7 @@ def keys_only(self):\n def key_filter(self, key, operator='='):\n \"\"\"Filter on a key.\n \n- :type key: :class:`gcloud.datastore.key.Key`\n+ :type key: :class:`google.cloud.datastore.key.Key`\n :param key: The key to filter on.\n \n :type operator: string\n@@ -318,7 +318,7 @@ def fetch(self, limit=None, offset=0, start_cursor=None, end_cursor=None,\n \n For example::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> query = client.query(kind='Person')\n >>> query.add_filter('name', '=', 'Sally')\n@@ -339,7 +339,7 @@ def fetch(self, limit=None, offset=0, start_cursor=None, end_cursor=None,\n :type end_cursor: bytes\n :param end_cursor: An optional cursor passed through to the iterator.\n \n- :type client: :class:`gcloud.datastore.client.Client`\n+ :type client: :class:`google.cloud.datastore.client.Client`\n :param client: client used to connect to datastore.\n If not supplied, uses the query's value.\n \n@@ -358,12 +358,12 @@ def fetch(self, limit=None, offset=0, start_cursor=None, end_cursor=None,\n class Iterator(object):\n \"\"\"Represent the state of a given execution of a Query.\n \n- :type query: :class:`gcloud.datastore.query.Query`\n+ :type query: :class:`google.cloud.datastore.query.Query`\n :param query: Query object holding permanent configuration (i.e.\n things that don't change on with each page in\n a results set).\n \n- :type client: :class:`gcloud.datastore.client.Client`\n+ :type client: :class:`google.cloud.datastore.client.Client`\n :param client: The client used to make a request.\n \n :type limit: integer\n@@ -457,7 +457,7 @@ def next_page(self):\n def __iter__(self):\n \"\"\"Generator yielding all results matching our query.\n \n- :rtype: sequence of :class:`gcloud.datastore.entity.Entity`\n+ :rtype: sequence of :class:`google.cloud.datastore.entity.Entity`\n \"\"\"\n while True:\n self.next_page()\n@@ -480,7 +480,7 @@ def _pb_from_query(query):\n :type query: :class:`Query`\n :param query: The source query.\n \n- :rtype: :class:`gcloud.datastore._generated.query_pb2.Query`\n+ :rtype: :class:`google.cloud.datastore._generated.query_pb2.Query`\n :returns: A protobuf that can be sent to the protobuf API. N.b. that\n it does not contain \"in-flight\" fields for ongoing query\n executions (cursors, offset, limit).\ndiff --git a/gcloud/datastore/transaction.py b/google/cloud/datastore/transaction.py\nsimilarity index 94%\nrename from gcloud/datastore/transaction.py\nrename to google/cloud/datastore/transaction.py\n--- a/gcloud/datastore/transaction.py\n+++ b/google/cloud/datastore/transaction.py\n@@ -12,9 +12,9 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud datastore transactions.\"\"\"\n+\"\"\"Create / interact with Google Cloud Datastore transactions.\"\"\"\n \n-from gcloud.datastore.batch import Batch\n+from google.cloud.datastore.batch import Batch\n \n \n class Transaction(Batch):\n@@ -27,7 +27,7 @@ class Transaction(Batch):\n operations (either ``insert`` or ``upsert``) into the same\n mutation, and execute those within a transaction::\n \n- >>> from gcloud import datastore\n+ >>> from google.cloud import datastore\n >>> client = datastore.Client()\n >>> with client.transaction():\n ... client.put_multi([entity1, entity2])\n@@ -86,7 +86,7 @@ class Transaction(Batch):\n ... else:\n ... transaction.commit()\n \n- :type client: :class:`gcloud.datastore.client.Client`\n+ :type client: :class:`google.cloud.datastore.client.Client`\n :param client: the client used to connect to datastore.\n \"\"\"\n \n@@ -111,7 +111,7 @@ def current(self):\n If the topmost element on the stack is not a transaction,\n returns None.\n \n- :rtype: :class:`gcloud.datastore.transaction.Transaction` or None\n+ :rtype: :class:`google.cloud.datastore.transaction.Transaction` or None\n :returns: The current transaction (if any are active).\n \"\"\"\n top = super(Transaction, self).current()\ndiff --git a/gcloud/dns/__init__.py b/google/cloud/dns/__init__.py\nsimilarity index 54%\nrename from gcloud/dns/__init__.py\nrename to google/cloud/dns/__init__.py\n--- a/gcloud/dns/__init__.py\n+++ b/google/cloud/dns/__init__.py\n@@ -16,18 +16,20 @@\n \n The main concepts with this API are:\n \n-- :class:`gcloud.DNS.zone.ManagedZone` represents an collection of tables.\n-- :class:`gcloud.DNS.resource_record_set.ResourceRecordSet` represents a\n- single resource definition within a zone.\n-- :class:`gcloud.DNS.changes.Changes` represents a set of changes (adding/\n- deleting resource record sets) to a zone.\n+- :class:`~google.cloud.DNS.zone.ManagedZone` represents an collection of\n+ tables.\n+- :class:`~google.cloud.DNS.resource_record_set.ResourceRecordSet` represents\n+ a single resource definition within a zone.\n+- :class:`~google.cloud.DNS.changes.Changes` represents a set of changes\n+ (adding/deleting resource record sets) to a zone.\n \"\"\"\n \n-from gcloud.dns.zone import Changes\n-from gcloud.dns.client import Client\n-from gcloud.dns.connection import Connection\n-from gcloud.dns.zone import ManagedZone\n-from gcloud.dns.resource_record_set import ResourceRecordSet\n+\n+from google.cloud.dns.zone import Changes\n+from google.cloud.dns.client import Client\n+from google.cloud.dns.connection import Connection\n+from google.cloud.dns.zone import ManagedZone\n+from google.cloud.dns.resource_record_set import ResourceRecordSet\n \n \n SCOPE = Connection.SCOPE\ndiff --git a/gcloud/dns/changes.py b/google/cloud/dns/changes.py\nsimilarity index 87%\nrename from gcloud/dns/changes.py\nrename to google/cloud/dns/changes.py\n--- a/gcloud/dns/changes.py\n+++ b/google/cloud/dns/changes.py\n@@ -16,20 +16,20 @@\n \n import six\n \n-from gcloud._helpers import _rfc3339_to_datetime\n-from gcloud.exceptions import NotFound\n-from gcloud.dns.resource_record_set import ResourceRecordSet\n+from google.cloud._helpers import _rfc3339_to_datetime\n+from google.cloud.exceptions import NotFound\n+from google.cloud.dns.resource_record_set import ResourceRecordSet\n \n \n class Changes(object):\n \"\"\"Changes are bundled additions / deletions of DNS resource records.\n \n- Changes are owned by a :class:`gcloud.dns.zone.ManagedZone` instance.\n+ Changes are owned by a :class:`google.cloud.dns.zone.ManagedZone` instance.\n \n See:\n https://cloud.google.com/dns/api/v1/changes\n \n- :type zone: :class:`gcloud.dns.zone.ManagedZone`\n+ :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds one or more record sets.\n \"\"\"\n \n@@ -45,10 +45,10 @@ def from_api_repr(cls, resource, zone):\n :type resource: dict\n :param resource: change set representation returned from the API.\n \n- :type zone: :class:`gcloud.dns.zone.ManagedZone`\n+ :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds zero or more change sets.\n \n- :rtype: :class:`gcloud.dns.changes.Changes`\n+ :rtype: :class:`google.cloud.dns.changes.Changes`\n :returns: RRS parsed from ``resource``.\n \"\"\"\n changes = cls(zone=zone)\n@@ -125,7 +125,7 @@ def additions(self):\n \"\"\"Resource record sets to be added to the zone.\n \n :rtype: sequence of\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`.\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`.\n :returns: record sets appended via :meth:`add_record_set`.\n \"\"\"\n return self._additions\n@@ -135,7 +135,7 @@ def deletions(self):\n \"\"\"Resource record sets to be deleted from the zone.\n \n :rtype: sequence of\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`.\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`.\n :returns: record sets appended via :meth:`delete_record_set`.\n \"\"\"\n return self._deletions\n@@ -144,7 +144,7 @@ def add_record_set(self, record_set):\n \"\"\"Append a record set to the 'additions' for the change set.\n \n :type record_set:\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n :param record_set: the record set to append.\n \n :raises: ``ValueError`` if ``record_set`` is not of the required type.\n@@ -157,7 +157,7 @@ def delete_record_set(self, record_set):\n \"\"\"Append a record set to the 'deletions' for the change set.\n \n :type record_set:\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n :param record_set: the record set to append.\n \n :raises: ``ValueError`` if ``record_set`` is not of the required type.\n@@ -169,11 +169,11 @@ def delete_record_set(self, record_set):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n- :rtype: :class:`gcloud.dns.client.Client`\n+ :rtype: :class:`google.cloud.dns.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -207,7 +207,7 @@ def create(self, client=None):\n See:\n https://cloud.google.com/dns/api/v1/changes/create\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \"\"\"\n@@ -226,7 +226,7 @@ def exists(self, client=None):\n See\n https://cloud.google.com/dns/api/v1/changes/get\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n@@ -248,7 +248,7 @@ def reload(self, client=None):\n See\n https://cloud.google.com/dns/api/v1/changes/get\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \"\"\"\ndiff --git a/gcloud/dns/client.py b/google/cloud/dns/client.py\nsimilarity index 94%\nrename from gcloud/dns/client.py\nrename to google/cloud/dns/client.py\n--- a/gcloud/dns/client.py\n+++ b/google/cloud/dns/client.py\n@@ -15,9 +15,9 @@\n \"\"\"Client for interacting with the Google Cloud DNS API.\"\"\"\n \n \n-from gcloud.client import JSONClient\n-from gcloud.dns.connection import Connection\n-from gcloud.dns.zone import ManagedZone\n+from google.cloud.client import JSONClient\n+from google.cloud.dns.connection import Connection\n+from google.cloud.dns.zone import ManagedZone\n \n \n class Client(JSONClient):\n@@ -75,7 +75,7 @@ def list_zones(self, max_results=None, page_token=None):\n zones.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.dns.zone.ManagedZone`, plus a\n+ :returns: list of :class:`google.cloud.dns.zone.ManagedZone`, plus a\n \"next page token\" string: if the token is not None,\n indicates that more zones can be retrieved with another\n call (pass that value as ``page_token``).\n@@ -109,7 +109,7 @@ def zone(self, name, dns_name=None, description=None):\n :param description: the description for the zone. If not passed,\n defaults to the value of 'dns_name'.\n \n- :rtype: :class:`gcloud.dns.zone.ManagedZone`\n+ :rtype: :class:`google.cloud.dns.zone.ManagedZone`\n :returns: a new ``ManagedZone`` instance.\n \"\"\"\n return ManagedZone(name, dns_name, client=self,\ndiff --git a/gcloud/dns/connection.py b/google/cloud/dns/connection.py\nsimilarity index 91%\nrename from gcloud/dns/connection.py\nrename to google/cloud/dns/connection.py\n--- a/gcloud/dns/connection.py\n+++ b/google/cloud/dns/connection.py\n@@ -12,9 +12,9 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud dns connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud DNS connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/dns/resource_record_set.py b/google/cloud/dns/resource_record_set.py\nsimilarity index 88%\nrename from gcloud/dns/resource_record_set.py\nrename to google/cloud/dns/resource_record_set.py\n--- a/gcloud/dns/resource_record_set.py\n+++ b/google/cloud/dns/resource_record_set.py\n@@ -18,7 +18,7 @@\n class ResourceRecordSet(object):\n \"\"\"ResourceRecordSets are DNS resource records.\n \n- RRS are owned by a :class:`gcloud.dns.zone.ManagedZone` instance.\n+ RRS are owned by a :class:`google.cloud.dns.zone.ManagedZone` instance.\n \n See:\n https://cloud.google.com/dns/api/v1/resourceRecordSets\n@@ -35,7 +35,7 @@ class ResourceRecordSet(object):\n :type rrdatas: list of string\n :param rrdatas: one or more lines containing the resource data.\n \n- :type zone: :class:`gcloud.dns.zone.ManagedZone`\n+ :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds one or more record sets.\n \"\"\"\n \n@@ -53,10 +53,10 @@ def from_api_repr(cls, resource, zone):\n :type resource: dict\n :param resource: record sets representation returned from the API\n \n- :type zone: :class:`gcloud.dns.zone.ManagedZone`\n+ :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds one or more record sets.\n \n- :rtype: :class:`gcloud.dns.zone.ResourceRecordSet`\n+ :rtype: :class:`google.cloud.dns.zone.ResourceRecordSet`\n :returns: RRS parsed from ``resource``.\n \"\"\"\n name = resource['name']\ndiff --git a/gcloud/dns/zone.py b/google/cloud/dns/zone.py\nsimilarity index 90%\nrename from gcloud/dns/zone.py\nrename to google/cloud/dns/zone.py\n--- a/gcloud/dns/zone.py\n+++ b/google/cloud/dns/zone.py\n@@ -15,10 +15,10 @@\n \"\"\"Define API ManagedZones.\"\"\"\n import six\n \n-from gcloud._helpers import _rfc3339_to_datetime\n-from gcloud.exceptions import NotFound\n-from gcloud.dns.changes import Changes\n-from gcloud.dns.resource_record_set import ResourceRecordSet\n+from google.cloud._helpers import _rfc3339_to_datetime\n+from google.cloud.exceptions import NotFound\n+from google.cloud.dns.changes import Changes\n+from google.cloud.dns.resource_record_set import ResourceRecordSet\n \n \n class ManagedZone(object):\n@@ -34,7 +34,7 @@ class ManagedZone(object):\n :param dns_name: the DNS name of the zone. If not passed, then calls\n to :meth:`create` will fail.\n \n- :type client: :class:`gcloud.dns.client.Client`\n+ :type client: :class:`google.cloud.dns.client.Client`\n :param client: A client which holds credentials and project configuration\n for the zone (which requires a project).\n \n@@ -59,11 +59,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: zone resource representation returned from the API\n \n- :type client: :class:`gcloud.dns.client.Client`\n+ :type client: :class:`google.cloud.dns.client.Client`\n :param client: Client which holds credentials and project\n configuration for the zone.\n \n- :rtype: :class:`gcloud.dns.zone.ManagedZone`\n+ :rtype: :class:`google.cloud.dns.zone.ManagedZone`\n :returns: Zone parsed from ``resource``.\n \"\"\"\n name = resource.get('name')\n@@ -184,7 +184,7 @@ def resource_record_set(self, name, record_type, ttl, rrdatas):\n :type rrdatas: list of string\n :param rrdatas: resource data for the RR\n \n- :rtype: :class:`gcloud.dns.resource_record_set.ResourceRecordSet`\n+ :rtype: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n :returns: a new ``ResourceRecordSet`` instance\n \"\"\"\n return ResourceRecordSet(name, record_type, ttl, rrdatas, zone=self)\n@@ -192,7 +192,7 @@ def resource_record_set(self, name, record_type, ttl, rrdatas):\n def changes(self):\n \"\"\"Construct a change set bound to this zone.\n \n- :rtype: :class:`gcloud.dns.changes.Changes`\n+ :rtype: :class:`google.cloud.dns.changes.Changes`\n :returns: a new ``Changes`` instance\n \"\"\"\n return Changes(zone=self)\n@@ -200,11 +200,11 @@ def changes(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n- :rtype: :class:`gcloud.dns.client.Client`\n+ :rtype: :class:`google.cloud.dns.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -248,7 +248,7 @@ def create(self, client=None):\n See:\n https://cloud.google.com/dns/api/v1/managedZones/create\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \"\"\"\n@@ -264,7 +264,7 @@ def exists(self, client=None):\n See\n https://cloud.google.com/dns/api/v1/managedZones/get\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n@@ -287,7 +287,7 @@ def reload(self, client=None):\n See\n https://cloud.google.com/dns/api/v1/managedZones/get\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \"\"\"\n@@ -303,7 +303,7 @@ def delete(self, client=None):\n See:\n https://cloud.google.com/dns/api/v1/managedZones/delete\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \"\"\"\n@@ -326,13 +326,13 @@ def list_resource_record_sets(self, max_results=None, page_token=None,\n not passed, the API will return the first page of\n zones.\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n :rtype: tuple, (list, str)\n :returns: list of\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`,\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`,\n plus a \"next page token\" string: if the token is not None,\n indicates that more zones can be retrieved with another\n call (pass that value as ``page_token``).\n@@ -369,13 +369,13 @@ def list_changes(self, max_results=None, page_token=None, client=None):\n not passed, the API will return the first page of\n zones.\n \n- :type client: :class:`gcloud.dns.client.Client` or ``NoneType``\n+ :type client: :class:`google.cloud.dns.client.Client` or ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current zone.\n \n :rtype: tuple, (list, str)\n :returns: list of\n- :class:`gcloud.dns.resource_record_set.ResourceRecordSet`,\n+ :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`,\n plus a \"next page token\" string: if the token is not None,\n indicates that more zones can be retrieved with another\n call (pass that value as ``page_token``).\ndiff --git a/gcloud/environment_vars.py b/google/cloud/environment_vars.py\nsimilarity index 88%\nrename from gcloud/environment_vars.py\nrename to google/cloud/environment_vars.py\n--- a/gcloud/environment_vars.py\n+++ b/google/cloud/environment_vars.py\n@@ -12,16 +12,16 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Comprehensive list of environment variables used in gcloud.\n+\"\"\"Comprehensive list of environment variables used in google-cloud.\n \n These enable many types of implicit behavior in both production\n and tests.\n \"\"\"\n \n-PROJECT = 'GCLOUD_PROJECT'\n+PROJECT = 'GOOGLE_CLOUD_PROJECT'\n \"\"\"Environment variable defining default project.\"\"\"\n \n-TESTS_PROJECT = 'GCLOUD_TESTS_PROJECT_ID'\n+TESTS_PROJECT = 'GOOGLE_CLOUD_TESTS_PROJECT_ID'\n \"\"\"Environment variable defining project for tests.\"\"\"\n \n GCD_DATASET = 'DATASTORE_DATASET'\ndiff --git a/gcloud/error_reporting/__init__.py b/google/cloud/error_reporting/__init__.py\nsimilarity index 92%\nrename from gcloud/error_reporting/__init__.py\nrename to google/cloud/error_reporting/__init__.py\n--- a/gcloud/error_reporting/__init__.py\n+++ b/google/cloud/error_reporting/__init__.py\n@@ -14,4 +14,5 @@\n \n \"\"\"Client library for Stackdriver Error Reporting\"\"\"\n \n-from gcloud.error_reporting.client import Client\n+\n+from google.cloud.error_reporting.client import Client\ndiff --git a/gcloud/error_reporting/client.py b/google/cloud/error_reporting/client.py\nsimilarity index 96%\nrename from gcloud/error_reporting/client.py\nrename to google/cloud/error_reporting/client.py\n--- a/gcloud/error_reporting/client.py\n+++ b/google/cloud/error_reporting/client.py\n@@ -16,7 +16,7 @@\n \n import traceback\n \n-import gcloud.logging.client\n+import google.cloud.logging.client\n import six\n \n \n@@ -105,7 +105,7 @@ def __init__(self, project=None,\n http=None,\n service=None,\n version=None):\n- self.logging_client = gcloud.logging.client.Client(\n+ self.logging_client = google.cloud.logging.client.Client(\n project, credentials, http)\n self.service = service if service else self.DEFAULT_SERVICE\n self.version = version\n@@ -139,7 +139,7 @@ def _send_error_report(self, message,\n This should be a Python dict that contains the keys 'filePath',\n 'lineNumber', and 'functionName'\n \n- :type http_context: :class`gcloud.error_reporting.HTTPContext`\n+ :type http_context: :class`google.cloud.error_reporting.HTTPContext`\n :param http_context: The HTTP request which was processed when the\n error was triggered.\n \n@@ -190,7 +190,7 @@ def report(self, message, http_context=None, user=None):\n :param message: A user-supplied message to report\n \n \n- :type http_context: :class`gcloud.error_reporting.HTTPContext`\n+ :type http_context: :class`google.cloud.error_reporting.HTTPContext`\n :param http_context: The HTTP request which was processed when the\n error was triggered.\n \n@@ -226,7 +226,7 @@ def report_exception(self, http_context=None, user=None):\n \"\"\" Reports the details of the latest exceptions to Stackdriver Error\n Reporting.\n \n- :type http_context: :class`gcloud.error_reporting.HTTPContext`\n+ :type http_context: :class`google.cloud.error_reporting.HTTPContext`\n :param http_context: The HTTP request which was processed when the\n error was triggered.\n \ndiff --git a/gcloud/exceptions.py b/google/cloud/exceptions.py\nsimilarity index 91%\nrename from gcloud/exceptions.py\nrename to google/cloud/exceptions.py\n--- a/gcloud/exceptions.py\n+++ b/google/cloud/exceptions.py\n@@ -12,7 +12,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Custom exceptions for :mod:`gcloud` package.\n+\"\"\"Custom exceptions for :mod:`google.cloud` package.\n \n See: https://cloud.google.com/storage/docs/json_api/v1/status-codes\n \"\"\"\n@@ -24,8 +24,8 @@\n _HTTP_CODE_TO_EXCEPTION = {} # populated at end of module\n \n \n-class GCloudError(Exception):\n- \"\"\"Base error class for gcloud errors (abstract).\n+class GoogleCloudError(Exception):\n+ \"\"\"Base error class for Google Cloud errors (abstract).\n \n Each subclass represents a single type of HTTP error response.\n \"\"\"\n@@ -36,7 +36,7 @@ class GCloudError(Exception):\n \"\"\"\n \n def __init__(self, message, errors=()):\n- super(GCloudError, self).__init__(message)\n+ super(GoogleCloudError, self).__init__(message)\n self.message = message\n self._errors = errors\n \n@@ -53,7 +53,7 @@ def errors(self):\n return [copy.deepcopy(error) for error in self._errors]\n \n \n-class Redirection(GCloudError):\n+class Redirection(GoogleCloudError):\n \"\"\"Base for 3xx responses\n \n This class is abstract.\n@@ -80,7 +80,7 @@ class ResumeIncomplete(Redirection):\n code = 308\n \n \n-class ClientError(GCloudError):\n+class ClientError(GoogleCloudError):\n \"\"\"Base for 4xx responses\n \n This class is abstract\n@@ -137,7 +137,7 @@ class TooManyRequests(ClientError):\n code = 429\n \n \n-class ServerError(GCloudError):\n+class ServerError(GoogleCloudError):\n \"\"\"Base for 5xx responses: (abstract)\"\"\"\n \n \n@@ -178,7 +178,7 @@ def make_exception(response, content, error_info=None, use_json=True):\n :type use_json: bool\n :param use_json: Flag indicating if ``content`` is expected to be JSON.\n \n- :rtype: instance of :class:`GCloudError`, or a concrete subclass.\n+ :rtype: instance of :class:`GoogleCloudError`, or a concrete subclass.\n :returns: Exception specific to the error response.\n \"\"\"\n if isinstance(content, six.binary_type):\n@@ -206,7 +206,7 @@ def make_exception(response, content, error_info=None, use_json=True):\n try:\n klass = _HTTP_CODE_TO_EXCEPTION[response.status]\n except KeyError:\n- error = GCloudError(message, errors)\n+ error = GoogleCloudError(message, errors)\n error.code = response.status\n else:\n error = klass(message, errors)\n@@ -222,7 +222,7 @@ def _walk_subclasses(klass):\n \n \n # Build the code->exception class mapping.\n-for _eklass in _walk_subclasses(GCloudError):\n+for _eklass in _walk_subclasses(GoogleCloudError):\n code = getattr(_eklass, 'code', None)\n if code is not None:\n _HTTP_CODE_TO_EXCEPTION[code] = _eklass\ndiff --git a/gcloud/iterator.py b/google/cloud/iterator.py\nsimilarity index 99%\nrename from gcloud/iterator.py\nrename to google/cloud/iterator.py\n--- a/gcloud/iterator.py\n+++ b/google/cloud/iterator.py\n@@ -48,7 +48,7 @@ def get_items_from_response(self, response):\n class Iterator(object):\n \"\"\"A generic class for iterating through Cloud JSON APIs list responses.\n \n- :type client: :class:`gcloud.client.Client`\n+ :type client: :class:`google.cloud.client.Client`\n :param client: The client, which owns a connection to make requests.\n \n :type path: string\ndiff --git a/gcloud/language/__init__.py b/google/cloud/language/__init__.py\nsimilarity index 81%\nrename from gcloud/language/__init__.py\nrename to google/cloud/language/__init__.py\n--- a/gcloud/language/__init__.py\n+++ b/google/cloud/language/__init__.py\n@@ -14,6 +14,7 @@\n \n \"\"\"Client library for Google Cloud Natural Language API.\"\"\"\n \n-from gcloud.language.client import Client\n-from gcloud.language.document import Document\n-from gcloud.language.document import Encoding\n+\n+from google.cloud.language.client import Client\n+from google.cloud.language.document import Document\n+from google.cloud.language.document import Encoding\ndiff --git a/gcloud/language/client.py b/google/cloud/language/client.py\nsimilarity index 96%\nrename from gcloud/language/client.py\nrename to google/cloud/language/client.py\n--- a/gcloud/language/client.py\n+++ b/google/cloud/language/client.py\n@@ -15,9 +15,9 @@\n \"\"\"Basic client for Google Cloud Natural Language API.\"\"\"\n \n \n-from gcloud import client as client_module\n-from gcloud.language.connection import Connection\n-from gcloud.language.document import Document\n+from google.cloud import client as client_module\n+from google.cloud.language.connection import Connection\n+from google.cloud.language.document import Document\n \n \n class Client(client_module.Client):\ndiff --git a/gcloud/language/connection.py b/google/cloud/language/connection.py\nsimilarity index 95%\nrename from gcloud/language/connection.py\nrename to google/cloud/language/connection.py\n--- a/gcloud/language/connection.py\n+++ b/google/cloud/language/connection.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Basic connection for Google Cloud Natural Language API.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/language/document.py b/google/cloud/language/document.py\nsimilarity index 97%\nrename from gcloud/language/document.py\nrename to google/cloud/language/document.py\n--- a/gcloud/language/document.py\n+++ b/google/cloud/language/document.py\n@@ -19,10 +19,10 @@\n \n import collections\n \n-from gcloud.language.entity import Entity\n-from gcloud.language.sentiment import Sentiment\n-from gcloud.language.syntax import Sentence\n-from gcloud.language.syntax import Token\n+from google.cloud.language.entity import Entity\n+from google.cloud.language.sentiment import Sentiment\n+from google.cloud.language.syntax import Sentence\n+from google.cloud.language.syntax import Token\n \n \n DEFAULT_LANGUAGE = 'en-US'\n@@ -72,7 +72,7 @@ class Document(object):\n stored on the document or referred to in a Google Cloud Storage\n object.\n \n- :type client: :class:`~gcloud.language.client.Client`\n+ :type client: :class:`~google.cloud.language.client.Client`\n :param client: A client which holds credentials and other\n configuration.\n \ndiff --git a/gcloud/language/entity.py b/google/cloud/language/entity.py\nsimilarity index 100%\nrename from gcloud/language/entity.py\nrename to google/cloud/language/entity.py\ndiff --git a/gcloud/language/sentiment.py b/google/cloud/language/sentiment.py\nsimilarity index 100%\nrename from gcloud/language/sentiment.py\nrename to google/cloud/language/sentiment.py\ndiff --git a/gcloud/language/syntax.py b/google/cloud/language/syntax.py\nsimilarity index 100%\nrename from gcloud/language/syntax.py\nrename to google/cloud/language/syntax.py\ndiff --git a/gcloud/logging/__init__.py b/google/cloud/logging/__init__.py\nsimilarity index 78%\nrename from gcloud/logging/__init__.py\nrename to google/cloud/logging/__init__.py\n--- a/gcloud/logging/__init__.py\n+++ b/google/cloud/logging/__init__.py\n@@ -14,10 +14,9 @@\n \n \"\"\"Google Stackdriver Logging API wrapper.\"\"\"\n \n-from gcloud.logging.client import Client\n-from gcloud.logging.connection import Connection\n-\n-\n-SCOPE = Connection.SCOPE\n-ASCENDING = 'timestamp asc'\n-DESCENDING = 'timestamp desc'\n+try:\n+ import pkg_resources\n+ pkg_resources.declare_namespace(__name__)\n+except ImportError:\n+ import pkgutil\n+ __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/gcloud/logging/_gax.py b/google/cloud/logging/_gax.py\nsimilarity index 97%\nrename from gcloud/logging/_gax.py\nrename to google/cloud/logging/_gax.py\n--- a/gcloud/logging/_gax.py\n+++ b/google/cloud/logging/_gax.py\n@@ -26,11 +26,13 @@\n from google.protobuf.json_format import Parse\n from grpc import StatusCode\n \n-from gcloud._helpers import _datetime_to_pb_timestamp\n-from gcloud._helpers import _pb_timestamp_to_rfc3339\n-from gcloud._helpers import exc_to_code\n-from gcloud.exceptions import Conflict\n-from gcloud.exceptions import NotFound\n+# pylint: disable=ungrouped-imports\n+from google.cloud._helpers import _datetime_to_pb_timestamp\n+from google.cloud._helpers import _pb_timestamp_to_rfc3339\n+from google.cloud._helpers import exc_to_code\n+from google.cloud.exceptions import Conflict\n+from google.cloud.exceptions import NotFound\n+# pylint: enable=ungrouped-imports\n \n \n class _LoggingAPI(object):\n@@ -56,8 +58,8 @@ def list_entries(self, projects, filter_='', order_by='',\n https://cloud.google.com/logging/docs/view/advanced_filters\n \n :type order_by: str\n- :param order_by: One of :data:`gcloud.logging.ASCENDING` or\n- :data:`gcloud.logging.DESCENDING`.\n+ :param order_by: One of :data:`~google.cloud.logging.client.ASCENDING`\n+ or :data:`~google.cloud.logging.client.DESCENDING`.\n \n :type page_size: int\n :param page_size: maximum number of entries to return, If not passed,\ndiff --git a/gcloud/logging/client.py b/google/cloud/logging/client.py\nsimilarity index 85%\nrename from gcloud/logging/client.py\nrename to google/cloud/logging/client.py\n--- a/gcloud/logging/client.py\n+++ b/google/cloud/logging/client.py\n@@ -23,9 +23,9 @@\n LoggingServiceV2Api as GeneratedLoggingAPI)\n from google.cloud.logging.v2.metrics_service_v2_api import (\n MetricsServiceV2Api as GeneratedMetricsAPI)\n- from gcloud.logging._gax import _LoggingAPI as GAXLoggingAPI\n- from gcloud.logging._gax import _MetricsAPI as GAXMetricsAPI\n- from gcloud.logging._gax import _SinksAPI as GAXSinksAPI\n+ from google.cloud.logging._gax import _LoggingAPI as GAXLoggingAPI\n+ from google.cloud.logging._gax import _MetricsAPI as GAXMetricsAPI\n+ from google.cloud.logging._gax import _SinksAPI as GAXSinksAPI\n except ImportError: # pragma: NO COVER\n _HAVE_GAX = False\n GeneratedLoggingAPI = GAXLoggingAPI = None\n@@ -34,21 +34,25 @@\n else:\n _HAVE_GAX = True\n \n-from gcloud.client import JSONClient\n-from gcloud.logging.connection import Connection\n-from gcloud.logging.connection import _LoggingAPI as JSONLoggingAPI\n-from gcloud.logging.connection import _MetricsAPI as JSONMetricsAPI\n-from gcloud.logging.connection import _SinksAPI as JSONSinksAPI\n-from gcloud.logging.entries import ProtobufEntry\n-from gcloud.logging.entries import StructEntry\n-from gcloud.logging.entries import TextEntry\n-from gcloud.logging.logger import Logger\n-from gcloud.logging.metric import Metric\n-from gcloud.logging.sink import Sink\n+from google.cloud.client import JSONClient\n+from google.cloud.logging.connection import Connection\n+from google.cloud.logging.connection import _LoggingAPI as JSONLoggingAPI\n+from google.cloud.logging.connection import _MetricsAPI as JSONMetricsAPI\n+from google.cloud.logging.connection import _SinksAPI as JSONSinksAPI\n+from google.cloud.logging.entries import ProtobufEntry\n+from google.cloud.logging.entries import StructEntry\n+from google.cloud.logging.entries import TextEntry\n+from google.cloud.logging.logger import Logger\n+from google.cloud.logging.metric import Metric\n+from google.cloud.logging.sink import Sink\n \n \n-_DISABLE_GAX = os.getenv('GCLOUD_DISABLE_GAX', False)\n+_DISABLE_GAX = os.getenv('GOOGLE_CLOUD_DISABLE_GAX', False)\n _USE_GAX = _HAVE_GAX and not _DISABLE_GAX\n+ASCENDING = 'timestamp asc'\n+\"\"\"Query string to order by ascending timestamps.\"\"\"\n+DESCENDING = 'timestamp desc'\n+\"\"\"Query string to order by decending timestamps.\"\"\"\n \n \n class Client(JSONClient):\n@@ -127,7 +131,7 @@ def logger(self, name):\n :type name: str\n :param name: the name of the logger to be constructed.\n \n- :rtype: :class:`gcloud.logging.logger.Logger`\n+ :rtype: :class:`google.cloud.logging.logger.Logger`\n :returns: Logger created with the current client.\n \"\"\"\n return Logger(name, client=self)\n@@ -143,9 +147,9 @@ def _entry_from_resource(self, resource, loggers):\n passed, the entry will have a newly-created logger.\n \n :rtype: One of:\n- :class:`gcloud.logging.entries.TextEntry`,\n- :class:`gcloud.logging.entries.StructEntry`,\n- :class:`gcloud.logging.entries.ProtobufEntry`\n+ :class:`google.cloud.logging.entries.TextEntry`,\n+ :class:`google.cloud.logging.entries.StructEntry`,\n+ :class:`google.cloud.logging.entries.ProtobufEntry`\n :returns: the entry instance, constructed via the resource\n \"\"\"\n if 'textPayload' in resource:\n@@ -172,8 +176,8 @@ def list_entries(self, projects=None, filter_=None, order_by=None,\n https://cloud.google.com/logging/docs/view/advanced_filters\n \n :type order_by: str\n- :param order_by: One of :data:`gcloud.logging.ASCENDING` or\n- :data:`gcloud.logging.DESCENDING`.\n+ :param order_by: One of :data:`~google.cloud.logging.client.ASCENDING`\n+ or :data:`~google.cloud.logging.client.DESCENDING`.\n \n :type page_size: int\n :param page_size: maximum number of entries to return, If not passed,\n@@ -185,7 +189,7 @@ def list_entries(self, projects=None, filter_=None, order_by=None,\n entries.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.logging.entry.TextEntry`, plus a\n+ :returns: list of :class:`google.cloud.logging.entry.TextEntry`, plus a\n \"next page token\" string: if not None, indicates that\n more entries can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -219,7 +223,7 @@ def sink(self, name, filter_=None, destination=None):\n already exist, to be refreshed via\n :meth:`Sink.reload`.\n \n- :rtype: :class:`gcloud.logging.sink.Sink`\n+ :rtype: :class:`google.cloud.logging.sink.Sink`\n :returns: Sink created with the current client.\n \"\"\"\n return Sink(name, filter_, destination, client=self)\n@@ -240,7 +244,7 @@ def list_sinks(self, page_size=None, page_token=None):\n sinks.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.logging.sink.Sink`, plus a\n+ :returns: list of :class:`google.cloud.logging.sink.Sink`, plus a\n \"next page token\" string: if not None, indicates that\n more sinks can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -268,7 +272,7 @@ def metric(self, name, filter_=None, description=''):\n If not passed, the instance should already exist,\n to be refreshed via :meth:`Metric.reload`.\n \n- :rtype: :class:`gcloud.logging.metric.Metric`\n+ :rtype: :class:`google.cloud.logging.metric.Metric`\n :returns: Metric created with the current client.\n \"\"\"\n return Metric(name, filter_, client=self, description=description)\n@@ -289,7 +293,7 @@ def list_metrics(self, page_size=None, page_token=None):\n metrics.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.logging.metric.Metric`, plus a\n+ :returns: list of :class:`google.cloud.logging.metric.Metric`, plus a\n \"next page token\" string: if not None, indicates that\n more metrics can be retrieved with another call (pass that\n value as ``page_token``).\ndiff --git a/gcloud/logging/connection.py b/google/cloud/logging/connection.py\nsimilarity index 97%\nrename from gcloud/logging/connection.py\nrename to google/cloud/logging/connection.py\n--- a/gcloud/logging/connection.py\n+++ b/google/cloud/logging/connection.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Create / interact with Stackdriver Logging connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\n@@ -55,7 +55,7 @@ class _LoggingAPI(object):\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/entries\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.logs\n \n- :type connection: :class:`gcloud.logging.connection.Connection`\n+ :type connection: :class:`google.cloud.logging.connection.Connection`\n :param connection: the connection used to make API requests.\n \"\"\"\n def __init__(self, connection):\n@@ -77,8 +77,8 @@ def list_entries(self, projects, filter_=None, order_by=None,\n https://cloud.google.com/logging/docs/view/advanced_filters\n \n :type order_by: str\n- :param order_by: One of :data:`gcloud.logging.ASCENDING` or\n- :data:`gcloud.logging.DESCENDING`.\n+ :param order_by: One of :data:`~google.cloud.logging.client.ASCENDING`\n+ or :data:`~google.cloud.logging.client.DESCENDING`.\n \n :type page_size: int\n :param page_size: maximum number of entries to return, If not passed,\n@@ -171,7 +171,7 @@ class _SinksAPI(object):\n See:\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks\n \n- :type connection: :class:`gcloud.logging.connection.Connection`\n+ :type connection: :class:`google.cloud.logging.connection.Connection`\n :param connection: the connection used to make API requests.\n \"\"\"\n def __init__(self, connection):\n@@ -310,7 +310,7 @@ class _MetricsAPI(object):\n See:\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics\n \n- :type connection: :class:`gcloud.logging.connection.Connection`\n+ :type connection: :class:`google.cloud.logging.connection.Connection`\n :param connection: the connection used to make API requests.\n \"\"\"\n def __init__(self, connection):\ndiff --git a/gcloud/logging/entries.py b/google/cloud/logging/entries.py\nsimilarity index 94%\nrename from gcloud/logging/entries.py\nrename to google/cloud/logging/entries.py\n--- a/gcloud/logging/entries.py\n+++ b/google/cloud/logging/entries.py\n@@ -19,8 +19,8 @@\n \n from google.protobuf.json_format import Parse\n \n-from gcloud._helpers import _name_from_project_path\n-from gcloud._helpers import _rfc3339_nanos_to_datetime\n+from google.cloud._helpers import _name_from_project_path\n+from google.cloud._helpers import _rfc3339_nanos_to_datetime\n \n \n _LOGGER_TEMPLATE = re.compile(r\"\"\"\n@@ -53,7 +53,7 @@ class _BaseEntry(object):\n :param payload: The payload passed as ``textPayload``, ``jsonPayload``,\n or ``protoPayload``.\n \n- :type logger: :class:`gcloud.logging.logger.Logger`\n+ :type logger: :class:`google.cloud.logging.logger.Logger`\n :param logger: the logger used to write the entry.\n \n :type insert_id: text, or :class:`NoneType`\n@@ -90,7 +90,7 @@ def from_api_repr(cls, resource, client, loggers=None):\n :param resource: text entry resource representation returned from\n the API\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: Client which holds credentials and project\n configuration.\n \n@@ -98,7 +98,7 @@ def from_api_repr(cls, resource, client, loggers=None):\n :param loggers: A mapping of logger fullnames -> loggers. If not\n passed, the entry will have a newly-created logger.\n \n- :rtype: :class:`gcloud.logging.entries.TextEntry`\n+ :rtype: :class:`google.cloud.logging.entries.TextEntry`\n :returns: Text entry parsed from ``resource``.\n \"\"\"\n if loggers is None:\ndiff --git a/gcloud/logging/handlers/__init__.py b/google/cloud/logging/handlers/__init__.py\nsimilarity index 83%\nrename from gcloud/logging/handlers/__init__.py\nrename to google/cloud/logging/handlers/__init__.py\n--- a/gcloud/logging/handlers/__init__.py\n+++ b/google/cloud/logging/handlers/__init__.py\n@@ -14,5 +14,5 @@\n \n \"\"\"Python :mod:`logging` handlers for Google Cloud Logging.\"\"\"\n \n-from gcloud.logging.handlers.handlers import CloudLoggingHandler\n-from gcloud.logging.handlers.handlers import setup_logging\n+from google.cloud.logging.handlers.handlers import CloudLoggingHandler\n+from google.cloud.logging.handlers.handlers import setup_logging\ndiff --git a/gcloud/logging/handlers/handlers.py b/google/cloud/logging/handlers/handlers.py\nsimilarity index 86%\nrename from gcloud/logging/handlers/handlers.py\nrename to google/cloud/logging/handlers/handlers.py\n--- a/gcloud/logging/handlers/handlers.py\n+++ b/google/cloud/logging/handlers/handlers.py\n@@ -16,11 +16,11 @@\n \n import logging\n \n-from gcloud.logging.handlers.transports import BackgroundThreadTransport\n+from google.cloud.logging.handlers.transports import BackgroundThreadTransport\n \n \n EXCLUDE_LOGGER_DEFAULTS = (\n- 'gcloud',\n+ 'google.cloud',\n 'oauth2client'\n )\n \n@@ -37,9 +37,9 @@ class CloudLoggingHandler(logging.StreamHandler):\n which means each logging statement that uses this handler will require\n an API call.\n \n- :type client: :class:`gcloud.logging.client`\n- :param client: the authenticated gcloud logging client for this handler\n- to use\n+ :type client: :class:`google.cloud.logging.client`\n+ :param client: the authenticated Google Cloud Logging client for this\n+ handler to use\n \n :type name: str\n :param name: the name of the custom log in Stackdriver Logging. Defaults\n@@ -57,10 +57,10 @@ class CloudLoggingHandler(logging.StreamHandler):\n \n .. doctest::\n \n- import gcloud.logging\n- from gcloud.logging.handlers import CloudLoggingHandler\n+ import google.cloud.logging\n+ from google.cloud.logging.handlers import CloudLoggingHandler\n \n- client = gcloud.logging.Client()\n+ client = google.cloud.logging.Client()\n handler = CloudLoggingHandler(client)\n \n cloud_logger = logging.getLogger('cloudLogger')\n@@ -112,12 +112,12 @@ def setup_logging(handler, excluded_loggers=EXCLUDE_LOGGER_DEFAULTS):\n .. doctest::\n \n import logging\n- import gcloud.logging\n- from gcloud.logging.handlers import CloudLoggingHandler\n+ import google.cloud.logging\n+ from google.cloud.logging.handlers import CloudLoggingHandler\n \n- client = gcloud.logging.Client()\n+ client = google.cloud.logging.Client()\n handler = CloudLoggingHandler(client)\n- gcloud.logging.setup_logging(handler)\n+ google.cloud.logging.setup_logging(handler)\n logging.getLogger().setLevel(logging.DEBUG)\n \n logging.error('bad news') # API call\ndiff --git a/gcloud/logging/handlers/transports/__init__.py b/google/cloud/logging/handlers/transports/__init__.py\nsimilarity index 74%\nrename from gcloud/logging/handlers/transports/__init__.py\nrename to google/cloud/logging/handlers/transports/__init__.py\n--- a/gcloud/logging/handlers/transports/__init__.py\n+++ b/google/cloud/logging/handlers/transports/__init__.py\n@@ -16,11 +16,11 @@\n \n Currently two options are provided, a synchronous transport that makes\n an API call for each log statement, and an asynchronous handler that\n-sends the API using a :class:`~gcloud.logging.logger.Batch` object in\n+sends the API using a :class:`~google.cloud.logging.logger.Batch` object in\n the background.\n \"\"\"\n \n-from gcloud.logging.handlers.transports.base import Transport\n-from gcloud.logging.handlers.transports.sync import SyncTransport\n-from gcloud.logging.handlers.transports.background_thread import (\n+from google.cloud.logging.handlers.transports.base import Transport\n+from google.cloud.logging.handlers.transports.sync import SyncTransport\n+from google.cloud.logging.handlers.transports.background_thread import (\n BackgroundThreadTransport)\ndiff --git a/gcloud/logging/handlers/transports/background_thread.py b/google/cloud/logging/handlers/transports/background_thread.py\nsimilarity index 96%\nrename from gcloud/logging/handlers/transports/background_thread.py\nrename to google/cloud/logging/handlers/transports/background_thread.py\n--- a/gcloud/logging/handlers/transports/background_thread.py\n+++ b/google/cloud/logging/handlers/transports/background_thread.py\n@@ -21,8 +21,8 @@\n import copy\n import threading\n \n-from gcloud.logging import Client\n-from gcloud.logging.handlers.transports.base import Transport\n+from google.cloud.logging.client import Client\n+from google.cloud.logging.handlers.transports.base import Transport\n \n \n class _Worker(object):\n@@ -97,7 +97,7 @@ def _start(self):\n self._entries_condition.acquire()\n self._thread = threading.Thread(\n target=self._run,\n- name='gcloud.logging.handlers.transport.Worker')\n+ name='google.cloud.logging.handlers.transport.Worker')\n self._thread.setDaemon(True)\n self._thread.start()\n finally:\ndiff --git a/gcloud/logging/handlers/transports/base.py b/google/cloud/logging/handlers/transports/base.py\nsimilarity index 95%\nrename from gcloud/logging/handlers/transports/base.py\nrename to google/cloud/logging/handlers/transports/base.py\n--- a/gcloud/logging/handlers/transports/base.py\n+++ b/google/cloud/logging/handlers/transports/base.py\n@@ -16,7 +16,7 @@\n \n \n class Transport(object):\n- \"\"\"Base class for ``gcloud`` logging handler transports.\n+ \"\"\"Base class for Google Cloud Logging handler transports.\n \n Subclasses of :class:`Transport` must have constructors that accept a\n client and name object, and must override :meth:`send`.\ndiff --git a/gcloud/logging/handlers/transports/sync.py b/google/cloud/logging/handlers/transports/sync.py\nsimilarity index 95%\nrename from gcloud/logging/handlers/transports/sync.py\nrename to google/cloud/logging/handlers/transports/sync.py\n--- a/gcloud/logging/handlers/transports/sync.py\n+++ b/google/cloud/logging/handlers/transports/sync.py\n@@ -17,7 +17,7 @@\n Logs directly to the the Stackdriver Logging API with a synchronous call.\n \"\"\"\n \n-from gcloud.logging.handlers.transports.base import Transport\n+from google.cloud.logging.handlers.transports.base import Transport\n \n \n class SyncTransport(Transport):\ndiff --git a/gcloud/logging/logger.py b/google/cloud/logging/logger.py\nsimilarity index 92%\nrename from gcloud/logging/logger.py\nrename to google/cloud/logging/logger.py\n--- a/gcloud/logging/logger.py\n+++ b/google/cloud/logging/logger.py\n@@ -28,7 +28,7 @@ class Logger(object):\n :type name: string\n :param name: the name of the logger\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: A client which holds credentials and project configuration\n for the logger (which requires a project).\n \n@@ -64,11 +64,12 @@ def path(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n \n- :rtype: :class:`gcloud.logging.client.Client`\n+ :rtype: :class:`google.cloud.logging.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -78,7 +79,8 @@ def _require_client(self, client):\n def batch(self, client=None):\n \"\"\"Return a batch to use as a context manager.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n@@ -165,7 +167,8 @@ def log_text(self, text, client=None, labels=None, insert_id=None,\n :type text: text\n :param text: the log message.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n \n@@ -198,7 +201,8 @@ def log_struct(self, info, client=None, labels=None, insert_id=None,\n :type info: dict\n :param info: the log entry information\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n \n@@ -231,7 +235,8 @@ def log_proto(self, message, client=None, labels=None, insert_id=None,\n :type message: Protobuf message\n :param message: the message to be logged\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n \n@@ -260,7 +265,8 @@ def delete(self, client=None):\n See:\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.logs/delete\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n \"\"\"\n@@ -283,8 +289,8 @@ def list_entries(self, projects=None, filter_=None, order_by=None,\n https://cloud.google.com/logging/docs/view/advanced_filters\n \n :type order_by: string\n- :param order_by: One of :data:`gcloud.logging.ASCENDING` or\n- :data:`gcloud.logging.DESCENDING`.\n+ :param order_by: One of :data:`~google.cloud.logging.client.ASCENDING`\n+ or :data:`~google.cloud.logging.client.DESCENDING`.\n \n :type page_size: int\n :param page_size: maximum number of entries to return, If not passed,\n@@ -296,7 +302,7 @@ def list_entries(self, projects=None, filter_=None, order_by=None,\n entries.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.logging.entry.TextEntry`, plus a\n+ :returns: list of :class:`google.cloud.logging.entry.TextEntry`, plus a\n \"next page token\" string: if not None, indicates that\n more entries can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -316,10 +322,10 @@ class Batch(object):\n \n Helper returned by :meth:`Logger.batch`\n \n- :type logger: :class:`gcloud.logging.logger.Logger`\n+ :type logger: :class:`google.cloud.logging.logger.Logger`\n :param logger: the logger to which entries will be logged.\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: The client to use.\n \"\"\"\n def __init__(self, logger, client):\n@@ -406,7 +412,8 @@ def log_proto(self, message, labels=None, insert_id=None, severity=None,\n def commit(self, client=None):\n \"\"\"Send saved log entries as a single API call.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n \"\"\"\ndiff --git a/gcloud/logging/metric.py b/google/cloud/logging/metric.py\nsimilarity index 86%\nrename from gcloud/logging/metric.py\nrename to google/cloud/logging/metric.py\n--- a/gcloud/logging/metric.py\n+++ b/google/cloud/logging/metric.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Define Stackdriver Logging API Metrics.\"\"\"\n \n-from gcloud.exceptions import NotFound\n+from google.cloud.exceptions import NotFound\n \n \n class Metric(object):\n@@ -31,7 +31,7 @@ class Metric(object):\n tracked by the metric. If not passed, the instance should\n already exist, to be refreshed via :meth:`reload`.\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: A client which holds credentials and project configuration\n for the metric (which requires a project).\n \n@@ -71,11 +71,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: metric resource representation returned from the API\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: Client which holds credentials and project\n configuration for the metric.\n \n- :rtype: :class:`gcloud.logging.metric.Metric`\n+ :rtype: :class:`google.cloud.logging.metric.Metric`\n :returns: Metric parsed from ``resource``.\n \"\"\"\n metric_name = resource['name']\n@@ -87,11 +87,12 @@ def from_api_repr(cls, resource, client):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \n- :rtype: :class:`gcloud.logging.client.Client`\n+ :rtype: :class:`google.cloud.logging.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -104,7 +105,8 @@ def create(self, client=None):\n See:\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics/create\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \"\"\"\n@@ -118,7 +120,8 @@ def exists(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics/get\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \n@@ -140,7 +143,8 @@ def reload(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics/get\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \"\"\"\n@@ -155,7 +159,8 @@ def update(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics/update\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \"\"\"\n@@ -169,7 +174,8 @@ def delete(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.metrics/delete\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current metric.\n \"\"\"\ndiff --git a/gcloud/logging/sink.py b/google/cloud/logging/sink.py\nsimilarity index 86%\nrename from gcloud/logging/sink.py\nrename to google/cloud/logging/sink.py\n--- a/gcloud/logging/sink.py\n+++ b/google/cloud/logging/sink.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Define Stackdriver Logging API Sinks.\"\"\"\n \n-from gcloud.exceptions import NotFound\n+from google.cloud.exceptions import NotFound\n \n \n class Sink(object):\n@@ -36,7 +36,7 @@ class Sink(object):\n If not passed, the instance should already exist, to\n be refreshed via :meth:`reload`.\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: A client which holds credentials and project configuration\n for the sink (which requires a project).\n \"\"\"\n@@ -73,11 +73,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: sink resource representation returned from the API\n \n- :type client: :class:`gcloud.logging.client.Client`\n+ :type client: :class:`google.cloud.logging.client.Client`\n :param client: Client which holds credentials and project\n configuration for the sink.\n \n- :rtype: :class:`gcloud.logging.sink.Sink`\n+ :rtype: :class:`google.cloud.logging.sink.Sink`\n :returns: Sink parsed from ``resource``.\n :raises: :class:`ValueError` if ``client`` is not ``None`` and the\n project from the resource does not agree with the project\n@@ -91,11 +91,12 @@ def from_api_repr(cls, resource, client):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \n- :rtype: :class:`gcloud.logging.client.Client`\n+ :rtype: :class:`google.cloud.logging.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -108,7 +109,8 @@ def create(self, client=None):\n See:\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks/create\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \"\"\"\n@@ -122,7 +124,8 @@ def exists(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks/get\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \n@@ -144,7 +147,8 @@ def reload(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks/get\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \"\"\"\n@@ -159,7 +163,8 @@ def update(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks/update\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \"\"\"\n@@ -173,7 +178,8 @@ def delete(self, client=None):\n See\n https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/projects.sinks/delete\n \n- :type client: :class:`gcloud.logging.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.logging.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current sink.\n \"\"\"\ndiff --git a/gcloud/monitoring/__init__.py b/google/cloud/monitoring/__init__.py\nsimilarity index 52%\nrename from gcloud/monitoring/__init__.py\nrename to google/cloud/monitoring/__init__.py\n--- a/gcloud/monitoring/__init__.py\n+++ b/google/cloud/monitoring/__init__.py\n@@ -14,22 +14,22 @@\n \n \"\"\"Google Stackdriver Monitoring API wrapper.\"\"\"\n \n-from gcloud.monitoring.client import Client\n-from gcloud.monitoring.connection import Connection\n-from gcloud.monitoring.group import Group\n-from gcloud.monitoring.label import LabelDescriptor\n-from gcloud.monitoring.label import LabelValueType\n-from gcloud.monitoring.metric import Metric\n-from gcloud.monitoring.metric import MetricDescriptor\n-from gcloud.monitoring.metric import MetricKind\n-from gcloud.monitoring.metric import ValueType\n-from gcloud.monitoring.query import Aligner\n-from gcloud.monitoring.query import Query\n-from gcloud.monitoring.query import Reducer\n-from gcloud.monitoring.resource import Resource\n-from gcloud.monitoring.resource import ResourceDescriptor\n-from gcloud.monitoring.timeseries import Point\n-from gcloud.monitoring.timeseries import TimeSeries\n+from google.cloud.monitoring.client import Client\n+from google.cloud.monitoring.connection import Connection\n+from google.cloud.monitoring.group import Group\n+from google.cloud.monitoring.label import LabelDescriptor\n+from google.cloud.monitoring.label import LabelValueType\n+from google.cloud.monitoring.metric import Metric\n+from google.cloud.monitoring.metric import MetricDescriptor\n+from google.cloud.monitoring.metric import MetricKind\n+from google.cloud.monitoring.metric import ValueType\n+from google.cloud.monitoring.query import Aligner\n+from google.cloud.monitoring.query import Query\n+from google.cloud.monitoring.query import Reducer\n+from google.cloud.monitoring.resource import Resource\n+from google.cloud.monitoring.resource import ResourceDescriptor\n+from google.cloud.monitoring.timeseries import Point\n+from google.cloud.monitoring.timeseries import TimeSeries\n \n __all__ = (\n 'Client',\ndiff --git a/gcloud/monitoring/_dataframe.py b/google/cloud/monitoring/_dataframe.py\nsimilarity index 98%\nrename from gcloud/monitoring/_dataframe.py\nrename to google/cloud/monitoring/_dataframe.py\n--- a/gcloud/monitoring/_dataframe.py\n+++ b/google/cloud/monitoring/_dataframe.py\n@@ -30,7 +30,7 @@ def _build_dataframe(time_series_iterable,\n \"\"\"Build a :mod:`pandas` dataframe out of time series.\n \n :type time_series_iterable:\n- iterable over :class:`~gcloud.monitoring.timeseries.TimeSeries`\n+ iterable over :class:`~google.cloud.monitoring.timeseries.TimeSeries`\n :param time_series_iterable:\n An iterable (e.g., a query object) yielding time series.\n \ndiff --git a/gcloud/monitoring/client.py b/google/cloud/monitoring/client.py\nsimilarity index 82%\nrename from gcloud/monitoring/client.py\nrename to google/cloud/monitoring/client.py\n--- a/gcloud/monitoring/client.py\n+++ b/google/cloud/monitoring/client.py\n@@ -16,7 +16,7 @@\n \n Example::\n \n- >>> from gcloud import monitoring\n+ >>> from google.cloud import monitoring\n >>> client = monitoring.Client()\n >>> query = client.query(minutes=5)\n >>> print(query.as_dataframe()) # Requires pandas.\n@@ -30,18 +30,18 @@\n \n import datetime\n \n-from gcloud.client import JSONClient\n-from gcloud.monitoring.connection import Connection\n-from gcloud.monitoring.group import Group\n-from gcloud.monitoring.metric import Metric\n-from gcloud.monitoring.metric import MetricDescriptor\n-from gcloud.monitoring.metric import MetricKind\n-from gcloud.monitoring.metric import ValueType\n-from gcloud.monitoring.query import Query\n-from gcloud.monitoring.resource import Resource\n-from gcloud.monitoring.resource import ResourceDescriptor\n-from gcloud.monitoring.timeseries import Point\n-from gcloud.monitoring.timeseries import TimeSeries\n+from google.cloud.client import JSONClient\n+from google.cloud.monitoring.connection import Connection\n+from google.cloud.monitoring.group import Group\n+from google.cloud.monitoring.metric import Metric\n+from google.cloud.monitoring.metric import MetricDescriptor\n+from google.cloud.monitoring.metric import MetricKind\n+from google.cloud.monitoring.metric import ValueType\n+from google.cloud.monitoring.query import Query\n+from google.cloud.monitoring.resource import Resource\n+from google.cloud.monitoring.resource import ResourceDescriptor\n+from google.cloud.monitoring.timeseries import Point\n+from google.cloud.monitoring.timeseries import TimeSeries\n \n _UTCNOW = datetime.datetime.utcnow # To be replaced by tests.\n \n@@ -82,7 +82,7 @@ def query(self,\n :type metric_type: string\n :param metric_type: The metric type name. The default value is\n :data:`Query.DEFAULT_METRIC_TYPE\n- `,\n+ `,\n but please note that this default value is provided only for\n demonstration purposes and is subject to change. See the\n `supported metrics`_.\n@@ -98,7 +98,7 @@ def query(self,\n \n It is also allowed to omit the end time and duration here,\n in which case\n- :meth:`~gcloud.monitoring.query.Query.select_interval`\n+ :meth:`~google.cloud.monitoring.query.Query.select_interval`\n must be called before the query is executed.\n \n :type days: integer\n@@ -110,13 +110,13 @@ def query(self,\n :type minutes: integer\n :param minutes: The number of minutes in the time interval.\n \n- :rtype: :class:`~gcloud.monitoring.query.Query`\n+ :rtype: :class:`~google.cloud.monitoring.query.Query`\n :returns: The query object.\n \n :raises: :exc:`ValueError` if ``end_time`` is specified but\n ``days``, ``hours``, and ``minutes`` are all zero.\n If you really want to specify a point in time, use\n- :meth:`~gcloud.monitoring.query.Query.select_interval`.\n+ :meth:`~google.cloud.monitoring.query.Query.select_interval`.\n \n .. _supported metrics: https://cloud.google.com/monitoring/api/metrics\n \"\"\"\n@@ -133,7 +133,8 @@ def metric_descriptor(self, type_,\n Metric descriptors specify the schema for a particular metric type.\n \n This factory method is used most often in conjunction with the metric\n- descriptor :meth:`~gcloud.monitoring.metric.MetricDescriptor.create`\n+ descriptor\n+ :meth:`~google.cloud.monitoring.metric.MetricDescriptor.create`\n method to define custom metrics::\n \n >>> descriptor = client.metric_descriptor(\n@@ -166,7 +167,7 @@ def metric_descriptor(self, type_,\n The kind of measurement. It must be one of\n :data:`MetricKind.GAUGE`, :data:`MetricKind.DELTA`,\n or :data:`MetricKind.CUMULATIVE`.\n- See :class:`~gcloud.monitoring.metric.MetricKind`.\n+ See :class:`~google.cloud.monitoring.metric.MetricKind`.\n \n :type value_type: string\n :param value_type:\n@@ -176,7 +177,8 @@ def metric_descriptor(self, type_,\n or :data:`ValueType.DISTRIBUTION`.\n See :class:`ValueType`.\n \n- :type labels: list of :class:`~gcloud.monitoring.label.LabelDescriptor`\n+ :type labels:\n+ list of :class:`~google.cloud.monitoring.label.LabelDescriptor`\n :param labels:\n A sequence of zero or more label descriptors specifying the labels\n used to identify a specific instance of this metric.\n@@ -207,10 +209,10 @@ def metric_descriptor(self, type_,\n def metric(type_, labels):\n \"\"\"Factory for constructing metric objects.\n \n- :class:`~gcloud.monitoring.metric.Metric` objects are typically\n+ :class:`~google.cloud.monitoring.metric.Metric` objects are typically\n created to write custom metric values. The type should match the\n metric type specified in the\n- :class:`~gcloud.monitoring.metric.MetricDescriptor` used to\n+ :class:`~google.cloud.monitoring.metric.MetricDescriptor` used to\n create the custom metric::\n \n >>> metric = client.metric('custom.googleapis.com/my_metric',\n@@ -224,9 +226,9 @@ def metric(type_, labels):\n :type labels: dict\n :param labels: A mapping from label names to values for all labels\n enumerated in the associated\n- :class:`~gcloud.monitoring.metric.MetricDescriptor`.\n+ :class:`~google.cloud.monitoring.metric.MetricDescriptor`.\n \n- :rtype: :class:`~gcloud.monitoring.metric.Metric`\n+ :rtype: :class:`~google.cloud.monitoring.metric.Metric`\n :returns: The metric object.\n \"\"\"\n return Metric(type=type_, labels=labels)\n@@ -236,9 +238,9 @@ def resource(type_, labels):\n \"\"\"Factory for constructing monitored resource objects.\n \n A monitored resource object (\n- :class:`~gcloud.monitoring.resource.Resource`) is\n+ :class:`~google.cloud.monitoring.resource.Resource`) is\n typically used to create a\n- :class:`~gcloud.monitoring.timeseries.TimeSeries` object.\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries` object.\n \n For a list of possible monitored resource types and their associated\n labels, see:\n@@ -251,11 +253,11 @@ def resource(type_, labels):\n :type labels: dict\n :param labels: A mapping from label names to values for all labels\n enumerated in the associated\n- :class:`~gcloud.monitoring.resource.ResourceDescriptor`,\n+ :class:`~google.cloud.monitoring.resource.ResourceDescriptor`,\n except that ``project_id`` can and should be omitted\n when writing time series data.\n \n- :rtype: :class:`~gcloud.monitoring.resource.Resource`\n+ :rtype: :class:`~google.cloud.monitoring.resource.Resource`\n :returns: A monitored resource object.\n \"\"\"\n return Resource(type_, labels)\n@@ -267,9 +269,9 @@ def time_series(metric, resource, value,\n \n .. note::\n \n- While :class:`~gcloud.monitoring.timeseries.TimeSeries` objects\n- returned by the API typically have multiple data points,\n- :class:`~gcloud.monitoring.timeseries.TimeSeries` objects\n+ While :class:`~google.cloud.monitoring.timeseries.TimeSeries`\n+ objects returned by the API typically have multiple data points,\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries` objects\n sent to the API must have at most one point.\n \n For example::\n@@ -281,17 +283,17 @@ def time_series(metric, resource, value,\n \n https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries\n \n- :type metric: :class:`~gcloud.monitoring.metric.Metric`\n- :param metric: A :class:`~gcloud.monitoring.metric.Metric` object.\n+ :type metric: :class:`~google.cloud.monitoring.metric.Metric`\n+ :param metric: A :class:`~google.cloud.monitoring.metric.Metric`.\n \n- :type resource: :class:`~gcloud.monitoring.resource.Resource`\n- :param resource: A :class:`~gcloud.monitoring.resource.Resource`\n+ :type resource: :class:`~google.cloud.monitoring.resource.Resource`\n+ :param resource: A :class:`~google.cloud.monitoring.resource.Resource`\n object.\n \n :type value: bool, int, string, or float\n :param value:\n The value of the data point to create for the\n- :class:`~gcloud.monitoring.timeseries.TimeSeries`.\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries`.\n \n .. note::\n \n@@ -314,7 +316,7 @@ def time_series(metric, resource, value,\n Defaults to None. If the start time is unspecified,\n the API interprets the start time to be the same as the end time.\n \n- :rtype: :class:`~gcloud.monitoring.timeseries.TimeSeries`\n+ :rtype: :class:`~google.cloud.monitoring.timeseries.TimeSeries`\n :returns: A time series object.\n \"\"\"\n if end_time is None:\n@@ -334,11 +336,11 @@ def fetch_metric_descriptor(self, metric_type):\n :type metric_type: string\n :param metric_type: The metric type name.\n \n- :rtype: :class:`~gcloud.monitoring.metric.MetricDescriptor`\n+ :rtype: :class:`~google.cloud.monitoring.metric.MetricDescriptor`\n :returns: The metric descriptor instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the metric descriptor\n- is not found.\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the metric\n+ descriptor is not found.\n \"\"\"\n return MetricDescriptor._fetch(self, metric_type)\n \n@@ -364,7 +366,8 @@ def list_metric_descriptors(self, filter_string=None, type_prefix=None):\n metric types. This adds ``metric.type = starts_with(\"\")``\n to the filter.\n \n- :rtype: list of :class:`~gcloud.monitoring.metric.MetricDescriptor`\n+ :rtype:\n+ list of :class:`~google.cloud.monitoring.metric.MetricDescriptor`\n :returns: A list of metric descriptor instances.\n \n .. _filter documentation:\n@@ -383,11 +386,11 @@ def fetch_resource_descriptor(self, resource_type):\n :type resource_type: string\n :param resource_type: The resource type name.\n \n- :rtype: :class:`~gcloud.monitoring.resource.ResourceDescriptor`\n+ :rtype: :class:`~google.cloud.monitoring.resource.ResourceDescriptor`\n :returns: The resource descriptor instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the resource descriptor\n- is not found.\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the resource\n+ descriptor is not found.\n \"\"\"\n return ResourceDescriptor._fetch(self, resource_type)\n \n@@ -404,7 +407,8 @@ def list_resource_descriptors(self, filter_string=None):\n An optional filter expression describing the resource descriptors\n to be returned. See the `filter documentation`_.\n \n- :rtype: list of :class:`~gcloud.monitoring.resource.ResourceDescriptor`\n+ :rtype: list of\n+ :class:`~google.cloud.monitoring.resource.ResourceDescriptor`\n :returns: A list of resource descriptor instances.\n \n .. _filter documentation:\n@@ -465,16 +469,17 @@ def fetch_group(self, group_id):\n \n >>> try:\n >>> group = client.fetch_group('1234')\n- >>> except gcloud.exceptions.NotFound:\n+ >>> except google.cloud.exceptions.NotFound:\n >>> print('That group does not exist!')\n \n :type group_id: string\n :param group_id: The ID of the group.\n \n- :rtype: :class:`~gcloud.monitoring.group.Group`\n+ :rtype: :class:`~google.cloud.monitoring.group.Group`\n :returns: The group instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the group is not found.\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the group\n+ is not found.\n \"\"\"\n return Group._fetch(self, group_id)\n \n@@ -486,7 +491,7 @@ def list_groups(self):\n >>> for group in client.list_groups():\n ... print((group.display_name, group.name))\n \n- :rtype: list of :class:`~gcloud.monitoring.group.Group`\n+ :rtype: list of :class:`~google.cloud.monitoring.group.Group`\n :returns: A list of group instances.\n \"\"\"\n return Group._list(self)\ndiff --git a/gcloud/monitoring/connection.py b/google/cloud/monitoring/connection.py\nsimilarity index 97%\nrename from gcloud/monitoring/connection.py\nrename to google/cloud/monitoring/connection.py\n--- a/gcloud/monitoring/connection.py\n+++ b/google/cloud/monitoring/connection.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Create / interact with Stackdriver Monitoring connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/monitoring/group.py b/google/cloud/monitoring/group.py\nsimilarity index 94%\nrename from gcloud/monitoring/group.py\nrename to google/cloud/monitoring/group.py\n--- a/gcloud/monitoring/group.py\n+++ b/google/cloud/monitoring/group.py\n@@ -21,10 +21,10 @@\n \n import re\n \n-from gcloud._helpers import _datetime_to_rfc3339\n-from gcloud._helpers import _name_from_project_path\n-from gcloud.exceptions import NotFound\n-from gcloud.monitoring.resource import Resource\n+from google.cloud._helpers import _datetime_to_rfc3339\n+from google.cloud._helpers import _name_from_project_path\n+from google.cloud.exceptions import NotFound\n+from google.cloud.monitoring.resource import Resource\n \n \n _GROUP_TEMPLATE = re.compile(r\"\"\"\n@@ -73,7 +73,7 @@ def _group_name_from_id(project, group_id):\n class Group(object):\n \"\"\"A dynamic collection of monitored resources.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: A client for operating on the metric descriptor.\n \n :type group_id: string or None\n@@ -242,7 +242,7 @@ def list_children(self):\n Returns groups whose parent_name field contains the group name. If no\n groups have this parent, the results are empty.\n \n- :rtype: list of :class:`~gcloud.monitoring.group.Group`\n+ :rtype: list of :class:`~google.cloud.monitoring.group.Group`\n :returns: A list of group instances.\n \"\"\"\n return self._list(self.client, children_of_group=self.name)\n@@ -254,7 +254,7 @@ def list_ancestors(self):\n and ending with the most distant ancestor. If the specified group has\n no immediate parent, the results are empty.\n \n- :rtype: list of :class:`~gcloud.monitoring.group.Group`\n+ :rtype: list of :class:`~google.cloud.monitoring.group.Group`\n :returns: A list of group instances.\n \"\"\"\n return self._list(self.client, ancestors_of_group=self.name)\n@@ -265,7 +265,7 @@ def list_descendants(self):\n This returns a superset of the results returned by the :meth:`children`\n method, and includes children-of-children, and so forth.\n \n- :rtype: list of :class:`~gcloud.monitoring.group.Group`\n+ :rtype: list of :class:`~google.cloud.monitoring.group.Group`\n :returns: A list of group instances.\n \"\"\"\n return self._list(self.client, descendants_of_group=self.name)\n@@ -313,7 +313,7 @@ def list_members(self, filter_string=None, end_time=None, start_time=None):\n The start time (exclusive) of the time interval for which results\n should be returned, as a datetime object.\n \n- :rtype: list of :class:`~gcloud.monitoring.resource.Resource`\n+ :rtype: list of :class:`~google.cloud.monitoring.resource.Resource`\n :returns: A list of resource instances.\n \n :raises:\n@@ -362,7 +362,7 @@ def list_members(self, filter_string=None, end_time=None, start_time=None):\n def _fetch(cls, client, group_id):\n \"\"\"Fetch a group from the API based on it's ID.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type group_id: string\n@@ -371,7 +371,7 @@ def _fetch(cls, client, group_id):\n :rtype: :class:`Group`\n :returns: The group instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the group\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the group\n is not found.\n \"\"\"\n new_group = cls(client, group_id)\n@@ -383,7 +383,7 @@ def _list(cls, client, children_of_group=None, ancestors_of_group=None,\n descendants_of_group=None):\n \"\"\"Lists all groups in the project.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type children_of_group: string or None\n@@ -402,7 +402,7 @@ def _list(cls, client, children_of_group=None, ancestors_of_group=None,\n of the results returned by the children_of_group filter, and\n includes children-of-children, and so forth.\n \n- :rtype: list of :class:`~gcloud.monitoring.group.Group`\n+ :rtype: list of :class:`~google.cloud.monitoring.group.Group`\n :returns: A list of group instances.\n \"\"\"\n path = '/projects/%s/groups/' % (client.project,)\n@@ -438,7 +438,7 @@ def _list(cls, client, children_of_group=None, ancestors_of_group=None,\n def _from_dict(cls, client, info):\n \"\"\"Constructs a Group instance from the parsed JSON representation.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: A client to be included in the returned object.\n \n :type info: dict\ndiff --git a/gcloud/monitoring/label.py b/google/cloud/monitoring/label.py\nsimilarity index 100%\nrename from gcloud/monitoring/label.py\nrename to google/cloud/monitoring/label.py\ndiff --git a/gcloud/monitoring/metric.py b/google/cloud/monitoring/metric.py\nsimilarity index 93%\nrename from gcloud/monitoring/metric.py\nrename to google/cloud/monitoring/metric.py\n--- a/gcloud/monitoring/metric.py\n+++ b/google/cloud/monitoring/metric.py\n@@ -21,7 +21,7 @@\n \n import collections\n \n-from gcloud.monitoring.label import LabelDescriptor\n+from google.cloud.monitoring.label import LabelDescriptor\n \n \n class MetricKind(object):\n@@ -62,10 +62,10 @@ class MetricDescriptor(object):\n \"\"\"Specification of a metric type and its schema.\n \n The preferred way to construct a metric descriptor object is using the\n- :meth:`~gcloud.monitoring.client.Client.metric_descriptor` factory method\n- of the :class:`~gcloud.monitoring.client.Client` class.\n+ :meth:`~google.cloud.monitoring.client.Client.metric_descriptor` factory\n+ method of the :class:`~google.cloud.monitoring.client.Client` class.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: A client for operating on the metric descriptor.\n \n :type type_: string\n@@ -87,7 +87,8 @@ class MetricDescriptor(object):\n or :data:`ValueType.DISTRIBUTION`.\n See :class:`ValueType`.\n \n- :type labels: list of :class:`~gcloud.monitoring.label.LabelDescriptor`\n+ :type labels:\n+ list of :class:`~google.cloud.monitoring.label.LabelDescriptor`\n :param labels:\n A sequence of zero or more label descriptors specifying the labels\n used to identify a specific instance of this metric.\n@@ -172,7 +173,7 @@ def delete(self):\n def _fetch(cls, client, metric_type):\n \"\"\"Look up a metric descriptor by type.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type metric_type: string\n@@ -181,8 +182,8 @@ def _fetch(cls, client, metric_type):\n :rtype: :class:`MetricDescriptor`\n :returns: The metric descriptor instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the metric descriptor\n- is not found.\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the metric\n+ descriptor is not found.\n \"\"\"\n path = '/projects/{project}/metricDescriptors/{type}'.format(\n project=client.project,\n@@ -194,7 +195,7 @@ def _fetch(cls, client, metric_type):\n def _list(cls, client, filter_string=None, type_prefix=None):\n \"\"\"List all metric descriptors for the project.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type filter_string: string or None\n@@ -250,7 +251,7 @@ def _list(cls, client, filter_string=None, type_prefix=None):\n def _from_dict(cls, client, info):\n \"\"\"Construct a metric descriptor from the parsed JSON representation.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: A client to be included in the returned object.\n \n :type info: dict\n@@ -320,8 +321,8 @@ class Metric(collections.namedtuple('Metric', 'type labels')):\n \"\"\"A specific metric identified by specifying values for all labels.\n \n The preferred way to construct a metric object is using the\n- :meth:`~gcloud.monitoring.client.Client.metric` factory method\n- of the :class:`~gcloud.monitoring.client.Client` class.\n+ :meth:`~google.cloud.monitoring.client.Client.metric` factory method\n+ of the :class:`~google.cloud.monitoring.client.Client` class.\n \n :type type: string\n :param type: The metric type name.\ndiff --git a/gcloud/monitoring/query.py b/google/cloud/monitoring/query.py\nsimilarity index 97%\nrename from gcloud/monitoring/query.py\nrename to google/cloud/monitoring/query.py\n--- a/gcloud/monitoring/query.py\n+++ b/google/cloud/monitoring/query.py\n@@ -25,9 +25,9 @@\n \n import six\n \n-from gcloud._helpers import _datetime_to_rfc3339\n-from gcloud.monitoring._dataframe import _build_dataframe\n-from gcloud.monitoring.timeseries import TimeSeries\n+from google.cloud._helpers import _datetime_to_rfc3339\n+from google.cloud.monitoring._dataframe import _build_dataframe\n+from google.cloud.monitoring.timeseries import TimeSeries\n \n _UTCNOW = datetime.datetime.utcnow # To be replaced by tests.\n \n@@ -72,16 +72,16 @@ class Query(object):\n \"\"\"Query object for retrieving metric data.\n \n The preferred way to construct a query object is using the\n- :meth:`~gcloud.monitoring.client.Client.query` method\n- of the :class:`~gcloud.monitoring.client.Client` class.\n+ :meth:`~google.cloud.monitoring.client.Client.query` method\n+ of the :class:`~google.cloud.monitoring.client.Client` class.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type metric_type: string\n :param metric_type: The metric type name. The default value is\n :data:`Query.DEFAULT_METRIC_TYPE\n- `,\n+ `,\n but please note that this default value is provided only for\n demonstration purposes and is subject to change. See the\n `supported metrics`_.\n@@ -97,7 +97,7 @@ class Query(object):\n \n It is also allowed to omit the end time and duration here,\n in which case\n- :meth:`~gcloud.monitoring.query.Query.select_interval`\n+ :meth:`~google.cloud.monitoring.query.Query.select_interval`\n must be called before the query is executed.\n \n :type days: integer\n@@ -112,7 +112,7 @@ class Query(object):\n :raises: :exc:`ValueError` if ``end_time`` is specified but\n ``days``, ``hours``, and ``minutes`` are all zero.\n If you really want to specify a point in time, use\n- :meth:`~gcloud.monitoring.query.Query.select_interval`.\n+ :meth:`~google.cloud.monitoring.query.Query.select_interval`.\n \n .. _supported metrics: https://cloud.google.com/monitoring/api/metrics\n \"\"\"\n@@ -430,7 +430,7 @@ def iter(self, headers_only=False, page_size=None):\n \"\"\"Yield all time series objects selected by the query.\n \n The generator returned iterates over\n- :class:`~gcloud.monitoring.timeseries.TimeSeries` objects\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries` objects\n containing points ordered from oldest to newest.\n \n Note that the :class:`Query` object itself is an iterable, such that\n@@ -508,7 +508,7 @@ def _build_query_params(self, headers_only=False,\n :type headers_only: boolean\n :param headers_only:\n Whether to omit the point data from the\n- :class:`~gcloud.monitoring.timeseries.TimeSeries` objects.\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries` objects.\n \n :type page_size: integer or None\n :param page_size: A limit on the number of points to return per page.\ndiff --git a/gcloud/monitoring/resource.py b/google/cloud/monitoring/resource.py\nsimilarity index 91%\nrename from gcloud/monitoring/resource.py\nrename to google/cloud/monitoring/resource.py\n--- a/gcloud/monitoring/resource.py\n+++ b/google/cloud/monitoring/resource.py\n@@ -22,7 +22,7 @@\n \n import collections\n \n-from gcloud.monitoring.label import LabelDescriptor\n+from google.cloud.monitoring.label import LabelDescriptor\n \n \n class ResourceDescriptor(object):\n@@ -45,7 +45,8 @@ class ResourceDescriptor(object):\n :param description:\n A detailed description that might be used in documentation.\n \n- :type labels: list of :class:`~gcloud.monitoring.label.LabelDescriptor`\n+ :type labels:\n+ list of :class:`~google.cloud.monitoring.label.LabelDescriptor`\n :param labels:\n A sequence of label descriptors specifying the labels used\n to identify a specific instance of this monitored resource.\n@@ -62,7 +63,7 @@ def __init__(self, name, type_, display_name, description, labels):\n def _fetch(cls, client, resource_type):\n \"\"\"Look up a monitored resource descriptor by type.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type resource_type: string\n@@ -71,8 +72,8 @@ def _fetch(cls, client, resource_type):\n :rtype: :class:`ResourceDescriptor`\n :returns: The resource descriptor instance.\n \n- :raises: :class:`gcloud.exceptions.NotFound` if the resource descriptor\n- is not found.\n+ :raises: :class:`google.cloud.exceptions.NotFound` if the resource\n+ descriptor is not found.\n \"\"\"\n path = ('/projects/{project}/monitoredResourceDescriptors/{type}'\n .format(project=client.project,\n@@ -84,7 +85,7 @@ def _fetch(cls, client, resource_type):\n def _list(cls, client, filter_string=None):\n \"\"\"List all monitored resource descriptors for the project.\n \n- :type client: :class:`gcloud.monitoring.client.Client`\n+ :type client: :class:`google.cloud.monitoring.client.Client`\n :param client: The client to use.\n \n :type filter_string: string or None\n@@ -159,8 +160,8 @@ class Resource(collections.namedtuple('Resource', 'type labels')):\n \"\"\"A monitored resource identified by specifying values for all labels.\n \n The preferred way to construct a resource object is using the\n- :meth:`~gcloud.monitoring.client.Client.resource` factory method\n- of the :class:`~gcloud.monitoring.client.Client` class.\n+ :meth:`~google.cloud.monitoring.client.Client.resource` factory method\n+ of the :class:`~google.cloud.monitoring.client.Client` class.\n \n :type type: string\n :param type: The resource type name.\ndiff --git a/gcloud/monitoring/timeseries.py b/google/cloud/monitoring/timeseries.py\nsimilarity index 88%\nrename from gcloud/monitoring/timeseries.py\nrename to google/cloud/monitoring/timeseries.py\n--- a/gcloud/monitoring/timeseries.py\n+++ b/google/cloud/monitoring/timeseries.py\n@@ -24,8 +24,8 @@\n \n import collections\n \n-from gcloud.monitoring.metric import Metric\n-from gcloud.monitoring.resource import Resource\n+from google.cloud.monitoring.metric import Metric\n+from google.cloud.monitoring.resource import Resource\n \n \n class TimeSeries(collections.namedtuple(\n@@ -33,28 +33,29 @@ class TimeSeries(collections.namedtuple(\n \"\"\"A single time series of metric values.\n \n The preferred way to construct a\n- :class:`~gcloud.monitoring.timeseries.TimeSeries` object is\n- using the :meth:`~gcloud.monitoring.client.Client.time_series` factory\n- method of the :class:`~gcloud.monitoring.client.Client` class.\n+ :class:`~google.cloud.monitoring.timeseries.TimeSeries` object is\n+ using the :meth:`~google.cloud.monitoring.client.Client.time_series`\n+ factory method of the :class:`~google.cloud.monitoring.client.Client`\n+ class.\n \n- :type metric: :class:`~gcloud.monitoring.metric.Metric`\n+ :type metric: :class:`~google.cloud.monitoring.metric.Metric`\n :param metric: A metric object.\n \n- :type resource: :class:`~gcloud.monitoring.resource.Resource`\n+ :type resource: :class:`~google.cloud.monitoring.resource.Resource`\n :param resource: A resource object.\n \n :type metric_kind: string\n :param metric_kind:\n The kind of measurement: :data:`MetricKind.GAUGE`,\n :data:`MetricKind.DELTA`, or :data:`MetricKind.CUMULATIVE`.\n- See :class:`~gcloud.monitoring.metric.MetricKind`.\n+ See :class:`~google.cloud.monitoring.metric.MetricKind`.\n \n :type value_type: string\n :param value_type:\n The value type of the metric: :data:`ValueType.BOOL`,\n :data:`ValueType.INT64`, :data:`ValueType.DOUBLE`,\n :data:`ValueType.STRING`, or :data:`ValueType.DISTRIBUTION`.\n- See :class:`~gcloud.monitoring.metric.ValueType`.\n+ See :class:`~google.cloud.monitoring.metric.ValueType`.\n \n :type points: list of :class:`Point`\n :param points: A list of point objects.\ndiff --git a/gcloud/operation.py b/google/cloud/operation.py\nsimilarity index 100%\nrename from gcloud/operation.py\nrename to google/cloud/operation.py\ndiff --git a/gcloud/pubsub/__init__.py b/google/cloud/pubsub/__init__.py\nsimilarity index 64%\nrename from gcloud/pubsub/__init__.py\nrename to google/cloud/pubsub/__init__.py\n--- a/gcloud/pubsub/__init__.py\n+++ b/google/cloud/pubsub/__init__.py\n@@ -16,17 +16,16 @@\n \n The main concepts with this API are:\n \n-- :class:`gcloud.pubsub.topic.Topic` represents an endpoint to which messages\n- can be published using the Cloud Storage Pubsub API.\n+- :class:`~google.cloud.pubsub.topic.Topic` represents an endpoint to which\n+ messages can be published using the Cloud Storage Pubsub API.\n \n-- :class:`gcloud.pubsub.subscription.Subscription` represents a named\n+- :class:`~google.cloud.pubsub.subscription.Subscription` represents a named\n subscription (either pull or push) to a topic.\n \"\"\"\n \n-from gcloud.pubsub.client import Client\n-from gcloud.pubsub.connection import Connection\n-from gcloud.pubsub.subscription import Subscription\n-from gcloud.pubsub.topic import Topic\n-\n-\n-SCOPE = Connection.SCOPE\n+try:\n+ import pkg_resources\n+ pkg_resources.declare_namespace(__name__)\n+except ImportError:\n+ import pkgutil\n+ __path__ = pkgutil.extend_path(__path__, __name__)\ndiff --git a/gcloud/pubsub/_gax.py b/google/cloud/pubsub/_gax.py\nsimilarity index 97%\nrename from gcloud/pubsub/_gax.py\nrename to google/cloud/pubsub/_gax.py\n--- a/gcloud/pubsub/_gax.py\n+++ b/google/cloud/pubsub/_gax.py\n@@ -21,10 +21,12 @@\n from google.pubsub.v1.pubsub_pb2 import PushConfig\n from grpc import StatusCode\n \n-from gcloud._helpers import _to_bytes\n-from gcloud._helpers import exc_to_code\n-from gcloud.exceptions import Conflict\n-from gcloud.exceptions import NotFound\n+# pylint: disable=ungrouped-imports\n+from google.cloud._helpers import _to_bytes\n+from google.cloud._helpers import exc_to_code\n+from google.cloud.exceptions import Conflict\n+from google.cloud.exceptions import NotFound\n+# pylint: enable=ungrouped-imports\n \n \n class _PublisherAPI(object):\n@@ -82,7 +84,7 @@ def topic_create(self, topic_path):\n \n :rtype: dict\n :returns: ``Topic`` resource returned from the API.\n- :raises: :exc:`gcloud.exceptions.Conflict` if the topic already\n+ :raises: :exc:`google.cloud.exceptions.Conflict` if the topic already\n exists\n \"\"\"\n try:\n@@ -105,7 +107,7 @@ def topic_get(self, topic_path):\n \n :rtype: dict\n :returns: ``Topic`` resource returned from the API.\n- :raises: :exc:`gcloud.exceptions.NotFound` if the topic does not\n+ :raises: :exc:`google.cloud.exceptions.NotFound` if the topic does not\n exist\n \"\"\"\n try:\n@@ -148,7 +150,7 @@ def topic_publish(self, topic_path, messages):\n \n :rtype: list of string\n :returns: list of opaque IDs for published messages.\n- :raises: :exc:`gcloud.exceptions.NotFound` if the topic does not\n+ :raises: :exc:`google.cloud.exceptions.NotFound` if the topic does not\n exist\n \"\"\"\n options = CallOptions(is_bundling=False)\n@@ -186,7 +188,7 @@ def topic_list_subscriptions(self, topic_path, page_size=0,\n :rtype: list of strings\n :returns: fully-qualified names of subscriptions for the supplied\n topic.\n- :raises: :exc:`gcloud.exceptions.NotFound` if the topic does not\n+ :raises: :exc:`google.cloud.exceptions.NotFound` if the topic does not\n exist\n \"\"\"\n if page_token is None:\ndiff --git a/gcloud/pubsub/_helpers.py b/google/cloud/pubsub/_helpers.py\nsimilarity index 97%\nrename from gcloud/pubsub/_helpers.py\nrename to google/cloud/pubsub/_helpers.py\n--- a/gcloud/pubsub/_helpers.py\n+++ b/google/cloud/pubsub/_helpers.py\n@@ -16,7 +16,7 @@\n \n import re\n \n-from gcloud._helpers import _name_from_project_path\n+from google.cloud._helpers import _name_from_project_path\n \n \n _TOPIC_TEMPLATE = re.compile(r\"\"\"\ndiff --git a/gcloud/pubsub/client.py b/google/cloud/pubsub/client.py\nsimilarity index 89%\nrename from gcloud/pubsub/client.py\nrename to google/cloud/pubsub/client.py\n--- a/gcloud/pubsub/client.py\n+++ b/google/cloud/pubsub/client.py\n@@ -16,13 +16,13 @@\n \n import os\n \n-from gcloud.client import JSONClient\n-from gcloud.pubsub.connection import Connection\n-from gcloud.pubsub.connection import _PublisherAPI as JSONPublisherAPI\n-from gcloud.pubsub.connection import _SubscriberAPI as JSONSubscriberAPI\n-from gcloud.pubsub.connection import _IAMPolicyAPI\n-from gcloud.pubsub.subscription import Subscription\n-from gcloud.pubsub.topic import Topic\n+from google.cloud.client import JSONClient\n+from google.cloud.pubsub.connection import Connection\n+from google.cloud.pubsub.connection import _PublisherAPI as JSONPublisherAPI\n+from google.cloud.pubsub.connection import _SubscriberAPI as JSONSubscriberAPI\n+from google.cloud.pubsub.connection import _IAMPolicyAPI\n+from google.cloud.pubsub.subscription import Subscription\n+from google.cloud.pubsub.topic import Topic\n \n # pylint: disable=ungrouped-imports\n try:\n@@ -30,8 +30,8 @@\n PublisherApi as GeneratedPublisherAPI)\n from google.cloud.pubsub.v1.subscriber_api import (\n SubscriberApi as GeneratedSubscriberAPI)\n- from gcloud.pubsub._gax import _PublisherAPI as GAXPublisherAPI\n- from gcloud.pubsub._gax import _SubscriberAPI as GAXSubscriberAPI\n+ from google.cloud.pubsub._gax import _PublisherAPI as GAXPublisherAPI\n+ from google.cloud.pubsub._gax import _SubscriberAPI as GAXSubscriberAPI\n except ImportError: # pragma: NO COVER\n _HAVE_GAX = False\n GeneratedPublisherAPI = GAXPublisherAPI = None\n@@ -41,7 +41,7 @@\n # pylint: enable=ungrouped-imports\n \n \n-_DISABLE_GAX = os.getenv('GCLOUD_DISABLE_GAX', False)\n+_DISABLE_GAX = os.getenv('GOOGLE_CLOUD_DISABLE_GAX', False)\n _USE_GAX = _HAVE_GAX and not _DISABLE_GAX\n \n \n@@ -120,7 +120,7 @@ def list_topics(self, page_size=None, page_token=None):\n topics.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.pubsub.topic.Topic`, plus a\n+ :returns: list of :class:`google.cloud.pubsub.topic.Topic`, plus a\n \"next page token\" string: if not None, indicates that\n more topics can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -154,7 +154,7 @@ def list_subscriptions(self, page_size=None, page_token=None):\n topics.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.pubsub.subscription.Subscription`,\n+ :returns: list of :class:`~.pubsub.subscription.Subscription`,\n plus a \"next page token\" string: if not None, indicates that\n more topics can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -183,7 +183,7 @@ def topic(self, name, timestamp_messages=False):\n :type timestamp_messages: boolean\n :param timestamp_messages: To be passed to ``Topic`` constructor.\n \n- :rtype: :class:`gcloud.pubsub.topic.Topic`\n+ :rtype: :class:`google.cloud.pubsub.topic.Topic`\n :returns: Topic created with the current client.\n \"\"\"\n return Topic(name, client=self, timestamp_messages=timestamp_messages)\ndiff --git a/gcloud/pubsub/connection.py b/google/cloud/pubsub/connection.py\nsimilarity index 99%\nrename from gcloud/pubsub/connection.py\nrename to google/cloud/pubsub/connection.py\n--- a/gcloud/pubsub/connection.py\n+++ b/google/cloud/pubsub/connection.py\n@@ -12,12 +12,12 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud pubsub connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud Pub/Sub connections.\"\"\"\n \n import os\n \n-from gcloud import connection as base_connection\n-from gcloud.environment_vars import PUBSUB_EMULATOR\n+from google.cloud import connection as base_connection\n+from google.cloud.environment_vars import PUBSUB_EMULATOR\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/pubsub/iam.py b/google/cloud/pubsub/iam.py\nsimilarity index 100%\nrename from gcloud/pubsub/iam.py\nrename to google/cloud/pubsub/iam.py\ndiff --git a/gcloud/pubsub/message.py b/google/cloud/pubsub/message.py\nsimilarity index 98%\nrename from gcloud/pubsub/message.py\nrename to google/cloud/pubsub/message.py\n--- a/gcloud/pubsub/message.py\n+++ b/google/cloud/pubsub/message.py\n@@ -16,7 +16,7 @@\n \n import base64\n \n-from gcloud._helpers import _rfc3339_to_datetime\n+from google.cloud._helpers import _rfc3339_to_datetime\n \n \n class Message(object):\ndiff --git a/gcloud/pubsub/subscription.py b/google/cloud/pubsub/subscription.py\nsimilarity index 88%\nrename from gcloud/pubsub/subscription.py\nrename to google/cloud/pubsub/subscription.py\n--- a/gcloud/pubsub/subscription.py\n+++ b/google/cloud/pubsub/subscription.py\n@@ -14,10 +14,10 @@\n \n \"\"\"Define API Subscriptions.\"\"\"\n \n-from gcloud.exceptions import NotFound\n-from gcloud.pubsub._helpers import topic_name_from_path\n-from gcloud.pubsub.iam import Policy\n-from gcloud.pubsub.message import Message\n+from google.cloud.exceptions import NotFound\n+from google.cloud.pubsub._helpers import topic_name_from_path\n+from google.cloud.pubsub.iam import Policy\n+from google.cloud.pubsub.message import Message\n \n \n class Subscription(object):\n@@ -29,7 +29,7 @@ class Subscription(object):\n :type name: string\n :param name: the name of the subscription.\n \n- :type topic: :class:`gcloud.pubsub.topic.Topic` or ``NoneType``\n+ :type topic: :class:`google.cloud.pubsub.topic.Topic` or ``NoneType``\n :param topic: the topic to which the subscription belongs; if ``None``,\n the subscription's topic has been deleted.\n \n@@ -41,7 +41,8 @@ class Subscription(object):\n :param push_endpoint: URL to which messages will be pushed by the back-end.\n If not set, the application must pull messages.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the topic.\n \"\"\"\n@@ -76,7 +77,7 @@ def from_api_repr(cls, resource, client, topics=None):\n :type resource: dict\n :param resource: topic resource representation returned from the API.\n \n- :type client: :class:`gcloud.pubsub.client.Client`\n+ :type client: :class:`google.cloud.pubsub.client.Client`\n :param client: Client which holds credentials and project\n configuration for a topic.\n \n@@ -84,7 +85,7 @@ def from_api_repr(cls, resource, client, topics=None):\n :param topics: A mapping of topic names -> topics. If not passed,\n the subscription will have a newly-created topic.\n \n- :rtype: :class:`gcloud.pubsub.subscription.Subscription`\n+ :rtype: :class:`google.cloud.pubsub.subscription.Subscription`\n :returns: Subscription parsed from ``resource``.\n \"\"\"\n if topics is None:\n@@ -132,7 +133,8 @@ def auto_ack(self, return_immediately=False, max_messages=1, client=None):\n :type max_messages: int\n :param max_messages: passed through to :meth:`Subscription.pull`\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: passed through to :meth:`Subscription.pull` and\n :meth:`Subscription.acknowledge`.\n \n@@ -144,12 +146,13 @@ def auto_ack(self, return_immediately=False, max_messages=1, client=None):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the topic of the\n current subscription.\n \n- :rtype: :class:`gcloud.pubsub.client.Client`\n+ :rtype: :class:`google.cloud.pubsub.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -168,7 +171,8 @@ def create(self, client=None):\n :start-after: [START subscription_create]\n :end-before: [END subscription_create]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -190,7 +194,8 @@ def exists(self, client=None):\n :start-after: [START subscription_exists]\n :end-before: [END subscription_exists]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \n@@ -218,7 +223,8 @@ def reload(self, client=None):\n :start-after: [START subscription_reload]\n :end-before: [END subscription_reload]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -241,7 +247,8 @@ def delete(self, client=None):\n :start-after: [START subscription_delete]\n :end-before: [END subscription_delete]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -270,7 +277,8 @@ def modify_push_configuration(self, push_endpoint, client=None):\n back-end. If None, the application must pull\n messages.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -300,14 +308,16 @@ def pull(self, return_immediately=False, max_messages=1, client=None):\n :type max_messages: int\n :param max_messages: the maximum number of messages to return.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \n :rtype: list of (ack_id, message) tuples\n :returns: sequence of tuples: ``ack_id`` is the ID to be used in a\n subsequent call to :meth:`acknowledge`, and ``message``\n- is an instance of :class:`gcloud.pubsub.message.Message`.\n+ is an instance of\n+ :class:`~google.cloud.pubsub.message.Message`.\n \"\"\"\n client = self._require_client(client)\n api = client.subscriber_api\n@@ -331,7 +341,8 @@ def acknowledge(self, ack_ids, client=None):\n :type ack_ids: list of string\n :param ack_ids: ack IDs of messages being acknowledged\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -351,7 +362,8 @@ def modify_ack_deadline(self, ack_ids, ack_deadline, client=None):\n :type ack_deadline: int\n :param ack_deadline: new deadline for the message, in seconds\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \"\"\"\n@@ -372,11 +384,12 @@ def get_iam_policy(self, client=None):\n :start-after: [START subscription_get_iam_policy]\n :end-before: [END subscription_get_iam_policy]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \n- :rtype: :class:`gcloud.pubsub.iam.Policy`\n+ :rtype: :class:`google.cloud.pubsub.iam.Policy`\n :returns: policy created from the resource returned by the\n ``getIamPolicy`` API request.\n \"\"\"\n@@ -397,15 +410,16 @@ def set_iam_policy(self, policy, client=None):\n :start-after: [START subscription_set_iam_policy]\n :end-before: [END subscription_set_iam_policy]\n \n- :type policy: :class:`gcloud.pubsub.iam.Policy`\n+ :type policy: :class:`google.cloud.pubsub.iam.Policy`\n :param policy: the new policy, typically fetched via\n :meth:`get_iam_policy` and updated in place.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \n- :rtype: :class:`gcloud.pubsub.iam.Policy`\n+ :rtype: :class:`google.cloud.pubsub.iam.Policy`\n :returns: updated policy created from the resource returned by the\n ``setIamPolicy`` API request.\n \"\"\"\n@@ -430,7 +444,8 @@ def check_iam_permissions(self, permissions, client=None):\n :type permissions: list of string\n :param permissions: list of permissions to be tested\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current subscription's topic.\n \n@@ -471,7 +486,8 @@ class AutoAck(dict):\n :type max_messages: int\n :param max_messages: passed through to :meth:`Subscription.pull`\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: passed through to :meth:`Subscription.pull` and\n :meth:`Subscription.acknowledge`.\n \"\"\"\ndiff --git a/gcloud/pubsub/topic.py b/google/cloud/pubsub/topic.py\nsimilarity index 87%\nrename from gcloud/pubsub/topic.py\nrename to google/cloud/pubsub/topic.py\n--- a/gcloud/pubsub/topic.py\n+++ b/google/cloud/pubsub/topic.py\n@@ -16,13 +16,13 @@\n \n import base64\n \n-from gcloud._helpers import _datetime_to_rfc3339\n-from gcloud._helpers import _NOW\n-from gcloud.exceptions import NotFound\n-from gcloud.pubsub._helpers import subscription_name_from_path\n-from gcloud.pubsub._helpers import topic_name_from_path\n-from gcloud.pubsub.iam import Policy\n-from gcloud.pubsub.subscription import Subscription\n+from google.cloud._helpers import _datetime_to_rfc3339\n+from google.cloud._helpers import _NOW\n+from google.cloud.exceptions import NotFound\n+from google.cloud.pubsub._helpers import subscription_name_from_path\n+from google.cloud.pubsub._helpers import topic_name_from_path\n+from google.cloud.pubsub.iam import Policy\n+from google.cloud.pubsub.subscription import Subscription\n \n \n class Topic(object):\n@@ -36,7 +36,7 @@ class Topic(object):\n :type name: string\n :param name: the name of the topic\n \n- :type client: :class:`gcloud.pubsub.client.Client`\n+ :type client: :class:`google.cloud.pubsub.client.Client`\n :param client: A client which holds credentials and project configuration\n for the topic (which requires a project).\n \n@@ -96,11 +96,11 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: topic resource representation returned from the API\n \n- :type client: :class:`gcloud.pubsub.client.Client`\n+ :type client: :class:`google.cloud.pubsub.client.Client`\n :param client: Client which holds credentials and project\n configuration for the topic.\n \n- :rtype: :class:`gcloud.pubsub.topic.Topic`\n+ :rtype: :class:`google.cloud.pubsub.topic.Topic`\n :returns: Topic parsed from ``resource``.\n :raises: :class:`ValueError` if ``client`` is not ``None`` and the\n project from the resource does not agree with the project\n@@ -122,11 +122,12 @@ def full_name(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n- :rtype: :class:`gcloud.pubsub.client.Client`\n+ :rtype: :class:`google.cloud.pubsub.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -145,7 +146,8 @@ def create(self, client=None):\n :start-after: [START topic_create]\n :end-before: [END topic_create]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \"\"\"\n@@ -165,7 +167,8 @@ def exists(self, client=None):\n :start-after: [START topic_exists]\n :end-before: [END topic_exists]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n@@ -194,7 +197,8 @@ def delete(self, client=None):\n :start-after: [START topic_delete]\n :end-before: [END topic_delete]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \"\"\"\n@@ -233,7 +237,8 @@ def publish(self, message, client=None, **attrs):\n :type message: bytes\n :param message: the message payload\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n@@ -267,7 +272,8 @@ def batch(self, client=None):\n used as a context manager, and only if the block exits without\n raising an exception.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n@@ -298,12 +304,13 @@ def list_subscriptions(self, page_size=None, page_token=None, client=None):\n passed, the API will return the first page of\n topics.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n \n :rtype: tuple, (list, str)\n- :returns: list of :class:`gcloud.pubsub.subscription.Subscription`,\n+ :returns: list of :class:`~.pubsub.subscription.Subscription`,\n plus a \"next page token\" string: if not None, indicates that\n more topics can be retrieved with another call (pass that\n value as ``page_token``).\n@@ -330,11 +337,12 @@ def get_iam_policy(self, client=None):\n :start-after: [START topic_get_iam_policy]\n :end-before: [END topic_get_iam_policy]\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n \n- :rtype: :class:`gcloud.pubsub.iam.Policy`\n+ :rtype: :class:`google.cloud.pubsub.iam.Policy`\n :returns: policy created from the resource returned by the\n ``getIamPolicy`` API request.\n \"\"\"\n@@ -355,15 +363,16 @@ def set_iam_policy(self, policy, client=None):\n :start-after: [START topic_set_iam_policy]\n :end-before: [END topic_set_iam_policy]\n \n- :type policy: :class:`gcloud.pubsub.iam.Policy`\n+ :type policy: :class:`google.cloud.pubsub.iam.Policy`\n :param policy: the new policy, typically fetched via\n :meth:`get_iam_policy` and updated in place.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n \n- :rtype: :class:`gcloud.pubsub.iam.Policy`\n+ :rtype: :class:`google.cloud.pubsub.iam.Policy`\n :returns: updated policy created from the resource returned by the\n ``setIamPolicy`` API request.\n \"\"\"\n@@ -388,7 +397,8 @@ def check_iam_permissions(self, permissions, client=None):\n :type permissions: list of string\n :param permissions: list of permissions to be tested\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n \n@@ -406,10 +416,10 @@ class Batch(object):\n \n Helper returned by :meth:Topic.batch\n \n- :type topic: :class:`gcloud.pubsub.topic.Topic`\n+ :type topic: :class:`google.cloud.pubsub.topic.Topic`\n :param topic: the topic being published\n \n- :type client: :class:`gcloud.pubsub.client.Client`\n+ :type client: :class:`google.cloud.pubsub.client.Client`\n :param client: The client to use.\n \"\"\"\n def __init__(self, topic, client):\n@@ -445,7 +455,8 @@ def publish(self, message, **attrs):\n def commit(self, client=None):\n \"\"\"Send saved messages as a single API call.\n \n- :type client: :class:`gcloud.pubsub.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.pubsub.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n \"\"\"\ndiff --git a/gcloud/resource_manager/__init__.py b/google/cloud/resource_manager/__init__.py\nsimilarity index 79%\nrename from gcloud/resource_manager/__init__.py\nrename to google/cloud/resource_manager/__init__.py\n--- a/gcloud/resource_manager/__init__.py\n+++ b/google/cloud/resource_manager/__init__.py\n@@ -14,9 +14,10 @@\n \n \"\"\"Google Cloud Resource Manager API wrapper.\"\"\"\n \n-from gcloud.resource_manager.client import Client\n-from gcloud.resource_manager.connection import Connection\n-from gcloud.resource_manager.project import Project\n+\n+from google.cloud.resource_manager.client import Client\n+from google.cloud.resource_manager.connection import Connection\n+from google.cloud.resource_manager.project import Project\n \n \n SCOPE = Connection.SCOPE\ndiff --git a/gcloud/resource_manager/client.py b/google/cloud/resource_manager/client.py\nsimilarity index 90%\nrename from gcloud/resource_manager/client.py\nrename to google/cloud/resource_manager/client.py\n--- a/gcloud/resource_manager/client.py\n+++ b/google/cloud/resource_manager/client.py\n@@ -15,10 +15,10 @@\n \"\"\"A Client for interacting with the Resource Manager API.\"\"\"\n \n \n-from gcloud.client import Client as BaseClient\n-from gcloud.iterator import Iterator\n-from gcloud.resource_manager.connection import Connection\n-from gcloud.resource_manager.project import Project\n+from google.cloud.client import Client as BaseClient\n+from google.cloud.iterator import Iterator\n+from google.cloud.resource_manager.connection import Connection\n+from google.cloud.resource_manager.project import Project\n \n \n class Client(BaseClient):\n@@ -30,7 +30,7 @@ class Client(BaseClient):\n \n Automatically get credentials::\n \n- >>> from gcloud import resource_manager\n+ >>> from google.cloud import resource_manager\n >>> client = resource_manager.Client()\n \n :type credentials: :class:`oauth2client.client.OAuth2Credentials` or\n@@ -52,7 +52,7 @@ def new_project(self, project_id, name=None, labels=None):\n \"\"\"Create a :class:`.Project` bound to the current client.\n \n Use :meth:`Project.reload() \\\n- ` to retrieve\n+ ` to retrieve\n project metadata after creating a :class:`.Project` instance.\n \n .. note:\n@@ -81,7 +81,7 @@ def fetch_project(self, project_id):\n .. note::\n \n If the project does not exist, this will raise a\n- :class:`NotFound ` error.\n+ :class:`NotFound ` error.\n \n :type project_id: str\n :param project_id: The ID for this project.\n@@ -98,7 +98,7 @@ def list_projects(self, filter_params=None, page_size=None):\n \n Example::\n \n- >>> from gcloud import resource_manager\n+ >>> from google.cloud import resource_manager\n >>> client = resource_manager.Client()\n >>> for project in client.list_projects():\n ... print project.project_id\n@@ -106,7 +106,7 @@ def list_projects(self, filter_params=None, page_size=None):\n List all projects with label ``'environment'`` set to ``'prod'``\n (filtering by labels)::\n \n- >>> from gcloud import resource_manager\n+ >>> from google.cloud import resource_manager\n >>> client = resource_manager.Client()\n >>> env_filter = {'labels.environment': 'prod'}\n >>> for project in client.list_projects(env_filter):\n@@ -159,10 +159,10 @@ class _ProjectIterator(Iterator):\n \"\"\"An iterator over a list of Project resources.\n \n You shouldn't have to use this directly, but instead should use the\n- helper methods on :class:`gcloud.resource_manager.client.Client`\n+ helper methods on :class:`google.cloud.resource_manager.client.Client`\n objects.\n \n- :type client: :class:`gcloud.resource_manager.client.Client`\n+ :type client: :class:`google.cloud.resource_manager.client.Client`\n :param client: The client to use for making connections.\n \n :type extra_params: dict\ndiff --git a/gcloud/resource_manager/connection.py b/google/cloud/resource_manager/connection.py\nsimilarity index 92%\nrename from gcloud/resource_manager/connection.py\nrename to google/cloud/resource_manager/connection.py\n--- a/gcloud/resource_manager/connection.py\n+++ b/google/cloud/resource_manager/connection.py\n@@ -12,10 +12,10 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud.resource_manager connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud Resource Manager connections.\"\"\"\n \n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/resource_manager/project.py b/google/cloud/resource_manager/project.py\nsimilarity index 90%\nrename from gcloud/resource_manager/project.py\nrename to google/cloud/resource_manager/project.py\n--- a/gcloud/resource_manager/project.py\n+++ b/google/cloud/resource_manager/project.py\n@@ -15,7 +15,7 @@\n \"\"\"Utility for managing projects via the Cloud Resource Manager API.\"\"\"\n \n \n-from gcloud.exceptions import NotFound\n+from google.cloud.exceptions import NotFound\n \n \n class Project(object):\n@@ -25,11 +25,11 @@ class Project(object):\n \n A :class:`Project` can also be created via\n :meth:`Client.new_project() \\\n- `\n+ `\n \n To manage labels on a :class:`Project`::\n \n- >>> from gcloud import resource_manager\n+ >>> from google.cloud import resource_manager\n >>> client = resource_manager.Client()\n >>> project = client.new_project('purple-spaceship-123')\n >>> project.labels = {'color': 'purple'}\n@@ -42,7 +42,7 @@ class Project(object):\n :type project_id: string\n :param project_id: The globally unique ID of the project.\n \n- :type client: :class:`gcloud.resource_manager.client.Client`\n+ :type client: :class:`google.cloud.resource_manager.client.Client`\n :param client: The Client used with this project.\n \n :type name: string\n@@ -69,10 +69,10 @@ def from_api_repr(cls, resource, client):\n :type resource: dict\n :param resource: project resource representation returned from the API\n \n- :type client: :class:`gcloud.resource_manager.client.Client`\n+ :type client: :class:`google.cloud.resource_manager.client.Client`\n :param client: The Client used with this project.\n \n- :rtype: :class:`gcloud.resource_manager.project.Project`\n+ :rtype: :class:`google.cloud.resource_manager.project.Project`\n :returns: The project created.\n \"\"\"\n project = cls(project_id=resource['projectId'], client=client)\n@@ -101,12 +101,12 @@ def path(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current project.\n \n- :rtype: :class:`gcloud.resource_manager.client.Client`\n+ :rtype: :class:`google.cloud.resource_manager.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -119,7 +119,7 @@ def create(self, client=None):\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\n@@ -141,7 +141,7 @@ def reload(self, client=None):\n This method will reload the newest metadata for the project. If you've\n created a new :class:`Project` instance via\n :meth:`Client.new_project() \\\n- `,\n+ `,\n this method will retrieve project metadata.\n \n .. warning::\n@@ -152,7 +152,7 @@ def reload(self, client=None):\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/get\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\n@@ -170,7 +170,7 @@ def exists(self, client=None):\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/get\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\n@@ -195,7 +195,7 @@ def update(self, client=None):\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/update\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\n@@ -219,7 +219,7 @@ def delete(self, client=None, reload_data=False):\n ``DELETE_IN_PROGRESS`` state, which means the deleting has actually\n begun.\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\n@@ -249,7 +249,7 @@ def undelete(self, client=None, reload_data=False):\n If the project has already reached a status of ``DELETE_IN_PROGRESS``,\n this request will fail and the project cannot be restored.\n \n- :type client: :class:`gcloud.resource_manager.client.Client` or\n+ :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType `\n :param client: the client to use. If not passed, falls back to\n the client stored on the current project.\ndiff --git a/gcloud/storage/__init__.py b/google/cloud/storage/__init__.py\nsimilarity index 72%\nrename from gcloud/storage/__init__.py\nrename to google/cloud/storage/__init__.py\n--- a/gcloud/storage/__init__.py\n+++ b/google/cloud/storage/__init__.py\n@@ -16,7 +16,7 @@\n \n You'll typically use these to get started with the API:\n \n->>> from gcloud import storage\n+>>> from google.cloud import storage\n >>> client = storage.Client()\n >>> bucket = client.get_bucket('bucket-id-here')\n >>> # Then do other things...\n@@ -28,22 +28,22 @@\n \n The main concepts with this API are:\n \n-- :class:`gcloud.storage.connection.Connection` which represents a\n+- :class:`google.cloud.storage.connection.Connection` which represents a\n connection between your machine and the Cloud Storage API.\n \n-- :class:`gcloud.storage.bucket.Bucket` which represents a particular\n+- :class:`google.cloud.storage.bucket.Bucket` which represents a particular\n bucket (akin to a mounted disk on a computer).\n \n-- :class:`gcloud.storage.blob.Blob` which represents a pointer to a\n+- :class:`google.cloud.storage.blob.Blob` which represents a pointer to a\n particular entity in Cloud Storage (akin to a file path on a remote\n machine).\n \"\"\"\n \n-from gcloud.storage.batch import Batch\n-from gcloud.storage.blob import Blob\n-from gcloud.storage.bucket import Bucket\n-from gcloud.storage.client import Client\n-from gcloud.storage.connection import Connection\n+from google.cloud.storage.batch import Batch\n+from google.cloud.storage.blob import Blob\n+from google.cloud.storage.bucket import Bucket\n+from google.cloud.storage.client import Client\n+from google.cloud.storage.connection import Connection\n \n \n SCOPE = Connection.SCOPE\ndiff --git a/gcloud/storage/_helpers.py b/google/cloud/storage/_helpers.py\nsimilarity index 92%\nrename from gcloud/storage/_helpers.py\nrename to google/cloud/storage/_helpers.py\n--- a/gcloud/storage/_helpers.py\n+++ b/google/cloud/storage/_helpers.py\n@@ -50,11 +50,12 @@ def client(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current object.\n \n- :rtype: :class:`gcloud.storage.client.Client`\n+ :rtype: :class:`google.cloud.storage.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -64,7 +65,8 @@ def _require_client(self, client):\n def reload(self, client=None):\n \"\"\"Reload properties from Cloud Storage.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current object.\n \"\"\"\n@@ -98,7 +100,7 @@ def _patch_property(self, name, value):\n def _set_properties(self, value):\n \"\"\"Set the properties for the current object.\n \n- :type value: dict or :class:`gcloud.storage.batch._FutureDict`\n+ :type value: dict or :class:`google.cloud.storage.batch._FutureDict`\n :param value: The properties to be set.\n \"\"\"\n self._properties = value\n@@ -110,7 +112,8 @@ def patch(self, client=None):\n \n Updates the ``_properties`` with the response from the backend.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current object.\n \"\"\"\ndiff --git a/gcloud/storage/acl.py b/google/cloud/storage/acl.py\nsimilarity index 93%\nrename from gcloud/storage/acl.py\nrename to google/cloud/storage/acl.py\n--- a/gcloud/storage/acl.py\n+++ b/google/cloud/storage/acl.py\n@@ -14,11 +14,11 @@\n \n \"\"\"Manipulate access control lists that Cloud Storage provides.\n \n-:class:`gcloud.storage.bucket.Bucket` has a getting method that creates\n+:class:`google.cloud.storage.bucket.Bucket` has a getting method that creates\n an ACL object under the hood, and you can interact with that using\n-:func:`gcloud.storage.bucket.Bucket.acl`::\n+:func:`google.cloud.storage.bucket.Bucket.acl`::\n \n- >>> from gcloud import storage\n+ >>> from google.cloud import storage\n >>> client = storage.Client()\n >>> bucket = client.get_bucket(bucket_name)\n >>> acl = bucket.acl\n@@ -58,13 +58,13 @@\n >>> acl.all().grant_read().revoke_write()\n \n After that, you can save any changes you make with the\n-:func:`gcloud.storage.acl.ACL.save` method::\n+:func:`google.cloud.storage.acl.ACL.save` method::\n \n >>> acl.save()\n \n-You can alternatively save any existing :class:`gcloud.storage.acl.ACL`\n+You can alternatively save any existing :class:`google.cloud.storage.acl.ACL`\n object (whether it was created by a factory method or not) from a\n-:class:`gcloud.storage.bucket.Bucket`::\n+:class:`google.cloud.storage.bucket.Bucket`::\n \n >>> bucket.acl.save(acl=acl)\n \n@@ -382,11 +382,12 @@ def client(self):\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current ACL.\n \n- :rtype: :class:`gcloud.storage.client.Client`\n+ :rtype: :class:`google.cloud.storage.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n@@ -396,7 +397,8 @@ def _require_client(self, client):\n def reload(self, client=None):\n \"\"\"Reload the ACL data from Cloud Storage.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the ACL's parent.\n \"\"\"\n@@ -413,7 +415,7 @@ def reload(self, client=None):\n def _save(self, acl, predefined, client):\n \"\"\"Helper for :meth:`save` and :meth:`save_predefined`.\n \n- :type acl: :class:`gcloud.storage.acl.ACL`, or a compatible list.\n+ :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.\n :param acl: The ACL object to save. If left blank, this will save\n current entries.\n \n@@ -422,7 +424,8 @@ def _save(self, acl, predefined, client):\n of the keys in :attr:`PREDEFINED_JSON_ACLS`\n If passed, `acl` must be None.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the ACL's parent.\n \"\"\"\n@@ -446,11 +449,12 @@ def _save(self, acl, predefined, client):\n def save(self, acl=None, client=None):\n \"\"\"Save this ACL for the current bucket.\n \n- :type acl: :class:`gcloud.storage.acl.ACL`, or a compatible list.\n+ :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.\n :param acl: The ACL object to save. If left blank, this will save\n current entries.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the ACL's parent.\n \"\"\"\n@@ -473,7 +477,8 @@ def save_predefined(self, predefined, client=None):\n aliased to the corresponding JSON name).\n If passed, `acl` must be None.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the ACL's parent.\n \"\"\"\n@@ -492,7 +497,8 @@ def clear(self, client=None):\n have access to a bucket that you created even after you clear\n ACL rules with this method.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the ACL's parent.\n \"\"\"\n@@ -502,7 +508,7 @@ def clear(self, client=None):\n class BucketACL(ACL):\n \"\"\"An ACL specifically for a bucket.\n \n- :type bucket: :class:`gcloud.storage.bucket.Bucket`\n+ :type bucket: :class:`google.cloud.storage.bucket.Bucket`\n :param bucket: The bucket to which this ACL relates.\n \"\"\"\n \n@@ -536,7 +542,7 @@ class DefaultObjectACL(BucketACL):\n class ObjectACL(ACL):\n \"\"\"An ACL specifically for a Cloud Storage object / blob.\n \n- :type blob: :class:`gcloud.storage.blob.Blob`\n+ :type blob: :class:`google.cloud.storage.blob.Blob`\n :param blob: The blob that this ACL corresponds to.\n \"\"\"\n \ndiff --git a/gcloud/storage/batch.py b/google/cloud/storage/batch.py\nsimilarity index 98%\nrename from gcloud/storage/batch.py\nrename to google/cloud/storage/batch.py\n--- a/gcloud/storage/batch.py\n+++ b/google/cloud/storage/batch.py\n@@ -26,8 +26,8 @@\n import httplib2\n import six\n \n-from gcloud.exceptions import make_exception\n-from gcloud.storage.connection import Connection\n+from google.cloud.exceptions import make_exception\n+from google.cloud.storage.connection import Connection\n \n \n class MIMEApplicationHTTP(MIMEApplication):\n@@ -126,7 +126,7 @@ def __setitem__(self, key, value):\n class Batch(Connection):\n \"\"\"Proxy an underlying connection, batching up change operations.\n \n- :type client: :class:`gcloud.storage.client.Client`\n+ :type client: :class:`google.cloud.storage.client.Client`\n :param client: The client to use for making connections.\n \"\"\"\n _MAX_BATCH_SIZE = 1000\ndiff --git a/gcloud/storage/blob.py b/google/cloud/storage/blob.py\nsimilarity index 92%\nrename from gcloud/storage/blob.py\nrename to google/cloud/storage/blob.py\n--- a/gcloud/storage/blob.py\n+++ b/google/cloud/storage/blob.py\n@@ -28,20 +28,20 @@\n import six\n from six.moves.urllib.parse import quote\n \n-from gcloud._helpers import _rfc3339_to_datetime\n-from gcloud._helpers import _to_bytes\n-from gcloud._helpers import _bytes_to_unicode\n-from gcloud.credentials import generate_signed_url\n-from gcloud.exceptions import NotFound\n-from gcloud.exceptions import make_exception\n-from gcloud.storage._helpers import _PropertyMixin\n-from gcloud.storage._helpers import _scalar_property\n-from gcloud.storage.acl import ObjectACL\n-from gcloud.streaming.http_wrapper import Request\n-from gcloud.streaming.http_wrapper import make_api_request\n-from gcloud.streaming.transfer import Download\n-from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n-from gcloud.streaming.transfer import Upload\n+from google.cloud._helpers import _rfc3339_to_datetime\n+from google.cloud._helpers import _to_bytes\n+from google.cloud._helpers import _bytes_to_unicode\n+from google.cloud.credentials import generate_signed_url\n+from google.cloud.exceptions import NotFound\n+from google.cloud.exceptions import make_exception\n+from google.cloud.storage._helpers import _PropertyMixin\n+from google.cloud.storage._helpers import _scalar_property\n+from google.cloud.storage.acl import ObjectACL\n+from google.cloud.streaming.http_wrapper import Request\n+from google.cloud.streaming.http_wrapper import make_api_request\n+from google.cloud.streaming.transfer import Download\n+from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n+from google.cloud.streaming.transfer import Upload\n \n \n _API_ACCESS_ENDPOINT = 'https://storage.googleapis.com'\n@@ -54,7 +54,7 @@ class Blob(_PropertyMixin):\n :param name: The name of the blob. This corresponds to the\n unique path of the object in the bucket.\n \n- :type bucket: :class:`gcloud.storage.bucket.Bucket`\n+ :type bucket: :class:`google.cloud.storage.bucket.Bucket`\n :param bucket: The bucket to which this blob belongs.\n \n :type chunk_size: integer\n@@ -170,7 +170,7 @@ def generate_signed_url(self, expiration, method='GET',\n service account from a JSON file rather than a GCE service account.\n \n .. _Issue 922: https://github.com/GoogleCloudPlatform/\\\n- gcloud-python/issues/922\n+ google-cloud-python/issues/922\n \n If you have a blob that you want to allow access to for a set\n amount of time, you can use this method to generate a URL that\n@@ -207,7 +207,8 @@ def generate_signed_url(self, expiration, method='GET',\n for the signed URL. Used to over-ride the content\n type of the underlying blob/object.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: (Optional) The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n@@ -242,7 +243,8 @@ def generate_signed_url(self, expiration, method='GET',\n def exists(self, client=None):\n \"\"\"Determines whether or not this blob exists.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n@@ -269,15 +271,16 @@ def exists(self, client=None):\n def delete(self, client=None):\n \"\"\"Deletes a blob from Cloud Storage.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n :rtype: :class:`Blob`\n :returns: The blob that was just deleted.\n- :raises: :class:`gcloud.exceptions.NotFound`\n+ :raises: :class:`google.cloud.exceptions.NotFound`\n (propagated from\n- :meth:`gcloud.storage.bucket.Bucket.delete_blob`).\n+ :meth:`google.cloud.storage.bucket.Bucket.delete_blob`).\n \"\"\"\n return self.bucket.delete_blob(self.name, client=client)\n \n@@ -292,8 +295,8 @@ def download_to_file(self, file_obj, encryption_key=None, client=None):\n Downloading a file that has been encrypted with a `customer-supplied`_\n encryption key::\n \n- >>> from gcloud import storage\n- >>> from gcloud.storage import Blob\n+ >>> from google.cloud import storage\n+ >>> from google.cloud.storage import Blob\n \n >>> client = storage.Client(project='my-project')\n >>> bucket = client.get_bucket('my-bucket')\n@@ -316,11 +319,12 @@ def download_to_file(self, file_obj, encryption_key=None, client=None):\n :param encryption_key: Optional 32 byte encryption key for\n customer-supplied encryption.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n- :raises: :class:`gcloud.exceptions.NotFound`\n+ :raises: :class:`google.cloud.exceptions.NotFound`\n \"\"\"\n client = self._require_client(client)\n if self.media_link is None: # not yet loaded\n@@ -358,11 +362,12 @@ def download_to_filename(self, filename, encryption_key=None, client=None):\n :param encryption_key: Optional 32 byte encryption key for\n customer-supplied encryption.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n- :raises: :class:`gcloud.exceptions.NotFound`\n+ :raises: :class:`google.cloud.exceptions.NotFound`\n \"\"\"\n with open(filename, 'wb') as file_obj:\n self.download_to_file(file_obj, encryption_key=encryption_key,\n@@ -378,13 +383,14 @@ def download_as_string(self, encryption_key=None, client=None):\n :param encryption_key: Optional 32 byte encryption key for\n customer-supplied encryption.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n :rtype: bytes\n :returns: The data stored in this blob.\n- :raises: :class:`gcloud.exceptions.NotFound`\n+ :raises: :class:`google.cloud.exceptions.NotFound`\n \"\"\"\n string_buffer = BytesIO()\n self.download_to_file(string_buffer, encryption_key=encryption_key,\n@@ -425,8 +431,8 @@ def upload_from_file(self, file_obj, rewind=False, size=None,\n \n Uploading a file with a `customer-supplied`_ encryption key::\n \n- >>> from gcloud import storage\n- >>> from gcloud.storage import Blob\n+ >>> from google.cloud import storage\n+ >>> from google.cloud.storage import Blob\n \n >>> client = storage.Client(project='my-project')\n >>> bucket = client.get_bucket('my-bucket')\n@@ -465,13 +471,14 @@ def upload_from_file(self, file_obj, rewind=False, size=None,\n :type num_retries: integer\n :param num_retries: Number of upload retries. Defaults to 6.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \n :raises: :class:`ValueError` if size is not passed in and can not be\n- determined; :class:`gcloud.exceptions.GCloudError` if the\n- upload response returns an error status.\n+ determined; :class:`google.cloud.exceptions.GoogleCloudError`\n+ if the upload response returns an error status.\n \"\"\"\n client = self._require_client(client)\n # Use the private ``_connection`` rather than the public\n@@ -584,7 +591,8 @@ def upload_from_filename(self, filename, content_type=None,\n :param encryption_key: Optional 32 byte encryption key for\n customer-supplied encryption.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \"\"\"\n@@ -623,7 +631,8 @@ def upload_from_string(self, data, content_type='text/plain',\n :param encryption_key: Optional 32 byte encryption key for\n customer-supplied encryption.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \"\"\"\n@@ -638,7 +647,8 @@ def upload_from_string(self, data, content_type='text/plain',\n def make_public(self, client=None):\n \"\"\"Make this blob public giving all users read access.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bucket.\n \"\"\"\ndiff --git a/gcloud/storage/bucket.py b/google/cloud/storage/bucket.py\nsimilarity index 90%\nrename from gcloud/storage/bucket.py\nrename to google/cloud/storage/bucket.py\n--- a/gcloud/storage/bucket.py\n+++ b/google/cloud/storage/bucket.py\n@@ -12,35 +12,35 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud storage buckets.\"\"\"\n+\"\"\"Create / interact with Google Cloud Storage buckets.\"\"\"\n \n import copy\n \n import six\n \n-from gcloud._helpers import _rfc3339_to_datetime\n-from gcloud.exceptions import NotFound\n-from gcloud.iterator import Iterator\n-from gcloud.storage._helpers import _PropertyMixin\n-from gcloud.storage._helpers import _scalar_property\n-from gcloud.storage.acl import BucketACL\n-from gcloud.storage.acl import DefaultObjectACL\n-from gcloud.storage.blob import Blob\n+from google.cloud._helpers import _rfc3339_to_datetime\n+from google.cloud.exceptions import NotFound\n+from google.cloud.iterator import Iterator\n+from google.cloud.storage._helpers import _PropertyMixin\n+from google.cloud.storage._helpers import _scalar_property\n+from google.cloud.storage.acl import BucketACL\n+from google.cloud.storage.acl import DefaultObjectACL\n+from google.cloud.storage.blob import Blob\n \n \n class _BlobIterator(Iterator):\n \"\"\"An iterator listing blobs in a bucket\n \n You shouldn't have to use this directly, but instead should use the\n- :class:`gcloud.storage.blob.Bucket.list_blobs` method.\n+ :class:`google.cloud.storage.blob.Bucket.list_blobs` method.\n \n- :type bucket: :class:`gcloud.storage.bucket.Bucket`\n+ :type bucket: :class:`google.cloud.storage.bucket.Bucket`\n :param bucket: The bucket from which to list blobs.\n \n :type extra_params: dict or None\n :param extra_params: Extra query string parameters for the API call.\n \n- :type client: :class:`gcloud.storage.client.Client`\n+ :type client: :class:`google.cloud.storage.client.Client`\n :param client: Optional. The client to use for making connections.\n Defaults to the bucket's client.\n \"\"\"\n@@ -72,7 +72,7 @@ def get_items_from_response(self, response):\n class Bucket(_PropertyMixin):\n \"\"\"A class representing a Bucket on Cloud Storage.\n \n- :type client: :class:`gcloud.storage.client.Client`\n+ :type client: :class:`google.cloud.storage.client.Client`\n :param client: A client which holds credentials and project configuration\n for the bucket (which requires a project).\n \n@@ -118,7 +118,7 @@ def blob(self, blob_name, chunk_size=None):\n (1 MB). This must be a multiple of 256 KB per the\n API specification.\n \n- :rtype: :class:`gcloud.storage.blob.Blob`\n+ :rtype: :class:`google.cloud.storage.blob.Blob`\n :returns: The blob object created.\n \"\"\"\n return Blob(name=blob_name, bucket=self, chunk_size=chunk_size)\n@@ -126,7 +126,8 @@ def blob(self, blob_name, chunk_size=None):\n def exists(self, client=None):\n \"\"\"Determines whether or not this bucket exists.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n@@ -154,11 +155,12 @@ def create(self, client=None):\n \"\"\"Creates current bucket.\n \n If the bucket already exists, will raise\n- :class:`gcloud.exceptions.Conflict`.\n+ :class:`google.cloud.exceptions.Conflict`.\n \n This implements \"storage.buckets.insert\".\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \"\"\"\n@@ -207,7 +209,7 @@ def get_blob(self, blob_name, client=None):\n \n This will return None if the blob doesn't exist::\n \n- >>> from gcloud import storage\n+ >>> from google.cloud import storage\n >>> client = storage.Client()\n >>> bucket = client.get_bucket('my-bucket')\n >>> print bucket.get_blob('/path/to/blob.txt')\n@@ -218,11 +220,12 @@ def get_blob(self, blob_name, client=None):\n :type blob_name: string\n :param blob_name: The name of the blob to retrieve.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n- :rtype: :class:`gcloud.storage.blob.Blob` or None\n+ :rtype: :class:`google.cloud.storage.blob.Blob` or None\n :returns: The blob object if it exists, otherwise None.\n \"\"\"\n client = self._require_client(client)\n@@ -273,7 +276,8 @@ def list_blobs(self, max_results=None, page_token=None, prefix=None,\n and the language of each blob returned:\n 'items/contentLanguage,nextPageToken'\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n@@ -304,7 +308,9 @@ def list_blobs(self, max_results=None, page_token=None, prefix=None,\n # Page token must be handled specially since the base `Iterator`\n # class has it as a reserved property.\n if page_token is not None:\n+ # pylint: disable=attribute-defined-outside-init\n result.next_page_token = page_token\n+ # pylint: enable=attribute-defined-outside-init\n return result\n \n def delete(self, force=False, client=None):\n@@ -315,8 +321,9 @@ def delete(self, force=False, client=None):\n objects / blobs in the bucket (i.e. try to empty the bucket).\n \n If the bucket doesn't exist, this will raise\n- :class:`gcloud.exceptions.NotFound`. If the bucket is not empty\n- (and ``force=False``), will raise :class:`gcloud.exceptions.Conflict`.\n+ :class:`google.cloud.exceptions.NotFound`. If the bucket is not empty\n+ (and ``force=False``), will raise\n+ :class:`google.cloud.exceptions.Conflict`.\n \n If ``force=True`` and the bucket contains more than 256 objects / blobs\n this will cowardly refuse to delete the objects (or the bucket). This\n@@ -326,7 +333,8 @@ def delete(self, force=False, client=None):\n :type force: boolean\n :param force: If True, empties the bucket's objects then deletes it.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n@@ -361,12 +369,12 @@ def delete_blob(self, blob_name, client=None):\n \"\"\"Deletes a blob from the current bucket.\n \n If the blob isn't found (backend 404), raises a\n- :class:`gcloud.exceptions.NotFound`.\n+ :class:`google.cloud.exceptions.NotFound`.\n \n For example::\n \n- >>> from gcloud.exceptions import NotFound\n- >>> from gcloud import storage\n+ >>> from google.cloud.exceptions import NotFound\n+ >>> from google.cloud import storage\n >>> client = storage.Client()\n >>> bucket = client.get_bucket('my-bucket')\n >>> print bucket.list_blobs()\n@@ -380,11 +388,12 @@ def delete_blob(self, blob_name, client=None):\n :type blob_name: string\n :param blob_name: A blob name to delete.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n- :raises: :class:`gcloud.exceptions.NotFound` (to suppress\n+ :raises: :class:`google.cloud.exceptions.NotFound` (to suppress\n the exception, call ``delete_blobs``, passing a no-op\n ``on_error`` callback, e.g.::\n \n@@ -403,19 +412,20 @@ def delete_blobs(self, blobs, on_error=None, client=None):\n \n Uses :func:`Bucket.delete_blob` to delete each individual blob.\n \n- :type blobs: list of string or :class:`gcloud.storage.blob.Blob`\n+ :type blobs: list of string or :class:`google.cloud.storage.blob.Blob`\n :param blobs: A list of blob names or Blob objects to delete.\n \n :type on_error: a callable taking (blob)\n :param on_error: If not ``None``, called once for each blob raising\n- :class:`gcloud.exceptions.NotFound`;\n+ :class:`google.cloud.exceptions.NotFound`;\n otherwise, the exception is propagated.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n- :raises: :class:`gcloud.exceptions.NotFound` (if\n+ :raises: :class:`google.cloud.exceptions.NotFound` (if\n `on_error` is not passed).\n \"\"\"\n for blob in blobs:\n@@ -434,21 +444,22 @@ def copy_blob(self, blob, destination_bucket, new_name=None,\n client=None):\n \"\"\"Copy the given blob to the given bucket, optionally with a new name.\n \n- :type blob: :class:`gcloud.storage.blob.Blob`\n+ :type blob: :class:`google.cloud.storage.blob.Blob`\n :param blob: The blob to be copied.\n \n- :type destination_bucket: :class:`gcloud.storage.bucket.Bucket`\n+ :type destination_bucket: :class:`google.cloud.storage.bucket.Bucket`\n :param destination_bucket: The bucket into which the blob should be\n copied.\n \n :type new_name: string\n :param new_name: (optional) the new name for the copied file.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n- :rtype: :class:`gcloud.storage.blob.Blob`\n+ :rtype: :class:`google.cloud.storage.blob.Blob`\n :returns: The new Blob.\n \"\"\"\n client = self._require_client(client)\n@@ -473,13 +484,14 @@ def rename_blob(self, blob, new_name, client=None):\n old blob. This means that with very large objects renaming\n could be a very (temporarily) costly or a very slow operation.\n \n- :type blob: :class:`gcloud.storage.blob.Blob`\n+ :type blob: :class:`google.cloud.storage.blob.Blob`\n :param blob: The blob to be renamed.\n \n :type new_name: string\n :param new_name: The new name for this blob.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \n@@ -735,7 +747,7 @@ def configure_website(self, main_page_suffix=None, not_found_page=None):\n If you want this bucket to host a website, just provide the name\n of an index page and a page to use when a blob isn't found::\n \n- >>> from gcloud import storage\n+ >>> from google.cloud import storage\n >>> client = storage.Client()\n >>> bucket = client.get_bucket(bucket_name)\n >>> bucket.configure_website('index.html', '404.html')\n@@ -785,7 +797,8 @@ def make_public(self, recursive=False, future=False, client=None):\n :param future: If True, this will make all objects created in the\n future public as well.\n \n- :type client: :class:`gcloud.storage.client.Client` or ``NoneType``\n+ :type client: :class:`~google.cloud.storage.client.Client` or\n+ ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the current bucket.\n \"\"\"\ndiff --git a/gcloud/storage/client.py b/google/cloud/storage/client.py\nsimilarity index 86%\nrename from gcloud/storage/client.py\nrename to google/cloud/storage/client.py\n--- a/gcloud/storage/client.py\n+++ b/google/cloud/storage/client.py\n@@ -15,13 +15,13 @@\n \"\"\"Client for interacting with the Google Cloud Storage API.\"\"\"\n \n \n-from gcloud._helpers import _LocalStack\n-from gcloud.client import JSONClient\n-from gcloud.exceptions import NotFound\n-from gcloud.iterator import Iterator\n-from gcloud.storage.batch import Batch\n-from gcloud.storage.bucket import Bucket\n-from gcloud.storage.connection import Connection\n+from google.cloud._helpers import _LocalStack\n+from google.cloud.client import JSONClient\n+from google.cloud.exceptions import NotFound\n+from google.cloud.iterator import Iterator\n+from google.cloud.storage.batch import Batch\n+from google.cloud.storage.bucket import Bucket\n+from google.cloud.storage.connection import Connection\n \n \n class Client(JSONClient):\n@@ -57,7 +57,7 @@ def __init__(self, project=None, credentials=None, http=None):\n def connection(self):\n \"\"\"Get connection or batch on the client.\n \n- :rtype: :class:`gcloud.storage.connection.Connection`\n+ :rtype: :class:`google.cloud.storage.connection.Connection`\n :returns: The connection set on the client, or the batch\n if one is set.\n \"\"\"\n@@ -74,7 +74,7 @@ def connection(self, value):\n self.connection = connection\n Will raise if the connection is set more than once.\n \n- :type value: :class:`gcloud.storage.connection.Connection`\n+ :type value: :class:`google.cloud.storage.connection.Connection`\n :param value: The connection set on the client.\n \n :raises: :class:`ValueError` if connection has already been set.\n@@ -88,7 +88,7 @@ def _push_batch(self, batch):\n \n \"Protected\", intended for use by batch context mgrs.\n \n- :type batch: :class:`gcloud.storage.batch.Batch`\n+ :type batch: :class:`google.cloud.storage.batch.Batch`\n :param batch: newly-active batch\n \"\"\"\n self._batch_stack.push(batch)\n@@ -99,7 +99,7 @@ def _pop_batch(self):\n \"Protected\", intended for use by batch context mgrs.\n \n :raises: IndexError if the stack is empty.\n- :rtype: :class:`gcloud.storage.batch.Batch`\n+ :rtype: :class:`google.cloud.storage.batch.Batch`\n :returns: the top-most batch/transaction, after removing it.\n \"\"\"\n return self._batch_stack.pop()\n@@ -108,7 +108,7 @@ def _pop_batch(self):\n def current_batch(self):\n \"\"\"Currently-active batch.\n \n- :rtype: :class:`gcloud.storage.batch.Batch` or ``NoneType`` (if\n+ :rtype: :class:`google.cloud.storage.batch.Batch` or ``NoneType`` (if\n no batch is active).\n :returns: The batch at the top of the batch stack.\n \"\"\"\n@@ -124,7 +124,7 @@ def bucket(self, bucket_name):\n :type bucket_name: string\n :param bucket_name: The name of the bucket to be instantiated.\n \n- :rtype: :class:`gcloud.storage.bucket.Bucket`\n+ :rtype: :class:`google.cloud.storage.bucket.Bucket`\n :returns: The bucket object created.\n \"\"\"\n return Bucket(client=self, name=bucket_name)\n@@ -136,7 +136,7 @@ def batch(self):\n This will not make an HTTP request; it simply instantiates\n a batch object owned by this client.\n \n- :rtype: :class:`gcloud.storage.batch.Batch`\n+ :rtype: :class:`google.cloud.storage.batch.Batch`\n :returns: The batch object created.\n \"\"\"\n return Batch(client=self)\n@@ -145,13 +145,13 @@ def get_bucket(self, bucket_name):\n \"\"\"Get a bucket by name.\n \n If the bucket isn't found, this will raise a\n- :class:`gcloud.storage.exceptions.NotFound`.\n+ :class:`google.cloud.storage.exceptions.NotFound`.\n \n For example::\n \n >>> try:\n >>> bucket = client.get_bucket('my-bucket')\n- >>> except gcloud.exceptions.NotFound:\n+ >>> except google.cloud.exceptions.NotFound:\n >>> print 'Sorry, that bucket does not exist!'\n \n This implements \"storage.buckets.get\".\n@@ -159,9 +159,9 @@ def get_bucket(self, bucket_name):\n :type bucket_name: string\n :param bucket_name: The name of the bucket to get.\n \n- :rtype: :class:`gcloud.storage.bucket.Bucket`\n+ :rtype: :class:`google.cloud.storage.bucket.Bucket`\n :returns: The bucket matching the name provided.\n- :raises: :class:`gcloud.exceptions.NotFound`\n+ :raises: :class:`google.cloud.exceptions.NotFound`\n \"\"\"\n bucket = Bucket(self, name=bucket_name)\n bucket.reload(client=self)\n@@ -183,7 +183,7 @@ def lookup_bucket(self, bucket_name):\n :type bucket_name: string\n :param bucket_name: The name of the bucket to get.\n \n- :rtype: :class:`gcloud.storage.bucket.Bucket`\n+ :rtype: :class:`google.cloud.storage.bucket.Bucket`\n :returns: The bucket matching the name provided or None if not found.\n \"\"\"\n try:\n@@ -203,12 +203,12 @@ def create_bucket(self, bucket_name):\n This implements \"storage.buckets.insert\".\n \n If the bucket already exists, will raise\n- :class:`gcloud.exceptions.Conflict`.\n+ :class:`google.cloud.exceptions.Conflict`.\n \n :type bucket_name: string\n :param bucket_name: The bucket name to create.\n \n- :rtype: :class:`gcloud.storage.bucket.Bucket`\n+ :rtype: :class:`google.cloud.storage.bucket.Bucket`\n :returns: The newly created bucket.\n \"\"\"\n bucket = Bucket(self, name=bucket_name)\n@@ -250,7 +250,8 @@ def list_buckets(self, max_results=None, page_token=None, prefix=None,\n and the language of each bucket returned:\n 'items/id,nextPageToken'\n \n- :rtype: iterable of :class:`gcloud.storage.bucket.Bucket` objects.\n+ :rtype: iterable of :class:`google.cloud.storage.bucket.Bucket`\n+ objects.\n :returns: All buckets belonging to this project.\n \"\"\"\n extra_params = {'project': self.project}\n@@ -271,7 +272,9 @@ def list_buckets(self, max_results=None, page_token=None, prefix=None,\n # Page token must be handled specially since the base `Iterator`\n # class has it as a reserved property.\n if page_token is not None:\n+ # pylint: disable=attribute-defined-outside-init\n result.next_page_token = page_token\n+ # pylint: enable=attribute-defined-outside-init\n return result\n \n \n@@ -279,10 +282,10 @@ class _BucketIterator(Iterator):\n \"\"\"An iterator listing all buckets.\n \n You shouldn't have to use this directly, but instead should use the\n- helper methods on :class:`gcloud.storage.connection.Connection`\n+ helper methods on :class:`google.cloud.storage.connection.Connection`\n objects.\n \n- :type client: :class:`gcloud.storage.client.Client`\n+ :type client: :class:`google.cloud.storage.client.Client`\n :param client: The client to use for making connections.\n \n :type extra_params: dict or ``NoneType``\ndiff --git a/gcloud/storage/connection.py b/google/cloud/storage/connection.py\nsimilarity index 93%\nrename from gcloud/storage/connection.py\nrename to google/cloud/storage/connection.py\n--- a/gcloud/storage/connection.py\n+++ b/google/cloud/storage/connection.py\n@@ -12,9 +12,9 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Create / interact with gcloud storage connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud Storage connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/streaming/__init__.py b/google/cloud/streaming/__init__.py\nsimilarity index 93%\nrename from gcloud/streaming/__init__.py\nrename to google/cloud/streaming/__init__.py\n--- a/gcloud/streaming/__init__.py\n+++ b/google/cloud/streaming/__init__.py\n@@ -13,3 +13,5 @@\n # limitations under the License.\n \n # Vendored-in from google-apitools 0.4.11\n+\n+\"\"\"Base ``google.cloud.streaming`` package.\"\"\"\ndiff --git a/gcloud/streaming/buffered_stream.py b/google/cloud/streaming/buffered_stream.py\nsimilarity index 100%\nrename from gcloud/streaming/buffered_stream.py\nrename to google/cloud/streaming/buffered_stream.py\ndiff --git a/gcloud/streaming/exceptions.py b/google/cloud/streaming/exceptions.py\nsimilarity index 95%\nrename from gcloud/streaming/exceptions.py\nrename to google/cloud/streaming/exceptions.py\n--- a/gcloud/streaming/exceptions.py\n+++ b/google/cloud/streaming/exceptions.py\n@@ -59,7 +59,7 @@ def status_code(self):\n def from_response(cls, http_response):\n \"\"\"Factory: construct an exception from a response.\n \n- :type http_response: :class:`gcloud.streaming.http_wrapper.Response`\n+ :type http_response: :class:`~.streaming.http_wrapper.Response`\n :param http_response: the response which returned the error\n \n :rtype: :class:`HttpError`\n@@ -108,7 +108,7 @@ def __init__(self, response, content, url, retry_after):\n def from_response(cls, http_response):\n \"\"\"Factory: construct an exception from a response.\n \n- :type http_response: :class:`gcloud.streaming.http_wrapper.Response`\n+ :type http_response: :class:`~.streaming.http_wrapper.Response`\n :param http_response: the response which returned the error.\n \n :rtype: :class:`RetryAfterError`\ndiff --git a/gcloud/streaming/http_wrapper.py b/google/cloud/streaming/http_wrapper.py\nsimilarity index 94%\nrename from gcloud/streaming/http_wrapper.py\nrename to google/cloud/streaming/http_wrapper.py\n--- a/gcloud/streaming/http_wrapper.py\n+++ b/google/cloud/streaming/http_wrapper.py\n@@ -29,10 +29,10 @@\n from six.moves import http_client\n from six.moves.urllib import parse\n \n-from gcloud.streaming.exceptions import BadStatusCodeError\n-from gcloud.streaming.exceptions import RequestError\n-from gcloud.streaming.exceptions import RetryAfterError\n-from gcloud.streaming.util import calculate_wait_for_retry\n+from google.cloud.streaming.exceptions import BadStatusCodeError\n+from google.cloud.streaming.exceptions import RequestError\n+from google.cloud.streaming.exceptions import RetryAfterError\n+from google.cloud.streaming.util import calculate_wait_for_retry\n \n \n _REDIRECTIONS = 5\n@@ -272,10 +272,10 @@ def _check_response(response):\n :type response: :class:`Response`\n :param response: the response to validate\n \n- :raises: :exc:`gcloud.streaming.exceptions.RequestError` if response is\n- None, :exc:`gcloud.streaming.exceptions.BadStatusCodeError` if\n+ :raises: :exc:`google.cloud.streaming.exceptions.RequestError` if response\n+ is None, :exc:`~.streaming.exceptions.BadStatusCodeError` if\n response status code indicates an error, or\n- :exc:`gcloud.streaming.exceptions.RetryAfterError` if response\n+ :exc:`~.streaming.exceptions.RetryAfterError` if response\n indicates a retry interval.\n \"\"\"\n if response is None:\n@@ -326,8 +326,8 @@ def _make_api_request_no_retry(http, http_request, redirections=_REDIRECTIONS):\n :rtype: :class:`Response`\n :returns: an object representing the server's response\n \n- :raises: :exc:`gcloud.streaming.exceptions.RequestError` if no response\n- could be parsed.\n+ :raises: :exc:`google.cloud.streaming.exceptions.RequestError` if no\n+ response could be parsed.\n \"\"\"\n connection_type = None\n # Handle overrides for connection types. This is used if the caller\n@@ -374,8 +374,8 @@ def make_api_request(http, http_request, retries=7,\n :rtype: :class:`Response`\n :returns: an object representing the server's response.\n \n- :raises: :exc:`gcloud.streaming.exceptions.RequestError` if no response\n- could be parsed.\n+ :raises: :exc:`google.cloud.streaming.exceptions.RequestError` if no\n+ response could be parsed.\n \"\"\"\n retry = 0\n while True:\ndiff --git a/gcloud/streaming/stream_slice.py b/google/cloud/streaming/stream_slice.py\nsimilarity index 100%\nrename from gcloud/streaming/stream_slice.py\nrename to google/cloud/streaming/stream_slice.py\ndiff --git a/gcloud/streaming/transfer.py b/google/cloud/streaming/transfer.py\nsimilarity index 94%\nrename from gcloud/streaming/transfer.py\nrename to google/cloud/streaming/transfer.py\n--- a/gcloud/streaming/transfer.py\n+++ b/google/cloud/streaming/transfer.py\n@@ -26,17 +26,17 @@\n import six\n from six.moves import http_client\n \n-from gcloud._helpers import _to_bytes\n-from gcloud.streaming.buffered_stream import BufferedStream\n-from gcloud.streaming.exceptions import CommunicationError\n-from gcloud.streaming.exceptions import HttpError\n-from gcloud.streaming.exceptions import TransferInvalidError\n-from gcloud.streaming.exceptions import TransferRetryError\n-from gcloud.streaming.http_wrapper import make_api_request\n-from gcloud.streaming.http_wrapper import Request\n-from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n-from gcloud.streaming.stream_slice import StreamSlice\n-from gcloud.streaming.util import acceptable_mime_type\n+from google.cloud._helpers import _to_bytes\n+from google.cloud.streaming.buffered_stream import BufferedStream\n+from google.cloud.streaming.exceptions import CommunicationError\n+from google.cloud.streaming.exceptions import HttpError\n+from google.cloud.streaming.exceptions import TransferInvalidError\n+from google.cloud.streaming.exceptions import TransferRetryError\n+from google.cloud.streaming.http_wrapper import make_api_request\n+from google.cloud.streaming.http_wrapper import Request\n+from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+from google.cloud.streaming.stream_slice import StreamSlice\n+from google.cloud.streaming.util import acceptable_mime_type\n \n \n RESUMABLE_UPLOAD_THRESHOLD = 5 << 20\n@@ -200,7 +200,7 @@ def initialized(self):\n def _ensure_initialized(self):\n \"\"\"Helper: assert that the instance is initialized.\n \n- :raises: :exc:`gcloud.streaming.exceptions.TransferInvalidError`\n+ :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n if the instance is not initialized.\n \"\"\"\n if not self.initialized:\n@@ -210,7 +210,7 @@ def _ensure_initialized(self):\n def _ensure_uninitialized(self):\n \"\"\"Helper: assert that the instance is not initialized.\n \n- :raises: :exc:`gcloud.streaming.exceptions.TransferInvalidError`\n+ :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n if the instance is already initialized.\n \"\"\"\n if self.initialized:\n@@ -334,7 +334,7 @@ def __repr__(self):\n def configure_request(self, http_request, url_builder):\n \"\"\"Update http_request/url_builder with download-appropriate values.\n \n- :type http_request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to be updated\n \n :type url_builder: instance with settable 'query_params' attribute.\n@@ -366,7 +366,7 @@ def initialize_download(self, http_request, http):\n If the instance has :attr:`auto_transfer` enabled, begins the\n download immediately.\n \n- :type http_request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to use to initialize this download.\n \n :type http: :class:`httplib2.Http` (or workalike)\n@@ -402,7 +402,7 @@ def _normalize_start_end(self, start, end=None):\n \n :rtype: tuple, (start, end)\n :returns: the normalized start, end pair.\n- :raises: :exc:`gcloud.streaming.exceptions.TransferInvalidError`\n+ :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n for invalid combinations of start, end.\n \"\"\"\n if end is not None:\n@@ -426,7 +426,7 @@ def _normalize_start_end(self, start, end=None):\n def _set_range_header(request, start, end=None):\n \"\"\"Update the 'Range' header in a request to match a byte range.\n \n- :type request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type request: :class:`google.cloud.streaming.http_wrapper.Request`\n :param request: the request to update\n \n :type start: integer\n@@ -497,7 +497,7 @@ def _get_chunk(self, start, end):\n :type end: integer or None\n :param end: end byte of the range.\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: response from the chunk request.\n \"\"\"\n self._ensure_initialized()\n@@ -509,14 +509,14 @@ def _get_chunk(self, start, end):\n def _process_response(self, response):\n \"\"\"Update attribtes and writing stream, based on response.\n \n- :type response: :class:`gcloud.streaming.http_wrapper.Response`\n+ :type response: :class:`google.cloud.streaming.http_wrapper.Response`\n :param response: response from a download request.\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: the response\n- :raises: :exc:`gcloud.streaming.exceptions.HttpError` for\n+ :raises: :exc:`google.cloud.streaming.exceptions.HttpError` for\n missing / unauthorized responses;\n- :exc:`gcloud.streaming.exceptions.TransferRetryError`\n+ :exc:`google.cloud.streaming.exceptions.TransferRetryError`\n for other error responses.\n \"\"\"\n if response.status_code not in self._ACCEPTABLE_STATUSES:\n@@ -564,7 +564,7 @@ def get_range(self, start, end=None, use_chunks=True):\n and fetch this range in a single request.\n If True, streams via chunks.\n \n- :raises: :exc:`gcloud.streaming.exceptions.TransferRetryError`\n+ :raises: :exc:`google.cloud.streaming.exceptions.TransferRetryError`\n if a request returns an empty response.\n \"\"\"\n self._ensure_initialized()\n@@ -810,7 +810,7 @@ def _set_default_strategy(self, upload_config, http_request):\n attributes\n :param upload_config: Configuration for the upload endpoint.\n \n- :type http_request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: The associated http request.\n \"\"\"\n if upload_config.resumable_path is None:\n@@ -834,7 +834,7 @@ def configure_request(self, upload_config, http_request, url_builder):\n attributes\n :param upload_config: transfer policy object to be queried\n \n- :type http_request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to be updated\n \n :type url_builder: instance with settable 'relative_path' and\n@@ -970,7 +970,7 @@ def refresh_upload_state(self):\n def _get_range_header(response):\n \"\"\"Return a 'Range' header from a response.\n \n- :type response: :class:`gcloud.streaming.http_wrapper.Response`\n+ :type response: :class:`google.cloud.streaming.http_wrapper.Response`\n :param response: response to be queried\n \n :rtype: string\n@@ -994,7 +994,7 @@ def _get_range_header(response):\n def initialize_upload(self, http_request, http):\n \"\"\"Initialize this upload from the given http_request.\n \n- :type http_request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to be used\n \n :type http: :class:`httplib2.Http` (or workalike)\n@@ -1002,7 +1002,7 @@ def initialize_upload(self, http_request, http):\n \n :raises: :exc:`ValueError` if the instance has not been configured\n with a strategy.\n- :rtype: :class:`~gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`~google.cloud.streaming.http_wrapper.Response`\n :returns: The response if the upload is resumable and auto transfer\n is not used.\n \"\"\"\n@@ -1070,7 +1070,7 @@ def stream_file(self, use_chunks=True):\n :param use_chunks: If False, send the stream in a single request.\n Otherwise, send it in chunks.\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: The response for the final request made.\n \"\"\"\n if self.strategy != RESUMABLE_UPLOAD:\n@@ -1110,15 +1110,15 @@ def _send_media_request(self, request, end):\n \n Helper for _send_media_body & _send_chunk:\n \n- :type request: :class:`gcloud.streaming.http_wrapper.Request`\n+ :type request: :class:`google.cloud.streaming.http_wrapper.Request`\n :param request: the request to upload\n \n :type end: integer\n :param end: end byte of the to be uploaded\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: the response\n- :raises: :exc:`gcloud.streaming.exceptions.HttpError` if the status\n+ :raises: :exc:`~.streaming.exceptions.HttpError` if the status\n code from the response indicates an error.\n \"\"\"\n response = make_api_request(\n@@ -1144,7 +1144,7 @@ def _send_media_body(self, start):\n :type start: integer\n :param start: start byte of the range.\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: The response from the media upload request.\n \"\"\"\n self._ensure_initialized()\n@@ -1174,7 +1174,7 @@ def _send_chunk(self, start):\n :type start: integer\n :param start: start byte of the range.\n \n- :rtype: :class:`gcloud.streaming.http_wrapper.Response`\n+ :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: The response from the chunked upload request.\n \"\"\"\n self._ensure_initialized()\ndiff --git a/gcloud/streaming/util.py b/google/cloud/streaming/util.py\nsimilarity index 100%\nrename from gcloud/streaming/util.py\nrename to google/cloud/streaming/util.py\ndiff --git a/gcloud/translate/__init__.py b/google/cloud/translate/__init__.py\nsimilarity index 85%\nrename from gcloud/translate/__init__.py\nrename to google/cloud/translate/__init__.py\n--- a/gcloud/translate/__init__.py\n+++ b/google/cloud/translate/__init__.py\n@@ -14,5 +14,5 @@\n \n \"\"\"Google Cloud Translate API wrapper.\"\"\"\n \n-from gcloud.translate.client import Client\n-from gcloud.translate.connection import Connection\n+from google.cloud.translate.client import Client\n+from google.cloud.translate.connection import Connection\ndiff --git a/gcloud/translate/client.py b/google/cloud/translate/client.py\nsimilarity index 98%\nrename from gcloud/translate/client.py\nrename to google/cloud/translate/client.py\n--- a/gcloud/translate/client.py\n+++ b/google/cloud/translate/client.py\n@@ -18,8 +18,8 @@\n import httplib2\n import six\n \n-from gcloud._helpers import _to_bytes\n-from gcloud.translate.connection import Connection\n+from google.cloud._helpers import _to_bytes\n+from google.cloud.translate.connection import Connection\n \n \n ENGLISH_ISO_639 = 'en'\ndiff --git a/gcloud/translate/connection.py b/google/cloud/translate/connection.py\nsimilarity index 95%\nrename from gcloud/translate/connection.py\nrename to google/cloud/translate/connection.py\n--- a/gcloud/translate/connection.py\n+++ b/google/cloud/translate/connection.py\n@@ -14,7 +14,7 @@\n \n \"\"\"Create / interact with Google Cloud Translate connections.\"\"\"\n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/vision/__init__.py b/google/cloud/vision/__init__.py\nsimilarity index 100%\nrename from gcloud/vision/__init__.py\nrename to google/cloud/vision/__init__.py\ndiff --git a/gcloud/vision/_fixtures.py b/google/cloud/vision/_fixtures.py\nsimilarity index 100%\nrename from gcloud/vision/_fixtures.py\nrename to google/cloud/vision/_fixtures.py\ndiff --git a/gcloud/vision/client.py b/google/cloud/vision/client.py\nsimilarity index 93%\nrename from gcloud/vision/client.py\nrename to google/cloud/vision/client.py\n--- a/gcloud/vision/client.py\n+++ b/google/cloud/vision/client.py\n@@ -15,10 +15,10 @@\n \"\"\"Client for interacting with the Google Cloud Vision API.\"\"\"\n \n \n-from gcloud.client import JSONClient\n-from gcloud.vision.connection import Connection\n-from gcloud.vision.feature import Feature\n-from gcloud.vision.image import Image\n+from google.cloud.client import JSONClient\n+from google.cloud.vision.connection import Connection\n+from google.cloud.vision.feature import Feature\n+from google.cloud.vision.image import Image\n \n \n class VisionRequest(object):\n@@ -89,7 +89,7 @@ def annotate(self, image, features):\n :param image: A string which can be a URL, a Google Cloud Storage path,\n or a byte stream of the image.\n \n- :type features: list of :class:`gcloud.vision.feature.Feature`\n+ :type features: list of :class:`google.cloud.vision.feature.Feature`\n :param features: The type of detection that the Vision API should\n use to determine image attributes. Pricing is\n based on the number of Feature Types.\ndiff --git a/gcloud/vision/connection.py b/google/cloud/vision/connection.py\nsimilarity index 93%\nrename from gcloud/vision/connection.py\nrename to google/cloud/vision/connection.py\n--- a/gcloud/vision/connection.py\n+++ b/google/cloud/vision/connection.py\n@@ -13,10 +13,10 @@\n # limitations under the License.\n \n \n-\"\"\"Create / interact with gcloud Vision connections.\"\"\"\n+\"\"\"Create / interact with Google Cloud Vision connections.\"\"\"\n \n \n-from gcloud import connection as base_connection\n+from google.cloud import connection as base_connection\n \n \n class Connection(base_connection.JSONConnection):\ndiff --git a/gcloud/vision/feature.py b/google/cloud/vision/feature.py\nsimilarity index 96%\nrename from gcloud/vision/feature.py\nrename to google/cloud/vision/feature.py\n--- a/gcloud/vision/feature.py\n+++ b/google/cloud/vision/feature.py\n@@ -34,7 +34,7 @@ class Feature(object):\n \n :type feature_type: str\n :param feature_type: String representation of\n- :class:`gcloud.vision.feature.FeatureType`.\n+ :class:`google.cloud.vision.feature.FeatureType`.\n \n :type max_results: int\n :param max_results: Number of results to return for the specified\ndiff --git a/gcloud/vision/image.py b/google/cloud/vision/image.py\nsimilarity index 95%\nrename from gcloud/vision/image.py\nrename to google/cloud/vision/image.py\n--- a/gcloud/vision/image.py\n+++ b/google/cloud/vision/image.py\n@@ -17,8 +17,8 @@\n \n from base64 import b64encode\n \n-from gcloud._helpers import _to_bytes\n-from gcloud._helpers import _bytes_to_unicode\n+from google.cloud._helpers import _to_bytes\n+from google.cloud._helpers import _bytes_to_unicode\n \n \n class Image(object):\ndiff --git a/scripts/generate_json_docs.py b/scripts/generate_json_docs.py\n--- a/scripts/generate_json_docs.py\n+++ b/scripts/generate_json_docs.py\n@@ -244,7 +244,7 @@ def build_link_from_list_of_types(type_names, object_type=None):\n def build_link_from_type(type_name, object_type=None):\n type_name = clean_type_name(type_name)\n \n- if not type_name.startswith('gcloud'):\n+ if not type_name.startswith('google.cloud'):\n return type_name\n doc_path = type_name\n \n@@ -425,13 +425,13 @@ def write_docs_file(path, contents):\n \n def generate_doc_types_json(modules, types_file_path):\n doc_types_list = [{\n- 'id': 'gcloud',\n+ 'id': 'google-cloud',\n 'contents': 'index.json',\n- 'title': 'gcloud'\n+ 'title': 'google-cloud'\n }]\n \n for module_name in modules:\n- if module_name == 'gcloud.__init__':\n+ if module_name == 'google.cloud.__init__':\n continue\n \n module_title = module_name.replace('.__init__', '').split('.')\n@@ -485,7 +485,7 @@ def generate_module_docs(modules, docs_path, real_base_path, toc):\n module_docs_path = os.path.join(docs_path, module_path) + '.json'\n \n if pdoc_module.functions():\n- toc_key = module_name.replace('gcloud.', '').split('.')[0]\n+ toc_key = module_name.replace('google.cloud.', '').split('.')[0]\n toc_entry = build_toc_entry(module.name, module_path)\n toc['services'][toc_key].append(toc_entry)\n \n@@ -501,7 +501,7 @@ def generate_class_docs(module, klass, base_path, toc):\n .replace('__init__', 'index'))\n module_docs_path = os.path.join(base_path, module_path,\n klass.name.lower()) + '.json'\n- toc_key = module.name.replace('gcloud.', '').split('.')[0]\n+ toc_key = module.name.replace('google.cloud.', '').split('.')[0]\n \n toc_entry = build_toc_entry(klass.name,\n os.path.join(module_path,\n@@ -590,8 +590,8 @@ def package_files(generated_json_dir, docs_build_dir, static_json_dir,\n shutil.rmtree(package_path, ignore_errors=True)\n \n shutil.copytree(static_json_dir, package_path)\n- shutil.copytree(os.path.join(generated_json_dir, 'gcloud'),\n- os.path.join(package_path, 'json', tag, 'gcloud'))\n+ shutil.copytree(os.path.join(generated_json_dir, 'google', 'cloud'),\n+ os.path.join(package_path, 'json', tag, 'google', 'cloud'))\n shutil.copyfile(os.path.join(generated_json_dir, 'types.json'),\n os.path.join(package_path, 'json', tag, 'types.json'))\n \n@@ -609,7 +609,8 @@ def main():\n toc = {\n 'services': {\n '__init__': [],\n- 'gcloud': [],\n+ 'google': [],\n+ 'cloud': [],\n 'bigquery': [],\n 'bigtable': [],\n 'client': [],\n@@ -641,8 +642,9 @@ def main():\n JSON_DOCS_DIR = os.path.join(DOCS_BUILD_DIR, 'json', args.tag)\n LIB_DIR = os.path.abspath(args.basepath)\n \n- library_dir = os.path.join(LIB_DIR, 'gcloud')\n- public_mods = get_public_modules(library_dir, base_package='gcloud')\n+ library_dir = os.path.join(LIB_DIR, 'google', 'cloud')\n+ public_mods = get_public_modules(library_dir,\n+ base_package='google.cloud')\n \n generate_module_docs(public_mods, JSON_DOCS_DIR, BASE_DIR, toc)\n generate_doc_types_json(public_mods,\ndiff --git a/scripts/make_datastore_grpc.py b/scripts/make_datastore_grpc.py\n--- a/scripts/make_datastore_grpc.py\n+++ b/scripts/make_datastore_grpc.py\n@@ -26,7 +26,7 @@\n PROTOS_DIR = os.path.join(ROOT_DIR, 'googleapis-pb')\n PROTO_PATH = os.path.join(PROTOS_DIR, 'google', 'datastore',\n 'v1', 'datastore.proto')\n-GRPC_ONLY_FILE = os.path.join(ROOT_DIR, 'gcloud', 'datastore',\n+GRPC_ONLY_FILE = os.path.join(ROOT_DIR, 'google', 'cloud', 'datastore',\n '_generated', 'datastore_grpc_pb2.py')\n GRPCIO_VIRTUALENV = os.getenv('GRPCIO_VIRTUALENV')\n if GRPCIO_VIRTUALENV is None:\n@@ -34,7 +34,8 @@\n else:\n PYTHON_EXECUTABLE = os.path.join(GRPCIO_VIRTUALENV, 'bin', 'python')\n MESSAGE_SNIPPET = ' = _reflection.GeneratedProtocolMessageType('\n-IMPORT_TEMPLATE = 'from gcloud.datastore._generated.datastore_pb2 import %s\\n'\n+IMPORT_TEMPLATE = (\n+ 'from google.cloud.datastore._generated.datastore_pb2 import %s\\n')\n \n \n def get_pb2_contents_with_grpc():\ndiff --git a/scripts/make_operations_grpc.py b/scripts/make_operations_grpc.py\n--- a/scripts/make_operations_grpc.py\n+++ b/scripts/make_operations_grpc.py\n@@ -27,7 +27,7 @@\n PROTO_PATH = os.path.join(PROTOS_DIR, 'google', 'longrunning',\n 'operations.proto')\n GENERATED_SUBDIR = os.getenv('GENERATED_SUBDIR', '_generated')\n-GRPC_ONLY_FILE = os.path.join(ROOT_DIR, 'gcloud', 'bigtable',\n+GRPC_ONLY_FILE = os.path.join(ROOT_DIR, 'google', 'cloud', 'bigtable',\n GENERATED_SUBDIR, 'operations_grpc_pb2.py')\n GRPCIO_VIRTUALENV = os.getenv('GRPCIO_VIRTUALENV')\n if GRPCIO_VIRTUALENV is None:\ndiff --git a/scripts/pycodestyle_on_repo.py b/scripts/pycodestyle_on_repo.py\n--- a/scripts/pycodestyle_on_repo.py\n+++ b/scripts/pycodestyle_on_repo.py\n@@ -12,7 +12,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Custom script to run pycodestyle on gcloud codebase.\n+\"\"\"Custom script to run pycodestyle on google-cloud codebase.\n \n This runs pycodestyle as a script via subprocess but only runs it on the\n .py files that are checked in to the repository.\ndiff --git a/scripts/rewrite_imports.py b/scripts/rewrite_imports.py\n--- a/scripts/rewrite_imports.py\n+++ b/scripts/rewrite_imports.py\n@@ -25,10 +25,10 @@\n IMPORT_FROM_TEMPLATE = 'from %s import '\n REPLACEMENTS = {\n # Bigtable v2\n- 'google.bigtable.v2': 'gcloud.bigtable._generated',\n- 'google.bigtable.admin.v2': 'gcloud.bigtable._generated',\n+ 'google.bigtable.v2': 'google.cloud.bigtable._generated',\n+ 'google.bigtable.admin.v2': 'google.cloud.bigtable._generated',\n # Datastore v1\n- 'google.datastore.v1': 'gcloud.datastore._generated',\n+ 'google.datastore.v1': 'google.cloud.datastore._generated',\n }\n \n \ndiff --git a/scripts/run_pylint.py b/scripts/run_pylint.py\n--- a/scripts/run_pylint.py\n+++ b/scripts/run_pylint.py\n@@ -12,7 +12,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\"\"\"Custom script to run PyLint on gcloud codebase.\n+\"\"\"Custom script to run PyLint on google-cloud codebase.\n \n This runs pylint as a script via subprocess in two different\n subprocesses. The first lints the production/library code\n@@ -31,14 +31,14 @@\n \n \n IGNORED_DIRECTORIES = [\n- os.path.join('gcloud', 'bigtable', '_generated'),\n- os.path.join('gcloud', 'datastore', '_generated'),\n+ os.path.join('google', 'cloud', 'bigtable', '_generated'),\n+ os.path.join('google', 'cloud', 'datastore', '_generated'),\n 'scripts/verify_included_modules.py',\n ]\n IGNORED_FILES = [\n os.path.join('docs', 'conf.py'),\n 'setup.py',\n- os.path.join('gcloud', 'vision', '_fixtures.py'),\n+ os.path.join('google', 'cloud', 'vision', '_fixtures.py'),\n ]\n SCRIPTS_DIR = os.path.abspath(os.path.dirname(__file__))\n PRODUCTION_RC = os.path.join(SCRIPTS_DIR, 'pylintrc_default')\n@@ -144,8 +144,8 @@ def get_files_for_linting(allow_limited=True):\n this value is not dependable.\n \n To allow faster local ``tox`` runs, the environment variables\n- ``GCLOUD_REMOTE_FOR_LINT`` and ``GCLOUD_BRANCH_FOR_LINT`` can be set to\n- specify a remote branch to diff against.\n+ ``GOOGLE_CLOUD_REMOTE_FOR_LINT`` and ``GOOGLE_CLOUD_BRANCH_FOR_LINT`` can\n+ be set to specify a remote branch to diff against.\n \n :type allow_limited: bool\n :param allow_limited: Boolean indicating if a reduced set of files can\n@@ -163,8 +163,8 @@ def get_files_for_linting(allow_limited=True):\n diff_base = 'origin/master'\n elif os.getenv('TRAVIS') is None:\n # Only allow specified remote and branch in local dev.\n- remote = os.getenv('GCLOUD_REMOTE_FOR_LINT')\n- branch = os.getenv('GCLOUD_BRANCH_FOR_LINT')\n+ remote = os.getenv('GOOGLE_CLOUD_REMOTE_FOR_LINT')\n+ branch = os.getenv('GOOGLE_CLOUD_BRANCH_FOR_LINT')\n if remote is not None and branch is not None:\n diff_base = '%s/%s' % (remote, branch)\n \ndiff --git a/scripts/verify_included_modules.py b/scripts/verify_included_modules.py\n--- a/scripts/verify_included_modules.py\n+++ b/scripts/verify_included_modules.py\n@@ -30,31 +30,31 @@\n DOCS_DIR = os.path.join(BASE_DIR, 'docs')\n IGNORED_PREFIXES = ('test_', '_')\n IGNORED_MODULES = frozenset([\n- 'gcloud.__init__',\n- 'gcloud.bigquery.__init__',\n- 'gcloud.bigtable.__init__',\n- 'gcloud.datastore.__init__',\n- 'gcloud.dns.__init__',\n- 'gcloud.error_reporting.__init__',\n- 'gcloud.iterator',\n- 'gcloud.language.__init__',\n- 'gcloud.logging.__init__',\n- 'gcloud.logging.handlers.__init__',\n- 'gcloud.logging.handlers.transports.__init__',\n- 'gcloud.monitoring.__init__',\n- 'gcloud.pubsub.__init__',\n- 'gcloud.resource_manager.__init__',\n- 'gcloud.storage.__init__',\n- 'gcloud.streaming.__init__',\n- 'gcloud.streaming.buffered_stream',\n- 'gcloud.streaming.exceptions',\n- 'gcloud.streaming.http_wrapper',\n- 'gcloud.streaming.stream_slice',\n- 'gcloud.streaming.transfer',\n- 'gcloud.streaming.util',\n- 'gcloud.translate.__init__',\n- 'gcloud.vision.__init__',\n- 'gcloud.vision.fixtures',\n+ 'google.cloud.__init__',\n+ 'google.cloud.bigquery.__init__',\n+ 'google.cloud.bigtable.__init__',\n+ 'google.cloud.datastore.__init__',\n+ 'google.cloud.dns.__init__',\n+ 'google.cloud.error_reporting.__init__',\n+ 'google.cloud.iterator',\n+ 'google.cloud.language.__init__',\n+ 'google.cloud.logging.__init__',\n+ 'google.cloud.logging.handlers.__init__',\n+ 'google.cloud.logging.handlers.transports.__init__',\n+ 'google.cloud.monitoring.__init__',\n+ 'google.cloud.pubsub.__init__',\n+ 'google.cloud.resource_manager.__init__',\n+ 'google.cloud.storage.__init__',\n+ 'google.cloud.streaming.__init__',\n+ 'google.cloud.streaming.buffered_stream',\n+ 'google.cloud.streaming.exceptions',\n+ 'google.cloud.streaming.http_wrapper',\n+ 'google.cloud.streaming.stream_slice',\n+ 'google.cloud.streaming.transfer',\n+ 'google.cloud.streaming.util',\n+ 'google.cloud.translate.__init__',\n+ 'google.cloud.vision.__init__',\n+ 'google.cloud.vision.fixtures',\n ])\n \n \n@@ -133,9 +133,9 @@ def main(build_root='_build'):\n object_inventory_relpath)\n sphinx_mods = set(inventory['py:module'].keys())\n \n- library_dir = os.path.join(BASE_DIR, 'gcloud')\n+ library_dir = os.path.join(BASE_DIR, 'google', 'cloud')\n public_mods = get_public_modules(library_dir,\n- base_package='gcloud')\n+ base_package='google.cloud')\n public_mods = set(public_mods)\n \n if not sphinx_mods <= public_mods:\n@@ -163,8 +163,9 @@ def get_parser():\n :rtype: :class:`argparse.ArgumentParser`\n :returns: The parser for this script.\n \"\"\"\n- parser = argparse.ArgumentParser(\n- description='Run check that all GCloud modules are included in docs.')\n+ description = ('Run check that all google-cloud '\n+ 'modules are included in docs.')\n+ parser = argparse.ArgumentParser(description=description)\n parser.add_argument('--build-root', dest='build_root',\n help='The root directory where docs are located.')\n return parser\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -32,14 +32,20 @@\n REQUIREMENTS.extend(GRPC_EXTRAS)\n \n setup(\n- name='gcloud',\n+ name='google-cloud',\n version='0.18.0',\n description='API Client library for Google Cloud',\n author='Google Cloud Platform',\n- author_email='jjg+gcloud-python@google.com',\n+ author_email='jjg+google-cloud-python@google.com',\n long_description=README,\n scripts=[],\n- url='https://github.com/GoogleCloudPlatform/gcloud-python',\n+ url='https://github.com/GoogleCloudPlatform/google-cloud-python',\n+ namespace_packages=[\n+ 'google',\n+ 'google.cloud',\n+ 'google.cloud.logging',\n+ 'google.cloud.pubsub',\n+ ],\n packages=find_packages(),\n license='Apache 2.0',\n platforms='Posix; MacOS X; Windows',\n", "test_patch": "diff --git a/system_tests/bigquery.py b/system_tests/bigquery.py\n--- a/system_tests/bigquery.py\n+++ b/system_tests/bigquery.py\n@@ -16,10 +16,10 @@\n \n import unittest\n \n-from gcloud import _helpers\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud import bigquery\n-from gcloud.exceptions import Forbidden\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud import bigquery\n+from google.cloud.exceptions import Forbidden\n \n from retry import RetryErrors\n from retry import RetryInstanceState\n@@ -244,7 +244,7 @@ def test_update_table(self):\n \n def test_load_table_then_dump_table(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n NOW_SECONDS = 1448911495.484366\n NOW = datetime.datetime.utcfromtimestamp(\n@@ -294,7 +294,7 @@ def _has_rows(result):\n def test_load_table_from_storage_then_dump_table(self):\n import csv\n import tempfile\n- from gcloud.storage import Client as StorageClient\n+ from google.cloud.storage import Client as StorageClient\n local_id = unique_resource_id()\n BUCKET_NAME = 'bq_load_test' + local_id\n BLOB_NAME = 'person_ages.csv'\ndiff --git a/system_tests/bigtable.py b/system_tests/bigtable.py\n--- a/system_tests/bigtable.py\n+++ b/system_tests/bigtable.py\n@@ -17,19 +17,19 @@\n \n import unittest\n \n-from gcloud import _helpers\n-from gcloud._helpers import _datetime_from_microseconds\n-from gcloud._helpers import _microseconds_from_datetime\n-from gcloud._helpers import UTC\n-from gcloud.bigtable.client import Client\n-from gcloud.bigtable.column_family import MaxVersionsGCRule\n-from gcloud.bigtable.row_filters import ApplyLabelFilter\n-from gcloud.bigtable.row_filters import ColumnQualifierRegexFilter\n-from gcloud.bigtable.row_filters import RowFilterChain\n-from gcloud.bigtable.row_filters import RowFilterUnion\n-from gcloud.bigtable.row_data import Cell\n-from gcloud.bigtable.row_data import PartialRowData\n-from gcloud.environment_vars import TESTS_PROJECT\n+from google.cloud import _helpers\n+from google.cloud._helpers import _datetime_from_microseconds\n+from google.cloud._helpers import _microseconds_from_datetime\n+from google.cloud._helpers import UTC\n+from google.cloud.bigtable.client import Client\n+from google.cloud.bigtable.column_family import MaxVersionsGCRule\n+from google.cloud.bigtable.row_filters import ApplyLabelFilter\n+from google.cloud.bigtable.row_filters import ColumnQualifierRegexFilter\n+from google.cloud.bigtable.row_filters import RowFilterChain\n+from google.cloud.bigtable.row_filters import RowFilterUnion\n+from google.cloud.bigtable.row_data import Cell\n+from google.cloud.bigtable.row_data import PartialRowData\n+from google.cloud.environment_vars import TESTS_PROJECT\n \n from retry import RetryErrors\n from retry import RetryResult\n@@ -37,8 +37,8 @@\n \n \n LOCATION_ID = 'us-central1-c'\n-INSTANCE_ID = 'gcloud' + unique_resource_id('-')\n-TABLE_ID = 'gcloud-python-test-table'\n+INSTANCE_ID = 'google-cloud' + unique_resource_id('-')\n+TABLE_ID = 'google-cloud-python-test-table'\n COLUMN_FAMILY_ID1 = u'col-fam-id1'\n COLUMN_FAMILY_ID2 = u'col-fam-id2'\n COL_NAME1 = b'col-name1'\n@@ -66,7 +66,7 @@ class Config(object):\n def _wait_until_complete(operation, max_attempts=5):\n \"\"\"Wait until an operation has completed.\n \n- :type operation: :class:`gcloud.bigtable.instance.Operation`\n+ :type operation: :class:`google.cloud.bigtable.instance.Operation`\n :param operation: Operation that has not complete.\n \n :type max_attempts: int\ndiff --git a/system_tests/clear_datastore.py b/system_tests/clear_datastore.py\n--- a/system_tests/clear_datastore.py\n+++ b/system_tests/clear_datastore.py\n@@ -20,8 +20,8 @@\n \n import six\n \n-from gcloud import datastore\n-from gcloud.environment_vars import TESTS_PROJECT\n+from google.cloud import datastore\n+from google.cloud.environment_vars import TESTS_PROJECT\n \n \n FETCH_MAX = 20\n@@ -36,7 +36,7 @@\n \n \n def print_func(message):\n- if os.getenv('GCLOUD_NO_PRINT') != 'true':\n+ if os.getenv('GOOGLE_CLOUD_NO_PRINT') != 'true':\n print(message)\n \n \ndiff --git a/system_tests/datastore.py b/system_tests/datastore.py\n--- a/system_tests/datastore.py\n+++ b/system_tests/datastore.py\n@@ -18,13 +18,13 @@\n \n import httplib2\n \n-from gcloud import _helpers\n-from gcloud._helpers import UTC\n-from gcloud import datastore\n-from gcloud.datastore.helpers import GeoPoint\n-from gcloud.environment_vars import GCD_DATASET\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud.exceptions import Conflict\n+from google.cloud import _helpers\n+from google.cloud._helpers import UTC\n+from google.cloud import datastore\n+from google.cloud.datastore.helpers import GeoPoint\n+from google.cloud.environment_vars import GCD_DATASET\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud.exceptions import Conflict\n \n import clear_datastore\n import populate_datastore\n@@ -433,7 +433,8 @@ def test_transaction_via_with_statement(self):\n self.assertEqual(retrieved_entity, entity)\n \n def test_transaction_via_explicit_begin_get_commit(self):\n- # See https://github.com/GoogleCloudPlatform/gcloud-python/issues/1859\n+ # See\n+ # github.com/GoogleCloudPlatform/google-cloud-python/issues/1859\n # Note that this example lacks the threading which provokes the race\n # condition in that issue: we are basically just exercising the\n # \"explict\" path for using transactions.\ndiff --git a/system_tests/language.py b/system_tests/language.py\n--- a/system_tests/language.py\n+++ b/system_tests/language.py\n@@ -14,11 +14,11 @@\n \n import unittest\n \n-from gcloud import _helpers\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud import exceptions\n-from gcloud import language\n-from gcloud import storage\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud import exceptions\n+from google.cloud import language\n+from google.cloud import storage\n \n from system_test_utils import unique_resource_id\n from retry import RetryErrors\n@@ -67,7 +67,7 @@ def tearDown(self):\n value.delete()\n \n def _check_analyze_entities_result(self, entities):\n- from gcloud.language.entity import EntityType\n+ from google.cloud.language.entity import EntityType\n \n self.assertEqual(len(entities), 3)\n entity1, entity2, entity3 = entities\ndiff --git a/system_tests/local_test_setup.sample b/system_tests/local_test_setup.sample\n--- a/system_tests/local_test_setup.sample\n+++ b/system_tests/local_test_setup.sample\n@@ -1,4 +1,4 @@\n export GOOGLE_APPLICATION_CREDENTIALS=\"app_credentials.json.sample\"\n-export GCLOUD_TESTS_PROJECT_ID=\"my-project\"\n-export GCLOUD_REMOTE_FOR_LINT=\"upstream\"\n-export GCLOUD_BRANCH_FOR_LINT=\"master\"\n+export GOOGLE_CLOUD_TESTS_PROJECT_ID=\"my-project\"\n+export GOOGLE_CLOUD_REMOTE_FOR_LINT=\"upstream\"\n+export GOOGLE_CLOUD_BRANCH_FOR_LINT=\"master\"\ndiff --git a/system_tests/logging_.py b/system_tests/logging_.py\n--- a/system_tests/logging_.py\n+++ b/system_tests/logging_.py\n@@ -15,12 +15,12 @@\n import logging\n import unittest\n \n-import gcloud.logging\n-import gcloud.logging.handlers.handlers\n-from gcloud.logging.handlers.handlers import CloudLoggingHandler\n-from gcloud.logging.handlers.transports import SyncTransport\n-from gcloud import _helpers\n-from gcloud.environment_vars import TESTS_PROJECT\n+import google.cloud.logging\n+import google.cloud.logging.handlers.handlers\n+from google.cloud.logging.handlers.handlers import CloudLoggingHandler\n+from google.cloud.logging.handlers.transports import SyncTransport\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import TESTS_PROJECT\n \n from retry import RetryErrors\n from retry import RetryResult\n@@ -31,9 +31,9 @@\n DEFAULT_SINK_NAME = 'system-tests-sink%s' % (_RESOURCE_ID,)\n DEFAULT_FILTER = 'logName:syslog AND severity>=INFO'\n DEFAULT_DESCRIPTION = 'System testing'\n-BUCKET_NAME = 'gcloud-python-system-testing%s' % (_RESOURCE_ID,)\n+BUCKET_NAME = 'google-cloud-python-system-testing%s' % (_RESOURCE_ID,)\n DATASET_NAME = ('system_testing_dataset' + _RESOURCE_ID).replace('-', '_')\n-TOPIC_NAME = 'gcloud-python-system-testing%s' % (_RESOURCE_ID,)\n+TOPIC_NAME = 'google-cloud-python-system-testing%s' % (_RESOURCE_ID,)\n \n \n def _retry_on_unavailable(exc):\n@@ -57,7 +57,7 @@ class Config(object):\n \n def setUpModule():\n _helpers.PROJECT = TESTS_PROJECT\n- Config.CLIENT = gcloud.logging.Client()\n+ Config.CLIENT = google.cloud.logging.Client()\n \n \n class TestLogging(unittest.TestCase):\n@@ -67,7 +67,7 @@ def setUp(self):\n self._handlers_cache = logging.getLogger().handlers[:]\n \n def tearDown(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n retry = RetryErrors(NotFound)\n for doomed in self.to_delete:\n retry(doomed.delete)()\n@@ -188,7 +188,7 @@ def test_log_root_handler(self):\n logger = Config.CLIENT.logger(handler.name)\n self.to_delete.append(logger)\n \n- gcloud.logging.handlers.handlers.setup_logging(handler)\n+ google.cloud.logging.handlers.handlers.setup_logging(handler)\n logging.warn(LOG_MESSAGE)\n \n entries, _ = self._list_entries(logger)\n@@ -254,7 +254,7 @@ def test_list_metrics(self):\n set([DEFAULT_METRIC_NAME]))\n \n def test_reload_metric(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n retry = RetryErrors(Conflict)\n metric = Config.CLIENT.metric(\n DEFAULT_METRIC_NAME, DEFAULT_FILTER, DEFAULT_DESCRIPTION)\n@@ -268,7 +268,7 @@ def test_reload_metric(self):\n self.assertEqual(metric.description, DEFAULT_DESCRIPTION)\n \n def test_update_metric(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n retry = RetryErrors(Conflict)\n NEW_FILTER = 'logName:other'\n NEW_DESCRIPTION = 'updated'\n@@ -287,7 +287,7 @@ def test_update_metric(self):\n self.assertEqual(after.description, NEW_DESCRIPTION)\n \n def _init_storage_bucket(self):\n- from gcloud import storage\n+ from google.cloud import storage\n BUCKET_URI = 'storage.googleapis.com/%s' % (BUCKET_NAME,)\n \n # Create the destination bucket, and set up the ACL to allow\n@@ -313,7 +313,7 @@ def test_create_sink_storage_bucket(self):\n self.assertTrue(sink.exists())\n \n def test_create_sink_pubsub_topic(self):\n- from gcloud import pubsub\n+ from google.cloud import pubsub\n \n # Create the destination topic, and set up the IAM policy to allow\n # Stackdriver Logging to write into it.\n@@ -335,8 +335,8 @@ def test_create_sink_pubsub_topic(self):\n self.assertTrue(sink.exists())\n \n def _init_bigquery_dataset(self):\n- from gcloud import bigquery\n- from gcloud.bigquery.dataset import AccessGrant\n+ from google.cloud import bigquery\n+ from google.cloud.bigquery.dataset import AccessGrant\n DATASET_URI = 'bigquery.googleapis.com/projects/%s/datasets/%s' % (\n Config.CLIENT.project, DATASET_NAME,)\n \n@@ -377,7 +377,7 @@ def test_list_sinks(self):\n set([DEFAULT_SINK_NAME]))\n \n def test_reload_sink(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n retry = RetryErrors(Conflict)\n uri = self._init_bigquery_dataset()\n sink = Config.CLIENT.sink(DEFAULT_SINK_NAME, DEFAULT_FILTER, uri)\n@@ -391,7 +391,7 @@ def test_reload_sink(self):\n self.assertEqual(sink.destination, uri)\n \n def test_update_sink(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n retry = RetryErrors(Conflict)\n bucket_uri = self._init_storage_bucket()\n dataset_uri = self._init_bigquery_dataset()\ndiff --git a/system_tests/monitoring.py b/system_tests/monitoring.py\n--- a/system_tests/monitoring.py\n+++ b/system_tests/monitoring.py\n@@ -14,12 +14,12 @@\n \n import unittest\n \n-from gcloud import _helpers\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud.exceptions import InternalServerError\n-from gcloud.exceptions import NotFound\n-from gcloud.exceptions import ServiceUnavailable\n-from gcloud import monitoring\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud.exceptions import InternalServerError\n+from google.cloud.exceptions import NotFound\n+from google.cloud.exceptions import ServiceUnavailable\n+from google.cloud import monitoring\n \n from retry import RetryErrors\n from system_test_utils import unique_resource_id\ndiff --git a/system_tests/populate_datastore.py b/system_tests/populate_datastore.py\n--- a/system_tests/populate_datastore.py\n+++ b/system_tests/populate_datastore.py\n@@ -21,8 +21,8 @@\n \n import six\n \n-from gcloud import datastore\n-from gcloud.environment_vars import TESTS_PROJECT\n+from google.cloud import datastore\n+from google.cloud.environment_vars import TESTS_PROJECT\n \n \n ANCESTOR = ('Book', 'GoT')\n@@ -84,7 +84,7 @@\n \n \n def print_func(message):\n- if os.getenv('GCLOUD_NO_PRINT') != 'true':\n+ if os.getenv('GOOGLE_CLOUD_NO_PRINT') != 'true':\n print(message)\n \n \ndiff --git a/system_tests/pubsub.py b/system_tests/pubsub.py\n--- a/system_tests/pubsub.py\n+++ b/system_tests/pubsub.py\n@@ -20,10 +20,12 @@\n from grpc._channel import _Rendezvous\n import httplib2\n \n-from gcloud import _helpers\n-from gcloud.environment_vars import PUBSUB_EMULATOR\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud import pubsub\n+# pylint: disable=ungrouped-imports\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import PUBSUB_EMULATOR\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud import pubsub\n+# pylint: enable=ungrouped-imports\n \n from retry import RetryInstanceState\n from retry import RetryResult\n@@ -213,7 +215,7 @@ def _maybe_emulator_skip(self):\n self.skipTest('IAM not supported by Pub/Sub emulator')\n \n def test_topic_iam_policy(self):\n- from gcloud.pubsub.iam import PUBSUB_TOPICS_GET_IAM_POLICY\n+ from google.cloud.pubsub.iam import PUBSUB_TOPICS_GET_IAM_POLICY\n self._maybe_emulator_skip()\n topic_name = 'test-topic-iam-policy-topic' + unique_resource_id('-')\n topic = Config.CLIENT.topic(topic_name)\n@@ -233,7 +235,7 @@ def test_topic_iam_policy(self):\n self.assertEqual(new_policy.viewers, policy.viewers)\n \n def test_subscription_iam_policy(self):\n- from gcloud.pubsub.iam import PUBSUB_SUBSCRIPTIONS_GET_IAM_POLICY\n+ from google.cloud.pubsub.iam import PUBSUB_SUBSCRIPTIONS_GET_IAM_POLICY\n self._maybe_emulator_skip()\n topic_name = 'test-sub-iam-policy-topic' + unique_resource_id('-')\n topic = Config.CLIENT.topic(topic_name)\n@@ -264,10 +266,10 @@ def test_subscription_iam_policy(self):\n self.assertEqual(new_policy.viewers, policy.viewers)\n \n # This test is ultra-flaky. See:\n- # https://github.com/GoogleCloudPlatform/gcloud-python/issues/2080\n+ # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2080\n @unittest.expectedFailure\n def test_fetch_delete_subscription_w_deleted_topic(self):\n- from gcloud.iterator import MethodIterator\n+ from google.cloud.iterator import MethodIterator\n TO_DELETE = 'delete-me' + unique_resource_id('-')\n ORPHANED = 'orphaned' + unique_resource_id('-')\n topic = Config.CLIENT.topic(TO_DELETE)\ndiff --git a/system_tests/run_emulator.py b/system_tests/run_emulator.py\n--- a/system_tests/run_emulator.py\n+++ b/system_tests/run_emulator.py\n@@ -25,9 +25,9 @@\n \n import psutil\n \n-from gcloud.environment_vars import GCD_DATASET\n-from gcloud.environment_vars import GCD_HOST\n-from gcloud.environment_vars import PUBSUB_EMULATOR\n+from google.cloud.environment_vars import GCD_DATASET\n+from google.cloud.environment_vars import GCD_HOST\n+from google.cloud.environment_vars import PUBSUB_EMULATOR\n from run_system_test import run_module_tests\n \n \n@@ -46,7 +46,7 @@ def get_parser():\n :returns: The parser for this script.\n \"\"\"\n parser = argparse.ArgumentParser(\n- description='Run GCloud system tests against local emulator.')\n+ description='Run google-cloud system tests against local emulator.')\n parser.add_argument('--package', dest='package',\n choices=('datastore', 'pubsub'),\n default='datastore', help='Package to be tested.')\ndiff --git a/system_tests/run_system_test.py b/system_tests/run_system_test.py\n--- a/system_tests/run_system_test.py\n+++ b/system_tests/run_system_test.py\n@@ -47,7 +47,7 @@ class FailedSystemTestModule(Exception):\n \n def get_parser():\n parser = argparse.ArgumentParser(\n- description='GCloud test runner against actual project.')\n+ description='google-cloud test runner against actual project.')\n parser.add_argument('--package', dest='package',\n choices=TEST_MODULES.keys(),\n default='datastore', help='Package to be tested.')\ndiff --git a/system_tests/storage.py b/system_tests/storage.py\n--- a/system_tests/storage.py\n+++ b/system_tests/storage.py\n@@ -20,11 +20,11 @@\n import httplib2\n import six\n \n-from gcloud import _helpers\n-from gcloud.environment_vars import TESTS_PROJECT\n-from gcloud import exceptions\n-from gcloud import storage\n-from gcloud.storage._helpers import _base64_md5hash\n+from google.cloud import _helpers\n+from google.cloud.environment_vars import TESTS_PROJECT\n+from google.cloud import exceptions\n+from google.cloud import storage\n+from google.cloud.storage._helpers import _base64_md5hash\n \n from system_test_utils import unique_resource_id\n from retry import RetryErrors\ndiff --git a/system_tests/system_test_utils.py b/system_tests/system_test_utils.py\n--- a/system_tests/system_test_utils.py\n+++ b/system_tests/system_test_utils.py\n@@ -17,8 +17,8 @@\n import sys\n import time\n \n-from gcloud.environment_vars import CREDENTIALS as TEST_CREDENTIALS\n-from gcloud.environment_vars import TESTS_PROJECT\n+from google.cloud.environment_vars import CREDENTIALS as TEST_CREDENTIALS\n+from google.cloud.environment_vars import TESTS_PROJECT\n \n \n # From shell environ. May be None.\ndiff --git a/system_tests/translate.py b/system_tests/translate.py\n--- a/system_tests/translate.py\n+++ b/system_tests/translate.py\n@@ -17,10 +17,10 @@\n \n import unittest\n \n-from gcloud import translate\n+from google.cloud import translate\n \n \n-ENV_VAR = 'GCLOUD_TESTS_API_KEY'\n+ENV_VAR = 'GOOGLE_CLOUD_TESTS_API_KEY'\n \n \n class Config(object):\ndiff --git a/unit_tests/bigquery/test__helpers.py b/unit_tests/bigquery/test__helpers.py\n--- a/unit_tests/bigquery/test__helpers.py\n+++ b/unit_tests/bigquery/test__helpers.py\n@@ -18,7 +18,7 @@\n class Test_ConfigurationProperty(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery._helpers import _ConfigurationProperty\n+ from google.cloud.bigquery._helpers import _ConfigurationProperty\n return _ConfigurationProperty\n \n def _makeOne(self, *args, **kw):\n@@ -53,7 +53,7 @@ def __init__(self):\n class Test_TypedProperty(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery._helpers import _TypedProperty\n+ from google.cloud.bigquery._helpers import _TypedProperty\n return _TypedProperty\n \n def _makeOne(self, *args, **kw):\n@@ -86,7 +86,7 @@ def __init__(self):\n class Test_EnumProperty(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery._helpers import _EnumProperty\n+ from google.cloud.bigquery._helpers import _EnumProperty\n return _EnumProperty\n \n def test_it(self):\ndiff --git a/unit_tests/bigquery/test_client.py b/unit_tests/bigquery/test_client.py\n--- a/unit_tests/bigquery/test_client.py\n+++ b/unit_tests/bigquery/test_client.py\n@@ -18,14 +18,14 @@\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery.client import Client\n+ from google.cloud.bigquery.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor(self):\n- from gcloud.bigquery.connection import Connection\n+ from google.cloud.bigquery.connection import Connection\n PROJECT = 'PROJECT'\n creds = _Credentials()\n http = object()\n@@ -35,7 +35,7 @@ def test_ctor(self):\n self.assertTrue(client.connection.http is http)\n \n def test_list_datasets_defaults(self):\n- from gcloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Dataset\n PROJECT = 'PROJECT'\n DATASET_1 = 'dataset_one'\n DATASET_2 = 'dataset_two'\n@@ -97,7 +97,7 @@ def test_list_datasets_explicit_response_missing_datasets_key(self):\n {'all': True, 'maxResults': 3, 'pageToken': TOKEN})\n \n def test_dataset(self):\n- from gcloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Dataset\n PROJECT = 'PROJECT'\n DATASET = 'dataset_name'\n creds = _Credentials()\n@@ -116,10 +116,10 @@ def test_job_from_resource_unknown_type(self):\n client.job_from_resource({'configuration': {'nonesuch': {}}})\n \n def test_list_jobs_defaults(self):\n- from gcloud.bigquery.job import LoadTableFromStorageJob\n- from gcloud.bigquery.job import CopyJob\n- from gcloud.bigquery.job import ExtractTableToStorageJob\n- from gcloud.bigquery.job import QueryJob\n+ from google.cloud.bigquery.job import LoadTableFromStorageJob\n+ from google.cloud.bigquery.job import CopyJob\n+ from google.cloud.bigquery.job import ExtractTableToStorageJob\n+ from google.cloud.bigquery.job import QueryJob\n PROJECT = 'PROJECT'\n DATASET = 'test_dataset'\n SOURCE_TABLE = 'source_table'\n@@ -243,7 +243,7 @@ def test_list_jobs_defaults(self):\n self.assertEqual(req['query_params'], {'projection': 'full'})\n \n def test_list_jobs_load_job_wo_sourceUris(self):\n- from gcloud.bigquery.job import LoadTableFromStorageJob\n+ from google.cloud.bigquery.job import LoadTableFromStorageJob\n PROJECT = 'PROJECT'\n DATASET = 'test_dataset'\n SOURCE_TABLE = 'source_table'\n@@ -321,7 +321,7 @@ def test_list_jobs_explicit_missing(self):\n 'stateFilter': 'done'})\n \n def test_load_table_from_storage(self):\n- from gcloud.bigquery.job import LoadTableFromStorageJob\n+ from google.cloud.bigquery.job import LoadTableFromStorageJob\n PROJECT = 'PROJECT'\n JOB = 'job_name'\n DATASET = 'dataset_name'\n@@ -340,7 +340,7 @@ def test_load_table_from_storage(self):\n self.assertTrue(job.destination is destination)\n \n def test_copy_table(self):\n- from gcloud.bigquery.job import CopyJob\n+ from google.cloud.bigquery.job import CopyJob\n PROJECT = 'PROJECT'\n JOB = 'job_name'\n DATASET = 'dataset_name'\n@@ -360,7 +360,7 @@ def test_copy_table(self):\n self.assertTrue(job.destination is destination)\n \n def test_extract_table_to_storage(self):\n- from gcloud.bigquery.job import ExtractTableToStorageJob\n+ from google.cloud.bigquery.job import ExtractTableToStorageJob\n PROJECT = 'PROJECT'\n JOB = 'job_name'\n DATASET = 'dataset_name'\n@@ -379,7 +379,7 @@ def test_extract_table_to_storage(self):\n self.assertEqual(list(job.destination_uris), [DESTINATION])\n \n def test_run_async_query(self):\n- from gcloud.bigquery.job import QueryJob\n+ from google.cloud.bigquery.job import QueryJob\n PROJECT = 'PROJECT'\n JOB = 'job_name'\n QUERY = 'select count(*) from persons'\n@@ -393,7 +393,7 @@ def test_run_async_query(self):\n self.assertEqual(job.query, QUERY)\n \n def test_run_sync_query(self):\n- from gcloud.bigquery.query import QueryResults\n+ from google.cloud.bigquery.query import QueryResults\n PROJECT = 'PROJECT'\n QUERY = 'select count(*) from persons'\n creds = _Credentials()\ndiff --git a/unit_tests/bigquery/test_connection.py b/unit_tests/bigquery/test_connection.py\n--- a/unit_tests/bigquery/test_connection.py\n+++ b/unit_tests/bigquery/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery.connection import Connection\n+ from google.cloud.bigquery.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/bigquery/test_dataset.py b/unit_tests/bigquery/test_dataset.py\n--- a/unit_tests/bigquery/test_dataset.py\n+++ b/unit_tests/bigquery/test_dataset.py\n@@ -18,7 +18,7 @@\n class TestAccessGrant(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery.dataset import AccessGrant\n+ from google.cloud.bigquery.dataset import AccessGrant\n return AccessGrant\n \n def _makeOne(self, *args, **kw):\n@@ -81,7 +81,7 @@ class TestDataset(unittest.TestCase):\n DS_NAME = 'dataset-name'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Dataset\n return Dataset\n \n def _makeOne(self, *args, **kw):\n@@ -89,7 +89,7 @@ def _makeOne(self, *args, **kw):\n \n def _setUpConstants(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n self.WHEN_TS = 1437767599.006\n self.WHEN = datetime.datetime.utcfromtimestamp(self.WHEN_TS).replace(\n@@ -201,7 +201,7 @@ def test_access_roles_setter_non_list(self):\n dataset.access_grants = object()\n \n def test_access_roles_setter_invalid_field(self):\n- from gcloud.bigquery.dataset import AccessGrant\n+ from google.cloud.bigquery.dataset import AccessGrant\n client = _Client(self.PROJECT)\n dataset = self._makeOne(self.DS_NAME, client)\n phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com')\n@@ -209,7 +209,7 @@ def test_access_roles_setter_invalid_field(self):\n dataset.access_grants = [phred, object()]\n \n def test_access_roles_setter(self):\n- from gcloud.bigquery.dataset import AccessGrant\n+ from google.cloud.bigquery.dataset import AccessGrant\n client = _Client(self.PROJECT)\n dataset = self._makeOne(self.DS_NAME, client)\n phred = AccessGrant('OWNER', 'userByEmail', 'phred@example.com')\n@@ -340,7 +340,7 @@ def test_create_w_bound_client(self):\n self._verifyResourceProperties(dataset, RESOURCE)\n \n def test_create_w_alternate_client(self):\n- from gcloud.bigquery.dataset import AccessGrant\n+ from google.cloud.bigquery.dataset import AccessGrant\n PATH = 'projects/%s/datasets' % self.PROJECT\n USER_EMAIL = 'phred@example.com'\n GROUP_EMAIL = 'group-name@lists.example.com'\n@@ -649,7 +649,7 @@ def test_list_tables_empty(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_tables_defaults(self):\n- from gcloud.bigquery.table import Table\n+ from google.cloud.bigquery.table import Table\n \n TABLE_1 = 'table_one'\n TABLE_2 = 'table_two'\n@@ -692,7 +692,7 @@ def test_list_tables_defaults(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_tables_explicit(self):\n- from gcloud.bigquery.table import Table\n+ from google.cloud.bigquery.table import Table\n \n TABLE_1 = 'table_one'\n TABLE_2 = 'table_two'\n@@ -736,7 +736,7 @@ def test_list_tables_explicit(self):\n {'maxResults': 3, 'pageToken': TOKEN})\n \n def test_table_wo_schema(self):\n- from gcloud.bigquery.table import Table\n+ from google.cloud.bigquery.table import Table\n conn = _Connection({})\n client = _Client(project=self.PROJECT, connection=conn)\n dataset = self._makeOne(self.DS_NAME, client=client)\n@@ -747,8 +747,8 @@ def test_table_wo_schema(self):\n self.assertEqual(table.schema, [])\n \n def test_table_w_schema(self):\n- from gcloud.bigquery.schema import SchemaField\n- from gcloud.bigquery.table import Table\n+ from google.cloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.table import Table\n conn = _Connection({})\n client = _Client(project=self.PROJECT, connection=conn)\n dataset = self._makeOne(self.DS_NAME, client=client)\n@@ -775,7 +775,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/bigquery/test_job.py b/unit_tests/bigquery/test_job.py\n--- a/unit_tests/bigquery/test_job.py\n+++ b/unit_tests/bigquery/test_job.py\n@@ -18,7 +18,7 @@\n class Test_UDFResourcesProperty(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery.job import UDFResourcesProperty\n+ from google.cloud.bigquery.job import UDFResourcesProperty\n return UDFResourcesProperty\n \n def _makeOne(self, *args, **kw):\n@@ -43,7 +43,7 @@ def test_instance_getter_empty(self):\n self.assertEqual(instance.udf_resources, [])\n \n def test_instance_getter_w_non_empty_list(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n udf_resources = [UDFResource(\"resourceUri\", RESOURCE_URI)]\n _, klass = self._descriptor_and_klass()\n@@ -53,7 +53,7 @@ def test_instance_getter_w_non_empty_list(self):\n self.assertEqual(instance.udf_resources, udf_resources)\n \n def test_instance_setter_w_empty_list(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n udf_resources = [UDFResource(\"resourceUri\", RESOURCE_URI)]\n _, klass = self._descriptor_and_klass()\n@@ -65,7 +65,7 @@ def test_instance_setter_w_empty_list(self):\n self.assertEqual(instance.udf_resources, [])\n \n def test_instance_setter_w_valid_udf(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n udf_resources = [UDFResource(\"resourceUri\", RESOURCE_URI)]\n _, klass = self._descriptor_and_klass()\n@@ -97,7 +97,7 @@ def _makeOne(self, *args, **kw):\n \n def _setUpConstants(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n self.WHEN_TS = 1437767599.006\n self.WHEN = datetime.datetime.utcfromtimestamp(self.WHEN_TS).replace(\n@@ -193,7 +193,7 @@ class TestLoadTableFromStorageJob(unittest.TestCase, _Base):\n JOB_TYPE = 'load'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.job import LoadTableFromStorageJob\n+ from google.cloud.bigquery.job import LoadTableFromStorageJob\n return LoadTableFromStorageJob\n \n def _setUpConstants(self):\n@@ -332,7 +332,7 @@ def test_ctor(self):\n self.assertTrue(job.write_disposition is None)\n \n def test_ctor_w_schema(self):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n client = _Client(self.PROJECT)\n table = _Table()\n full_name = SchemaField('full_name', 'STRING', mode='REQUIRED')\n@@ -349,7 +349,7 @@ def test_schema_setter_non_list(self):\n job.schema = object()\n \n def test_schema_setter_invalid_field(self):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n client = _Client(self.PROJECT)\n table = _Table()\n job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client)\n@@ -358,7 +358,7 @@ def test_schema_setter_invalid_field(self):\n job.schema = [full_name, object()]\n \n def test_schema_setter(self):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n client = _Client(self.PROJECT)\n table = _Table()\n job = self._makeOne(self.JOB_NAME, table, [self.SOURCE1], client)\n@@ -369,8 +369,8 @@ def test_schema_setter(self):\n \n def test_props_set_by_server(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _millis\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _millis\n \n CREATED = datetime.datetime(2015, 8, 11, 12, 13, 22, tzinfo=UTC)\n STARTED = datetime.datetime(2015, 8, 11, 13, 47, 15, tzinfo=UTC)\n@@ -523,7 +523,7 @@ def test_begin_w_bound_client(self):\n self._verifyResourceProperties(job, RESOURCE)\n \n def test_begin_w_alternate_client(self):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n PATH = 'projects/%s/jobs' % self.PROJECT\n RESOURCE = self._makeResource(ended=True)\n LOAD_CONFIGURATION = {\n@@ -701,7 +701,7 @@ class TestCopyJob(unittest.TestCase, _Base):\n DESTINATION_TABLE = 'destination_table'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.job import CopyJob\n+ from google.cloud.bigquery.job import CopyJob\n return CopyJob\n \n def _makeResource(self, started=False, ended=False):\n@@ -998,7 +998,7 @@ class TestExtractTableToStorageJob(unittest.TestCase, _Base):\n DESTINATION_URI = 'gs://bucket_name/object_name'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.job import ExtractTableToStorageJob\n+ from google.cloud.bigquery.job import ExtractTableToStorageJob\n return ExtractTableToStorageJob\n \n def _makeResource(self, started=False, ended=False):\n@@ -1291,7 +1291,7 @@ class TestQueryJob(unittest.TestCase, _Base):\n DESTINATION_TABLE = 'destination_table'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.job import QueryJob\n+ from google.cloud.bigquery.job import QueryJob\n return QueryJob\n \n def _makeResource(self, started=False, ended=False):\n@@ -1474,8 +1474,8 @@ def test_begin_w_bound_client(self):\n self._verifyResourceProperties(job, RESOURCE)\n \n def test_begin_w_alternate_client(self):\n- from gcloud.bigquery.dataset import Dataset\n- from gcloud.bigquery.dataset import Table\n+ from google.cloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Table\n PATH = 'projects/%s/jobs' % self.PROJECT\n TABLE = 'TABLE'\n DS_NAME = 'DATASET'\n@@ -1539,7 +1539,7 @@ def test_begin_w_alternate_client(self):\n self._verifyResourceProperties(job, RESOURCE)\n \n def test_begin_w_bound_client_and_udf(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n PATH = 'projects/%s/jobs' % self.PROJECT\n RESOURCE = self._makeResource()\n@@ -1611,8 +1611,8 @@ def test_exists_hit_w_alternate_client(self):\n self.assertEqual(req['query_params'], {'fields': 'id'})\n \n def test_reload_w_bound_client(self):\n- from gcloud.bigquery.dataset import Dataset\n- from gcloud.bigquery.dataset import Table\n+ from google.cloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Table\n PATH = 'projects/%s/jobs/%s' % (self.PROJECT, self.JOB_NAME)\n DS_NAME = 'DATASET'\n DEST_TABLE = 'dest_table'\n@@ -1669,7 +1669,7 @@ def __init__(self, project='project', connection=None):\n self.connection = connection\n \n def dataset(self, name):\n- from gcloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Dataset\n return Dataset(name, client=self)\n \n \n@@ -1700,7 +1700,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/bigquery/test_query.py b/unit_tests/bigquery/test_query.py\n--- a/unit_tests/bigquery/test_query.py\n+++ b/unit_tests/bigquery/test_query.py\n@@ -24,7 +24,7 @@ class TestQueryResults(unittest.TestCase):\n TOKEN = 'TOKEN'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.query import QueryResults\n+ from google.cloud.bigquery.query import QueryResults\n return QueryResults\n \n def _makeOne(self, *args, **kw):\n@@ -73,7 +73,7 @@ def _makeResource(self, complete=False):\n return resource\n \n def _verifySchema(self, query, resource):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n if 'schema' in resource:\n fields = resource['schema']['fields']\n self.assertEqual(len(query.schema), len(fields))\n@@ -144,7 +144,7 @@ def test_job_wo_jobid(self):\n self.assertTrue(query.job is None)\n \n def test_job_w_jobid(self):\n- from gcloud.bigquery.job import QueryJob\n+ from google.cloud.bigquery.job import QueryJob\n SERVER_GENERATED = 'SERVER_GENERATED'\n client = _Client(self.PROJECT)\n query = self._makeOne(self.QUERY, client)\n@@ -234,7 +234,7 @@ def test_run_w_alternate_client(self):\n self._verifyResourceProperties(query, RESOURCE)\n \n def test_run_w_inline_udf(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n INLINE_UDF_CODE = 'var someCode = \"here\";'\n PATH = 'projects/%s/queries' % self.PROJECT\n RESOURCE = self._makeResource(complete=False)\n@@ -256,7 +256,7 @@ def test_run_w_inline_udf(self):\n self._verifyResourceProperties(query, RESOURCE)\n \n def test_run_w_udf_resource_uri(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n PATH = 'projects/%s/queries' % self.PROJECT\n RESOURCE = self._makeResource(complete=False)\n@@ -278,7 +278,7 @@ def test_run_w_udf_resource_uri(self):\n self._verifyResourceProperties(query, RESOURCE)\n \n def test_run_w_mixed_udfs(self):\n- from gcloud.bigquery.job import UDFResource\n+ from google.cloud.bigquery.job import UDFResource\n RESOURCE_URI = 'gs://some-bucket/js/lib.js'\n INLINE_UDF_CODE = 'var someCode = \"here\";'\n PATH = 'projects/%s/queries' % self.PROJECT\n@@ -388,7 +388,7 @@ def __init__(self, project='project', connection=None):\n self.connection = connection\n \n def dataset(self, name):\n- from gcloud.bigquery.dataset import Dataset\n+ from google.cloud.bigquery.dataset import Dataset\n return Dataset(name, client=self)\n \n \ndiff --git a/unit_tests/bigquery/test_schema.py b/unit_tests/bigquery/test_schema.py\n--- a/unit_tests/bigquery/test_schema.py\n+++ b/unit_tests/bigquery/test_schema.py\n@@ -18,7 +18,7 @@\n class TestSchemaField(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigquery.schema import SchemaField\n+ from google.cloud.bigquery.schema import SchemaField\n return SchemaField\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/bigquery/test_table.py b/unit_tests/bigquery/test_table.py\n--- a/unit_tests/bigquery/test_table.py\n+++ b/unit_tests/bigquery/test_table.py\n@@ -36,7 +36,7 @@ class TestTable(unittest.TestCase, _SchemaBase):\n TABLE_NAME = 'table-name'\n \n def _getTargetClass(self):\n- from gcloud.bigquery.table import Table\n+ from google.cloud.bigquery.table import Table\n return Table\n \n def _makeOne(self, *args, **kw):\n@@ -44,7 +44,7 @@ def _makeOne(self, *args, **kw):\n \n def _setUpConstants(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n self.WHEN_TS = 1437767599.006\n self.WHEN = datetime.datetime.utcfromtimestamp(self.WHEN_TS).replace(\n@@ -160,7 +160,7 @@ def test_ctor(self):\n self.assertEqual(table.view_query, None)\n \n def test_ctor_w_schema(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n client = _Client(self.PROJECT)\n dataset = _Dataset(client)\n full_name = SchemaField('full_name', 'STRING', mode='REQUIRED')\n@@ -221,7 +221,7 @@ def test_schema_setter_non_list(self):\n table.schema = object()\n \n def test_schema_setter_invalid_field(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n client = _Client(self.PROJECT)\n dataset = _Dataset(client)\n table = self._makeOne(self.TABLE_NAME, dataset)\n@@ -230,7 +230,7 @@ def test_schema_setter_invalid_field(self):\n table.schema = [full_name, object()]\n \n def test_schema_setter(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n client = _Client(self.PROJECT)\n dataset = _Dataset(client)\n table = self._makeOne(self.TABLE_NAME, dataset)\n@@ -241,8 +241,8 @@ def test_schema_setter(self):\n \n def test_props_set_by_server(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _millis\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _millis\n \n CREATED = datetime.datetime(2015, 7, 29, 12, 13, 22, tzinfo=UTC)\n MODIFIED = datetime.datetime(2015, 7, 29, 14, 47, 15, tzinfo=UTC)\n@@ -294,7 +294,7 @@ def test_expires_setter_bad_value(self):\n \n def test_expires_setter(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n WHEN = datetime.datetime(2015, 7, 28, 16, 39, tzinfo=UTC)\n client = _Client(self.PROJECT)\n@@ -400,7 +400,7 @@ def test_create_no_view_query_no_schema(self):\n table.create()\n \n def test_create_w_bound_client(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME)\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n@@ -430,7 +430,7 @@ def test_create_w_bound_client(self):\n self._verifyResourceProperties(table, RESOURCE)\n \n def test_create_w_partition_no_expire(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME)\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n@@ -464,7 +464,7 @@ def test_create_w_partition_no_expire(self):\n self._verifyResourceProperties(table, RESOURCE)\n \n def test_create_w_partition_and_expire(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME)\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n@@ -498,7 +498,7 @@ def test_create_w_partition_and_expire(self):\n self._verifyResourceProperties(table, RESOURCE)\n \n def test_partition_type_setter_bad_type(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -511,7 +511,7 @@ def test_partition_type_setter_bad_type(self):\n table.partitioning_type = 123\n \n def test_partition_type_setter_unknown_value(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -524,7 +524,7 @@ def test_partition_type_setter_unknown_value(self):\n table.partitioning_type = \"HASH\"\n \n def test_partition_type_setter_w_known_value(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -538,7 +538,7 @@ def test_partition_type_setter_w_known_value(self):\n self.assertEqual(table.partitioning_type, 'DAY')\n \n def test_partition_type_setter_w_none(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -553,7 +553,7 @@ def test_partition_type_setter_w_none(self):\n self.assertFalse('timePartitioning' in table._properties)\n \n def test_partition_experation_bad_type(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -566,7 +566,7 @@ def test_partition_experation_bad_type(self):\n table.partition_expiration = \"NEVER\"\n \n def test_partition_expiration_w_integer(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -581,7 +581,7 @@ def test_partition_expiration_w_integer(self):\n self.assertEqual(table.partition_expiration, 100)\n \n def test_partition_expiration_w_none(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -600,7 +600,7 @@ def test_partition_expiration_w_none(self):\n self.assertEqual(table.partition_expiration, None)\n \n def test_partition_expiration_w_none_no_partition_set(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n RESOURCE = self._makeResource()\n conn = _Connection(RESOURCE)\n client = _Client(project=self.PROJECT, connection=conn)\n@@ -615,7 +615,7 @@ def test_partition_expiration_w_none_no_partition_set(self):\n self.assertEqual(table.partition_expiration, None)\n \n def test_list_partitions(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n conn = _Connection()\n client = _Client(project=self.PROJECT, connection=conn)\n client._query_results = [(20160804, None), (20160805, None)]\n@@ -628,9 +628,9 @@ def test_list_partitions(self):\n \n def test_create_w_alternate_client(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _millis\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _millis\n+ from google.cloud.bigquery.table import SchemaField\n \n PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME)\n DESCRIPTION = 'DESCRIPTION'\n@@ -680,7 +680,7 @@ def test_create_w_alternate_client(self):\n def test_create_w_missing_output_properties(self):\n # In the wild, the resource returned from 'dataset.create' sometimes\n # lacks 'creationTime' / 'lastModifiedTime'\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables' % (self.PROJECT, self.DS_NAME)\n RESOURCE = self._makeResource()\n del RESOURCE['creationTime']\n@@ -825,9 +825,9 @@ def test_patch_w_bound_client(self):\n \n def test_patch_w_alternate_client(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _millis\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _millis\n+ from google.cloud.bigquery.table import SchemaField\n \n PATH = 'projects/%s/datasets/%s/tables/%s' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n@@ -894,7 +894,7 @@ def test_patch_w_schema_None(self):\n self._verifyResourceProperties(table, RESOURCE)\n \n def test_update_w_bound_client(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n DESCRIPTION = 'DESCRIPTION'\n@@ -934,8 +934,8 @@ def test_update_w_bound_client(self):\n \n def test_update_w_alternate_client(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _millis\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _millis\n \n PATH = 'projects/%s/datasets/%s/tables/%s' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n@@ -1015,8 +1015,8 @@ def test_delete_w_alternate_client(self):\n \n def test_fetch_data_w_bound_client(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud._helpers import UTC\n+ from google.cloud.bigquery.table import SchemaField\n \n PATH = 'projects/%s/datasets/%s/tables/%s/data' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n@@ -1084,7 +1084,7 @@ def _bigquery_timestamp_float_repr(ts_float):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_fetch_data_w_alternate_client(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/data' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n MAX = 10\n@@ -1150,7 +1150,7 @@ def test_fetch_data_w_alternate_client(self):\n {'maxResults': MAX, 'pageToken': TOKEN})\n \n def test_fetch_data_w_repeated_fields(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/data' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n ROWS = 1234\n@@ -1192,7 +1192,7 @@ def test_fetch_data_w_repeated_fields(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_fetch_data_w_record_schema(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/data' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n ROWS = 1234\n@@ -1250,9 +1250,9 @@ def test_fetch_data_w_record_schema(self):\n \n def test_insert_data_w_bound_client(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _microseconds_from_datetime\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _microseconds_from_datetime\n+ from google.cloud.bigquery.table import SchemaField\n \n WHEN_TS = 1437767599.006\n WHEN = datetime.datetime.utcfromtimestamp(WHEN_TS).replace(\n@@ -1296,7 +1296,7 @@ def _row_data(row):\n self.assertEqual(req['data'], SENT)\n \n def test_insert_data_w_alternate_client(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n RESPONSE = {\n@@ -1360,7 +1360,7 @@ def _row_data(row):\n self.assertEqual(req['data'], SENT)\n \n def test_insert_data_w_repeated_fields(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n conn = _Connection({})\n@@ -1395,7 +1395,7 @@ def _row_data(row):\n self.assertEqual(req['data'], SENT)\n \n def test_insert_data_w_record_schema(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n PATH = 'projects/%s/datasets/%s/tables/%s/insertAll' % (\n self.PROJECT, self.DS_NAME, self.TABLE_NAME)\n conn = _Connection({})\n@@ -1462,9 +1462,9 @@ def _upload_from_file_helper(self, **kw):\n import csv\n import datetime\n from six.moves.http_client import OK\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n \n WHEN_TS = 1437767599.006\n WHEN = datetime.datetime.utcfromtimestamp(WHEN_TS).replace(\n@@ -1514,7 +1514,7 @@ def test_upload_from_file_w_bound_client_multipart(self):\n import json\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n- from gcloud._helpers import _to_bytes\n+ from google.cloud._helpers import _to_bytes\n \n requested, PATH, BODY = self._upload_from_file_helper()\n parse_chunk = _email_chunk_parser()\n@@ -1571,7 +1571,7 @@ def test_upload_from_file_w_explicit_client_resumable(self):\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _Monkey\n- from gcloud.bigquery import table as MUT\n+ from google.cloud.bigquery import table as MUT\n \n UPLOAD_PATH = 'https://example.com/upload/test'\n initial_response = {'status': OK, 'location': UPLOAD_PATH}\n@@ -1656,7 +1656,7 @@ class _UploadConfig(object):\n class Test_parse_schema_resource(unittest.TestCase, _SchemaBase):\n \n def _callFUT(self, resource):\n- from gcloud.bigquery.table import _parse_schema_resource\n+ from google.cloud.bigquery.table import _parse_schema_resource\n return _parse_schema_resource(resource)\n \n def _makeResource(self):\n@@ -1700,11 +1700,11 @@ def test__parse_schema_resource_fields_without_mode(self):\n class Test_build_schema_resource(unittest.TestCase, _SchemaBase):\n \n def _callFUT(self, resource):\n- from gcloud.bigquery.table import _build_schema_resource\n+ from google.cloud.bigquery.table import _build_schema_resource\n return _build_schema_resource(resource)\n \n def test_defaults(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n full_name = SchemaField('full_name', 'STRING', mode='REQUIRED')\n age = SchemaField('age', 'INTEGER', mode='REQUIRED')\n resource = self._callFUT([full_name, age])\n@@ -1719,7 +1719,7 @@ def test_defaults(self):\n 'mode': 'REQUIRED'})\n \n def test_w_description(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n DESCRIPTION = 'DESCRIPTION'\n full_name = SchemaField('full_name', 'STRING', mode='REQUIRED',\n description=DESCRIPTION)\n@@ -1737,7 +1737,7 @@ def test_w_description(self):\n 'mode': 'REQUIRED'})\n \n def test_w_subfields(self):\n- from gcloud.bigquery.table import SchemaField\n+ from google.cloud.bigquery.table import SchemaField\n full_name = SchemaField('full_name', 'STRING', mode='REQUIRED')\n ph_type = SchemaField('type', 'STRING', 'REQUIRED')\n ph_num = SchemaField('number', 'STRING', 'REQUIRED')\n@@ -1836,7 +1836,7 @@ def __init__(self, *responses):\n self.http = _HTTP(*responses)\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/bigtable/test_client.py b/unit_tests/bigtable/test_client.py\n--- a/unit_tests/bigtable/test_client.py\n+++ b/unit_tests/bigtable/test_client.py\n@@ -19,12 +19,12 @@\n class Test__make_data_stub(unittest.TestCase):\n \n def _callFUT(self, client):\n- from gcloud.bigtable.client import _make_data_stub\n+ from google.cloud.bigtable.client import _make_data_stub\n return _make_data_stub(client)\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n credentials = _Credentials()\n user_agent = 'you-sir-age-int'\n@@ -55,12 +55,12 @@ def mock_make_stub(*args):\n class Test__make_instance_stub(unittest.TestCase):\n \n def _callFUT(self, client):\n- from gcloud.bigtable.client import _make_instance_stub\n+ from google.cloud.bigtable.client import _make_instance_stub\n return _make_instance_stub(client)\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n credentials = _Credentials()\n user_agent = 'you-sir-age-int'\n@@ -91,12 +91,12 @@ def mock_make_stub(*args):\n class Test__make_operations_stub(unittest.TestCase):\n \n def _callFUT(self, client):\n- from gcloud.bigtable.client import _make_operations_stub\n+ from google.cloud.bigtable.client import _make_operations_stub\n return _make_operations_stub(client)\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n credentials = _Credentials()\n user_agent = 'you-sir-age-int'\n@@ -127,12 +127,12 @@ def mock_make_stub(*args):\n class Test__make_table_stub(unittest.TestCase):\n \n def _callFUT(self, client):\n- from gcloud.bigtable.client import _make_table_stub\n+ from google.cloud.bigtable.client import _make_table_stub\n return _make_table_stub(client)\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n credentials = _Credentials()\n user_agent = 'you-sir-age-int'\n@@ -168,7 +168,7 @@ class TestClient(unittest.TestCase):\n USER_AGENT = 'you-sir-age-int'\n \n def _getTargetClass(self):\n- from gcloud.bigtable.client import Client\n+ from google.cloud.bigtable.client import Client\n return Client\n \n def _makeOne(self, *args, **kwargs):\n@@ -176,7 +176,7 @@ def _makeOne(self, *args, **kwargs):\n \n def _makeOneWithMocks(self, *args, **kwargs):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n mock_make_data_stub = _MakeStubMock()\n mock_make_instance_stub = _MakeStubMock()\n@@ -192,7 +192,7 @@ def _constructor_test_helper(self, expected_scopes, creds,\n read_only=False, admin=False,\n user_agent=None, expected_creds=None):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n user_agent = user_agent or MUT.DEFAULT_USER_AGENT\n \n@@ -241,14 +241,14 @@ def _constructor_test_helper(self, expected_scopes, creds,\n self.assertIsNone(client._table_stub_internal)\n \n def test_constructor_default_scopes(self):\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n expected_scopes = [MUT.DATA_SCOPE]\n creds = _Credentials()\n self._constructor_test_helper(expected_scopes, creds)\n \n def test_constructor_custom_user_agent(self):\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n CUSTOM_USER_AGENT = 'custom-application'\n expected_scopes = [MUT.DATA_SCOPE]\n@@ -257,14 +257,14 @@ def test_constructor_custom_user_agent(self):\n user_agent=CUSTOM_USER_AGENT)\n \n def test_constructor_with_admin(self):\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n expected_scopes = [MUT.DATA_SCOPE, MUT.ADMIN_SCOPE]\n creds = _Credentials()\n self._constructor_test_helper(expected_scopes, creds, admin=True)\n \n def test_constructor_with_read_only(self):\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n expected_scopes = [MUT.READ_ONLY_SCOPE]\n creds = _Credentials()\n@@ -278,7 +278,7 @@ def test_constructor_both_admin_and_read_only(self):\n \n def test_constructor_implicit_credentials(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n creds = _Credentials()\n expected_scopes = [MUT.DATA_SCOPE]\n@@ -297,7 +297,7 @@ def test_constructor_credentials_wo_create_scoped(self):\n \n def _copy_test_helper(self, read_only=False, admin=False):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import client as MUT\n+ from google.cloud.bigtable import client as MUT\n \n credentials = _Credentials('value')\n client = self._makeOneWithMocks(\n@@ -407,9 +407,10 @@ def test_table_stub_non_admin_failure(self):\n getattr(client, '_table_stub')\n \n def test_instance_factory_defaults(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n- from gcloud.bigtable.instance import Instance\n- from gcloud.bigtable.instance import _EXISTING_INSTANCE_LOCATION_ID\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.instance import Instance\n+ from google.cloud.bigtable.instance import (\n+ _EXISTING_INSTANCE_LOCATION_ID)\n \n PROJECT = 'PROJECT'\n INSTANCE_ID = 'instance-id'\n@@ -429,7 +430,7 @@ def test_instance_factory_defaults(self):\n self.assertTrue(instance._client is client)\n \n def test_instance_factory_w_explicit_serve_nodes(self):\n- from gcloud.bigtable.instance import Instance\n+ from google.cloud.bigtable.instance import Instance\n \n PROJECT = 'PROJECT'\n INSTANCE_ID = 'instance-id'\n@@ -452,9 +453,9 @@ def test_instance_factory_w_explicit_serve_nodes(self):\n self.assertTrue(instance._client is client)\n \n def test_list_instances(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \ndiff --git a/unit_tests/bigtable/test_cluster.py b/unit_tests/bigtable/test_cluster.py\n--- a/unit_tests/bigtable/test_cluster.py\n+++ b/unit_tests/bigtable/test_cluster.py\n@@ -26,14 +26,14 @@ class TestCluster(unittest.TestCase):\n '/clusters/' + CLUSTER_ID)\n \n def _getTargetClass(self):\n- from gcloud.bigtable.cluster import Cluster\n+ from google.cloud.bigtable.cluster import Cluster\n return Cluster\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_constructor_defaults(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n \n@@ -70,7 +70,7 @@ def test_copy(self):\n self.assertEqual(cluster, new_cluster)\n \n def test__update_from_pb_success(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n \n SERVE_NODES = 8\n cluster_pb = _ClusterPB(\n@@ -85,7 +85,7 @@ def test__update_from_pb_success(self):\n self.assertEqual(cluster.serve_nodes, SERVE_NODES)\n \n def test__update_from_pb_no_serve_nodes(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n \n cluster_pb = _ClusterPB()\n client = _Client(self.PROJECT)\n@@ -188,7 +188,7 @@ def test___ne__(self):\n \n def test_reload(self):\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n \n SERVE_NODES = 31\n LOCATION = 'LOCATION'\n@@ -229,8 +229,8 @@ def test_reload(self):\n \n def test_create(self):\n from google.longrunning import operations_pb2\n- from gcloud.operation import Operation\n- from gcloud.bigtable._generated import (\n+ from google.cloud.operation import Operation\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -274,15 +274,15 @@ def test_create(self):\n def test_update(self):\n import datetime\n from google.longrunning import operations_pb2\n- from gcloud.operation import Operation\n+ from google.cloud.operation import Operation\n from google.protobuf.any_pb2 import Any\n- from gcloud._helpers import _datetime_to_pb_timestamp\n- from gcloud.bigtable._generated import (\n+ from google.cloud._helpers import _datetime_to_pb_timestamp\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable.cluster import _UPDATE_CLUSTER_METADATA_URL\n+ from google.cloud.bigtable.cluster import _UPDATE_CLUSTER_METADATA_URL\n \n NOW = datetime.datetime.utcnow()\n NOW_PB = _datetime_to_pb_timestamp(NOW)\n@@ -372,11 +372,11 @@ def test_delete(self):\n class Test__prepare_create_request(unittest.TestCase):\n \n def _callFUT(self, cluster):\n- from gcloud.bigtable.cluster import _prepare_create_request\n+ from google.cloud.bigtable.cluster import _prepare_create_request\n return _prepare_create_request(cluster)\n \n def test_it(self):\n- from gcloud.bigtable.cluster import Cluster\n+ from google.cloud.bigtable.cluster import Cluster\n \n PROJECT = 'PROJECT'\n INSTANCE_ID = 'instance-id'\n@@ -396,19 +396,19 @@ def test_it(self):\n \n \n def _ClusterPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as instance_v2_pb2)\n return instance_v2_pb2.Cluster(*args, **kw)\n \n \n def _DeleteClusterRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n return messages_v2_pb2.DeleteClusterRequest(*args, **kw)\n \n \n def _GetClusterRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n return messages_v2_pb2.GetClusterRequest(*args, **kw)\n \ndiff --git a/unit_tests/bigtable/test_column_family.py b/unit_tests/bigtable/test_column_family.py\n--- a/unit_tests/bigtable/test_column_family.py\n+++ b/unit_tests/bigtable/test_column_family.py\n@@ -19,7 +19,8 @@\n class Test__timedelta_to_duration_pb(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.bigtable.column_family import _timedelta_to_duration_pb\n+ from google.cloud.bigtable.column_family import (\n+ _timedelta_to_duration_pb)\n return _timedelta_to_duration_pb(*args, **kwargs)\n \n def test_it(self):\n@@ -64,7 +65,8 @@ def test_with_negative_seconds(self):\n class Test__duration_pb_to_timedelta(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.bigtable.column_family import _duration_pb_to_timedelta\n+ from google.cloud.bigtable.column_family import (\n+ _duration_pb_to_timedelta)\n return _duration_pb_to_timedelta(*args, **kwargs)\n \n def test_it(self):\n@@ -84,7 +86,7 @@ def test_it(self):\n class TestMaxVersionsGCRule(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n return MaxVersionsGCRule\n \n def _makeOne(self, *args, **kwargs):\n@@ -117,7 +119,7 @@ def test_to_pb(self):\n class TestMaxAgeGCRule(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n return MaxAgeGCRule\n \n def _makeOne(self, *args, **kwargs):\n@@ -156,7 +158,7 @@ def test_to_pb(self):\n class TestGCRuleUnion(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.column_family import GCRuleUnion\n+ from google.cloud.bigtable.column_family import GCRuleUnion\n return GCRuleUnion\n \n def _makeOne(self, *args, **kwargs):\n@@ -189,8 +191,8 @@ def test___ne__same_value(self):\n def test_to_pb(self):\n import datetime\n from google.protobuf import duration_pb2\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n max_num_versions = 42\n rule1 = MaxVersionsGCRule(max_num_versions)\n@@ -211,8 +213,8 @@ def test_to_pb(self):\n def test_to_pb_nested(self):\n import datetime\n from google.protobuf import duration_pb2\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n max_num_versions1 = 42\n rule1 = MaxVersionsGCRule(max_num_versions1)\n@@ -242,7 +244,7 @@ def test_to_pb_nested(self):\n class TestGCRuleIntersection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.column_family import GCRuleIntersection\n+ from google.cloud.bigtable.column_family import GCRuleIntersection\n return GCRuleIntersection\n \n def _makeOne(self, *args, **kwargs):\n@@ -275,8 +277,8 @@ def test___ne__same_value(self):\n def test_to_pb(self):\n import datetime\n from google.protobuf import duration_pb2\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n max_num_versions = 42\n rule1 = MaxVersionsGCRule(max_num_versions)\n@@ -298,8 +300,8 @@ def test_to_pb(self):\n def test_to_pb_nested(self):\n import datetime\n from google.protobuf import duration_pb2\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n max_num_versions1 = 42\n rule1 = MaxVersionsGCRule(max_num_versions1)\n@@ -331,7 +333,7 @@ def test_to_pb_nested(self):\n class TestColumnFamily(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.column_family import ColumnFamily\n+ from google.cloud.bigtable.column_family import ColumnFamily\n return ColumnFamily\n \n def _makeOne(self, *args, **kwargs):\n@@ -395,7 +397,7 @@ def test_to_pb_no_rules(self):\n self.assertEqual(pb_val, expected)\n \n def test_to_pb_with_rule(self):\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n gc_rule = MaxVersionsGCRule(1)\n column_family = self._makeOne('column_family_id', None,\n@@ -405,7 +407,7 @@ def test_to_pb_with_rule(self):\n self.assertEqual(pb_val, expected)\n \n def _create_test_helper(self, gc_rule=None):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -458,13 +460,13 @@ def test_create(self):\n self._create_test_helper(gc_rule=None)\n \n def test_create_with_gc_rule(self):\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n gc_rule = MaxVersionsGCRule(1337)\n self._create_test_helper(gc_rule=gc_rule)\n \n def _update_test_helper(self, gc_rule=None):\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n \n project_id = 'project-id'\n@@ -516,13 +518,13 @@ def test_update(self):\n self._update_test_helper(gc_rule=None)\n \n def test_update_with_gc_rule(self):\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n gc_rule = MaxVersionsGCRule(1337)\n self._update_test_helper(gc_rule=gc_rule)\n \n def test_delete(self):\n from google.protobuf import empty_pb2\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -569,7 +571,7 @@ def test_delete(self):\n class Test__gc_rule_from_pb(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.bigtable.column_family import _gc_rule_from_pb\n+ from google.cloud.bigtable.column_family import _gc_rule_from_pb\n return _gc_rule_from_pb(*args, **kwargs)\n \n def test_empty(self):\n@@ -578,7 +580,7 @@ def test_empty(self):\n self.assertEqual(self._callFUT(gc_rule_pb), None)\n \n def test_max_num_versions(self):\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n orig_rule = MaxVersionsGCRule(1)\n gc_rule_pb = orig_rule.to_pb()\n@@ -588,7 +590,7 @@ def test_max_num_versions(self):\n \n def test_max_age(self):\n import datetime\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n \n orig_rule = MaxAgeGCRule(datetime.timedelta(seconds=1))\n gc_rule_pb = orig_rule.to_pb()\n@@ -598,9 +600,9 @@ def test_max_age(self):\n \n def test_union(self):\n import datetime\n- from gcloud.bigtable.column_family import GCRuleUnion\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import GCRuleUnion\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n rule1 = MaxVersionsGCRule(1)\n rule2 = MaxAgeGCRule(datetime.timedelta(seconds=1))\n@@ -612,9 +614,9 @@ def test_union(self):\n \n def test_intersection(self):\n import datetime\n- from gcloud.bigtable.column_family import GCRuleIntersection\n- from gcloud.bigtable.column_family import MaxAgeGCRule\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import GCRuleIntersection\n+ from google.cloud.bigtable.column_family import MaxAgeGCRule\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n rule1 = MaxVersionsGCRule(1)\n rule2 = MaxAgeGCRule(datetime.timedelta(seconds=1))\n@@ -640,25 +642,25 @@ def WhichOneof(cls, name):\n \n \n def _GcRulePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.GcRule(*args, **kw)\n \n \n def _GcRuleIntersectionPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.GcRule.Intersection(*args, **kw)\n \n \n def _GcRuleUnionPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.GcRule.Union(*args, **kw)\n \n \n def _ColumnFamilyPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.ColumnFamily(*args, **kw)\n \ndiff --git a/unit_tests/bigtable/test_instance.py b/unit_tests/bigtable/test_instance.py\n--- a/unit_tests/bigtable/test_instance.py\n+++ b/unit_tests/bigtable/test_instance.py\n@@ -31,14 +31,14 @@ class TestInstance(unittest.TestCase):\n TABLE_NAME = INSTANCE_NAME + '/tables/' + TABLE_ID\n \n def _getTargetClass(self):\n- from gcloud.bigtable.instance import Instance\n+ from google.cloud.bigtable.instance import Instance\n return Instance\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_constructor_defaults(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n \n client = object()\n instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID)\n@@ -74,7 +74,7 @@ def test_copy(self):\n self.assertEqual(instance, new_instance)\n \n def test_table_factory(self):\n- from gcloud.bigtable.table import Table\n+ from google.cloud.bigtable.table import Table\n \n instance = self._makeOne(self.INSTANCE_ID, None, self.LOCATION_ID)\n \n@@ -84,7 +84,7 @@ def test_table_factory(self):\n self.assertEqual(table._instance, instance)\n \n def test__update_from_pb_success(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n \n display_name = 'display_name'\n@@ -98,7 +98,7 @@ def test__update_from_pb_success(self):\n self.assertEqual(instance.display_name, display_name)\n \n def test__update_from_pb_no_display_name(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n \n instance_pb = data_v2_pb2.Instance()\n@@ -109,8 +109,9 @@ def test__update_from_pb_no_display_name(self):\n self.assertEqual(instance.display_name, None)\n \n def test_from_pb_success(self):\n- from gcloud.bigtable.instance import _EXISTING_INSTANCE_LOCATION_ID\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable.instance import (\n+ _EXISTING_INSTANCE_LOCATION_ID)\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n \n client = _Client(project=self.PROJECT)\n@@ -129,7 +130,7 @@ def test_from_pb_success(self):\n _EXISTING_INSTANCE_LOCATION_ID)\n \n def test_from_pb_bad_instance_name(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n \n instance_name = 'INCORRECT_FORMAT'\n@@ -140,7 +141,7 @@ def test_from_pb_bad_instance_name(self):\n klass.from_pb(instance_pb, None)\n \n def test_from_pb_project_mistmatch(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n \n ALT_PROJECT = 'ALT_PROJECT'\n@@ -185,9 +186,9 @@ def test___ne__(self):\n self.assertNotEqual(instance1, instance2)\n \n def test_reload(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -229,13 +230,14 @@ def test_create(self):\n import datetime\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n- from gcloud._helpers import _datetime_to_pb_timestamp\n+ from google.cloud._helpers import _datetime_to_pb_timestamp\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.operation import Operation\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n- from gcloud.bigtable.instance import _CREATE_INSTANCE_METADATA_URL\n+ from google.cloud.operation import Operation\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable.instance import (\n+ _CREATE_INSTANCE_METADATA_URL)\n \n NOW = datetime.datetime.utcnow()\n NOW_PB = _datetime_to_pb_timestamp(NOW)\n@@ -283,10 +285,10 @@ def test_create(self):\n \n def test_create_w_explicit_serve_nodes(self):\n from google.longrunning import operations_pb2\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.operation import Operation\n+ from google.cloud.operation import Operation\n \n SERVE_NODES = 5\n \n@@ -322,7 +324,7 @@ def test_create_w_explicit_serve_nodes(self):\n self.assertEqual(kwargs, {})\n \n def test_update(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -357,7 +359,7 @@ def test_update(self):\n \n def test_delete(self):\n from google.protobuf import empty_pb2\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -388,9 +390,9 @@ def test_delete(self):\n )])\n \n def test_list_clusters(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as instance_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -445,9 +447,9 @@ def test_list_clusters(self):\n )])\n \n def _list_tables_helper(self, table_name=None):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_messages_v1_pb2)\n from unit_tests.bigtable._testing import _FakeStub\n \n@@ -511,16 +513,16 @@ class Test__prepare_create_request(unittest.TestCase):\n CLUSTER_NAME = INSTANCE_NAME + '/clusters/' + INSTANCE_ID\n \n def _callFUT(self, instance, **kw):\n- from gcloud.bigtable.instance import _prepare_create_request\n+ from google.cloud.bigtable.instance import _prepare_create_request\n return _prepare_create_request(instance, **kw)\n \n def test_w_defaults(self):\n- from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable.cluster import DEFAULT_SERVE_NODES\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb)\n- from gcloud.bigtable.instance import Instance\n+ from google.cloud.bigtable.instance import Instance\n \n client = _Client(self.PROJECT)\n \n@@ -542,11 +544,11 @@ def test_w_defaults(self):\n self.assertEqual(cluster.serve_nodes, DEFAULT_SERVE_NODES)\n \n def test_w_explicit_serve_nodes(self):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n instance_pb2 as data_v2_pb2)\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_instance_admin_pb2 as messages_v2_pb)\n- from gcloud.bigtable.instance import Instance\n+ from google.cloud.bigtable.instance import Instance\n DISPLAY_NAME = u'DISPLAY_NAME'\n SERVE_NODES = 5\n client = _Client(self.PROJECT)\ndiff --git a/unit_tests/bigtable/test_row.py b/unit_tests/bigtable/test_row.py\n--- a/unit_tests/bigtable/test_row.py\n+++ b/unit_tests/bigtable/test_row.py\n@@ -19,7 +19,7 @@\n class Test_SetDeleteRow(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row import _SetDeleteRow\n+ from google.cloud.bigtable.row import _SetDeleteRow\n return _SetDeleteRow\n \n def _makeOne(self, *args, **kwargs):\n@@ -34,7 +34,7 @@ def test__get_mutations_virtual(self):\n class TestDirectRow(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row import DirectRow\n+ from google.cloud.bigtable.row import DirectRow\n return DirectRow\n \n def _makeOne(self, *args, **kwargs):\n@@ -123,7 +123,7 @@ def test_set_cell_with_non_bytes_value(self):\n \n def test_set_cell_with_non_null_timestamp(self):\n import datetime\n- from gcloud._helpers import _EPOCH\n+ from google.cloud._helpers import _EPOCH\n \n microseconds = 898294371\n millis_granularity = microseconds - (microseconds % 1000)\n@@ -243,8 +243,8 @@ def test_delete_cells_no_time_range(self):\n \n def test_delete_cells_with_time_range(self):\n import datetime\n- from gcloud._helpers import _EPOCH\n- from gcloud.bigtable.row_filters import TimestampRange\n+ from google.cloud._helpers import _EPOCH\n+ from google.cloud.bigtable.row_filters import TimestampRange\n \n microseconds = 30871000 # Makes sure already milliseconds granularity\n start = _EPOCH + datetime.timedelta(microseconds=microseconds)\n@@ -344,7 +344,7 @@ def test_commit(self):\n \n def test_commit_too_many_mutations(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import row as MUT\n+ from google.cloud.bigtable import row as MUT\n \n row_key = b'row_key'\n table = object()\n@@ -377,7 +377,7 @@ def test_commit_no_mutations(self):\n class TestConditionalRow(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row import ConditionalRow\n+ from google.cloud.bigtable.row import ConditionalRow\n return ConditionalRow\n \n def _makeOne(self, *args, **kwargs):\n@@ -408,7 +408,7 @@ def test__get_mutations(self):\n \n def test_commit(self):\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n \n row_key = b'row_key'\n table_name = 'projects/more-stuff'\n@@ -482,7 +482,7 @@ def test_commit(self):\n \n def test_commit_too_many_mutations(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import row as MUT\n+ from google.cloud.bigtable import row as MUT\n \n row_key = b'row_key'\n table = object()\n@@ -518,7 +518,7 @@ def test_commit_no_mutations(self):\n class TestAppendRow(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row import AppendRow\n+ from google.cloud.bigtable.row import AppendRow\n return AppendRow\n \n def _makeOne(self, *args, **kwargs):\n@@ -574,7 +574,7 @@ def test_increment_cell_value(self):\n def test_commit(self):\n from unit_tests._testing import _Monkey\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable import row as MUT\n+ from google.cloud.bigtable import row as MUT\n \n row_key = b'row_key'\n table_name = 'projects/more-stuff'\n@@ -647,7 +647,7 @@ def test_commit_no_rules(self):\n \n def test_commit_too_many_mutations(self):\n from unit_tests._testing import _Monkey\n- from gcloud.bigtable import row as MUT\n+ from google.cloud.bigtable import row as MUT\n \n row_key = b'row_key'\n table = object()\n@@ -662,11 +662,11 @@ def test_commit_too_many_mutations(self):\n class Test__parse_rmw_row_response(unittest.TestCase):\n \n def _callFUT(self, row_response):\n- from gcloud.bigtable.row import _parse_rmw_row_response\n+ from google.cloud.bigtable.row import _parse_rmw_row_response\n return _parse_rmw_row_response(row_response)\n \n def test_it(self):\n- from gcloud._helpers import _datetime_from_microseconds\n+ from google.cloud._helpers import _datetime_from_microseconds\n col_fam1 = u'col-fam-id'\n col_fam2 = u'col-fam-id2'\n col_name1 = b'col-name1'\n@@ -747,11 +747,11 @@ def test_it(self):\n class Test__parse_family_pb(unittest.TestCase):\n \n def _callFUT(self, family_pb):\n- from gcloud.bigtable.row import _parse_family_pb\n+ from google.cloud.bigtable.row import _parse_family_pb\n return _parse_family_pb(family_pb)\n \n def test_it(self):\n- from gcloud._helpers import _datetime_from_microseconds\n+ from google.cloud._helpers import _datetime_from_microseconds\n col_fam1 = u'col-fam-id'\n col_name1 = b'col-name1'\n col_name2 = b'col-name2'\n@@ -802,91 +802,91 @@ def test_it(self):\n \n \n def _CheckAndMutateRowRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.CheckAndMutateRowRequest(*args, **kw)\n \n \n def _CheckAndMutateRowResponsePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.CheckAndMutateRowResponse(*args, **kw)\n \n \n def _MutateRowRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.MutateRowRequest(*args, **kw)\n \n \n def _ReadModifyWriteRowRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.ReadModifyWriteRowRequest(*args, **kw)\n \n \n def _ReadModifyWriteRowResponsePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.ReadModifyWriteRowResponse(*args, **kw)\n \n \n def _CellPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Cell(*args, **kw)\n \n \n def _ColumnPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Column(*args, **kw)\n \n \n def _FamilyPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Family(*args, **kw)\n \n \n def _MutationPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Mutation(*args, **kw)\n \n \n def _MutationSetCellPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Mutation.SetCell(*args, **kw)\n \n \n def _MutationDeleteFromColumnPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Mutation.DeleteFromColumn(*args, **kw)\n \n \n def _MutationDeleteFromFamilyPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Mutation.DeleteFromFamily(*args, **kw)\n \n \n def _MutationDeleteFromRowPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Mutation.DeleteFromRow(*args, **kw)\n \n \n def _RowPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.Row(*args, **kw)\n \n \n def _ReadModifyWriteRulePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.ReadModifyWriteRule(*args, **kw)\n \ndiff --git a/unit_tests/bigtable/test_row_data.py b/unit_tests/bigtable/test_row_data.py\n--- a/unit_tests/bigtable/test_row_data.py\n+++ b/unit_tests/bigtable/test_row_data.py\n@@ -19,7 +19,7 @@\n class TestCell(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_data import Cell\n+ from google.cloud.bigtable.row_data import Cell\n return Cell\n \n def _makeOne(self, *args, **kwargs):\n@@ -27,8 +27,8 @@ def _makeOne(self, *args, **kwargs):\n \n def _from_pb_test_helper(self, labels=None):\n import datetime\n- from gcloud._helpers import _EPOCH\n- from gcloud.bigtable._generated import (\n+ from google.cloud._helpers import _EPOCH\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n \n timestamp_micros = 18738724000 # Make sure millis granularity\n@@ -94,7 +94,7 @@ def test___ne__(self):\n class TestPartialRowData(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_data import PartialRowData\n+ from google.cloud.bigtable.row_data import PartialRowData\n return PartialRowData\n \n def _makeOne(self, *args, **kwargs):\n@@ -185,7 +185,7 @@ def test_row_key_getter(self):\n class TestPartialRowsData(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_data import PartialRowsData\n+ from google.cloud.bigtable.row_data import PartialRowsData\n return PartialRowsData\n \n def _getDoNothingClass(self):\n@@ -383,7 +383,7 @@ def test__save_row_no_cell(self):\n self.assertTrue(prd._rows[ROW_KEY] is row)\n \n def test_invalid_last_scanned_row_key_on_start(self):\n- from gcloud.bigtable.row_data import InvalidReadRowsResponse\n+ from google.cloud.bigtable.row_data import InvalidReadRowsResponse\n response = _ReadRowsResponseV2(chunks=(), last_scanned_row_key='ABC')\n iterator = _MockCancellableIterator(response)\n prd = self._makeOne(iterator)\n@@ -400,7 +400,7 @@ def test_valid_last_scanned_row_key_on_start(self):\n self.assertEqual(prd._last_scanned_row_key, 'AFTER')\n \n def test_invalid_empty_chunk(self):\n- from gcloud.bigtable.row_data import InvalidChunk\n+ from google.cloud.bigtable.row_data import InvalidChunk\n chunks = _generate_cell_chunks([''])\n response = _ReadRowsResponseV2(chunks)\n iterator = _MockCancellableIterator(response)\n@@ -409,7 +409,7 @@ def test_invalid_empty_chunk(self):\n prd.consume_next()\n \n def test_invalid_empty_second_chunk(self):\n- from gcloud.bigtable.row_data import InvalidChunk\n+ from google.cloud.bigtable.row_data import InvalidChunk\n chunks = _generate_cell_chunks(['', ''])\n first = chunks[0]\n first.row_key = b'RK'\n@@ -427,7 +427,7 @@ class TestPartialRowsData_JSON_acceptance_tests(unittest.TestCase):\n _json_tests = None\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_data import PartialRowsData\n+ from google.cloud.bigtable.row_data import PartialRowsData\n return PartialRowsData\n \n def _makeOne(self, *args, **kwargs):\n@@ -447,7 +447,7 @@ def _load_json_test(self, test_name):\n # JSON Error cases: invalid chunks\n \n def _fail_during_consume(self, testcase_name):\n- from gcloud.bigtable.row_data import InvalidChunk\n+ from google.cloud.bigtable.row_data import InvalidChunk\n chunks, results = self._load_json_test(testcase_name)\n response = _ReadRowsResponseV2(chunks)\n iterator = _MockCancellableIterator(response)\n@@ -637,8 +637,8 @@ def test_empty_cell_chunk(self):\n def _flatten_cells(prd):\n # Match results format from JSON testcases.\n # Doesn't handle error cases.\n- from gcloud._helpers import _bytes_to_unicode\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import _bytes_to_unicode\n+ from google.cloud._helpers import _microseconds_from_datetime\n for row_key, row in prd.rows.items():\n for family_name, family in row.cells.items():\n for qualifier, column in family.items():\n@@ -698,7 +698,7 @@ def __init__(self, chunks, last_scanned_row_key=''):\n \n def _generate_cell_chunks(chunk_text_pbs):\n from google.protobuf.text_format import Merge\n- from gcloud.bigtable._generated.bigtable_pb2 import ReadRowsResponse\n+ from google.cloud.bigtable._generated.bigtable_pb2 import ReadRowsResponse\n \n chunks = []\n \ndiff --git a/unit_tests/bigtable/test_row_filters.py b/unit_tests/bigtable/test_row_filters.py\n--- a/unit_tests/bigtable/test_row_filters.py\n+++ b/unit_tests/bigtable/test_row_filters.py\n@@ -19,7 +19,7 @@\n class Test_BoolFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import _BoolFilter\n+ from google.cloud.bigtable.row_filters import _BoolFilter\n return _BoolFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -53,7 +53,7 @@ def test___ne__same_value(self):\n class TestSinkFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import SinkFilter\n+ from google.cloud.bigtable.row_filters import SinkFilter\n return SinkFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -70,7 +70,7 @@ def test_to_pb(self):\n class TestPassAllFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import PassAllFilter\n+ from google.cloud.bigtable.row_filters import PassAllFilter\n return PassAllFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -87,7 +87,7 @@ def test_to_pb(self):\n class TestBlockAllFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import BlockAllFilter\n+ from google.cloud.bigtable.row_filters import BlockAllFilter\n return BlockAllFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -104,7 +104,7 @@ def test_to_pb(self):\n class Test_RegexFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import _RegexFilter\n+ from google.cloud.bigtable.row_filters import _RegexFilter\n return _RegexFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -143,7 +143,7 @@ def test___ne__same_value(self):\n class TestRowKeyRegexFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import RowKeyRegexFilter\n+ from google.cloud.bigtable.row_filters import RowKeyRegexFilter\n return RowKeyRegexFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -160,7 +160,7 @@ def test_to_pb(self):\n class TestRowSampleFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n return RowSampleFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -194,7 +194,7 @@ def test_to_pb(self):\n class TestFamilyNameRegexFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import FamilyNameRegexFilter\n+ from google.cloud.bigtable.row_filters import FamilyNameRegexFilter\n return FamilyNameRegexFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -211,7 +211,8 @@ def test_to_pb(self):\n class TestColumnQualifierRegexFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ColumnQualifierRegexFilter\n+ from google.cloud.bigtable.row_filters import (\n+ ColumnQualifierRegexFilter)\n return ColumnQualifierRegexFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -229,7 +230,7 @@ def test_to_pb(self):\n class TestTimestampRange(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import TimestampRange\n+ from google.cloud.bigtable.row_filters import TimestampRange\n return TimestampRange\n \n def _makeOne(self, *args, **kwargs):\n@@ -266,7 +267,7 @@ def test___ne__same_value(self):\n \n def _to_pb_helper(self, start_micros=None, end_micros=None):\n import datetime\n- from gcloud._helpers import _EPOCH\n+ from google.cloud._helpers import _EPOCH\n pb_kwargs = {}\n \n start = None\n@@ -303,7 +304,7 @@ def test_to_pb_end_only(self):\n class TestTimestampRangeFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import TimestampRangeFilter\n+ from google.cloud.bigtable.row_filters import TimestampRangeFilter\n return TimestampRangeFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -327,7 +328,7 @@ def test___eq__same_value(self):\n self.assertEqual(row_filter1, row_filter2)\n \n def test_to_pb(self):\n- from gcloud.bigtable.row_filters import TimestampRange\n+ from google.cloud.bigtable.row_filters import TimestampRange\n \n range_ = TimestampRange()\n row_filter = self._makeOne(range_)\n@@ -340,7 +341,7 @@ def test_to_pb(self):\n class TestColumnRangeFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ColumnRangeFilter\n+ from google.cloud.bigtable.row_filters import ColumnRangeFilter\n return ColumnRangeFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -464,7 +465,7 @@ def test_to_pb_exclusive_end(self):\n class TestValueRegexFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ValueRegexFilter\n+ from google.cloud.bigtable.row_filters import ValueRegexFilter\n return ValueRegexFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -481,7 +482,7 @@ def test_to_pb(self):\n class TestValueRangeFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ValueRangeFilter\n+ from google.cloud.bigtable.row_filters import ValueRangeFilter\n return ValueRangeFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -572,7 +573,7 @@ def test_to_pb_exclusive_end(self):\n class Test_CellCountFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import _CellCountFilter\n+ from google.cloud.bigtable.row_filters import _CellCountFilter\n return _CellCountFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -606,7 +607,7 @@ def test___ne__same_value(self):\n class TestCellsRowOffsetFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import CellsRowOffsetFilter\n+ from google.cloud.bigtable.row_filters import CellsRowOffsetFilter\n return CellsRowOffsetFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -624,7 +625,7 @@ def test_to_pb(self):\n class TestCellsRowLimitFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import CellsRowLimitFilter\n+ from google.cloud.bigtable.row_filters import CellsRowLimitFilter\n return CellsRowLimitFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -642,7 +643,7 @@ def test_to_pb(self):\n class TestCellsColumnLimitFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import CellsColumnLimitFilter\n+ from google.cloud.bigtable.row_filters import CellsColumnLimitFilter\n return CellsColumnLimitFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -660,7 +661,8 @@ def test_to_pb(self):\n class TestStripValueTransformerFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n return StripValueTransformerFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -677,7 +679,7 @@ def test_to_pb(self):\n class TestApplyLabelFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ApplyLabelFilter\n+ from google.cloud.bigtable.row_filters import ApplyLabelFilter\n return ApplyLabelFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -711,7 +713,7 @@ def test_to_pb(self):\n class Test_FilterCombination(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import _FilterCombination\n+ from google.cloud.bigtable.row_filters import _FilterCombination\n return _FilterCombination\n \n def _makeOne(self, *args, **kwargs):\n@@ -742,15 +744,16 @@ def test___eq__type_differ(self):\n class TestRowFilterChain(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import RowFilterChain\n+ from google.cloud.bigtable.row_filters import RowFilterChain\n return RowFilterChain\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_to_pb(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter1_pb = row_filter1.to_pb()\n@@ -769,9 +772,10 @@ def test_to_pb(self):\n self.assertEqual(filter_pb, expected_pb)\n \n def test_to_pb_nested(self):\n- from gcloud.bigtable.row_filters import CellsRowLimitFilter\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import CellsRowLimitFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter2 = RowSampleFilter(0.25)\n@@ -796,15 +800,16 @@ def test_to_pb_nested(self):\n class TestRowFilterUnion(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import RowFilterUnion\n+ from google.cloud.bigtable.row_filters import RowFilterUnion\n return RowFilterUnion\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_to_pb(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter1_pb = row_filter1.to_pb()\n@@ -823,9 +828,10 @@ def test_to_pb(self):\n self.assertEqual(filter_pb, expected_pb)\n \n def test_to_pb_nested(self):\n- from gcloud.bigtable.row_filters import CellsRowLimitFilter\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import CellsRowLimitFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter2 = RowSampleFilter(0.25)\n@@ -850,7 +856,7 @@ def test_to_pb_nested(self):\n class TestConditionalRowFilter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.bigtable.row_filters import ConditionalRowFilter\n+ from google.cloud.bigtable.row_filters import ConditionalRowFilter\n return ConditionalRowFilter\n \n def _makeOne(self, *args, **kwargs):\n@@ -890,9 +896,10 @@ def test___eq__type_differ(self):\n self.assertNotEqual(cond_filter1, cond_filter2)\n \n def test_to_pb(self):\n- from gcloud.bigtable.row_filters import CellsRowOffsetFilter\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import CellsRowOffsetFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter1_pb = row_filter1.to_pb()\n@@ -917,8 +924,9 @@ def test_to_pb(self):\n self.assertEqual(filter_pb, expected_pb)\n \n def test_to_pb_true_only(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter1_pb = row_filter1.to_pb()\n@@ -938,8 +946,9 @@ def test_to_pb_true_only(self):\n self.assertEqual(filter_pb, expected_pb)\n \n def test_to_pb_false_only(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n- from gcloud.bigtable.row_filters import StripValueTransformerFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import (\n+ StripValueTransformerFilter)\n \n row_filter1 = StripValueTransformerFilter(True)\n row_filter1_pb = row_filter1.to_pb()\n@@ -960,42 +969,42 @@ def test_to_pb_false_only(self):\n \n \n def _ColumnRangePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.ColumnRange(*args, **kw)\n \n \n def _RowFilterPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.RowFilter(*args, **kw)\n \n \n def _RowFilterChainPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.RowFilter.Chain(*args, **kw)\n \n \n def _RowFilterConditionPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.RowFilter.Condition(*args, **kw)\n \n \n def _RowFilterInterleavePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.RowFilter.Interleave(*args, **kw)\n \n \n def _TimestampRangePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.TimestampRange(*args, **kw)\n \n \n def _ValueRangePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n data_pb2 as data_v2_pb2)\n return data_v2_pb2.ValueRange(*args, **kw)\ndiff --git a/unit_tests/bigtable/test_table.py b/unit_tests/bigtable/test_table.py\n--- a/unit_tests/bigtable/test_table.py\n+++ b/unit_tests/bigtable/test_table.py\n@@ -30,7 +30,7 @@ class TestTable(unittest.TestCase):\n VALUE = b'value'\n \n def _getTargetClass(self):\n- from gcloud.bigtable.table import Table\n+ from google.cloud.bigtable.table import Table\n return Table\n \n def _makeOne(self, *args, **kwargs):\n@@ -54,7 +54,7 @@ def test_name_property(self):\n self.assertEqual(table.name, expected_name)\n \n def test_column_family_factory(self):\n- from gcloud.bigtable.column_family import ColumnFamily\n+ from google.cloud.bigtable.column_family import ColumnFamily\n \n table_id = 'table-id'\n gc_rule = object()\n@@ -68,7 +68,7 @@ def test_column_family_factory(self):\n self.assertEqual(column_family._table, table)\n \n def test_row_factory_direct(self):\n- from gcloud.bigtable.row import DirectRow\n+ from google.cloud.bigtable.row import DirectRow\n \n table_id = 'table-id'\n table = self._makeOne(table_id, None)\n@@ -80,7 +80,7 @@ def test_row_factory_direct(self):\n self.assertEqual(row._table, table)\n \n def test_row_factory_conditional(self):\n- from gcloud.bigtable.row import ConditionalRow\n+ from google.cloud.bigtable.row import ConditionalRow\n \n table_id = 'table-id'\n table = self._makeOne(table_id, None)\n@@ -93,7 +93,7 @@ def test_row_factory_conditional(self):\n self.assertEqual(row._table, table)\n \n def test_row_factory_append(self):\n- from gcloud.bigtable.row import AppendRow\n+ from google.cloud.bigtable.row import AppendRow\n \n table_id = 'table-id'\n table = self._makeOne(table_id, None)\n@@ -133,7 +133,7 @@ def test___ne__(self):\n self.assertNotEqual(table1, table2)\n \n def _create_test_helper(self, initial_split_keys, column_families=()):\n- from gcloud._helpers import _to_bytes\n+ from google.cloud._helpers import _to_bytes\n from unit_tests.bigtable._testing import _FakeStub\n \n client = _Client()\n@@ -186,8 +186,8 @@ def test_create_with_split_keys(self):\n self._create_test_helper(initial_split_keys)\n \n def test_create_with_column_families(self):\n- from gcloud.bigtable.column_family import ColumnFamily\n- from gcloud.bigtable.column_family import MaxVersionsGCRule\n+ from google.cloud.bigtable.column_family import ColumnFamily\n+ from google.cloud.bigtable.column_family import MaxVersionsGCRule\n \n cf_id1 = 'col-fam-id1'\n cf1 = ColumnFamily(cf_id1, None)\n@@ -269,7 +269,7 @@ def test_delete(self):\n def _read_row_helper(self, chunks, expected_result):\n from unit_tests._testing import _Monkey\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable import table as MUT\n+ from google.cloud.bigtable import table as MUT\n \n client = _Client()\n instance = _Instance(self.INSTANCE_NAME, client=client)\n@@ -315,8 +315,8 @@ def test_read_row_miss_no_chunks_in_response(self):\n self._read_row_helper(chunks, None)\n \n def test_read_row_complete(self):\n- from gcloud.bigtable.row_data import Cell\n- from gcloud.bigtable.row_data import PartialRowData\n+ from google.cloud.bigtable.row_data import Cell\n+ from google.cloud.bigtable.row_data import PartialRowData\n \n chunk = _ReadRowsResponseCellChunkPB(\n row_key=self.ROW_KEY,\n@@ -349,8 +349,8 @@ def test_read_row_still_partial(self):\n def test_read_rows(self):\n from unit_tests._testing import _Monkey\n from unit_tests.bigtable._testing import _FakeStub\n- from gcloud.bigtable.row_data import PartialRowsData\n- from gcloud.bigtable import table as MUT\n+ from google.cloud.bigtable.row_data import PartialRowsData\n+ from google.cloud.bigtable import table as MUT\n \n client = _Client()\n instance = _Instance(self.INSTANCE_NAME, client=client)\n@@ -430,7 +430,7 @@ class Test__create_row_request(unittest.TestCase):\n \n def _callFUT(self, table_name, row_key=None, start_key=None, end_key=None,\n filter_=None, limit=None):\n- from gcloud.bigtable.table import _create_row_request\n+ from google.cloud.bigtable.table import _create_row_request\n return _create_row_request(\n table_name, row_key=row_key, start_key=start_key, end_key=end_key,\n filter_=filter_, limit=limit)\n@@ -484,7 +484,7 @@ def test_row_range_both_keys(self):\n self.assertEqual(result, expected_result)\n \n def test_with_filter(self):\n- from gcloud.bigtable.row_filters import RowSampleFilter\n+ from google.cloud.bigtable.row_filters import RowSampleFilter\n table_name = 'table_name'\n row_filter = RowSampleFilter(0.33)\n result = self._callFUT(table_name, filter_=row_filter)\n@@ -506,37 +506,37 @@ def test_with_limit(self):\n \n \n def _CreateTableRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n return table_admin_v2_pb2.CreateTableRequest(*args, **kw)\n \n \n def _CreateTableRequestSplitPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n return table_admin_v2_pb2.CreateTableRequest.Split(*args, **kw)\n \n \n def _DeleteTableRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n return table_admin_v2_pb2.DeleteTableRequest(*args, **kw)\n \n \n def _GetTableRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_table_admin_pb2 as table_admin_v2_pb2)\n return table_admin_v2_pb2.GetTableRequest(*args, **kw)\n \n \n def _ReadRowsRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.ReadRowsRequest(*args, **kw)\n \n \n def _ReadRowsResponseCellChunkPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n family_name = kw.pop('family_name')\n qualifier = kw.pop('qualifier')\n@@ -547,25 +547,25 @@ def _ReadRowsResponseCellChunkPB(*args, **kw):\n \n \n def _ReadRowsResponsePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.ReadRowsResponse(*args, **kw)\n \n \n def _SampleRowKeysRequestPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n bigtable_pb2 as messages_v2_pb2)\n return messages_v2_pb2.SampleRowKeysRequest(*args, **kw)\n \n \n def _TablePB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.Table(*args, **kw)\n \n \n def _ColumnFamilyPB(*args, **kw):\n- from gcloud.bigtable._generated import (\n+ from google.cloud.bigtable._generated import (\n table_pb2 as table_v2_pb2)\n return table_v2_pb2.ColumnFamily(*args, **kw)\n \ndiff --git a/unit_tests/datastore/test_batch.py b/unit_tests/datastore/test_batch.py\n--- a/unit_tests/datastore/test_batch.py\n+++ b/unit_tests/datastore/test_batch.py\n@@ -18,7 +18,7 @@\n class TestBatch(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.batch import Batch\n+ from google.cloud.datastore.batch import Batch\n \n return Batch\n \n@@ -26,7 +26,7 @@ def _makeOne(self, client):\n return self._getTargetClass()(client)\n \n def test_ctor(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n _PROJECT = 'PROJECT'\n _NAMESPACE = 'NAMESPACE'\n connection = _Connection()\n@@ -97,7 +97,7 @@ def test_put_entity_w_partial_key(self):\n self.assertEqual(batch._partial_key_entities, [entity])\n \n def test_put_entity_w_completed_key(self):\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.helpers import _property_tuples\n \n _PROJECT = 'PROJECT'\n _PROPERTIES = {\n@@ -344,7 +344,7 @@ def is_partial(self):\n return self._id is None\n \n def to_protobuf(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n key = self._key = entity_pb2.Key()\n # Don't assign it, because it will just get ripped out\n # key.partition_id.project_id = self.project\ndiff --git a/unit_tests/datastore/test_client.py b/unit_tests/datastore/test_client.py\n--- a/unit_tests/datastore/test_client.py\n+++ b/unit_tests/datastore/test_client.py\n@@ -16,8 +16,8 @@\n \n \n def _make_entity_pb(project, kind, integer_id, name=None, str_val=None):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity_pb = entity_pb2.Entity()\n entity_pb.key.partition_id.project_id = project\n@@ -34,7 +34,7 @@ def _make_entity_pb(project, kind, integer_id, name=None, str_val=None):\n class Test__get_gcd_project(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud.datastore.client import _get_gcd_project\n+ from google.cloud.datastore.client import _get_gcd_project\n return _get_gcd_project()\n \n def test_no_value(self):\n@@ -49,7 +49,7 @@ def test_no_value(self):\n def test_value_set(self):\n import os\n from unit_tests._testing import _Monkey\n- from gcloud.datastore.client import GCD_DATASET\n+ from google.cloud.datastore.client import GCD_DATASET\n \n MOCK_PROJECT = object()\n environ = {GCD_DATASET: MOCK_PROJECT}\n@@ -61,14 +61,14 @@ def test_value_set(self):\n class Test__determine_default_project(unittest.TestCase):\n \n def _callFUT(self, project=None):\n- from gcloud.datastore.client import (\n+ from google.cloud.datastore.client import (\n _determine_default_project)\n return _determine_default_project(project=project)\n \n def _determine_default_helper(self, gcd=None, fallback=None,\n project_called=None):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import client\n+ from google.cloud.datastore import client\n \n _callers = []\n \n@@ -129,7 +129,7 @@ def tearDown(self):\n KLASS._connection_class = self.original_cnxn_class\n \n def _getTargetClass(self):\n- from gcloud.datastore.client import Client\n+ from google.cloud.datastore.client import Client\n return Client\n \n def _makeOne(self, project=PROJECT, namespace=None,\n@@ -141,7 +141,7 @@ def _makeOne(self, project=PROJECT, namespace=None,\n \n def test_ctor_w_project_no_environ(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import client as _MUT\n+ from google.cloud.datastore import client as _MUT\n \n # Some environments (e.g. AppVeyor CI) run in GCE, so\n # this test would fail artificially.\n@@ -150,8 +150,8 @@ def test_ctor_w_project_no_environ(self):\n \n def test_ctor_w_implicit_inputs(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import client as _MUT\n- from gcloud import client as _base_client\n+ from google.cloud.datastore import client as _MUT\n+ from google.cloud import client as _base_client\n \n OTHER = 'other'\n creds = object()\n@@ -263,7 +263,7 @@ def test_get_multi_no_keys(self):\n self.assertEqual(results, [])\n \n def test_get_multi_miss(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n creds = object()\n client = self._makeOne(credentials=creds)\n@@ -273,8 +273,8 @@ def test_get_multi_miss(self):\n self.assertEqual(results, [])\n \n def test_get_multi_miss_w_missing(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.key import Key\n \n KIND = 'Kind'\n ID = 1234\n@@ -299,7 +299,7 @@ def test_get_multi_miss_w_missing(self):\n [key.to_protobuf()])\n \n def test_get_multi_w_missing_non_empty(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n creds = object()\n client = self._makeOne(credentials=creds)\n@@ -310,7 +310,7 @@ def test_get_multi_w_missing_non_empty(self):\n [key], missing=missing)\n \n def test_get_multi_w_deferred_non_empty(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n creds = object()\n client = self._makeOne(credentials=creds)\n@@ -321,7 +321,7 @@ def test_get_multi_w_deferred_non_empty(self):\n [key], deferred=deferred)\n \n def test_get_multi_miss_w_deferred(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n key = Key('Kind', 1234, project=self.PROJECT)\n \n@@ -337,9 +337,9 @@ def test_get_multi_miss_w_deferred(self):\n [key.to_protobuf()])\n \n def test_get_multi_w_deferred_from_backend_but_not_passed(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.key import Key\n \n key1 = Key('Kind', project=self.PROJECT)\n key1_pb = key1.to_protobuf()\n@@ -390,7 +390,7 @@ def test_get_multi_w_deferred_from_backend_but_not_passed(self):\n self.assertTrue(tid is None)\n \n def test_get_multi_hit(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n KIND = 'Kind'\n ID = 1234\n@@ -416,7 +416,7 @@ def test_get_multi_hit(self):\n self.assertEqual(result['foo'], 'Foo')\n \n def test_get_multi_hit_w_transaction(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n TXN_ID = '123'\n KIND = 'Kind'\n@@ -450,7 +450,7 @@ def test_get_multi_hit_w_transaction(self):\n self.assertEqual(transaction_id, TXN_ID)\n \n def test_get_multi_hit_multiple_keys_same_project(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n KIND = 'Kind'\n ID1 = 1234\n@@ -476,7 +476,7 @@ def test_get_multi_hit_multiple_keys_same_project(self):\n self.assertEqual(dict(retrieved2), {})\n \n def test_get_multi_hit_multiple_keys_different_project(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n PROJECT1 = 'PROJECT'\n PROJECT2 = 'PROJECT-ALT'\n@@ -495,8 +495,8 @@ def test_get_multi_hit_multiple_keys_different_project(self):\n \n def test_get_multi_max_loops(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import client as _MUT\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore import client as _MUT\n+ from google.cloud.datastore.key import Key\n \n KIND = 'Kind'\n ID = 1234\n@@ -544,15 +544,15 @@ def test_put_multi_no_entities(self):\n self.assertEqual(client.put_multi([]), None)\n \n def test_put_multi_w_single_empty_entity(self):\n- # https://github.com/GoogleCloudPlatform/gcloud-python/issues/649\n- from gcloud.datastore.entity import Entity\n+ # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/649\n+ from google.cloud.datastore.entity import Entity\n \n creds = object()\n client = self._makeOne(credentials=creds)\n self.assertRaises(ValueError, client.put_multi, Entity())\n \n def test_put_multi_no_batch_w_partial_key(self):\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.helpers import _property_tuples\n \n entity = _Entity(foo=u'bar')\n key = entity.key = _Key(self.PROJECT)\n@@ -582,7 +582,7 @@ def test_put_multi_no_batch_w_partial_key(self):\n self.assertTrue(transaction_id is None)\n \n def test_put_multi_existing_batch_w_completed_key(self):\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.helpers import _property_tuples\n \n creds = object()\n client = self._makeOne(credentials=creds)\n@@ -701,7 +701,7 @@ def test_key_w_project(self):\n client.key, KIND, ID, project=self.PROJECT)\n \n def test_key_wo_project(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -722,7 +722,7 @@ def test_key_wo_project(self):\n self.assertEqual(key.kwargs, expected_kwargs)\n \n def test_key_w_namespace(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -743,7 +743,7 @@ def test_key_w_namespace(self):\n self.assertEqual(key.kwargs, expected_kwargs)\n \n def test_key_w_namespace_collision(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -765,7 +765,7 @@ def test_key_w_namespace_collision(self):\n self.assertEqual(key.kwargs, expected_kwargs)\n \n def test_batch(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n creds = object()\n@@ -779,7 +779,7 @@ def test_batch(self):\n self.assertEqual(batch.kwargs, {})\n \n def test_transaction_defaults(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n creds = object()\n@@ -811,7 +811,7 @@ def test_query_w_project(self):\n client.query, kind=KIND, project=self.PROJECT)\n \n def test_query_w_defaults(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n creds = object()\n@@ -829,7 +829,7 @@ def test_query_w_defaults(self):\n self.assertEqual(query.kwargs, expected_kwargs)\n \n def test_query_explicit(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -869,7 +869,7 @@ def test_query_explicit(self):\n self.assertEqual(query.kwargs, kwargs)\n \n def test_query_w_namespace(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -891,7 +891,7 @@ def test_query_w_namespace(self):\n self.assertEqual(query.kwargs, expected_kwargs)\n \n def test_query_w_namespace_collision(self):\n- from gcloud.datastore import client as MUT\n+ from google.cloud.datastore import client as MUT\n from unit_tests._testing import _Monkey\n \n KIND = 'KIND'\n@@ -957,7 +957,7 @@ def allocate_ids(self, project, key_pbs):\n class _NoCommitBatch(object):\n \n def __init__(self, client):\n- from gcloud.datastore.batch import Batch\n+ from google.cloud.datastore.batch import Batch\n self._client = client\n self._batch = Batch(client)\n \n@@ -972,7 +972,7 @@ def __exit__(self, *args):\n class _NoCommitTransaction(object):\n \n def __init__(self, client, transaction_id='TRANSACTION'):\n- from gcloud.datastore.transaction import Transaction\n+ from google.cloud.datastore.transaction import Transaction\n self._client = client\n xact = self._transaction = Transaction(client)\n xact._id = transaction_id\n@@ -1007,7 +1007,7 @@ def is_partial(self):\n return self._id is None\n \n def to_protobuf(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n key = self._key = entity_pb2.Key()\n # Don't assign it, because it will just get ripped out\n # key.partition_id.project_id = self.project\ndiff --git a/unit_tests/datastore/test_connection.py b/unit_tests/datastore/test_connection.py\n--- a/unit_tests/datastore/test_connection.py\n+++ b/unit_tests/datastore/test_connection.py\n@@ -14,13 +14,13 @@\n \n import unittest\n \n-from gcloud.datastore.connection import _HAVE_GRPC\n+from google.cloud.datastore.connection import _HAVE_GRPC\n \n \n class Test_DatastoreAPIOverHttp(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.connection import _DatastoreAPIOverHttp\n+ from google.cloud.datastore.connection import _DatastoreAPIOverHttp\n return _DatastoreAPIOverHttp\n \n def _makeOne(self, *args, **kw):\n@@ -84,7 +84,7 @@ def test__request_w_200(self):\n [{'method': METHOD, 'project': PROJECT}])\n \n def test__request_not_200(self):\n- from gcloud.exceptions import BadRequest\n+ from google.cloud.exceptions import BadRequest\n from google.rpc import status_pb2\n \n error = status_pb2.Status()\n@@ -109,12 +109,12 @@ def test__request_not_200(self):\n class Test_DatastoreAPIOverGRPC(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.connection import _DatastoreAPIOverGRPC\n+ from google.cloud.datastore.connection import _DatastoreAPIOverGRPC\n return _DatastoreAPIOverGRPC\n \n def _makeOne(self, stub, connection=None, mock_args=None):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import connection as MUT\n+ from google.cloud.datastore import connection as MUT\n \n if connection is None:\n connection = _Connection(None)\n@@ -131,7 +131,7 @@ def mock_make_stub(*args):\n return self._getTargetClass()(connection)\n \n def test_constructor(self):\n- from gcloud.datastore import connection as MUT\n+ from google.cloud.datastore import connection as MUT\n \n conn = _Connection(None)\n conn.credentials = object()\n@@ -221,7 +221,7 @@ def test_commit_failure_aborted(self):\n from grpc import StatusCode\n from grpc._channel import _Rendezvous\n from grpc._channel import _RPCState\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n \n details = 'Bad things.'\n exc_state = _RPCState((), None, None, StatusCode.ABORTED, details)\n@@ -274,19 +274,19 @@ def test_allocate_ids(self):\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.connection import Connection\n+ from google.cloud.datastore.connection import Connection\n \n return Connection\n \n def _make_key_pb(self, project, id_=1234):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n path_args = ('Kind',)\n if id_ is not None:\n path_args += (id_,)\n return Key(*path_args, project=project).to_protobuf()\n \n def _make_query_pb(self, kind):\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import query_pb2\n pb = query_pb2.Query()\n pb.kind.add().name = kind\n return pb\n@@ -294,7 +294,7 @@ def _make_query_pb(self, kind):\n def _makeOne(self, credentials=None, http=None,\n api_base_url=None, have_grpc=False):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import connection as MUT\n+ from google.cloud.datastore import connection as MUT\n with _Monkey(MUT, _HAVE_GRPC=have_grpc):\n return self._getTargetClass()(credentials=credentials, http=http,\n api_base_url=api_base_url)\n@@ -315,8 +315,8 @@ def test_default_url(self):\n def test_custom_url_from_env(self):\n import os\n from unit_tests._testing import _Monkey\n- from gcloud.connection import API_BASE_URL\n- from gcloud.environment_vars import GCD_HOST\n+ from google.cloud.connection import API_BASE_URL\n+ from google.cloud.environment_vars import GCD_HOST\n \n HOST = 'CURR_HOST'\n fake_environ = {GCD_HOST: HOST}\n@@ -328,7 +328,7 @@ def test_custom_url_from_env(self):\n self.assertEqual(conn.api_base_url, HOST + '/datastore')\n \n def test_custom_url_from_constructor(self):\n- from gcloud.connection import API_BASE_URL\n+ from google.cloud.connection import API_BASE_URL\n \n HOST = object()\n conn = self._makeOne(api_base_url=HOST)\n@@ -338,8 +338,8 @@ def test_custom_url_from_constructor(self):\n def test_custom_url_constructor_and_env(self):\n import os\n from unit_tests._testing import _Monkey\n- from gcloud.connection import API_BASE_URL\n- from gcloud.environment_vars import GCD_HOST\n+ from google.cloud.connection import API_BASE_URL\n+ from google.cloud.environment_vars import GCD_HOST\n \n HOST1 = object()\n HOST2 = object()\n@@ -358,7 +358,7 @@ def test_ctor_defaults(self):\n \n def test_ctor_without_grpc(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import connection as MUT\n+ from google.cloud.datastore import connection as MUT\n \n connections = []\n return_val = object()\n@@ -376,7 +376,7 @@ def mock_api(connection):\n \n def test_ctor_with_grpc(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore import connection as MUT\n+ from google.cloud.datastore import connection as MUT\n \n connections = []\n return_val = object()\n@@ -460,7 +460,7 @@ def test_build_api_url_w_explicit_base_version(self):\n URI)\n \n def test_lookup_single_key_empty_response(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n key_pb = self._make_key_pb(PROJECT)\n@@ -487,7 +487,7 @@ def test_lookup_single_key_empty_response(self):\n self.assertEqual(key_pb, keys[0])\n \n def test_lookup_single_key_empty_response_w_eventual(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n key_pb = self._make_key_pb(PROJECT)\n@@ -526,7 +526,7 @@ def test_lookup_single_key_empty_response_w_eventual_and_transaction(self):\n eventual=True, transaction_id=TRANSACTION)\n \n def test_lookup_single_key_empty_response_w_transaction(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n TRANSACTION = b'TRANSACTION'\n@@ -556,8 +556,8 @@ def test_lookup_single_key_empty_response_w_transaction(self):\n self.assertEqual(request.read_options.transaction, TRANSACTION)\n \n def test_lookup_single_key_nonempty_response(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n PROJECT = 'PROJECT'\n key_pb = self._make_key_pb(PROJECT)\n@@ -588,7 +588,7 @@ def test_lookup_single_key_nonempty_response(self):\n self.assertEqual(key_pb, keys[0])\n \n def test_lookup_multiple_keys_empty_response(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n key_pb1 = self._make_key_pb(PROJECT)\n@@ -617,7 +617,7 @@ def test_lookup_multiple_keys_empty_response(self):\n self.assertEqual(key_pb2, keys[1])\n \n def test_lookup_multiple_keys_w_missing(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n key_pb1 = self._make_key_pb(PROJECT)\n@@ -651,7 +651,7 @@ def test_lookup_multiple_keys_w_missing(self):\n self.assertEqual(key_pb2, keys[1])\n \n def test_lookup_multiple_keys_w_deferred(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n key_pb1 = self._make_key_pb(PROJECT)\n@@ -687,8 +687,8 @@ def test_lookup_multiple_keys_w_deferred(self):\n self.assertEqual(key_pb2, keys[1])\n \n def test_run_query_w_eventual_no_transaction(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n PROJECT = 'PROJECT'\n KIND = 'Nonesuch'\n@@ -725,8 +725,8 @@ def test_run_query_w_eventual_no_transaction(self):\n self.assertEqual(request.read_options.transaction, b'')\n \n def test_run_query_wo_eventual_w_transaction(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n PROJECT = 'PROJECT'\n KIND = 'Nonesuch'\n@@ -765,8 +765,8 @@ def test_run_query_wo_eventual_w_transaction(self):\n self.assertEqual(request.read_options.transaction, TRANSACTION)\n \n def test_run_query_w_eventual_and_transaction(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n PROJECT = 'PROJECT'\n KIND = 'Nonesuch'\n@@ -783,8 +783,8 @@ def test_run_query_w_eventual_and_transaction(self):\n eventual=True, transaction_id=TRANSACTION)\n \n def test_run_query_wo_namespace_empty_result(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n PROJECT = 'PROJECT'\n KIND = 'Nonesuch'\n@@ -817,8 +817,8 @@ def test_run_query_wo_namespace_empty_result(self):\n self.assertEqual(request.query, q_pb)\n \n def test_run_query_w_namespace_nonempty_result(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n PROJECT = 'PROJECT'\n KIND = 'Kind'\n@@ -847,7 +847,7 @@ def test_run_query_w_namespace_nonempty_result(self):\n self.assertEqual(request.query, q_pb)\n \n def test_begin_transaction(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n TRANSACTION = b'TRANSACTION'\n@@ -870,9 +870,9 @@ def test_begin_transaction(self):\n \n def test_commit_wo_transaction(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore import connection as MUT\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore import connection as MUT\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n PROJECT = 'PROJECT'\n key_pb = self._make_key_pb(PROJECT)\n@@ -916,9 +916,9 @@ def mock_parse(response):\n \n def test_commit_w_transaction(self):\n from unit_tests._testing import _Monkey\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore import connection as MUT\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore import connection as MUT\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n PROJECT = 'PROJECT'\n key_pb = self._make_key_pb(PROJECT)\n@@ -961,7 +961,7 @@ def mock_parse(response):\n self.assertEqual(_parsed, [rsp_pb])\n \n def test_rollback_ok(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n PROJECT = 'PROJECT'\n TRANSACTION = b'xact'\n \n@@ -983,7 +983,7 @@ def test_rollback_ok(self):\n self.assertEqual(request.transaction, TRANSACTION)\n \n def test_allocate_ids_empty(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n rsp_pb = datastore_pb2.AllocateIdsResponse()\n@@ -1004,7 +1004,7 @@ def test_allocate_ids_empty(self):\n self.assertEqual(list(request.keys), [])\n \n def test_allocate_ids_non_empty(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n PROJECT = 'PROJECT'\n before_key_pbs = [\n@@ -1041,12 +1041,12 @@ def test_allocate_ids_non_empty(self):\n class Test__parse_commit_response(unittest.TestCase):\n \n def _callFUT(self, commit_response_pb):\n- from gcloud.datastore.connection import _parse_commit_response\n+ from google.cloud.datastore.connection import _parse_commit_response\n return _parse_commit_response(commit_response_pb)\n \n def test_it(self):\n- from gcloud.datastore._generated import datastore_pb2\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n index_updates = 1337\n keys = [\ndiff --git a/unit_tests/datastore/test_entity.py b/unit_tests/datastore/test_entity.py\n--- a/unit_tests/datastore/test_entity.py\n+++ b/unit_tests/datastore/test_entity.py\n@@ -22,7 +22,7 @@\n class TestEntity(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.entity import Entity\n+ from google.cloud.datastore.entity import Entity\n return Entity\n \n def _makeOne(self, key=None, exclude_from_indexes=()):\n@@ -51,14 +51,14 @@ def test_ctor_bad_exclude_from_indexes(self):\n exclude_from_indexes=BAD_EXCLUDE_FROM_INDEXES)\n \n def test___eq_____ne___w_non_entity(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key = Key(_KIND, _ID, project=_PROJECT)\n entity = self._makeOne(key=key)\n self.assertFalse(entity == object())\n self.assertTrue(entity != object())\n \n def test___eq_____ne___w_different_keys(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n _ID1 = 1234\n _ID2 = 2345\n key1 = Key(_KIND, _ID1, project=_PROJECT)\n@@ -69,7 +69,7 @@ def test___eq_____ne___w_different_keys(self):\n self.assertTrue(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n name = 'foo'\n value = 42\n@@ -89,7 +89,7 @@ def test___eq_____ne___w_same_keys(self):\n self.assertFalse(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys_different_props(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key1 = Key(_KIND, _ID, project=_PROJECT)\n entity1 = self._makeOne(key=key1)\n entity1['foo'] = 'Foo'\n@@ -100,7 +100,7 @@ def test___eq_____ne___w_same_keys_different_props(self):\n self.assertTrue(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys_props_w_equiv_keys_as_value(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key1 = Key(_KIND, _ID, project=_PROJECT)\n key2 = Key(_KIND, _ID, project=_PROJECT)\n entity1 = self._makeOne(key=key1)\n@@ -111,7 +111,7 @@ def test___eq_____ne___w_same_keys_props_w_equiv_keys_as_value(self):\n self.assertFalse(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys_props_w_diff_keys_as_value(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n _ID1 = 1234\n _ID2 = 2345\n key1 = Key(_KIND, _ID1, project=_PROJECT)\n@@ -124,7 +124,7 @@ def test___eq_____ne___w_same_keys_props_w_diff_keys_as_value(self):\n self.assertTrue(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys_props_w_equiv_entities_as_value(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key = Key(_KIND, _ID, project=_PROJECT)\n entity1 = self._makeOne(key=key)\n sub1 = self._makeOne()\n@@ -138,7 +138,7 @@ def test___eq_____ne___w_same_keys_props_w_equiv_entities_as_value(self):\n self.assertFalse(entity1 != entity2)\n \n def test___eq_____ne___w_same_keys_props_w_diff_entities_as_value(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key = Key(_KIND, _ID, project=_PROJECT)\n entity1 = self._makeOne(key=key)\n sub1 = self._makeOne()\n@@ -152,7 +152,7 @@ def test___eq_____ne___w_same_keys_props_w_diff_entities_as_value(self):\n self.assertTrue(entity1 != entity2)\n \n def test__eq__same_value_different_exclude(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n name = 'foo'\n value = 42\n@@ -167,7 +167,7 @@ def test__eq__same_value_different_exclude(self):\n self.assertFalse(entity1 == entity2)\n \n def test__eq__same_value_different_meanings(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n name = 'foo'\n value = 42\ndiff --git a/unit_tests/datastore/test_helpers.py b/unit_tests/datastore/test_helpers.py\n--- a/unit_tests/datastore/test_helpers.py\n+++ b/unit_tests/datastore/test_helpers.py\n@@ -18,11 +18,11 @@\n class Test__new_value_pb(unittest.TestCase):\n \n def _callFUT(self, entity_pb, name):\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore.helpers import _new_value_pb\n return _new_value_pb(entity_pb, name)\n \n def test_it(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n entity_pb = entity_pb2.Entity()\n name = 'foo'\n@@ -36,13 +36,13 @@ def test_it(self):\n class Test__property_tuples(unittest.TestCase):\n \n def _callFUT(self, entity_pb):\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.helpers import _property_tuples\n return _property_tuples(entity_pb)\n \n def test_it(self):\n import types\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity_pb = entity_pb2.Entity()\n name1 = 'foo'\n@@ -59,12 +59,12 @@ def test_it(self):\n class Test_entity_from_protobuf(unittest.TestCase):\n \n def _callFUT(self, val):\n- from gcloud.datastore.helpers import entity_from_protobuf\n+ from google.cloud.datastore.helpers import entity_from_protobuf\n return entity_from_protobuf(val)\n \n def test_it(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n _PROJECT = 'PROJECT'\n _KIND = 'KIND'\n@@ -109,8 +109,8 @@ def test_it(self):\n self.assertEqual(key.id, _ID)\n \n def test_mismatched_value_indexed(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n _PROJECT = 'PROJECT'\n _KIND = 'KIND'\n@@ -133,7 +133,7 @@ def test_mismatched_value_indexed(self):\n self._callFUT(entity_pb)\n \n def test_entity_no_key(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n entity_pb = entity_pb2.Entity()\n entity = self._callFUT(entity_pb)\n@@ -142,8 +142,8 @@ def test_entity_no_key(self):\n self.assertEqual(dict(entity), {})\n \n def test_entity_with_meaning(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity_pb = entity_pb2.Entity()\n name = 'hello'\n@@ -157,8 +157,8 @@ def test_entity_with_meaning(self):\n self.assertEqual(entity._meanings, {name: (meaning, val)})\n \n def test_nested_entity_no_key(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n PROJECT = 'FOO'\n KIND = 'KIND'\n@@ -192,11 +192,11 @@ def test_nested_entity_no_key(self):\n class Test_entity_to_protobuf(unittest.TestCase):\n \n def _callFUT(self, entity):\n- from gcloud.datastore.helpers import entity_to_protobuf\n+ from google.cloud.datastore.helpers import entity_to_protobuf\n return entity_to_protobuf(entity)\n \n def _compareEntityProto(self, entity_pb1, entity_pb2):\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.helpers import _property_tuples\n \n self.assertEqual(entity_pb1.key, entity_pb2.key)\n value_list1 = sorted(_property_tuples(entity_pb1))\n@@ -214,17 +214,17 @@ def _compareEntityProto(self, entity_pb1, entity_pb2):\n self.assertEqual(val1, val2)\n \n def test_empty(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n \n entity = Entity()\n entity_pb = self._callFUT(entity)\n self._compareEntityProto(entity_pb, entity_pb2.Entity())\n \n def test_key_only(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.key import Key\n \n kind, name = 'PATH', 'NAME'\n project = 'PROJECT'\n@@ -241,9 +241,9 @@ def test_key_only(self):\n self._compareEntityProto(entity_pb, expected_pb)\n \n def test_simple_fields(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity = Entity()\n name1 = 'foo'\n@@ -261,8 +261,8 @@ def test_simple_fields(self):\n self._compareEntityProto(entity_pb, expected_pb)\n \n def test_with_empty_list(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n \n entity = Entity()\n entity['foo'] = []\n@@ -271,9 +271,9 @@ def test_with_empty_list(self):\n self._compareEntityProto(entity_pb, entity_pb2.Entity())\n \n def test_inverts_to_protobuf(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n- from gcloud.datastore.helpers import entity_from_protobuf\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore.helpers import entity_from_protobuf\n \n original_pb = entity_pb2.Entity()\n # Add a key.\n@@ -324,9 +324,9 @@ def test_inverts_to_protobuf(self):\n self._compareEntityProto(original_pb, new_pb)\n \n def test_meaning_with_change(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity = Entity()\n name = 'foo'\n@@ -342,9 +342,9 @@ def test_meaning_with_change(self):\n self._compareEntityProto(entity_pb, expected_pb)\n \n def test_variable_meanings(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n entity = Entity()\n name = 'quux'\n@@ -371,12 +371,12 @@ def test_variable_meanings(self):\n class Test_key_from_protobuf(unittest.TestCase):\n \n def _callFUT(self, val):\n- from gcloud.datastore.helpers import key_from_protobuf\n+ from google.cloud.datastore.helpers import key_from_protobuf\n \n return key_from_protobuf(val)\n \n def _makePB(self, project=None, namespace=None, path=()):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n pb = entity_pb2.Key()\n if project is not None:\n pb.partition_id.project_id = project\n@@ -425,14 +425,14 @@ def test_w_nothing_in_pb(self):\n class Test__pb_attr_value(unittest.TestCase):\n \n def _callFUT(self, val):\n- from gcloud.datastore.helpers import _pb_attr_value\n+ from google.cloud.datastore.helpers import _pb_attr_value\n \n return _pb_attr_value(val)\n \n def test_datetime_naive(self):\n import calendar\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n micros = 4375\n naive = datetime.datetime(2014, 9, 16, 10, 19, 32, micros) # No zone.\n@@ -445,7 +445,7 @@ def test_datetime_naive(self):\n def test_datetime_w_zone(self):\n import calendar\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n micros = 4375\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, micros, UTC)\n@@ -455,7 +455,7 @@ def test_datetime_w_zone(self):\n self.assertEqual(value.nanos, 1000 * micros)\n \n def test_key(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n key = Key('PATH', 1234, project='PROJECT')\n name, value = self._callFUT(key)\n@@ -503,7 +503,7 @@ def test_unicode(self):\n self.assertEqual(value, u'str')\n \n def test_entity(self):\n- from gcloud.datastore.entity import Entity\n+ from google.cloud.datastore.entity import Entity\n entity = Entity()\n name, value = self._callFUT(entity)\n self.assertEqual(name, 'entity_value')\n@@ -517,7 +517,7 @@ def test_array(self):\n \n def test_geo_point(self):\n from google.type import latlng_pb2\n- from gcloud.datastore.helpers import GeoPoint\n+ from google.cloud.datastore.helpers import GeoPoint\n \n lat = 42.42\n lng = 99.0007\n@@ -541,12 +541,12 @@ def test_object(self):\n class Test__get_value_from_value_pb(unittest.TestCase):\n \n def _callFUT(self, pb):\n- from gcloud.datastore.helpers import _get_value_from_value_pb\n+ from google.cloud.datastore.helpers import _get_value_from_value_pb\n \n return _get_value_from_value_pb(pb)\n \n def _makePB(self, attr_name, value):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n pb = entity_pb2.Value()\n setattr(pb, attr_name, value)\n@@ -555,8 +555,8 @@ def _makePB(self, attr_name, value):\n def test_datetime(self):\n import calendar\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud._helpers import UTC\n+ from google.cloud.datastore._generated import entity_pb2\n \n micros = 4375\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, micros, UTC)\n@@ -566,8 +566,8 @@ def test_datetime(self):\n self.assertEqual(self._callFUT(pb), utc)\n \n def test_key(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.key import Key\n \n pb = entity_pb2.Value()\n expected = Key('KIND', 1234, project='PROJECT').to_protobuf()\n@@ -596,9 +596,9 @@ def test_unicode(self):\n self.assertEqual(self._callFUT(pb), u'str')\n \n def test_entity(self):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n pb = entity_pb2.Value()\n entity_pb = pb.entity_value\n@@ -612,7 +612,7 @@ def test_entity(self):\n self.assertEqual(entity['foo'], 'Foo')\n \n def test_array(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n pb = entity_pb2.Value()\n array_pb = pb.array_value.values\n@@ -625,8 +625,8 @@ def test_array(self):\n \n def test_geo_point(self):\n from google.type import latlng_pb2\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore.helpers import GeoPoint\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore.helpers import GeoPoint\n \n lat = -3.14\n lng = 13.37\n@@ -639,14 +639,14 @@ def test_geo_point(self):\n \n def test_null(self):\n from google.protobuf import struct_pb2\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n pb = entity_pb2.Value(null_value=struct_pb2.NULL_VALUE)\n result = self._callFUT(pb)\n self.assertIsNone(result)\n \n def test_unknown(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n pb = entity_pb2.Value()\n with self.assertRaises(ValueError):\n@@ -656,18 +656,18 @@ def test_unknown(self):\n class Test_set_protobuf_value(unittest.TestCase):\n \n def _callFUT(self, value_pb, val):\n- from gcloud.datastore.helpers import _set_protobuf_value\n+ from google.cloud.datastore.helpers import _set_protobuf_value\n \n return _set_protobuf_value(value_pb, val)\n \n def _makePB(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n return entity_pb2.Value()\n \n def test_datetime(self):\n import calendar\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n pb = self._makePB()\n micros = 4375\n@@ -678,7 +678,7 @@ def test_datetime(self):\n self.assertEqual(value.nanos, 1000 * micros)\n \n def test_key(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n pb = self._makePB()\n key = Key('KIND', 1234, project='PROJECT')\n@@ -739,8 +739,8 @@ def test_unicode(self):\n self.assertEqual(value, u'str')\n \n def test_entity_empty_wo_key(self):\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _property_tuples\n \n pb = self._makePB()\n entity = Entity()\n@@ -750,9 +750,9 @@ def test_entity_empty_wo_key(self):\n self.assertEqual(len(list(_property_tuples(value))), 0)\n \n def test_entity_w_key(self):\n- from gcloud.datastore.entity import Entity\n- from gcloud.datastore.helpers import _property_tuples\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.entity import Entity\n+ from google.cloud.datastore.helpers import _property_tuples\n+ from google.cloud.datastore.key import Key\n \n name = 'foo'\n value = u'Foo'\n@@ -781,7 +781,7 @@ def test_array(self):\n \n def test_geo_point(self):\n from google.type import latlng_pb2\n- from gcloud.datastore.helpers import GeoPoint\n+ from google.cloud.datastore.helpers import GeoPoint\n \n pb = self._makePB()\n lat = 9.11\n@@ -795,18 +795,18 @@ def test_geo_point(self):\n class Test__get_meaning(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.datastore.helpers import _get_meaning\n+ from google.cloud.datastore.helpers import _get_meaning\n return _get_meaning(*args, **kwargs)\n \n def test_no_meaning(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n result = self._callFUT(value_pb)\n self.assertEqual(result, None)\n \n def test_single(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n value_pb.meaning = meaning = 22\n@@ -815,7 +815,7 @@ def test_single(self):\n self.assertEqual(meaning, result)\n \n def test_empty_array_value(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n value_pb.array_value.values.add()\n@@ -825,7 +825,7 @@ def test_empty_array_value(self):\n self.assertEqual(None, result)\n \n def test_array_value(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n meaning = 9\n@@ -840,7 +840,7 @@ def test_array_value(self):\n self.assertEqual(meaning, result)\n \n def test_array_value_multiple_meanings(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n meaning1 = 9\n@@ -857,7 +857,7 @@ def test_array_value_multiple_meanings(self):\n self.assertEqual(result, [meaning1, meaning2])\n \n def test_array_value_meaning_partially_unset(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n value_pb = entity_pb2.Value()\n meaning1 = 9\n@@ -875,7 +875,7 @@ def test_array_value_meaning_partially_unset(self):\n class TestGeoPoint(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.helpers import GeoPoint\n+ from google.cloud.datastore.helpers import GeoPoint\n return GeoPoint\n \n def _makeOne(self, *args, **kwargs):\ndiff --git a/unit_tests/datastore/test_key.py b/unit_tests/datastore/test_key.py\n--- a/unit_tests/datastore/test_key.py\n+++ b/unit_tests/datastore/test_key.py\n@@ -20,7 +20,7 @@ class TestKey(unittest.TestCase):\n _DEFAULT_PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n return Key\n \n def _makeOne(self, *args, **kwargs):\n@@ -313,7 +313,7 @@ def test_completed_key_on_complete(self):\n self.assertRaises(ValueError, key.completed_key, 5678)\n \n def test_to_protobuf_defaults(self):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n _KIND = 'KIND'\n key = self._makeOne(_KIND, project=self._DEFAULT_PROJECT)\ndiff --git a/unit_tests/datastore/test_query.py b/unit_tests/datastore/test_query.py\n--- a/unit_tests/datastore/test_query.py\n+++ b/unit_tests/datastore/test_query.py\n@@ -20,7 +20,7 @@ class TestQuery(unittest.TestCase):\n _PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.datastore.query import Query\n+ from google.cloud.datastore.query import Query\n return Query\n \n def _makeOne(self, *args, **kw):\n@@ -45,7 +45,7 @@ def test_ctor_defaults(self):\n self.assertEqual(query.distinct_on, [])\n \n def test_ctor_explicit(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n _PROJECT = 'OTHER_PROJECT'\n _KIND = 'KIND'\n _NAMESPACE = 'OTHER_NAMESPACE'\n@@ -143,7 +143,7 @@ def _assign(val):\n self.assertRaises(TypeError, _assign, ['KIND', 'NAME'])\n \n def test_ancestor_setter_w_key(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n _NAME = u'NAME'\n key = Key('KIND', 123, project=self._PROJECT)\n query = self._makeOne(self._makeClient())\n@@ -152,7 +152,7 @@ def test_ancestor_setter_w_key(self):\n self.assertEqual(query.ancestor.path, key.path)\n \n def test_ancestor_deleter_w_key(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key = Key('KIND', 123, project=self._PROJECT)\n query = self._makeOne(client=self._makeClient(), ancestor=key)\n del query.ancestor\n@@ -183,7 +183,7 @@ def test_add_filter_w_all_operators(self):\n self.assertEqual(query.filters[4], ('eq_prop', '=', u'val5'))\n \n def test_add_filter_w_known_operator_and_entity(self):\n- from gcloud.datastore.entity import Entity\n+ from google.cloud.datastore.entity import Entity\n query = self._makeOne(self._makeClient())\n other = Entity()\n other['firstname'] = u'John'\n@@ -198,14 +198,14 @@ def test_add_filter_w_whitespace_property_name(self):\n self.assertEqual(query.filters, [(PROPERTY_NAME, '=', u'John')])\n \n def test_add_filter___key__valid_key(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n query = self._makeOne(self._makeClient())\n key = Key('Foo', project=self._PROJECT)\n query.add_filter('__key__', '=', key)\n self.assertEqual(query.filters, [('__key__', '=', key)])\n \n def test_filter___key__not_equal_operator(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n key = Key('Foo', project=self._PROJECT)\n query = self._makeOne(self._makeClient())\n query.add_filter('__key__', '<', key)\n@@ -245,7 +245,7 @@ def test_keys_only(self):\n self.assertEqual(query.projection, ['__key__'])\n \n def test_key_filter_defaults(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n client = self._makeClient()\n query = self._makeOne(client)\n@@ -255,7 +255,7 @@ def test_key_filter_defaults(self):\n self.assertEqual(query.filters, [('__key__', '=', key)])\n \n def test_key_filter_explicit(self):\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n \n client = self._makeClient()\n query = self._makeOne(client)\n@@ -339,7 +339,7 @@ class TestIterator(unittest.TestCase):\n _END = b'\\xFF'\n \n def _getTargetClass(self):\n- from gcloud.datastore.query import Iterator\n+ from google.cloud.datastore.query import Iterator\n return Iterator\n \n def _makeOne(self, *args, **kw):\n@@ -347,9 +347,9 @@ def _makeOne(self, *args, **kw):\n \n def _addQueryResults(self, connection, cursor=_END, more=False,\n skipped_results=None, no_entity=False):\n- from gcloud.datastore._generated import entity_pb2\n- from gcloud.datastore._generated import query_pb2\n- from gcloud.datastore.helpers import _new_value_pb\n+ from google.cloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import query_pb2\n+ from google.cloud.datastore.helpers import _new_value_pb\n \n if more:\n more_enum = query_pb2.QueryResultBatch.NOT_FINISHED\n@@ -394,7 +394,7 @@ def test_ctor_explicit(self):\n self.assertEqual(iterator._offset, 29)\n \n def test_next_page_no_cursors_no_more(self):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n connection = _Connection()\n client = self._makeClient(connection)\n query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)\n@@ -421,7 +421,7 @@ def test_next_page_no_cursors_no_more(self):\n self.assertEqual(connection._called_with, [EXPECTED])\n \n def test_next_page_no_cursors_no_more_w_offset_and_limit(self):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n connection = _Connection()\n client = self._makeClient(connection)\n query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)\n@@ -453,7 +453,7 @@ def test_next_page_no_cursors_no_more_w_offset_and_limit(self):\n def test_next_page_w_cursors_w_more(self):\n from base64 import urlsafe_b64decode\n from base64 import urlsafe_b64encode\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n connection = _Connection()\n client = self._makeClient(connection)\n query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)\n@@ -496,7 +496,7 @@ def test_next_page_w_cursors_w_bogus_more(self):\n self.assertRaises(ValueError, iterator.next_page)\n \n def test___iter___no_more(self):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n connection = _Connection()\n client = self._makeClient(connection)\n query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)\n@@ -520,7 +520,7 @@ def test___iter___no_more(self):\n self.assertEqual(connection._called_with, [EXPECTED])\n \n def test___iter___w_more(self):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n connection = _Connection()\n client = self._makeClient(connection)\n query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)\n@@ -556,7 +556,7 @@ def test___iter___w_more(self):\n self.assertEqual(connection._called_with[1], EXPECTED2)\n \n def test___iter___w_limit(self):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n \n connection = _Connection()\n client = self._makeClient(connection)\n@@ -614,11 +614,11 @@ def test___iter___w_limit(self):\n class Test__pb_from_query(unittest.TestCase):\n \n def _callFUT(self, query):\n- from gcloud.datastore.query import _pb_from_query\n+ from google.cloud.datastore.query import _pb_from_query\n return _pb_from_query(query)\n \n def test_empty(self):\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n pb = self._callFUT(_Query())\n self.assertEqual(list(pb.projection), [])\n@@ -645,8 +645,8 @@ def test_kind(self):\n self.assertEqual([item.name for item in pb.kind], ['KIND'])\n \n def test_ancestor(self):\n- from gcloud.datastore.key import Key\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore.key import Key\n+ from google.cloud.datastore._generated import query_pb2\n \n ancestor = Key('Ancestor', 123, project='PROJECT')\n pb = self._callFUT(_Query(ancestor=ancestor))\n@@ -659,7 +659,7 @@ def test_ancestor(self):\n self.assertEqual(pfilter.value.key_value, ancestor_pb)\n \n def test_filter(self):\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n query = _Query(filters=[('name', '=', u'John')])\n query.OPERATORS = {\n@@ -674,8 +674,8 @@ def test_filter(self):\n self.assertEqual(pfilter.value.string_value, u'John')\n \n def test_filter_key(self):\n- from gcloud.datastore.key import Key\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore.key import Key\n+ from google.cloud.datastore._generated import query_pb2\n \n key = Key('Kind', 123, project='PROJECT')\n query = _Query(filters=[('__key__', '=', key)])\n@@ -692,7 +692,7 @@ def test_filter_key(self):\n self.assertEqual(pfilter.value.key_value, key_pb)\n \n def test_order(self):\n- from gcloud.datastore._generated import query_pb2\n+ from google.cloud.datastore._generated import query_pb2\n \n pb = self._callFUT(_Query(order=['a', '-b', 'c']))\n self.assertEqual([item.property.name for item in pb.order],\ndiff --git a/unit_tests/datastore/test_transaction.py b/unit_tests/datastore/test_transaction.py\n--- a/unit_tests/datastore/test_transaction.py\n+++ b/unit_tests/datastore/test_transaction.py\n@@ -18,14 +18,14 @@\n class TestTransaction(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.datastore.transaction import Transaction\n+ from google.cloud.datastore.transaction import Transaction\n return Transaction\n \n def _makeOne(self, client, **kw):\n return self._getTargetClass()(client, **kw)\n \n def test_ctor_defaults(self):\n- from gcloud.datastore._generated import datastore_pb2\n+ from google.cloud.datastore._generated import datastore_pb2\n \n _PROJECT = 'PROJECT'\n connection = _Connection()\n@@ -164,7 +164,7 @@ class Foo(Exception):\n \n \n def _make_key(kind, id_, project):\n- from gcloud.datastore._generated import entity_pb2\n+ from google.cloud.datastore._generated import entity_pb2\n \n key = entity_pb2.Key()\n key.partition_id.project_id = project\n@@ -199,7 +199,7 @@ class _Entity(dict):\n \n def __init__(self):\n super(_Entity, self).__init__()\n- from gcloud.datastore.key import Key\n+ from google.cloud.datastore.key import Key\n self.key = Key('KIND', project='PROJECT')\n \n \n@@ -225,7 +225,7 @@ def current_batch(self):\n class _NoCommitBatch(object):\n \n def __init__(self, client):\n- from gcloud.datastore.batch import Batch\n+ from google.cloud.datastore.batch import Batch\n self._client = client\n self._batch = Batch(client)\n \ndiff --git a/unit_tests/dns/test_changes.py b/unit_tests/dns/test_changes.py\n--- a/unit_tests/dns/test_changes.py\n+++ b/unit_tests/dns/test_changes.py\n@@ -21,19 +21,19 @@ class TestChanges(unittest.TestCase):\n CHANGES_NAME = 'changeset_id'\n \n def _getTargetClass(self):\n- from gcloud.dns.changes import Changes\n+ from google.cloud.dns.changes import Changes\n return Changes\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def _setUpConstants(self):\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _NOW\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _NOW\n self.WHEN = _NOW().replace(tzinfo=UTC)\n \n def _makeResource(self):\n- from gcloud._helpers import _datetime_to_rfc3339\n+ from google.cloud._helpers import _datetime_to_rfc3339\n when_str = _datetime_to_rfc3339(self.WHEN)\n return {\n 'kind': 'dns#change',\n@@ -55,7 +55,7 @@ def _makeResource(self):\n }\n \n def _verifyResourceProperties(self, changes, resource, zone):\n- from gcloud._helpers import _rfc3339_to_datetime\n+ from google.cloud._helpers import _rfc3339_to_datetime\n self.assertEqual(changes.name, resource['id'])\n started = _rfc3339_to_datetime(resource['startTime'])\n self.assertEqual(changes.started, started)\n@@ -133,7 +133,7 @@ def test_add_record_set_invalid_value(self):\n changes.add_record_set(object())\n \n def test_add_record_set(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n zone = _Zone()\n changes = self._makeOne(zone)\n rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600,\n@@ -149,7 +149,7 @@ def test_delete_record_set_invalid_value(self):\n changes.delete_record_set(object())\n \n def test_delete_record_set(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n zone = _Zone()\n changes = self._makeOne(zone)\n rrs = ResourceRecordSet('test.example.com', 'CNAME', 3600,\n@@ -171,7 +171,7 @@ def test_create_wo_additions_or_deletions(self):\n self.assertEqual(len(conn._requested), 0)\n \n def test_create_w_bound_client(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n self._setUpConstants()\n RESOURCE = self._makeResource()\n PATH = 'projects/%s/managedZones/%s/changes' % (\n@@ -199,7 +199,7 @@ def test_create_w_bound_client(self):\n self._verifyResourceProperties(changes, RESOURCE, zone)\n \n def test_create_w_alternate_client(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n self._setUpConstants()\n RESOURCE = self._makeResource()\n PATH = 'projects/%s/managedZones/%s/changes' % (\n@@ -332,7 +332,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/dns/test_client.py b/unit_tests/dns/test_client.py\n--- a/unit_tests/dns/test_client.py\n+++ b/unit_tests/dns/test_client.py\n@@ -21,14 +21,14 @@ class TestClient(unittest.TestCase):\n ZONE_NAME = 'zone-name'\n \n def _getTargetClass(self):\n- from gcloud.dns.client import Client\n+ from google.cloud.dns.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor(self):\n- from gcloud.dns.connection import Connection\n+ from google.cloud.dns.connection import Connection\n creds = _Credentials()\n http = object()\n client = self._makeOne(project=self.PROJECT, credentials=creds,\n@@ -106,7 +106,7 @@ def test_quotas_w_kind_key(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_zones_defaults(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n ID_1 = '123'\n ZONE_1 = 'zone_one'\n DNS_1 = 'one.example.com'\n@@ -148,7 +148,7 @@ def test_list_zones_defaults(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_zones_explicit(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n ID_1 = '123'\n ZONE_1 = 'zone_one'\n DNS_1 = 'one.example.com'\n@@ -191,7 +191,7 @@ def test_list_zones_explicit(self):\n {'maxResults': 3, 'pageToken': TOKEN})\n \n def test_zone_explicit(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n DESCRIPTION = 'DESCRIPTION'\n DNS_NAME = 'test.example.com'\n creds = _Credentials()\n@@ -204,7 +204,7 @@ def test_zone_explicit(self):\n self.assertTrue(zone._client is client)\n \n def test_zone_w_dns_name_wo_description(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n DNS_NAME = 'test.example.com'\n creds = _Credentials()\n client = self._makeOne(self.PROJECT, creds)\n@@ -216,7 +216,7 @@ def test_zone_w_dns_name_wo_description(self):\n self.assertTrue(zone._client is client)\n \n def test_zone_wo_dns_name(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n creds = _Credentials()\n client = self._makeOne(self.PROJECT, creds)\n zone = client.zone(self.ZONE_NAME)\ndiff --git a/unit_tests/dns/test_connection.py b/unit_tests/dns/test_connection.py\n--- a/unit_tests/dns/test_connection.py\n+++ b/unit_tests/dns/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.dns.connection import Connection\n+ from google.cloud.dns.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/dns/test_resource_record_set.py b/unit_tests/dns/test_resource_record_set.py\n--- a/unit_tests/dns/test_resource_record_set.py\n+++ b/unit_tests/dns/test_resource_record_set.py\n@@ -18,7 +18,7 @@\n class TestResourceRecordSet(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n return ResourceRecordSet\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/dns/test_zone.py b/unit_tests/dns/test_zone.py\n--- a/unit_tests/dns/test_zone.py\n+++ b/unit_tests/dns/test_zone.py\n@@ -22,7 +22,7 @@ class TestManagedZone(unittest.TestCase):\n DNS_NAME = 'test.example.com'\n \n def _getTargetClass(self):\n- from gcloud.dns.zone import ManagedZone\n+ from google.cloud.dns.zone import ManagedZone\n return ManagedZone\n \n def _makeOne(self, *args, **kw):\n@@ -30,7 +30,7 @@ def _makeOne(self, *args, **kw):\n \n def _setUpConstants(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n year = 2015\n month = 7\n@@ -184,7 +184,7 @@ def test_name_server_set_setter(self):\n self.assertEqual(zone.name_server_set, 'NAME_SERVER_SET')\n \n def test_resource_record_set(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n RRS_NAME = 'other.example.com'\n RRS_TYPE = 'CNAME'\n TTL = 3600\n@@ -200,7 +200,7 @@ def test_resource_record_set(self):\n self.assertTrue(rrs.zone is zone)\n \n def test_changes(self):\n- from gcloud.dns.changes import Changes\n+ from google.cloud.dns.changes import Changes\n client = _Client(self.PROJECT)\n zone = self._makeOne(self.ZONE_NAME, self.DNS_NAME, client)\n changes = zone.changes()\n@@ -260,7 +260,7 @@ def test_create_w_alternate_client(self):\n self._verifyResourceProperties(zone, RESOURCE)\n \n def test_create_wo_dns_name_or_description(self):\n- from gcloud.exceptions import BadRequest\n+ from google.cloud.exceptions import BadRequest\n PATH = 'projects/%s/managedZones' % self.PROJECT\n \n _requested = []\n@@ -409,7 +409,7 @@ def test_delete_w_alternate_client(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_resource_record_sets_defaults(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n PATH = 'projects/%s/managedZones/%s/rrsets' % (\n self.PROJECT, self.ZONE_NAME)\n TOKEN = 'TOKEN'\n@@ -457,7 +457,7 @@ def test_list_resource_record_sets_defaults(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_resource_record_sets_explicit(self):\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n PATH = 'projects/%s/managedZones/%s/rrsets' % (\n self.PROJECT, self.ZONE_NAME)\n TOKEN = 'TOKEN'\n@@ -510,9 +510,9 @@ def test_list_resource_record_sets_explicit(self):\n {'maxResults': 3, 'pageToken': TOKEN})\n \n def test_list_changes_defaults(self):\n- from gcloud._helpers import _datetime_to_rfc3339\n- from gcloud.dns.changes import Changes\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud._helpers import _datetime_to_rfc3339\n+ from google.cloud.dns.changes import Changes\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n self._setUpConstants()\n PATH = 'projects/%s/managedZones/%s/changes' % (\n self.PROJECT, self.ZONE_NAME)\n@@ -586,9 +586,9 @@ def test_list_changes_defaults(self):\n self.assertEqual(req['path'], '/%s' % PATH)\n \n def test_list_changes_explicit(self):\n- from gcloud._helpers import _datetime_to_rfc3339\n- from gcloud.dns.changes import Changes\n- from gcloud.dns.resource_record_set import ResourceRecordSet\n+ from google.cloud._helpers import _datetime_to_rfc3339\n+ from google.cloud.dns.changes import Changes\n+ from google.cloud.dns.resource_record_set import ResourceRecordSet\n self._setUpConstants()\n PATH = 'projects/%s/managedZones/%s/changes' % (\n self.PROJECT, self.ZONE_NAME)\n@@ -681,7 +681,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/error_reporting/test_client.py b/unit_tests/error_reporting/test_client.py\n--- a/unit_tests/error_reporting/test_client.py\n+++ b/unit_tests/error_reporting/test_client.py\n@@ -19,11 +19,11 @@\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.error_reporting.client import Client\n+ from google.cloud.error_reporting.client import Client\n return Client\n \n def _getHttpContext(self):\n- from gcloud.error_reporting.client import HTTPContext\n+ from google.cloud.error_reporting.client import HTTPContext\n return HTTPContext\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/language/test_client.py b/unit_tests/language/test_client.py\n--- a/unit_tests/language/test_client.py\n+++ b/unit_tests/language/test_client.py\n@@ -18,14 +18,14 @@\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.client import Client\n+ from google.cloud.language.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor(self):\n- from gcloud.language.connection import Connection\n+ from google.cloud.language.connection import Connection\n \n creds = _Credentials()\n http = object()\n@@ -35,7 +35,7 @@ def test_ctor(self):\n self.assertTrue(client.connection.http is http)\n \n def test_document_from_text_factory(self):\n- from gcloud.language.document import Document\n+ from google.cloud.language.document import Document\n \n creds = _Credentials()\n client = self._makeOne(credentials=creds, http=object())\n@@ -59,7 +59,7 @@ def test_document_from_text_factory_failure(self):\n client.document_from_text('abc', doc_type='foo')\n \n def test_document_from_html_factory(self):\n- from gcloud.language.document import Document\n+ from google.cloud.language.document import Document\n \n creds = _Credentials()\n client = self._makeOne(credentials=creds, http=object())\n@@ -83,7 +83,7 @@ def test_document_from_html_factory_failure(self):\n client.document_from_html('abc', doc_type='foo')\n \n def test_document_from_url_factory(self):\n- from gcloud.language.document import Document\n+ from google.cloud.language.document import Document\n \n creds = _Credentials()\n client = self._makeOne(credentials=creds, http=object())\n@@ -97,8 +97,8 @@ def test_document_from_url_factory(self):\n self.assertEqual(document.doc_type, Document.PLAIN_TEXT)\n \n def test_document_from_url_factory_explicit(self):\n- from gcloud.language.document import Document\n- from gcloud.language.document import Encoding\n+ from google.cloud.language.document import Document\n+ from google.cloud.language.document import Encoding\n \n creds = _Credentials()\n client = self._makeOne(credentials=creds, http=object())\ndiff --git a/unit_tests/language/test_connection.py b/unit_tests/language/test_connection.py\n--- a/unit_tests/language/test_connection.py\n+++ b/unit_tests/language/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.connection import Connection\n+ from google.cloud.language.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/language/test_document.py b/unit_tests/language/test_document.py\n--- a/unit_tests/language/test_document.py\n+++ b/unit_tests/language/test_document.py\n@@ -40,7 +40,7 @@ def _make_token_json(name, part_of_speech, head, edge_label):\n \n \n def _get_token_and_sentences(include_syntax):\n- from gcloud.language.syntax import PartOfSpeech\n+ from google.cloud.language.syntax import PartOfSpeech\n \n if include_syntax:\n token_info = [\n@@ -68,7 +68,7 @@ def _get_token_and_sentences(include_syntax):\n \n \n def _get_entities(include_entities):\n- from gcloud.language.entity import EntityType\n+ from google.cloud.language.entity import EntityType\n \n if include_entities:\n entities = [\n@@ -98,14 +98,14 @@ def _get_entities(include_entities):\n class TestDocument(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.document import Document\n+ from google.cloud.language.document import Document\n return Document\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_constructor_defaults(self):\n- import gcloud.language.document as MUT\n+ import google.cloud.language.document as MUT\n \n client = object()\n content = 'abc'\n@@ -118,7 +118,7 @@ def test_constructor_defaults(self):\n self.assertEqual(document.encoding, MUT.Encoding.UTF8)\n \n def test_constructor_explicit(self):\n- import gcloud.language.document as MUT\n+ import google.cloud.language.document as MUT\n \n client = object()\n gcs_url = 'gs://some-bucket/some-obj.html'\n@@ -176,7 +176,7 @@ def test__to_dict_with_no_content(self):\n })\n \n def _verify_entity(self, entity, name, entity_type, wiki_url, salience):\n- from gcloud.language.entity import Entity\n+ from google.cloud.language.entity import Entity\n \n self.assertIsInstance(entity, Entity)\n self.assertEqual(entity.name, name)\n@@ -187,7 +187,7 @@ def _verify_entity(self, entity, name, entity_type, wiki_url, salience):\n self.assertEqual(entity.mentions, [name])\n \n def test_analyze_entities(self):\n- from gcloud.language.entity import EntityType\n+ from google.cloud.language.entity import EntityType\n \n name1 = 'R-O-C-K'\n name2 = 'USA'\n@@ -248,7 +248,7 @@ def test_analyze_entities(self):\n self.assertEqual(req['method'], 'POST')\n \n def _verify_sentiment(self, sentiment, polarity, magnitude):\n- from gcloud.language.sentiment import Sentiment\n+ from google.cloud.language.sentiment import Sentiment\n \n self.assertIsInstance(sentiment, Sentiment)\n self.assertEqual(sentiment.polarity, polarity)\n@@ -279,7 +279,7 @@ def test_analyze_sentiment(self):\n self.assertEqual(req['method'], 'POST')\n \n def _verify_sentences(self, include_syntax, annotations):\n- from gcloud.language.syntax import Sentence\n+ from google.cloud.language.syntax import Sentence\n \n if include_syntax:\n self.assertEqual(len(annotations.sentences), 1)\n@@ -291,7 +291,7 @@ def _verify_sentences(self, include_syntax, annotations):\n self.assertEqual(annotations.sentences, [])\n \n def _verify_tokens(self, annotations, token_info):\n- from gcloud.language.syntax import Token\n+ from google.cloud.language.syntax import Token\n \n self.assertEqual(len(annotations.tokens), len(token_info))\n for token, info in zip(annotations.tokens, token_info):\n@@ -305,8 +305,8 @@ def _verify_tokens(self, annotations, token_info):\n \n def _annotate_text_helper(self, include_sentiment,\n include_entities, include_syntax):\n- from gcloud.language.document import Annotations\n- from gcloud.language.entity import EntityType\n+ from google.cloud.language.document import Annotations\n+ from google.cloud.language.entity import EntityType\n \n token_info, sentences = _get_token_and_sentences(include_syntax)\n entities = _get_entities(include_entities)\ndiff --git a/unit_tests/language/test_entity.py b/unit_tests/language/test_entity.py\n--- a/unit_tests/language/test_entity.py\n+++ b/unit_tests/language/test_entity.py\n@@ -18,7 +18,7 @@\n class TestEntity(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.entity import Entity\n+ from google.cloud.language.entity import Entity\n return Entity\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/language/test_sentiment.py b/unit_tests/language/test_sentiment.py\n--- a/unit_tests/language/test_sentiment.py\n+++ b/unit_tests/language/test_sentiment.py\n@@ -18,7 +18,7 @@\n class TestSentiment(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.sentiment import Sentiment\n+ from google.cloud.language.sentiment import Sentiment\n return Sentiment\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/language/test_syntax.py b/unit_tests/language/test_syntax.py\n--- a/unit_tests/language/test_syntax.py\n+++ b/unit_tests/language/test_syntax.py\n@@ -18,7 +18,7 @@\n class TestPartOfSpeech(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.syntax import PartOfSpeech\n+ from google.cloud.language.syntax import PartOfSpeech\n return PartOfSpeech\n \n def test_reverse(self):\n@@ -36,14 +36,14 @@ def test_reverse(self):\n class TestToken(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.syntax import Token\n+ from google.cloud.language.syntax import Token\n return Token\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_constructor(self):\n- from gcloud.language.syntax import PartOfSpeech\n+ from google.cloud.language.syntax import PartOfSpeech\n \n text_content = 'All'\n text_begin = -1\n@@ -61,7 +61,7 @@ def test_constructor(self):\n self.assertEqual(token.lemma, lemma)\n \n def test_from_api_repr(self):\n- from gcloud.language.syntax import PartOfSpeech\n+ from google.cloud.language.syntax import PartOfSpeech\n \n klass = self._getTargetClass()\n text_content = 'pretty'\n@@ -96,7 +96,7 @@ def test_from_api_repr(self):\n class TestSentence(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.language.syntax import Sentence\n+ from google.cloud.language.syntax import Sentence\n return Sentence\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/logging/handlers/test_handlers.py b/unit_tests/logging/handlers/test_handlers.py\n--- a/unit_tests/logging/handlers/test_handlers.py\n+++ b/unit_tests/logging/handlers/test_handlers.py\n@@ -21,7 +21,7 @@ class TestCloudLoggingHandler(unittest.TestCase):\n PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.logging.handlers.handlers import CloudLoggingHandler\n+ from google.cloud.logging.handlers.handlers import CloudLoggingHandler\n return CloudLoggingHandler\n \n def _makeOne(self, *args, **kw):\n@@ -46,7 +46,7 @@ def test_emit(self):\n class TestSetupLogging(unittest.TestCase):\n \n def _callFUT(self, handler, excludes=None):\n- from gcloud.logging.handlers.handlers import setup_logging\n+ from google.cloud.logging.handlers.handlers import setup_logging\n if excludes:\n return setup_logging(handler, excluded_loggers=excludes)\n else:\ndiff --git a/unit_tests/logging/handlers/transports/test_background_thread.py b/unit_tests/logging/handlers/transports/test_background_thread.py\n--- a/unit_tests/logging/handlers/transports/test_background_thread.py\n+++ b/unit_tests/logging/handlers/transports/test_background_thread.py\n@@ -22,7 +22,7 @@ class TestBackgroundThreadHandler(unittest.TestCase):\n PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.logging.handlers.transports import (\n+ from google.cloud.logging.handlers.transports import (\n BackgroundThreadTransport)\n return BackgroundThreadTransport\n \n@@ -58,9 +58,8 @@ def test_send(self):\n class TestWorker(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.logging.handlers.transports.background_thread import (\n- _Worker)\n- return _Worker\n+ from google.cloud.logging.handlers.transports import background_thread\n+ return background_thread._Worker\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\ndiff --git a/unit_tests/logging/handlers/transports/test_base.py b/unit_tests/logging/handlers/transports/test_base.py\n--- a/unit_tests/logging/handlers/transports/test_base.py\n+++ b/unit_tests/logging/handlers/transports/test_base.py\n@@ -20,7 +20,7 @@ class TestBaseHandler(unittest.TestCase):\n PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.logging.handlers.transports import Transport\n+ from google.cloud.logging.handlers.transports import Transport\n return Transport\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/logging/handlers/transports/test_sync.py b/unit_tests/logging/handlers/transports/test_sync.py\n--- a/unit_tests/logging/handlers/transports/test_sync.py\n+++ b/unit_tests/logging/handlers/transports/test_sync.py\n@@ -21,7 +21,7 @@ class TestSyncHandler(unittest.TestCase):\n PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.logging.handlers.transports import SyncTransport\n+ from google.cloud.logging.handlers.transports import SyncTransport\n return SyncTransport\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/logging/test__gax.py b/unit_tests/logging/test__gax.py\n--- a/unit_tests/logging/test__gax.py\n+++ b/unit_tests/logging/test__gax.py\n@@ -17,7 +17,7 @@\n \n try:\n # pylint: disable=unused-import\n- import gcloud.logging._gax\n+ import google.cloud.logging._gax\n # pylint: enable=unused-import\n except ImportError: # pragma: NO COVER\n _HAVE_GAX = False\n@@ -41,7 +41,7 @@ class Test_LoggingAPI(_Base, unittest.TestCase):\n LOG_NAME = 'log_name'\n \n def _getTargetClass(self):\n- from gcloud.logging._gax import _LoggingAPI\n+ from google.cloud.logging._gax import _LoggingAPI\n return _LoggingAPI\n \n def test_ctor(self):\n@@ -51,7 +51,7 @@ def test_ctor(self):\n \n def test_list_entries_no_paging(self):\n from google.gax import INITIAL_PAGE\n- from gcloud.logging import DESCENDING\n+ from google.cloud.logging.client import DESCENDING\n from unit_tests._testing import _GAXPageIterator\n TOKEN = 'TOKEN'\n TEXT = 'TEXT'\n@@ -116,9 +116,9 @@ def test_list_entries_with_extra_properties(self):\n from datetime import datetime\n from google.logging.type.log_severity_pb2 import WARNING\n from unit_tests._testing import _GAXPageIterator\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _datetime_to_rfc3339\n- from gcloud._helpers import _datetime_to_pb_timestamp\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _datetime_to_rfc3339\n+ from google.cloud._helpers import _datetime_to_pb_timestamp\n NOW = datetime.utcnow().replace(tzinfo=UTC)\n SIZE = 23\n TOKEN = 'TOKEN'\n@@ -224,7 +224,7 @@ def test_write_entries_w_extra_properties(self):\n from datetime import datetime\n from google.logging.type.log_severity_pb2 import WARNING\n from google.logging.v2.log_entry_pb2 import LogEntry\n- from gcloud._helpers import UTC, _pb_timestamp_to_datetime\n+ from google.cloud._helpers import UTC, _pb_timestamp_to_datetime\n NOW = datetime.utcnow().replace(tzinfo=UTC)\n TEXT = 'TEXT'\n LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME)\n@@ -322,7 +322,7 @@ def test_write_entries_multiple(self):\n from google.logging.v2.log_entry_pb2 import LogEntry\n from google.protobuf.any_pb2 import Any\n from google.protobuf.struct_pb2 import Struct\n- from gcloud._helpers import _datetime_to_rfc3339, UTC\n+ from google.cloud._helpers import _datetime_to_rfc3339, UTC\n TEXT = 'TEXT'\n NOW = datetime.datetime.utcnow().replace(tzinfo=UTC)\n TIMESTAMP_TYPE_URL = 'type.googleapis.com/google.protobuf.Timestamp'\n@@ -409,7 +409,7 @@ def test_logger_delete(self):\n self.assertEqual(options, None)\n \n def test_logger_delete_not_found(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME)\n gax_api = _GAXLoggingAPI(_delete_not_found=True)\n api = self._makeOne(gax_api)\n@@ -442,7 +442,7 @@ class Test_SinksAPI(_Base, unittest.TestCase):\n DESTINATION_URI = 'faux.googleapis.com/destination'\n \n def _getTargetClass(self):\n- from gcloud.logging._gax import _SinksAPI\n+ from google.cloud.logging._gax import _SinksAPI\n return _SinksAPI\n \n def test_ctor(self):\n@@ -512,7 +512,7 @@ def test_sink_create_error(self):\n self.DESTINATION_URI)\n \n def test_sink_create_conflict(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n gax_api = _GAXSinksAPI(_create_sink_conflict=True)\n api = self._makeOne(gax_api)\n \n@@ -539,7 +539,7 @@ def test_sink_create_ok(self):\n self.assertEqual(options, None)\n \n def test_sink_get_error(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSinksAPI()\n api = self._makeOne(gax_api)\n \n@@ -584,7 +584,7 @@ def test_sink_update_error(self):\n self.DESTINATION_URI)\n \n def test_sink_update_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSinksAPI()\n api = self._makeOne(gax_api)\n \n@@ -621,7 +621,7 @@ def test_sink_delete_error(self):\n api.sink_delete(self.PROJECT, self.SINK_NAME)\n \n def test_sink_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSinksAPI(_sink_not_found=True)\n api = self._makeOne(gax_api)\n \n@@ -646,7 +646,7 @@ class Test_MetricsAPI(_Base, unittest.TestCase):\n DESCRIPTION = 'Description'\n \n def _getTargetClass(self):\n- from gcloud.logging._gax import _MetricsAPI\n+ from google.cloud.logging._gax import _MetricsAPI\n return _MetricsAPI\n \n def test_ctor(self):\n@@ -716,7 +716,7 @@ def test_metric_create_error(self):\n self.DESCRIPTION)\n \n def test_metric_create_conflict(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n gax_api = _GAXMetricsAPI(_create_log_metric_conflict=True)\n api = self._makeOne(gax_api)\n \n@@ -743,7 +743,7 @@ def test_metric_create_ok(self):\n self.assertEqual(options, None)\n \n def test_metric_get_error(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXMetricsAPI()\n api = self._makeOne(gax_api)\n \n@@ -788,7 +788,7 @@ def test_metric_update_error(self):\n self.DESCRIPTION)\n \n def test_metric_update_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXMetricsAPI()\n api = self._makeOne(gax_api)\n \n@@ -825,7 +825,7 @@ def test_metric_delete_error(self):\n api.metric_delete(self.PROJECT, self.METRIC_NAME)\n \n def test_metric_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXMetricsAPI(_log_metric_not_found=True)\n api = self._makeOne(gax_api)\n \n@@ -847,7 +847,7 @@ def test_metric_delete_hit(self):\n class Test_value_pb_to_value(_Base, unittest.TestCase):\n \n def _callFUT(self, value_pb):\n- from gcloud.logging._gax import _value_pb_to_value\n+ from google.cloud.logging._gax import _value_pb_to_value\n return _value_pb_to_value(value_pb)\n \n def test_w_null_values(self):\n@@ -1080,8 +1080,8 @@ def HasField(self, field_name):\n @staticmethod\n def _make_timestamp():\n from datetime import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _datetime_to_pb_timestamp\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _datetime_to_pb_timestamp\n NOW = datetime.utcnow().replace(tzinfo=UTC)\n return _datetime_to_pb_timestamp(NOW)\n \ndiff --git a/unit_tests/logging/test_client.py b/unit_tests/logging/test_client.py\n--- a/unit_tests/logging/test_client.py\n+++ b/unit_tests/logging/test_client.py\n@@ -27,7 +27,7 @@ class TestClient(unittest.TestCase):\n DESCRIPTION = 'DESCRIPTION'\n \n def _getTargetClass(self):\n- from gcloud.logging.client import Client\n+ from google.cloud.logging.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n@@ -39,8 +39,8 @@ def test_ctor(self):\n self.assertEqual(client.project, self.PROJECT)\n \n def test_logging_api_wo_gax(self):\n- from gcloud.logging.connection import _LoggingAPI\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging.connection import _LoggingAPI\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n client = self._makeOne(self.PROJECT, credentials=_Credentials())\n conn = client.connection = object()\n@@ -55,7 +55,7 @@ def test_logging_api_wo_gax(self):\n self.assertTrue(again is api)\n \n def test_logging_api_w_gax(self):\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n \n wrapped = object()\n@@ -86,8 +86,8 @@ def __init__(self, _wrapped):\n self.assertTrue(again is api)\n \n def test_sinks_api_wo_gax(self):\n- from gcloud.logging.connection import _SinksAPI\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging.connection import _SinksAPI\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n client = self._makeOne(self.PROJECT, credentials=_Credentials())\n conn = client.connection = object()\n@@ -102,7 +102,7 @@ def test_sinks_api_wo_gax(self):\n self.assertTrue(again is api)\n \n def test_sinks_api_w_gax(self):\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n \n wrapped = object()\n@@ -133,8 +133,8 @@ def __init__(self, _wrapped):\n self.assertTrue(again is api)\n \n def test_metrics_api_wo_gax(self):\n- from gcloud.logging.connection import _MetricsAPI\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging.connection import _MetricsAPI\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n client = self._makeOne(self.PROJECT, credentials=_Credentials())\n conn = client.connection = object()\n@@ -149,7 +149,7 @@ def test_metrics_api_wo_gax(self):\n self.assertTrue(again is api)\n \n def test_metrics_api_w_gax(self):\n- from gcloud.logging import client as MUT\n+ from google.cloud.logging import client as MUT\n from unit_tests._testing import _Monkey\n \n wrapped = object()\n@@ -180,7 +180,7 @@ def __init__(self, _wrapped):\n self.assertTrue(again is api)\n \n def test_logger(self):\n- from gcloud.logging.logger import Logger\n+ from google.cloud.logging.logger import Logger\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n logger = client.logger(self.LOGGER_NAME)\n@@ -198,7 +198,7 @@ def test__entry_from_resource_unknown_type(self):\n client._entry_from_resource({'unknownPayload': {}}, loggers)\n \n def test_list_entries_defaults(self):\n- from gcloud.logging.entries import TextEntry\n+ from google.cloud.logging.entries import TextEntry\n IID = 'IID'\n TEXT = 'TEXT'\n TOKEN = 'TOKEN'\n@@ -234,10 +234,10 @@ def test_list_entries_defaults(self):\n ([self.PROJECT], None, None, None, None))\n \n def test_list_entries_explicit(self):\n- from gcloud.logging import DESCENDING\n- from gcloud.logging.entries import ProtobufEntry\n- from gcloud.logging.entries import StructEntry\n- from gcloud.logging.logger import Logger\n+ from google.cloud.logging.client import DESCENDING\n+ from google.cloud.logging.entries import ProtobufEntry\n+ from google.cloud.logging.entries import StructEntry\n+ from google.cloud.logging.logger import Logger\n PROJECT1 = 'PROJECT1'\n PROJECT2 = 'PROJECT2'\n FILTER = 'logName:LOGNAME'\n@@ -301,7 +301,7 @@ def test_list_entries_explicit(self):\n ([PROJECT1, PROJECT2], FILTER, DESCENDING, PAGE_SIZE, TOKEN))\n \n def test_sink_defaults(self):\n- from gcloud.logging.sink import Sink\n+ from google.cloud.logging.sink import Sink\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n sink = client.sink(self.SINK_NAME)\n@@ -313,7 +313,7 @@ def test_sink_defaults(self):\n self.assertEqual(sink.project, self.PROJECT)\n \n def test_sink_explicit(self):\n- from gcloud.logging.sink import Sink\n+ from google.cloud.logging.sink import Sink\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n sink = client.sink(self.SINK_NAME, self.FILTER, self.DESTINATION_URI)\n@@ -325,7 +325,7 @@ def test_sink_explicit(self):\n self.assertEqual(sink.project, self.PROJECT)\n \n def test_list_sinks_no_paging(self):\n- from gcloud.logging.sink import Sink\n+ from google.cloud.logging.sink import Sink\n PROJECT = 'PROJECT'\n TOKEN = 'TOKEN'\n SINK_NAME = 'sink_name'\n@@ -353,7 +353,7 @@ def test_list_sinks_no_paging(self):\n (PROJECT, None, None))\n \n def test_list_sinks_with_paging(self):\n- from gcloud.logging.sink import Sink\n+ from google.cloud.logging.sink import Sink\n PROJECT = 'PROJECT'\n SINK_NAME = 'sink_name'\n FILTER = 'logName:syslog AND severity>=ERROR'\n@@ -381,7 +381,7 @@ def test_list_sinks_with_paging(self):\n (PROJECT, PAGE_SIZE, TOKEN))\n \n def test_metric_defaults(self):\n- from gcloud.logging.metric import Metric\n+ from google.cloud.logging.metric import Metric\n creds = _Credentials()\n \n client_obj = self._makeOne(project=self.PROJECT, credentials=creds)\n@@ -394,7 +394,7 @@ def test_metric_defaults(self):\n self.assertEqual(metric.project, self.PROJECT)\n \n def test_metric_explicit(self):\n- from gcloud.logging.metric import Metric\n+ from google.cloud.logging.metric import Metric\n creds = _Credentials()\n \n client_obj = self._makeOne(project=self.PROJECT, credentials=creds)\n@@ -408,7 +408,7 @@ def test_metric_explicit(self):\n self.assertEqual(metric.project, self.PROJECT)\n \n def test_list_metrics_no_paging(self):\n- from gcloud.logging.metric import Metric\n+ from google.cloud.logging.metric import Metric\n PROJECT = 'PROJECT'\n TOKEN = 'TOKEN'\n METRICS = [{\n@@ -433,7 +433,7 @@ def test_list_metrics_no_paging(self):\n (PROJECT, None, None))\n \n def test_list_metrics_with_paging(self):\n- from gcloud.logging.metric import Metric\n+ from google.cloud.logging.metric import Metric\n PROJECT = 'PROJECT'\n TOKEN = 'TOKEN'\n PAGE_SIZE = 42\ndiff --git a/unit_tests/logging/test_connection.py b/unit_tests/logging/test_connection.py\n--- a/unit_tests/logging/test_connection.py\n+++ b/unit_tests/logging/test_connection.py\n@@ -21,7 +21,7 @@ class TestConnection(unittest.TestCase):\n FILTER = 'logName:syslog AND severity>=ERROR'\n \n def _getTargetClass(self):\n- from gcloud.logging.connection import Connection\n+ from google.cloud.logging.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\n@@ -43,7 +43,7 @@ class Test_LoggingAPI(unittest.TestCase):\n FILTER = 'logName:syslog AND severity>=ERROR'\n \n def _getTargetClass(self):\n- from gcloud.logging.connection import _LoggingAPI\n+ from google.cloud.logging.connection import _LoggingAPI\n return _LoggingAPI\n \n def _makeOne(self, *args, **kw):\n@@ -57,7 +57,7 @@ def test_ctor(self):\n @staticmethod\n def _make_timestamp():\n from datetime import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n NOW = datetime.utcnow().replace(tzinfo=UTC)\n return _datetime_to_rfc3339_w_nanos(NOW)\n@@ -97,7 +97,7 @@ def test_list_entries_no_paging(self):\n self.assertEqual(conn._called_with['data'], SENT)\n \n def test_list_entries_w_paging(self):\n- from gcloud.logging import DESCENDING\n+ from google.cloud.logging.client import DESCENDING\n PROJECT1 = 'PROJECT1'\n PROJECT2 = 'PROJECT2'\n TIMESTAMP = self._make_timestamp()\n@@ -227,7 +227,7 @@ class Test_SinksAPI(unittest.TestCase):\n DESTINATION_URI = 'faux.googleapis.com/destination'\n \n def _getTargetClass(self):\n- from gcloud.logging.connection import _SinksAPI\n+ from google.cloud.logging.connection import _SinksAPI\n return _SinksAPI\n \n def _makeOne(self, *args, **kw):\n@@ -287,7 +287,7 @@ def test_list_sinks_w_paging(self):\n {'pageSize': PAGE_SIZE, 'pageToken': TOKEN})\n \n def test_sink_create_conflict(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n SENT = {\n 'name': self.SINK_NAME,\n 'filter': self.FILTER,\n@@ -325,7 +325,7 @@ def test_sink_create_ok(self):\n self.assertEqual(conn._called_with['data'], SENT)\n \n def test_sink_get_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n conn = _Connection()\n api = self._makeOne(conn)\n \n@@ -353,7 +353,7 @@ def test_sink_get_hit(self):\n self.assertEqual(conn._called_with['path'], path)\n \n def test_sink_update_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n SENT = {\n 'name': self.SINK_NAME,\n 'filter': self.FILTER,\n@@ -390,7 +390,7 @@ def test_sink_update_hit(self):\n self.assertEqual(conn._called_with['data'], SENT)\n \n def test_sink_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n conn = _Connection()\n api = self._makeOne(conn)\n \n@@ -422,7 +422,7 @@ class Test_MetricsAPI(unittest.TestCase):\n DESCRIPTION = 'DESCRIPTION'\n \n def _getTargetClass(self):\n- from gcloud.logging.connection import _MetricsAPI\n+ from google.cloud.logging.connection import _MetricsAPI\n return _MetricsAPI\n \n def _makeOne(self, *args, **kw):\n@@ -474,7 +474,7 @@ def test_list_metrics_w_paging(self):\n {'pageSize': PAGE_SIZE, 'pageToken': TOKEN})\n \n def test_metric_create_conflict(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n SENT = {\n 'name': self.METRIC_NAME,\n 'filter': self.FILTER,\n@@ -512,7 +512,7 @@ def test_metric_create_ok(self):\n self.assertEqual(conn._called_with['data'], SENT)\n \n def test_metric_get_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n conn = _Connection()\n api = self._makeOne(conn)\n \n@@ -540,7 +540,7 @@ def test_metric_get_hit(self):\n self.assertEqual(conn._called_with['path'], path)\n \n def test_metric_update_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n SENT = {\n 'name': self.METRIC_NAME,\n 'filter': self.FILTER,\n@@ -577,7 +577,7 @@ def test_metric_update_hit(self):\n self.assertEqual(conn._called_with['data'], SENT)\n \n def test_metric_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n conn = _Connection()\n api = self._makeOne(conn)\n \n@@ -621,8 +621,8 @@ def __init__(self, *responses):\n self._responses = responses\n \n def api_request(self, **kw):\n- from gcloud.exceptions import Conflict\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import Conflict\n+ from google.cloud.exceptions import NotFound\n self._called_with = kw\n if self._raise_conflict:\n raise Conflict('oops')\n@@ -634,6 +634,6 @@ def api_request(self, **kw):\n \n \n def _datetime_to_rfc3339_w_nanos(value):\n- from gcloud._helpers import _RFC3339_NO_FRACTION\n+ from google.cloud._helpers import _RFC3339_NO_FRACTION\n no_fraction = value.strftime(_RFC3339_NO_FRACTION)\n return '%s.%09dZ' % (no_fraction, value.microsecond * 1000)\ndiff --git a/unit_tests/logging/test_entries.py b/unit_tests/logging/test_entries.py\n--- a/unit_tests/logging/test_entries.py\n+++ b/unit_tests/logging/test_entries.py\n@@ -18,7 +18,7 @@\n class Test_logger_name_from_path(unittest.TestCase):\n \n def _callFUT(self, path):\n- from gcloud.logging.entries import logger_name_from_path\n+ from google.cloud.logging.entries import logger_name_from_path\n return logger_name_from_path(path)\n \n def test_w_simple_name(self):\n@@ -42,7 +42,7 @@ class Test_BaseEntry(unittest.TestCase):\n LOGGER_NAME = 'LOGGER_NAME'\n \n def _getTargetClass(self):\n- from gcloud.logging.entries import _BaseEntry\n+ from google.cloud.logging.entries import _BaseEntry\n \n class _Dummy(_BaseEntry):\n _PAYLOAD_KEY = 'dummyPayload'\n@@ -118,7 +118,7 @@ def test_from_api_repr_missing_data_no_loggers(self):\n \n def test_from_api_repr_w_loggers_no_logger_match(self):\n from datetime import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n klass = self._getTargetClass()\n client = _Client(self.PROJECT)\n PAYLOAD = 'PAYLOAD'\n@@ -162,7 +162,7 @@ def test_from_api_repr_w_loggers_no_logger_match(self):\n \n def test_from_api_repr_w_loggers_w_logger_match(self):\n from datetime import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n client = _Client(self.PROJECT)\n PAYLOAD = 'PAYLOAD'\n IID = 'IID'\n@@ -194,7 +194,7 @@ class TestProtobufEntry(unittest.TestCase):\n LOGGER_NAME = 'LOGGER_NAME'\n \n def _getTargetClass(self):\n- from gcloud.logging.entries import ProtobufEntry\n+ from google.cloud.logging.entries import ProtobufEntry\n return ProtobufEntry\n \n def _makeOne(self, *args, **kw):\n@@ -214,7 +214,7 @@ def test_parse_message(self):\n \n \n def _datetime_to_rfc3339_w_nanos(value):\n- from gcloud._helpers import _RFC3339_NO_FRACTION\n+ from google.cloud._helpers import _RFC3339_NO_FRACTION\n no_fraction = value.strftime(_RFC3339_NO_FRACTION)\n return '%s.%09dZ' % (no_fraction, value.microsecond * 1000)\n \ndiff --git a/unit_tests/logging/test_logger.py b/unit_tests/logging/test_logger.py\n--- a/unit_tests/logging/test_logger.py\n+++ b/unit_tests/logging/test_logger.py\n@@ -21,7 +21,7 @@ class TestLogger(unittest.TestCase):\n LOGGER_NAME = 'logger-name'\n \n def _getTargetClass(self):\n- from gcloud.logging.logger import Logger\n+ from google.cloud.logging.logger import Logger\n return Logger\n \n def _makeOne(self, *args, **kw):\n@@ -55,7 +55,7 @@ def test_ctor_explicit(self):\n self.assertEqual(logger.labels, LABELS)\n \n def test_batch_w_bound_client(self):\n- from gcloud.logging.logger import Batch\n+ from google.cloud.logging.logger import Batch\n conn = object()\n client = _Client(self.PROJECT, conn)\n logger = self._makeOne(self.LOGGER_NAME, client=client)\n@@ -65,7 +65,7 @@ def test_batch_w_bound_client(self):\n self.assertTrue(batch.client is client)\n \n def test_batch_w_alternate_client(self):\n- from gcloud.logging.logger import Batch\n+ from google.cloud.logging.logger import Batch\n conn1 = object()\n conn2 = object()\n client1 = _Client(self.PROJECT, conn1)\n@@ -364,7 +364,7 @@ def test_list_entries_defaults(self):\n self.assertEqual(client._listed, LISTED)\n \n def test_list_entries_explicit(self):\n- from gcloud.logging import DESCENDING\n+ from google.cloud.logging.client import DESCENDING\n PROJECT1 = 'PROJECT1'\n PROJECT2 = 'PROJECT2'\n FILTER = 'resource.type:global'\n@@ -393,7 +393,7 @@ class TestBatch(unittest.TestCase):\n PROJECT = 'test-project'\n \n def _getTargetClass(self):\n- from gcloud.logging.logger import Batch\n+ from google.cloud.logging.logger import Batch\n return Batch\n \n def _makeOne(self, *args, **kwargs):\n@@ -544,7 +544,7 @@ def test_commit_w_alternate_client(self):\n import json\n from google.protobuf.json_format import MessageToJson\n from google.protobuf.struct_pb2 import Struct, Value\n- from gcloud.logging.logger import Logger\n+ from google.cloud.logging.logger import Logger\n TEXT = 'This is the entry text'\n STRUCT = {'message': TEXT, 'weather': 'partly cloudy'}\n message = Struct(fields={'foo': Value(bool_value=True)})\n@@ -588,7 +588,7 @@ def test_context_mgr_success(self):\n import json\n from google.protobuf.json_format import MessageToJson\n from google.protobuf.struct_pb2 import Struct, Value\n- from gcloud.logging.logger import Logger\n+ from google.cloud.logging.logger import Logger\n TEXT = 'This is the entry text'\n STRUCT = {'message': TEXT, 'weather': 'partly cloudy'}\n message = Struct(fields={'foo': Value(bool_value=True)})\ndiff --git a/unit_tests/logging/test_metric.py b/unit_tests/logging/test_metric.py\n--- a/unit_tests/logging/test_metric.py\n+++ b/unit_tests/logging/test_metric.py\n@@ -23,7 +23,7 @@ class TestMetric(unittest.TestCase):\n DESCRIPTION = 'DESCRIPTION'\n \n def _getTargetClass(self):\n- from gcloud.logging.metric import Metric\n+ from google.cloud.logging.metric import Metric\n return Metric\n \n def _makeOne(self, *args, **kw):\n@@ -236,7 +236,7 @@ def metric_create(self, project, metric_name, filter_, description):\n project, metric_name, filter_, description)\n \n def metric_get(self, project, metric_name):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._metric_get_called_with = (project, metric_name)\n try:\n return self._metric_get_response\ndiff --git a/unit_tests/logging/test_sink.py b/unit_tests/logging/test_sink.py\n--- a/unit_tests/logging/test_sink.py\n+++ b/unit_tests/logging/test_sink.py\n@@ -23,7 +23,7 @@ class TestSink(unittest.TestCase):\n DESTINATION_URI = 'faux.googleapis.com/destination'\n \n def _getTargetClass(self):\n- from gcloud.logging.sink import Sink\n+ from google.cloud.logging.sink import Sink\n return Sink\n \n def _makeOne(self, *args, **kw):\n@@ -247,7 +247,7 @@ def sink_create(self, project, sink_name, filter_, destination):\n project, sink_name, filter_, destination)\n \n def sink_get(self, project, sink_name):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._sink_get_called_with = (project, sink_name)\n try:\n return self._sink_get_response\ndiff --git a/unit_tests/monitoring/test__dataframe.py b/unit_tests/monitoring/test__dataframe.py\n--- a/unit_tests/monitoring/test__dataframe.py\n+++ b/unit_tests/monitoring/test__dataframe.py\n@@ -54,16 +54,16 @@\n \n def parse_timestamps(): # pragma: NO COVER\n import datetime\n- from gcloud._helpers import _RFC3339_MICROS\n+ from google.cloud._helpers import _RFC3339_MICROS\n return [datetime.datetime.strptime(t, _RFC3339_MICROS)\n for t in TIMESTAMPS]\n \n \n def generate_query_results(): # pragma: NO COVER\n- from gcloud.monitoring.metric import Metric\n- from gcloud.monitoring.resource import Resource\n- from gcloud.monitoring.timeseries import Point\n- from gcloud.monitoring.timeseries import TimeSeries\n+ from google.cloud.monitoring.metric import Metric\n+ from google.cloud.monitoring.resource import Resource\n+ from google.cloud.monitoring.timeseries import Point\n+ from google.cloud.monitoring.timeseries import TimeSeries\n \n def P(timestamp, value):\n return Point(\n@@ -87,7 +87,7 @@ def P(timestamp, value):\n class Test__build_dataframe(unittest.TestCase): # pragma: NO COVER\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.monitoring._dataframe import _build_dataframe\n+ from google.cloud.monitoring._dataframe import _build_dataframe\n return _build_dataframe(*args, **kwargs)\n \n def test_both_label_and_labels_illegal(self):\n@@ -208,19 +208,19 @@ def test_empty_table_smart_labels(self):\n class Test__sorted_resource_labels(unittest.TestCase):\n \n def _callFUT(self, labels):\n- from gcloud.monitoring._dataframe import _sorted_resource_labels\n+ from google.cloud.monitoring._dataframe import _sorted_resource_labels\n return _sorted_resource_labels(labels)\n \n def test_empty(self):\n self.assertEqual(self._callFUT([]), [])\n \n def test_sorted(self):\n- from gcloud.monitoring._dataframe import TOP_RESOURCE_LABELS\n+ from google.cloud.monitoring._dataframe import TOP_RESOURCE_LABELS\n EXPECTED = TOP_RESOURCE_LABELS + ('other-1', 'other-2')\n self.assertSequenceEqual(self._callFUT(EXPECTED), EXPECTED)\n \n def test_reversed(self):\n- from gcloud.monitoring._dataframe import TOP_RESOURCE_LABELS\n+ from google.cloud.monitoring._dataframe import TOP_RESOURCE_LABELS\n EXPECTED = TOP_RESOURCE_LABELS + ('other-1', 'other-2')\n INPUT = list(reversed(EXPECTED))\n self.assertSequenceEqual(self._callFUT(INPUT), EXPECTED)\ndiff --git a/unit_tests/monitoring/test_client.py b/unit_tests/monitoring/test_client.py\n--- a/unit_tests/monitoring/test_client.py\n+++ b/unit_tests/monitoring/test_client.py\n@@ -20,7 +20,7 @@\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.client import Client\n+ from google.cloud.monitoring.client import Client\n return Client\n \n def _makeOne(self, *args, **kwargs):\n@@ -28,8 +28,8 @@ def _makeOne(self, *args, **kwargs):\n \n def test_query(self):\n import datetime\n- from gcloud._helpers import _datetime_to_rfc3339\n- from gcloud.exceptions import NotFound\n+ from google.cloud._helpers import _datetime_to_rfc3339\n+ from google.cloud.exceptions import NotFound\n \n START_TIME = datetime.datetime(2016, 4, 6, 22, 5, 0)\n END_TIME = datetime.datetime(2016, 4, 6, 22, 10, 0)\n@@ -185,7 +185,7 @@ def test_resource_factory(self):\n def test_timeseries_factory_gauge(self):\n import datetime\n from unit_tests._testing import _Monkey\n- import gcloud.monitoring.client\n+ import google.cloud.monitoring.client\n METRIC_TYPE = 'custom.googleapis.com/my_metric'\n METRIC_LABELS = {\n 'status': 'successful'\n@@ -218,7 +218,7 @@ def test_timeseries_factory_gauge(self):\n TIME2 = datetime.datetime.utcnow()\n # Construct a time series assuming a gauge metric using the current\n # time\n- with _Monkey(gcloud.monitoring.client, _UTCNOW=lambda: TIME2):\n+ with _Monkey(google.cloud.monitoring.client, _UTCNOW=lambda: TIME2):\n timeseries_no_end = client.time_series(metric, resource, VALUE)\n \n self.assertEqual(timeseries_no_end.points[0].end_time, TIME2)\n@@ -562,7 +562,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kwargs):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kwargs)\n try:\n return self._responses.pop(0)\ndiff --git a/unit_tests/monitoring/test_connection.py b/unit_tests/monitoring/test_connection.py\n--- a/unit_tests/monitoring/test_connection.py\n+++ b/unit_tests/monitoring/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.connection import Connection\n+ from google.cloud.monitoring.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kwargs):\ndiff --git a/unit_tests/monitoring/test_group.py b/unit_tests/monitoring/test_group.py\n--- a/unit_tests/monitoring/test_group.py\n+++ b/unit_tests/monitoring/test_group.py\n@@ -18,7 +18,7 @@\n class Test_group_id_from_name(unittest.TestCase):\n \n def _callFUT(self, path, project):\n- from gcloud.monitoring.group import _group_id_from_name\n+ from google.cloud.monitoring.group import _group_id_from_name\n return _group_id_from_name(path, project)\n \n def test_w_empty_name(self):\n@@ -86,7 +86,7 @@ def setUp(self):\n }\n \n def _setUpResources(self):\n- from gcloud.monitoring.resource import Resource\n+ from google.cloud.monitoring.resource import Resource\n info1 = {\n 'type': 'gce_instance',\n 'labels': {\n@@ -108,7 +108,7 @@ def _setUpResources(self):\n self.MEMBERS = [info1, info2]\n \n def _getTargetClass(self):\n- from gcloud.monitoring.group import Group\n+ from google.cloud.monitoring.group import Group\n return Group\n \n def _makeOne(self, *args, **kwargs):\n@@ -350,7 +350,7 @@ def test_list(self):\n self.assertEqual(request, expected_request)\n \n def test_list_paged(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n LIST_OF_GROUPS = [self.JSON_GROUP, self.JSON_PARENT]\n TOKEN = 'second-page-please'\n@@ -483,7 +483,7 @@ def test_list_members_paged(self):\n \n def test_list_members_w_all_arguments(self):\n import datetime\n- from gcloud._helpers import _datetime_to_rfc3339\n+ from google.cloud._helpers import _datetime_to_rfc3339\n \n self._setUpResources()\n \n@@ -532,7 +532,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kwargs):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kwargs)\n try:\n return self._responses.pop(0)\ndiff --git a/unit_tests/monitoring/test_label.py b/unit_tests/monitoring/test_label.py\n--- a/unit_tests/monitoring/test_label.py\n+++ b/unit_tests/monitoring/test_label.py\n@@ -18,7 +18,7 @@\n class TestLabelValueType(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.label import LabelValueType\n+ from google.cloud.monitoring.label import LabelValueType\n return LabelValueType\n \n def test_one(self):\n@@ -33,7 +33,7 @@ def test_names(self):\n class TestLabelDescriptor(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.label import LabelDescriptor\n+ from google.cloud.monitoring.label import LabelDescriptor\n return LabelDescriptor\n \n def _makeOne(self, *args, **kwargs):\ndiff --git a/unit_tests/monitoring/test_metric.py b/unit_tests/monitoring/test_metric.py\n--- a/unit_tests/monitoring/test_metric.py\n+++ b/unit_tests/monitoring/test_metric.py\n@@ -18,7 +18,7 @@\n class TestMetricKind(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.metric import MetricKind\n+ from google.cloud.monitoring.metric import MetricKind\n return MetricKind\n \n def test_one(self):\n@@ -33,7 +33,7 @@ def test_names(self):\n class TestValueType(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.metric import ValueType\n+ from google.cloud.monitoring.metric import ValueType\n return ValueType\n \n def test_one(self):\n@@ -48,14 +48,14 @@ def test_names(self):\n class TestMetricDescriptor(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.metric import MetricDescriptor\n+ from google.cloud.monitoring.metric import MetricDescriptor\n return MetricDescriptor\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_constructor(self):\n- from gcloud.monitoring.label import LabelDescriptor\n+ from google.cloud.monitoring.label import LabelDescriptor\n \n TYPE = 'appengine.googleapis.com/http/server/response_count'\n NAME = 'projects/my-project/metricDescriptors/' + TYPE\n@@ -384,7 +384,7 @@ def test_list(self):\n self.assertEqual(request, expected_request)\n \n def test_list_paged(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n PROJECT = 'my-project'\n PATH = 'projects/{project}/metricDescriptors/'.format(project=PROJECT)\n@@ -493,7 +493,7 @@ def test_list_filtered_by_type_prefix(self):\n class TestMetric(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.metric import Metric\n+ from google.cloud.monitoring.metric import Metric\n return Metric\n \n def _makeOne(self, *args, **kwargs):\n@@ -538,7 +538,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kwargs):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kwargs)\n try:\n return self._responses.pop(0)\ndiff --git a/unit_tests/monitoring/test_query.py b/unit_tests/monitoring/test_query.py\n--- a/unit_tests/monitoring/test_query.py\n+++ b/unit_tests/monitoring/test_query.py\n@@ -43,7 +43,7 @@\n class TestAligner(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.query import Aligner\n+ from google.cloud.monitoring.query import Aligner\n return Aligner\n \n def test_one(self):\n@@ -58,7 +58,7 @@ def test_names(self):\n class TestReducer(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.query import Reducer\n+ from google.cloud.monitoring.query import Reducer\n return Reducer\n \n def test_one(self):\n@@ -74,7 +74,7 @@ def test_names(self):\n class TestQuery(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.query import Query\n+ from google.cloud.monitoring.query import Query\n return Query\n \n def _makeOne(self, *args, **kwargs):\n@@ -82,7 +82,7 @@ def _makeOne(self, *args, **kwargs):\n \n @staticmethod\n def _make_timestamp(value):\n- from gcloud._helpers import _datetime_to_rfc3339\n+ from google.cloud._helpers import _datetime_to_rfc3339\n return _datetime_to_rfc3339(value)\n \n def test_constructor_minimal(self):\n@@ -127,7 +127,7 @@ def test_constructor_maximal(self):\n def test_constructor_default_end_time(self):\n import datetime\n from unit_tests._testing import _Monkey\n- from gcloud.monitoring import query as MUT\n+ from google.cloud.monitoring import query as MUT\n \n MINUTES = 5\n NOW, T0, T1 = [\n@@ -334,7 +334,7 @@ def test_iteration(self):\n def test_iteration_paged(self):\n import copy\n import datetime\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n T0 = datetime.datetime(2016, 4, 6, 22, 5, 0)\n T1 = datetime.datetime(2016, 4, 6, 22, 10, 0)\n@@ -500,7 +500,7 @@ def test_iteration_headers_only(self):\n class Test_Filter(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.query import _Filter\n+ from google.cloud.monitoring.query import _Filter\n return _Filter\n \n def _makeOne(self, metric_type):\n@@ -534,7 +534,7 @@ def test_maximal(self):\n class Test__build_label_filter(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.monitoring.query import _build_label_filter\n+ from google.cloud.monitoring.query import _build_label_filter\n return _build_label_filter(*args, **kwargs)\n \n def test_no_labels(self):\n@@ -630,7 +630,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kwargs):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kwargs)\n try:\n return self._responses.pop(0)\ndiff --git a/unit_tests/monitoring/test_resource.py b/unit_tests/monitoring/test_resource.py\n--- a/unit_tests/monitoring/test_resource.py\n+++ b/unit_tests/monitoring/test_resource.py\n@@ -18,14 +18,14 @@\n class TestResourceDescriptor(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.resource import ResourceDescriptor\n+ from google.cloud.monitoring.resource import ResourceDescriptor\n return ResourceDescriptor\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_constructor(self):\n- from gcloud.monitoring.label import LabelDescriptor\n+ from google.cloud.monitoring.label import LabelDescriptor\n \n TYPE = 'gce_instance'\n NAME = 'projects/my-project/monitoredResourceDescriptors/' + TYPE\n@@ -192,7 +192,7 @@ def test_list(self):\n self.assertEqual(request, expected_request)\n \n def test_list_paged(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n PROJECT = 'my-project'\n PATH = 'projects/{project}/monitoredResourceDescriptors/'.format(\n@@ -277,7 +277,7 @@ def test_list_filtered(self):\n class TestResource(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.resource import Resource\n+ from google.cloud.monitoring.resource import Resource\n return Resource\n \n def _makeOne(self, *args, **kwargs):\n@@ -324,7 +324,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kwargs):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kwargs)\n try:\n return self._responses.pop(0)\ndiff --git a/unit_tests/monitoring/test_timeseries.py b/unit_tests/monitoring/test_timeseries.py\n--- a/unit_tests/monitoring/test_timeseries.py\n+++ b/unit_tests/monitoring/test_timeseries.py\n@@ -35,16 +35,16 @@\n class TestTimeSeries(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.timeseries import TimeSeries\n+ from google.cloud.monitoring.timeseries import TimeSeries\n return TimeSeries\n \n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n \n def test_constructor(self):\n- from gcloud.monitoring.metric import Metric\n- from gcloud.monitoring.resource import Resource\n- from gcloud.monitoring.timeseries import Point\n+ from google.cloud.monitoring.metric import Metric\n+ from google.cloud.monitoring.resource import Resource\n+ from google.cloud.monitoring.timeseries import Point\n \n VALUE = 60 # seconds\n \n@@ -151,7 +151,7 @@ def test_labels(self):\n class TestPoint(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.monitoring.timeseries import Point\n+ from google.cloud.monitoring.timeseries import Point\n return Point\n \n def _makeOne(self, *args, **kwargs):\ndiff --git a/unit_tests/pubsub/test__gax.py b/unit_tests/pubsub/test__gax.py\n--- a/unit_tests/pubsub/test__gax.py\n+++ b/unit_tests/pubsub/test__gax.py\n@@ -17,7 +17,7 @@\n \n try:\n # pylint: disable=unused-import\n- import gcloud.pubsub._gax\n+ import google.cloud.pubsub._gax\n # pylint: enable=unused-import\n except ImportError: # pragma: NO COVER\n _HAVE_GAX = False\n@@ -45,7 +45,7 @@ def _makeOne(self, *args, **kw):\n class Test_PublisherAPI(_Base, unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.pubsub._gax import _PublisherAPI\n+ from google.cloud.pubsub._gax import _PublisherAPI\n return _PublisherAPI\n \n def test_ctor(self):\n@@ -111,7 +111,7 @@ def test_topic_create(self):\n self.assertEqual(options, None)\n \n def test_topic_create_already_exists(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n gax_api = _GAXPublisherAPI(_create_topic_conflict=True)\n api = self._makeOne(gax_api)\n \n@@ -147,7 +147,7 @@ def test_topic_get_hit(self):\n self.assertEqual(options, None)\n \n def test_topic_get_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXPublisherAPI()\n api = self._makeOne(gax_api)\n \n@@ -181,7 +181,7 @@ def test_topic_delete_hit(self):\n self.assertEqual(options, None)\n \n def test_topic_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXPublisherAPI(_delete_topic_ok=False)\n api = self._makeOne(gax_api)\n \n@@ -226,7 +226,7 @@ def test_topic_publish_hit(self):\n \n def test_topic_publish_miss_w_attrs_w_bytes_payload(self):\n import base64\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n PAYLOAD = b'This is the message text'\n B64 = base64.b64encode(PAYLOAD)\n MESSAGE = {'data': B64, 'attributes': {'foo': 'bar'}}\n@@ -314,7 +314,7 @@ def test_topic_list_subscriptions_with_paging(self):\n \n def test_topic_list_subscriptions_miss(self):\n from google.gax import INITIAL_PAGE\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXPublisherAPI()\n api = self._makeOne(gax_api)\n \n@@ -349,7 +349,7 @@ class Test_SubscriberAPI(_Base, unittest.TestCase):\n PUSH_ENDPOINT = 'https://api.example.com/push'\n \n def _getTargetClass(self):\n- from gcloud.pubsub._gax import _SubscriberAPI\n+ from google.cloud.pubsub._gax import _SubscriberAPI\n return _SubscriberAPI\n \n def test_ctor(self):\n@@ -432,7 +432,7 @@ def test_subscription_create(self):\n self.assertEqual(options, None)\n \n def test_subscription_create_already_exists(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n DEADLINE = 600\n gax_api = _GAXSubscriberAPI(_create_subscription_conflict=True)\n api = self._makeOne(gax_api)\n@@ -487,7 +487,7 @@ def test_subscription_get_hit(self):\n self.assertEqual(options, None)\n \n def test_subscription_get_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSubscriberAPI()\n api = self._makeOne(gax_api)\n \n@@ -521,7 +521,7 @@ def test_subscription_delete_hit(self):\n self.assertEqual(options, None)\n \n def test_subscription_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSubscriberAPI(_delete_subscription_ok=False)\n api = self._makeOne(gax_api)\n \n@@ -556,7 +556,7 @@ def test_subscription_modify_push_config_hit(self):\n self.assertEqual(options, None)\n \n def test_subscription_modify_push_config_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSubscriberAPI()\n api = self._makeOne(gax_api)\n \n@@ -609,7 +609,7 @@ def test_subscription_pull_explicit(self):\n self.assertEqual(options, None)\n \n def test_subscription_pull_defaults_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n gax_api = _GAXSubscriberAPI()\n api = self._makeOne(gax_api)\n \n@@ -652,7 +652,7 @@ def test_subscription_acknowledge_hit(self):\n self.assertEqual(options, None)\n \n def test_subscription_acknowledge_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n ACK_ID1 = 'DEADBEEF'\n ACK_ID2 = 'BEADCAFE'\n gax_api = _GAXSubscriberAPI()\n@@ -699,7 +699,7 @@ def test_subscription_modify_ack_deadline_hit(self):\n self.assertEqual(options, None)\n \n def test_subscription_modify_ack_deadline_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n ACK_ID1 = 'DEADBEEF'\n ACK_ID2 = 'BEADCAFE'\n NEW_DEADLINE = 90\ndiff --git a/unit_tests/pubsub/test__helpers.py b/unit_tests/pubsub/test__helpers.py\n--- a/unit_tests/pubsub/test__helpers.py\n+++ b/unit_tests/pubsub/test__helpers.py\n@@ -18,7 +18,7 @@\n class Test_topic_name_from_path(unittest.TestCase):\n \n def _callFUT(self, path, project):\n- from gcloud.pubsub._helpers import topic_name_from_path\n+ from google.cloud.pubsub._helpers import topic_name_from_path\n return topic_name_from_path(path, project)\n \n def test_w_simple_name(self):\n@@ -39,7 +39,7 @@ def test_w_name_w_all_extras(self):\n class Test_subscription_name_from_path(unittest.TestCase):\n \n def _callFUT(self, path, project):\n- from gcloud.pubsub._helpers import subscription_name_from_path\n+ from google.cloud.pubsub._helpers import subscription_name_from_path\n return subscription_name_from_path(path, project)\n \n def test_w_simple_name(self):\ndiff --git a/unit_tests/pubsub/test_client.py b/unit_tests/pubsub/test_client.py\n--- a/unit_tests/pubsub/test_client.py\n+++ b/unit_tests/pubsub/test_client.py\n@@ -23,15 +23,15 @@ class TestClient(unittest.TestCase):\n SUB_PATH = 'projects/%s/subscriptions/%s' % (PROJECT, SUB_NAME)\n \n def _getTargetClass(self):\n- from gcloud.pubsub.client import Client\n+ from google.cloud.pubsub.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_publisher_api_wo_gax(self):\n- from gcloud.pubsub.connection import _PublisherAPI\n- from gcloud.pubsub import client as MUT\n+ from google.cloud.pubsub.connection import _PublisherAPI\n+ from google.cloud.pubsub import client as MUT\n from unit_tests._testing import _Monkey\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n@@ -47,7 +47,7 @@ def test_publisher_api_wo_gax(self):\n self.assertTrue(again is api)\n \n def test_publisher_api_w_gax(self):\n- from gcloud.pubsub import client as MUT\n+ from google.cloud.pubsub import client as MUT\n from unit_tests._testing import _Monkey\n \n wrapped = object()\n@@ -78,8 +78,8 @@ def __init__(self, _wrapped):\n self.assertTrue(again is api)\n \n def test_subscriber_api_wo_gax(self):\n- from gcloud.pubsub.connection import _SubscriberAPI\n- from gcloud.pubsub import client as MUT\n+ from google.cloud.pubsub.connection import _SubscriberAPI\n+ from google.cloud.pubsub import client as MUT\n from unit_tests._testing import _Monkey\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n@@ -95,7 +95,7 @@ def test_subscriber_api_wo_gax(self):\n self.assertTrue(again is api)\n \n def test_subscriber_api_w_gax(self):\n- from gcloud.pubsub import client as MUT\n+ from google.cloud.pubsub import client as MUT\n from unit_tests._testing import _Monkey\n \n wrapped = object()\n@@ -126,7 +126,7 @@ def __init__(self, _wrapped):\n self.assertTrue(again is api)\n \n def test_iam_policy_api(self):\n- from gcloud.pubsub.connection import _IAMPolicyAPI\n+ from google.cloud.pubsub.connection import _IAMPolicyAPI\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n conn = client.connection = object()\n@@ -138,7 +138,7 @@ def test_iam_policy_api(self):\n self.assertTrue(again is api)\n \n def test_list_topics_no_paging(self):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n client.connection = object()\n@@ -155,7 +155,7 @@ def test_list_topics_no_paging(self):\n self.assertEqual(api._listed_topics, (self.PROJECT, None, None))\n \n def test_list_topics_with_paging(self):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n TOKEN1 = 'TOKEN1'\n TOKEN2 = 'TOKEN2'\n SIZE = 1\n@@ -189,7 +189,7 @@ def test_list_topics_missing_key(self):\n self.assertEqual(api._listed_topics, (self.PROJECT, None, None))\n \n def test_list_subscriptions_no_paging(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n SUB_INFO = {'name': self.SUB_PATH, 'topic': self.TOPIC_PATH}\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\n@@ -209,7 +209,7 @@ def test_list_subscriptions_no_paging(self):\n (self.PROJECT, None, None))\n \n def test_list_subscriptions_with_paging(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n SUB_INFO = {'name': self.SUB_PATH, 'topic': self.TOPIC_PATH}\n creds = _Credentials()\n client = self._makeOne(project=self.PROJECT, credentials=creds)\ndiff --git a/unit_tests/pubsub/test_connection.py b/unit_tests/pubsub/test_connection.py\n--- a/unit_tests/pubsub/test_connection.py\n+++ b/unit_tests/pubsub/test_connection.py\n@@ -32,7 +32,7 @@ def _makeOne(self, *args, **kw):\n class TestConnection(_Base):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.connection import Connection\n+ from google.cloud.pubsub.connection import Connection\n return Connection\n \n def test_default_url(self):\n@@ -43,7 +43,7 @@ def test_default_url(self):\n def test_custom_url_from_env(self):\n import os\n from unit_tests._testing import _Monkey\n- from gcloud.environment_vars import PUBSUB_EMULATOR\n+ from google.cloud.environment_vars import PUBSUB_EMULATOR\n \n HOST = 'localhost:8187'\n fake_environ = {PUBSUB_EMULATOR: HOST}\n@@ -66,7 +66,7 @@ def test_custom_url_from_constructor(self):\n def test_custom_url_constructor_and_env(self):\n import os\n from unit_tests._testing import _Monkey\n- from gcloud.environment_vars import PUBSUB_EMULATOR\n+ from google.cloud.environment_vars import PUBSUB_EMULATOR\n \n HOST1 = object()\n HOST2 = object()\n@@ -117,7 +117,7 @@ def test_build_api_url_w_base_url_override(self):\n class Test_PublisherAPI(_Base):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.connection import _PublisherAPI\n+ from google.cloud.pubsub.connection import _PublisherAPI\n return _PublisherAPI\n \n def _makeOne(self, *args, **kw):\n@@ -200,7 +200,7 @@ def test_topic_create(self):\n self.assertEqual(connection._called_with['path'], path)\n \n def test_topic_create_already_exists(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n connection = _Connection()\n connection._no_response_error = Conflict\n api = self._makeOne(connection)\n@@ -225,7 +225,7 @@ def test_topic_get_hit(self):\n self.assertEqual(connection._called_with['path'], path)\n \n def test_topic_get_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n connection = _Connection()\n api = self._makeOne(connection)\n \n@@ -248,7 +248,7 @@ def test_topic_delete_hit(self):\n self.assertEqual(connection._called_with['path'], path)\n \n def test_topic_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n connection = _Connection()\n api = self._makeOne(connection)\n \n@@ -280,7 +280,7 @@ def test_topic_publish_hit(self):\n \n def test_topic_publish_miss(self):\n import base64\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n PAYLOAD = b'This is the message text'\n B64 = base64.b64encode(PAYLOAD).decode('ascii')\n MESSAGE = {'data': B64, 'attributes': {}}\n@@ -362,7 +362,7 @@ def test_topic_list_subscriptions_missing_key(self):\n self.assertEqual(connection._called_with['query_params'], {})\n \n def test_topic_list_subscriptions_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n connection = _Connection()\n api = self._makeOne(connection)\n \n@@ -378,7 +378,7 @@ def test_topic_list_subscriptions_miss(self):\n class Test_SubscriberAPI(_Base):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.connection import _SubscriberAPI\n+ from google.cloud.pubsub.connection import _SubscriberAPI\n return _SubscriberAPI\n \n def _makeOne(self, *args, **kw):\n@@ -631,7 +631,7 @@ def test_subscription_modify_ack_deadline(self):\n class Test_IAMPolicyAPI(_Base):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.connection import _IAMPolicyAPI\n+ from google.cloud.pubsub.connection import _IAMPolicyAPI\n return _IAMPolicyAPI\n \n def test_ctor(self):\n@@ -640,7 +640,10 @@ def test_ctor(self):\n self.assertTrue(api._connection is connection)\n \n def test_get_iam_policy(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n OWNER1 = 'user:phred@example.com'\n OWNER2 = 'group:cloud-logs@google.com'\n EDITOR1 = 'domain:google.com'\n@@ -667,7 +670,10 @@ def test_get_iam_policy(self):\n self.assertEqual(connection._called_with['path'], path)\n \n def test_set_iam_policy(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n OWNER1 = 'user:phred@example.com'\n OWNER2 = 'group:cloud-logs@google.com'\n EDITOR1 = 'domain:google.com'\n@@ -697,7 +703,10 @@ def test_set_iam_policy(self):\n {'policy': POLICY})\n \n def test_test_iam_permissions(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ALL_ROLES = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE]\n ALLOWED = ALL_ROLES[1:]\n RETURNED = {'permissions': ALLOWED}\n@@ -714,7 +723,10 @@ def test_test_iam_permissions(self):\n {'permissions': ALL_ROLES})\n \n def test_test_iam_permissions_missing_key(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ALL_ROLES = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE]\n RETURNED = {}\n connection = _Connection(RETURNED)\n@@ -739,7 +751,7 @@ def __init__(self, *responses):\n self._responses = responses\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._called_with = kw\n try:\n response, self._responses = self._responses[0], self._responses[1:]\ndiff --git a/unit_tests/pubsub/test_iam.py b/unit_tests/pubsub/test_iam.py\n--- a/unit_tests/pubsub/test_iam.py\n+++ b/unit_tests/pubsub/test_iam.py\n@@ -18,7 +18,7 @@\n class TestPolicy(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.iam import Policy\n+ from google.cloud.pubsub.iam import Policy\n return Policy\n \n def _makeOne(self, *args, **kw):\n@@ -91,7 +91,7 @@ def test_from_api_repr_only_etag(self):\n self.assertEqual(list(policy.viewers), [])\n \n def test_from_api_repr_complete(self):\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import (\n OWNER_ROLE,\n EDITOR_ROLE,\n VIEWER_ROLE,\n@@ -150,7 +150,7 @@ def test_to_api_repr_only_etag(self):\n self.assertEqual(policy.to_api_repr(), {'etag': 'DEADBEEF'})\n \n def test_to_api_repr_full(self):\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import (\n PUBSUB_ADMIN_ROLE,\n PUBSUB_EDITOR_ROLE,\n PUBSUB_VIEWER_ROLE,\ndiff --git a/unit_tests/pubsub/test_message.py b/unit_tests/pubsub/test_message.py\n--- a/unit_tests/pubsub/test_message.py\n+++ b/unit_tests/pubsub/test_message.py\n@@ -18,7 +18,7 @@\n class TestMessage(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.message import Message\n+ from google.cloud.pubsub.message import Message\n return Message\n \n def _makeOne(self, *args, **kw):\n@@ -68,8 +68,8 @@ def _to_fail():\n \n def test_timestamp_w_timestamp_in_attributes(self):\n from datetime import datetime\n- from gcloud._helpers import _RFC3339_MICROS\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import _RFC3339_MICROS\n+ from google.cloud._helpers import UTC\n DATA = b'DEADBEEF'\n MESSAGE_ID = b'12345'\n TIMESTAMP = '2015-04-10T18:42:27.131956Z'\ndiff --git a/unit_tests/pubsub/test_subscription.py b/unit_tests/pubsub/test_subscription.py\n--- a/unit_tests/pubsub/test_subscription.py\n+++ b/unit_tests/pubsub/test_subscription.py\n@@ -25,7 +25,7 @@ class TestSubscription(unittest.TestCase):\n ENDPOINT = 'https://api.example.com/push'\n \n def _getTargetClass(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n return Subscription\n \n def _makeOne(self, *args, **kw):\n@@ -68,7 +68,7 @@ def test_ctor_w_neither_topic_nor_client(self):\n self._makeOne(self.SUB_NAME)\n \n def test_from_api_repr_no_topics(self):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n resource = {'topic': self.TOPIC_PATH,\n 'name': self.SUB_PATH,\n 'ackDeadlineSeconds': self.DEADLINE,\n@@ -99,7 +99,7 @@ def test_from_api_repr_w_deleted_topic(self):\n self.assertEqual(subscription.push_endpoint, self.ENDPOINT)\n \n def test_from_api_repr_w_topics_no_topic_match(self):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n resource = {'topic': self.TOPIC_PATH,\n 'name': self.SUB_PATH,\n 'ackDeadlineSeconds': self.DEADLINE,\n@@ -144,7 +144,7 @@ def test_full_name_and_path(self):\n self.assertEqual(subscription.path, SUB_PATH)\n \n def test_autoack_defaults(self):\n- from gcloud.pubsub.subscription import AutoAck\n+ from google.cloud.pubsub.subscription import AutoAck\n client = _Client(project=self.PROJECT)\n topic = _Topic(self.TOPIC_NAME, client=client)\n subscription = self._makeOne(self.SUB_NAME, topic)\n@@ -156,7 +156,7 @@ def test_autoack_defaults(self):\n self.assertTrue(auto_ack._client is None)\n \n def test_autoack_explicit(self):\n- from gcloud.pubsub.subscription import AutoAck\n+ from google.cloud.pubsub.subscription import AutoAck\n client1 = _Client(project=self.PROJECT)\n client2 = _Client(project=self.PROJECT)\n topic = _Topic(self.TOPIC_NAME, client=client1)\n@@ -323,7 +323,7 @@ def test_modify_push_config_wo_endpoint_w_alternate_client(self):\n \n def test_pull_wo_return_immediately_max_messages_w_bound_client(self):\n import base64\n- from gcloud.pubsub.message import Message\n+ from google.cloud.pubsub.message import Message\n ACK_ID = 'DEADBEEF'\n MSG_ID = 'BEADCAFE'\n PAYLOAD = b'This is the message text'\n@@ -350,7 +350,7 @@ def test_pull_wo_return_immediately_max_messages_w_bound_client(self):\n \n def test_pull_w_return_immediately_w_max_messages_w_alt_client(self):\n import base64\n- from gcloud.pubsub.message import Message\n+ from google.cloud.pubsub.message import Message\n ACK_ID = 'DEADBEEF'\n MSG_ID = 'BEADCAFE'\n PAYLOAD = b'This is the message text'\n@@ -450,7 +450,7 @@ def test_modify_ack_deadline_w_alternate_client(self):\n (self.SUB_PATH, [ACK_ID1, ACK_ID2], self.DEADLINE))\n \n def test_get_iam_policy_w_bound_client(self):\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import (\n PUBSUB_ADMIN_ROLE,\n PUBSUB_EDITOR_ROLE,\n PUBSUB_VIEWER_ROLE,\n@@ -515,8 +515,8 @@ def test_get_iam_policy_w_alternate_client(self):\n self.assertEqual(api._got_iam_policy, self.SUB_PATH)\n \n def test_set_iam_policy_w_bound_client(self):\n- from gcloud.pubsub.iam import Policy\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import Policy\n+ from google.cloud.pubsub.iam import (\n PUBSUB_ADMIN_ROLE,\n PUBSUB_EDITOR_ROLE,\n PUBSUB_VIEWER_ROLE,\n@@ -572,7 +572,7 @@ def test_set_iam_policy_w_bound_client(self):\n self.assertEqual(api._set_iam_policy, (self.SUB_PATH, POLICY))\n \n def test_set_iam_policy_w_alternate_client(self):\n- from gcloud.pubsub.iam import Policy\n+ from google.cloud.pubsub.iam import Policy\n RESPONSE = {'etag': 'ACAB'}\n client1 = _Client(project=self.PROJECT)\n client2 = _Client(project=self.PROJECT)\n@@ -592,7 +592,10 @@ def test_set_iam_policy_w_alternate_client(self):\n self.assertEqual(api._set_iam_policy, (self.SUB_PATH, {}))\n \n def test_check_iam_permissions_w_bound_client(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ROLES = [VIEWER_ROLE, EDITOR_ROLE, OWNER_ROLE]\n client = _Client(project=self.PROJECT)\n api = client.iam_policy_api = _FauxIAMPolicy()\n@@ -607,7 +610,10 @@ def test_check_iam_permissions_w_bound_client(self):\n (self.SUB_PATH, ROLES))\n \n def test_check_iam_permissions_w_alternate_client(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ROLES = [VIEWER_ROLE, EDITOR_ROLE, OWNER_ROLE]\n client1 = _Client(project=self.PROJECT)\n client2 = _Client(project=self.PROJECT)\n@@ -632,7 +638,7 @@ def subscription_create(self, subscription_path, topic_path,\n return self._subscription_create_response\n \n def subscription_get(self, subscription_path):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._subscription_got = subscription_path\n try:\n return self._subscription_get_response\n@@ -669,7 +675,7 @@ def subscription_modify_ack_deadline(self, subscription_path, ack_ids,\n class TestAutoAck(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.pubsub.subscription import AutoAck\n+ from google.cloud.pubsub.subscription import AutoAck\n return AutoAck\n \n def _makeOne(self, *args, **kw):\n@@ -774,7 +780,7 @@ def __init__(self, project):\n self.project = project\n \n def topic(self, name, timestamp_messages=False):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n return Topic(name, client=self, timestamp_messages=timestamp_messages)\n \n \ndiff --git a/unit_tests/pubsub/test_topic.py b/unit_tests/pubsub/test_topic.py\n--- a/unit_tests/pubsub/test_topic.py\n+++ b/unit_tests/pubsub/test_topic.py\n@@ -21,7 +21,7 @@ class TestTopic(unittest.TestCase):\n TOPIC_PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME)\n \n def _getTargetClass(self):\n- from gcloud.pubsub.topic import Topic\n+ from google.cloud.pubsub.topic import Topic\n return Topic\n \n def _makeOne(self, *args, **kw):\n@@ -138,8 +138,8 @@ def test_publish_single_bytes_wo_attrs_w_bound_client(self):\n def test_publish_single_bytes_wo_attrs_w_add_timestamp_alt_client(self):\n import base64\n import datetime\n- from gcloud.pubsub import topic as MUT\n- from gcloud._helpers import _RFC3339_MICROS\n+ from google.cloud.pubsub import topic as MUT\n+ from google.cloud._helpers import _RFC3339_MICROS\n from unit_tests._testing import _Monkey\n NOW = datetime.datetime.utcnow()\n \n@@ -287,7 +287,7 @@ def test_publish_multiple_error(self):\n self.assertEqual(getattr(api, '_topic_published', self), self)\n \n def test_subscription(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n client = _Client(project=self.PROJECT)\n topic = self._makeOne(self.TOPIC_NAME, client=client)\n \n@@ -298,7 +298,7 @@ def test_subscription(self):\n self.assertTrue(subscription.topic is topic)\n \n def test_list_subscriptions_no_paging(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n SUB_NAME_1 = 'subscription_1'\n SUB_PATH_1 = 'projects/%s/subscriptions/%s' % (\n self.PROJECT, SUB_NAME_1)\n@@ -332,7 +332,7 @@ def test_list_subscriptions_no_paging(self):\n (self.TOPIC_PATH, None, None))\n \n def test_list_subscriptions_with_paging(self):\n- from gcloud.pubsub.subscription import Subscription\n+ from google.cloud.pubsub.subscription import Subscription\n SUB_NAME_1 = 'subscription_1'\n SUB_PATH_1 = 'projects/%s/subscriptions/%s' % (\n self.PROJECT, SUB_NAME_1)\n@@ -382,7 +382,7 @@ def test_list_subscriptions_missing_key(self):\n (self.TOPIC_PATH, None, None))\n \n def test_get_iam_policy_w_bound_client(self):\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import (\n PUBSUB_ADMIN_ROLE,\n PUBSUB_EDITOR_ROLE,\n PUBSUB_VIEWER_ROLE,\n@@ -447,8 +447,8 @@ def test_get_iam_policy_w_alternate_client(self):\n self.assertEqual(api._got_iam_policy, self.TOPIC_PATH)\n \n def test_set_iam_policy_w_bound_client(self):\n- from gcloud.pubsub.iam import Policy\n- from gcloud.pubsub.iam import (\n+ from google.cloud.pubsub.iam import Policy\n+ from google.cloud.pubsub.iam import (\n PUBSUB_ADMIN_ROLE,\n PUBSUB_EDITOR_ROLE,\n PUBSUB_VIEWER_ROLE,\n@@ -509,7 +509,7 @@ def test_set_iam_policy_w_bound_client(self):\n self.assertEqual(api._set_iam_policy, (self.TOPIC_PATH, POLICY))\n \n def test_set_iam_policy_w_alternate_client(self):\n- from gcloud.pubsub.iam import Policy\n+ from google.cloud.pubsub.iam import Policy\n RESPONSE = {'etag': 'ACAB'}\n \n client1 = _Client(project=self.PROJECT)\n@@ -530,7 +530,10 @@ def test_set_iam_policy_w_alternate_client(self):\n self.assertEqual(api._set_iam_policy, (self.TOPIC_PATH, {}))\n \n def test_check_iam_permissions_w_bound_client(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ROLES = [VIEWER_ROLE, EDITOR_ROLE, OWNER_ROLE]\n client = _Client(project=self.PROJECT)\n api = client.iam_policy_api = _FauxIAMPolicy()\n@@ -544,7 +547,10 @@ def test_check_iam_permissions_w_bound_client(self):\n (self.TOPIC_PATH, ROLES))\n \n def test_check_iam_permissions_w_alternate_client(self):\n- from gcloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE\n+ from google.cloud.pubsub.iam import OWNER_ROLE\n+ from google.cloud.pubsub.iam import EDITOR_ROLE\n+ from google.cloud.pubsub.iam import VIEWER_ROLE\n+\n ROLES = [VIEWER_ROLE, EDITOR_ROLE, OWNER_ROLE]\n client1 = _Client(project=self.PROJECT)\n client2 = _Client(project=self.PROJECT)\n@@ -563,7 +569,7 @@ class TestBatch(unittest.TestCase):\n PROJECT = 'PROJECT'\n \n def _getTargetClass(self):\n- from gcloud.pubsub.topic import Batch\n+ from google.cloud.pubsub.topic import Batch\n return Batch\n \n def _makeOne(self, *args, **kwargs):\n@@ -735,7 +741,7 @@ def topic_create(self, topic_path):\n return self._topic_create_response\n \n def topic_get(self, topic_path):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._topic_got = topic_path\n try:\n return self._topic_get_response\ndiff --git a/unit_tests/resource_manager/test_client.py b/unit_tests/resource_manager/test_client.py\n--- a/unit_tests/resource_manager/test_client.py\n+++ b/unit_tests/resource_manager/test_client.py\n@@ -18,7 +18,7 @@\n class Test__ProjectIterator(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.resource_manager.client import _ProjectIterator\n+ from google.cloud.resource_manager.client import _ProjectIterator\n return _ProjectIterator\n \n def _makeOne(self, *args, **kw):\n@@ -39,7 +39,7 @@ def test_get_items_from_response_empty(self):\n self.assertEqual(list(iterator.get_items_from_response({})), [])\n \n def test_get_items_from_response_non_empty(self):\n- from gcloud.resource_manager.project import Project\n+ from google.cloud.resource_manager.project import Project\n \n PROJECT_ID = 'project-id'\n PROJECT_NAME = 'My Project Name'\n@@ -72,14 +72,14 @@ def test_get_items_from_response_non_empty(self):\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.resource_manager.client import Client\n+ from google.cloud.resource_manager.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_constructor(self):\n- from gcloud.resource_manager.connection import Connection\n+ from google.cloud.resource_manager.connection import Connection\n \n http = object()\n credentials = _Credentials()\n@@ -89,7 +89,7 @@ def test_constructor(self):\n self.assertEqual(client.connection._http, http)\n \n def test_new_project_factory(self):\n- from gcloud.resource_manager.project import Project\n+ from google.cloud.resource_manager.project import Project\n \n credentials = _Credentials()\n client = self._makeOne(credentials=credentials)\n@@ -105,7 +105,7 @@ def test_new_project_factory(self):\n self.assertEqual(project.labels, labels)\n \n def test_fetch_project(self):\n- from gcloud.resource_manager.project import Project\n+ from google.cloud.resource_manager.project import Project\n \n project_id = 'project-id'\n project_number = 123\n@@ -132,7 +132,7 @@ def test_fetch_project(self):\n self.assertEqual(project.labels, labels)\n \n def test_list_projects_return_type(self):\n- from gcloud.resource_manager.client import _ProjectIterator\n+ from google.cloud.resource_manager.client import _ProjectIterator\n \n credentials = _Credentials()\n client = self._makeOne(credentials=credentials)\ndiff --git a/unit_tests/resource_manager/test_connection.py b/unit_tests/resource_manager/test_connection.py\n--- a/unit_tests/resource_manager/test_connection.py\n+++ b/unit_tests/resource_manager/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.resource_manager.connection import Connection\n+ from google.cloud.resource_manager.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/resource_manager/test_project.py b/unit_tests/resource_manager/test_project.py\n--- a/unit_tests/resource_manager/test_project.py\n+++ b/unit_tests/resource_manager/test_project.py\n@@ -18,7 +18,7 @@\n class TestProject(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.resource_manager.project import Project\n+ from google.cloud.resource_manager.project import Project\n return Project\n \n def _makeOne(self, *args, **kw):\n@@ -323,7 +323,7 @@ def __init__(self, *responses):\n self._requested = []\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n try:\ndiff --git a/unit_tests/storage/test__helpers.py b/unit_tests/storage/test__helpers.py\n--- a/unit_tests/storage/test__helpers.py\n+++ b/unit_tests/storage/test__helpers.py\n@@ -18,7 +18,7 @@\n class Test_PropertyMixin(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage._helpers import _PropertyMixin\n+ from google.cloud.storage._helpers import _PropertyMixin\n return _PropertyMixin\n \n def _makeOne(self, *args, **kw):\n@@ -97,7 +97,7 @@ def test_patch(self):\n class Test__scalar_property(unittest.TestCase):\n \n def _callFUT(self, fieldName):\n- from gcloud.storage._helpers import _scalar_property\n+ from google.cloud.storage._helpers import _scalar_property\n return _scalar_property(fieldName)\n \n def test_getter(self):\n@@ -125,7 +125,7 @@ def _patch_property(self, name, value):\n class Test__base64_md5hash(unittest.TestCase):\n \n def _callFUT(self, bytes_to_sign):\n- from gcloud.storage._helpers import _base64_md5hash\n+ from google.cloud.storage._helpers import _base64_md5hash\n return _base64_md5hash(bytes_to_sign)\n \n def test_it(self):\n@@ -140,7 +140,7 @@ def test_it(self):\n \n def test_it_with_stubs(self):\n from unit_tests._testing import _Monkey\n- from gcloud.storage import _helpers as MUT\n+ from google.cloud.storage import _helpers as MUT\n \n class _Buffer(object):\n \ndiff --git a/unit_tests/storage/test_acl.py b/unit_tests/storage/test_acl.py\n--- a/unit_tests/storage/test_acl.py\n+++ b/unit_tests/storage/test_acl.py\n@@ -18,7 +18,7 @@\n class Test_ACLEntity(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n return _ACLEntity\n \n def _makeOne(self, *args, **kw):\n@@ -127,7 +127,7 @@ def test_revoke_owner(self):\n class Test_ACL(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.acl import ACL\n+ from google.cloud.storage.acl import ACL\n return ACL\n \n def _makeOne(self, *args, **kw):\n@@ -267,7 +267,7 @@ def _reload():\n self.assertTrue(acl.loaded)\n \n def test_has_entity_miss_entity(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n TYPE = 'type'\n ID = 'id'\n entity = _ACLEntity(TYPE, ID)\n@@ -307,7 +307,7 @@ def _reload():\n self.assertTrue(acl.loaded)\n \n def test_get_entity_miss_entity_no_default(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n TYPE = 'type'\n ID = 'id'\n entity = _ACLEntity(TYPE, ID)\n@@ -322,7 +322,7 @@ def test_get_entity_miss_str_w_default(self):\n self.assertTrue(acl.get_entity('nonesuch', DEFAULT) is DEFAULT)\n \n def test_get_entity_miss_entity_w_default(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n DEFAULT = object()\n TYPE = 'type'\n ID = 'id'\n@@ -348,7 +348,7 @@ def test_get_entity_hit_entity(self):\n self.assertTrue(acl.has_entity(entity))\n \n def test_add_entity_miss_eager(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n TYPE = 'type'\n ID = 'id'\n ROLE = 'role'\n@@ -363,7 +363,7 @@ def test_add_entity_miss_eager(self):\n self.assertEqual(list(acl.get_entities()), [entity])\n \n def test_add_entity_miss_lazy(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n TYPE = 'type'\n ID = 'id'\n ROLE = 'role'\n@@ -383,7 +383,7 @@ def _reload():\n self.assertTrue(acl.loaded)\n \n def test_add_entity_hit(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n TYPE = 'type'\n ID = 'id'\n ENTITY_VAL = '%s-%s' % (TYPE, ID)\n@@ -510,7 +510,7 @@ def test_get_entities_nonempty(self):\n self.assertEqual(acl.get_entities(), [entity])\n \n def test_reload_missing(self):\n- # https://github.com/GoogleCloudPlatform/gcloud-python/issues/652\n+ # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/652\n ROLE = 'role'\n connection = _Connection({})\n client = _Client(connection)\n@@ -711,7 +711,7 @@ def test_clear(self):\n class Test_BucketACL(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.acl import BucketACL\n+ from google.cloud.storage.acl import BucketACL\n return BucketACL\n \n def _makeOne(self, *args, **kw):\n@@ -731,7 +731,7 @@ def test_ctor(self):\n class Test_DefaultObjectACL(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.acl import DefaultObjectACL\n+ from google.cloud.storage.acl import DefaultObjectACL\n return DefaultObjectACL\n \n def _makeOne(self, *args, **kw):\n@@ -751,7 +751,7 @@ def test_ctor(self):\n class Test_ObjectACL(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.acl import ObjectACL\n+ from google.cloud.storage.acl import ObjectACL\n return ObjectACL\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/storage/test_batch.py b/unit_tests/storage/test_batch.py\n--- a/unit_tests/storage/test_batch.py\n+++ b/unit_tests/storage/test_batch.py\n@@ -18,7 +18,7 @@\n class TestMIMEApplicationHTTP(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.batch import MIMEApplicationHTTP\n+ from google.cloud.storage.batch import MIMEApplicationHTTP\n return MIMEApplicationHTTP\n \n def _makeOne(self, *args, **kw):\n@@ -69,7 +69,7 @@ def test_ctor_body_dict(self):\n class TestBatch(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.batch import Batch\n+ from google.cloud.storage.batch import Batch\n return Batch\n \n def _makeOne(self, *args, **kw):\n@@ -85,7 +85,7 @@ def test_ctor(self):\n self.assertEqual(len(batch._target_objects), 0)\n \n def test_current(self):\n- from gcloud.storage.client import Client\n+ from google.cloud.storage.client import Client\n project = 'PROJECT'\n credentials = _Credentials()\n client = Client(project=project, credentials=credentials)\n@@ -100,7 +100,7 @@ def test_current(self):\n self.assertTrue(batch1.current() is batch2)\n \n def test__make_request_GET_normal(self):\n- from gcloud.storage.batch import _FutureDict\n+ from google.cloud.storage.batch import _FutureDict\n URL = 'http://example.com/api'\n expected = _Response()\n http = _HTTP((expected, ''))\n@@ -126,7 +126,7 @@ def test__make_request_GET_normal(self):\n self.assertEqual(solo_request[3], None)\n \n def test__make_request_POST_normal(self):\n- from gcloud.storage.batch import _FutureDict\n+ from google.cloud.storage.batch import _FutureDict\n URL = 'http://example.com/api'\n http = _HTTP() # no requests expected\n connection = _Connection(http=http)\n@@ -151,7 +151,7 @@ def test__make_request_POST_normal(self):\n self.assertEqual(solo_request[3], {'foo': 1})\n \n def test__make_request_PATCH_normal(self):\n- from gcloud.storage.batch import _FutureDict\n+ from google.cloud.storage.batch import _FutureDict\n URL = 'http://example.com/api'\n http = _HTTP() # no requests expected\n connection = _Connection(http=http)\n@@ -176,7 +176,7 @@ def test__make_request_PATCH_normal(self):\n self.assertEqual(solo_request[3], {'foo': 1})\n \n def test__make_request_DELETE_normal(self):\n- from gcloud.storage.batch import _FutureDict\n+ from google.cloud.storage.batch import _FutureDict\n URL = 'http://example.com/api'\n http = _HTTP() # no requests expected\n connection = _Connection(http=http)\n@@ -315,7 +315,7 @@ def test_finish_responses_mismatch(self):\n self.assertRaises(ValueError, batch.finish)\n \n def test_finish_nonempty_with_status_failure(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n URL = 'http://api.example.com/other_api'\n expected = _Response()\n expected['content-type'] = 'multipart/mixed; boundary=\"DEADBEEF=\"'\n@@ -370,7 +370,7 @@ def test_finish_nonempty_non_multipart_response(self):\n self.assertRaises(ValueError, batch.finish)\n \n def test_as_context_mgr_wo_error(self):\n- from gcloud.storage.client import Client\n+ from google.cloud.storage.client import Client\n URL = 'http://example.com/api'\n expected = _Response()\n expected['content-type'] = 'multipart/mixed; boundary=\"DEADBEEF=\"'\n@@ -406,8 +406,8 @@ def test_as_context_mgr_wo_error(self):\n self.assertEqual(target3._properties, '')\n \n def test_as_context_mgr_w_error(self):\n- from gcloud.storage.batch import _FutureDict\n- from gcloud.storage.client import Client\n+ from google.cloud.storage.batch import _FutureDict\n+ from google.cloud.storage.client import Client\n URL = 'http://example.com/api'\n http = _HTTP()\n connection = _Connection(http=http)\n@@ -447,7 +447,7 @@ def test_as_context_mgr_w_error(self):\n class Test__unpack_batch_response(unittest.TestCase):\n \n def _callFUT(self, response, content):\n- from gcloud.storage.batch import _unpack_batch_response\n+ from google.cloud.storage.batch import _unpack_batch_response\n return _unpack_batch_response(response, content)\n \n def _unpack_helper(self, response, content):\n@@ -538,7 +538,7 @@ def test_unicode(self):\n class Test__FutureDict(unittest.TestCase):\n \n def _makeOne(self, *args, **kw):\n- from gcloud.storage.batch import _FutureDict\n+ from google.cloud.storage.batch import _FutureDict\n return _FutureDict(*args, **kw)\n \n def test_get(self):\ndiff --git a/unit_tests/storage/test_blob.py b/unit_tests/storage/test_blob.py\n--- a/unit_tests/storage/test_blob.py\n+++ b/unit_tests/storage/test_blob.py\n@@ -18,7 +18,7 @@\n class Test_Blob(unittest.TestCase):\n \n def _makeOne(self, *args, **kw):\n- from gcloud.storage.blob import Blob\n+ from google.cloud.storage.blob import Blob\n properties = kw.pop('properties', None)\n blob = Blob(*args, **kw)\n blob._properties = properties or {}\n@@ -36,7 +36,7 @@ def test_ctor(self):\n self.assertTrue(blob._acl.blob is blob)\n \n def test_chunk_size_ctor(self):\n- from gcloud.storage.blob import Blob\n+ from google.cloud.storage.blob import Blob\n BLOB_NAME = 'blob-name'\n BUCKET = object()\n chunk_size = 10 * Blob._CHUNK_SIZE_MULTIPLE\n@@ -71,7 +71,7 @@ def test_chunk_size_setter_bad_value(self):\n blob.chunk_size = 11\n \n def test_acl_property(self):\n- from gcloud.storage.acl import ObjectACL\n+ from google.cloud.storage.acl import ObjectACL\n FAKE_BUCKET = _Bucket()\n blob = self._makeOne(None, bucket=FAKE_BUCKET)\n acl = blob.acl\n@@ -119,7 +119,7 @@ def test_public_url_w_slash_in_name(self):\n \n def _basic_generate_signed_url_helper(self, credentials=None):\n from unit_tests._testing import _Monkey\n- from gcloud.storage import blob as MUT\n+ from google.cloud.storage import blob as MUT\n \n BLOB_NAME = 'blob-name'\n EXPIRATION = '2014-10-16T20:34:37.000Z'\n@@ -158,7 +158,7 @@ def test_generate_signed_url_w_default_method(self):\n \n def test_generate_signed_url_w_content_type(self):\n from unit_tests._testing import _Monkey\n- from gcloud.storage import blob as MUT\n+ from google.cloud.storage import blob as MUT\n \n BLOB_NAME = 'blob-name'\n EXPIRATION = '2014-10-16T20:34:37.000Z'\n@@ -196,7 +196,7 @@ def test_generate_signed_url_w_credentials(self):\n \n def test_generate_signed_url_w_slash_in_name(self):\n from unit_tests._testing import _Monkey\n- from gcloud.storage import blob as MUT\n+ from google.cloud.storage import blob as MUT\n \n BLOB_NAME = 'parent/child'\n EXPIRATION = '2014-10-16T20:34:37.000Z'\n@@ -227,7 +227,7 @@ def test_generate_signed_url_w_slash_in_name(self):\n \n def test_generate_signed_url_w_method_arg(self):\n from unit_tests._testing import _Monkey\n- from gcloud.storage import blob as MUT\n+ from google.cloud.storage import blob as MUT\n \n BLOB_NAME = 'blob-name'\n EXPIRATION = '2014-10-16T20:34:37.000Z'\n@@ -511,7 +511,7 @@ def test_upload_from_file_stream(self):\n from six.moves.http_client import OK\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n \n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n@@ -608,7 +608,7 @@ def test_upload_from_file_simple(self):\n \n def test_upload_from_file_simple_not_found(self):\n from six.moves.http_client import NOT_FOUND\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n with self.assertRaises(NotFound):\n self._upload_from_file_simple_test_helper(status=NOT_FOUND)\n \n@@ -643,8 +643,8 @@ def test_upload_from_file_resumable(self):\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _Monkey\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.streaming import http_wrapper\n- from gcloud.streaming import transfer\n+ from google.cloud.streaming import http_wrapper\n+ from google.cloud.streaming import transfer\n \n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n@@ -727,8 +727,8 @@ def test_upload_from_file_resumable_w_error(self):\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _Monkey\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.streaming import transfer\n- from gcloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming import transfer\n+ from google.cloud.streaming.exceptions import HttpError\n \n BLOB_NAME = 'blob-name'\n DATA = b'ABCDEF'\n@@ -780,7 +780,7 @@ def test_upload_from_file_w_slash_in_name(self):\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n \n BLOB_NAME = 'parent/child'\n UPLOAD_URL = 'http://example.com/upload/name/parent%2Fchild'\n@@ -830,7 +830,7 @@ def test_upload_from_filename_w_key(self):\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n \n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n@@ -889,7 +889,7 @@ def _upload_from_filename_test_helper(self, properties=None,\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _NamedTemporaryFile\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n \n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n@@ -959,7 +959,7 @@ def test_upload_from_string_w_bytes(self):\n from six.moves.http_client import OK\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n DATA = b'ABCDEF'\n@@ -998,7 +998,7 @@ def test_upload_from_string_w_text(self):\n from six.moves.http_client import OK\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n BLOB_NAME = 'blob-name'\n UPLOAD_URL = 'http://example.com/upload/name/key'\n DATA = u'ABCDEF\\u1234'\n@@ -1038,7 +1038,7 @@ def test_upload_from_string_text_w_key(self):\n from six.moves.http_client import OK\n from six.moves.urllib.parse import parse_qsl\n from six.moves.urllib.parse import urlsplit\n- from gcloud.streaming import http_wrapper\n+ from google.cloud.streaming import http_wrapper\n BLOB_NAME = 'blob-name'\n KEY = 'aa426195405adee2c8081bb9e7e74b19'\n HEADER_KEY_VALUE = 'YWE0MjYxOTU0MDVhZGVlMmM4MDgxYmI5ZTdlNzRiMTk='\n@@ -1084,7 +1084,7 @@ def test_upload_from_string_text_w_key(self):\n \n def test_make_public(self):\n from six.moves.http_client import OK\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n BLOB_NAME = 'blob-name'\n permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]\n after = ({'status': OK}, {'acl': permissive})\n@@ -1368,8 +1368,8 @@ def test_storage_class(self):\n \n def test_time_deleted(self):\n import datetime\n- from gcloud._helpers import _RFC3339_MICROS\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import _RFC3339_MICROS\n+ from google.cloud._helpers import UTC\n BLOB_NAME = 'blob-name'\n bucket = _Bucket()\n TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC)\n@@ -1385,8 +1385,8 @@ def test_time_deleted_unset(self):\n \n def test_updated(self):\n import datetime\n- from gcloud._helpers import _RFC3339_MICROS\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import _RFC3339_MICROS\n+ from google.cloud._helpers import UTC\n BLOB_NAME = 'blob-name'\n bucket = _Bucket()\n TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC)\n@@ -1426,7 +1426,7 @@ def __init__(self, *responses):\n \n def api_request(self, **kw):\n from six.moves.http_client import NOT_FOUND\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n info, content = self._respond(**kw)\n if info.get('status') == NOT_FOUND:\n raise NotFound(info)\ndiff --git a/unit_tests/storage/test_bucket.py b/unit_tests/storage/test_bucket.py\n--- a/unit_tests/storage/test_bucket.py\n+++ b/unit_tests/storage/test_bucket.py\n@@ -18,7 +18,7 @@\n class Test__BlobIterator(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.bucket import _BlobIterator\n+ from google.cloud.storage.bucket import _BlobIterator\n return _BlobIterator\n \n def _makeOne(self, *args, **kw):\n@@ -46,7 +46,7 @@ def test_get_items_from_response_empty(self):\n self.assertEqual(iterator.prefixes, set())\n \n def test_get_items_from_response_non_empty(self):\n- from gcloud.storage.blob import Blob\n+ from google.cloud.storage.blob import Blob\n BLOB_NAME = 'blob-name'\n response = {'items': [{'name': BLOB_NAME}], 'prefixes': ['foo']}\n connection = _Connection()\n@@ -61,7 +61,7 @@ def test_get_items_from_response_non_empty(self):\n self.assertEqual(iterator.prefixes, set(['foo']))\n \n def test_get_items_from_response_cumulative_prefixes(self):\n- from gcloud.storage.blob import Blob\n+ from google.cloud.storage.blob import Blob\n BLOB_NAME = 'blob-name1'\n response1 = {'items': [{'name': BLOB_NAME}], 'prefixes': ['foo']}\n response2 = {\n@@ -88,7 +88,7 @@ def test_get_items_from_response_cumulative_prefixes(self):\n class Test_Bucket(unittest.TestCase):\n \n def _makeOne(self, client=None, name=None, properties=None):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n if client is None:\n connection = _Connection()\n client = _Client(connection)\n@@ -108,7 +108,7 @@ def test_ctor(self):\n self.assertTrue(bucket._default_object_acl.bucket is bucket)\n \n def test_blob(self):\n- from gcloud.storage.blob import Blob\n+ from google.cloud.storage.blob import Blob\n \n BUCKET_NAME = 'BUCKET_NAME'\n BLOB_NAME = 'BLOB_NAME'\n@@ -123,7 +123,7 @@ def test_blob(self):\n self.assertEqual(blob.chunk_size, CHUNK_SIZE)\n \n def test_exists_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n class _FakeConnection(object):\n \n@@ -230,14 +230,14 @@ def test_create_w_extra_properties(self):\n self.assertEqual(kw['data'], DATA)\n \n def test_acl_property(self):\n- from gcloud.storage.acl import BucketACL\n+ from google.cloud.storage.acl import BucketACL\n bucket = self._makeOne()\n acl = bucket.acl\n self.assertTrue(isinstance(acl, BucketACL))\n self.assertTrue(acl is bucket._acl)\n \n def test_default_object_acl_property(self):\n- from gcloud.storage.acl import DefaultObjectACL\n+ from google.cloud.storage.acl import DefaultObjectACL\n bucket = self._makeOne()\n acl = bucket.default_object_acl\n self.assertTrue(isinstance(acl, DefaultObjectACL))\n@@ -342,7 +342,7 @@ def test_list_blobs(self):\n self.assertEqual(kw['query_params'], {'projection': 'noAcl'})\n \n def test_delete_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n NAME = 'name'\n connection = _Connection()\n client = _Client(connection)\n@@ -435,7 +435,7 @@ def test_delete_too_many(self):\n self.assertEqual(connection._deleted_buckets, [])\n \n def test_delete_blob_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n NAME = 'name'\n NONESUCH = 'nonesuch'\n connection = _Connection()\n@@ -479,7 +479,7 @@ def test_delete_blobs_hit(self):\n self.assertEqual(kw[0]['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))\n \n def test_delete_blobs_miss_no_on_error(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n NAME = 'name'\n BLOB_NAME = 'blob-name'\n NONESUCH = 'nonesuch'\n@@ -790,8 +790,8 @@ def test_storage_class_setter_DURABLE_REDUCED_AVAILABILITY(self):\n \n def test_time_created(self):\n import datetime\n- from gcloud._helpers import _RFC3339_MICROS\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import _RFC3339_MICROS\n+ from google.cloud._helpers import UTC\n TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC)\n TIME_CREATED = TIMESTAMP.strftime(_RFC3339_MICROS)\n properties = {'timeCreated': TIME_CREATED}\n@@ -845,7 +845,7 @@ def test_disable_website(self):\n self.assertEqual(bucket._properties, UNSET)\n \n def test_make_public_defaults(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n NAME = 'name'\n permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]\n after = {'acl': permissive, 'defaultObjectAcl': []}\n@@ -865,7 +865,7 @@ def test_make_public_defaults(self):\n self.assertEqual(kw[0]['query_params'], {'projection': 'full'})\n \n def _make_public_w_future_helper(self, default_object_acl_loaded=True):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n NAME = 'name'\n permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]\n after1 = {'acl': permissive, 'defaultObjectAcl': []}\n@@ -907,8 +907,8 @@ def test_make_public_w_future_reload_default(self):\n self._make_public_w_future_helper(default_object_acl_loaded=False)\n \n def test_make_public_recursive(self):\n- from gcloud.storage.acl import _ACLEntity\n- from gcloud.storage.bucket import _BlobIterator\n+ from google.cloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.bucket import _BlobIterator\n _saved = []\n \n class _Blob(object):\n@@ -965,7 +965,7 @@ def get_items_from_response(self, response):\n {'maxResults': max_results, 'projection': 'full'})\n \n def test_make_public_recursive_too_many(self):\n- from gcloud.storage.acl import _ACLEntity\n+ from google.cloud.storage.acl import _ACLEntity\n \n PERMISSIVE = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]\n AFTER = {'acl': PERMISSIVE, 'defaultObjectAcl': []}\n@@ -1004,7 +1004,7 @@ def _is_bucket_path(path):\n return path.startswith('/b/') and path.count('/') == 2\n \n def api_request(self, **kw):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n self._requested.append(kw)\n \n method = kw.get('method')\ndiff --git a/unit_tests/storage/test_client.py b/unit_tests/storage/test_client.py\n--- a/unit_tests/storage/test_client.py\n+++ b/unit_tests/storage/test_client.py\n@@ -18,14 +18,14 @@\n class TestClient(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.client import Client\n+ from google.cloud.storage.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor_connection_type(self):\n- from gcloud.storage.connection import Connection\n+ from google.cloud.storage.connection import Connection\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -38,7 +38,7 @@ def test_ctor_connection_type(self):\n self.assertEqual(list(client._batch_stack), [])\n \n def test__push_batch_and__pop_batch(self):\n- from gcloud.storage.batch import Batch\n+ from google.cloud.storage.batch import Batch\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -80,7 +80,7 @@ def test_connection_getter_no_batch(self):\n self.assertTrue(client.current_batch is None)\n \n def test_connection_getter_with_batch(self):\n- from gcloud.storage.batch import Batch\n+ from google.cloud.storage.batch import Batch\n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n client = self._makeOne(project=PROJECT, credentials=CREDENTIALS)\n@@ -91,7 +91,7 @@ def test_connection_getter_with_batch(self):\n self.assertTrue(client.current_batch is batch)\n \n def test_bucket(self):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -104,7 +104,7 @@ def test_bucket(self):\n self.assertEqual(bucket.name, BUCKET_NAME)\n \n def test_batch(self):\n- from gcloud.storage.batch import Batch\n+ from google.cloud.storage.batch import Batch\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -115,7 +115,7 @@ def test_batch(self):\n self.assertTrue(batch._client is client)\n \n def test_get_bucket_miss(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -138,7 +138,7 @@ def test_get_bucket_miss(self):\n self.assertEqual(http._called_with['uri'], URI)\n \n def test_get_bucket_hit(self):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -186,7 +186,7 @@ def test_lookup_bucket_miss(self):\n self.assertEqual(http._called_with['uri'], URI)\n \n def test_lookup_bucket_hit(self):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -212,7 +212,7 @@ def test_lookup_bucket_hit(self):\n self.assertEqual(http._called_with['uri'], URI)\n \n def test_create_bucket_conflict(self):\n- from gcloud.exceptions import Conflict\n+ from google.cloud.exceptions import Conflict\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -235,7 +235,7 @@ def test_create_bucket_conflict(self):\n self.assertEqual(http._called_with['uri'], URI)\n \n def test_create_bucket_success(self):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n \n PROJECT = 'PROJECT'\n CREDENTIALS = _Credentials()\n@@ -373,7 +373,7 @@ def test_list_buckets_all_arguments(self):\n class Test__BucketIterator(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.client import _BucketIterator\n+ from google.cloud.storage.client import _BucketIterator\n return _BucketIterator\n \n def _makeOne(self, *args, **kw):\n@@ -395,7 +395,7 @@ def test_get_items_from_response_empty(self):\n self.assertEqual(list(iterator.get_items_from_response({})), [])\n \n def test_get_items_from_response_non_empty(self):\n- from gcloud.storage.bucket import Bucket\n+ from google.cloud.storage.bucket import Bucket\n BLOB_NAME = 'blob-name'\n response = {'items': [{'name': BLOB_NAME}]}\n connection = object()\ndiff --git a/unit_tests/storage/test_connection.py b/unit_tests/storage/test_connection.py\n--- a/unit_tests/storage/test_connection.py\n+++ b/unit_tests/storage/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.storage.connection import Connection\n+ from google.cloud.storage.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/streaming/test_buffered_stream.py b/unit_tests/streaming/test_buffered_stream.py\n--- a/unit_tests/streaming/test_buffered_stream.py\n+++ b/unit_tests/streaming/test_buffered_stream.py\n@@ -4,7 +4,7 @@\n class Test_BufferedStream(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.buffered_stream import BufferedStream\n+ from google.cloud.streaming.buffered_stream import BufferedStream\n return BufferedStream\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/streaming/test_exceptions.py b/unit_tests/streaming/test_exceptions.py\n--- a/unit_tests/streaming/test_exceptions.py\n+++ b/unit_tests/streaming/test_exceptions.py\n@@ -4,7 +4,7 @@\n class Test_HttpError(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.exceptions import HttpError\n return HttpError\n \n def _makeOne(self, *args, **kw):\n@@ -45,7 +45,7 @@ class _Response(object):\n class Test_RetryAfterError(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.exceptions import RetryAfterError\n+ from google.cloud.streaming.exceptions import RetryAfterError\n return RetryAfterError\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/streaming/test_http_wrapper.py b/unit_tests/streaming/test_http_wrapper.py\n--- a/unit_tests/streaming/test_http_wrapper.py\n+++ b/unit_tests/streaming/test_http_wrapper.py\n@@ -4,7 +4,7 @@\n class Test__httplib2_debug_level(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.http_wrapper import _httplib2_debug_level\n+ from google.cloud.streaming.http_wrapper import _httplib2_debug_level\n return _httplib2_debug_level\n \n def _makeOne(self, *args, **kw):\n@@ -12,7 +12,7 @@ def _makeOne(self, *args, **kw):\n \n def test_wo_loggable_body_wo_http(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n \n request = _Request()\n LEVEL = 1\n@@ -23,7 +23,7 @@ def test_wo_loggable_body_wo_http(self):\n \n def test_w_loggable_body_wo_http(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n \n request = _Request(loggable_body=object())\n LEVEL = 1\n@@ -35,7 +35,7 @@ def test_w_loggable_body_wo_http(self):\n \n def test_w_loggable_body_w_http(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n \n class _Connection(object):\n debuglevel = 0\n@@ -63,7 +63,7 @@ def set_debuglevel(self, value):\n class Test_Request(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.http_wrapper import Request\n+ from google.cloud.streaming.http_wrapper import Request\n return Request\n \n def _makeOne(self, *args, **kw):\n@@ -78,7 +78,7 @@ def test_ctor_defaults(self):\n self.assertEqual(request.loggable_body, None)\n \n def test_loggable_body_setter_w_body_None(self):\n- from gcloud.streaming.exceptions import RequestError\n+ from google.cloud.streaming.exceptions import RequestError\n request = self._makeOne(body=None)\n with self.assertRaises(RequestError):\n request.loggable_body = 'abc'\n@@ -103,7 +103,7 @@ def test_body_setter_w_non_string(self):\n class Test_Response(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.http_wrapper import Response\n+ from google.cloud.streaming.http_wrapper import Response\n return Response\n \n def _makeOne(self, *args, **kw):\n@@ -199,23 +199,23 @@ def test_is_redirect_w_code_w_location(self):\n class Test__check_response(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.http_wrapper import _check_response\n+ from google.cloud.streaming.http_wrapper import _check_response\n return _check_response(*args, **kw)\n \n def test_w_none(self):\n- from gcloud.streaming.exceptions import RequestError\n+ from google.cloud.streaming.exceptions import RequestError\n with self.assertRaises(RequestError):\n self._callFUT(None)\n \n def test_w_TOO_MANY_REQUESTS(self):\n- from gcloud.streaming.exceptions import BadStatusCodeError\n- from gcloud.streaming.http_wrapper import TOO_MANY_REQUESTS\n+ from google.cloud.streaming.exceptions import BadStatusCodeError\n+ from google.cloud.streaming.http_wrapper import TOO_MANY_REQUESTS\n \n with self.assertRaises(BadStatusCodeError):\n self._callFUT(_Response(TOO_MANY_REQUESTS))\n \n def test_w_50x(self):\n- from gcloud.streaming.exceptions import BadStatusCodeError\n+ from google.cloud.streaming.exceptions import BadStatusCodeError\n \n with self.assertRaises(BadStatusCodeError):\n self._callFUT(_Response(500))\n@@ -224,7 +224,7 @@ def test_w_50x(self):\n self._callFUT(_Response(503))\n \n def test_w_retry_after(self):\n- from gcloud.streaming.exceptions import RetryAfterError\n+ from google.cloud.streaming.exceptions import RetryAfterError\n \n with self.assertRaises(RetryAfterError):\n self._callFUT(_Response(200, 20))\n@@ -236,7 +236,7 @@ def test_pass(self):\n class Test__reset_http_connections(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.http_wrapper import _reset_http_connections\n+ from google.cloud.streaming.http_wrapper import _reset_http_connections\n return _reset_http_connections(*args, **kw)\n \n def test_wo_connections(self):\n@@ -254,7 +254,8 @@ def test_w_connections(self):\n class Test___make_api_request_no_retry(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.http_wrapper import _make_api_request_no_retry\n+ from google.cloud.streaming.http_wrapper import (\n+ _make_api_request_no_retry)\n return _make_api_request_no_retry(*args, **kw)\n \n def _verify_requested(self, http, request,\n@@ -270,7 +271,7 @@ def _verify_requested(self, http, request,\n \n def test_defaults_wo_connections(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n INFO = {'status': '200'}\n CONTENT = 'CONTENT'\n _http = _Http((INFO, CONTENT))\n@@ -290,7 +291,7 @@ def test_defaults_wo_connections(self):\n \n def test_w_http_connections_miss(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n INFO = {'status': '200'}\n CONTENT = 'CONTENT'\n CONN_TYPE = object()\n@@ -312,7 +313,7 @@ def test_w_http_connections_miss(self):\n \n def test_w_http_connections_hit(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n INFO = {'status': '200'}\n CONTENT = 'CONTENT'\n CONN_TYPE = object()\n@@ -334,8 +335,8 @@ def test_w_http_connections_hit(self):\n \n def test_w_request_returning_None(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n- from gcloud.streaming.exceptions import RequestError\n+ from google.cloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming.exceptions import RequestError\n INFO = None\n CONTENT = None\n CONN_TYPE = object()\n@@ -352,11 +353,11 @@ def test_w_request_returning_None(self):\n class Test_make_api_request(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.http_wrapper import make_api_request\n+ from google.cloud.streaming.http_wrapper import make_api_request\n return make_api_request(*args, **kw)\n \n def test_wo_exception(self):\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n from unit_tests._testing import _Monkey\n \n HTTP, REQUEST, RESPONSE = object(), object(), object()\n@@ -376,8 +377,8 @@ def _wo_exception(*args, **kw):\n self.assertEqual(_checked, []) # not called by '_wo_exception'\n \n def test_w_exceptions_lt_max_retries(self):\n- from gcloud.streaming.exceptions import RetryAfterError\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming.exceptions import RetryAfterError\n+ from google.cloud.streaming import http_wrapper as MUT\n from unit_tests._testing import _Monkey\n \n HTTP, RESPONSE = object(), object()\n@@ -405,7 +406,7 @@ def _wo_exception(*args, **kw):\n \n def test_w_exceptions_gt_max_retries(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import http_wrapper as MUT\n+ from google.cloud.streaming import http_wrapper as MUT\n HTTP = object()\n REQUEST = _Request()\n _created, _checked = [], []\ndiff --git a/unit_tests/streaming/test_stream_slice.py b/unit_tests/streaming/test_stream_slice.py\n--- a/unit_tests/streaming/test_stream_slice.py\n+++ b/unit_tests/streaming/test_stream_slice.py\n@@ -4,7 +4,7 @@\n class Test_StreamSlice(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.streaming.stream_slice import StreamSlice\n+ from google.cloud.streaming.stream_slice import StreamSlice\n return StreamSlice\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/streaming/test_transfer.py b/unit_tests/streaming/test_transfer.py\n--- a/unit_tests/streaming/test_transfer.py\n+++ b/unit_tests/streaming/test_transfer.py\n@@ -5,14 +5,14 @@ class Test__Transfer(unittest.TestCase):\n URL = 'http://example.com/api'\n \n def _getTargetClass(self):\n- from gcloud.streaming.transfer import _Transfer\n+ from google.cloud.streaming.transfer import _Transfer\n return _Transfer\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor_defaults(self):\n- from gcloud.streaming.transfer import _DEFAULT_CHUNKSIZE\n+ from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE\n stream = _Stream()\n xfer = self._makeOne(stream)\n self.assertTrue(xfer.stream is stream)\n@@ -98,7 +98,7 @@ def test__initialize_w_existing_http(self):\n self.assertTrue(xfer.url is self.URL)\n \n def test__initialize_already_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n URL_2 = 'http://example.com/other'\n HTTP_1, HTTP_2 = object(), object()\n stream = _Stream()\n@@ -115,7 +115,7 @@ def test__ensure_initialized_hit(self):\n xfer._ensure_initialized() # no raise\n \n def test__ensure_initialized_miss(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n stream = _Stream()\n xfer = self._makeOne(stream)\n with self.assertRaises(TransferInvalidError):\n@@ -127,7 +127,7 @@ def test__ensure_uninitialized_hit(self):\n xfer._ensure_uninitialized() # no raise\n \n def test__ensure_uninitialized_miss(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n stream = _Stream()\n HTTP = object()\n xfer = self._makeOne(stream)\n@@ -149,7 +149,7 @@ class Test_Download(unittest.TestCase):\n URL = \"http://example.com/api\"\n \n def _getTargetClass(self):\n- from gcloud.streaming.transfer import Download\n+ from google.cloud.streaming.transfer import Download\n return Download\n \n def _makeOne(self, *args, **kw):\n@@ -258,7 +258,7 @@ def test__set_total_w_content_range_w_asterisk_total(self):\n self.assertEqual(download.total_size, 0)\n \n def test_initialize_download_already_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n request = _Request()\n download = self._makeOne(_Stream())\n download._initialize(None, self.URL)\n@@ -276,8 +276,8 @@ def test_initialize_download_wo_autotransfer(self):\n def test_initialize_download_w_autotransfer_failing(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import HttpError\n request = _Request()\n http = object()\n download = self._makeOne(_Stream(), auto_transfer=True)\n@@ -295,7 +295,7 @@ def test_initialize_download_w_autotransfer_failing(self):\n def test_initialize_download_w_autotransfer_w_content_location(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n REDIRECT_URL = 'http://example.com/other'\n request = _Request()\n http = object()\n@@ -316,14 +316,14 @@ def test_initialize_download_w_autotransfer_w_content_location(self):\n self.assertTrue(requester._requested[0][0] is request)\n \n def test__normalize_start_end_w_end_w_start_lt_0(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n \n with self.assertRaises(TransferInvalidError):\n download._normalize_start_end(-1, 0)\n \n def test__normalize_start_end_w_end_w_start_gt_total(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n \n@@ -331,7 +331,7 @@ def test__normalize_start_end_w_end_w_start_gt_total(self):\n download._normalize_start_end(3, 0)\n \n def test__normalize_start_end_w_end_lt_start(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n \n@@ -403,7 +403,7 @@ def test__compute_end_byte_w_start_ge_0_wo_end_w_total_size(self):\n self.assertEqual(download._compute_end_byte(0, use_chunks=False), 9)\n \n def test__get_chunk_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n \n with self.assertRaises(TransferInvalidError):\n@@ -412,7 +412,7 @@ def test__get_chunk_not_initialized(self):\n def test__get_chunk(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n http = object()\n download = self._makeOne(_Stream())\n download._initialize(http, self.URL)\n@@ -430,7 +430,7 @@ def test__get_chunk(self):\n self.assertEqual(request.headers['range'], 'bytes=0-10')\n \n def test__process_response_w_FORBIDDEN(self):\n- from gcloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.exceptions import HttpError\n from six.moves import http_client\n download = self._makeOne(_Stream())\n response = _makeResponse(http_client.FORBIDDEN)\n@@ -438,7 +438,7 @@ def test__process_response_w_FORBIDDEN(self):\n download._process_response(response)\n \n def test__process_response_w_NOT_FOUND(self):\n- from gcloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.exceptions import HttpError\n from six.moves import http_client\n download = self._makeOne(_Stream())\n response = _makeResponse(http_client.NOT_FOUND)\n@@ -446,7 +446,7 @@ def test__process_response_w_NOT_FOUND(self):\n download._process_response(response)\n \n def test__process_response_w_other_error(self):\n- from gcloud.streaming.exceptions import TransferRetryError\n+ from google.cloud.streaming.exceptions import TransferRetryError\n from six.moves import http_client\n download = self._makeOne(_Stream())\n response = _makeResponse(http_client.BAD_REQUEST)\n@@ -500,7 +500,7 @@ def test__process_response_w_NO_CONTENT(self):\n self.assertEqual(download.encoding, None)\n \n def test_get_range_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n with self.assertRaises(TransferInvalidError):\n download.get_range(0, 10)\n@@ -508,7 +508,7 @@ def test_get_range_not_initialized(self):\n def test_get_range_wo_total_size_complete(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n REQ_RANGE = 'bytes=0-%d' % (LEN,)\n@@ -535,7 +535,7 @@ def test_get_range_wo_total_size_complete(self):\n def test_get_range_wo_total_size_wo_end(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n START = 5\n@@ -564,7 +564,7 @@ def test_get_range_wo_total_size_wo_end(self):\n def test_get_range_w_total_size_partial(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n PARTIAL_LEN = 5\n@@ -593,8 +593,8 @@ def test_get_range_w_total_size_partial(self):\n def test_get_range_w_empty_chunk(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import TransferRetryError\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import TransferRetryError\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n START = 5\n@@ -624,7 +624,7 @@ def test_get_range_w_empty_chunk(self):\n def test_get_range_w_total_size_wo_use_chunks(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n CHUNK_SIZE = 3\n@@ -652,7 +652,7 @@ def test_get_range_w_total_size_wo_use_chunks(self):\n def test_get_range_w_multiple_chunks(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDE'\n LEN = len(CONTENT)\n CHUNK_SIZE = 3\n@@ -686,7 +686,7 @@ def test_get_range_w_multiple_chunks(self):\n self.assertEqual(download.total_size, LEN)\n \n def test_stream_file_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._makeOne(_Stream())\n \n with self.assertRaises(TransferInvalidError):\n@@ -713,7 +713,7 @@ def test_stream_file_w_initial_response_complete(self):\n def test_stream_file_w_initial_response_incomplete(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CHUNK_SIZE = 3\n CONTENT = b'ABCDEF'\n LEN = len(CONTENT)\n@@ -750,7 +750,7 @@ def test_stream_file_w_initial_response_incomplete(self):\n def test_stream_file_wo_initial_response_wo_total_size(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n+ from google.cloud.streaming import transfer as MUT\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n CHUNK_SIZE = 123\n@@ -784,14 +784,14 @@ class Test_Upload(unittest.TestCase):\n UPLOAD_URL = 'http://example.com/upload/id=foobar'\n \n def _getTargetClass(self):\n- from gcloud.streaming.transfer import Upload\n+ from google.cloud.streaming.transfer import Upload\n return Upload\n \n def _makeOne(self, stream, mime_type=MIME_TYPE, *args, **kw):\n return self._getTargetClass()(stream, mime_type, *args, **kw)\n \n def test_ctor_defaults(self):\n- from gcloud.streaming.transfer import _DEFAULT_CHUNKSIZE\n+ from google.cloud.streaming.transfer import _DEFAULT_CHUNKSIZE\n stream = _Stream()\n upload = self._makeOne(stream)\n self.assertTrue(upload.stream is stream)\n@@ -901,19 +901,19 @@ def test_strategy_setter_invalid(self):\n upload.strategy = 'unknown'\n \n def test_strategy_setter_SIMPLE_UPLOAD(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n upload = self._makeOne(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n self.assertEqual(upload.strategy, SIMPLE_UPLOAD)\n \n def test_strategy_setter_RESUMABLE_UPLOAD(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n upload = self._makeOne(_Stream())\n upload.strategy = RESUMABLE_UPLOAD\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n \n def test_total_size_setter_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n SIZE = 123\n upload = self._makeOne(_Stream)\n http = object()\n@@ -928,7 +928,7 @@ def test_total_size_setter_not_initialized(self):\n self.assertEqual(upload.total_size, SIZE)\n \n def test__set_default_strategy_w_existing_strategy(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n config = _Dummy(\n resumable_path='/resumable/endpoint',\n simple_multipart=True,\n@@ -941,7 +941,7 @@ def test__set_default_strategy_w_existing_strategy(self):\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n \n def test__set_default_strategy_wo_resumable_path(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n config = _Dummy(\n resumable_path=None,\n simple_multipart=True,\n@@ -953,8 +953,8 @@ def test__set_default_strategy_wo_resumable_path(self):\n self.assertEqual(upload.strategy, SIMPLE_UPLOAD)\n \n def test__set_default_strategy_w_total_size_gt_threshhold(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD_THRESHOLD\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD_THRESHOLD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n config = _UploadConfig()\n request = _Request()\n upload = self._makeOne(\n@@ -963,7 +963,7 @@ def test__set_default_strategy_w_total_size_gt_threshhold(self):\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n \n def test__set_default_strategy_w_body_wo_multipart(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n config = _UploadConfig()\n config.simple_multipart = False\n@@ -973,7 +973,7 @@ def test__set_default_strategy_w_body_wo_multipart(self):\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n \n def test__set_default_strategy_w_body_w_multipart_wo_simple_path(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n config = _UploadConfig()\n config.simple_path = None\n@@ -983,7 +983,7 @@ def test__set_default_strategy_w_body_w_multipart_wo_simple_path(self):\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n \n def test__set_default_strategy_w_body_w_multipart_w_simple_path(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n config = _UploadConfig()\n request = _Request(body=CONTENT)\n@@ -1011,7 +1011,7 @@ def test_configure_request_w_invalid_mimetype(self):\n upload.configure_request(config, request, url_builder)\n \n def test_configure_request_w_simple_wo_body(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n CONTENT = b'CONTENT'\n config = _UploadConfig()\n request = _Request()\n@@ -1029,8 +1029,8 @@ def test_configure_request_w_simple_wo_body(self):\n self.assertEqual(request.loggable_body, '')\n \n def test_configure_request_w_simple_w_body(self):\n- from gcloud._helpers import _to_bytes\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud._helpers import _to_bytes\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n CONTENT = b'CONTENT'\n BODY = b'BODY'\n config = _UploadConfig()\n@@ -1072,7 +1072,7 @@ def test_configure_request_w_simple_w_body(self):\n self.assertTrue(b'' in request.loggable_body)\n \n def test_configure_request_w_resumable_wo_total_size(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'CONTENT'\n config = _UploadConfig()\n request = _Request()\n@@ -1089,7 +1089,7 @@ def test_configure_request_w_resumable_wo_total_size(self):\n {'X-Upload-Content-Type': self.MIME_TYPE})\n \n def test_configure_request_w_resumable_w_total_size(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'CONTENT'\n LEN = len(CONTENT)\n config = _UploadConfig()\n@@ -1109,14 +1109,14 @@ def test_configure_request_w_resumable_w_total_size(self):\n 'X-Upload-Content-Length': '%d' % (LEN,)})\n \n def test_refresh_upload_state_w_simple_strategy(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n upload = self._makeOne(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n upload.refresh_upload_state() # no-op\n \n def test_refresh_upload_state_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n upload = self._makeOne(_Stream())\n upload.strategy = RESUMABLE_UPLOAD\n with self.assertRaises(TransferInvalidError):\n@@ -1125,8 +1125,8 @@ def test_refresh_upload_state_not_initialized(self):\n def test_refresh_upload_state_w_OK(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,)\n@@ -1152,8 +1152,8 @@ def test_refresh_upload_state_w_OK(self):\n def test_refresh_upload_state_w_CREATED(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN,)\n@@ -1177,10 +1177,10 @@ def test_refresh_upload_state_w_CREATED(self):\n self.assertTrue(upload._final_response is response)\n \n def test_refresh_upload_state_w_RESUME_INCOMPLETE_w_range(self):\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n from unit_tests._testing import _Monkey\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n LAST = 5\n@@ -1204,10 +1204,10 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_w_range(self):\n self.assertFalse(upload._final_response is response)\n \n def test_refresh_upload_state_w_RESUME_INCOMPLETE_wo_range(self):\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n from unit_tests._testing import _Monkey\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n http = object()\n@@ -1231,9 +1231,9 @@ def test_refresh_upload_state_w_RESUME_INCOMPLETE_wo_range(self):\n def test_refresh_upload_state_w_error(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import HttpError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n http = object()\n@@ -1272,15 +1272,15 @@ def test_initialize_upload_no_strategy(self):\n upload.initialize_upload(request, http=object())\n \n def test_initialize_upload_simple_w_http(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n request = _Request()\n upload = self._makeOne(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n upload.initialize_upload(request, http=object()) # no-op\n \n def test_initialize_upload_resumable_already_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n request = _Request()\n upload = self._makeOne(_Stream())\n upload.strategy = RESUMABLE_UPLOAD\n@@ -1291,9 +1291,9 @@ def test_initialize_upload_resumable_already_initialized(self):\n def test_initialize_upload_w_http_resumable_not_initialized_w_error(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import HttpError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n request = _Request()\n upload = self._makeOne(_Stream())\n upload.strategy = RESUMABLE_UPLOAD\n@@ -1307,8 +1307,8 @@ def test_initialize_upload_w_http_resumable_not_initialized_w_error(self):\n def test_initialize_upload_w_http_wo_auto_transfer_w_OK(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n request = _Request()\n upload = self._makeOne(_Stream(), auto_transfer=False)\n upload.strategy = RESUMABLE_UPLOAD\n@@ -1328,8 +1328,8 @@ def test_initialize_upload_w_http_wo_auto_transfer_w_OK(self):\n def test_initialize_upload_w_granularity_w_auto_transfer_w_OK(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n request = _Request()\n@@ -1377,14 +1377,14 @@ def test__validate_chunksize_w__server_chunk_granularity_hit(self):\n upload._validate_chunksize(400)\n \n def test_stream_file_w_simple_strategy(self):\n- from gcloud.streaming.transfer import SIMPLE_UPLOAD\n+ from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n upload = self._makeOne(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n with self.assertRaises(ValueError):\n upload.stream_file()\n \n def test_stream_file_w_use_chunks_invalid_chunk_size(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n upload = self._makeOne(_Stream(), chunksize=1024)\n upload.strategy = RESUMABLE_UPLOAD\n upload._server_chunk_granularity = 100\n@@ -1392,8 +1392,8 @@ def test_stream_file_w_use_chunks_invalid_chunk_size(self):\n upload.stream_file(use_chunks=True)\n \n def test_stream_file_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n upload = self._makeOne(_Stream(), chunksize=1024)\n upload.strategy = RESUMABLE_UPLOAD\n upload._server_chunk_granularity = 128\n@@ -1401,7 +1401,7 @@ def test_stream_file_not_initialized(self):\n upload.stream_file()\n \n def test_stream_file_already_complete_w_unseekable_stream(self):\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n http = object()\n stream = object()\n response = object()\n@@ -1414,8 +1414,8 @@ def test_stream_file_already_complete_w_unseekable_stream(self):\n self.assertTrue(upload.stream_file() is response)\n \n def test_stream_file_already_complete_w_seekable_stream_unsynced(self):\n- from gcloud.streaming.exceptions import CommunicationError\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.exceptions import CommunicationError\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _Stream(CONTENT)\n@@ -1431,7 +1431,7 @@ def test_stream_file_already_complete_w_seekable_stream_unsynced(self):\n \n def test_stream_file_already_complete_wo_seekable_method_synced(self):\n import os\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _Stream(CONTENT)\n@@ -1447,7 +1447,7 @@ def test_stream_file_already_complete_wo_seekable_method_synced(self):\n \n def test_stream_file_already_complete_w_seekable_method_true_synced(self):\n import os\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _StreamWithSeekableMethod(CONTENT, True)\n@@ -1463,7 +1463,7 @@ def test_stream_file_already_complete_w_seekable_method_true_synced(self):\n \n def test_stream_file_already_complete_w_seekable_method_false(self):\n import os\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _StreamWithSeekableMethod(CONTENT, False)\n@@ -1480,9 +1480,9 @@ def test_stream_file_already_complete_w_seekable_method_false(self):\n def test_stream_file_incomplete(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _Stream(CONTENT)\n@@ -1524,10 +1524,10 @@ def test_stream_file_incomplete(self):\n \n def test_stream_file_incomplete_w_transfer_error(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import CommunicationError\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import CommunicationError\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n http = object()\n stream = _Stream(CONTENT)\n@@ -1562,8 +1562,8 @@ def test_stream_file_incomplete_w_transfer_error(self):\n \n def test__send_media_request_wo_error(self):\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n CONTENT = b'ABCDEFGHIJ'\n bytes_http = object()\n stream = _Stream(CONTENT)\n@@ -1590,10 +1590,10 @@ def test__send_media_request_wo_error(self):\n def test__send_media_request_w_error(self):\n from six.moves import http_client\n from unit_tests._testing import _Monkey\n- from gcloud.streaming import transfer as MUT\n- from gcloud.streaming.exceptions import HttpError\n- from gcloud.streaming.http_wrapper import RESUME_INCOMPLETE\n- from gcloud.streaming.transfer import RESUMABLE_UPLOAD\n+ from google.cloud.streaming import transfer as MUT\n+ from google.cloud.streaming.exceptions import HttpError\n+ from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n+ from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n bytes_http = object()\n http = object()\n@@ -1629,13 +1629,13 @@ def test__send_media_request_w_error(self):\n self.assertTrue(second_http is http)\n \n def test__send_media_body_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n upload = self._makeOne(_Stream())\n with self.assertRaises(TransferInvalidError):\n upload._send_media_body(0)\n \n def test__send_media_body_wo_total_size(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n http = object()\n upload = self._makeOne(_Stream())\n upload._initialize(http, _Request.URL)\n@@ -1643,7 +1643,7 @@ def test__send_media_body_wo_total_size(self):\n upload._send_media_body(0)\n \n def test__send_media_body_start_lt_total_size(self):\n- from gcloud.streaming.stream_slice import StreamSlice\n+ from google.cloud.streaming.stream_slice import StreamSlice\n SIZE = 1234\n http = object()\n stream = _Stream()\n@@ -1670,7 +1670,7 @@ def test__send_media_body_start_lt_total_size(self):\n self.assertEqual(end, SIZE)\n \n def test__send_media_body_start_eq_total_size(self):\n- from gcloud.streaming.stream_slice import StreamSlice\n+ from google.cloud.streaming.stream_slice import StreamSlice\n SIZE = 1234\n http = object()\n stream = _Stream()\n@@ -1697,7 +1697,7 @@ def test__send_media_body_start_eq_total_size(self):\n self.assertEqual(end, SIZE)\n \n def test__send_chunk_not_initialized(self):\n- from gcloud.streaming.exceptions import TransferInvalidError\n+ from google.cloud.streaming.exceptions import TransferInvalidError\n upload = self._makeOne(_Stream())\n with self.assertRaises(TransferInvalidError):\n upload._send_chunk(0)\n@@ -1756,7 +1756,7 @@ def test__send_chunk_wo_total_size_stream_not_exhausted(self):\n self.assertEqual(end, CHUNK_SIZE)\n \n def test__send_chunk_w_total_size_stream_not_exhausted(self):\n- from gcloud.streaming.stream_slice import StreamSlice\n+ from google.cloud.streaming.stream_slice import StreamSlice\n CONTENT = b'ABCDEFGHIJ'\n SIZE = len(CONTENT)\n CHUNK_SIZE = SIZE - 5\n@@ -1787,7 +1787,7 @@ def test__send_chunk_w_total_size_stream_not_exhausted(self):\n self.assertEqual(end, CHUNK_SIZE)\n \n def test__send_chunk_w_total_size_stream_exhausted(self):\n- from gcloud.streaming.stream_slice import StreamSlice\n+ from google.cloud.streaming.stream_slice import StreamSlice\n CONTENT = b'ABCDEFGHIJ'\n SIZE = len(CONTENT)\n CHUNK_SIZE = 1000\ndiff --git a/unit_tests/streaming/test_util.py b/unit_tests/streaming/test_util.py\n--- a/unit_tests/streaming/test_util.py\n+++ b/unit_tests/streaming/test_util.py\n@@ -4,7 +4,7 @@\n class Test_calculate_wait_for_retry(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.util import calculate_wait_for_retry\n+ from google.cloud.streaming.util import calculate_wait_for_retry\n return calculate_wait_for_retry(*args, **kw)\n \n def test_w_negative_jitter_lt_max_wait(self):\n@@ -23,7 +23,7 @@ def test_w_positive_jitter_gt_max_wait(self):\n class Test_acceptable_mime_type(unittest.TestCase):\n \n def _callFUT(self, *args, **kw):\n- from gcloud.streaming.util import acceptable_mime_type\n+ from google.cloud.streaming.util import acceptable_mime_type\n return acceptable_mime_type(*args, **kw)\n \n def test_pattern_wo_slash(self):\ndiff --git a/unit_tests/test__helpers.py b/unit_tests/test__helpers.py\n--- a/unit_tests/test__helpers.py\n+++ b/unit_tests/test__helpers.py\n@@ -19,7 +19,7 @@\n class Test__LocalStack(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud._helpers import _LocalStack\n+ from google.cloud._helpers import _LocalStack\n \n return _LocalStack\n \n@@ -47,14 +47,14 @@ def test_it(self):\n class Test__UTC(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud._helpers import _UTC\n+ from google.cloud._helpers import _UTC\n return _UTC\n \n def _makeOne(self):\n return self._getTargetClass()()\n \n def test_module_property(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n klass = self._getTargetClass()\n try:\n import pytz\n@@ -100,7 +100,7 @@ def test___str__(self):\n class Test__ensure_tuple_or_list(unittest.TestCase):\n \n def _callFUT(self, arg_name, tuple_or_list):\n- from gcloud._helpers import _ensure_tuple_or_list\n+ from google.cloud._helpers import _ensure_tuple_or_list\n return _ensure_tuple_or_list(arg_name, tuple_or_list)\n \n def test_valid_tuple(self):\n@@ -127,12 +127,12 @@ def test_invalid_iterable(self):\n class Test__app_engine_id(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _app_engine_id\n+ from google.cloud._helpers import _app_engine_id\n return _app_engine_id()\n \n def test_no_value(self):\n from unit_tests._testing import _Monkey\n- from gcloud import _helpers\n+ from google.cloud import _helpers\n \n with _Monkey(_helpers, app_identity=None):\n dataset_id = self._callFUT()\n@@ -140,7 +140,7 @@ def test_no_value(self):\n \n def test_value_set(self):\n from unit_tests._testing import _Monkey\n- from gcloud import _helpers\n+ from google.cloud import _helpers\n \n APP_ENGINE_ID = object()\n APP_IDENTITY = _AppIdentity(APP_ENGINE_ID)\n@@ -152,11 +152,11 @@ def test_value_set(self):\n class Test__file_project_id(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _file_project_id\n+ from google.cloud._helpers import _file_project_id\n return _file_project_id()\n \n def test_success(self):\n- from gcloud.environment_vars import CREDENTIALS\n+ from google.cloud.environment_vars import CREDENTIALS\n from unit_tests._testing import _Monkey\n from unit_tests._testing import _NamedTemporaryFile\n \n@@ -185,11 +185,11 @@ def test_no_environment_variable_set(self):\n class Test__get_nix_config_path(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _get_nix_config_path\n+ from google.cloud._helpers import _get_nix_config_path\n return _get_nix_config_path()\n \n def test_it(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n from unit_tests._testing import _Monkey\n \n user_root = 'a'\n@@ -205,11 +205,11 @@ def test_it(self):\n class Test__get_windows_config_path(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _get_windows_config_path\n+ from google.cloud._helpers import _get_windows_config_path\n return _get_windows_config_path()\n \n def test_it(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n from unit_tests._testing import _Monkey\n \n appdata_dir = 'a'\n@@ -228,11 +228,11 @@ class Test__default_service_project_id(unittest.TestCase):\n CONFIG_TEMPLATE = '[%s]\\n%s = %s\\n'\n \n def _callFUT(self):\n- from gcloud._helpers import _default_service_project_id\n+ from google.cloud._helpers import _default_service_project_id\n return _default_service_project_id()\n \n def test_nix(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n from unit_tests._testing import _Monkey\n from unit_tests._testing import _NamedTemporaryFile\n \n@@ -255,7 +255,7 @@ def mock_get_path():\n self.assertEqual(result, project_id)\n \n def test_windows(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n from unit_tests._testing import _Monkey\n from unit_tests._testing import _NamedTemporaryFile\n \n@@ -278,7 +278,7 @@ def mock_get_path():\n self.assertEqual(result, project_id)\n \n def test_gae(self):\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n from unit_tests._testing import _Monkey\n \n with _Monkey(os, name='not-nt'):\n@@ -291,12 +291,12 @@ def test_gae(self):\n class Test__compute_engine_id(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _compute_engine_id\n+ from google.cloud._helpers import _compute_engine_id\n return _compute_engine_id()\n \n def _monkeyConnection(self, connection):\n from unit_tests._testing import _Monkey\n- from gcloud import _helpers\n+ from google.cloud import _helpers\n \n def _connection_factory(host, timeout):\n connection.host = host\n@@ -328,7 +328,7 @@ def test_socket_raises(self):\n class Test__get_production_project(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud._helpers import _get_production_project\n+ from google.cloud._helpers import _get_production_project\n return _get_production_project()\n \n def test_no_value(self):\n@@ -341,7 +341,7 @@ def test_no_value(self):\n \n def test_value_set(self):\n from unit_tests._testing import _Monkey\n- from gcloud._helpers import PROJECT\n+ from google.cloud._helpers import PROJECT\n \n MOCK_PROJECT = object()\n environ = {PROJECT: MOCK_PROJECT}\n@@ -353,13 +353,13 @@ def test_value_set(self):\n class Test__determine_default_project(unittest.TestCase):\n \n def _callFUT(self, project=None):\n- from gcloud._helpers import _determine_default_project\n+ from google.cloud._helpers import _determine_default_project\n return _determine_default_project(project=project)\n \n def _determine_default_helper(self, prod=None, gae=None, gce=None,\n file_id=None, srv_id=None, project=None):\n from unit_tests._testing import _Monkey\n- from gcloud import _helpers\n+ from google.cloud import _helpers\n \n _callers = []\n \n@@ -432,12 +432,12 @@ def test_gce(self):\n class Test__millis(unittest.TestCase):\n \n def _callFUT(self, value):\n- from gcloud._helpers import _millis\n+ from google.cloud._helpers import _millis\n return _millis(value)\n \n def test_one_second_from_epoch(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n WHEN = datetime.datetime(1970, 1, 1, 0, 0, 1, tzinfo=UTC)\n self.assertEqual(self._callFUT(WHEN), 1000)\n@@ -446,7 +446,7 @@ def test_one_second_from_epoch(self):\n class Test__microseconds_from_datetime(unittest.TestCase):\n \n def _callFUT(self, value):\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import _microseconds_from_datetime\n return _microseconds_from_datetime(value)\n \n def test_it(self):\n@@ -463,7 +463,7 @@ def test_it(self):\n class Test__millis_from_datetime(unittest.TestCase):\n \n def _callFUT(self, value):\n- from gcloud._helpers import _millis_from_datetime\n+ from google.cloud._helpers import _millis_from_datetime\n return _millis_from_datetime(value)\n \n def test_w_none(self):\n@@ -472,8 +472,8 @@ def test_w_none(self):\n def test_w_utc_datetime(self):\n import datetime\n import six\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _microseconds_from_datetime\n \n NOW = datetime.datetime.utcnow().replace(tzinfo=UTC)\n NOW_MICROS = _microseconds_from_datetime(NOW)\n@@ -485,8 +485,8 @@ def test_w_utc_datetime(self):\n def test_w_non_utc_datetime(self):\n import datetime\n import six\n- from gcloud._helpers import _UTC\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import _UTC\n+ from google.cloud._helpers import _microseconds_from_datetime\n \n class CET(_UTC):\n _tzname = 'CET'\n@@ -503,8 +503,8 @@ class CET(_UTC):\n def test_w_naive_datetime(self):\n import datetime\n import six\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _microseconds_from_datetime\n \n NOW = datetime.datetime.utcnow()\n UTC_NOW = NOW.replace(tzinfo=UTC)\n@@ -518,13 +518,13 @@ def test_w_naive_datetime(self):\n class Test__datetime_from_microseconds(unittest.TestCase):\n \n def _callFUT(self, value):\n- from gcloud._helpers import _datetime_from_microseconds\n+ from google.cloud._helpers import _datetime_from_microseconds\n return _datetime_from_microseconds(value)\n \n def test_it(self):\n import datetime\n- from gcloud._helpers import UTC\n- from gcloud._helpers import _microseconds_from_datetime\n+ from google.cloud._helpers import UTC\n+ from google.cloud._helpers import _microseconds_from_datetime\n \n NOW = datetime.datetime(2015, 7, 29, 17, 45, 21, 123456,\n tzinfo=UTC)\n@@ -535,7 +535,7 @@ def test_it(self):\n class Test__rfc3339_to_datetime(unittest.TestCase):\n \n def _callFUT(self, dt_str):\n- from gcloud._helpers import _rfc3339_to_datetime\n+ from google.cloud._helpers import _rfc3339_to_datetime\n return _rfc3339_to_datetime(dt_str)\n \n def test_w_bogus_zone(self):\n@@ -554,7 +554,7 @@ def test_w_bogus_zone(self):\n \n def test_w_microseconds(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n year = 2009\n month = 12\n@@ -589,7 +589,7 @@ def test_w_naonseconds(self):\n class Test__rfc3339_nanos_to_datetime(unittest.TestCase):\n \n def _callFUT(self, dt_str):\n- from gcloud._helpers import _rfc3339_nanos_to_datetime\n+ from google.cloud._helpers import _rfc3339_nanos_to_datetime\n return _rfc3339_nanos_to_datetime(dt_str)\n \n def test_w_bogus_zone(self):\n@@ -608,7 +608,7 @@ def test_w_bogus_zone(self):\n \n def test_w_truncated_nanos(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n year = 2009\n month = 12\n@@ -637,7 +637,7 @@ def test_w_truncated_nanos(self):\n \n def test_w_naonseconds(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n year = 2009\n month = 12\n@@ -659,12 +659,12 @@ def test_w_naonseconds(self):\n class Test__datetime_to_rfc3339(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud._helpers import _datetime_to_rfc3339\n+ from google.cloud._helpers import _datetime_to_rfc3339\n return _datetime_to_rfc3339(*args, **kwargs)\n \n @staticmethod\n def _make_timezone(offset):\n- from gcloud._helpers import _UTC\n+ from google.cloud._helpers import _UTC\n \n class CET(_UTC):\n _tzname = 'CET'\n@@ -674,7 +674,7 @@ class CET(_UTC):\n \n def test_w_utc_datetime(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=UTC)\n result = self._callFUT(TIMESTAMP, ignore_zone=False)\n@@ -682,7 +682,7 @@ def test_w_utc_datetime(self):\n \n def test_w_non_utc_datetime(self):\n import datetime\n- from gcloud._helpers import _UTC\n+ from google.cloud._helpers import _UTC\n \n zone = self._make_timezone(offset=datetime.timedelta(hours=-1))\n TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=zone)\n@@ -691,7 +691,7 @@ def test_w_non_utc_datetime(self):\n \n def test_w_non_utc_datetime_and_ignore_zone(self):\n import datetime\n- from gcloud._helpers import _UTC\n+ from google.cloud._helpers import _UTC\n \n zone = self._make_timezone(offset=datetime.timedelta(hours=-1))\n TIMESTAMP = datetime.datetime(2016, 4, 5, 13, 30, 0, tzinfo=zone)\n@@ -709,7 +709,7 @@ def test_w_naive_datetime(self):\n class Test__to_bytes(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud._helpers import _to_bytes\n+ from google.cloud._helpers import _to_bytes\n return _to_bytes(*args, **kwargs)\n \n def test_with_bytes(self):\n@@ -736,7 +736,7 @@ def test_with_nonstring_type(self):\n class Test__bytes_to_unicode(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud._helpers import _bytes_to_unicode\n+ from google.cloud._helpers import _bytes_to_unicode\n return _bytes_to_unicode(*args, **kwargs)\n \n def test_with_bytes(self):\n@@ -757,13 +757,13 @@ def test_with_nonstring_type(self):\n class Test__pb_timestamp_to_datetime(unittest.TestCase):\n \n def _callFUT(self, timestamp):\n- from gcloud._helpers import _pb_timestamp_to_datetime\n+ from google.cloud._helpers import _pb_timestamp_to_datetime\n return _pb_timestamp_to_datetime(timestamp)\n \n def test_it(self):\n import datetime\n from google.protobuf.timestamp_pb2 import Timestamp\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n # Epoch is midnight on January 1, 1970 ...\n dt_stamp = datetime.datetime(1970, month=1, day=1, hour=0,\n@@ -778,7 +778,7 @@ def test_it(self):\n class Test__pb_timestamp_to_rfc3339(unittest.TestCase):\n \n def _callFUT(self, timestamp):\n- from gcloud._helpers import _pb_timestamp_to_rfc3339\n+ from google.cloud._helpers import _pb_timestamp_to_rfc3339\n return _pb_timestamp_to_rfc3339(timestamp)\n \n def test_it(self):\n@@ -795,13 +795,13 @@ def test_it(self):\n class Test__datetime_to_pb_timestamp(unittest.TestCase):\n \n def _callFUT(self, when):\n- from gcloud._helpers import _datetime_to_pb_timestamp\n+ from google.cloud._helpers import _datetime_to_pb_timestamp\n return _datetime_to_pb_timestamp(when)\n \n def test_it(self):\n import datetime\n from google.protobuf.timestamp_pb2 import Timestamp\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n # Epoch is midnight on January 1, 1970 ...\n dt_stamp = datetime.datetime(1970, month=1, day=1, hour=0,\n@@ -820,7 +820,7 @@ class Test__name_from_project_path(unittest.TestCase):\n TEMPLATE = r'projects/(?P\\w+)/things/(?P\\w+)'\n \n def _callFUT(self, path, project, template):\n- from gcloud._helpers import _name_from_project_path\n+ from google.cloud._helpers import _name_from_project_path\n return _name_from_project_path(path, project, template)\n \n def test_w_invalid_path_length(self):\n@@ -858,7 +858,7 @@ def test_w_project_passed_as_none(self):\n class TestMetadataPlugin(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud._helpers import MetadataPlugin\n+ from google.cloud._helpers import MetadataPlugin\n return MetadataPlugin\n \n def _makeOne(self, *args, **kwargs):\n@@ -894,12 +894,12 @@ def callback(*args):\n class Test_make_stub(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud._helpers import make_stub\n+ from google.cloud._helpers import make_stub\n return make_stub(*args, **kwargs)\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud import _helpers as MUT\n+ from google.cloud import _helpers as MUT\n \n mock_result = object()\n stub_inputs = []\n@@ -972,7 +972,7 @@ def mock_plugin(*args):\n class Test_exc_to_code(unittest.TestCase):\n \n def _callFUT(self, exc):\n- from gcloud._helpers import exc_to_code\n+ from google.cloud._helpers import exc_to_code\n return exc_to_code(exc)\n \n def test_with_stable(self):\ndiff --git a/unit_tests/test_client.py b/unit_tests/test_client.py\n--- a/unit_tests/test_client.py\n+++ b/unit_tests/test_client.py\n@@ -18,7 +18,7 @@\n class Test_ClientFactoryMixin(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.client import _ClientFactoryMixin\n+ from google.cloud.client import _ClientFactoryMixin\n return _ClientFactoryMixin\n \n def test_virtual(self):\n@@ -38,7 +38,7 @@ def tearDown(self):\n KLASS._connection_class = self.original_cnxn_class\n \n def _getTargetClass(self):\n- from gcloud.client import Client\n+ from google.cloud.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n@@ -46,7 +46,7 @@ def _makeOne(self, *args, **kw):\n \n def test_ctor_defaults(self):\n from unit_tests._testing import _Monkey\n- from gcloud import client\n+ from google.cloud import client\n \n CREDENTIALS = object()\n FUNC_CALLS = []\n@@ -73,7 +73,7 @@ def test_ctor_explicit(self):\n \n def test_from_service_account_json(self):\n from unit_tests._testing import _Monkey\n- from gcloud import client\n+ from google.cloud import client\n \n KLASS = self._getTargetClass()\n MOCK_FILENAME = 'foo.path'\n@@ -93,7 +93,7 @@ def test_from_service_account_json_fail(self):\n \n def test_from_service_account_p12(self):\n from unit_tests._testing import _Monkey\n- from gcloud import client\n+ from google.cloud import client\n \n KLASS = self._getTargetClass()\n CLIENT_EMAIL = 'phred@example.com'\n@@ -127,7 +127,7 @@ def tearDown(self):\n KLASS._connection_class = self.original_cnxn_class\n \n def _getTargetClass(self):\n- from gcloud.client import JSONClient\n+ from google.cloud.client import JSONClient\n return JSONClient\n \n def _makeOne(self, *args, **kw):\n@@ -135,7 +135,7 @@ def _makeOne(self, *args, **kw):\n \n def test_ctor_defaults(self):\n from unit_tests._testing import _Monkey\n- from gcloud import client\n+ from google.cloud import client\n \n PROJECT = 'PROJECT'\n CREDENTIALS = object()\n@@ -162,7 +162,7 @@ def mock_get_credentials():\n \n def test_ctor_missing_project(self):\n from unit_tests._testing import _Monkey\n- from gcloud import client\n+ from google.cloud import client\n \n FUNC_CALLS = []\n \ndiff --git a/unit_tests/test_connection.py b/unit_tests/test_connection.py\n--- a/unit_tests/test_connection.py\n+++ b/unit_tests/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.connection import Connection\n+ from google.cloud.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\n@@ -69,8 +69,8 @@ def test_http_w_creds(self):\n \n def test_user_agent_format(self):\n from pkg_resources import get_distribution\n- expected_ua = 'gcloud-python/{0}'.format(\n- get_distribution('gcloud').version)\n+ expected_ua = 'google-cloud-python/{0}'.format(\n+ get_distribution('google-cloud').version)\n conn = self._makeOne()\n self.assertEqual(conn.USER_AGENT, expected_ua)\n \n@@ -78,7 +78,7 @@ def test_user_agent_format(self):\n class TestJSONConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.connection import JSONConnection\n+ from google.cloud.connection import JSONConnection\n return JSONConnection\n \n def _makeOne(self, *args, **kw):\n@@ -316,7 +316,7 @@ def test_api_request_w_data(self):\n self.assertEqual(http._called_with['headers'], expected_headers)\n \n def test_api_request_w_404(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n conn = self._makeMockOne()\n conn._http = _Http(\n {'status': '404', 'content-type': 'text/plain'},\n@@ -325,7 +325,7 @@ def test_api_request_w_404(self):\n self.assertRaises(NotFound, conn.api_request, 'GET', '/')\n \n def test_api_request_w_500(self):\n- from gcloud.exceptions import InternalServerError\n+ from google.cloud.exceptions import InternalServerError\n conn = self._makeMockOne()\n conn._http = _Http(\n {'status': '500', 'content-type': 'text/plain'},\ndiff --git a/unit_tests/test_credentials.py b/unit_tests/test_credentials.py\n--- a/unit_tests/test_credentials.py\n+++ b/unit_tests/test_credentials.py\n@@ -18,12 +18,12 @@\n class Test_get_credentials(unittest.TestCase):\n \n def _callFUT(self):\n- from gcloud import credentials\n+ from google.cloud import credentials\n return credentials.get_credentials()\n \n def test_it(self):\n from unit_tests._testing import _Monkey\n- from gcloud import credentials as MUT\n+ from google.cloud import credentials as MUT\n \n client = _Client()\n with _Monkey(MUT, client=client):\n@@ -36,7 +36,7 @@ def test_it(self):\n class Test_generate_signed_url(unittest.TestCase):\n \n def _callFUT(self, *args, **kwargs):\n- from gcloud.credentials import generate_signed_url\n+ from google.cloud.credentials import generate_signed_url\n return generate_signed_url(*args, **kwargs)\n \n def _generate_helper(self, response_type=None, response_disposition=None,\n@@ -45,7 +45,7 @@ def _generate_helper(self, response_type=None, response_disposition=None,\n from six.moves.urllib.parse import parse_qs\n from six.moves.urllib.parse import urlsplit\n from unit_tests._testing import _Monkey\n- from gcloud import credentials as MUT\n+ from google.cloud import credentials as MUT\n \n ENDPOINT = 'http://api.example.com'\n RESOURCE = '/name/path'\n@@ -104,7 +104,7 @@ def test_w_custom_fields(self):\n class Test_generate_signed_url_exception(unittest.TestCase):\n def test_with_google_credentials(self):\n import time\n- from gcloud.credentials import generate_signed_url\n+ from google.cloud.credentials import generate_signed_url\n RESOURCE = '/name/path'\n \n credentials = _GoogleCredentials()\n@@ -116,7 +116,7 @@ def test_with_google_credentials(self):\n class Test__get_signed_query_params(unittest.TestCase):\n \n def _callFUT(self, credentials, expiration, string_to_sign):\n- from gcloud.credentials import _get_signed_query_params\n+ from google.cloud.credentials import _get_signed_query_params\n return _get_signed_query_params(credentials, expiration,\n string_to_sign)\n \n@@ -143,7 +143,7 @@ def test_it(self):\n class Test__get_expiration_seconds(unittest.TestCase):\n \n def _callFUT(self, expiration):\n- from gcloud.credentials import _get_expiration_seconds\n+ from google.cloud.credentials import _get_expiration_seconds\n return _get_expiration_seconds(expiration)\n \n def _utc_seconds(self, when):\n@@ -174,7 +174,7 @@ def test_w_naive_datetime(self):\n \n def test_w_utc_datetime(self):\n import datetime\n- from gcloud._helpers import UTC\n+ from google.cloud._helpers import UTC\n \n expiration_utc = datetime.datetime(2004, 8, 19, 0, 0, 0, 0, UTC)\n utc_seconds = self._utc_seconds(expiration_utc)\n@@ -182,7 +182,7 @@ def test_w_utc_datetime(self):\n \n def test_w_other_zone_datetime(self):\n import datetime\n- from gcloud._helpers import _UTC\n+ from google.cloud._helpers import _UTC\n \n class CET(_UTC):\n _tzname = 'CET'\n@@ -197,7 +197,7 @@ class CET(_UTC):\n def test_w_timedelta_seconds(self):\n import datetime\n from unit_tests._testing import _Monkey\n- from gcloud import credentials as MUT\n+ from google.cloud import credentials as MUT\n \n dummy_utcnow = datetime.datetime(2004, 8, 19, 0, 0, 0, 0)\n utc_seconds = self._utc_seconds(dummy_utcnow)\n@@ -211,7 +211,7 @@ def test_w_timedelta_seconds(self):\n def test_w_timedelta_days(self):\n import datetime\n from unit_tests._testing import _Monkey\n- from gcloud import credentials as MUT\n+ from google.cloud import credentials as MUT\n \n dummy_utcnow = datetime.datetime(2004, 8, 19, 0, 0, 0, 0)\n utc_seconds = self._utc_seconds(dummy_utcnow)\ndiff --git a/unit_tests/test_exceptions.py b/unit_tests/test_exceptions.py\n--- a/unit_tests/test_exceptions.py\n+++ b/unit_tests/test_exceptions.py\n@@ -15,11 +15,11 @@\n import unittest\n \n \n-class Test_GCloudError(unittest.TestCase):\n+class Test_GoogleCloudError(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.exceptions import GCloudError\n- return GCloudError\n+ from google.cloud.exceptions import GoogleCloudError\n+ return GoogleCloudError\n \n def _makeOne(self, message, errors=()):\n return self._getTargetClass()(message, errors=errors)\n@@ -49,12 +49,12 @@ def test_ctor_explicit(self):\n class Test_make_exception(unittest.TestCase):\n \n def _callFUT(self, response, content, error_info=None, use_json=True):\n- from gcloud.exceptions import make_exception\n+ from google.cloud.exceptions import make_exception\n return make_exception(response, content, error_info=error_info,\n use_json=use_json)\n \n def test_hit_w_content_as_str(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n response = _Response(404)\n content = b'{\"error\": {\"message\": \"Not Found\"}}'\n exception = self._callFUT(response, content)\n@@ -63,7 +63,7 @@ def test_hit_w_content_as_str(self):\n self.assertEqual(list(exception.errors), [])\n \n def test_miss_w_content_as_dict(self):\n- from gcloud.exceptions import GCloudError\n+ from google.cloud.exceptions import GoogleCloudError\n ERROR = {\n 'domain': 'global',\n 'location': 'test',\n@@ -74,12 +74,12 @@ def test_miss_w_content_as_dict(self):\n response = _Response(600)\n content = {\"error\": {\"message\": \"Unknown Error\", \"errors\": [ERROR]}}\n exception = self._callFUT(response, content)\n- self.assertTrue(isinstance(exception, GCloudError))\n+ self.assertTrue(isinstance(exception, GoogleCloudError))\n self.assertEqual(exception.message, 'Unknown Error')\n self.assertEqual(list(exception.errors), [ERROR])\n \n def test_html_when_json_expected(self):\n- from gcloud.exceptions import NotFound\n+ from google.cloud.exceptions import NotFound\n response = _Response(NotFound.code)\n content = '404 Not Found'\n exception = self._callFUT(response, content, use_json=True)\ndiff --git a/unit_tests/test_iterator.py b/unit_tests/test_iterator.py\n--- a/unit_tests/test_iterator.py\n+++ b/unit_tests/test_iterator.py\n@@ -18,7 +18,7 @@\n class TestIterator(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.iterator import Iterator\n+ from google.cloud.iterator import Iterator\n return Iterator\n \n def _makeOne(self, *args, **kw):\n@@ -175,7 +175,7 @@ def test_get_items_from_response_raises_NotImplementedError(self):\n class TestMethodIterator(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.iterator import MethodIterator\n+ from google.cloud.iterator import MethodIterator\n return MethodIterator\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/test_operation.py b/unit_tests/test_operation.py\n--- a/unit_tests/test_operation.py\n+++ b/unit_tests/test_operation.py\n@@ -18,14 +18,14 @@\n class Test__compute_type_url(unittest.TestCase):\n \n def _callFUT(self, klass, prefix=None):\n- from gcloud.operation import _compute_type_url\n+ from google.cloud.operation import _compute_type_url\n if prefix is None:\n return _compute_type_url(klass)\n return _compute_type_url(klass, prefix)\n \n def test_wo_prefix(self):\n from google.protobuf.struct_pb2 import Struct\n- from gcloud.operation import _GOOGLE_APIS_PREFIX\n+ from google.cloud.operation import _GOOGLE_APIS_PREFIX\n \n type_url = self._callFUT(Struct)\n \n@@ -35,7 +35,7 @@ def test_wo_prefix(self):\n \n def test_w_prefix(self):\n from google.protobuf.struct_pb2 import Struct\n- PREFIX = 'test.gcloud-python.com'\n+ PREFIX = 'test.google-cloud-python.com'\n \n type_url = self._callFUT(Struct, PREFIX)\n \n@@ -47,13 +47,13 @@ def test_w_prefix(self):\n class Test__register_type_url(unittest.TestCase):\n \n def _callFUT(self, type_url, klass):\n- from gcloud.operation import _register_type_url\n+ from google.cloud.operation import _register_type_url\n _register_type_url(type_url, klass)\n \n def test_simple(self):\n- from gcloud import operation as MUT\n+ from google.cloud import operation as MUT\n from unit_tests._testing import _Monkey\n- TYPE_URI = 'testing.gcloud-python.com/testing'\n+ TYPE_URI = 'testing.google-cloud-python.com/testing'\n klass = object()\n type_url_map = {}\n \n@@ -63,9 +63,9 @@ def test_simple(self):\n self.assertEqual(type_url_map, {TYPE_URI: klass})\n \n def test_w_same_class(self):\n- from gcloud import operation as MUT\n+ from google.cloud import operation as MUT\n from unit_tests._testing import _Monkey\n- TYPE_URI = 'testing.gcloud-python.com/testing'\n+ TYPE_URI = 'testing.google-cloud-python.com/testing'\n klass = object()\n type_url_map = {TYPE_URI: klass}\n \n@@ -75,9 +75,9 @@ def test_w_same_class(self):\n self.assertEqual(type_url_map, {TYPE_URI: klass})\n \n def test_w_conflict(self):\n- from gcloud import operation as MUT\n+ from google.cloud import operation as MUT\n from unit_tests._testing import _Monkey\n- TYPE_URI = 'testing.gcloud-python.com/testing'\n+ TYPE_URI = 'testing.google-cloud-python.com/testing'\n klass, other = object(), object()\n type_url_map = {TYPE_URI: other}\n \n@@ -93,7 +93,7 @@ class OperationTests(unittest.TestCase):\n OPERATION_NAME = 'operations/projects/foo/instances/bar/operations/123'\n \n def _getTargetClass(self):\n- from gcloud.operation import Operation\n+ from google.cloud.operation import Operation\n return Operation\n \n def _makeOne(self, *args, **kw):\n@@ -157,7 +157,7 @@ def test_from_pb_w_metadata_and_kwargs(self):\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n from google.protobuf.struct_pb2 import Struct, Value\n- from gcloud import operation as MUT\n+ from google.cloud import operation as MUT\n from unit_tests._testing import _Monkey\n TYPE_URI = 'type.googleapis.com/%s' % (Struct.DESCRIPTOR.full_name,)\n type_url_map = {TYPE_URI: Struct}\ndiff --git a/unit_tests/translate/test_client.py b/unit_tests/translate/test_client.py\n--- a/unit_tests/translate/test_client.py\n+++ b/unit_tests/translate/test_client.py\n@@ -20,15 +20,15 @@ class TestClient(unittest.TestCase):\n KEY = 'abc-123-my-key'\n \n def _getTargetClass(self):\n- from gcloud.translate.client import Client\n+ from google.cloud.translate.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_ctor(self):\n- from gcloud.translate.connection import Connection\n- from gcloud.translate.client import ENGLISH_ISO_639\n+ from google.cloud.translate.connection import Connection\n+ from google.cloud.translate.client import ENGLISH_ISO_639\n \n http = object()\n client = self._makeOne(self.KEY, http=http)\n@@ -38,7 +38,7 @@ def test_ctor(self):\n self.assertEqual(client.target_language, ENGLISH_ISO_639)\n \n def test_ctor_non_default(self):\n- from gcloud.translate.connection import Connection\n+ from google.cloud.translate.connection import Connection\n \n http = object()\n target = 'es'\n@@ -49,7 +49,7 @@ def test_ctor_non_default(self):\n self.assertEqual(client.target_language, target)\n \n def test_get_languages(self):\n- from gcloud.translate.client import ENGLISH_ISO_639\n+ from google.cloud.translate.client import ENGLISH_ISO_639\n \n client = self._makeOne(self.KEY)\n supported = [\ndiff --git a/unit_tests/translate/test_connection.py b/unit_tests/translate/test_connection.py\n--- a/unit_tests/translate/test_connection.py\n+++ b/unit_tests/translate/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.translate.connection import Connection\n+ from google.cloud.translate.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/vision/test_client.py b/unit_tests/vision/test_client.py\n--- a/unit_tests/vision/test_client.py\n+++ b/unit_tests/vision/test_client.py\n@@ -16,7 +16,7 @@\n import base64\n import unittest\n \n-from gcloud._helpers import _to_bytes\n+from google.cloud._helpers import _to_bytes\n \n \n class TestClient(unittest.TestCase):\n@@ -26,7 +26,7 @@ class TestClient(unittest.TestCase):\n B64_IMAGE_CONTENT = base64.b64encode(IMAGE_CONTENT)\n \n def _getTargetClass(self):\n- from gcloud.vision.client import Client\n+ from google.cloud.vision.client import Client\n return Client\n \n def _makeOne(self, *args, **kw):\n@@ -39,9 +39,9 @@ def test_ctor(self):\n self.assertTrue('annotate' in dir(client))\n \n def test_face_annotation(self):\n+ from google.cloud.vision._fixtures import FACE_DETECTION_RESPONSE\n \n- from gcloud.vision._fixtures import FACE_DETECTION_RESPONSE as RETURNED\n-\n+ RETURNED = FACE_DETECTION_RESPONSE\n REQUEST = {\n \"requests\": [\n {\n@@ -61,7 +61,7 @@ def test_face_annotation(self):\n client = self._makeOne(project=self.PROJECT, credentials=credentials)\n client.connection = _Connection(RETURNED)\n \n- from gcloud.vision.feature import Feature, FeatureTypes\n+ from google.cloud.vision.feature import Feature, FeatureTypes\n \n features = [Feature(feature_type=FeatureTypes.FACE_DETECTION,\n max_results=3)]\n@@ -78,14 +78,14 @@ class TestVisionRequest(unittest.TestCase):\n _IMAGE_CONTENT = _to_bytes('/9j/4QNURXhpZgAASUkq')\n \n def _getTargetClass(self):\n- from gcloud.vision.client import VisionRequest\n+ from google.cloud.vision.client import VisionRequest\n return VisionRequest\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_make_vision_request(self):\n- from gcloud.vision.feature import Feature, FeatureTypes\n+ from google.cloud.vision.feature import Feature, FeatureTypes\n feature = Feature(feature_type=FeatureTypes.FACE_DETECTION,\n max_results=3)\n vision_request = self._makeOne(self._IMAGE_CONTENT, feature)\ndiff --git a/unit_tests/vision/test_connection.py b/unit_tests/vision/test_connection.py\n--- a/unit_tests/vision/test_connection.py\n+++ b/unit_tests/vision/test_connection.py\n@@ -18,7 +18,7 @@\n class TestConnection(unittest.TestCase):\n \n def _getTargetClass(self):\n- from gcloud.vision.connection import Connection\n+ from google.cloud.vision.connection import Connection\n return Connection\n \n def _makeOne(self, *args, **kw):\ndiff --git a/unit_tests/vision/test_feature.py b/unit_tests/vision/test_feature.py\n--- a/unit_tests/vision/test_feature.py\n+++ b/unit_tests/vision/test_feature.py\n@@ -17,14 +17,14 @@\n \n class TestFeature(unittest.TestCase):\n def _getTargetClass(self):\n- from gcloud.vision.feature import Feature\n+ from google.cloud.vision.feature import Feature\n return Feature\n \n def _makeOne(self, *args, **kw):\n return self._getTargetClass()(*args, **kw)\n \n def test_construct_feature(self):\n- from gcloud.vision.feature import FeatureTypes\n+ from google.cloud.vision.feature import FeatureTypes\n feature = self._makeOne(FeatureTypes.LABEL_DETECTION)\n self.assertEqual(1, feature.max_results)\n self.assertEqual('LABEL_DETECTION', feature.feature_type)\n@@ -34,7 +34,7 @@ def test_construct_feature(self):\n self.assertEqual('FACE_DETECTION', feature.feature_type)\n \n def test_feature_as_dict(self):\n- from gcloud.vision.feature import FeatureTypes\n+ from google.cloud.vision.feature import FeatureTypes\n feature = self._makeOne(FeatureTypes.FACE_DETECTION, max_results=5)\n EXPECTED = {\n 'type': 'FACE_DETECTION',\ndiff --git a/unit_tests/vision/test_image.py b/unit_tests/vision/test_image.py\n--- a/unit_tests/vision/test_image.py\n+++ b/unit_tests/vision/test_image.py\n@@ -15,7 +15,7 @@\n import unittest\n import base64\n \n-from gcloud._helpers import _to_bytes\n+from google.cloud._helpers import _to_bytes\n \n \n class TestVisionImage(unittest.TestCase):\n@@ -25,7 +25,7 @@ class TestVisionImage(unittest.TestCase):\n _CLIENT_MOCK = {'source': ''}\n \n def _getTargetClass(self):\n- from gcloud.vision.image import Image\n+ from google.cloud.vision.image import Image\n return Image\n \n def _makeOne(self, *args, **kw):\n@@ -42,7 +42,7 @@ def test_image_source_type_content(self):\n self.assertEqual(None, image.source)\n self.assertEqual(_AS_DICT, image.as_dict())\n \n- def test_image_source_type_gcloud_storage(self):\n+ def test_image_source_type_google_cloud_storage(self):\n image = self._makeOne(self._IMAGE_SOURCE, self._CLIENT_MOCK)\n \n _AS_DICT = {\n", "problem_statement": "", "hints_text": "", "created_at": "2016-08-30T18:42:57Z"} diff --git a/PythonDataset/test/isso-task-instances.jsonl.all b/PythonDataset/test/isso-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..81bd7f3ada9766c7dd92cdbe1f6538f326499b7d --- /dev/null +++ b/PythonDataset/test/isso-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "isso-comments/isso", "pull_number": 485, "instance_id": "isso-comments__isso-485", "issue_numbers": "", "base_commit": "8e37a88d6d2b5fa3485f9aff39ff4b452ce2f578", "patch": "diff --git a/isso/utils/html.py b/isso/utils/html.py\n--- a/isso/utils/html.py\n+++ b/isso/utils/html.py\n@@ -6,61 +6,53 @@\n \n from distutils.version import LooseVersion as Version\n \n-HTML5LIB_VERSION = Version(pkg_resources.get_distribution(\"html5lib\").version)\n-HTML5LIB_SIMPLETREE = Version(\"0.95\")\n-\n-import html5lib\n-from html5lib.sanitizer import HTMLSanitizer\n-from html5lib.serializer import HTMLSerializer\n-\n+import bleach\n import misaka\n \n \n-def Sanitizer(elements, attributes):\n-\n- class Inner(HTMLSanitizer):\n+class Sanitizer(object):\n \n+ def __init__(self, elements, attributes):\n # attributes found in Sundown's HTML serializer [1]\n # except for tag,\n # because images are not generated anyways.\n #\n # [1] https://github.com/vmg/sundown/blob/master/html/html.c\n- allowed_elements = [\"a\", \"p\", \"hr\", \"br\", \"ol\", \"ul\", \"li\",\n+ self.elements = [\"a\", \"p\", \"hr\", \"br\", \"ol\", \"ul\", \"li\",\n \"pre\", \"code\", \"blockquote\",\n \"del\", \"ins\", \"strong\", \"em\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\",\n \"table\", \"thead\", \"tbody\", \"th\", \"td\"] + elements\n \n # href for and align for \n- allowed_attributes = [\"align\", \"href\"] + attributes\n-\n- # remove disallowed tokens from the output\n- def disallowed_token(self, token, token_type):\n- return None\n+ self.attributes = [\"align\", \"href\"] + attributes\n \n- return Inner\n \n \n-def sanitize(tokenizer, document):\n+ def sanitize(self, text):\n+ clean_html = bleach.clean(text, tags=self.elements,\n+ attributes=self.attributes, strip=True)\n \n- parser = html5lib.HTMLParser(tokenizer=tokenizer)\n- domtree = parser.parseFragment(document)\n+ def set_links(attrs, new=False):\n+ href_key = (None, u'href')\n \n- if HTML5LIB_VERSION > HTML5LIB_SIMPLETREE:\n- builder = \"etree\"\n+ if href_key not in attrs:\n+ return attrs\n+ if attrs[href_key].startswith(u'mailto:'):\n+ return attrs\n \n- for link in domtree.findall(\".//{http://www.w3.org/1999/xhtml}a\"):\n- if link.get('href', None):\n- link.set(\"rel\", \"nofollow noopener\")\n+ rel_key = (None, u'rel')\n+ rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]\n \n- else:\n- builder = \"simpletree\"\n+ for value in [u'nofollow', u'noopener']:\n+ if value not in [rel_val.lower() for rel_val in rel_values]:\n+ rel_values.append(value)\n \n- stream = html5lib.treewalkers.getTreeWalker(builder)(domtree)\n- serializer = HTMLSerializer(\n- quote_attr_values=True, omit_optional_tags=False)\n+ attrs[rel_key] = u' '.join(rel_values)\n+ return attrs\n \n- return serializer.render(stream)\n+ linker = bleach.linkifier.Linker(callbacks=[set_links])\n+ return linker.linkify(clean_html)\n \n \n def Markdown(extensions=(\"strikethrough\", \"superscript\", \"autolink\",\n@@ -100,7 +92,7 @@ def __init__(self, conf):\n conf.getlist(\"allowed-elements\"),\n conf.getlist(\"allowed-attributes\"))\n \n- self._render = lambda text: sanitize(sanitizer, parser(text))\n+ self._render = lambda text: sanitizer.sanitize(parser(text))\n \n def render(self, text):\n return self._render(text)\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -5,8 +5,8 @@\n \n from setuptools import setup, find_packages\n \n-requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib<0.9999999',\n- 'werkzeug>=0.9']\n+requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',\n+ 'werkzeug>=0.9', 'bleach']\n \n if sys.version_info < (2, 7):\n raise SystemExit(\"Python 2 versions < 2.7 are not supported.\")\n", "test_patch": "diff --git a/isso/tests/test_html.py b/isso/tests/test_html.py\n--- a/isso/tests/test_html.py\n+++ b/isso/tests/test_html.py\n@@ -59,7 +59,6 @@ def test_github_flavoured_markdown(self):\n print(\"Hello, World\")\n \"\"\")\n \n- @unittest.skipIf(html.HTML5LIB_VERSION <= html.HTML5LIB_SIMPLETREE, \"backport\")\n def test_sanitizer(self):\n sanitizer = html.Sanitizer(elements=[], attributes=[])\n examples = [\n@@ -73,11 +72,10 @@ def test_sanitizer(self):\n \n for (input, expected) in examples:\n if isinstance(expected, list):\n- self.assertIn(html.sanitize(sanitizer, input), expected)\n+ self.assertIn(sanitizer.sanitize(input), expected)\n else:\n- self.assertEqual(html.sanitize(sanitizer, input), expected)\n+ self.assertEqual(sanitizer.sanitize(input), expected)\n \n- @unittest.skipIf(html.HTML5LIB_VERSION <= html.HTML5LIB_SIMPLETREE, \"backport\")\n def test_sanitizer_extensions(self):\n sanitizer = html.Sanitizer(elements=[\"img\"], attributes=[\"src\"])\n examples = [\n@@ -85,7 +83,7 @@ def test_sanitizer_extensions(self):\n ('', '')]\n \n for (input, expected) in examples:\n- self.assertEqual(html.sanitize(sanitizer, input), expected)\n+ self.assertEqual(sanitizer.sanitize(input), expected)\n \n def test_render(self):\n conf = config.new({\n", "problem_statement": "", "hints_text": "", "created_at": "2018-10-01T02:51:13Z"} diff --git a/PythonDataset/test/libcloud-task-instances.jsonl.all b/PythonDataset/test/libcloud-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..3b3ca86a6b2ac77a9c50e5aa0b1e51bc258a5f72 --- /dev/null +++ b/PythonDataset/test/libcloud-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "apache/libcloud", "pull_number": 1280, "instance_id": "apache__libcloud-1280", "issue_numbers": "", "base_commit": "e8735a71023a46c24b715830358ee59039b45704", "patch": "diff --git a/libcloud/common/google.py b/libcloud/common/google.py\n--- a/libcloud/common/google.py\n+++ b/libcloud/common/google.py\n@@ -24,7 +24,7 @@\n Both are initially set up from the Cloud Console Console -\n https://cloud.google.com/console\n \n-Setting up Service Account authentication (note that you need the PyCrypto\n+Setting up Service Account authentication (note that you need the cryptography\n package installed to use this):\n \n - Go to the Console\n@@ -89,16 +89,13 @@\n LibcloudError)\n \n try:\n- from Crypto.Hash import SHA256\n- from Crypto.PublicKey import RSA\n- from Crypto.Signature import PKCS1_v1_5\n- import Crypto.Random\n- Crypto.Random.atfork()\n+ from cryptography.hazmat.backends import default_backend\n+ from cryptography.hazmat.primitives import serialization\n+ from cryptography.hazmat.primitives.hashes import SHA256\n+ from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15\n except ImportError:\n- # The pycrypto library is unavailable\n+ # The cryptography library is unavailable\n SHA256 = None\n- RSA = None\n- PKCS1_v1_5 = None\n \n UTC_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%SZ'\n \n@@ -472,8 +469,8 @@ class GoogleServiceAcctAuthConnection(GoogleBaseAuthConnection):\n \"\"\"Authentication class for \"Service Account\" authentication.\"\"\"\n def __init__(self, user_id, key, *args, **kwargs):\n \"\"\"\n- Check to see if PyCrypto is available, and convert key file path into a\n- key string if the key is in a file.\n+ Check to see if cryptography is available, and convert key file path\n+ into a key string if the key is in a file.\n \n :param user_id: Email address to be used for Service Account\n authentication.\n@@ -483,7 +480,7 @@ def __init__(self, user_id, key, *args, **kwargs):\n :type key: ``str``\n \"\"\"\n if SHA256 is None:\n- raise GoogleAuthError('PyCrypto library required for '\n+ raise GoogleAuthError('cryptography library required for '\n 'Service Account Authentication.')\n # Check to see if 'key' is a file and read the file if it is.\n if key.find(\"PRIVATE KEY---\") == -1:\n@@ -526,10 +523,17 @@ def get_new_token(self):\n # The message contains both the header and claim set\n message = b'.'.join((header_enc, claim_set_enc))\n # Then the message is signed using the key supplied\n- key = RSA.importKey(self.key)\n- hash_func = SHA256.new(message)\n- signer = PKCS1_v1_5.new(key)\n- signature = base64.urlsafe_b64encode(signer.sign(hash_func))\n+ key = serialization.load_pem_private_key(\n+ b(self.key),\n+ password=None,\n+ backend=default_backend()\n+ )\n+ signature = key.sign(\n+ data=b(message),\n+ padding=PKCS1v15(),\n+ algorithm=SHA256()\n+ )\n+ signature = base64.urlsafe_b64encode(signature)\n \n # Finally the message and signature are sent to get a token\n jwt = b'.'.join((message, signature))\ndiff --git a/libcloud/compute/drivers/softlayer.py b/libcloud/compute/drivers/softlayer.py\n--- a/libcloud/compute/drivers/softlayer.py\n+++ b/libcloud/compute/drivers/softlayer.py\n@@ -18,7 +18,9 @@\n \n import time\n try:\n- from Crypto.PublicKey import RSA\n+ from cryptography.hazmat.primitives.asymmetric import rsa\n+ from cryptography.hazmat.backends import default_backend\n+ from cryptography.hazmat.primitives import serialization\n crypto = True\n except ImportError:\n crypto = False\n@@ -386,17 +388,29 @@ def get_key_pair(self, name):\n def create_key_pair(self, name, ex_size=4096):\n if crypto is False:\n raise NotImplementedError('create_key_pair needs'\n- 'the pycrypto library')\n- key = RSA.generate(ex_size)\n+ 'the cryptography library')\n+ key = rsa.generate_private_key(\n+ public_exponent=65537,\n+ key_size=4096,\n+ backend=default_backend()\n+ )\n+ public_key = key.public_key().public_bytes(\n+ encoding=serialization.Encoding.OpenSSH,\n+ format=serialization.PublicFormat.OpenSSH\n+ )\n new_key = {\n- 'key': key.publickey().exportKey('OpenSSH'),\n+ 'key': public_key,\n 'label': name,\n 'notes': '',\n }\n result = self.connection.request(\n 'SoftLayer_Security_Ssh_Key', 'createObject', new_key\n ).object\n- result['private'] = key.exportKey('PEM')\n+ result['private'] = key.private_bytes(\n+ encoding=serialization.Encoding.PEM,\n+ format=serialization.PrivateFormat.TraditionalOpenSSL,\n+ encryption_algorithm=serialization.NoEncryption()\n+ )\n return self._to_key_pair(result)\n \n def import_key_pair_from_string(self, name, key_material):\ndiff --git a/libcloud/utils/publickey.py b/libcloud/utils/publickey.py\n--- a/libcloud/utils/publickey.py\n+++ b/libcloud/utils/publickey.py\n@@ -17,7 +17,7 @@\n import hashlib\n \n from libcloud.utils.py3 import hexadigits\n-from libcloud.utils.py3 import bchr\n+from libcloud.utils.py3 import b\n \n __all__ = [\n 'get_pubkey_openssh_fingerprint',\n@@ -26,11 +26,11 @@\n ]\n \n try:\n- from Crypto.Util.asn1 import DerSequence, DerObject\n- from Crypto.PublicKey.RSA import algorithmIdentifier, importKey\n- pycrypto_available = True\n+ from cryptography.hazmat.backends import default_backend\n+ from cryptography.hazmat.primitives import serialization\n+ cryptography_available = True\n except ImportError:\n- pycrypto_available = False\n+ cryptography_available = False\n \n \n def _to_md5_fingerprint(data):\n@@ -40,25 +40,33 @@ def _to_md5_fingerprint(data):\n \n def get_pubkey_openssh_fingerprint(pubkey):\n # We import and export the key to make sure it is in OpenSSH format\n- if not pycrypto_available:\n- raise RuntimeError('pycrypto is not available')\n- k = importKey(pubkey)\n- pubkey = k.exportKey('OpenSSH')[7:]\n- decoded = base64.decodestring(pubkey)\n- return _to_md5_fingerprint(decoded)\n+ if not cryptography_available:\n+ raise RuntimeError('cryptography is not available')\n+ public_key = serialization.load_ssh_public_key(\n+ b(pubkey),\n+ backend=default_backend()\n+ )\n+ pub_openssh = public_key.public_bytes(\n+ encoding=serialization.Encoding.OpenSSH,\n+ format=serialization.PublicFormat.OpenSSH,\n+ )[7:] # strip ssh-rsa prefix\n+ return _to_md5_fingerprint(base64.decodestring(pub_openssh))\n \n \n def get_pubkey_ssh2_fingerprint(pubkey):\n # This is the format that EC2 shows for public key fingerprints in its\n # KeyPair mgmt API\n- if not pycrypto_available:\n- raise RuntimeError('pycrypto is not available')\n- k = importKey(pubkey)\n- derPK = DerSequence([k.n, k.e])\n- bitmap = DerObject('BIT STRING')\n- bitmap.payload = bchr(0x00) + derPK.encode()\n- der = DerSequence([algorithmIdentifier, bitmap.encode()])\n- return _to_md5_fingerprint(der.encode())\n+ if not cryptography_available:\n+ raise RuntimeError('cryptography is not available')\n+ public_key = serialization.load_ssh_public_key(\n+ b(pubkey),\n+ backend=default_backend()\n+ )\n+ pub_der = public_key.public_bytes(\n+ encoding=serialization.Encoding.DER,\n+ format=serialization.PublicFormat.SubjectPublicKeyInfo,\n+ )\n+ return _to_md5_fingerprint(pub_der)\n \n \n def get_pubkey_comment(pubkey, default=None):\ndiff --git a/libcloud/utils/py3.py b/libcloud/utils/py3.py\n--- a/libcloud/utils/py3.py\n+++ b/libcloud/utils/py3.py\n@@ -126,7 +126,7 @@ def tostring(node):\n \n def hexadigits(s):\n # s needs to be a byte string.\n- return [format(x, \"x\") for x in s]\n+ return [format(x, \"02x\") for x in s]\n \n else:\n import httplib # NOQA\n", "test_patch": "diff --git a/libcloud/test/common/test_google.py b/libcloud/test/common/test_google.py\n--- a/libcloud/test/common/test_google.py\n+++ b/libcloud/test/common/test_google.py\n@@ -40,9 +40,9 @@\n from libcloud.utils.py3 import httplib\n \n \n-# Skip some tests if PyCrypto is unavailable\n+# Skip some tests if cryptography is unavailable\n try:\n- from Crypto.Hash import SHA256\n+ from cryptography.hazmat.primitives.hashes import SHA256\n except ImportError:\n SHA256 = None\n \ndiff --git a/libcloud/test/compute/test_softlayer.py b/libcloud/test/compute/test_softlayer.py\n--- a/libcloud/test/compute/test_softlayer.py\n+++ b/libcloud/test/compute/test_softlayer.py\n@@ -16,12 +16,6 @@\n import unittest\n import sys\n import pytest\n-try:\n- import Crypto\n- Crypto\n- crypto = True\n-except ImportError:\n- crypto = False\n \n from libcloud.common.types import InvalidCredsError\n \n@@ -170,17 +164,13 @@ def test_get_key_pair_does_not_exist(self):\n \n @pytest.mark.skip(reason=\"no way of currently testing this\")\n def test_create_key_pair(self):\n- if crypto:\n- key_pair = self.driver.create_key_pair(name='my-key-pair')\n- fingerprint = ('1f:51:ae:28:bf:89:e9:d8:1f:25:5d'\n- ':37:2d:7d:b8:ca:9f:f5:f1:6f')\n-\n- self.assertEqual(key_pair.name, 'my-key-pair')\n- self.assertEqual(key_pair.fingerprint, fingerprint)\n- self.assertTrue(key_pair.private_key is not None)\n- else:\n- self.assertRaises(NotImplementedError, self.driver.create_key_pair,\n- name='my-key-pair')\n+ key_pair = self.driver.create_key_pair(name='my-key-pair')\n+ fingerprint = ('1f:51:ae:28:bf:89:e9:d8:1f:25:5d'\n+ ':37:2d:7d:b8:ca:9f:f5:f1:6f')\n+\n+ self.assertEqual(key_pair.name, 'my-key-pair')\n+ self.assertEqual(key_pair.fingerprint, fingerprint)\n+ self.assertTrue(key_pair.private_key is not None)\n \n def test_delete_key_pair(self):\n success = self.driver.delete_key_pair('test1')\ndiff --git a/libcloud/test/test_utils.py b/libcloud/test/test_utils.py\n--- a/libcloud/test/test_utils.py\n+++ b/libcloud/test/test_utils.py\n@@ -47,6 +47,10 @@\n from libcloud.utils.networking import increment_ipv4_segments\n from libcloud.utils.decorators import wrap_non_libcloud_exceptions\n from libcloud.utils.connection import get_response_object\n+from libcloud.utils.publickey import (\n+ get_pubkey_openssh_fingerprint,\n+ get_pubkey_ssh2_fingerprint,\n+)\n from libcloud.common.types import LibcloudError\n from libcloud.storage.drivers.dummy import DummyIterator\n \n@@ -385,6 +389,26 @@ def test_increment_ipv4_segments(self):\n self.assertEqual(result, incremented_ip)\n \n \n+class TestPublicKeyUtils(unittest.TestCase):\n+\n+ PUBKEY = (\n+ 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDOfbWSXOlqvYjZmRO84/lIoV4gvuX+'\n+ 'P1lLg50MMg6jZjLZIlYY081XPRmuom0xY0+BO++J2KgLl7gxJ6xMsKK2VQ+TakdfAH20'\n+ 'XfMcTohd/zVCeWsbqZQvEhVXBo4hPIktcfNz0u9Ez3EtInO+kb7raLcRhOVi9QmOkOrC'\n+ 'WtQU9mS71AWJuqI9H0YAnTiI8Hs5bn2tpMIqmTXT3g2bwywC25x1Nx9Hy0/FP+KUL6Ag'\n+ 'vDXv47l+TgSDfTBEkvq+IF1ITrnaOG+nRE02oZC6cwHYTifM/IOollkujxIQmi2Z+j66'\n+ 'OHSrjnEQugr0FqGJF2ygKfIh/i2u3fVLM60qE2NN user@example'\n+ )\n+\n+ def test_pubkey_openssh_fingerprint(self):\n+ fp = get_pubkey_openssh_fingerprint(self.PUBKEY)\n+ self.assertEqual(fp, '35:22:13:5b:82:e2:5d:e1:90:8c:73:74:9f:ef:3b:d8')\n+\n+ def test_pubkey_ssh2_fingerprint(self):\n+ fp = get_pubkey_ssh2_fingerprint(self.PUBKEY)\n+ self.assertEqual(fp, '11:ad:5d:4c:5b:99:c9:80:7e:81:03:76:5a:25:9d:8c')\n+\n+\n def test_decorator():\n \n @wrap_non_libcloud_exceptions\n", "problem_statement": "", "hints_text": "", "created_at": "2019-03-11T14:45:18Z"} diff --git a/PythonDataset/test/maintainer-tools-task-instances.jsonl.all b/PythonDataset/test/maintainer-tools-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..3af243efb0d9749be55939090d943193eccf9d01 --- /dev/null +++ b/PythonDataset/test/maintainer-tools-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "OCA/maintainer-tools", "pull_number": 262, "instance_id": "OCA__maintainer-tools-262", "issue_numbers": "", "base_commit": "405113684e304b2294782a3732618ff3a7ef5705", "patch": "diff --git a/tools/pypi_upload_wheels.py b/tools/pypi_upload_wheels.py\nnew file mode 100644\n--- /dev/null\n+++ b/tools/pypi_upload_wheels.py\n@@ -0,0 +1,182 @@\n+import anydbm\n+import contextlib\n+import logging\n+import os\n+import requests\n+import subprocess\n+from wheel.install import WheelFile\n+from ConfigParser import RawConfigParser\n+from pkg_resources import parse_version\n+\n+import click\n+\n+_logger = logging.getLogger(__name__)\n+\n+\n+def _split_wheelfilename(wheelfilename):\n+ wheelfile = WheelFile(wheelfilename)\n+ package_name = wheelfile.parsed_filename.group('name')\n+ package_name = package_name.replace('_', '-')\n+ package_ver = wheelfile.parsed_filename.group('ver')\n+ package_ver = parse_version(package_ver)\n+ return package_name, package_ver\n+\n+\n+class OcaPypi(object):\n+ \"\"\"A wrapper around twine, with caching\n+ to avoid multiple useless upload attempts for the same file.\"\"\"\n+\n+ def __init__(self, pypirc, repository, cache, dryrun):\n+ parser = RawConfigParser()\n+ parser.read(pypirc)\n+ self.pypirc = pypirc\n+ self.repository = repository\n+ self.repository_url = parser.get(repository, 'repository')\n+ self.cache = cache\n+ self.dryrun = dryrun\n+\n+ def _make_key(self, wheelfilename):\n+ return str(self.repository_url + '#' + os.path.basename(wheelfilename))\n+\n+ def _key_match(self, key):\n+ return key.startswith(self.repository_url + '#')\n+\n+ def _key_to_wheel(self, key):\n+ return key[len(self.repository_url) + 1:]\n+\n+ def _registered(self, wheelfilename):\n+ package_name, package_ver = _split_wheelfilename(wheelfilename)\n+ package_url = self.repository_url + '/' + package_name\n+ r = requests.head(package_url)\n+ return r.status_code == 200\n+\n+ def _register(self, wheelfilename):\n+ cmd = ['twine', 'register', '--config-file', self.pypirc,\n+ '-r', self.repository, wheelfilename]\n+ if not self.dryrun:\n+ try:\n+ subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n+ except subprocess.CalledProcessError as e:\n+ if \"HTTPError: 400 Client Error\" in e.output:\n+ return e.output\n+ raise\n+ else:\n+ _logger.info(\"dryrun: %s\", cmd)\n+\n+ def _upload(self, wheelfilename):\n+ cmd = ['twine', 'upload', '--config-file', self.pypirc,\n+ '-r', self.repository, '--skip-existing', wheelfilename]\n+ if not self.dryrun:\n+ try:\n+ subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n+ except subprocess.CalledProcessError as e:\n+ if \"HTTPError: 400 Client Error\" in e.output:\n+ return e.output\n+ raise\n+ else:\n+ _logger.info(\"dryrun: %s\", cmd)\n+\n+ def upload_wheel(self, wheelfilename):\n+ key = self._make_key(wheelfilename)\n+ with contextlib.closing(anydbm.open(self.cache, 'c')) as dbm:\n+ if key in dbm:\n+ value = dbm[key]\n+ detail = '' if not value else ' (with error)'\n+ _logger.debug(\"skipped %s: found in cache%s\",\n+ wheelfilename, detail)\n+ return\n+ if not self._registered(wheelfilename):\n+ _logger.info(\"registering %s to %s\",\n+ wheelfilename, self.repository_url)\n+ r = self._register(wheelfilename)\n+ if r:\n+ # registration failed, store the error in cache\n+ # so we don't try again, and do not try to upload\n+ _logger.error(\"registering %s to %s failed: %s\",\n+ wheelfilename, self.repository_url, r)\n+ if not self.dryrun:\n+ dbm[key] = r or ''\n+ return\n+ _logger.info(\"uploading %s to %s\",\n+ wheelfilename, self.repository_url)\n+ r = self._upload(wheelfilename)\n+ if r:\n+ _logger.error(\"uploading %s to %s failed: %s\",\n+ wheelfilename, self.repository_url, r)\n+ if not self.dryrun:\n+ dbm[key] = r or ''\n+\n+ def upload_wheels(self, wheelfilenames):\n+ to_upload = []\n+ for wheelfilename in wheelfilenames:\n+ if os.path.isfile(wheelfilename) and \\\n+ wheelfilename.lower().endswith('.whl'):\n+ to_upload.append(wheelfilename)\n+ else:\n+ _logger.warn(\"skipped %s: not a wheel file\", wheelfilename)\n+ for wheelfilename in sorted(to_upload, key=_split_wheelfilename):\n+ self.upload_wheel(wheelfilename)\n+\n+ def cache_print_errors(self):\n+ with contextlib.closing(anydbm.open(self.cache, 'r')) as dbm:\n+ for key, value in dbm.items():\n+ if not self._key_match(key):\n+ continue\n+ if value:\n+ wheel = self._key_to_wheel(key)\n+ click.echo(u\"{}: {}\".format(wheel, value))\n+\n+ def cache_rm_wheels(self, wheelfilenames):\n+ with contextlib.closing(anydbm.open(self.cache, 'w')) as dbm:\n+ for wheelfilename in wheelfilenames:\n+ wheelfilename = os.path.basename(wheelfilename)\n+ key = self._make_key(wheelfilename)\n+ if key in dbm:\n+ del dbm[key]\n+\n+\n+@click.group()\n+@click.option('--pypirc', required=True)\n+@click.option('--repository', required=True)\n+@click.option('--cache', required=True)\n+@click.option('--dryrun/--no-dryrun', default=False)\n+@click.option('--debug/--no-debug', default=False)\n+@click.pass_context\n+def cli(ctx, pypirc, repository, cache, dryrun, debug):\n+ if debug:\n+ level = logging.DEBUG\n+ else:\n+ level = logging.INFO\n+ logging.basicConfig(\n+ format='%(asctime)s:%(levelname)s:%(message)s',\n+ level=level)\n+ ctx.obj = OcaPypi(pypirc, repository, cache, dryrun)\n+\n+\n+@click.command()\n+@click.argument('wheels', nargs=-1)\n+@click.pass_context\n+def upload(ctx, wheels):\n+ ctx.obj.upload_wheels(wheels)\n+\n+\n+@click.command()\n+@click.pass_context\n+def cache_print_errors(ctx):\n+ ctx.obj.cache_print_errors()\n+\n+\n+@click.command()\n+@click.argument('wheels', nargs=-1)\n+@click.pass_context\n+def cache_rm_wheels(ctx, wheels):\n+ ctx.obj.cache_rm_wheels(wheels)\n+\n+\n+cli.add_command(upload)\n+cli.add_command(cache_print_errors)\n+cli.add_command(cache_rm_wheels)\n+\n+\n+if __name__ == '__main__':\n+ cli()\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2017-03-05T17:20:05Z"} diff --git a/PythonDataset/test/mimic-task-instances.jsonl.all b/PythonDataset/test/mimic-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..a7a2fdaf5e6c1e90479040ef85c21fe7ba1b2f09 --- /dev/null +++ b/PythonDataset/test/mimic-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "rackerlabs/mimic", "pull_number": 538, "instance_id": "rackerlabs__mimic-538", "issue_numbers": "", "base_commit": "d3ae1a11db45e4c695f012e10762aaa0ec81941d", "patch": "diff --git a/mimic/model/clb_objects.py b/mimic/model/clb_objects.py\n--- a/mimic/model/clb_objects.py\n+++ b/mimic/model/clb_objects.py\n@@ -12,8 +12,6 @@\n \n import attr\n \n-from characteristic import attributes, Attribute\n-\n from six import text_type\n \n from toolz.dicttoolz import dissoc\n@@ -157,20 +155,40 @@ def full_json(self):\n return result\n \n \n-@attributes([\"keys\"])\n+@attr.s\n class BadKeysError(Exception):\n \"\"\"\n When trying to alter the settings of a load balancer, this exception will\n be raised if you attempt to alter an attribute which doesn't exist.\n \"\"\"\n+ keys = attr.ib()\n+ code = attr.ib(validator=attr.validators.instance_of(int), default=400)\n+\n+ def to_json(self):\n+ \"\"\"\n+ :return: a JSON dict representation of this error.\n+ \"\"\"\n+ return {'message': 'Attempt to alter a bad attribute',\n+ 'code': self.code}\n \n \n-@attributes([\"value\", \"accepted_values\"])\n+@attr.s\n class BadValueError(Exception):\n \"\"\"\n When trying to alter the settings of a load balancer, this exception will\n be raised if you attempt to set a valid attribute to an invalid setting.\n \"\"\"\n+ value = attr.ib()\n+ accepted_values = attr.ib()\n+ code = attr.ib(validator=attr.validators.instance_of(int), default=400)\n+\n+ def to_json(self):\n+ \"\"\"\n+ :return: a JSON dict representation of this error.\n+ \"\"\"\n+ return {'message': ('Unsupported status {0} not one of {1}'.format(\n+ self.value, self.accepted_values)),\n+ 'code': self.code}\n \n \n def node_feed_xml(events):\n@@ -296,7 +314,7 @@ def set_attributes(self, lb_id, kvpairs):\n if k not in supported_keys:\n badKeys.append(k)\n if len(badKeys) > 0:\n- raise BadKeysError(\"Attempt to alter a bad attribute\", keys=badKeys)\n+ raise BadKeysError(keys=badKeys)\n \n if \"status\" in kvpairs:\n supported_statuses = [\n@@ -305,9 +323,6 @@ def set_attributes(self, lb_id, kvpairs):\n s = kvpairs[\"status\"]\n if s not in supported_statuses:\n raise BadValueError(\n- \"Unsupported status {0} not one of {1}\".format(\n- s, supported_statuses\n- ),\n value=s, accepted_values=supported_statuses\n )\n \n@@ -624,8 +639,7 @@ def del_load_balancer(self, lb_id):\n return not_found_response(\"loadbalancer\"), 404\n \n \n-@attributes([\"clock\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalCLBCollections(object):\n \"\"\"\n A :obj:`GlobalCLBCollections` is a set of all the\n@@ -633,6 +647,8 @@ class GlobalCLBCollections(object):\n words, all the objects that a single tenant owns globally in a\n cloud load balancer service.\n \"\"\"\n+ clock = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n \n def collection_for_region(self, region_name):\n \"\"\"\ndiff --git a/mimic/model/customer_objects.py b/mimic/model/customer_objects.py\n--- a/mimic/model/customer_objects.py\n+++ b/mimic/model/customer_objects.py\n@@ -4,16 +4,19 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes, Attribute\n+import attr\n \n \n-@attributes([\"tenant_id\", \"email_address\", \"role\",\n- Attribute(\"first_name\", default_value=\"Test FirstName\"),\n- Attribute(\"last_name\", default_value=\"Test LastName\")])\n+@attr.s\n class Contact(object):\n \"\"\"\n A :obj:`Contact` is a representation for each contact for a tenant.\n \"\"\"\n+ tenant_id = attr.ib()\n+ email_address = attr.ib()\n+ role = attr.ib()\n+ first_name = attr.ib(default=\"Test FirstName\")\n+ last_name = attr.ib(default=\"Test LastName\")\n \n static_defaults = {\n \"firstName\": \"Pat\",\n@@ -72,11 +75,12 @@ def generate_contacts(self):\n return template\n \n \n-@attributes([Attribute(\"contacts_store\", default_factory=dict)])\n+@attr.s\n class ContactsStore(object):\n \"\"\"\n A collection of contact objects for a tenant.\n \"\"\"\n+ contacts_store = attr.ib(default=attr.Factory(dict))\n \n def add_to_contacts_store(self, tenant_id, contact_list):\n \"\"\"\ndiff --git a/mimic/model/flavor_collections.py b/mimic/model/flavor_collections.py\n--- a/mimic/model/flavor_collections.py\n+++ b/mimic/model/flavor_collections.py\n@@ -6,7 +6,7 @@\n \n from six import iteritems\n \n-from characteristic import attributes, Attribute\n+import attr\n from json import dumps\n from mimic.model.flavors import (\n RackspaceStandardFlavor, RackspaceComputeFlavor, RackspaceMemoryFlavor,\n@@ -16,14 +16,16 @@\n from mimic.model.nova_objects import not_found\n \n \n-@attributes(\n- [\"tenant_id\", \"region_name\", \"clock\",\n- Attribute(\"flavors_store\", default_factory=list)]\n-)\n+@attr.s\n class RegionalFlavorCollection(object):\n \"\"\"\n A collection of flavors, in a given region, for a given tenant.\n \"\"\"\n+ tenant_id = attr.ib()\n+ region_name = attr.ib()\n+ clock = attr.ib()\n+ flavors_store = attr.ib(default=attr.Factory(list))\n+\n def flavor_by_id(self, flavor_id):\n \"\"\"\n Retrieve a :obj:`Flavor` object by its ID.\n@@ -87,14 +89,16 @@ def get_flavor(self, http_get_request, flavor_id, absolutize_url):\n return dumps({\"flavor\": flavor.detailed_json(absolutize_url)})\n \n \n-@attributes([\"tenant_id\", \"clock\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalFlavorCollection(object):\n \"\"\"\n A :obj:`GlobalFlavorCollection` is a set of all the\n :obj:`RegionalFlavorCollection` objects owned by a given tenant. In other\n words, all the flavor objects that a single tenant owns globally.\n \"\"\"\n+ tenant_id = attr.ib()\n+ clock = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n \n def collection_for_region(self, region_name):\n \"\"\"\ndiff --git a/mimic/model/flavors.py b/mimic/model/flavors.py\n--- a/mimic/model/flavors.py\n+++ b/mimic/model/flavors.py\n@@ -4,14 +4,21 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes\n+import attr\n \n \n-@attributes(['flavor_id', 'tenant_id', 'name', 'ram', 'vcpus', 'rxtx', 'disk'])\n+@attr.s\n class Flavor(object):\n \"\"\"\n A Flavor object\n \"\"\"\n+ flavor_id = attr.ib()\n+ tenant_id = attr.ib()\n+ name = attr.ib()\n+ ram = attr.ib()\n+ vcpus = attr.ib()\n+ rxtx = attr.ib()\n+ disk = attr.ib()\n \n static_defaults = {\n \"swap\": \"\",\ndiff --git a/mimic/model/heat_objects.py b/mimic/model/heat_objects.py\n--- a/mimic/model/heat_objects.py\n+++ b/mimic/model/heat_objects.py\n@@ -2,23 +2,24 @@\n Model objects for the Heat mimic.\n \"\"\"\n \n-from characteristic import attributes, Attribute\n+import attr\n import json\n from random import randrange\n \n from mimic.model.behaviors import BehaviorRegistryCollection, EventDescription\n \n \n-@attributes(['collection', 'stack_name',\n- Attribute('stack_id',\n- default_factory=lambda: Stack.generate_stack_id()),\n- Attribute('action', default_factory=lambda: Stack.CREATE),\n- Attribute('status', default_factory=lambda: Stack.COMPLETE),\n- Attribute('tags', default_factory=list)])\n+@attr.s\n class Stack(object):\n \"\"\"\n A :obj:`Stack` is a representation of a Heat stack.\n \"\"\"\n+ collection = attr.ib()\n+ stack_name = attr.ib()\n+ stack_id = attr.ib(default=attr.Factory(lambda: Stack.generate_stack_id()))\n+ action = attr.ib(default=attr.Factory(lambda: Stack.CREATE))\n+ status = attr.ib(default=attr.Factory(lambda: Stack.COMPLETE))\n+ tags = attr.ib(default=attr.Factory(list))\n \n ACTIONS = (\n CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND, RESUME, ADOPT,\n@@ -199,17 +200,17 @@ def default_delete_behavior(collection, request, stack_name, stack_id):\n return b''\n \n \n-@attributes(\n- [\"tenant_id\", \"region_name\",\n- Attribute(\"stacks\", default_factory=list),\n- Attribute(\n- \"behavior_registry_collection\",\n- default_factory=lambda: BehaviorRegistryCollection())]\n-)\n+@attr.s\n class RegionalStackCollection(object):\n \"\"\"\n A collection of :obj:`Stack` objects for a region.\n \"\"\"\n+ tenant_id = attr.ib()\n+ region_name = attr.ib()\n+ stacks = attr.ib(default=attr.Factory(list))\n+ behavior_registry_collection = attr.ib(default=attr.Factory(\n+ lambda: BehaviorRegistryCollection()))\n+\n def stack_by_id(self, stack_id):\n \"\"\"\n Retrieves a stack by its ID\n@@ -302,12 +303,14 @@ def request_deletion(self, request, stack_name, stack_id):\n stack_id=stack_id)\n \n \n-@attributes([\"tenant_id\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalStackCollections(object):\n \"\"\"\n A set of :obj:`RegionalStackCollection` objects owned by a tenant.\n \"\"\"\n+ tenant_id = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n+\n def collection_for_region(self, region_name):\n \"\"\"\n Retrieves a :obj:`RegionalStackCollection` for a region.\ndiff --git a/mimic/model/ironic_objects.py b/mimic/model/ironic_objects.py\n--- a/mimic/model/ironic_objects.py\n+++ b/mimic/model/ironic_objects.py\n@@ -4,7 +4,7 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes, Attribute\n+import attr\n from uuid import uuid4\n from json import dumps\n \n@@ -12,26 +12,26 @@\n from mimic.util.helper import random_hex_generator\n \n \n-@attributes([\"node_id\",\n- Attribute(\"chassis_uuid\", default_value=None),\n- Attribute(\"driver\", default_value=None),\n- Attribute(\"driver_info\", default_value=None),\n- Attribute(\"properties\", default_value=None),\n- Attribute(\"flavor_id\", default_value=\"onmetal-io1\"),\n- Attribute(\"power_state\", default_value=\"power on\"),\n- Attribute(\"provision_state\", default_value=\"available\"),\n- Attribute(\"instance_uuid\", default_value=None),\n- Attribute(\"maintenance\", default_value=False),\n- Attribute(\"cache_image_id\", default_value=None),\n- Attribute(\"memory_mb\", default_value=None),\n- Attribute(\"name\", default_value=None)\n- ])\n+@attr.s\n class Node(object):\n \"\"\"\n A :obj:`Node` is a representation of all the state associated with a ironic\n node. It can produce JSON-serializable objects for various pieces of\n state that are required for API responses.\n \"\"\"\n+ node_id = attr.ib()\n+ chassis_uuid = attr.ib(default=None)\n+ driver = attr.ib(default=None)\n+ driver_info = attr.ib(default=None)\n+ properties = attr.ib(default=None)\n+ flavor_id = attr.ib(default=\"onmetal-io1\")\n+ power_state = attr.ib(default=\"power on\")\n+ provision_state = attr.ib(default=\"available\")\n+ instance_uuid = attr.ib(default=None)\n+ maintenance = attr.ib(default=False)\n+ cache_image_id = attr.ib(default=None)\n+ memory_mb = attr.ib(default=None)\n+ name = attr.ib(default=None)\n \n static_defaults = {\n \"target_power_state\": None,\n@@ -178,11 +178,12 @@ def detail_json(self):\n return template\n \n \n-@attributes([Attribute(\"ironic_node_store\", default_factory=list)])\n+@attr.s\n class IronicNodeStore(object):\n \"\"\"\n A collection of ironic :obj:`Node` objects.\n \"\"\"\n+ ironic_node_store = attr.ib(default=attr.Factory(list))\n \n memory_to_flavor_map = {131072: \"onmetal-io1\",\n 32768: \"onmetal-compute1\",\ndiff --git a/mimic/model/keypair_objects.py b/mimic/model/keypair_objects.py\n--- a/mimic/model/keypair_objects.py\n+++ b/mimic/model/keypair_objects.py\n@@ -6,14 +6,17 @@\n \n import json\n \n-from characteristic import attributes, Attribute\n+import attr\n \n \n-@attributes(['name', 'public_key'])\n+@attr.s\n class KeyPair(object):\n \"\"\"\n A KeyPair object\n \"\"\"\n+ name = attr.ib()\n+ public_key = attr.ib()\n+\n fingerprint = \"aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa\"\n user_id = \"fake\"\n \n@@ -31,15 +34,16 @@ def key_json(self):\n }\n \n \n-@attributes(\n- [\"tenant_id\", \"region_name\", \"clock\",\n- Attribute(\"keypairs\", default_factory=list)]\n-)\n+@attr.s\n class RegionalKeyPairCollection(object):\n \"\"\"\n A :obj:`ReionalKeyPairCollection` is a collection of\n :obj:`KeyPair` objects owned by a given tenant for a region.\n \"\"\"\n+ tenant_id = attr.ib()\n+ region_name = attr.ib()\n+ clock = attr.ib()\n+ keypairs = attr.ib(default=attr.Factory(list))\n \n def create_keypair(self, keypair):\n \"\"\"\n@@ -82,14 +86,16 @@ def remove_keypair(self, name):\n self.keypairs.remove(kp_to_remove)\n \n \n-@attributes([\"tenant_id\", \"clock\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalKeyPairCollections(object):\n \"\"\"\n A :obj:`GlobalKeyPairCollections` is a set of all the\n :obj:`RegionalKeyPairCollection` objects owned by a given tenant. In other\n words, all the objects that a single tenant owns globally.\n \"\"\"\n+ tenant_id = attr.ib()\n+ clock = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n \n def collection_for_region(self, region_name):\n \"\"\"\ndiff --git a/mimic/model/mailgun_objects.py b/mimic/model/mailgun_objects.py\n--- a/mimic/model/mailgun_objects.py\n+++ b/mimic/model/mailgun_objects.py\n@@ -4,18 +4,23 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n+import attr\n import time\n-from characteristic import attributes, Attribute\n \n \n-@attributes([\"message_id\", \"to\", \"msg_from\", \"subject\", \"body\",\n- Attribute(\"custom_headers\", default_factory=dict)])\n+@attr.s\n class Message(object):\n \"\"\"\n A :obj:`Message` is a representation of an email in Mailgun.\n It can produce JSON-serializable objects for various pieces of\n state that are required for API responses.\n \"\"\"\n+ message_id = attr.ib()\n+ to = attr.ib()\n+ msg_from = attr.ib()\n+ subject = attr.ib()\n+ body = attr.ib()\n+ custom_headers = attr.ib(default=attr.Factory(dict))\n \n static_defaults = {\n \"tags\": [],\n@@ -76,11 +81,12 @@ def generate_events(self):\n return template\n \n \n-@attributes([Attribute(\"message_store\", default_factory=list)])\n+@attr.s\n class MessageStore(object):\n \"\"\"\n A collection of message objects.\n \"\"\"\n+ message_store = attr.ib(default=attr.Factory(list))\n \n def add_to_message_store(self, **attributes):\n \"\"\"\ndiff --git a/mimic/model/nova_image_collection.py b/mimic/model/nova_image_collection.py\n--- a/mimic/model/nova_image_collection.py\n+++ b/mimic/model/nova_image_collection.py\n@@ -4,7 +4,7 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes, Attribute\n+import attr\n from json import dumps\n from mimic.model.rackspace_images import OnMetalImage\n \n@@ -12,12 +12,16 @@\n from mimic.canned_responses.mimic_presets import get_presets\n \n \n-@attributes(\n- [\"tenant_id\", \"region_name\", \"clock\", \"image_store\"])\n+@attr.s\n class RegionalNovaImageCollection(object):\n \"\"\"\n A collection of nova images, in a given region, for a given tenant.\n \"\"\"\n+ tenant_id = attr.ib()\n+ region_name = attr.ib()\n+ clock = attr.ib()\n+ image_store = attr.ib()\n+\n def list_images(self, include_details, absolutize_url):\n \"\"\"\n Return a list of images.\n@@ -49,14 +53,16 @@ def get_image(self, http_get_request, image_id, absolutize_url):\n return dumps({\"image\": image.detailed_json(absolutize_url)})\n \n \n-@attributes([\"tenant_id\", \"clock\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalNovaImageCollection(object):\n \"\"\"\n A :obj:`GlobalNovaImageCollection` is a set of all the\n :obj:`RegionalNovaImageCollection` objects owned by a given tenant. In other\n words, all the image objects that a single tenant owns globally.\n \"\"\"\n+ tenant_id = attr.ib()\n+ clock = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n \n def collection_for_region(self, region_name, image_store):\n \"\"\"\ndiff --git a/mimic/model/nova_objects.py b/mimic/model/nova_objects.py\n--- a/mimic/model/nova_objects.py\n+++ b/mimic/model/nova_objects.py\n@@ -6,7 +6,7 @@\n \n import re\n import uuid\n-from characteristic import attributes, Attribute\n+import attr\n from random import randrange\n from json import loads, dumps\n from six.moves.urllib.parse import urlencode\n@@ -28,18 +28,20 @@\n from mimic.model.rackspace_images import RackspaceSavedImage\n \n \n-@attributes(['nova_message'])\n+@attr.s\n class LimitError(Exception):\n \"\"\"\n Error to be raised when a limit has been exceeded.\n \"\"\"\n+ nova_message = attr.ib()\n \n \n-@attributes(['nova_message'])\n+@attr.s\n class BadRequestError(Exception):\n \"\"\"\n Error to be raised when bad input has been received to Nova.\n \"\"\"\n+ nova_message = attr.ib()\n \n \n def _nova_error_message(msg_type, message, status_code, request):\n@@ -115,18 +117,29 @@ def conflicting(message, request):\n return _nova_error_message(\"conflictingRequest\", message, CONFLICT, request)\n \n \n-@attributes([\"collection\", \"server_id\", \"server_name\", \"metadata\",\n- \"creation_time\", \"update_time\", \"public_ips\", \"private_ips\",\n- \"status\", \"flavor_ref\", \"image_ref\", \"disk_config\", \"key_name\",\n- \"admin_password\", \"creation_request_json\",\n- Attribute('max_metadata_items', instance_of=int,\n- default_value=40)])\n+@attr.s\n class Server(object):\n \"\"\"\n A :obj:`Server` is a representation of all the state associated with a nova\n server. It can produce JSON-serializable objects for various pieces of\n state that are required for API responses.\n \"\"\"\n+ admin_password = attr.ib()\n+ collection = attr.ib()\n+ creation_request_json = attr.ib()\n+ creation_time = attr.ib()\n+ disk_config = attr.ib()\n+ flavor_ref = attr.ib()\n+ image_ref = attr.ib()\n+ key_name = attr.ib()\n+ metadata = attr.ib()\n+ private_ips = attr.ib()\n+ public_ips = attr.ib()\n+ server_id = attr.ib()\n+ server_name = attr.ib()\n+ status = attr.ib()\n+ update_time = attr.ib()\n+ max_metadata_items = attr.ib(validator=attr.validators.instance_of(int), default=40)\n \n static_defaults = {\n \"OS-EXT-STS:power_state\": 1,\n@@ -339,11 +352,12 @@ def from_creation_request_json(cls, collection, creation_json,\n return self\n \n \n-@attributes([\"address\"])\n+@attr.s\n class IPv4Address(object):\n \"\"\"\n An IPv4 address for a server.\n \"\"\"\n+ address = attr.ib()\n \n def json(self):\n \"\"\"\n@@ -352,11 +366,12 @@ def json(self):\n return {\"addr\": self.address, \"version\": 4}\n \n \n-@attributes([\"address\"])\n+@attr.s\n class IPv6Address(object):\n \"\"\"\n An IPv6 address for a server.\n \"\"\"\n+ address = attr.ib()\n \n def json(self):\n \"\"\"\n@@ -650,17 +665,17 @@ def metadata_to_creation_behavior(metadata):\n return None\n \n \n-@attributes(\n- [\"tenant_id\", \"region_name\", \"clock\",\n- Attribute(\"servers\", default_factory=list),\n- Attribute(\n- \"behavior_registry_collection\",\n- default_factory=lambda: BehaviorRegistryCollection())]\n-)\n+@attr.s\n class RegionalServerCollection(object):\n \"\"\"\n A collection of servers, in a given region, for a given tenant.\n \"\"\"\n+ tenant_id = attr.ib()\n+ region_name = attr.ib()\n+ clock = attr.ib()\n+ servers = attr.ib(default=attr.Factory(list))\n+ behavior_registry_collection = attr.ib(default=attr.Factory(\n+ lambda: BehaviorRegistryCollection()))\n \n def server_by_id(self, server_id):\n \"\"\"\n@@ -973,8 +988,7 @@ def request_action(self, http_action_request, server_id, absolutize_url,\n return dumps(bad_request(\"There is no such action currently supported\", http_action_request))\n \n \n-@attributes([\"tenant_id\", \"clock\",\n- Attribute(\"regional_collections\", default_factory=dict)])\n+@attr.s\n class GlobalServerCollections(object):\n \"\"\"\n A :obj:`GlobalServerCollections` is a set of all the\n@@ -982,6 +996,9 @@ class GlobalServerCollections(object):\n words, all the objects that a single tenant owns globally in a Nova\n service.\n \"\"\"\n+ tenant_id = attr.ib()\n+ clock = attr.ib()\n+ regional_collections = attr.ib(default=attr.Factory(dict))\n \n def collection_for_region(self, region_name):\n \"\"\"\ndiff --git a/mimic/model/rackspace_image_store.py b/mimic/model/rackspace_image_store.py\n--- a/mimic/model/rackspace_image_store.py\n+++ b/mimic/model/rackspace_image_store.py\n@@ -2,7 +2,7 @@\n An image store representing Rackspace specific images\n \"\"\"\n from __future__ import absolute_import, division, unicode_literals\n-from characteristic import attributes, Attribute\n+import attr\n from six import iteritems\n from mimic.model.rackspace_images import (RackspaceWindowsImage,\n RackspaceCentOSPVImage, RackspaceCentOSPVHMImage,\n@@ -19,12 +19,14 @@\n from mimic.model.rackspace_images import create_rackspace_images\n \n \n-@attributes([Attribute(\"image_list\", default_factory=list)])\n+@attr.s\n class RackspaceImageStore(object):\n \"\"\"\n A store for images to share between nova_api and glance_api\n :var image_list: list of Rackspace images\n \"\"\"\n+ image_list = attr.ib(default=attr.Factory(list))\n+\n def create_image_store(self, tenant_id):\n \"\"\"\n Generates the data for each image in each image class\ndiff --git a/mimic/model/rackspace_images.py b/mimic/model/rackspace_images.py\n--- a/mimic/model/rackspace_images.py\n+++ b/mimic/model/rackspace_images.py\n@@ -4,7 +4,7 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes, Attribute\n+import attr\n import uuid\n import random\n \n@@ -23,18 +23,7 @@ def random_image_size():\n return random.randint(250000, 80000000000)\n \n \n-@attributes([\n- # Prior to refactor; no default value\n- 'image_id', 'tenant_id', 'name', 'minDisk', 'minRam', 'image_size',\n- # Post-refactor; all have default values, but these should be slowly\n- # removed.\n- Attribute('flavor_classes', default_value=\"*\"),\n- Attribute('image_type', default_value=\"base\"),\n- Attribute('os_type', default_value=\"linux\"),\n- Attribute('os_distro', default_value=\"\"),\n- Attribute('vm_mode', default_value=\"hvm\"),\n- Attribute('auto_disk_config', default_value=\"disabled\"),\n-])\n+@attr.s\n class Image(object):\n \"\"\"\n A Image object\n@@ -54,6 +43,22 @@ class Image(object):\n with this image; possible values: \"True\", \"disabled\", and \"False\".\n (TODO: what does \"False\" mean?)\n \"\"\"\n+ # Prior to refactor; no default value\n+ image_id = attr.ib()\n+ tenant_id = attr.ib()\n+ name = attr.ib()\n+ minDisk = attr.ib()\n+ minRam = attr.ib()\n+ image_size = attr.ib()\n+\n+ # Post-refactor; all have default values, but these should be slowly\n+ # removed.\n+ flavor_classes = attr.ib(default=\"*\")\n+ image_type = attr.ib(default=\"base\")\n+ os_type = attr.ib(default=\"linux\")\n+ os_distro = attr.ib(default=\"\")\n+ vm_mode = attr.ib(default=\"hvm\")\n+ auto_disk_config = attr.ib(default=\"disabled\")\n \n is_default = False\n \n@@ -138,12 +143,25 @@ def detailed_json(self, absolutize_url):\n return template\n \n \n-@attributes(['image_id', 'tenant_id', 'name', 'minDisk', 'minRam', 'image_size', 'server_id', 'links',\n- 'flavor_classes', 'os_type', 'os_distro', 'vm_mode', 'disk_config'])\n+@attr.s\n class RackspaceSavedImage(object):\n \"\"\"\n A Rackspace saved image object representation\n \"\"\"\n+ image_id = attr.ib()\n+ tenant_id = attr.ib()\n+ name = attr.ib()\n+ minDisk = attr.ib()\n+ minRam = attr.ib()\n+ image_size = attr.ib()\n+ server_id = attr.ib()\n+ links = attr.ib()\n+ flavor_classes = attr.ib()\n+ os_type = attr.ib()\n+ os_distro = attr.ib()\n+ vm_mode = attr.ib()\n+ disk_config = attr.ib()\n+\n is_default = False\n \n def metadata_json(self):\n@@ -654,11 +672,17 @@ def metadata_json(self):\n }\n \n \n-@attributes(['image_id', 'tenant_id', 'name', 'minDisk', 'minRam', 'image_size'])\n+@attr.s\n class OnMetalImage(object):\n \"\"\"\n A Image object\n \"\"\"\n+ image_id = attr.ib()\n+ tenant_id = attr.ib()\n+ name = attr.ib()\n+ minDisk = attr.ib()\n+ minRam = attr.ib()\n+ image_size = attr.ib()\n \n is_default = False\n \ndiff --git a/mimic/model/valkyrie_objects.py b/mimic/model/valkyrie_objects.py\n--- a/mimic/model/valkyrie_objects.py\n+++ b/mimic/model/valkyrie_objects.py\n@@ -4,7 +4,7 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n-from characteristic import attributes, Attribute\n+import attr\n from json import dumps\n \n from mimic.util.helper import random_hex_generator\n@@ -67,7 +67,7 @@ def json(self):\n }\n \n \n-@attributes([Attribute(\"valkyrie_store\", default_factory=list)])\n+@attr.s\n class ValkyrieStore(object):\n \"\"\"\n \n@@ -85,6 +85,7 @@ class ValkyrieStore(object):\n http://localhost:8900/valkyrie/v2/account/123456/permissions/contacts/devices/by_contact/56/effective\n \n \"\"\"\n+ valkyrie_store = attr.ib(default=attr.Factory(list))\n \n permissions = []\n # Arguments are: account, contact, (direct) permission, item, item_type (1=account or 2=device)\ndiff --git a/mimic/rest/cloudfeeds.py b/mimic/rest/cloudfeeds.py\n--- a/mimic/rest/cloudfeeds.py\n+++ b/mimic/rest/cloudfeeds.py\n@@ -14,7 +14,7 @@\n from mimic.rest.mimicapp import MimicApp\n \n \n-from characteristic import attributes\n+import attr\n \n \n @implementer(IAPIMock, IPlugin)\n@@ -57,12 +57,14 @@ def resource_for_region(self, region, uri_prefix, session_store):\n \n \n @implementer(IAPIMock, IPlugin)\n-@attributes([\"cf_api\"])\n+@attr.s\n class CloudFeedsControlApi(object):\n \"\"\"\n This class registers the load balancer controller API in the service\n catalog.\n \"\"\"\n+ cf_api = attr.ib()\n+\n def catalog_entries(self, tenant_id):\n \"\"\"\n Cloud feeds controller endpoints.\n@@ -89,11 +91,15 @@ def resource_for_region(self, region, uri_prefix, session_store):\n return cfc_region.app.resource()\n \n \n-@attributes([\"api_mock\", \"uri_prefix\", \"session_store\", \"region\"])\n+@attr.s\n class CloudFeedsControlRegion(object):\n \"\"\"\n Klein routes for cloud feed's control API within a particular region.\n \"\"\"\n+ api_mock = attr.ib()\n+ uri_prefix = attr.ib()\n+ session_store = attr.ib()\n+ region = attr.ib()\n \n app = MimicApp()\n \ndiff --git a/mimic/rest/loadbalancer_api.py b/mimic/rest/loadbalancer_api.py\n--- a/mimic/rest/loadbalancer_api.py\n+++ b/mimic/rest/loadbalancer_api.py\n@@ -23,7 +23,7 @@\n \n from mimic.util.helper import invalid_resource, json_dump\n from mimic.util.helper import json_from_request\n-from characteristic import attributes\n+import attr\n \n \n @implementer(IAPIMock, IPlugin)\n@@ -78,12 +78,14 @@ def _get_session(self, session_store, tenant_id):\n \n \n @implementer(IAPIMock, IPlugin)\n-@attributes([\"lb_api\"])\n+@attr.s\n class LoadBalancerControlApi(object):\n \"\"\"\n This class registers the load balancer controller API in the service\n catalog.\n \"\"\"\n+ lb_api = attr.ib()\n+\n def catalog_entries(self, tenant_id):\n \"\"\"\n Cloud load balancer controller endpoints.\n@@ -108,11 +110,15 @@ def resource_for_region(self, region, uri_prefix, session_store):\n return lbc_region.app.resource()\n \n \n-@attributes([\"api_mock\", \"uri_prefix\", \"session_store\", \"region\"])\n+@attr.s\n class LoadBalancerControlRegion(object):\n \"\"\"\n Klein routes for load balancer's control API within a particular region.\n \"\"\"\n+ api_mock = attr.ib()\n+ uri_prefix = attr.ib()\n+ session_store = attr.ib()\n+ region = attr.ib()\n \n app = MimicApp()\n \n@@ -151,18 +157,9 @@ def set_attributes(self, request, tenant_id, clb_id):\n \n try:\n regional_lbs.set_attributes(clb_id, content)\n- except BadKeysError as bke:\n- request.setResponseCode(400)\n- return json.dumps({\n- \"message\": str(bke),\n- \"code\": 400,\n- })\n- except BadValueError as bve:\n- request.setResponseCode(400)\n- return json.dumps({\n- \"message\": str(bve),\n- \"code\": 400,\n- })\n+ except (BadKeysError, BadValueError) as err:\n+ request.setResponseCode(err.code)\n+ return json.dumps(err.to_json())\n else:\n request.setResponseCode(204)\n return b''\ndiff --git a/mimic/rest/maas_api.py b/mimic/rest/maas_api.py\n--- a/mimic/rest/maas_api.py\n+++ b/mimic/rest/maas_api.py\n@@ -14,7 +14,6 @@\n import attr\n from six import text_type\n \n-from characteristic import attributes\n from zope.interface import implementer\n \n from twisted.plugin import IPlugin\n@@ -1662,11 +1661,13 @@ def latest_alarm_states(self, request, tenant_id):\n \n \n @implementer(IAPIMock, IPlugin)\n-@attributes([\"maas_api\"])\n+@attr.s\n class MaasControlApi(object):\n \"\"\"\n This class registers the MaaS controller API in the service catalog.\n \"\"\"\n+ maas_api = attr.ib()\n+\n def catalog_entries(self, tenant_id):\n \"\"\"\n List catalog entries for the MaaS API.\n@@ -1693,11 +1694,14 @@ def resource_for_region(self, region, uri_prefix, session_store):\n return maas_controller.app.resource()\n \n \n-@attributes([\"api_mock\", \"session_store\", \"region\"])\n+@attr.s\n class MaasController(object):\n \"\"\"\n Klein routes for MaaS control API.\n \"\"\"\n+ api_mock = attr.ib()\n+ session_store = attr.ib()\n+ region = attr.ib()\n \n def _entity_cache_for_tenant(self, tenant_id):\n \"\"\"\ndiff --git a/mimic/rest/nova_api.py b/mimic/rest/nova_api.py\n--- a/mimic/rest/nova_api.py\n+++ b/mimic/rest/nova_api.py\n@@ -8,7 +8,7 @@\n from uuid import uuid4\n import json\n \n-from characteristic import attributes\n+import attr\n from six import text_type\n \n from zope.interface import implementer\n@@ -87,11 +87,12 @@ def _get_session(self, session_store, tenant_id):\n \n \n @implementer(IAPIMock, IPlugin)\n-@attributes([\"nova_api\"])\n+@attr.s\n class NovaControlApi(object):\n \"\"\"\n Rest endpoints for the Nova Control Api.\n \"\"\"\n+ nova_api = attr.ib()\n \n def catalog_entries(self, tenant_id):\n \"\"\"\n@@ -128,11 +129,16 @@ def resource_for_region(self, region, uri_prefix, session_store):\n \"\"\"\n \n \n-@attributes([\"api_mock\", \"uri_prefix\", \"session_store\", \"region\"])\n+@attr.s\n class NovaControlApiRegion(object):\n \"\"\"\n Klein resources for the Nova Control plane API\n \"\"\"\n+ api_mock = attr.ib()\n+ uri_prefix = attr.ib()\n+ session_store = attr.ib()\n+ region = attr.ib()\n+\n app = MimicApp()\n \n @app.route('/v2//behaviors', branch=True)\ndiff --git a/mimic/rest/rackconnect_v3_api.py b/mimic/rest/rackconnect_v3_api.py\n--- a/mimic/rest/rackconnect_v3_api.py\n+++ b/mimic/rest/rackconnect_v3_api.py\n@@ -11,7 +11,7 @@\n import json\n from uuid import uuid4, UUID\n \n-from characteristic import attributes, Attribute\n+import attr\n from six import text_type\n \n from twisted.plugin import IPlugin\n@@ -72,17 +72,7 @@ def resource_for_region(self, region, uri_prefix, session_store):\n default_pools=self.default_pools).app.resource()\n \n \n-@attributes(\n- [Attribute(\"id\", default_factory=lambda: text_type(uuid4()),\n- instance_of=text_type),\n- Attribute(\"name\", default_value=u\"default\", instance_of=text_type),\n- Attribute(\"port\", default_value=80, instance_of=int),\n- Attribute(\"status\", default_value=u\"ACTIVE\", instance_of=text_type),\n- Attribute(\"status_detail\", default_value=None),\n- Attribute(\"virtual_ip\", default_factory=random_ipv4,\n- instance_of=text_type),\n- Attribute('nodes', default_factory=list, instance_of=list)],\n- apply_with_cmp=False)\n+@attr.s(hash=False)\n class LoadBalancerPool(object):\n \"\"\"\n Represents a RackConnecvt v3 Load Balancer Pool.\n@@ -102,17 +92,25 @@ class LoadBalancerPool(object):\n :param text_type virtual_ip: The IP of the load balancer pool\n :param list nodes: :class:`LoadBalancerPoolNode`s\n \"\"\"\n+ id = attr.ib(default=attr.Factory(lambda: text_type(uuid4())),\n+ validator=attr.validators.instance_of(text_type))\n+ name = attr.ib(default=\"default\", validator=attr.validators.instance_of(text_type))\n+ port = attr.ib(default=80, validator=attr.validators.instance_of(int))\n+ status = attr.ib(default=\"ACTIVE\", validator=attr.validators.instance_of(text_type))\n+ status_detail = attr.ib(default=None)\n+ virtual_ip = attr.ib(default=attr.Factory(random_ipv4),\n+ validator=attr.validators.instance_of(text_type))\n+ nodes = attr.ib(default=attr.Factory(list), validator=attr.validators.instance_of(list))\n+\n def as_json(self):\n \"\"\"\n Create a JSON-serializable representation of the contents of this\n object, which can be used in a REST response for a request for the\n details of this particular object\n \"\"\"\n- # no dictionary comprehensions in py2.6\n- response = dict([\n- (attr.name, getattr(self, attr.name))\n- for attr in LoadBalancerPool.characteristic_attributes\n- if attr.name != \"nodes\"])\n+ response = {aa.name: getattr(self, aa.name)\n+ for aa in attr.fields(LoadBalancerPool)\n+ if aa.name != \"nodes\"}\n response['node_counts'] = {\n \"cloud_servers\": len(self.nodes),\n \"external\": 0,\n@@ -141,13 +139,7 @@ def node_by_id(self, node_id):\n return next((node for node in self.nodes if node.id == node_id), None)\n \n \n-@attributes([\"created\", \"load_balancer_pool\", \"cloud_server\",\n- Attribute(\"id\", default_factory=lambda: text_type(uuid4()),\n- instance_of=text_type),\n- Attribute(\"updated\", default_value=None),\n- Attribute(\"status\", default_value=text_type(\"ACTIVE\"),\n- instance_of=text_type),\n- Attribute(\"status_detail\", default_value=None)])\n+@attr.s\n class LoadBalancerPoolNode(object):\n \"\"\"\n Represents a Load Balancer Pool Node.\n@@ -173,6 +165,15 @@ class LoadBalancerPoolNode(object):\n in theory can also be some external (not a cloud server) resource,\n but that is not supported yet on the API.\n \"\"\"\n+ created = attr.ib()\n+ load_balancer_pool = attr.ib()\n+ cloud_server = attr.ib()\n+ id = attr.ib(default=attr.Factory(lambda: text_type(uuid4())),\n+ validator=attr.validators.instance_of(text_type))\n+ updated = attr.ib(default=None)\n+ status = attr.ib(default=\"ACTIVE\", validator=attr.validators.instance_of(text_type))\n+ status_detail = attr.ib(default=None)\n+\n def short_json(self):\n \"\"\"\n Create a short JSON-serializable representation of the contents of\n@@ -184,11 +185,9 @@ def short_json(self):\n GET /v3/{tenant_id}/load_balancer_pools/{load_balancer_pool_id}/nodes\n (list load balancer pool nodes)\n \"\"\"\n- # no dictionary comprehensions in py2.6\n- response = dict([\n- (attr.name, getattr(self, attr.name))\n- for attr in LoadBalancerPoolNode.characteristic_attributes\n- if attr.name not in ('load_balancer_pool', 'cloud_server')])\n+ response = {aa.name: getattr(self, aa.name)\n+ for aa in attr.fields(LoadBalancerPoolNode)\n+ if aa.name not in ('load_balancer_pool', 'cloud_server')}\n response['load_balancer_pool'] = {'id': self.load_balancer_pool.id}\n response['cloud_server'] = {'id': self.cloud_server}\n return response\n@@ -202,12 +201,17 @@ def update(self, now, status, status_detail=None):\n self.status_detail = status_detail\n \n \n-@attributes([\"iapi\", \"uri_prefix\", \"session_store\", \"region_name\",\n- \"default_pools\"])\n+@attr.s\n class RackConnectV3Region(object):\n \"\"\"\n A set of ``klein`` routes representing a RackConnect V3 endpoint.\n \"\"\"\n+ iapi = attr.ib()\n+ uri_prefix = attr.ib()\n+ session_store = attr.ib()\n+ region_name = attr.ib()\n+ default_pools = attr.ib()\n+\n app = MimicApp()\n \n @app.route(\"/v3//load_balancer_pools\", branch=True)\n@@ -232,12 +236,15 @@ def get_tenant_lb_pools(self, request, tenant_id):\n # exclude all the attributes from comparison so that equality has to be\n # determined by identity, since lbpools is mutable and we don't want to\n # compare clocks\n-@attributes([\"lbpools\", \"clock\"], apply_with_cmp=False)\n+@attr.s(hash=False)\n class LoadBalancerPoolsInRegion(object):\n \"\"\"\n A set of ``klein`` routes handling RackConnect V3 Load Balancer Pools\n collections.\n \"\"\"\n+ lbpools = attr.ib()\n+ clock = attr.ib()\n+\n app = MimicApp()\n \n def _pool_by_id(self, id):\n@@ -389,12 +396,14 @@ def delegate_to_one_pool_handler(self, request, id):\n return \"Load Balancer Pool {0} does not exist\".format(id)\n \n \n-@attributes([\"pool\"])\n+@attr.s\n class OneLoadBalancerPool(object):\n \"\"\"\n A set of ``klein`` routes handling the RackConnect V3 API for a single\n load balancer pool\n \"\"\"\n+ pool = attr.ib()\n+\n app = MimicApp()\n \n @app.route(\"/\", methods=[\"GET\"])\ndiff --git a/mimic/rest/swift_api.py b/mimic/rest/swift_api.py\n--- a/mimic/rest/swift_api.py\n+++ b/mimic/rest/swift_api.py\n@@ -9,7 +9,7 @@\n from uuid import uuid4, uuid5, NAMESPACE_URL\n from six import text_type\n \n-from characteristic import attributes, Attribute\n+import attr\n from json import dumps\n \n from mimic.imimic import IAPIMock\n@@ -79,12 +79,15 @@ def resource_for_region(self, region, uri_prefix, session_store):\n session_store=session_store).app.resource()\n \n \n-@attributes(\"api uri_prefix session_store\".split())\n+@attr.s\n class SwiftRegion(object):\n \"\"\"\n :obj:`SwiftRegion` is a set of klein routes and application representing a\n Swift endpoint.\n \"\"\"\n+ api = attr.ib()\n+ uri_prefix = attr.ib()\n+ session_store = attr.ib()\n \n app = MimicApp()\n \n@@ -99,12 +102,15 @@ def get_one_tenant_resource(self, request, tenant_id):\n SwiftTenantInRegion().app.resource()))\n \n \n-@attributes([\"name\", \"content_type\", \"data\"])\n+@attr.s\n class Object(object):\n \"\"\"\n A Python object (i.e. instance) representing a Swift object (i.e. bag of\n octets).\n \"\"\"\n+ name = attr.ib()\n+ content_type = attr.ib()\n+ data = attr.ib()\n \n def as_json(self):\n \"\"\"\n@@ -118,11 +124,13 @@ def as_json(self):\n }\n \n \n-@attributes([\"name\", Attribute(\"objects\", default_factory=dict)])\n+@attr.s\n class Container(object):\n \"\"\"\n A Swift container (collection of :obj:`Object`.)\n \"\"\"\n+ name = attr.ib()\n+ objects = attr.ib(default=attr.Factory(dict))\n \n \n class SwiftTenantInRegion(object):\ndiff --git a/mimic/session.py b/mimic/session.py\n--- a/mimic/session.py\n+++ b/mimic/session.py\n@@ -10,17 +10,21 @@\n from uuid import uuid4\n from datetime import datetime, timedelta\n \n-from characteristic import attributes, Attribute\n+import attr\n \n \n-@attributes(['username', 'token', 'tenant_id', 'expires',\n- Attribute('impersonator_session_map', default_factory=dict),\n- Attribute('_api_objects', default_factory=dict)])\n+@attr.s\n class Session(object):\n \"\"\"\n A mimic Session is a record of an authentication token for a particular\n username and tenant_id.\n \"\"\"\n+ username = attr.ib()\n+ token = attr.ib()\n+ tenant_id = attr.ib()\n+ expires = attr.ib()\n+ impersonator_session_map = attr.ib(default=attr.Factory(dict))\n+ _api_objects = attr.ib(default=attr.Factory(dict))\n \n @property\n def user_id(self):\n@@ -46,12 +50,13 @@ def data_for_api(self, api_mock, data_factory):\n return self._api_objects[api_mock]\n \n \n-@attributes([Attribute('session', instance_of=Session),\n- 'desired_tenant'])\n+@attr.s\n class NonMatchingTenantError(Exception):\n \"\"\"\n A session's tenant ID does not match the desired tenant ID.\n \"\"\"\n+ session = attr.ib(validator=attr.validators.instance_of(Session))\n+ desired_tenant = attr.ib()\n \n \n class SessionStore(object):\n", "test_patch": "diff --git a/mimic/test/test_rackconnect_v3.py b/mimic/test/test_rackconnect_v3.py\n--- a/mimic/test/test_rackconnect_v3.py\n+++ b/mimic/test/test_rackconnect_v3.py\n@@ -4,6 +4,7 @@\n \n from __future__ import absolute_import, division, unicode_literals\n \n+import attr\n import json\n from random import randint\n from uuid import uuid4\n@@ -201,14 +202,14 @@ def test_list_pools_default_one(self):\n pool_json = response_json[0]\n # has the right JSON\n self.assertTrue(all(\n- attr.name in pool_json\n- for attr in LoadBalancerPool.characteristic_attributes\n- if attr.name != \"nodes\"))\n+ aa.name in pool_json\n+ for aa in attr.fields(LoadBalancerPool)\n+ if aa.name != \"nodes\"))\n # Generated values\n self.assertTrue(all(\n- pool_json.get(attr.name)\n- for attr in LoadBalancerPool.characteristic_attributes\n- if attr.name not in (\"nodes\", \"status_detail\")))\n+ pool_json.get(aa.name)\n+ for aa in attr.fields(LoadBalancerPool)\n+ if aa.name not in (\"nodes\", \"status_detail\")))\n \n self.assertEqual(\n {\n", "problem_statement": "", "hints_text": "", "created_at": "2016-02-17T07:33:08Z"} diff --git a/PythonDataset/test/mixpanel-python-task-instances.jsonl.all b/PythonDataset/test/mixpanel-python-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..2e42d0f1ba0cc16a7b999ddb02003db273227236 --- /dev/null +++ b/PythonDataset/test/mixpanel-python-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "mixpanel/mixpanel-python", "pull_number": 64, "instance_id": "mixpanel__mixpanel-python-64", "issue_numbers": ["63"], "base_commit": "40c98e0b285898384cc4aa6cc803d8d0f46f6218", "patch": "diff --git a/mixpanel/__init__.py b/mixpanel/__init__.py\n--- a/mixpanel/__init__.py\n+++ b/mixpanel/__init__.py\n@@ -345,6 +345,7 @@ def send(self, endpoint, json_message, api_key=None):\n :param endpoint: the Mixpanel API endpoint appropriate for the message\n :type endpoint: \"events\" | \"people\" | \"imports\"\n :param str json_message: a JSON message formatted for the endpoint\n+ :param str api_key: your Mixpanel project's API key\n :raises MixpanelException: if the endpoint doesn't exist, the server is\n unreachable, or the message cannot be processed\n \"\"\"\n@@ -412,6 +413,7 @@ def __init__(self, max_size=50, events_url=None, people_url=None, import_url=Non\n 'imports': [],\n }\n self._max_size = min(50, max_size)\n+ self._api_key = None\n \n def send(self, endpoint, json_message, api_key=None):\n \"\"\"Record an event or profile update.\n@@ -424,16 +426,22 @@ def send(self, endpoint, json_message, api_key=None):\n :param endpoint: the Mixpanel API endpoint appropriate for the message\n :type endpoint: \"events\" | \"people\" | \"imports\"\n :param str json_message: a JSON message formatted for the endpoint\n+ :param str api_key: your Mixpanel project's API key\n :raises MixpanelException: if the endpoint doesn't exist, the server is\n unreachable, or any buffered message cannot be processed\n+\n+ .. versionadded:: 4.3.2\n+ The *api_key* parameter.\n \"\"\"\n if endpoint not in self._buffers:\n raise MixpanelException('No such endpoint \"{0}\". Valid endpoints are one of {1}'.format(endpoint, self._buffers.keys()))\n \n buf = self._buffers[endpoint]\n buf.append(json_message)\n+ if api_key is not None:\n+ self._api_key = api_key\n if len(buf) >= self._max_size:\n- self._flush_endpoint(endpoint, api_key)\n+ self._flush_endpoint(endpoint)\n \n def flush(self):\n \"\"\"Immediately send all buffered messages to Mixpanel.\n@@ -444,13 +452,13 @@ def flush(self):\n for endpoint in self._buffers.keys():\n self._flush_endpoint(endpoint)\n \n- def _flush_endpoint(self, endpoint, api_key=None):\n+ def _flush_endpoint(self, endpoint):\n buf = self._buffers[endpoint]\n while buf:\n batch = buf[:self._max_size]\n batch_json = '[{0}]'.format(','.join(batch))\n try:\n- self._consumer.send(endpoint, batch_json, api_key)\n+ self._consumer.send(endpoint, batch_json, self._api_key)\n except MixpanelException as orig_e:\n mp_e = MixpanelException(orig_e)\n mp_e.message = batch_json\n", "test_patch": "diff --git a/test_mixpanel.py b/test_mixpanel.py\n--- a/test_mixpanel.py\n+++ b/test_mixpanel.py\n@@ -353,40 +353,32 @@ class TestBufferedConsumer:\n def setup_class(cls):\n cls.MAX_LENGTH = 10\n cls.consumer = mixpanel.BufferedConsumer(cls.MAX_LENGTH)\n- cls.mock = Mock()\n- cls.mock.read.return_value = six.b('{\"status\":1, \"error\": null}')\n+ cls.consumer._consumer = LogConsumer()\n+ cls.log = cls.consumer._consumer.log\n \n- def test_buffer_hold_and_flush(self):\n- with patch('six.moves.urllib.request.urlopen', return_value=self.mock) as urlopen:\n- self.consumer.send('events', '\"Event\"')\n- assert not self.mock.called\n- self.consumer.flush()\n+ def setup_method(self):\n+ del self.log[:]\n \n- assert urlopen.call_count == 1\n-\n- (call_args, kwargs) = urlopen.call_args\n- (request,) = call_args\n- timeout = kwargs.get('timeout', None)\n-\n- assert request.get_full_url() == 'https://api.mixpanel.com/track'\n- assert qs(request.data) == qs('ip=0&data=WyJFdmVudCJd&verbose=1')\n- assert timeout is None\n+ def test_buffer_hold_and_flush(self):\n+ self.consumer.send('events', '\"Event\"')\n+ assert len(self.log) == 0\n+ self.consumer.flush()\n+ assert self.log == [('events', ['Event'])]\n \n def test_buffer_fills_up(self):\n- with patch('six.moves.urllib.request.urlopen', return_value=self.mock) as urlopen:\n- for i in range(self.MAX_LENGTH - 1):\n- self.consumer.send('events', '\"Event\"')\n- assert not self.mock.called\n-\n- self.consumer.send('events', '\"Last Event\"')\n+ for i in range(self.MAX_LENGTH - 1):\n+ self.consumer.send('events', '\"Event\"')\n+ assert len(self.log) == 0\n \n- assert urlopen.call_count == 1\n- ((request,), _) = urlopen.call_args\n- assert request.get_full_url() == 'https://api.mixpanel.com/track'\n- assert qs(request.data) == \\\n- qs('ip=0&data=WyJFdmVudCIsIkV2ZW50IiwiRXZlbnQiLCJFdmVudCIsIkV2ZW50IiwiRXZlbnQiLCJFdmVudCIsIkV2ZW50IiwiRXZlbnQiLCJMYXN0IEV2ZW50Il0%3D&verbose=1')\n+ self.consumer.send('events', '\"Last Event\"')\n+ assert len(self.log) == 1\n+ assert self.log == [('events', [\n+ 'Event', 'Event', 'Event', 'Event', 'Event',\n+ 'Event', 'Event', 'Event', 'Event', 'Last Event',\n+ ])]\n \n- def test_unknown_endpoint(self):\n+ def test_unknown_endpoint_raises_on_send(self):\n+ # Ensure the exception isn't hidden until a flush.\n with pytest.raises(mixpanel.MixpanelException):\n self.consumer.send('unknown', '1')\n \n@@ -394,17 +386,19 @@ def test_useful_reraise_in_flush_endpoint(self):\n error_mock = Mock()\n error_mock.read.return_value = six.b('{\"status\": 0, \"error\": \"arbitrary error\"}')\n broken_json = '{broken JSON'\n+ consumer = mixpanel.BufferedConsumer(2)\n with patch('six.moves.urllib.request.urlopen', return_value=error_mock):\n- self.consumer.send('events', broken_json)\n+ consumer.send('events', broken_json)\n with pytest.raises(mixpanel.MixpanelException) as excinfo:\n- self.consumer.flush()\n+ consumer.flush()\n assert excinfo.value.message == '[%s]' % broken_json\n assert excinfo.value.endpoint == 'events'\n \n- def test_import_data_receives_api_key(self):\n- # Ensure BufferedConsumer.send accepts the API_KEY parameter needed for\n- # import_data; see #62.\n+ def test_send_remembers_api_key(self):\n self.consumer.send('imports', '\"Event\"', api_key='MY_API_KEY')\n+ assert len(self.log) == 0\n+ self.consumer.flush()\n+ assert self.log == [('imports', ['Event'], 'MY_API_KEY')]\n \n \n class TestFunctional:\n", "problem_statement": "flush function for Buffered Consumer not working\nHi,\nin class BufferedConsumer the flush function in line 338 should change to \ndef flush (self,api_key=None) \n\nand then in line 444-445 should change to:\n for endpoint in self._buffers.keys():\n self._flush_endpoint(endpoint,api_key=api_key)\n\n", "hints_text": "+1\n\nI have the same issue. The exception is: \"Mixpanel error: token, missing or empty\" because of this bug.\n\n+1 I also just ran into this. Is it worth submitting a PR for this? I see 3 unmerged PRs that are a few years old.", "created_at": "2016-12-22T00:07:05Z"} diff --git a/PythonDataset/test/monet-task-instances.jsonl.all b/PythonDataset/test/monet-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..5939c7e68d343f0112eb898b674c600f55d5a1dc --- /dev/null +++ b/PythonDataset/test/monet-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "noaa-oar-arl/monet", "pull_number": 22, "instance_id": "noaa-oar-arl__monet-22", "issue_numbers": "", "base_commit": "122196d3691f4ee40491739adae1f5a4ba764b62", "patch": "diff --git a/docs/conf.py b/docs/conf.py\nnew file mode 100644\n--- /dev/null\n+++ b/docs/conf.py\n@@ -0,0 +1,178 @@\n+# -*- coding: utf-8 -*-\n+#\n+# Configuration file for the Sphinx documentation builder.\n+#\n+# This file does only contain a selection of the most common options. For a\n+# full list see the documentation:\n+# http://www.sphinx-doc.org/en/master/config\n+\n+# -- Path setup --------------------------------------------------------------\n+\n+# If extensions (or modules to document with autodoc) are in another directory,\n+# add these directories to sys.path here. If the directory is relative to the\n+# documentation root, use os.path.abspath to make it absolute, like shown here.\n+#\n+import os\n+import sys\n+sys.path.insert(0, os.path.abspath('../'))\n+\n+# -- Project information -----------------------------------------------------\n+\n+project = u'MONET'\n+copyright = u'2018, Barry Baker'\n+author = u'Barry Baker'\n+\n+# The short X.Y version\n+version = u''\n+# The full version, including alpha/beta/rc tags\n+release = u''\n+\n+# -- General configuration ---------------------------------------------------\n+\n+# If your documentation needs a minimal Sphinx version, state it here.\n+#\n+# needs_sphinx = '1.0'\n+\n+# Add any Sphinx extension module names here, as strings. They can be\n+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n+# ones.\n+extensions = [\n+ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon',\n+ 'sphinx.ext.extlinks'\n+]\n+#exclude_patterns = ['_build', '**.ipynb_checkpoints']\n+\n+extlinks = {\n+ 'issue': ('https://github.com/noaa-oar-arl/MONET/issues/%s', 'GH'),\n+ 'pull': ('https://github.com/noaa-oar-arl/MONET/pull/%s', 'PR'),\n+}\n+\n+autosummary_generate = True\n+numpydoc_class_members_toctree = True\n+napoleon_google_docstring = False\n+napoleon_use_param = False\n+napoleon_use_ivar = True\n+\n+# Add any paths that contain templates here, relative to this directory.\n+templates_path = ['_templates']\n+\n+# The suffix(es) of source filenames.\n+# You can specify multiple suffix as a list of string:\n+#\n+# source_suffix = ['.rst', '.md']\n+source_suffix = '.rst'\n+\n+# The master toctree document.\n+master_doc = 'index'\n+\n+# The language for content autogenerated by Sphinx. Refer to documentation\n+# for a list of supported languages.\n+#\n+# This is also used if you do content translation via gettext catalogs.\n+# Usually you set \"language\" from the command line for these cases.\n+language = None\n+\n+# List of patterns, relative to source directory, that match files and\n+# directories to ignore when looking for source files.\n+# This pattern also affects html_static_path and html_extra_path .\n+exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store']\n+\n+# The name of the Pygments (syntax highlighting) style to use.\n+pygments_style = 'sphinx'\n+\n+# -- Options for HTML output -------------------------------------------------\n+\n+# The theme to use for HTML and HTML Help pages. See the documentation for\n+# a list of builtin themes.\n+#\n+html_theme = 'sphinx_rtd_theme'\n+\n+# Theme options are theme-specific and customize the look and feel of a theme\n+# further. For a list of options available for each theme, see the\n+# documentation.\n+#\n+# html_theme_options = {}\n+\n+# Add any paths that contain custom static files (such as style sheets) here,\n+# relative to this directory. They are copied after the builtin static files,\n+# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n+html_static_path = ['_static']\n+\n+# Custom sidebar templates, must be a dictionary that maps document names\n+# to template names.\n+#\n+# The default sidebars (for documents that don't match any pattern) are\n+# defined by theme itself. Builtin themes are using these templates by\n+# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n+# 'searchbox.html']``.\n+#\n+# html_sidebars = {}\n+\n+# -- Options for HTMLHelp output ---------------------------------------------\n+\n+# Output file base name for HTML help builder.\n+htmlhelp_basename = 'MONETdoc'\n+\n+html_theme_options = {\n+ 'logo_only': True,\n+}\n+\n+# Add any paths that contain custom themes here, relative to this directory.\n+#html_theme_path = []\n+\n+# The name for this set of Sphinx documents. If None, it defaults to\n+# \" v documentation\".\n+#html_title = None\n+\n+# A shorter title for the navigation bar. Default is the same as html_title.\n+#html_short_title = None\n+\n+# The name of an image file (relative to this directory) to place at the top\n+# of the sidebar.\n+html_logo = \"_static/noaa.png\"\n+\n+# -- Options for LaTeX output ------------------------------------------------\n+\n+latex_elements = {\n+ # The paper size ('letterpaper' or 'a4paper').\n+ #\n+ # 'papersize': 'letterpaper',\n+\n+ # The font size ('10pt', '11pt' or '12pt').\n+ #\n+ # 'pointsize': '10pt',\n+\n+ # Additional stuff for the LaTeX preamble.\n+ #\n+ # 'preamble': '',\n+\n+ # Latex figure (float) alignment\n+ #\n+ # 'figure_align': 'htbp',\n+}\n+\n+# Grouping the document tree into LaTeX files. List of tuples\n+# (source start file, target name, title,\n+# author, documentclass [howto, manual, or own class]).\n+latex_documents = [\n+ (master_doc, 'MONET.tex', u'MONET Documentation', u'Barry Baker',\n+ 'manual'),\n+]\n+\n+# -- Options for manual page output ------------------------------------------\n+\n+# One entry per manual page. List of tuples\n+# (source start file, name, description, authors, manual section).\n+man_pages = [(master_doc, 'monet', u'MONET Documentation', [author], 1)]\n+\n+# -- Options for Texinfo output ----------------------------------------------\n+\n+# Grouping the document tree into Texinfo files. List of tuples\n+# (source start file, target name, title, author,\n+# dir menu entry, description, category)\n+texinfo_documents = [\n+ (master_doc, 'MONET', u'MONET Documentation', author, 'MONET',\n+ 'One line description of project.', 'Miscellaneous'),\n+]\n+\n+# -- Extension configuration -------------------------------------------------\ndiff --git a/monet/__init__.py b/monet/__init__.py\n--- a/monet/__init__.py\n+++ b/monet/__init__.py\n@@ -1,9 +1,6 @@\n from __future__ import absolute_import, print_function\n-\n from . import models, obs, plots, util, verification\n-from .monet import MONET\n-\n-# from monet.models import camx, cmaq\n+from . import monet_accessor\n \n # from .monetmodels, obs, plots, util\n-__all__ = ['models', 'obs', 'plots', 'verification', 'util']\n+__all__ = ['models', 'obs', 'plots', 'verification', 'util', 'monet_accessor']\ndiff --git a/monet/grids.py b/monet/grids.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/grids.py\n@@ -0,0 +1,210 @@\n+\"\"\" This is a module that will derive the proj4 string and\n+ pyesample.geometry.AreaDefinition for any gridded dataset (satellite,\n+ models, etc....)\n+\n+ \"\"\"\n+import os\n+path = os.path.abspath(__file__)\n+\n+\n+def _geos_16_grid(dset):\n+ from pyresample import geometry\n+ from numpy import asarray\n+ projection = dset.goes_imager_projection\n+ h = projection.perspective_point_height\n+ a = projection.semi_major_axis\n+ b = projection.semi_minor_axis\n+ lon_0 = projection.longitude_of_projection_origin\n+ sweep = projection.sweep_angle_axis\n+ x = dset.x * h\n+ y = dset.y * h\n+ x_ll = x[0] # lower left corner\n+ x_ur = x[-1] # upper right corner\n+ y_ll = y[0] # lower left corner\n+ y_ur = y[-1] # upper right corner\n+ x_h = (x_ur - x_ll) / (len(x) - 1.) / 2. # 1/2 grid size\n+ y_h = (y_ur - y_ll) / (len(y) - 1.) / 2. # 1/2 grid size\n+ area_extent = (x_ll - x_h, y_ll - y_h, x_ur + x_h, y_ur + y_h)\n+\n+ proj_dict = {\n+ 'a': float(a),\n+ 'b': float(b),\n+ 'lon_0': float(lon_0),\n+ 'h': float(h),\n+ 'proj': 'geos',\n+ 'units': 'm',\n+ 'sweep': sweep\n+ }\n+\n+ area = geometry.AreaDefinition('GEOS_ABI', 'ABI', 'GOES_ABI', proj_dict,\n+ len(x), len(y), asarray(area_extent))\n+ return area\n+\n+\n+def _get_sinu_grid_df():\n+ from pandas import read_csv\n+ \"\"\"This function finds the modis grid tiles found within\n+ the defined grid.\n+ input:\n+ lon = gridded longitude - numpy array\n+ lat = gridded latitude - numpy array\n+ output:\n+ pandas dataframe of tiles\n+ \"\"\"\n+ f = path[:-8] + 'data/sn_bound_10deg.txt'\n+ td = read_csv(f, skiprows=4, delim_whitespace=True)\n+ td = td.assign(ihiv='h' + td.ih.astype(str).str.zfill(2) + 'v' +\n+ td.iv.astype(str).str.zfill(2))\n+ return td\n+\n+\n+def _sinu_grid_latlon_boundary(h, v):\n+ td = _get_sinu_grid_df()\n+ o = td.loc[(td.ih == int(h)) & (td.iv == int(v))]\n+ latmin = o.lat_min.iloc[0]\n+ lonmin = o.lon_min.iloc[0]\n+ latmax = o.lat_max.iloc[0]\n+ lonmax = o.lon_max.iloc[0]\n+ return lonmin, latmin, lonmax, latmax\n+\n+\n+def _get_sinu_xy(lon, lat):\n+ from pyproj import Proj\n+ sinu = Proj(\n+ '+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m'\n+ )\n+ return sinu(lon, lat)\n+\n+\n+def _get_sinu_latlon(x, y):\n+ from numpy import meshgrid\n+ from pyproj import Proj\n+ xv, yv = meshgrid(x, y)\n+ sinu = Proj(\n+ '+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m, +R=6371007.181'\n+ )\n+ return sinu(xv, yv, inverse=True)\n+\n+\n+def get_sinu_area_extent(lonmin, latmin, lonmax, latmax):\n+ xmin, ymin = _get_sinu_xy(lonmin, latmin)\n+ xmax, ymax = _get_sinu_xy(lonmax, latmax)\n+ return (xmin, ymin, xmax, ymax)\n+\n+\n+def get_modis_latlon_from_swath_hv(h, v, dset):\n+ from numpy import linspace\n+ lonmin, latmin, lonmax, latmax = _sinu_grid_latlon_boundary(h, v)\n+ xmin, ymin = _get_sinu_xy(lonmin, latmin)\n+ xmax, ymax = _get_sinu_xy(lonmax, latmax)\n+ x = linspace(xmin, xmax, len(dset.x))\n+ y = linspace(ymin, ymax, len(dset.y))\n+ lon, lat = _get_sinu_latlon(x, y)\n+ dset.coords['longitude'] = (('x', 'y'), lon)\n+ dset.coords['latitude'] = (('x', 'y'), lat)\n+ dset.attrs['area_extent'] = (x.min(), y.min(), x.max(), y.max())\n+ dset.attrs[\n+ 'proj4_srs'] = '+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 ' \\\n+ '+b=6371007.181 +units=m'\n+ return dset\n+\n+\n+def get_sinu_area_def(dset):\n+ from pyresample import utils\n+ from pyproj import Proj\n+ p = Proj(dset.attrs['proj4_srs'])\n+ proj4_args = p.srs\n+ area_name = 'MODIS Grid Def'\n+ area_id = 'modis'\n+ proj_id = area_id\n+ area_extent = dset.attrs['area_extent']\n+ nx, ny = dset.longitude.shape\n+ return utils.get_area_def(area_id, area_name, proj_id, proj4_args, nx, ny,\n+ area_extent)\n+\n+\n+def get_ioapi_pyresample_area_def(ds, proj4_srs):\n+ from pyresample import geometry, utils\n+ y_size = ds.NROWS\n+ x_size = ds.NCOLS\n+ projection = utils.proj4_str_to_dict(proj4_srs)\n+ proj_id = 'IOAPI_Dataset'\n+ description = 'IOAPI area_def for pyresample'\n+ area_id = 'MONET_Object_Grid'\n+ x_ll, y_ll = ds.XORIG + ds.XCELL * .5, ds.YORIG + ds.YCELL * .5\n+ x_ur, y_ur = ds.XORIG + (ds.NCOLS * ds.XCELL) + .5 * ds.XCELL, ds.YORIG + (\n+ ds.YCELL * ds.NROWS) + .5 * ds.YCELL\n+ area_extent = (x_ll, y_ll, x_ur, y_ur)\n+ area_def = geometry.AreaDefinition(area_id, description, proj_id,\n+ projection, x_size, y_size, area_extent)\n+ return area_def\n+\n+\n+def _ioapi_grid_from_dataset(ds, earth_radius=6370000):\n+ \"\"\"Get the IOAPI projection out of the file into proj4.\"\"\"\n+\n+ pargs = dict()\n+ pargs['lat_1'] = ds.P_ALP\n+ pargs['lat_2'] = ds.P_BET\n+ pargs['lat_0'] = ds.YCENT\n+ pargs['lon_0'] = ds.P_GAM\n+ pargs['center_lon'] = ds.XCENT\n+ pargs['x0'] = ds.XORIG\n+ pargs['y0'] = ds.YORIG\n+ pargs['r'] = earth_radius\n+ proj_id = ds.GDTYP\n+ if proj_id == 2:\n+ # Lambert\n+ p4 = '+proj=lcc +lat_1={lat_1} +lat_2={lat_2} ' \\\n+ '+lat_0={lat_0} +lon_0={lon_0} ' \\\n+ '+x_0=0 +y_0=0 +datum=WGS84 +units=m +a={r} +b={r}'\n+ p4 = p4.format(**pargs)\n+ elif proj_id == 4:\n+ # Polar stereo\n+ p4 = '+proj=stere +lat_ts={lat_1} +lon_0={lon_0} +lat_0=90.0' \\\n+ '+x_0=0 +y_0=0 +a={r} +b={r}'\n+ p4 = p4.format(**pargs)\n+ elif proj_id == 3:\n+ # Mercator\n+ p4 = '+proj=merc +lat_ts={lat_1} ' \\\n+ '+lon_0={center_lon} ' \\\n+ '+x_0={x0} +y_0={y0} +a={r} +b={r}'\n+ p4 = p4.format(**pargs)\n+ else:\n+ raise NotImplementedError('IOAPI proj not implemented yet: '\n+ '{}'.format(proj_id))\n+ #area_def = _get_ioapi_pyresample_area_def(ds)\n+ return p4 # , area_def\n+\n+\n+def _hysplit_latlon_grid_from_dataset(ds):\n+ pargs = dict()\n+ pargs['lat_0'] = ds.latitude.mean()\n+ pargs['lon_0'] = ds.longitude.mean()\n+\n+ p4 = '+proj=eqc +lat_ts={lat_0} +lat_0={lat_0} +lon_0={lon_0} ' \\\n+ '+ellps=WGS84 +datum=WGS84 +units=m +no_defs'.format(pargs)\n+ return p4\n+\n+\n+def get_hysplit_latlon_pyreample_area_def(ds, proj4_srs):\n+ from pyresample import geometry\n+ return geometry.SwathDefinition(\n+ lons=ds.longitude.values, lats=ds.latitude.values)\n+\n+\n+def grid_from_dataset(ds, earth_radius=6370000):\n+ \"\"\"Find out if the dataset contains enough info for Salem to understand.\n+\n+ ``ds`` can be an xarray dataset\n+\n+ Returns a :py:string:`proj4_string` if successful, ``None`` otherwise\n+ \"\"\"\n+ # maybe its an IOAPI file\n+ if hasattr(ds, 'IOAPI_VERSION') or hasattr(ds, 'P_ALP'):\n+ # IOAPI_VERSION\n+ return _ioapi_grid_from_dataset(ds, earth_radius=earth_radius)\n+\n+ # Try out platte carree\n+\n+ # return _lonlat_grid_from_dataset(ds)\ndiff --git a/monet/models/__init__.py b/monet/models/__init__.py\n--- a/monet/models/__init__.py\n+++ b/monet/models/__init__.py\n@@ -1,9 +1,5 @@\n-from __future__ import absolute_import, print_function\n+from . import cmaq, hysplit, camx\n \n-from . import camx, cmaq\n+__all__ = ['cmaq', 'hysplit', 'camx']\n \n-__all__ = ['camx', 'cmaq']\n-\n-__name__ = 'models'\n-\n-#\n+__name__ = 'models'\n\\ No newline at end of file\ndiff --git a/monet/models/camx.py b/monet/models/camx.py\n--- a/monet/models/camx.py\n+++ b/monet/models/camx.py\n@@ -1,179 +1,311 @@\n-from __future__ import division, print_function\n+\"\"\" CAMx File Reader \"\"\"\n+from numpy import array, concatenate\n+from pandas import Series, to_datetime\n+import xarray as xr\n+from ..grids import grid_from_dataset, get_ioapi_pyresample_area_def\n \n-from builtins import object, zip\n \n-import pandas as pd\n-import xarray as xr\n-from dask.diagnostics import ProgressBar\n-from numpy import array\n-from past.utils import old_div\n-\n-# This file is to deal with CAMx code - try to make it general for CAMx 4.7.1 --> 5.1\n-\n-\n-ProgressBar().register()\n-\n-\n-class CAMx(object):\n- def __init__(self):\n- self.objtype = 'CAMX'\n- self.coarse = array(\n- ['NA', 'PSO4', 'PNO3', 'PNH4', 'PH2O', 'PCL', 'PEC', 'FPRM', 'FCRS', 'CPRM', 'CCRS', 'SOA1', 'SOA2', 'SOA3',\n- 'SOA4'])\n- self.fine = array(\n- ['NA', 'PSO4', 'PNO3', 'PNH4', 'PH2O', 'PCL', 'PEC', 'FPRM', 'FCRS', 'SOA1', 'SOA2', 'SOA3',\n- 'SOA4'])\n- self.noy_gas = array(\n- ['NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA', 'NTR', 'CRON', 'CRN2', 'CRNO',\n- 'CRPX', 'OPAN'])\n- self.poc = array(['SOA1', 'SOA2', 'SOA3', 'SOA4'])\n- self.dset = None\n- self.grid = None # gridcro2d obj\n- self.fname = None\n- self.metcrofnames = None\n- self.aerofnames = None\n- self.dates = None\n- self.keys = None\n- self.indexdates = None\n- self.metindex = None\n- self.latitude = None\n- self.longitude = None\n- self.map = None\n-\n- def get_dates(self):\n- print('Reading CAMx dates...')\n- print(self.dset)\n- tflag1 = array(self.dset['TFLAG'][:, 0], dtype='|S7')\n- tflag2 = array(old_div(self.dset['TFLAG'][:, 1], 10000), dtype='|S6')\n- date = pd.to_datetime([i + j.zfill(2) for i, j in zip(tflag1, tflag2)], format='%Y%j%H')\n- indexdates = pd.Series(date).drop_duplicates(keep='last').index.values\n- self.dset = self.dset.isel(time=indexdates)\n- self.dset['time'] = date[indexdates]\n-\n- def open_camx(self, file):\n- from glob import glob\n- from numpy import sort\n- dropset = ['layer', 'longitude_bounds', 'latitude_bounds',\n- 'x', 'y', 'level', 'lambert_conformal_conic']\n- nameset = {'COL': 'x', 'ROW': 'y', 'TSTEP': 'time', 'LAY': 'z'}\n- if type(file) == str:\n- fname = sort(array(glob(file)))\n- else:\n- fname = sort(array(file))\n- if fname.shape[0] >= 1:\n- if self.dset is None:\n- self.dset = xr.open_mfdataset(\n- fname.tolist(), concat_dim='TSTEP', engine='pnc').drop(dropset).rename(nameset).squeeze()\n- self.load_conus_basemap(res='l')\n- self.get_dates()\n- else:\n- dset = xr.open_mfdataset(fname.tolist(), concat_dim='TSTEP',\n- engine='pnc').drop(dropset).rename(nameset).squeeze()\n- self.dset = xr.merge([self.dset, dset])\n- else:\n- print('Files not found')\n- self.keys = list(self.dset.keys())\n-\n- def check_z(self, varname):\n- if pd.Series(self.dset[varname].dims).isin('z').max():\n- return True\n- else:\n- return False\n-\n- def get_nox(self, lay=None):\n- if self.check_z('NO'):\n- if lay is not None:\n- var = self.dset['NO'][:, 0, :, :].squeeze().copy()\n- var += self.dset['NO2'][:, 0, :, :].squeeze().copy()\n- else:\n- var = self.dset['NO'][:, :, :, :].copy()\n- var += self.dset['NO2'][:, :, :, :].copy()\n- else:\n- var = self.dset['NO'][:, :, :].copy()\n- var += self.dset['NO2'][:, :, :].copy()\n- return var\n-\n- def get_pm25(self, lay=None):\n- keys = list(self.dset.keys())\n- allvars = self.fine\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- if self.check_z(newkeys[0]):\n- if lay is not None:\n- var = self.dset[newkeys[0]][:, 0, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, 0, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :].copy()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :].squeeze()\n- return var\n-\n- def get_pm10(self, lay=None):\n- keys = list(self.dset.keys())\n- allvars = self.coarse\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- if self.check_z(newkeys[0]):\n- if lay is not None:\n- var = self.dset[newkeys[0]][:, 0, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, 0, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :].copy()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :].squeeze()\n- return var\n-\n- def get_var(self, param='O3', lay=None):\n- p = param.upper()\n- print(param)\n- if p == 'PM25':\n- var = self.get_pm25(lay=lay)\n- elif p == 'PM10':\n- var = self.get_pm10(lay=lay)\n- elif p == 'NOX':\n- var = self.get_nox(lay=lay)\n- elif p == 'OC':\n- var = self.get_oc(lay=lay)\n- elif p == 'VOC':\n- if lay is not None:\n- var = self.dset['VOC'][:, 0, :, :].copy().squeeze()\n- else:\n- var = self.dset['VOC'][:, :, :, :].copy().squeeze()\n- else:\n- if self.check_z(param):\n- if lay is None:\n- var = self.dset[param][:, :, :, :].copy()\n- else:\n- var = self.dset[param][:, lay, :, :].copy().squeeze()\n- else:\n- var = self.dset[param]\n- return var\n-\n- def load_conus_basemap(self, res='l'):\n- from mpl_toolkits.basemap import Basemap\n- if self.map is None:\n- lat1 = self.dset.P_ALP\n- lat2 = self.dset.P_BET\n- lon1 = self.dset.P_GAM\n- lon0 = self.dset.XCENT\n- lat0 = self.dset.YCENT\n- m = Basemap(projection='lcc', resolution=res, lat_1=lat1, lat_2=lat2, lat_0=lat0, lon_0=lon0,\n- lon_1=lon1,\n- llcrnrlat=self.dset.latitude[0, 0], urcrnrlat=self.dset.latitude[-1, -1],\n- llcrnrlon=self.dset.longitude[0, 0],\n- urcrnrlon=self.dset.longitude[-1, -1], rsphere=6371200.,\n- area_thresh=50.)\n- self.map = m\n- else:\n- m = self.map\n- return self.map\n+def can_do(index):\n+ if index.max():\n+ return True\n+ else:\n+ return False\n+\n+\n+def open_files(fname, earth_radius=6370000):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ fname : type\n+ Description of parameter `fname`.\n+ earth_radius : type\n+ Description of parameter `earth_radius`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ # open the dataset using xarray\n+ dset = xr.open_mfdataset(\n+ fname, engine='pseudonetcdf', backend_kwargs={'format': 'uamiv'})\n+\n+ # get the grid information\n+ grid = grid_from_dataset(dset, earth_radius=earth_radius)\n+ area_def = get_ioapi_pyresample_area_def(dset, grid)\n+ # assign attributes for dataset and all DataArrays\n+ dset = dset.assign_attrs({'proj4_srs': grid})\n+ for i in dset.variables:\n+ dset[i] = dset[i].assign_attrs({'proj4_srs': grid})\n+ for j in dset[i].attrs:\n+ dset[i].attrs[j] = dset[i].attrs[j].strip()\n+ dset[i] = dset[i].assign_attrs({'area': area_def})\n+ dset = dset.assign_attrs(area=area_def)\n+\n+ # add lazy diagnostic variables\n+ dset = add_lazy_pm25(dset)\n+ dset = add_lazy_pm10(dset)\n+ dset = add_lazy_pm_course(dset)\n+ dset = add_lazy_noy(dset)\n+ dset = add_lazy_nox(dset)\n+\n+ # get the times\n+ dset = _get_times(dset)\n+\n+ # get the lat lon\n+ dset = _get_latlon(dset)\n+\n+ # get Predefined mapping tables for observations\n+ dset = _predefined_mapping_tables(dset)\n+\n+ # rename dimensions\n+ dset = dset.rename({'COL': 'x', 'ROW': 'y', 'LAY': 'z'})\n+\n+ return dset\n+\n+\n+def _get_times(d):\n+ idims = len(d.TFLAG.dims)\n+ if idims == 2:\n+ tflag1 = Series(d['TFLAG'][:, 0]).astype(str).str.zfill(7)\n+ tflag2 = Series(d['TFLAG'][:, 1]).astype(str).str.zfill(6)\n+ else:\n+ tflag1 = Series(d['TFLAG'][:, 0, 0]).astype(str).str.zfill(7)\n+ tflag2 = Series(d['TFLAG'][:, 0, 1]).astype(str).str.zfill(6)\n+ date = to_datetime(\n+ [i + j for i, j in zip(tflag1, tflag2)], format='%Y%j%H%M%S')\n+ indexdates = Series(date).drop_duplicates(keep='last').index.values\n+ d = d.isel(TSTEP=indexdates)\n+ d['TSTEP'] = date[indexdates]\n+ return d.rename({'TSTEP': 'time'})\n+\n+\n+def _get_latlon(dset):\n+ \"\"\"gets the lat and lons from the pyreample.geometry.AreaDefinition\n+\n+ Parameters\n+ ----------\n+ dset : xarray.Dataset\n+ Description of parameter `dset`.\n+\n+ Returns\n+ -------\n+ xarray.Dataset\n+ Description of returned object.\n+\n+ \"\"\"\n+ lon, lat = dset.area.get_lonlats()\n+ dset['longitude'] = xr.DataArray(lon[::-1, :], dims=['ROW', 'COL'])\n+ dset['latitude'] = xr.DataArray(lat[::-1, :], dims=['ROW', 'COL'])\n+ dset = dset.assign_coords(longitude=dset.longitude, latitude=dset.latitude)\n+ return dset\n+\n+\n+def add_lazy_pm25(d):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ d : type\n+ Description of parameter `d`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(fine)\n+ if 'PM25_TOT' in keys:\n+ d['PM25'] = d['PM25_TOT'].chunk()\n+ else:\n+ index = allvars.isin(keys)\n+ newkeys = allvars.loc[index]\n+ d['PM25'] = add_multiple_lazy(d, newkeys)\n+ d['PM25'].assign_attrs({'name': 'PM2.5', 'long_name': 'PM2.5'})\n+ return d\n+\n+\n+def add_lazy_pm10(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(concatenate([fine, coarse]))\n+ if 'PM_TOT' in keys:\n+ d['PM10'] = d['PM_TOT'].chunk()\n+ else:\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['PM10'] = add_multiple_lazy(d, newkeys)\n+ d['PM10'] = d['PM10'].assign_attrs({\n+ 'name':\n+ 'PM10',\n+ 'long_name':\n+ 'Particulate Matter < 10 microns'\n+ })\n+ return d\n+\n+\n+def add_lazy_pm_course(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(coarse)\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['PM_COURSE'] = add_multiple_lazy(d, newkeys)\n+ d['PM_COURSE'] = d['PM_COURSE'].assign_attrs({\n+ 'name':\n+ 'PM_COURSE',\n+ 'long_name':\n+ 'Course Mode Particulate Matter'\n+ })\n+ return d\n+\n+\n+def add_lazy_clf(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ACLI', 'ACLJ', 'ACLK'])\n+ weights = Series([1, 1, .2])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['CLf'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['CLf'] = d['CLf'].assign_attrs({\n+ 'name':\n+ 'CLf',\n+ 'long_name':\n+ 'Fine Mode particulate Cl'\n+ })\n+ return d\n+\n+\n+def add_lazy_noy(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(noy_gas)\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['NOy'] = add_multiple_lazy(d, newkeys)\n+ d['NOy'] = d['NOy'].assign_attrs({'name': 'NOy', 'long_name': 'NOy'})\n+ return d\n+\n+\n+def add_lazy_nox(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['NO', 'NOX'])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['NOx'] = add_multiple_lazy(d, newkeys)\n+ d['NOx'] = d['NOx'].assign_attrs({'name': 'NOx', 'long_name': 'NOx'})\n+ return d\n+\n+\n+def add_multiple_lazy(dset, variables, weights=None):\n+ from numpy import ones\n+ if weights is None:\n+ weights = ones(len(variables))\n+ new = dset[variables[0]].copy() * weights[0]\n+ for i, j in zip(variables[1:], weights[1:]):\n+ new = new + dset[i].chunk() * j\n+ return new\n+\n+\n+def _predefined_mapping_tables(dset):\n+ \"\"\"Predefined mapping tables for different observational parings used when\n+ combining data.\n+\n+ Returns\n+ -------\n+ dictionary\n+ A dictionary of to map to.\n+\n+ \"\"\"\n+ to_improve = {}\n+ to_nadp = {}\n+ to_aqs = {\n+ 'OZONE': ['O3'],\n+ 'PM2.5': ['PM25'],\n+ 'CO': ['CO'],\n+ 'NOY': [\n+ 'NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA',\n+ 'NTR', 'CRON', 'CRN2', 'CRNO', 'CRPX', 'OPAN'\n+ ],\n+ 'NOX': ['NO', 'NO2'],\n+ 'SO2': ['SO2'],\n+ 'NO': ['NO'],\n+ 'NO2': ['NO2'],\n+ 'SO4f': ['PSO4'],\n+ 'PM10': ['PM10'],\n+ 'NO3f': ['PNO3'],\n+ 'ECf': ['PEC'],\n+ 'OCf': ['OC'],\n+ 'ETHANE': ['ETHA'],\n+ 'BENZENE': ['BENZENE'],\n+ 'TOLUENE': ['TOL'],\n+ 'ISOPRENE': ['ISOP'],\n+ 'O-XYLENE': ['XYL'],\n+ 'WS': ['WSPD10'],\n+ 'TEMP': ['TEMP2'],\n+ 'WD': ['WDIR10'],\n+ 'NAf': ['NA'],\n+ 'NH4f': ['PNH4']\n+ }\n+ to_airnow = {\n+ 'OZONE': ['O3'],\n+ 'PM2.5': ['PM25'],\n+ 'CO': ['CO'],\n+ 'NOY': [\n+ 'NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA',\n+ 'NTR', 'CRON', 'CRN2', 'CRNO', 'CRPX', 'OPAN'\n+ ],\n+ 'NOX': ['NO', 'NO2'],\n+ 'SO2': ['SO2'],\n+ 'NO': ['NO'],\n+ 'NO2': ['NO2'],\n+ 'SO4f': ['PSO4'],\n+ 'PM10': ['PM10'],\n+ 'NO3f': ['PNO3'],\n+ 'ECf': ['PEC'],\n+ 'OCf': ['OC'],\n+ 'ETHANE': ['ETHA'],\n+ 'BENZENE': ['BENZENE'],\n+ 'TOLUENE': ['TOL'],\n+ 'ISOPRENE': ['ISOP'],\n+ 'O-XYLENE': ['XYL'],\n+ 'WS': ['WSPD10'],\n+ 'TEMP': ['TEMP2'],\n+ 'WD': ['WDIR10'],\n+ 'NAf': ['NA'],\n+ 'NH4f': ['PNH4']\n+ }\n+ to_crn = {}\n+ to_aeronet = {}\n+ to_cems = {}\n+ mapping_tables = {\n+ 'improve': to_improve,\n+ 'aqs': to_aqs,\n+ 'airnow': to_airnow,\n+ 'crn': to_crn,\n+ 'cems': to_cems,\n+ 'nadp': to_nadp,\n+ 'aeronet': to_aeronet\n+ }\n+ dset = dset.assign_attrs({'mapping_tables': mapping_tables})\n+ return dset\n+\n+\n+# Arrays for different gasses and pm groupings\n+coarse = array(['CPRM', 'CCRS'])\n+fine = array([\n+ 'NA', 'PSO4', 'PNO3', 'PNH4', 'PH2O', 'PCL', 'PEC', 'FPRM', 'FCRS', 'SOA1',\n+ 'SOA2', 'SOA3', 'SOA4'\n+])\n+noy_gas = array([\n+ 'NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA', 'NTR',\n+ 'CRON', 'CRN2', 'CRNO', 'CRPX', 'OPAN'\n+])\n+poc = array(['SOA1', 'SOA2', 'SOA3', 'SOA4'])\ndiff --git a/monet/models/cmaq.py b/monet/models/cmaq.py\n--- a/monet/models/cmaq.py\n+++ b/monet/models/cmaq.py\n@@ -1,447 +1,504 @@\n-from __future__ import absolute_import, division, print_function\n+\"\"\" CMAQ File Reader \"\"\"\n+from numpy import array, concatenate\n+from pandas import Series, to_datetime\n+import xarray as xr\n+from ..grids import grid_from_dataset, get_ioapi_pyresample_area_def\n \n-# This file is to deal with CMAQ code - try to make it general for cmaq 4.7.1 --> 5.1\n-from builtins import object, zip\n-from gc import collect\n \n-import pandas as pd\n-import xarray as xr\n-from dask.diagnostics import ProgressBar\n-from numpy import array, zeros\n-from past.utils import old_div\n-\n-ProgressBar().register()\n-\n-\n-class CMAQ(object):\n- def __init__(self):\n- self.objtype = 'CMAQ'\n- self.dust_pm25 = array(\n- ['ASO4J', 'ANO3J', 'ACLJ', 'ANH4J', 'ANAJ', 'ACAJ', 'AMGJ', 'AKJ', 'APOCJ', 'APNCOMJ', 'AECJ', 'AFEJ',\n- 'AALJ', 'ASIJ', 'ATIJ', 'AMNJ', 'AOTHRJ'])\n- self.dust_total = array(\n- ['ASO4J', 'ASO4K', 'ANO3J', 'ANO3K', 'ACLJ', 'ACLK', 'ANH4J', 'ANAJ', 'ACAJ', 'AMGJ', 'AKJ', 'APOCJ',\n- 'APNCOMJ', 'AECJ', 'AFEJ', 'AALJ', 'ASIJ', 'ATIJ', 'AMNJ', 'AOTHRJ', 'ASOIL'])\n- self.aitken = array(['ACLI', 'AECI', 'ANAI', 'ANH4I',\n- 'ANO3I', 'AOTHRI', 'APNCOMI', 'APOCI',\n- 'ASO4I', 'AORGAI', 'AORGPAI',\n- 'AORGBI'])\n- self.accumulation = array(\n- ['AALJ', 'AALK1J', 'AALK2J', 'ABNZ1J', 'ABNZ2J', 'ABNZ3J', 'ACAJ', 'ACLJ', 'AECJ', 'AFEJ',\n- 'AISO1J', 'AISO2J', 'AISO3J', 'AKJ', 'AMGJ', 'AMNJ', 'ANAJ', 'ANH4J', 'ANO3J', 'AOLGAJ', 'AOLGBJ',\n- 'AORGCJ', 'AOTHRJ', 'APAH1J', 'APAH2J', 'APAH3J', 'APNCOMJ', 'APOCJ', 'ASIJ', 'ASO4J', 'ASQTJ', 'ATIJ',\n- 'ATOL1J', 'ATOL2J', 'ATOL3J', 'ATRP1J', 'ATRP2J', 'AXYL1J', 'AXYL2J', 'AXYL3J', 'AORGAJ',\n- 'AORGPAJ', 'AORGBJ'])\n- self.coarse = array(['ACLK', 'ACORS', 'ANH4K', 'ANO3K', 'ASEACAT', 'ASO4K', 'ASOIL'])\n- self.noy_gas = array(\n- ['NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA', 'NTR', 'CRON', 'CRN2', 'CRNO',\n- 'CRPX', 'OPAN'])\n- self.pec = array(['AECI', 'AECJ'])\n- self.pso4 = array(['ASO4I', 'ASO4J'])\n- self.pno3 = array(['ANO3I', 'ANO3J'])\n- self.pnh4 = array(['ANH4I', 'ANH4J'])\n- self.pcl = array(['ACLI', 'ACLJ'])\n- self.poc = array(['AOTHRI', 'APNCOMI', 'APOCI', 'AORGAI', 'AORGPAI', 'AORGBI', 'ATOL1J', 'ATOL2J', 'ATOL3J',\n- 'ATRP1J', 'ATRP2J', 'AXYL1J', 'AXYL2J', 'AXYL3J', 'AORGAJ', 'AORGPAJ', 'AORGBJ', 'AOLGAJ',\n- 'AOLGBJ', 'AORGCJ', 'AOTHRJ', 'APAH1J', 'APAH2J', 'APAH3J', 'APNCOMJ', 'APOCJ', 'ASQTJ',\n- 'AISO1J', 'AISO2J', 'AISO3J', 'AALK1J', 'AALK2J', 'ABNZ1J', 'ABNZ2J', 'ABNZ3J', 'AORGAI',\n- 'AORGAJ', 'AORGPAI', 'AORGPAJ', 'AORGBI', 'AORGBJ'])\n- self.minerals = array(['AALJ', 'ACAJ', 'AFEJ', 'AKJ', 'AMGJ', 'AMNJ', 'ANAJ', 'ATIJ', 'ASIJ'])\n- self.dset = None # CMAQ xarray dataset object\n- self.grid = None # CMAQ xarray dataset gridcro2d obj\n- self.dates = None\n- self.keys = None\n- self.metcrokeys = []\n- self.indexdates = None\n- self.metdates = None\n- self.metindex = None\n- self.latitude = None\n- self.longitude = None\n- self.map = None\n-\n- def get_dates(self):\n- print('Reading CMAQ dates...')\n- idims = len(self.dset.TFLAG.dims)\n- if idims == 2:\n- tflag1 = array(self.dset['TFLAG'][:, 0], dtype='|S7')\n- tflag2 = array(old_div(self.dset['TFLAG'][:, 1], 10000), dtype='|S6')\n- else:\n- tflag1 = array(self.dset['TFLAG'][:, 0, 0], dtype='|S7')\n- tflag2 = array(old_div(self.dset['TFLAG'][:, 0, 1], 10000), dtype='|S6')\n- date = pd.to_datetime([i + j.zfill(2) for i, j in zip(tflag1, tflag2)], format='%Y%j%H')\n- indexdates = pd.Series(date).drop_duplicates(keep='last').index.values\n- self.dset = self.dset.isel(time=indexdates)\n- self.dset['time'] = date[indexdates]\n-\n- def open_cmaq(self, file):\n- from glob import glob\n- from numpy import sort\n- nameset = {'COL': 'x', 'ROW': 'y', 'TSTEP': 'time', 'LAY': 'z'}\n- if type(file) == str:\n- fname = sort(array(glob(file)))\n- else:\n- fname = sort(array(file))\n- if fname.shape[0] >= 1:\n- if self.dset is None:\n- self.dset = xr.open_mfdataset(fname.tolist(), concat_dim='TSTEP').rename(nameset).squeeze()\n- else:\n- dset = xr.open_mfdataset(fname.tolist(), concat_dim='TSTEP').rename(nameset).squeeze()\n- self.dset = xr.merge([self.dset, dset])\n- else:\n- print('Files not found')\n- if self.grid is not None:\n- self.dset = self.dset.assign(latitude=self.grid.LAT.squeeze())\n- self.dset = self.dset.assign(longitude=self.grid.LON.squeeze())\n- self.dset = self.dset.set_coords(['latitude', 'longitude'])\n- self.get_dates()\n- self.keys = list(self.dset.keys())\n-\n- def check_z(self, varname):\n- if pd.Series(self.dset[varname].dims).isin(['z']).max():\n- return True\n- else:\n- return False\n-\n- def add_multiple_fields(self, findkeys, lay=None, weights=None):\n- from numpy import ones\n- keys = self.keys\n- newkeys = pd.Series(findkeys).loc[pd.Series(findkeys).isin(keys)].values\n- if weights is None:\n- w = ones(len(newkeys))\n- if self.check_z(newkeys[0]):\n- if lay is not None:\n- var = self.dset[newkeys[0]][:, 0, :, :].squeeze() * w[0]\n- for i, j in zip(newkeys[1:], w[1:]):\n- var += self.dset[i][:, 0, :, :].squeeze() * j\n- else:\n- var = self.dset[newkeys[0]][:, :, :, :].squeeze() * w[0]\n- for i, j in zip(newkeys[1:], w[1:]):\n- var += self.dset[i][:, :, :, :].squeeze() * j\n- else:\n- var = self.dset[newkeys[0]][:, :, :].copy() * w[0]\n- for i, j in zip(newkeys[1:], w[1:]):\n- var += self.dset[i][:, :, :].squeeze() * j\n- return var\n-\n- def get_dust_total(self, lay=None):\n- return self.add_multiple_fields(self.dust_totl, lay=lay)\n-\n- def get_noy(self, lay=None):\n- keys = self.keys\n- if 'NOY' in keys:\n- if self.check_z('NOY'):\n- if lay is not None:\n- var = self.dset['NOY'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['NOY'][:, :, :, :]\n- else:\n- var = self.dset['NOY'][:]\n- else:\n- var = self.add_multiple_fields(self.noy_gas, lay=lay)\n- return var\n-\n- def get_nox(self, lay=None):\n- var = self.add_multiple_fields(['NO', 'NOX'], lay=lay)\n- return var\n-\n- def get_dust_pm25(self, lay=None):\n- return self.add_multiple_fields(self.dust_pm25, lay=lay)\n-\n- def get_pm25(self, lay=None):\n- from numpy import concatenate\n- keys = self.keys\n- allvars = concatenate([self.aitken, self.accumulation, self.coarse])\n- weights = array(\n- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n- 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n- 1., 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2])\n- if 'PM25_TOT' in keys:\n- if self.check_z('PM25_TOT'):\n- if lay is not None:\n- var = self.dset['PM25_TOT'][:, lay, :, :].copy().squeeze()\n- else:\n- var = self.dset['PM25_TOT'][:, :, :, :].copy()\n- else:\n- var = self.dset['PM25_TOT'][:, :, :].copy()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM2.5'\n- var['long_name'] = 'PM2.5'\n- var['var_desc'] = 'Variable PM2.5'\n- return var\n-\n- def get_pm10(self, lay=None):\n- from numpy import concatenate\n- keys = self.keys\n- allvars = concatenate([self.aitken, self.accumulation, self.coarse])\n- var = None\n- if 'PMC_TOT' in keys:\n- if self.check_z('PM10_TOT'):\n- if lay is not None:\n- var = self.dset['PMC_TOT'][:, lay, :, :].copy().squeeze()\n- else:\n- var = self.dset['PMC_TOT'][:, :, :, :].copy()\n- else:\n- var = self.dset['PMC_TOT'][:, :, :].copy()\n- elif 'PM10' in keys:\n- if self.check_z('PM10_TOT'):\n- if lay is not None:\n- var = self.dset['PM10'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM10'][:, :, :, :].squeeze()\n- else:\n- var = self.dset['PMC_TOT'][:, :, :].copy()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM2.5'\n- var['long_name'] = 'PM2.5'\n- var['var_desc'] = 'Variable PM2.5'\n- return var\n-\n- def get_clf(self, lay=None):\n- keys = self.keys\n- allvars = array(['ACLI', 'ACLJ', 'ACLK'])\n- weights = array([1, 1, .2])\n- var = None\n- if 'PM25_CL' in keys:\n- var = self.dset['PM25_CL'][:, lay, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_CL'\n- var['long_name'] = 'PM25_CL'\n- var['var_desc'] = 'Variable PM25_CL'\n- return var\n-\n- def get_naf(self, lay=None):\n- keys = self.keys\n- allvars = array(['ANAI', 'ANAJ', 'ASEACAT', 'ASOIL', 'ACORS'])\n- weights = array([1, 1, .2 * 837.3 / 1000., .2 * 62.6 / 1000., .2 * 2.3 / 1000.])\n- if 'PM25_NA' in keys:\n- if lay is not None:\n- var = self.dset['PM25_NA'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_NA'][:, :, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_NA'\n- var['long_name'] = 'PM25_NA'\n- var['var_desc'] = 'Variable PM25_NA'\n- return var\n-\n- def get_kf(self, lay=None):\n- keys = self.keys\n- allvars = array(['AKI', 'AKJ', 'ASEACAT', 'ASOIL', 'ACORS'])\n- weights = array([1, 1, .2 * 31. / 1000., .2 * 24. / 1000., .2 * 17.6 / 1000.])\n- if 'PM25_K' in keys:\n- if lay is not None:\n- var = self.dset['PM25_K'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_K'][:, :, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_K'\n- var['long_name'] = 'PM25_K'\n- var['var_desc'] = 'Variable PM25_K'\n-\n- return var\n-\n- def get_caf(self, lay=None):\n- keys = self.keys\n- allvars = array(['ACAI', 'ACAJ', 'ASEACAT', 'ASOIL', 'ACORS'])\n- weights = array([1, 1, .2 * 32. / 1000., .2 * 83.8 / 1000., .2 * 56.2 / 1000.])\n- if 'PM25_CA' in keys:\n- if lay is not None:\n- var = self.dset['PM25_CA'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_CA'][:, :, :, :].squeeze()\n- else:\n- print(' Computing PM25_NO3...')\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index.values]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_CA'\n- var['long_name'] = 'PM25_CA'\n- var['var_desc'] = 'Variable PM25_CA'\n- return var\n-\n- def get_so4f(self, lay=None):\n- keys = self.keys\n- allvars = array(['ASO4I', 'ASO4J', 'ASO4K'])\n- weights = array([1., 1., .2])\n- if 'PM25_SO4' in keys:\n- if lay is not None:\n- var = self.dset['PM25_SO4'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_SO4'][:, :, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index.values]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_SO4'\n- var['long_name'] = 'PM25_SO4'\n- var['var_desc'] = 'Variable PM25_SO4'\n- return var\n-\n- def get_nh4f(self, lay=None):\n- keys = self.keys\n- allvars = array(['ANH4I', 'ANH4J', 'ANH4K'])\n- weights = array([1., 1., .2])\n- var = None\n- if 'PM25_NH4' in keys:\n- if lay is not None:\n- var = self.dset['PM25_NH4'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_NH4'][:, :, :, :].squeeze()\n- else:\n- print(' Computing PM25_NH4...')\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_NH4'\n- var['long_name'] = 'PM25_NH4'\n- var['var_desc'] = 'Variable PM25_NH4'\n-\n- return var\n-\n- def get_no3f(self, lay=None):\n- keys = self.keys\n- allvars = array(['ANO3I', 'ANO3J', 'ANO3K'])\n- weights = array([1., 1., .2])\n- var = None\n- if 'PM25_NO3' in keys:\n- if lay is not None:\n- var = self.dset['PM25_NO3'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_NO3'][:, :, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_NO3'\n- var['long_name'] = 'PM25_NO3'\n- var['var_desc'] = 'Variable PM25_NO3'\n- return var\n-\n- def get_ec(self, lay=None):\n- keys = self.keys\n- allvars = array(['AECI', 'AECJ'])\n- weights = array([1., 1.])\n- var = None\n- if 'PM25_EC' in keys:\n- if lay is not None:\n- var = self.dset['PM25_EC'][:, lay, :, :].squeeze()\n- else:\n- var = self.dset['PM25_EC'][:, :, :, :].squeeze()\n- else:\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- neww = weights[index]\n- var = self.add_multiple_fields(newkeys, lay=lay, weights=neww)\n- var.name = 'PM25_EC'\n- var['long_name'] = 'PM25_EC'\n- var['var_desc'] = 'Variable PM25_EC'\n-\n- return var\n-\n- def get_var(self, param='O3', lay=None):\n- p = param.upper()\n- print(param)\n- if p == 'PM25':\n- var = self.get_pm25(lay=lay)\n- elif p == 'PM10':\n- var = self.get_pm10(lay=lay)\n- elif p == 'PM25_DUST':\n- var = self.get_dust_pm25(lay=lay)\n- elif p == 'PM10_DUST':\n- var = self.get_dust_total(lay=lay)\n- elif p == 'NOX':\n- var = self.get_nox(lay=lay)\n- elif p == 'NOY':\n- var = self.get_noy(lay=lay)\n- elif p == 'CLF':\n- var = self.get_clf(lay=lay)\n- elif p == 'CAF':\n- var = self.get_caf(lay=lay)\n- elif p == 'NAF':\n- var = self.get_naf(lay=lay)\n- elif p == 'KF':\n- var = self.get_kf(lay=lay)\n- elif (p == 'SO4F') | (p == 'PM2.5_SO4'):\n- var = self.get_so4f(lay=lay)\n- elif p == 'NH4F':\n- var = self.get_nh4f(lay=lay)\n- elif (p == 'NO3F') | (p == 'PM2.5_NO3'):\n- var = self.get_no3f(lay=lay)\n- elif (p == 'PM2.5_EC') | (p == 'ECF'):\n- var = self.get_ec(lay=lay)\n- elif p == 'OC':\n- var = self.get_oc(lay=lay)\n- elif p == 'VOC':\n- var = self.dset['VOC'][:, lay, :, :].squeeze()\n- elif p == 'RH':\n- var = self.get_metcro2d_rh(self, lay=lay)\n- else:\n- if self.check_z(param):\n- if lay is None:\n- var = self.dset[param][:, :, :, :].copy()\n- else:\n- var = self.dset[param][:, lay, :, :].copy().squeeze()\n- else:\n- var = self.dset[param][:, :, :].copy()\n- return var\n-\n- def get_metcro2d_rh(self, lay=None):\n- import atmos\n- data = {'T': self.dset['TEMP2'][:].compute().values, 'rv': self.dset['Q2'][:].compute().values,\n- 'p': self.dset['PRSFC'][:].compute().values}\n- if lay is None:\n- a = atmos.calculate('RH', **data)[:, :, :, :].squeeze()\n- else:\n- atmos.calculate('RH', **data)[:, lay, :, :].squeeze()\n- return a\n-\n- def set_gridcro2d(self, filename):\n- self.grid = xr.open_dataset(filename).rename({'COL': 'x', 'ROW': 'y'}).drop('TFLAG').squeeze()\n- lat = 'LAT'\n- lon = 'LON'\n- self.latitude = self.grid[lat][:][:, :].squeeze().compute()\n- self.longitude = self.grid[lon][:][:, :].squeeze().compute()\n- self.load_conus_basemap(res='l')\n-\n- def load_conus_basemap(self, res='l'):\n- from mpl_toolkits.basemap import Basemap\n- if isinstance(self.map, type(None)):\n- lat1 = self.grid.P_ALP\n- lat2 = self.grid.P_BET\n- lon1 = self.grid.P_GAM\n- lon0 = self.grid.XCENT\n- lat0 = self.grid.YCENT\n- m = Basemap(projection='lcc', resolution=res, lat_1=lat1, lat_2=lat2, lat_0=lat0, lon_0=lon0,\n- lon_1=lon1,\n- llcrnrlat=self.latitude[0, 0], urcrnrlat=self.latitude[-1, -1],\n- llcrnrlon=self.longitude[0, 0],\n- urcrnrlon=self.longitude[-1, -1], rsphere=6371200.,\n- area_thresh=50.)\n- self.map = m\n- else:\n- m = self.map\n- return self.map\n+def can_do(index):\n+ if index.max():\n+ return True\n+ else:\n+ return False\n+\n+\n+def open_files(fname, earth_radius=6370000, convert_to_ppb=True):\n+ \"\"\"Method to open CMAQ IOAPI netcdf files.\n+\n+ Parameters\n+ ----------\n+ fname : string or list\n+ fname is the path to the file or files. It will accept hot keys in\n+ strings as well.\n+ earth_radius : float\n+ The earth radius used for the map projection\n+ convert_to_ppb : boolean\n+ If true the units of the gas species will be converted to ppbV\n+\n+ Returns\n+ -------\n+ xarray.DataSet\n+\n+\n+ \"\"\"\n+\n+ # open the dataset using xarray\n+ dset = xr.open_mfdataset(fname)\n+\n+ # set log pressure as coordinate\n+ if 'PRES' in dset.variables:\n+ dset.coords['logp'] = xr.ufuncs.log(dset.PRES.chunk())\n+ # add lazy diagnostic variables\n+ dset = add_lazy_pm25(dset)\n+ dset = add_lazy_pm10(dset)\n+ dset = add_lazy_pm_course(dset)\n+ dset = add_lazy_clf(dset)\n+ dset = add_lazy_naf(dset)\n+ dset = add_lazy_caf(dset)\n+ dset = add_lazy_noy(dset)\n+ dset = add_lazy_nox(dset)\n+ dset = add_lazy_no3f(dset)\n+ dset = add_lazy_nh4f(dset)\n+ dset = add_lazy_so4f(dset)\n+ dset = add_lazy_rh(dset)\n+\n+ # get the grid information\n+ grid = grid_from_dataset(dset, earth_radius=earth_radius)\n+ area_def = get_ioapi_pyresample_area_def(dset, grid)\n+ # assign attributes for dataset and all DataArrays\n+ dset = dset.assign_attrs({'proj4_srs': grid})\n+ for i in dset.variables:\n+ dset[i] = dset[i].assign_attrs({'proj4_srs': grid})\n+ for j in dset[i].attrs:\n+ dset[i].attrs[j] = dset[i].attrs[j].strip()\n+ dset[i] = dset[i].assign_attrs({'area': area_def})\n+ dset = dset.assign_attrs(area=area_def)\n+\n+ # get the times\n+ dset = _get_times(dset)\n+\n+ # get the lat lon\n+ dset = _get_latlon(dset)\n+\n+ # get Predefined mapping tables for observations\n+ dset = _predefined_mapping_tables(dset)\n+\n+ # rename dimensions\n+ dset = dset.rename({'COL': 'x', 'ROW': 'y', 'LAY': 'z'})\n+\n+ # convert all gas species to ppbv\n+ if convert_to_ppb:\n+ for i in dset.variables:\n+ if 'units' in dset[i].attrs:\n+ if 'ppmV' in dset[i].attrs['units']:\n+ dset[i] *= 1000.\n+ dset[i].attrs['units'] = 'ppbV'\n+\n+ # convert 'micrograms to \\mu g'\n+ for i in dset.variables:\n+ if 'units' in dset[i].attrs:\n+ if 'micrograms' in dset[i].attrs['units']:\n+ dset[i].attrs['units'] = '$\\mu g m^{-3}$'\n+\n+ return dset\n+\n+\n+def _get_times(d):\n+ idims = len(d.TFLAG.dims)\n+ if idims == 2:\n+ tflag1 = Series(d['TFLAG'][:, 0]).astype(str).str.zfill(7)\n+ tflag2 = Series(d['TFLAG'][:, 1]).astype(str).str.zfill(6)\n+ else:\n+ tflag1 = Series(d['TFLAG'][:, 0, 0]).astype(str).str.zfill(7)\n+ tflag2 = Series(d['TFLAG'][:, 0, 1]).astype(str).str.zfill(6)\n+ date = to_datetime(\n+ [i + j for i, j in zip(tflag1, tflag2)], format='%Y%j%H%M%S')\n+ indexdates = Series(date).drop_duplicates(keep='last').index.values\n+ d = d.isel(TSTEP=indexdates)\n+ d['TSTEP'] = date[indexdates]\n+ return d.rename({'TSTEP': 'time'})\n+\n+\n+def _get_latlon(dset):\n+ \"\"\"gets the lat and lons from the pyreample.geometry.AreaDefinition\n+\n+ Parameters\n+ ----------\n+ dset : xarray.Dataset\n+ Description of parameter `dset`.\n+\n+ Returns\n+ -------\n+ xarray.Dataset\n+ Description of returned object.\n+\n+ \"\"\"\n+ lon, lat = dset.area.get_lonlats()\n+ dset['longitude'] = xr.DataArray(lon[::-1, :], dims=['ROW', 'COL'])\n+ dset['latitude'] = xr.DataArray(lat[::-1, :], dims=['ROW', 'COL'])\n+ dset = dset.assign_coords(longitude=dset.longitude, latitude=dset.latitude)\n+ return dset\n+\n+\n+def add_lazy_pm25(d):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ d : type\n+ Description of parameter `d`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(concatenate([aitken, accumulation, coarse]))\n+ weights = Series([\n+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n+ 1., 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2\n+ ])\n+ if 'PM25_TOT' in keys:\n+ d['PM25'] = d['PM25_TOT'].chunk()\n+\n+ else:\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ newweights = weights.loc[index]\n+ d['PM25'] = add_multiple_lazy(d, newkeys, weights=newweights)\n+ d['PM25'] = d['PM25'].assign_attrs({\n+ 'units': '$\\mu g m^{-3}$',\n+ 'name': 'PM2.5',\n+ 'long_name': 'PM2.5'\n+ })\n+ return d\n+\n+\n+def add_lazy_pm10(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(concatenate([aitken, accumulation, coarse]))\n+ if 'PM_TOT' in keys:\n+ d['PM10'] = d['PM_TOT'].chunk()\n+ else:\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['PM10'] = add_multiple_lazy(d, newkeys)\n+ d['PM10'] = d['PM10'].assign_attrs({\n+ 'units':\n+ '$\\mu g m^{-3}$',\n+ 'name':\n+ 'PM10',\n+ 'long_name':\n+ 'Particulate Matter < 10 microns'\n+ })\n+ return d\n+\n+\n+def add_lazy_pm_course(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(coarse)\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['PM_COURSE'] = add_multiple_lazy(d, newkeys)\n+ d['PM_COURSE'] = d['PM_COURSE'].assign_attrs({\n+ 'units':\n+ '$\\mu g m^{-3}$',\n+ 'name':\n+ 'PM_COURSE',\n+ 'long_name':\n+ 'Course Mode Particulate Matter'\n+ })\n+ return d\n+\n+\n+def add_lazy_clf(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ACLI', 'ACLJ', 'ACLK'])\n+ weights = Series([1, 1, .2])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['CLf'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['CLf'] = d['CLf'].assign_attrs({\n+ 'units':\n+ '$\\mu g m^{-3}$',\n+ 'name':\n+ 'CLf',\n+ 'long_name':\n+ 'Fine Mode particulate Cl'\n+ })\n+ return d\n+\n+\n+def add_lazy_caf(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ACAI', 'ACAJ', 'ASEACAT', 'ASOIL', 'ACORS'])\n+ weights = Series(\n+ [1, 1, .2 * 32. / 1000., .2 * 83.8 / 1000., .2 * 56.2 / 1000.])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['CAf'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['CAf'] = d['CAf'].assign_attrs({\n+ 'units':\n+ '$\\mu g m^{-3}$',\n+ 'name':\n+ 'CAf',\n+ 'long_name':\n+ 'Fine Mode particulate CA'\n+ })\n+ return d\n+\n+\n+def add_lazy_naf(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ANAI', 'ANAJ', 'ASEACAT', 'ASOIL', 'ACORS'])\n+ weights = Series(\n+ [1, 1, .2 * 837.3 / 1000., .2 * 62.6 / 1000., .2 * 2.3 / 1000.])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['NAf'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['NAf'] = d['NAf'].assign_attrs({\n+ 'units': '$\\mu g m^{-3}$',\n+ 'name': 'NAf',\n+ 'long_name': 'NAf'\n+ })\n+ return d\n+\n+\n+def add_lazy_so4f(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ASO4I', 'ASO4J', 'ASO4K'])\n+ weights = Series([1., 1., .2])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['SO4f'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['SO4f'] = d['SO4f'].assign_attrs({\n+ 'units': '$\\mu g m^{-3}$',\n+ 'name': 'SO4f',\n+ 'long_name': 'SO4f'\n+ })\n+ return d\n+\n+\n+def add_lazy_nh4f(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ANH4I', 'ANH4J', 'ANH4K'])\n+ weights = Series([1., 1., .2])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['NH4f'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['NH4f'] = d['NH4f'].assign_attrs({\n+ 'units': '$\\mu g m^{-3}$',\n+ 'name': 'NH4f',\n+ 'long_name': 'NH4f'\n+ })\n+ return d\n+\n+\n+def add_lazy_no3f(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['ANO3I', 'ANO3J', 'ANO3K'])\n+ weights = Series([1., 1., .2])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ neww = weights.loc[index]\n+ d['NO3f'] = add_multiple_lazy(d, newkeys, weights=neww)\n+ d['NO3f'] = d['NO3f'].assign_attrs({\n+ 'units': '$\\mu g m^{-3}$',\n+ 'name': 'NO3f',\n+ 'long_name': 'NO3f'\n+ })\n+ return d\n+\n+\n+def add_lazy_noy(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(noy_gas)\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['NOy'] = add_multiple_lazy(d, newkeys)\n+ d['NOy'] = d['NOy'].assign_attrs({'name': 'NOy', 'long_name': 'NOy'})\n+ return d\n+\n+\n+def add_lazy_rh(d):\n+ # keys = Series([i for i in d.variables])\n+ # allvars = Series(['TEMP', 'Q', 'PRES'])\n+ # index = allvars.isin(keys)\n+ # if can_do(index):\n+ # import atmos\n+ # data = {\n+ # 'T': dset['TEMP'][:].compute().values,\n+ # 'rv': dset['Q'][:].compute().values,\n+ # 'p': dset['PRES'][:].compute().values\n+ # }\n+ # d['NOx'] = add_multiple_lazy(d, newkeys)\n+ # d['NOx'] = d['NOx'].assign_attrs({'name': 'NOx', 'long_name': 'NOx'})\n+ return d\n+\n+\n+def add_lazy_nox(d):\n+ keys = Series([i for i in d.variables])\n+ allvars = Series(['NO', 'NOX'])\n+ index = allvars.isin(keys)\n+ if can_do(index):\n+ newkeys = allvars.loc[index]\n+ d['NOx'] = add_multiple_lazy(d, newkeys)\n+ d['NOx'] = d['NOx'].assign_attrs({'name': 'NOx', 'long_name': 'NOx'})\n+ return d\n+\n+\n+def add_multiple_lazy(dset, variables, weights=None):\n+ from numpy import ones\n+ if weights is None:\n+ weights = ones(len(variables))\n+ new = dset[variables[0]].copy() * weights[0]\n+ for i, j in zip(variables[1:], weights[1:]):\n+ new = new + dset[i].chunk() * j\n+ return new\n+\n+\n+def _predefined_mapping_tables(dset):\n+ \"\"\"Predefined mapping tables for different observational parings used when\n+ combining data.\n+\n+ Returns\n+ -------\n+ dictionary\n+ A dictionary of to map to.\n+\n+ \"\"\"\n+ to_improve = {}\n+ to_nadp = {}\n+ to_aqs = {\n+ 'OZONE': ['O3'],\n+ 'PM2.5': ['PM25'],\n+ 'CO': ['CO'],\n+ 'NOY': ['NOy'],\n+ 'NOX': ['NOx'],\n+ 'SO2': ['SO2'],\n+ 'NOX': ['NOx'],\n+ 'NO': ['NO'],\n+ 'NO2': ['NO2'],\n+ 'SO4f': ['SO4f'],\n+ 'PM10': ['PM10'],\n+ 'NO3f': ['NO3f'],\n+ 'ECf': ['ECf'],\n+ 'OCf': ['OCf'],\n+ 'ETHANE': ['ETHA'],\n+ 'BENZENE': ['BENZENE'],\n+ 'TOLUENE': ['TOL'],\n+ 'ISOPRENE': ['ISOP'],\n+ 'O-XYLENE': ['XYL'],\n+ 'WS': ['WSPD10'],\n+ 'TEMP': ['TEMP2'],\n+ 'WD': ['WDIR10'],\n+ 'NAf': ['NAf'],\n+ 'MGf': ['AMGJ'],\n+ 'TIf': ['ATIJ'],\n+ 'SIf': ['ASIJ'],\n+ 'Kf': ['Kf'],\n+ 'CAf': ['CAf'],\n+ 'NH4f': ['NH4f'],\n+ 'FEf': ['AFEJ'],\n+ 'ALf': ['AALJ'],\n+ 'MNf': ['AMNJ']\n+ }\n+ to_airnow = {\n+ 'OZONE': ['O3'],\n+ 'PM2.5': ['PM25'],\n+ 'CO': ['CO'],\n+ 'NOY': ['NOy'],\n+ 'NOX': ['NOx'],\n+ 'SO2': ['SO2'],\n+ 'NOX': ['NOx'],\n+ 'NO': ['NO'],\n+ 'NO2': ['NO2'],\n+ 'SO4f': ['SO4f'],\n+ 'PM10': ['PM10'],\n+ 'NO3f': ['NO3f'],\n+ 'ECf': ['ECf'],\n+ 'OCf': ['OCf'],\n+ 'ETHANE': ['ETHA'],\n+ 'BENZENE': ['BENZENE'],\n+ 'TOLUENE': ['TOL'],\n+ 'ISOPRENE': ['ISOP'],\n+ 'O-XYLENE': ['XYL'],\n+ 'WS': ['WSPD10'],\n+ 'TEMP': ['TEMP2'],\n+ 'WD': ['WDIR10'],\n+ 'NAf': ['NAf'],\n+ 'MGf': ['AMGJ'],\n+ 'TIf': ['ATIJ'],\n+ 'SIf': ['ASIJ'],\n+ 'Kf': ['Kf'],\n+ 'CAf': ['CAf'],\n+ 'NH4f': ['NH4f'],\n+ 'FEf': ['AFEJ'],\n+ 'ALf': ['AALJ'],\n+ 'MNf': ['AMNJ']\n+ }\n+ to_crn = {\n+ 'SUR_TEMP': ['TEMPG'],\n+ 'T_HR_AVG': ['TEMP2'],\n+ 'SOLARAD': ['RGRND'],\n+ 'SOIL_MOISTURE_5': ['SOIM1'],\n+ 'SOIL_MOISTURE_10': ['SOIM2']\n+ }\n+ to_aeronet = {}\n+ to_cems = {}\n+ mapping_tables = {\n+ 'improve': to_improve,\n+ 'aqs': to_aqs,\n+ 'airnow': to_airnow,\n+ 'crn': to_crn,\n+ 'cems': to_cems,\n+ 'nadp': to_nadp,\n+ 'aeronet': to_aeronet\n+ }\n+ dset = dset.assign_attrs({'mapping_tables': mapping_tables})\n+ return dset\n+\n+\n+# Arrays for different gasses and pm groupings\n+accumulation = array([\n+ 'AALJ', 'AALK1J', 'AALK2J', 'ABNZ1J', 'ABNZ2J', 'ABNZ3J', 'ACAJ', 'ACLJ',\n+ 'AECJ', 'AFEJ', 'AISO1J', 'AISO2J', 'AISO3J', 'AKJ', 'AMGJ', 'AMNJ',\n+ 'ANAJ', 'ANH4J', 'ANO3J', 'AOLGAJ', 'AOLGBJ', 'AORGCJ', 'AOTHRJ', 'APAH1J',\n+ 'APAH2J', 'APAH3J', 'APNCOMJ', 'APOCJ', 'ASIJ', 'ASO4J', 'ASQTJ', 'ATIJ',\n+ 'ATOL1J', 'ATOL2J', 'ATOL3J', 'ATRP1J', 'ATRP2J', 'AXYL1J', 'AXYL2J',\n+ 'AXYL3J', 'AORGAJ', 'AORGPAJ', 'AORGBJ'\n+])\n+aitken = array([\n+ 'ACLI', 'AECI', 'ANAI', 'ANH4I', 'ANO3I', 'AOTHRI', 'APNCOMI', 'APOCI',\n+ 'ASO4I', 'AORGAI', 'AORGPAI', 'AORGBI'\n+])\n+coarse = array(\n+ ['ACLK', 'ACORS', 'ANH4K', 'ANO3K', 'ASEACAT', 'ASO4K', 'ASOIL'])\n+noy_gas = array([\n+ 'NO', 'NO2', 'NO3', 'N2O5', 'HONO', 'HNO3', 'PAN', 'PANX', 'PNA', 'NTR',\n+ 'CRON', 'CRN2', 'CRNO', 'CRPX', 'OPAN'\n+])\n+pec = array(['AECI', 'AECJ'])\n+pso4 = array(['ASO4I', 'ASO4J'])\n+pno3 = array(['ANO3I', 'ANO3J'])\n+pnh4 = array(['ANH4I', 'ANH4J'])\n+pcl = array(['ACLI', 'ACLJ'])\n+poc = array([\n+ 'AOTHRI', 'APNCOMI', 'APOCI', 'AORGAI', 'AORGPAI', 'AORGBI', 'ATOL1J',\n+ 'ATOL2J', 'ATOL3J', 'ATRP1J', 'ATRP2J', 'AXYL1J', 'AXYL2J', 'AXYL3J',\n+ 'AORGAJ', 'AORGPAJ', 'AORGBJ', 'AOLGAJ', 'AOLGBJ', 'AORGCJ', 'AOTHRJ',\n+ 'APAH1J', 'APAH2J', 'APAH3J', 'APNCOMJ', 'APOCJ', 'ASQTJ', 'AISO1J',\n+ 'AISO2J', 'AISO3J', 'AALK1J', 'AALK2J', 'ABNZ1J', 'ABNZ2J', 'ABNZ3J',\n+ 'AORGAI', 'AORGAJ', 'AORGPAI', 'AORGPAJ', 'AORGBI', 'AORGBJ'\n+])\n+minerals = array(\n+ ['AALJ', 'ACAJ', 'AFEJ', 'AKJ', 'AMGJ', 'AMNJ', 'ANAJ', 'ATIJ', 'ASIJ'])\ndiff --git a/monet/models/combinetool.py b/monet/models/combinetool.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/models/combinetool.py\n@@ -0,0 +1,224 @@\n+from __future__ import absolute_import, print_function\n+\n+from pandas import Series\n+\n+# from ..util import interp_util as interpo\n+# from ..obs import epa_util\n+\n+\n+def combine_da_to_df(da, df, col=None, radius_of_influence=12e3, merge=True):\n+ \"\"\"This function will combine an xarray data array with spatial information\n+ point observations in `df`.\n+\n+ Parameters\n+ ----------\n+ da : xr.DataArray\n+ Description of parameter `da`.\n+ df : pd.DataFrame\n+ Description of parameter `df`.\n+ lay : iterable, default = [0]\n+ Description of parameter `lay`.\n+ radius : integer or float, default = 12e3\n+ Description of parameter `radius`.\n+\n+ Returns\n+ -------\n+ pandas.DataFrame\n+ \"\"\"\n+ from ..util.interp_util import lonlat_to_swathdefinition\n+ from ..util.resample import resample_dataset\n+ try:\n+ if col is None:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('Must enter column name')\n+ dfn = df.dropna(subset=[col])\n+ dfnn = dfn.drop_duplicates(subset=['latitude', 'longitude'])\n+ # unit = dfnn[col + '_unit'].unique()[0]\n+ target_grid = lonlat_to_swathdefinition(\n+ longitude=dfnn.longitude.values, latitude=dfnn.latitude.values)\n+ da_interped = resample_dataset(\n+ da.compute(), target_grid, radius_of_influence=radius_of_influence)\n+ # add model if da.name is the same as column\n+ df_interped = da_interped.to_dataframe().reset_index()\n+ cols = Series(df_interped.columns)\n+ drop_cols = cols.loc[cols.isin(['x', 'y', 'z'])]\n+ df_interped.drop(drop_cols, axis=1, inplace=True)\n+ if da.name in df.columns:\n+ df_interped.rename(columns={da.name: da.name + '_new'}, inplace=True)\n+ print(df_interped.keys())\n+ final_df = df.merge(\n+ df_interped, on=['latitude', 'longitude', 'time'], how='left')\n+ return final_df\n+\n+\n+def combine_da_to_height_profile(da, dset, radius_of_influence=12e3):\n+ \"\"\"This function will combine an xarray.DataArray to a 2d dataset with\n+ dimensions (time,z)\n+\n+ Parameters\n+ ----------\n+ da : xarray.DataArray\n+ Description of parameter `da`.\n+ dset : xarray.Dataset\n+ Description of parameter `dset`.\n+\n+ Returns\n+ -------\n+ xarray.Dataset\n+ returns the xarray.Dataset with the `da` added as an additional\n+ variable.\n+\n+ \"\"\"\n+ # from ..util.interp_util import nearest_point_swathdefinition\n+ lon, lat = dset.longitude, dset.latitude\n+ # target_grid = nearest_point_swathdefinition(longitude=lon, latitude=lat)\n+ da_interped = da.monet.nearest_latlon(\n+ lon=lon, lat=lat, radius_of_influence=radius_of_influence)\n+\n+ # FIXME: interp to height here\n+\n+ dset[da.name] = da_interped\n+\n+ return dset\n+\n+\n+#\n+# def combine_to_df(model=None,\n+# obs=None,\n+# mapping_table=None,\n+# lay=None,\n+# radius=None):\n+# # first get mapping table for obs to model\n+# if radius is None:\n+# try:\n+# radius = model.dset.XCELL\n+# except AttributeError:\n+# radius = 40e3\n+# if mapping_table is None:\n+# mapping_table = get_mapping_table(model, obs)\n+# # get the data inside of the obs dataset (check for tolnet)\n+# if obs.objtype is not 'TOLNET' and obs.objtype is not 'AERONET':\n+# obslist = Series(obs.df.variable.unique())\n+# # find all variables to map\n+# comparelist = obslist.loc[obslist.isin(mapping_table.keys())]\n+# dfs = []\n+# for i in comparelist:\n+# print('Pairing: ' + i)\n+# obsdf = obs.df.groupby('variable').get_group(\n+# i) # get observations locations\n+# obsunit = obsdf.units.unique()[0] # get observation unit\n+# # get observation lat and lons\n+# dfn = obsdf.drop_duplicates(subset=['latitude', 'longitude'])\n+# factor = check_units(model, obsunit, variable=mapping_table[i][0])\n+# try:\n+# if lay is None and Series([model.objtype]).isin(\n+# ['CAMX', 'CMAQ']).max():\n+# modelvar = get_model_fields(\n+# model, mapping_table[i], lay=0).compute() * factor\n+# else:\n+# modelvar = get_model_fields(\n+# model, mapping_table[i], lay=lay).compute() * factor\n+# mvar_interped = interpo.interp_latlon(\n+# modelvar,\n+# dfn.latitude.values,\n+# dfn.longitude.values,\n+# radius=radius)\n+# combined_df = merge_obs_and_model(\n+# mvar_interped,\n+# obsdf,\n+# dfn,\n+# model_time=modelvar.time.to_index(),\n+# daily=obs.daily,\n+# obstype=obs.objtype)\n+# dfs.append(combined_df)\n+# except KeyError:\n+# print(i + ' not in dataset and will not be paired')\n+# df = concat(dfs)\n+#\n+# return df\n+#\n+#\n+# def merge_obs_and_model(model,\n+# obs,\n+# dfn,\n+# model_time=None,\n+# daily=False,\n+# obstype=None):\n+# import pandas as pd\n+# e = pd.DataFrame(model, index=dfn.siteid, columns=model_time)\n+# w = e.stack(dropna=False).reset_index().rename(columns={\n+# 'level_1': 'time',\n+# 0: 'model'\n+# })\n+# if daily and pd.Series(['AirNow', 'AQS', 'IMPROVE']).isin([obstype]).max():\n+# w = w.merge(\n+# dfn[['siteid', 'variable', 'gmt_offset', 'pollutant_standard']],\n+# on='siteid',\n+# how='left')\n+# w = epa_util.regulatory_resample(w)\n+# w = w.merge(\n+# obs.drop(['time', 'gmt_offset', 'variable'], axis=1),\n+# on=['siteid', 'time_local', 'pollutant_standard'],\n+# how='left')\n+# elif daily:\n+# w.index = w.time\n+# w = w.resample('D').mean().reset_index().rename(\n+# columns={'level_1': 'time'})\n+# w = w.merge(obs, on=['siteid', 'time'], how='left')\n+# else:\n+# w = w.merge(\n+# obs, on=['siteid', 'time'],\n+# how='left') # assume outputs are hourly\n+# return w\n+#\n+#\n+# def get_model_fields(model, findkeys, lay=None, weights=None):\n+# from numpy import ones\n+# keys = model.dset.keys()\n+# print(findkeys)\n+# newkeys = Series(findkeys).loc[Series(findkeys).isin(keys)]\n+# if len(newkeys) > 1:\n+# mvar = model.select_layer(model.dset[newkeys[0]], lay=lay)\n+# for i in newkeys:\n+# mvar = mvar + model.select_layer(model.dset[newkeys[0]], lay=lay)\n+# else:\n+# mvar = model.get_var(findkeys[0], lay=lay)\n+# return mvar\n+#\n+#\n+# def check_units(model, obsunit, variable=None):\n+# \"\"\"Short summary.\n+#\n+# Parameters\n+# ----------\n+# df : type\n+# Description of parameter `df`.\n+# param : type\n+# Description of parameter `param` (the default is 'O3').\n+# aqs_param : type\n+# Description of parameter `aqs_param` (the default is 'OZONE').\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# if obsunit == 'UG/M3':\n+# fac = 1.\n+# elif obsunit == 'PPB':\n+# fac = 1000.\n+# elif obsunit == 'ppbC':\n+# fac = 1000.\n+# if variable == 'ISOPRENE':\n+# fac *= 5.\n+# elif variable == 'BENZENE':\n+# fac *= 6.\n+# elif variable == 'TOLUENE':\n+# fac *= 7.\n+# elif variable == 'O-XYLENE':\n+# fac *= 8.\n+# else:\n+# fac = 1.\n+# return fac\ndiff --git a/monet/models/hysplit.py b/monet/models/hysplit.py\n--- a/monet/models/hysplit.py\n+++ b/monet/models/hysplit.py\n@@ -1,165 +1,529 @@\n-from __future__ import division, print_function\n-\n-from builtins import object, zip\n-\n+\"\"\" HYPSLIT MODEL READER \"\"\"\n+from ..grids import _hysplit_latlon_grid_from_dataset\n+from ..grids import get_hysplit_latlon_pyreample_area_def\n import pandas as pd\n import xarray as xr\n-from dask.diagnostics import ProgressBar\n-from numpy import array\n-from past.utils import old_div\n \n-# This file is to deal with CAMx code - try to make it general for CAMx 4.7.1 --> 5.1\n \n+def open_files(fname):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ fname : type\n+ Description of parameter `fname`.\n+ earth_radius : type\n+ Description of parameter `earth_radius`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ CHANGES for PYTHON 3\n+ For python 3 the numpy char4 are read in as a numpy.bytes_ class and need to\n+ be converted to a python\n+ string by using decode('UTF-8').\n+\n+\n+ \"\"\"\n+\n+ # open the dataset using xarray\n+ binfile = ModelBin(fname, verbose=False, readwrite='r')\n+ dset = binfile.dset\n+\n+ # get the grid information\n+ p4 = _hysplit_latlon_grid_from_dataset(dset)\n+ swath = get_hysplit_latlon_pyreample_area_def(dset, p4)\n+\n+ # now assign this to the dataset and each dataarray\n+ dset = dset.assign_attrs({'proj4_srs': p4})\n+ for i in dset.variables:\n+ dset[i] = dset[i].assign_attrs({'proj4_srs': p4})\n+ for j in dset[i].attrs:\n+ dset[i].attrs[j] = dset[i].attrs[j].strip()\n+ dset[i] = dset[i].assign_attrs({'area': swath})\n+ dset = dset.assign_attrs(area=swath)\n+\n+ # return the dataset\n+ return dset\n+\n+\n+# class HYSPLIT(BaseModel):\n+# def __init__(self):\n+# BaseModel.__init__(self)\n+# self.dset = None\n+#\n+# # use open_files method from the BaseModel class.\n+#\n+# def add_files(self, cdump, verbose=True):\n+# # TO DO dset needs to be made into a regular array.\n+# binfile = ModelBin(cdump, verbose=False, readwrite='r')\n+# dset = binfile.dset\n+# if self.dset is None:\n+# self.dset = dset\n+# else:\n+# #self.dset = xr.merge([self.dset, dset])\n+# self.dset.combine_first(dset)\n+# print(self.dset)\n+#\n+# @staticmethod\n+# def select_layer(variable, layer=None):\n+# if lay is not None:\n+# try:\n+# var = variable.sel(levels=layer)\n+# except ValueError:\n+# print(\n+# 'Dimension \\'levels\\' not in Dataset. Returning Dataset\n+# anyway'\n+# )\n+# var = variable\n+# else:\n+# var = variable\n+# return var\n+#\n+# def get_var(self, param, layer=None):\n+# return self.select_layer(self.dset[param], layer=layer)\n+\n+\n+class ModelBin(object):\n+ \"\"\"represents a binary cdump (concentration) output file from HYSPLIT\n+ methods:\n+ readfile - opens and reads contents of cdump file into an xarray\n+ self.dset\n+\n+ \"\"\"\n+\n+ def __init__(self,\n+ filename,\n+ drange=None,\n+ century=None,\n+ verbose=False,\n+ readwrite='r',\n+ fillra=False):\n+ \"\"\"\n+ drange should be a list of two datetime objects.\n+ The read method will store data from the cdump file for which the\n+ sample start is greater thand drange[0] and less than drange[1]\n+ for which the sample stop is less than drange[1].\n+\n+ \"\"\"\n+ self.drange = drange\n+ self.filename = filename\n+ self.century = century\n+ self.verbose = verbose\n+ # list of tuples (date1, date2) of averaging periods with zero\n+ # concentrations\n+ self.zeroconcdates = []\n+ # list of tuples of averaging periods with nonzero concentrtations]\n+ self.nonzeroconcdates = []\n+ if readwrite == 'r':\n+ self.dataflag = self.readfile(\n+ filename, drange, verbose, century, fillra=fillra)\n+\n+ @staticmethod\n+ def define_struct():\n+ \"\"\"Each record in the fortran binary begins and ends with 4 bytes which\n+ specify the length of the record. These bytes are called pad below.\n+ They are not used here, but are thrown out. The following block defines\n+ a numpy dtype object for each record in the binary file. \"\"\"\n+ from numpy import dtype\n+ real4 = '>f'\n+ int4 = '>i'\n+ int2 = '>i2'\n+ char4 = '>a4'\n+\n+ rec1 = dtype([\n+ ('pad1', int4),\n+ ('model_id', char4), # meteorological model id\n+ ('met_year', int4), # meteorological model starting time\n+ ('met_month', int4),\n+ ('met_day', int4),\n+ ('met_hr', int4),\n+ ('met_fhr', int4), # forecast hour\n+ ('start_loc', int4), # number of starting locations\n+ ('conc_pack', int4), # concentration packing flag (0=no, 1=yes)\n+ ('pad2', int4),\n+ ])\n+\n+ # start_loc in rec1 tell how many rec there are.\n+ rec2 = dtype([\n+ ('pad1', int4),\n+ ('r_year', int4), # release starting time\n+ ('r_month', int4),\n+ ('r_day', int4),\n+ ('r_hr', int4),\n+ ('s_lat', real4), # Release location\n+ ('s_lon', real4),\n+ ('s_ht', real4),\n+ ('r_min', int4), # release startime time (minutes)\n+ ('pad2', int4),\n+ ])\n+\n+ rec3 = dtype([\n+ ('pad1', int4),\n+ ('nlat', int4),\n+ ('nlon', int4),\n+ ('dlat', real4),\n+ ('dlon', real4),\n+ ('llcrnr_lat', real4),\n+ ('llcrnr_lon', real4),\n+ ('pad2', int4),\n+ ])\n+\n+ rec4a = dtype([\n+ ('pad1', int4),\n+ ('nlev', int4), # number of vertical levels in concentration grid\n+ ])\n+\n+ rec4b = dtype([\n+ ('levht', int4), # height of each level (meters above ground)\n+ ])\n+\n+ rec5a = dtype([\n+ ('pad1', int4),\n+ ('pad2', int4),\n+ ('pollnum', int4), # number of different pollutants\n+ ])\n+\n+ rec5b = dtype([\n+ ('pname', char4), # identification string for each pollutant\n+ ])\n+\n+ rec5c = dtype([\n+ ('pad2', int4),\n+ ])\n+\n+ rec6 = dtype([\n+ ('pad1', int4),\n+ ('oyear', int4), # sample start time.\n+ ('omonth', int4),\n+ ('oday', int4),\n+ ('ohr', int4),\n+ ('omin', int4),\n+ ('oforecast', int4),\n+ ('pad3', int4),\n+ ])\n+\n+ # rec7 has same form as rec6. #sample stop time.\n+\n+ # record 8 is pollutant type identification string, output level.\n \n-ProgressBar().register()\n+ rec8a = dtype([\n+ ('pad1', int4),\n+ ('poll', char4), # pollutant identification string\n+ ('lev', int4),\n+ ('ne', int4), # number of elements\n+ ])\n \n+ rec8b = dtype([\n+ ('indx', int2), # longitude index\n+ ('jndx', int2), # latitude index\n+ ('conc', real4),\n+ ])\n \n-class HYSPLIT(object):\n- def __init__(self):\n- self.objtype = 'HYSPLIT'\n+ rec8c = dtype([\n+ ('pad2', int4),\n+ ])\n+ recs = (rec1, rec2, rec3, rec4a, rec4b, rec5a, rec5b, rec5c, rec6,\n+ rec8a, rec8b, rec8c)\n+ return recs\n+\n+ def readfile(self, filename, drange, verbose, century, fillra=True):\n+ \"\"\"Data from the file is stored in an xarray, self.dset\n+ returns False if all concentrations are zero else returns True.\n+ INPUTS\n+ filename - name of cdump file to open\n+ drange - [date1, date2] - range of dates to load data for. if []\n+ then loads all data.\n+ date1 and date2 should be datetime ojbects.\n+ verbose - turns on print statements\n+ century - if None will try to guess the century by looking\n+ at the last two digits of the year.\n+ For python 3 the numpy char4 are read in as a numpy.bytes_\n+ class and need to be converted to a python\n+ string by using decode('UTF-8').\n+ fillra : if True will return complete concentration grid array\n+ with zero cocenctrations filled in\n+\n+ \"\"\"\n+ from numpy import fromfile, arange\n+ import datetime\n+ # 8/16/2016 moved species=[] to before while loop. Added print\n+ # statements when verbose.\n self.dset = None\n- self.fname = None\n- self.dates = None\n- self.keys = None\n- self.indexdates = None\n- self.latitude = None\n- self.longitude = None\n- self.map = None\n-\n- def get_dates(self):\n- print('Reading CAMx dates...')\n- print(self.dset)\n- tflag1 = array(self.dset['TFLAG'][:, 0], dtype='|S7')\n- tflag2 = array(old_div(self.dset['TFLAG'][:, 1], 10000), dtype='|S6')\n- date = pd.to_datetime([i + j.zfill(2) for i, j in zip(tflag1, tflag2)], format='%Y%j%H')\n- indexdates = pd.Series(date).drop_duplicates(keep='last').index.values\n- self.dset = self.dset.isel(time=indexdates)\n- self.dset['time'] = date[indexdates]\n-\n- def open_camx(self, file):\n- from glob import glob\n- from numpy import sort\n- dropset = ['layer', 'longitude_bounds', 'latitude_bounds',\n- 'x', 'y', 'level', 'lambert_conformal_conic']\n- nameset = {'COL': 'x', 'ROW': 'y', 'TSTEP': 'time', 'LAY': 'z'}\n- if type(file) == str:\n- fname = sort(array(glob(file)))\n- else:\n- fname = sort(array(file))\n- if fname.shape[0] >= 1:\n- if self.dset is None:\n- self.dset = xr.open_mfdataset(\n- fname.tolist(), concat_dim='TSTEP', engine='pnc').drop(dropset).rename(nameset).squeeze()\n- self.load_conus_basemap(res='l')\n- self.get_dates()\n- else:\n- dset = xr.open_mfdataset(fname.tolist(), concat_dim='TSTEP',\n- engine='pnc').drop(dropset).rename(nameset).squeeze()\n- self.dset = xr.merge([self.dset, dset])\n- else:\n- print('Files not found')\n- self.keys = list(self.dset.keys())\n-\n- def check_z(self, varname):\n- if pd.Series(self.dset[varname].dims).isin('z').max():\n- return True\n- else:\n- return False\n+ atthash = {\n+ } # dictionary which will be turned into the dset attributes.\n+ ahash = {}\n+ fp = open(filename, 'rb')\n \n- def get_nox(self, lay=None):\n- if self.check_z('NO'):\n- if lay is not None:\n- var = self.dset['NO'][:, 0, :, :].squeeze().copy()\n- var += self.dset['NO2'][:, 0, :, :].squeeze().copy()\n- else:\n- var = self.dset['NO'][:, :, :, :].copy()\n- var += self.dset['NO2'][:, :, :, :].copy()\n- else:\n- var = self.dset['NO'][:, :, :].copy()\n- var += self.dset['NO2'][:, :, :].copy()\n- return var\n-\n- def get_pm25(self, lay=None):\n- keys = list(self.dset.keys())\n- allvars = self.fine\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- if self.check_z(newkeys[0]):\n- if lay is not None:\n- var = self.dset[newkeys[0]][:, 0, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, 0, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :].copy()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :].squeeze()\n- return var\n-\n- def get_pm10(self, lay=None):\n- keys = list(self.dset.keys())\n- allvars = self.coarse\n- index = pd.Series(allvars).isin(keys)\n- newkeys = allvars[index]\n- if self.check_z(newkeys[0]):\n- if lay is not None:\n- var = self.dset[newkeys[0]][:, 0, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, 0, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :, :].squeeze()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :, :].squeeze()\n- else:\n- var = self.dset[newkeys[0]][:, :, :].copy()\n- for i in newkeys[1:]:\n- var += self.dset[i][:, :, :].squeeze()\n- return var\n-\n- def get_var(self, param='O3', lay=None):\n- p = param.upper()\n- print(param)\n- if p == 'PM25':\n- var = self.get_pm25(lay=lay)\n- elif p == 'PM10':\n- var = self.get_pm10(lay=lay)\n- elif p == 'NOX':\n- var = self.get_nox(lay=lay)\n- elif p == 'OC':\n- var = self.get_oc(lay=lay)\n- elif p == 'VOC':\n- if lay is not None:\n- var = self.dset['VOC'][:, 0, :, :].copy().squeeze()\n- else:\n- var = self.dset['VOC'][:, :, :, :].copy().squeeze()\n- else:\n- if self.check_z(param):\n- if lay is None:\n- var = self.dset[param][:, :, :, :].copy()\n+ # each record in the fortran binary begins and ends with 4 bytes which\n+ # specify the length of the record.\n+ # These bytes are called pad1 and pad2 below. They are not used here,\n+ # but are thrown out.\n+ # The following block defines a numpy dtype object for each record in\n+ # the binary file.\n+ recs = self.define_struct()\n+ rec1, rec2, rec3, rec4a = recs[0], recs[1], recs[2], recs[3]\n+ rec4b, rec5a, rec5b, rec5c = recs[4], recs[5], recs[6], recs[7]\n+ rec6, rec8a, rec8b, rec8c = recs[8], recs[9], recs[10], recs[11]\n+\n+ # rec7 = rec6\n+ # start_loc in rec1 tell how many rec there are.\n+ tempzeroconcdates = []\n+ # Reads header data. This consists of records 1-5.\n+ hdata1 = fromfile(fp, dtype=rec1, count=1)\n+ nstartloc = hdata1['start_loc'][0]\n+ # in python 3 np.fromfile reads the record into a list even if it is\n+ # just one number.\n+ # so if the length of this record is greater than one something is\n+ # wrong.\n+ if len(hdata1['start_loc']) != 1:\n+ print(\n+ 'WARNING in ModelBin _readfile - number of starting locations '\n+ 'incorrect')\n+ print(hdata1['start_loc'])\n+ hdata2 = fromfile(fp, dtype=rec2, count=nstartloc)\n+ hdata3 = fromfile(fp, dtype=rec3, count=1)\n+ atthash['Number Start Locations'] = nstartloc\n+\n+ # Description of concentration grid\n+ ahash['Number Lat Points'] = hdata3['nlat'][0]\n+ ahash['Number Lon Points'] = hdata3['nlon'][0]\n+ ahash['Latitude Spacing'] = hdata3['dlat'][0]\n+ ahash['Longitude Spacing'] = hdata3['dlon'][0]\n+ ahash['llcrnr longitude'] = hdata3['llcrnr_lon'][0]\n+ ahash['llrcrnr latitude'] = hdata3['llcrnr_lat'][0]\n+\n+ self.llcrnr_lon = hdata3['llcrnr_lon'][0]\n+ self.llcrnr_lat = hdata3['llcrnr_lat'][0]\n+ self.nlat = hdata3['nlat'][0]\n+ self.nlon = hdata3['nlon'][0]\n+ self.dlat = hdata3['dlat'][0]\n+ self.dlon = hdata3['dlon'][0]\n+\n+ atthash['Meteorological Model ID'] = hdata1['model_id'][0].decode(\n+ 'UTF-8')\n+ self.sourcedate = []\n+ self.slat = []\n+ self.slon = []\n+ self.sht = []\n+ atthash['Starting Locations'] = []\n+ atthash['Source Date'] = []\n+ # Loop through starting locations\n+\n+ for n in range(0, nstartloc):\n+ # create list of starting latitudes, longitudes and heights.\n+ self.slat.append(hdata2['s_lat'][n])\n+ self.slon.append(hdata2['s_lon'][n])\n+ self.sht.append(hdata2['s_ht'][n])\n+ atthash['Starting Locations'].append((hdata2['s_lat'][n],\n+ hdata2['s_lon'][n]))\n+\n+ # try to guess century if century not given\n+ if century is None:\n+ if hdata2['r_year'][0] < 50:\n+ century = 2000\n else:\n- var = self.dset[param][:, lay, :, :].copy().squeeze()\n+ century = 1900\n+ print(\n+ 'WARNING: Guessing Century for HYSPLIT concentration file',\n+ century)\n+ # add sourcedate which is datetime.datetime object\n+ sourcedate = (datetime.datetime(\n+ century + hdata2['r_year'][n], hdata2['r_month'][n],\n+ hdata2['r_day'][n], hdata2['r_hr'][n], hdata2['r_min'][n]))\n+ self.sourcedate.append(sourcedate)\n+ atthash['Source Date'].append(sourcedate)\n+\n+ # read record 4 which gives information about vertical levels.\n+ hdata4a = fromfile(fp, dtype=rec4a, count=1) # gets nmber of levels\n+ hdata4b = fromfile(\n+ fp, dtype=rec4b, count=hdata4a['nlev'][\n+ 0]) # reads levels, count is number of levels.\n+ self.levels = hdata4b['levht']\n+ atthash['Number of Levels'] = hdata4a['nlev'][0]\n+ atthash['Level top heights (m)'] = hdata4b['levht']\n+\n+ # read record 5 which gives information about pollutants / species.\n+ hdata5a = fromfile(fp, dtype=rec5a, count=1)\n+ fromfile(fp, dtype=rec5b, count=hdata5a['pollnum'][0])\n+ fromfile(fp, dtype=rec5c, count=1)\n+ # hdata5b = fromfile(fp, dtype=rec5b, count=hdata5a['pollnum'][0])\n+ # hdata5c = fromfile(fp, dtype=rec5c, count=1)\n+ atthash['Number of Species'] = hdata5a['pollnum'][0]\n+\n+ # Loop to reads records 6-8. Number of loops is equal to number of\n+ # output times.\n+ # Only save data for output times within drange. if drange=[] then\n+ # save all.\n+ # Loop to go through each sampling time\n+ ii = 0 # check to make sure don't go above max number of iterations\n+ iii = 0 # checks to see if some nonzero data was saved in xarray\n+ # Safety valve - will not allow more than 1000 loops to be executed.\n+ imax = 1e3\n+ testf = True\n+ while testf:\n+ hdata6 = fromfile(fp, dtype=rec6, count=1)\n+ hdata7 = fromfile(fp, dtype=rec6, count=1)\n+ if len(hdata6\n+ ) == 0: # if no data read then break out of the while loop.\n+ break\n+ if verbose:\n+ print('REC 6 & 7 ***************')\n+ print(hdata6)\n+ print(hdata7)\n+ # pdate1 is the sample start\n+ # pdate2 is the sample stop\n+ pdate1 = datetime.datetime(century + hdata6['oyear'],\n+ hdata6['omonth'], hdata6['oday'],\n+ hdata6['ohr'])\n+ pdate2 = datetime.datetime(century + hdata7['oyear'],\n+ hdata7['omonth'], hdata7['oday'],\n+ hdata7['ohr'])\n+ atthash['Sampling Time'] = pdate2 - pdate1\n+ savedata = True\n+\n+ # if pdate1 is within drange then save the data.\n+ # AND if pdate2 is within drange then save the data.\n+ # if drange[0] > pdate1 then stop looping to look for more data\n+ # this block sets savedata to true if data within specified time\n+ # range or time range not specified\n+ if drange is None:\n+ savedata = True\n+ elif pdate1 >= drange[0] and pdate1 <= drange[1] and pdate2 <= drange[1]:\n+ savedata = True\n+ elif pdate1 > drange[1] or pdate2 > drange[1]:\n+ testf = False\n+ savedata = False\n else:\n- var = self.dset[param]\n- return var\n-\n- def load_conus_basemap(self, res='l'):\n- from mpl_toolkits.basemap import Basemap\n- if self.map is None:\n- lat1 = self.dset.P_ALP\n- lat2 = self.dset.P_BET\n- lon1 = self.dset.P_GAM\n- lon0 = self.dset.XCENT\n- lat0 = self.dset.YCENT\n- m = Basemap(projection='lcc', resolution=res, lat_1=lat1, lat_2=lat2, lat_0=lat0, lon_0=lon0,\n- lon_1=lon1,\n- llcrnrlat=self.dset.latitude[0, 0], urcrnrlat=self.dset.latitude[-1, -1],\n- llcrnrlon=self.dset.longitude[0, 0],\n- urcrnrlon=self.dset.longitude[-1, -1], rsphere=6371200.,\n- area_thresh=50.)\n- self.map = m\n- else:\n- m = self.map\n- return self.map\n+ savedata = False\n+ # END block\n+\n+ if verbose:\n+ print(savedata, 'DATES :', pdate1, pdate2)\n+\n+ # datelist = []\n+ atthash['Species ID'] = []\n+ inc_iii = False\n+ # LOOP to go through each level\n+ for lev in range(hdata4a['nlev'][0]):\n+ # LOOP to go through each pollutant\n+ for pollutant in range(hdata5a['pollnum'][0]):\n+\n+ # record 8a has the number of elements (ne). If number of\n+ # elements greater than 0 than there are concentrations.\n+ hdata8a = fromfile(fp, dtype=rec8a, count=1)\n+ atthash['Species ID'].append(\n+ hdata8a['poll'][0].decode('UTF-8'))\n+ # if number of elements is nonzero then\n+ if hdata8a['ne'] >= 1:\n+ hdata8b = fromfile(\n+ fp, dtype=rec8b,\n+ count=hdata8a['ne'][0]) # get rec8 - indx and jndx\n+ self.nonzeroconcdates.append(\n+ pdate1\n+ ) # add sample start time to list of start times with\n+ # non zero conc\n+ else:\n+ tempzeroconcdates.append(\n+ pdate1\n+ ) # or add sample start time to list of start times\n+ # with zero conc.\n+ # This is just padding.\n+ fromfile(fp, dtype=rec8c, count=1)\n+ # if savedata is set and nonzero concentrations then save\n+ # the data in a pandas dataframe\n+ if savedata and hdata8a['ne'] >= 1:\n+ self.nonzeroconcdates.append(pdate1)\n+ # set to True to indicate that there is data to be\n+ # saved.\n+ inc_iii = True\n+\n+ lev_name = hdata8a['lev'][0]\n+ col_name = hdata8a['poll'][0].decode('UTF-8')\n+ ndata = hdata8b.byteswap().newbyteorder(\n+ ) # otherwise get endian error.\n+ concframe = pd.DataFrame.from_records(ndata)\n+ # add latitude longitude columns\n+ lat = arange(self.llcrnr_lat,\n+ self.llcrnr_lat + self.nlat * self.dlat,\n+ self.dlat)\n+ lon = arange(self.llcrnr_lon,\n+ self.llcrnr_lon + self.nlon * self.dlon,\n+ self.dlon)\n+\n+ def flat(x):\n+ return lat[x - 1]\n+\n+ def flon(x):\n+ return lon[x - 1]\n+\n+ # This block will fill in zero values in the\n+ # concentration grid.\n+ if fillra:\n+ n1 = arange(1, self.nlat + 1)\n+ n2 = arange(1, self.nlon + 1)\n+ concframe['ji'] = zip(concframe['jndx'],\n+ concframe['indx'])\n+ concframe.set_index(['ji'], inplace=True)\n+ newi = [(x, y) for x in n1 for y in n2]\n+ concframe = concframe.reindex(newi)\n+ concframe.reset_index(inplace=True)\n+ concframe[['jndx',\n+ 'indx']] = concframe['ji'].tolist()\n+ concframe.fillna(0, inplace=True)\n+ concframe.drop('ji', axis=1, inplace=True)\n+ # print(len(lat))\n+ # print(len(lon))\n+ # print(len(n1), len(n2), n1[-1], n2[-1])\n+ # print(self.nlat, self.nlon)\n+ # print(self.llcrnr_lat, self.llcrnr_lon)\n+ # print(concframe[-50:-1])\n+\n+ concframe['latitude'] = concframe['jndx'].apply(flat)\n+ concframe['longitude'] = concframe['indx'].apply(flon)\n+ concframe.drop(['jndx', 'indx'], axis=1, inplace=True)\n+ concframe['levels'] = lev_name\n+ concframe['time'] = pdate1\n+ if verbose:\n+ print('pdate1')\n+ concframe.set_index(\n+ ['time', 'levels', 'longitude', 'latitude'],\n+ inplace=True)\n+ concframe.rename(\n+ columns={'conc': col_name}, inplace=True)\n+ dset = xr.Dataset.from_dataframe(concframe)\n+ # if this is the first time through. create dataframe\n+ # for first level and pollutant.\n+ if self.dset is None:\n+ self.dset = dset\n+ else: # create dataframe for level and pollutant and\n+ # then merge with main dataframe.\n+ # self.dset = xr.concat([self.dset, dset],'levels')\n+ self.dset = xr.merge([self.dset, dset])\n+ ii += 1\n+\n+ # END LOOP to go through each pollutant\n+ # END LOOP to go through each level\n+ # safety check - will stop sampling time while loop if goes over\n+ # imax iterations.\n+ if ii > imax:\n+ testf = False\n+ if inc_iii:\n+ iii += 1\n+\n+ atthash['Concentration Grid'] = ahash\n+ atthash['Species ID'] = list(set(atthash['Species ID']))\n+ atthash['Coordinate time description'] = 'Beginning of sampling time'\n+ # END OF Loop to go through each sampling time\n+ self.dset.attrs = atthash\n+ if verbose:\n+ print(self.dset)\n+\n+ if iii == 0:\n+ print(\n+ 'Warning: ModelBin class _readfile method: no data in the date range found'\n+ )\n+ return False\n+ return True\ndiff --git a/monet/monet_accessor.py b/monet/monet_accessor.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/monet_accessor.py\n@@ -0,0 +1,507 @@\n+\"MONET Accessor\"\n+\n+from __future__ import absolute_import, division, print_function\n+from builtins import object\n+import pandas as pd\n+import xarray as xr\n+import stratify\n+\n+\n+@xr.register_dataarray_accessor('monet')\n+class MONETAccessor(object):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ xray_obj : type\n+ Description of parameter `xray_obj`.\n+\n+ Attributes\n+ ----------\n+ obj : type\n+ Description of attribute `obj`.\n+\n+ \"\"\"\n+\n+ def __init__(self, xray_obj):\n+ self.obj = xray_obj\n+\n+ def stratify(self, levels, vertical, axis=1):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ levels : type\n+ Description of parameter `levels`.\n+ vertical : type\n+ Description of parameter `vertical`.\n+ axis : type\n+ Description of parameter `axis`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ result = stratify.interpolate(\n+ levels, vertical.chunk(), self.obj.chunk(), axis=axis)\n+ dims = self.obj.dims\n+ out = xr.DataArray(result, dims=dims)\n+ for i in dims:\n+ if i != 'z':\n+ out[i] = self.obj[i]\n+ out.attrs = self.obj.attrs.copy()\n+ if len(self.obj.coords) > 0:\n+ for i in self.obj.coords:\n+ out.coords[i] = self.obj.coords[i]\n+ return out\n+\n+ def interp_constant_lat(self, lat=None, **kwargs):\n+ \"\"\"Interpolates the data array to constant longitude.\n+\n+ Parameters\n+ ----------\n+ lon : float\n+ Latitude on which to interpolate to\n+\n+ Returns\n+ -------\n+ DataArray\n+ DataArray of at constant longitude\n+\n+ \"\"\"\n+ from .util.interp_util import constant_lat_swathdefition\n+ from .util.resample import resample_dataset\n+ from numpy import linspace\n+ try:\n+ if lat is None:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('Must enter lat value')\n+ longitude = linspace(self.obj.longitude.min(),\n+ self.obj.longitude.max(), len(self.obj.x))\n+ target = constant_lat_swathdefition(longitude=longitude, latitude=lat)\n+ output = resample_dataset(self.obj, target, **kwargs).squeeze()\n+ return output\n+\n+ def interp_constant_lon(self, lon=None, **kwargs):\n+ \"\"\"Interpolates the data array to constant longitude.\n+\n+ Parameters\n+ ----------\n+ lon : float\n+ Latitude on which to interpolate to\n+\n+ Returns\n+ -------\n+ DataArray\n+ DataArray of at constant longitude\n+\n+ \"\"\"\n+ from .util.interp_util import constant_lon_swathdefition\n+ from .util.resample import resample_dataset\n+ from numpy import linspace\n+ try:\n+ if lon is None:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('Must enter lon value')\n+ latitude = linspace(self.obj.latitude.min(), self.obj.latitude.max(),\n+ len(self.obj.y))\n+ target = constant_lon_swathdefition(longitude=lon, latitude=latitude)\n+ output = resample_dataset(self.obj, target, **kwargs).squeeze()\n+ return output\n+\n+ def nearest_latlon(self, lat=None, lon=None, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ lat : type\n+ Description of parameter `lat`.\n+ lon : type\n+ Description of parameter `lon`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .util.interp_util import nearest_point_swathdefinition\n+ from .util.resample import resample_dataset\n+ try:\n+ if lat is None or lon is None:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('Must provide latitude and longitude')\n+ target = nearest_point_swathdefinition(longitude=lon, latitude=lat)\n+ output = resample_dataset(self.obj, target, **kwargs)\n+ return output\n+\n+ def cartopy(self):\n+ \"\"\"Short summary.\n+\n+ Returns\n+ -------\n+ type\n+ Returns a cartopy.crs.Projection for this dataset\n+\n+ \"\"\"\n+\n+ return self.obj.area.to_cartopy_crs()\n+\n+ def quick_map(self, map_kwarg={}, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ map_kwarg : type\n+ Description of parameter `map_kwarg`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .plots.mapgen import draw_map\n+ from matplotlib.pyplot import tight_layout\n+ # import cartopy.crs as ccrs\n+ # crs = self.obj.monet.cartopy()\n+ ax = draw_map(**map_kwarg)\n+ self.obj.plot(x='longitude', y='latitude', ax=ax, **kwargs)\n+ ax.outline_patch.set_alpha(0)\n+ tight_layout()\n+ return ax\n+\n+ def remap_data(self, dataarray, grid=None, **kwargs):\n+ \"\"\"remaps from another grid to the current grid of self using pyresample.\n+ it assumes that the dimensions are ordered in ROW,COL,CHANNEL per\n+ pyresample docs\n+\n+ Parameters\n+ ----------\n+ grid : pyresample grid (SwathDefinition or AreaDefinition)\n+ Description of parameter `grid`.\n+ da : ndarray or xarray DataArray\n+ Description of parameter `dset`.\n+ radius_of_influence : float or integer\n+ radius of influcence for pyresample in meters.\n+\n+ Returns\n+ -------\n+ xarray.DataArray\n+ resampled object on current grid.\n+\n+ \"\"\"\n+ from .util import resample\n+ # check to see if grid is supplied\n+ target = self.obj.area\n+ if grid is None: # grid is assumed to be in da.area\n+ out = resample.resample_dataset(dataarray.chunk(), target,\n+ **kwargs)\n+ else:\n+ dataarray.attrs['area'] = grid\n+ out = resample.resample_dataset(dataarray.chunk(), target,\n+ **kwargs)\n+ return out\n+\n+ def combine(self, data, col=None, radius_of_influence=None):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ data : type\n+ Description of parameter `data`.\n+ col : type\n+ Description of parameter `col`.\n+ radius : type\n+ Description of parameter `radius`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .models.combinetool import combine_da_to_df\n+ # point source data\n+ if isinstance(data, pd.DataFrame):\n+ try:\n+ if col is None:\n+ raise RuntimeError\n+ return combine_da_to_df(\n+ self.obj,\n+ data,\n+ col=col,\n+ radius_of_influence=radius_of_influence)\n+ except RuntimeError:\n+ print('Must enter col ')\n+ elif isinstance(data, xr.Dataset) or isinstance(data, xr.DataArray):\n+ print('do spatial transform')\n+ else:\n+ print('d must be either a pd.DataFrame or xr.DataArray')\n+\n+\n+@xr.register_dataset_accessor('monet')\n+class MONETAccessorDataset(object):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ xray_obj : type\n+ Description of parameter `xray_obj`.\n+\n+ Attributes\n+ ----------\n+ obj : type\n+ Description of attribute `obj`.\n+\n+ \"\"\"\n+\n+ def __init__(self, xray_obj):\n+ self.obj = xray_obj\n+\n+ def remap_data(self, data, grid=None, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ data : type\n+ Description of parameter `data`.\n+ grid : type\n+ Description of parameter `grid`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ try:\n+ if isinstance(data, xr.DataArray):\n+ self._remap_dataarray(data, grid=grid, **kwargs)\n+ elif isinstance(data, xr.Dataset):\n+ self._remap_dataset(data, grid=None, **kwargs)\n+ else:\n+ raise TypeError\n+ except TypeError:\n+ print('data must be an xarray.DataArray or xarray.Dataset')\n+\n+ def _remap_dataset(self, dset, grid=None, **kwargs):\n+ \"\"\"Resample the entire dset (xarray.Dataset) to the current dataset object.\n+\n+ Parameters\n+ ----------\n+ dset : xarray.Dataset\n+ Description of parameter `dataarray`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ # from .util import resample\n+ # target = self.obj.area\n+ skip_keys = ['latitude', 'longitude', 'time', 'TFLAG']\n+ vars = pd.Series(dset.variables)\n+ loop_vars = vars.loc[~vars.isin(skip_keys)]\n+ # get the first one in the loop and get the resample_cache data\n+ dataarray = dset[loop_vars[0]]\n+\n+ da, resample_cache = self._remap_dataarray(\n+ dataarray, grid=grid, return_neighbor_info=True, **kwargs)\n+ if da.name in self.obj.variables:\n+ da.name = da.name + '_y'\n+ self.obj[da.name] = da\n+ for i in loop_vars[1:]:\n+ dataarray = dset[i]\n+ da, resample_cache = self._remap_dataarray(\n+ dataarray, grid=grid, resample_cache=resample_cache, **kwargs)\n+ if da.name in self.obj.variables:\n+ da.name = da.name + '_y'\n+ self.obj[da.name] = da\n+\n+ def _remap_dataarray(self, dataarray, grid=None, **kwargs):\n+ \"\"\"Resample the DataArray to the dataset object.\n+\n+ Parameters\n+ ----------\n+ dataarray : type\n+ Description of parameter `dataarray`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .util import resample\n+ target = self.obj.area\n+ if grid is None: # grid is assumed to be in da.area\n+ out = resample.resample_dataset(dataarray.chunk(), target,\n+ **kwargs)\n+\n+ else:\n+ dataarray.attrs['area'] = grid\n+ out = resample.resample_dataset(dataarray.chunk(), target,\n+ **kwargs)\n+ if out.name in self.obj.variables:\n+ out.name = out.name + '_y'\n+ self.obj[out.name] = out\n+\n+ def nearest_latlon(self, lat=None, lon=None, **kwargs):\n+ vars = pd.Series(self.obj.variables)\n+ skip_keys = ['latitude', 'longitude', 'time', 'TFLAG']\n+ loop_vars = vars.loc[~vars.isin(skip_keys)]\n+ orig = self.obj[loop_vars.iloc[0]].monet.nearest_latlon(\n+ lat=lat, lon=lon, **kwargs)\n+ dset = orig.to_dataset()\n+ dset.attrs = self.obj.attrs.copy()\n+ for i in loop_vars[1:].values:\n+ dset[i] = self.obj[i].monet.nearest_latlon(\n+ lat=lat, lon=lon, **kwargs)\n+ return dset\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ lat : type\n+ Description of parameter `lat`.\n+ lon : type\n+ Description of parameter `lon`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+\n+ def interp_constant_lat(self, lat=None, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ lat : type\n+ Description of parameter `lat`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ vars = pd.Series(self.obj.variables)\n+ skip_keys = ['latitude', 'longitude', 'time', 'TFLAG']\n+ loop_vars = vars.loc[~vars.isin(skip_keys)]\n+\n+ orig = self.obj[loop_vars.iloc[0]].monet.interp_constant_lat(\n+ lat=lat, **kwargs)\n+\n+ dset = orig.to_dataset()\n+ dset.attrs = self.obj.attrs.copy()\n+ for i in loop_vars[1:].values:\n+ dset[i] = self.obj[i].interp_constant_lat(lat=lat, **kwargs)\n+ return dset\n+\n+ def interp_constant_lon(self, lon=None, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ lon : type\n+ Description of parameter `lon`.\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ vars = pd.Series(self.obj.variables)\n+ skip_keys = ['latitude', 'longitude', 'time', 'TFLAG']\n+ loop_vars = vars.loc[~vars.isin(skip_keys)]\n+ orig = self.obj[loop_vars[0]].interp_constant_lon(lon=lon, **kwargs)\n+ dset = orig.to_dataset()\n+ dset.attrs = self.obj.attrs.copy()\n+ for i in loop_vars[1:].values:\n+ dset[i] = self.obj[i].interp_constant_lon(lon=lon, **kwargs)\n+ return dset\n+\n+ def stratify(self, levels, vertical, axis=1):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ levels : type\n+ Description of parameter `levels`.\n+ vertical : type\n+ Description of parameter `vertical`.\n+ axis : type\n+ Description of parameter `axis`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ loop_vars = [i for i in self.obj.variables if 'z' in self.obj[i].dims]\n+ orig = self.obj[loop_vars[0]].stratify(levels, vertical, axis=axis)\n+ dset = orig.to_dataset()\n+ dset.attrs = self.obj.attrs.copy()\n+ for i in loop_vars[1:]:\n+ dset[i] = self.obj[i].stratify(levels, vertical, axis=axis)\n+ return dset\n+\n+ def cartopy(self):\n+ \"\"\"Returns a cartopy.crs.Projection for this dataset.\"\"\"\n+ return self.obj.area.to_cartopy_crs()\n+\n+ def combine_to_df(self, df, mapping_table=None, radius_of_influence=None):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ df : type\n+ Description of parameter `df`.\n+ mapping_table : type\n+ Description of parameter `mapping_table`.\n+ radius : type\n+ Description of parameter `radius`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .models.combinetool import combine_da_to_df\n+ try:\n+ if ~isinstance(df, pd.DataFrame):\n+ raise TypeError\n+ except TypeError:\n+ print('df must be of type pd.DataFrame')\n+ for i in mapping_table:\n+ df = combine_da_to_df(\n+ self.obj[mapping_table[i]],\n+ df,\n+ col=i,\n+ radius=radius_of_influence)\n+ return df\ndiff --git a/monet/obs/__init__.py b/monet/obs/__init__.py\n--- a/monet/obs/__init__.py\n+++ b/monet/obs/__init__.py\n@@ -1,7 +1,21 @@\n from __future__ import absolute_import, print_function\n+from . import aeronet_mod, airnow_mod, aqs_mod, crn_mod, epa_util, improve_mod\n+from . import ish_mod, tolnet_mod, cems_mod, nadp_mod, modis_swath\n \n-from . import aeronet, airnow, aqs, crn, epa_util, improve, ish, tolnet\n-\n-__all__ = ['aeronet', 'airnow', 'aqs', 'crn', 'epa_util', 'improve', 'ish', 'tolnet']\n+__all__ = [\n+ 'aeronet_mod', 'airnow_mod', 'aqs_mod', 'crn_mod', 'epa_util',\n+ 'improve_mod', 'ish_mod', 'tolnet_mod', 'cems_mod', 'nadp_mod',\n+ 'modis_swath'\n+]\n \n __name__ = 'obs'\n+\n+airnow = airnow_mod.AirNow()\n+aqs = aqs_mod.AQS()\n+aeronet = aeronet_mod.AERONET()\n+crn = crn_mod.crn()\n+improve = improve_mod.IMPROVE()\n+tolnet = tolnet_mod.TOLNet()\n+cems = cems_mod.CEMS()\n+nadp = nadp_mod.NADP()\n+\ndiff --git a/monet/obs/aeronet_mod.py b/monet/obs/aeronet_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/aeronet_mod.py\n@@ -0,0 +1,175 @@\n+from __future__ import division, print_function\n+\n+# this is written to retrive airnow data concatenate and add to pandas array\n+# for usage\n+from builtins import object, str\n+from datetime import datetime\n+\n+import pandas as pd\n+from past.utils import old_div\n+\n+\n+def dateparse(x):\n+ return pd.datetime.strptime(x, '%d:%m:%Y %H:%M:%S')\n+\n+\n+class AERONET(object):\n+ def __init__(self):\n+ from numpy import concatenate, arange\n+ self.baseurl = 'https://aeronet.gsfc.nasa.gov/cgi-bin/print_web_data_v3?'\n+ self.dates = [\n+ datetime.strptime('2016-06-06 12:00:00', '%Y-%m-%d %H:%M:%S'),\n+ datetime.strptime('2016-06-10 13:00:00', '%Y-%m-%d %H:%M:%S')\n+ ]\n+ self.datestr = []\n+ self.df = pd.DataFrame()\n+ self.daily = None\n+ self.prod = None\n+ self.inv_type = None\n+ self.objtype = 'AERONET'\n+ self.usecols = concatenate((arange(30), arange(65, 83)))\n+ # [21.1,-131.6686,53.04,-58.775] #[latmin,lonmin,latmax,lonmax]\n+ self.latlonbox = None\n+ self.url = None\n+\n+ def build_url(self):\n+ sy = self.dates.min().strftime('%Y')\n+ sm = self.dates.min().strftime('%m').zfill(2)\n+ sd = self.dates.min().strftime('%d').zfill(2)\n+ sh = self.dates.min().strftime('%H').zfill(2)\n+ ey = self.dates.max().strftime('%Y').zfill(2)\n+ em = self.dates.max().strftime('%m').zfill(2)\n+ ed = self.dates.max().strftime('%d').zfill(2)\n+ eh = self.dates.max().strftime('%H').zfill(2)\n+ if self.prod in [\n+ 'AOD10', 'AOD15', 'AOD20', 'SDA10', 'SDA15', 'SDA20', 'TOT10',\n+ 'TOT15', 'TOT20'\n+ ]:\n+ base_url = 'https://aeronet.gsfc.nasa.gov/cgi-bin/print_web_data_v3?'\n+ inv_type = ''\n+ else:\n+ base_url = 'https://aeronet.gsfc.nasa.gov/cgi-bin/print_web_data_inv_v3?'\n+ if self.inv_type == 'ALM15':\n+ inv_type = '&ALM15=1'\n+ else:\n+ inv_type = '&AML20=1'\n+ date_portion = 'year=' + sy + '&month=' + sm + '&day=' + sd + \\\n+ '&hour=' + sh + '&year2=' + ey + '&month2=' + em + '&day2=' + ed +\\\n+ '&hour2=' + eh\n+ if self.inv_type is not '':\n+ product = '&product=' + self.prod\n+ else:\n+ product = '&' + self.prod + '=1'\n+ time = '&AVG=' + str(self.daily)\n+ if self.latlonbox is None:\n+ latlonbox = ''\n+ else:\n+ lat1 = str(self.latlonbox[0])\n+ lon1 = str(self.latlonbox[1])\n+ lat2 = str(self.latlonbox[2])\n+ lon2 = str(self.latlonbox[3])\n+ latlonbox = '&lat1=' + lat1 + '&lat2=' + \\\n+ lat2 + '&lon1=' + lon1 + '&lon2=' + lon2\n+ self.url = base_url + date_portion + product + inv_type + time +\\\n+ '&if_no_html=1'\n+ #\n+ # self.url = 'https://aeronet.gsfc.nasa.gov/cgi-bin/print_web_data_v3?year=' + sy + '&month=' + sm + '&day=' + sd + \\\n+ # '&hour=' + sh + '&year2=' + ey + '&month2=' + em + '&day2=' + ed + '&hour2=' + eh + '&AOD15=1&AVG=10&if_no_html=1'\n+ #\n+ #\n+ # self.url = 'https://aeronet.gsfc.nasa.gov/cgi-bin/print_web_data_v3?year=' + sy + '&month=' + sm + '&day=' + sd + '&hour=' + sh + '&year2=' + ey + \\\n+ # '&month2=' + em + '&day2=' + ed + '&hour2=' + eh + '&lat1=' + lat1 + '&lat2=' + lat2 + '&lon1=' + lon1 + '&lon2=' + lon2 + '&AOD15=1&AVG=10&if_no_html=1'\n+\n+ def read_aeronet(self):\n+ print('Reading Aeronet Data...')\n+ # header = self.get_columns()\n+ df = pd.read_csv(\n+ self.url,\n+ engine='python',\n+ header=None,\n+ skiprows=6,\n+ parse_dates={'time': [1, 2]},\n+ date_parser=dateparse,\n+ na_values=-999)\n+ # df.rename(columns={'date_time': 'time'}, inplace=True)\n+ columns = self.get_columns()\n+ df.columns = columns # self.get_columns()\n+ df.index = df.time\n+ df.rename(\n+ columns={\n+ 'site_latitude(degrees)': 'latitude',\n+ 'site_longitude(degrees)': 'longitude',\n+ 'site_elevation(m)': 'elevation',\n+ 'aeronet_site': 'siteid'\n+ },\n+ inplace=True)\n+ df.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ df.dropna(axis=1, how='all', inplace=True)\n+ self.df = df\n+\n+ def get_columns(self):\n+ header = pd.read_csv(\n+ self.url, skiprows=5, header=None, nrows=1).values.flatten()\n+ final = ['time']\n+ for i in header:\n+ if \"Date(\" in i or 'Time(' in i:\n+ pass\n+ else:\n+ final.append(i.lower())\n+ return final\n+\n+ def add_data(self,\n+ dates=None,\n+ product='AOD15',\n+ latlonbox=None,\n+ daily=False,\n+ calc_550=True,\n+ inv_type=None,\n+ freq=None,\n+ detect_dust=False):\n+ self.latlonbox = latlonbox\n+ if dates is None: # get the current day\n+ self.dates = pd.date_range(\n+ start=pd.to_datetime('today'),\n+ end=pd.to_datetime('now'),\n+ freq='H')\n+ else:\n+ self.dates = dates\n+ self.prod = product.upper()\n+ if daily:\n+ self.daily = 20 # daily data\n+ else:\n+ self.daily = 10 # all points\n+ if inv_type is None:\n+ self.inv_type = 'ALM15'\n+ else:\n+ self.inv_type = inv_type\n+ self.build_url()\n+ self.read_aeronet()\n+ if freq is not None:\n+ self.df = self.df.groupby('siteid').resample(\n+ freq).mean().reset_index()\n+ if detect_dust:\n+ self.dust_detect()\n+ if calc_550:\n+ self.calc_550nm()\n+ return self.df.copy()\n+\n+ def calc_550nm(self):\n+ \"\"\"Since AOD at 500nm is not calculated we use the extrapolation of\n+ V. Cesnulyte et al (ACP,2014) for the calculation\n+\n+ aod550 = aod500 * (550/500) ^ -alpha\n+ \"\"\"\n+ self.df['aod_550nm'] = self.df.aod_500nm * (old_div(\n+ 550., 500.))**(-self.df['440-870_angstrom_exponent'])\n+\n+ def dust_detect(self):\n+ \"\"\" [Dubovik et al., 2002]. AOD_1020 > 0.3 and AE(440,870) < 0.6\"\"\"\n+ self.df['dust'] = (self.df['aod_1020nm'] >\n+ 0.3) & (self.df['440-870_angstrom_exponent'] < 0.6)\n+\n+ def set_daterange(self, begin='', end=''):\n+ dates = pd.date_range(\n+ start=begin, end=end, freq='H').values.astype('M8[s]').astype('O')\n+ self.dates = dates\ndiff --git a/monet/obs/airnow_mod.py b/monet/obs/airnow_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/airnow_mod.py\n@@ -0,0 +1,291 @@\n+from __future__ import print_function\n+\n+import inspect\n+import os\n+# this is written to retrive airnow data concatenate and add to pandas array\n+# for usage\n+from builtins import object\n+from datetime import datetime\n+\n+import pandas as pd\n+\n+\n+class AirNow(object):\n+ \"\"\"Short summary.\n+\n+ Attributes\n+ ----------\n+ url : type\n+ Description of attribute `url`.\n+ dates : type\n+ Description of attribute `dates`.\n+ datestr : type\n+ Description of attribute `datestr`.\n+ df : type\n+ Description of attribute `df`.\n+ daily : type\n+ Description of attribute `daily`.\n+ objtype : type\n+ Description of attribute `objtype`.\n+ filelist : type\n+ Description of attribute `filelist`.\n+ monitor_file : type\n+ Description of attribute `monitor_file`.\n+ __class__ : type\n+ Description of attribute `__class__`.\n+ monitor_df : type\n+ Description of attribute `monitor_df`.\n+ savecols : type\n+ Description of attribute `savecols`.\n+ \"\"\"\n+\n+ def __init__(self):\n+ self.datadir = '.'\n+ self.cwd = os.getcwd()\n+ self.url = None\n+ self.dates = [\n+ datetime.strptime('2016-06-06 12:00:00', '%Y-%m-%d %H:%M:%S'),\n+ datetime.strptime('2016-06-06 13:00:00', '%Y-%m-%d %H:%M:%S')\n+ ]\n+ self.datestr = []\n+ self.df = pd.DataFrame()\n+ self.daily = False\n+ self.objtype = 'AirNow'\n+ self.filelist = None\n+ self.monitor_file = inspect.getfile(\n+ self.__class__)[:-13] + 'data/monitoring_site_locations.dat'\n+ self.monitor_df = None\n+ self.savecols = [\n+ 'time', 'siteid', 'site', 'utcoffset', 'variable', 'units', 'obs',\n+ 'time_local', 'latitude', 'longitude', 'cmsa_name', 'msa_code',\n+ 'msa_name', 'state_name', 'epa_region'\n+ ]\n+\n+ def convert_dates_tofnames(self):\n+ \"\"\"Helper function to create file names\n+\n+ Returns\n+ -------\n+\n+\n+ \"\"\"\n+ self.datestr = []\n+ for i in self.dates:\n+ self.datestr.append(i.strftime('%Y%m%d%H.dat'))\n+\n+ def build_urls(self):\n+ \"\"\"Short summary.\n+\n+ Returns\n+ -------\n+ helper function to build urls\n+\n+ \"\"\"\n+\n+ furls = []\n+ fnames = []\n+ print('Building AIRNOW URLs...')\n+ # 2017/20170131/HourlyData_2017012408.dat\n+ url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/'\n+ for i in self.dates:\n+ f = url + i.strftime('%Y/%Y%m%d/HourlyData_%Y%m%d%H.dat')\n+ fname = i.strftime('HourlyData_%Y%m%d%H.dat')\n+ furls.append(f)\n+ fnames.append(fname)\n+ # https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/2017/20170108/HourlyData_2016121506.dat\n+\n+ # files needed for comparison\n+ self.url = pd.Series(furls, index=None)\n+ self.fnames = pd.Series(fnames, index=None)\n+\n+ def read_csv(self, fn):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ fn : string\n+ file name to read\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ try:\n+ dft = pd.read_csv(\n+ fn,\n+ delimiter='|',\n+ header=None,\n+ error_bad_lines=False,\n+ encoding='ISO-8859-1')\n+ cols = [\n+ 'date', 'time', 'siteid', 'site', 'utcoffset', 'variable',\n+ 'units', 'obs', 'source'\n+ ]\n+ dft.columns = cols\n+ except Exception:\n+ cols = [\n+ 'date', 'time', 'siteid', 'site', 'utcoffset', 'variable',\n+ 'units', 'obs', 'source'\n+ ]\n+ dft = pd.DataFrame(columns=cols)\n+ dft['obs'] = dft.obs.astype(float)\n+ dft['siteid'] = dft.siteid.str.zfill(9)\n+ dft['utcoffset'] = dft.utcoffset.astype(int)\n+ return dft\n+\n+ def retrieve(self, url, fname):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ url : type\n+ Description of parameter `url`.\n+ fname : type\n+ Description of parameter `fname`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import requests\n+\n+ if not os.path.isfile(fname):\n+ print('\\n Retrieving: ' + fname)\n+ print(url)\n+ print('\\n')\n+ r = requests.get(url)\n+ open(fname, 'wb').write(r.content)\n+ else:\n+ print('\\n File Exists: ' + fname)\n+\n+ def aggregate_files(self, download=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ download : type\n+ Description of parameter `download` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import dask\n+ import dask.dataframe as dd\n+\n+ print('Aggregating AIRNOW files...')\n+ self.build_urls()\n+ if download:\n+ for url, fname in zip(self.url, self.fnames):\n+ self.retrieve(url, fname)\n+ dfs = [dask.delayed(self.read_csv)(f) for f in self.fnames]\n+ else:\n+ dfs = [dask.delayed(self.read_csv)(f) for f in self.url]\n+ dff = dd.from_delayed(dfs)\n+ df = dff.compute()\n+ df['time'] = pd.to_datetime(\n+ df.date + ' ' + df.time,\n+ format='%m/%d/%y %H:%M',\n+ exact=True,\n+ box=False)\n+ df.drop(['date'], axis=1, inplace=True)\n+ df['time_local'] = df.time + pd.to_timedelta(df.utcoffset, unit='H')\n+ self.df = df\n+ print(' Adding in Meta-data')\n+ self.get_station_locations()\n+ self.df = self.df[self.savecols]\n+ self.df.drop_duplicates(inplace=True)\n+ self.filter_bad_values()\n+\n+ def add_data(self, dates, download=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ dates : type\n+ Description of parameter `dates`.\n+ download : type\n+ Description of parameter `download` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ self.dates = dates\n+ self.aggregate_files(download=download)\n+ return self.df\n+\n+ def filter_bad_values(self):\n+ \"\"\"Short summary.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from numpy import NaN\n+ self.df.loc[(self.df.obs > 1000) | (self.df.obs < 0), 'obs'] = NaN\n+\n+ def set_daterange(self, **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ begin : type\n+ Description of parameter `begin` (the default is '').\n+ end : type\n+ Description of parameter `end` (the default is '').\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ dates = pd.date_range(**kwargs)\n+ self.dates = dates\n+ return dates\n+\n+ def get_station_locations(self):\n+ \"\"\"Short summary.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .epa_util import read_monitor_file\n+ self.monitor_df = read_monitor_file(airnow=True)\n+ self.df = pd.merge(\n+ self.df, self.monitor_df, on='siteid') # , how='left')\n+\n+ def get_station_locations_remerge(self, df):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ df : type\n+ Description of parameter `df`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ df = pd.merge(\n+ df,\n+ self.monitor_df.drop(['Latitude', 'Longitude'], axis=1),\n+ on='siteid') # ,\n+ # how='left')\n+ return df\ndiff --git a/monet/obs/aqs_mod.py b/monet/obs/aqs_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/aqs_mod.py\n@@ -0,0 +1,568 @@\n+from __future__ import print_function\n+\n+import inspect\n+import os\n+# this is a class to deal with aqs data\n+from builtins import object, zip\n+import pandas as pd\n+from dask.diagnostics import ProgressBar\n+\n+from .epa_util import read_monitor_file\n+\n+pbar = ProgressBar()\n+pbar.register()\n+\n+\n+class AQS(object):\n+ \"\"\"Short summary.\n+\n+ Attributes\n+ ----------\n+ baseurl : type\n+ Description of attribute `baseurl`.\n+ objtype : type\n+ Description of attribute `objtype`.\n+ baseurl : type\n+ Description of attribute `baseurl`.\n+ dates : type\n+ Description of attribute `dates`.\n+ renamedhcols : type\n+ Description of attribute `renamedhcols`.\n+ renameddcols : type\n+ Description of attribute `renameddcols`.\n+ savecols : type\n+ Description of attribute `savecols`.\n+ df : type\n+ Description of attribute `df`.\n+ monitor_file : type\n+ Description of attribute `monitor_file`.\n+ __class__ : type\n+ Description of attribute `__class__`.\n+ monitor_df : type\n+ Description of attribute `monitor_df`.\n+ daily : type\n+ Description of attribute `daily`.\n+ d_df : type\n+ Description of attribute `d_df`.\n+\n+ \"\"\"\n+\n+ def __init__(self):\n+ # self.baseurl = 'https://aqs.epa.gov/aqsweb/airdata/'\n+ self.objtype = 'AQS'\n+ self.baseurl = 'https://aqs.epa.gov/aqsweb/airdata/'\n+ self.renamedhcols = [\n+ 'time_local', 'time', 'state_code', 'county_code', 'site_num',\n+ 'parameter_code', 'poc', 'latitude', 'longitude', 'datum',\n+ 'parameter_name', 'obs', 'units', 'mdl', 'uncertainty',\n+ 'qualifier', 'method_type', 'method_code', 'method_name',\n+ 'state_name', 'county_name', 'date_of_last_change'\n+ ]\n+ self.renameddcols = [\n+ 'time_local', 'state_code', 'county_code', 'site_num',\n+ 'parameter_code', 'poc', 'latitude', 'longitude', 'datum',\n+ 'parameter_name', 'sample_duration', 'pollutant_standard', 'units',\n+ 'event_type', 'observation_Count', 'observation_Percent', 'obs',\n+ '1st_max_Value', '1st_max_hour', 'aqi', 'method_code',\n+ 'method_name', 'local_site_name', 'address', 'state_name',\n+ 'county_name', 'city_name', 'msa_name', 'date_of_last_change'\n+ ]\n+ self.savecols = [\n+ 'time_local', 'time', 'siteid', 'latitude', 'longitude', 'obs',\n+ 'units', 'variable'\n+ ]\n+ self.df = pd.DataFrame() # hourly dataframe\n+ self.monitor_file = inspect.getfile(\n+ self.__class__)[:-10] + 'data/monitoring_site_locations.dat'\n+ self.monitor_df = None\n+ self.daily = False\n+ self.d_df = None # daily dataframe\n+\n+ def load_aqs_file(self, url, network):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ url : type\n+ Description of parameter `url`.\n+ network : type\n+ Description of parameter `network`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ if 'daily' in url:\n+\n+ def dateparse(x):\n+ return pd.datetime.strptime(x, '%Y-%m-%d')\n+\n+ df = pd.read_csv(\n+ url,\n+ parse_dates={'time_local': [\"Date Local\"]},\n+ date_parser=dateparse,\n+ dtype={\n+ 0: str,\n+ 1: str,\n+ 2: str\n+ },\n+ encoding='ISO-8859-1')\n+ df.columns = self.renameddcols\n+ df['pollutant_standard'] = df.pollutant_standard.astype(str)\n+ self.daily = True\n+ # df.rename(columns={'parameter_name':'variable'})\n+ else:\n+ df = pd.read_csv(\n+ url,\n+ parse_dates={\n+ 'time': ['Date GMT', 'Time GMT'],\n+ 'time_local': [\"Date Local\", \"Time Local\"]\n+ },\n+ infer_datetime_format=True)\n+ df.columns = self.renamedhcols\n+\n+ df['siteid'] = df.state_code.astype(str).str.zfill(\n+ 2) + df.county_code.astype(str).str.zfill(3) + df.site_num.astype(\n+ str).str.zfill(4)\n+ # df['siteid'] = df.state_code + df.county_code + df.site_num\n+ df.drop(['state_name', 'county_name'], axis=1, inplace=True)\n+ df.columns = [i.lower() for i in df.columns]\n+ if 'daily' not in url:\n+ df.drop(['datum', 'qualifier'], axis=1, inplace=True)\n+ if 'VOC' in url:\n+ voc = True\n+ else:\n+ voc = False\n+ df = self.get_species(df, voc=voc)\n+ return df\n+\n+ def build_url(self, param, year, daily=False, download=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ param : type\n+ Description of parameter `param`.\n+ year : type\n+ Description of parameter `year`.\n+ daily : type\n+ Description of parameter `daily` (the default is False).\n+ download : type\n+ Description of parameter `download` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ if daily:\n+ beginning = self.baseurl + 'daily_'\n+ fname = 'daily_'\n+ else:\n+ beginning = self.baseurl + 'hourly_'\n+ fname = 'hourly_'\n+ if (param.upper() == 'OZONE') | (param.upper() == 'O3'):\n+ code = '44201_'\n+ elif param.upper() == 'PM2.5':\n+ code = '88101_'\n+ elif param.upper() == 'PM2.5_FRM':\n+ code = '88502_'\n+ elif param.upper() == 'PM10':\n+ code = '81102_'\n+ elif param.upper() == 'SO2':\n+ code = '42401_'\n+ elif param.upper() == 'NO2':\n+ code = '42602_'\n+ elif param.upper() == 'CO':\n+ code = '42101_'\n+ elif param.upper() == 'NONOxNOy'.upper():\n+ code = 'NONOxNOy_'\n+ elif param.upper() == 'VOC':\n+ # https://aqs.epa.gov/aqsweb/airdata/daily_VOCS_2017.zip\n+ code = 'VOCS_'\n+ elif param.upper() == 'SPEC':\n+ code = 'SPEC_'\n+ elif param.upper() == 'PM10SPEC':\n+ code = 'PM10SPEC_'\n+ elif param.upper() == 'WIND':\n+ code = 'WIND_'\n+ elif param.upper() == 'TEMP':\n+ code = 'TEMP_'\n+ elif param.upper() == 'RHDP':\n+ code = 'RH_DP_'\n+ elif (param.upper() == 'WIND') | (param.upper() == 'WS') | (\n+ param.upper() == 'WDIR'):\n+ code = 'WIND_'\n+ url = beginning + code + year + '.zip'\n+ fname = fname + code + year + '.zip'\n+ return url, fname\n+\n+ def build_urls(self, params, dates, daily=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ params : type\n+ Description of parameter `params`.\n+ dates : list of datetime objects\n+ dates to retrieve data for. Only the years are taken into account.\n+ daily : type\n+ Description of parameter `daily` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ years = pd.DatetimeIndex(dates).year.unique().astype(str)\n+ urls = []\n+ fnames = []\n+ for i in params:\n+ for y in years:\n+ url, fname = self.build_url(i, y, daily=daily)\n+ urls.append(url)\n+ fnames.append(fname)\n+ return urls, fnames\n+\n+ def retrieve(self, url, fname):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ url : type\n+ Description of parameter `url`.\n+ fname : type\n+ Description of parameter `fname`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import requests\n+\n+ if not os.path.isfile(fname):\n+ print('\\n Retrieving: ' + fname)\n+ print(url)\n+ print('\\n')\n+ r = requests.get(url)\n+ open(fname, 'wb').write(r.content)\n+ else:\n+ print('\\n File Exists: ' + fname)\n+\n+ def add_data(self,\n+ dates,\n+ param=None,\n+ daily=False,\n+ network=None,\n+ download=False,\n+ local=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ dates : list of datetime objects\n+ Description of parameter `dates`.\n+ param : list of strings\n+ Description of parameter `param` (the default is None).\n+ daily : boolean\n+ Description of parameter `daily` (the default is False).\n+ network : type\n+ Description of parameter `network` (the default is None).\n+ download : type\n+ Description of parameter `download` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import dask\n+ import dask.dataframe as dd\n+ if param is None:\n+ params = [\n+ 'SPEC', 'PM10', 'PM2.5', 'PM2.5_FRM', 'CO', 'OZONE', 'SO2',\n+ 'VOC', 'NONOXNOY', 'WIND', 'TEMP', 'RHDP'\n+ ]\n+ else:\n+ params = param\n+ urls, fnames = self.build_urls(params, dates, daily=daily)\n+ if download:\n+ for url, fname in zip(urls, fnames):\n+ self.retrieve(url, fname)\n+ dfs = [\n+ dask.delayed(self.load_aqs_file)(i, network) for i in fnames\n+ ]\n+ elif local:\n+ dfs = [\n+ dask.delayed(self.load_aqs_file)(i, network) for i in fnames\n+ ]\n+ else:\n+ dfs = [dask.delayed(self.load_aqs_file)(i, network) for i in urls]\n+ dff = dd.from_delayed(dfs)\n+ self.df = dff.compute()\n+ self.df = self.change_units(self.df)\n+ if self.monitor_df is None:\n+ self.monitor_df = read_monitor_file()\n+ drop_monitor_cols = True\n+ else:\n+ drop_monitor_cols = False\n+ if daily:\n+ if drop_monitor_cols:\n+ monitor_drop = [\n+ 'msa_name', 'city_name', u'local_site_name', u'address',\n+ u'datum'\n+ ]\n+ self.monitor_df.drop(monitor_drop, axis=1, inplace=True)\n+ # else:\n+ # monitor_drop = [u'datum']\n+ # self.monitor_df.drop(monitor_drop, axis=1, inplace=True)\n+ if network is not None:\n+ monitors = self.monitor_df.loc[self.monitor_df.isin(\n+ [network])].drop_duplicates(subset=['siteid'])\n+ else:\n+ monitors = self.monitor_df.drop_duplicates(subset=['siteid'])\n+ self.df = pd.merge(self.df, monitors, on=['siteid'], how='left')\n+ if daily:\n+ self.df['time'] = self.df.time_local - pd.to_timedelta(\n+ self.df.gmt_offset, unit='H')\n+ # if pd.Series(self.df.columns).isin(['parameter_name']).max():\n+ # self.df.drop('parameter_name', axis=1, inplace=True)\n+ return self.df.copy()\n+\n+ def get_species(self, df, voc=False):\n+ \"\"\"Short summary.\n+\n+ Parameterssdfdsf\n+ ----------\n+ df : type\n+ Description of parameter `df`.\n+ voc : type\n+ Description of parameter `voc` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ pc = df.parameter_code.unique()\n+ df['variable'] = ''\n+ if voc:\n+ df['variable'] = df.parameter_name.str.upper()\n+ return df\n+ for i in pc:\n+ con = df.parameter_code == i\n+ if (i == 88101) | (i == 88502):\n+ df.loc[con, 'variable'] = 'PM2.5'\n+ if i == 44201:\n+ df.loc[con, 'variable'] = 'OZONE'\n+ if i == 81102:\n+ df.loc[con, 'variable'] = 'PM10'\n+ if i == 42401:\n+ df.loc[con, 'variable'] = 'SO2'\n+ if i == 42602:\n+ df.loc[con, 'variable'] = 'NO2'\n+ if i == 42101:\n+ df.loc[con, 'variable'] = 'CO'\n+ if i == 62101:\n+ df.loc[con, 'variable'] = 'TEMP'\n+ if i == 88305:\n+ df.loc[con, 'variable'] = 'OC'\n+ if i == 88306:\n+ df.loc[con, 'variable'] = 'NO3f'\n+ if (i == 88307):\n+ df.loc[con, 'variable'] = 'ECf'\n+ if i == 88316:\n+ df.loc[con, 'variable'] = 'ECf_optical'\n+ if i == 88403:\n+ df.loc[con, 'variable'] = 'SO4f'\n+ if i == 88312:\n+ df.loc[con, 'variable'] = 'TCf'\n+ if i == 88104:\n+ df.loc[con, 'variable'] = 'Alf'\n+ if i == 88107:\n+ df.loc[con, 'variable'] = 'Baf'\n+ if i == 88313:\n+ df.loc[con, 'variable'] = 'BCf'\n+ if i == 88109:\n+ df.loc[con, 'variable'] = 'Brf'\n+ if i == 88110:\n+ df.loc[con, 'variable'] = 'Cdf'\n+ if i == 88111:\n+ df.loc[con, 'variable'] = 'Caf'\n+ if i == 88117:\n+ df.loc[con, 'variable'] = 'Cef'\n+ if i == 88118:\n+ df.loc[con, 'variable'] = 'Csf'\n+ if i == 88203:\n+ df.loc[con, 'variable'] = 'Cl-f'\n+ if i == 88115:\n+ df.loc[con, 'variable'] = 'Clf'\n+ if i == 88112:\n+ df.loc[con, 'variable'] = 'Crf'\n+ if i == 88113:\n+ df.loc[con, 'variable'] = 'Cof'\n+ if i == 88114:\n+ df.loc[con, 'variable'] = 'Cuf'\n+ if i == 88121:\n+ df.loc[con, 'variable'] = 'Euf'\n+ if i == 88143:\n+ df.loc[con, 'variable'] = 'Auf'\n+ if i == 88127:\n+ df.loc[con, 'variable'] = 'Hff'\n+ if i == 88131:\n+ df.loc[con, 'variable'] = 'Inf'\n+ if i == 88126:\n+ df.loc[con, 'variable'] = 'Fef'\n+ if i == 88146:\n+ df.loc[con, 'variable'] = 'Laf'\n+ if i == 88128:\n+ df.loc[con, 'variable'] = 'Pbf'\n+ if i == 88140:\n+ df.loc[con, 'variable'] = 'Mgf'\n+ if i == 88132:\n+ df.loc[con, 'variable'] = 'Mnf'\n+ if i == 88142:\n+ df.loc[con, 'variable'] = 'Hgf'\n+ if i == 88134:\n+ df.loc[con, 'variable'] = 'Mof'\n+ if i == 88136:\n+ df.loc[con, 'variable'] = 'Nif'\n+ if i == 88147:\n+ df.loc[con, 'variable'] = 'Nbf'\n+ if i == 88310:\n+ df.loc[con, 'variable'] = 'NO3f'\n+ if i == 88152:\n+ df.loc[con, 'variable'] = 'Pf'\n+ if i == 88303:\n+ df.loc[con, 'variable'] = 'K+f'\n+ if i == 88176:\n+ df.loc[con, 'variable'] = 'Rbf'\n+ if i == 88162:\n+ df.loc[con, 'variable'] = 'Smf'\n+ if i == 88163:\n+ df.loc[con, 'variable'] = 'Scf'\n+ if i == 88154:\n+ df.loc[con, 'variable'] = 'Sef'\n+ if i == 88165:\n+ df.loc[con, 'variable'] = 'Sif'\n+ if i == 88166:\n+ df.loc[con, 'variable'] = 'Agf'\n+ if i == 88302:\n+ df.loc[con, 'variable'] = 'Na+f'\n+ if i == 88184:\n+ df.loc[con, 'variable'] = 'Naf'\n+ if i == 88168:\n+ df.loc[con, 'variable'] = 'Srf'\n+ if i == 88403:\n+ df.loc[con, 'variable'] = 'SO4f'\n+ if i == 88169:\n+ df.loc[con, 'variable'] = 'Sf'\n+ if i == 88170:\n+ df.loc[con, 'variable'] = 'Taf'\n+ if i == 88172:\n+ df.loc[con, 'variable'] = 'Tbf'\n+ if i == 88160:\n+ df.loc[con, 'variable'] = 'Snf'\n+ if i == 88161:\n+ df.loc[con, 'variable'] = 'Tif'\n+ if i == 88312:\n+ df.loc[con, 'variable'] = 'TOT_Cf'\n+ if i == 88310:\n+ df.loc[con, 'variable'] = 'NON-VOLITILE_NO3f'\n+ if i == 88309:\n+ df.loc[con, 'variable'] = 'VOLITILE_NO3f'\n+ if i == 88186:\n+ df.loc[con, 'variable'] = 'Wf'\n+ if i == 88314:\n+ df.loc[con, 'variable'] = 'C_370nmf'\n+ if i == 88179:\n+ df.loc[con, 'variable'] = 'Uf'\n+ if i == 88164:\n+ df.loc[con, 'variable'] = 'Vf'\n+ if i == 88183:\n+ df.loc[con, 'variable'] = 'Yf'\n+ if i == 88167:\n+ df.loc[con, 'variable'] = 'Znf'\n+ if i == 88185:\n+ df.loc[con, 'variable'] = 'Zrf'\n+ if i == 88102:\n+ df.loc[con, 'variable'] = 'Sbf'\n+ if i == 88103:\n+ df.loc[con, 'variable'] = 'Asf'\n+ if i == 88105:\n+ df.loc[con, 'variable'] = 'Bef'\n+ if i == 88124:\n+ df.loc[con, 'variable'] = 'Gaf'\n+ if i == 88185:\n+ df.loc[con, 'variable'] = 'Irf'\n+ if i == 88180:\n+ df.loc[con, 'variable'] = 'Kf'\n+ if i == 88301:\n+ df.loc[con, 'variable'] = 'NH4+f'\n+ if (i == 88320) | (i == 88355):\n+ df.loc[con, 'variable'] = 'OCf'\n+ if (i == 88357) | (i == 88321):\n+ df.loc[con, 'variable'] = 'ECf'\n+ if i == 42600:\n+ df.loc[con, 'variable'] = 'NOY'\n+ if i == 42601:\n+ df.loc[con, 'variable'] = 'NO'\n+ if i == 42603:\n+ df.loc[con, 'variable'] = 'NOX'\n+ if (i == 61103) | (i == 61101):\n+ df.loc[con, 'variable'] = 'WS'\n+ if (i == 61104) | (i == 61102):\n+ df.loc[con, 'variable'] = 'WD'\n+ if i == 62201:\n+ df.loc[con, 'variable'] = 'RH'\n+ if i == 62103:\n+ df.loc[con, 'variable'] = 'DP'\n+ return df\n+\n+ @staticmethod\n+ def change_units(df):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ df : type\n+ Description of parameter `df`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ units = df.units.unique()\n+ for i in units:\n+ con = df.units == i\n+ if i.upper() == 'Parts per billion Carbon'.upper():\n+ df.loc[con, 'units'] = 'ppbC'\n+ if i == 'Parts per billion':\n+ df.loc[con, 'units'] = 'ppb'\n+ if i == 'Parts per million':\n+ df.loc[con, 'units'] = 'ppm'\n+ if i == 'Micrograms/cubic meter (25 C)':\n+ df.loc[con, 'units'] = 'UG/M3'.lower()\n+ if i == 'Degrees Centigrade':\n+ df.loc[con, 'units'] = 'C'\n+ if i == 'Micrograms/cubic meter (LC)':\n+ df.loc[con, 'units'] = 'UG/M3'.lower()\n+ if i == 'Knots':\n+ df.loc[con, 'obs'] *= 0.51444\n+ df.loc[con, 'units'] = 'M/S'.lower()\n+ if i == 'Degrees Fahrenheit':\n+ df.loc[con, 'obs'] = (df.loc[con, 'obs'] + 459.67) * 5. / 9.\n+ df.loc[con, 'units'] = 'K'\n+ if i == 'Percent relative humidity':\n+ df.loc[con, 'units'] = '%'\n+ return df\ndiff --git a/monet/obs/cems_mod.py b/monet/obs/cems_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/cems_mod.py\n@@ -0,0 +1,537 @@\n+from __future__ import print_function\n+import os\n+import datetime\n+import pandas as pd\n+import numpy as np\n+\"\"\"\n+NAME: cems_mod.py\n+PGRMMER: Alice Crawford ORG: ARL\n+This code written at the NOAA air resources laboratory\n+Python 3\n+#################################################################\n+\"\"\"\n+\n+\n+def getdegrees(degrees, minutes, seconds):\n+ return degrees + minutes / 60.0 + seconds / 3600.00\n+\n+\n+def addmonth(dt):\n+ month = dt.month + 1\n+ year = dt.year\n+ day = dt.day\n+ hour = dt.hour\n+ if month > 12:\n+ year = dt.year + 1\n+ month = month - 12\n+ if day == 31 and month in [4, 6, 9, 11]:\n+ day = 30\n+ if month == 2 and day in [29, 30, 31]:\n+ if year % 4 == 0:\n+ day = 29\n+ else:\n+ day = 28\n+ return datetime.datetime(year, month, day, hour)\n+\n+\n+def get_date_fmt(date, verbose=False):\n+ \"\"\"Determines what format of the date is in.\n+ In some files year is first and others it is last.\n+ Parameters\n+ ----------\n+ date: str\n+ with format either YYYY-mm-DD or mm-DD-YYYY\n+ verbose: boolean\n+ if TRUE print extra information\n+ Rerturns\n+ --------\n+ fmt: str\n+ string which can be used with datetime object to give format of date\n+ string.\n+ \"\"\"\n+ if verbose:\n+ print('Determining date format')\n+ if verbose:\n+ print(date)\n+ temp = date.split('-')\n+ if len(temp[0]) == 4:\n+ fmt = \"%Y-%m-%d %H\"\n+ else:\n+ fmt = \"%m-%d-%Y %H\"\n+ return fmt\n+\n+\n+class CEMS(object):\n+ \"\"\"\n+ Class for data from continuous emission monitoring systems (CEMS).\n+ Data from power plants can be downloaded from\n+ ftp://newftp.epa.gov/DMDNLoad/emissions/\n+\n+ Attributes\n+ ----------\n+ efile : type string\n+ Description of attribute `efile`.\n+ url : type string\n+ Description of attribute `url`.\n+ info : type string\n+ Information about data.\n+ df : pandas DataFrame\n+ dataframe containing emissions data.\n+ Methods\n+ ----------\n+ __init__(self)\n+ add_data(self, rdate, states=['md'], download=False, verbose=True):\n+ load(self, efile, verbose=True):\n+ retrieve(self, rdate, state, download=True):\n+\n+ match_column(self, varname):\n+ get_var(self, varname, loc=None, daterange=None, unitid=-99, verbose=True):\n+ retrieve(self, rdate, state, download=True):\n+ create_location_dictionary(self):\n+ rename(self, ccc, newname, rcolumn, verbose):\n+ \"\"\"\n+\n+ def __init__(self):\n+ self.efile = None\n+ self.url = \"ftp://newftp.epa.gov/DmDnLoad/emissions/\"\n+ self.lb2kg = 0.453592 # number of kilograms per pound.\n+ self.info = \"Data from continuous emission monitoring systems (CEMS)\\n\"\n+ self.info += self.url + '\\n'\n+ self.df = pd.DataFrame()\n+ self.namehash = {\n+ } # if columns are renamed keeps track of original names.\n+ # Each facility may have more than one unit which is specified by the\n+ # unit id.\n+\n+ def __str__(self):\n+ return self.info\n+\n+ def add_data(self, rdate, states=['md'], download=False, verbose=True):\n+ \"\"\"\n+ gets the ftp url from the retrieve method and then\n+ loads the data from the ftp site using the load method.\n+\n+ Parameters\n+ ----------\n+ rdate : single datetime object of list of datetime objects\n+ The first datetime object indicates the month and year of the\n+ first file to retrieve.\n+ The second datetime object indicates the month and year of the\n+ last file to retrieve.\n+ states : list of strings\n+ list of two letter state identifications.\n+ download : boolean\n+ if download=True then retrieve will download the files and load\n+ will read the downloaded files.\n+ if download=False then retrieve will return the url and load\n+ will read directly from ftp site.\n+ verbose : boolean\n+ if TRUE prints out additional information.\n+ Returns\n+ -------\n+ boolean True\n+\n+ \"\"\"\n+ if isinstance(states, str):\n+ states = [states]\n+ if isinstance(rdate, list):\n+ r1 = rdate[0]\n+ r2 = rdate[1]\n+ rdatelist = [r1]\n+ done = False\n+ iii = 0\n+ while not done:\n+ r3 = addmonth(rdatelist[-1])\n+ if r3 <= r2:\n+ rdatelist.append(r3)\n+ else:\n+ done = True\n+ if iii > 100:\n+ done = True\n+ iii += 1\n+ else:\n+ rdatelist = [rdate]\n+ for rd in rdatelist:\n+ print('getting data')\n+ print(rd)\n+ for st in states:\n+ url = self.retrieve(rd, st, download=download, verbose=verbose)\n+ self.load(url, verbose=verbose)\n+ return True\n+\n+ def match_column(self, varname):\n+ \"\"\"varname is list of strings.\n+ returns column name which contains all the strings.\n+ \"\"\"\n+ columns = list(self.df.columns.values)\n+ cmatch = None\n+ for ccc in columns:\n+ # print('-----' + ccc + '------')\n+ # print( temp[ccc].unique())\n+ match = 0\n+ for vstr in varname:\n+ if vstr.lower() in ccc.lower():\n+ match += 1\n+ if match == len(varname):\n+ cmatch = ccc\n+ return cmatch\n+\n+ def cemspivot(self, varname, daterange=None, unitid=False, verbose=True):\n+ \"\"\"\n+ Parameters\n+ ----------\n+ varname: string\n+ name of column in the cems dataframe\n+ daterange: list of two datetime objects\n+ define a date range\n+ unitid: boolean.\n+ If True and unit id columns exist then these will be kept as\n+ separate columns in the pivot table.\n+ verbose: boolean\n+ if true print out extra information.\n+ Returns: pandas DataFrame object\n+ returns dataframe with rows time. Columns are (orispl_code,\n+ unit_id).\n+ If no unit_id in the file then columns are just orispl_code.\n+ if unitid flag set to False then sums over unit_id's that belong to\n+ an orispl_code. Values are from the column specified by the\n+ varname input.\n+ \"\"\"\n+\n+ from .obs_util import timefilter\n+ temp = self.df.copy()\n+ if daterange:\n+ temp = timefilter(temp, daterange)\n+ if 'unit_id' in temp.columns.values and unitid:\n+ if temp['unit_id'].unique():\n+ if verbose:\n+ print('UNIT IDs ', temp['unit_id'].unique())\n+ # create pandas frame with index datetime and columns for value for\n+ # each unit_id,orispl\n+ pivot = pd.pivot_table(\n+ temp,\n+ values=varname,\n+ index=['time'],\n+ columns=['orispl_code', 'unit_id'],\n+ aggfunc=np.sum)\n+ else:\n+ if verbose:\n+ print('NO UNIT ID')\n+ # returns data frame where rows are date and columns are the values\n+ # of cmatch for orispl\n+ pivot = pd.pivot_table(\n+ temp,\n+ values=varname,\n+ index=['time'],\n+ columns=['orispl_code'],\n+ aggfunc=np.sum)\n+ return pivot\n+\n+ def get_var(self,\n+ varname,\n+ orisp=None,\n+ daterange=None,\n+ unitid=-99,\n+ verbose=True):\n+ \"\"\"\n+ returns time series with variable indicated by varname.\n+ returns data frame where rows are date and columns are the\n+ values of cmatch for each fac_id.\n+\n+ routine looks for column which contains all strings in varname.\n+ Currently not case sensitive.\n+\n+ loc and ORISPL CODES.\n+ unitid is a unit_id\n+\n+ if a particular unitid is specified then will return values for that\n+ unit.\n+\n+\n+ Parameters\n+ ----------\n+ varname : string or iteratable of strings\n+ varname may be string or list of strings.\n+ loc : type\n+ Description of parameter `loc`.\n+ daterange : type\n+ Description of parameter `daterange`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+ \"\"\"\n+ if unitid == -99:\n+ ui = False\n+ temp = self.cemspivot(varname, daterange, unitid=ui)\n+ if not ui:\n+ return temp[orisp]\n+ else:\n+ return temp[orisp, unitid]\n+\n+ def retrieve(self, rdate, state, download=True, verbose=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ rdate : datetime object\n+ Uses year and month. Day and hour are not used.\n+ state : string\n+ state abbreviation to retrieve data for\n+ download : boolean\n+ set to True to download\n+ if download FALSE then returns string with url of ftp\n+ if download TRUE then returns name of downloaded file\n+\n+ Returns\n+ -------\n+ efile string\n+ if download FALSE then returns string with url of ftp\n+ if download TRUE then returns name of downloaded file\n+ \"\"\"\n+ # import requests\n+ # TO DO: requests does not support ftp sites.\n+ efile = 'empty'\n+ ftpsite = self.url\n+ ftpsite += 'hourly/'\n+ ftpsite += 'monthly/'\n+ ftpsite += rdate.strftime(\"%Y\") + '/'\n+ print(ftpsite)\n+ print(rdate)\n+ print(state)\n+ fname = rdate.strftime(\"%Y\") + state + rdate.strftime(\"%m\") + '.zip'\n+ if not download:\n+ efile = ftpsite + fname\n+ if not os.path.isfile(fname):\n+ # print('retrieving ' + ftpsite + fname)\n+ # r = requests.get(ftpsite + fname)\n+ # open(efile, 'wb').write(r.content)\n+ # print('retrieved ' + ftpsite + fname)\n+ efile = ftpsite + fname\n+ print('WARNING: Downloading file not supported at this time')\n+ print('you may download manually using the following address')\n+ print(efile)\n+ else:\n+ print('file exists ' + fname)\n+ efile = fname\n+ self.info += 'File retrieved :' + efile + '\\n'\n+ return efile\n+\n+ def create_location_dictionary(self, verbose=False):\n+ \"\"\"\n+ returns dictionary withe key orispl_code and value (latitude,\n+ longitude) tuple\n+ \"\"\"\n+ if 'latitude' in list(self.df.columns.values):\n+ dftemp = self.df.copy()\n+ pairs = zip(dftemp['orispl_code'],\n+ zip(dftemp['latitude'], dftemp['longitude']))\n+ pairs = list(set(pairs))\n+ lhash = dict(pairs) # key is facility id and value is name.\n+ if verbose:\n+ print(lhash)\n+ return lhash\n+ else:\n+ return False\n+\n+ def create_name_dictionary(self, verbose=False):\n+ \"\"\"\n+ returns dictionary withe key orispl_code and value facility name\n+ \"\"\"\n+ if 'latitude' in list(self.df.columns.values):\n+ dftemp = self.df.copy()\n+ pairs = zip(dftemp['orispl_code'], dftemp['facility_name'])\n+ pairs = list(set(pairs))\n+ lhash = dict(pairs) # key is facility id and value is name.\n+ if verbose:\n+ print(lhash)\n+ return lhash\n+ else:\n+ return False\n+\n+ def columns_rename(self, columns, verbose=False):\n+ \"\"\"\n+ Maps columns with one name to a standard name\n+ Parameters:\n+ ----------\n+ columns: list of strings\n+\n+ Returns:\n+ --------\n+ rcolumn: list of strings\n+ \"\"\"\n+ rcolumn = []\n+ for ccc in columns:\n+ if 'facility' in ccc.lower() and 'name' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'facility_name', rcolumn, verbose)\n+ elif 'orispl' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'orispl_code', rcolumn, verbose)\n+ elif 'facility' in ccc.lower() and 'id' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'fac_id', rcolumn, verbose)\n+ elif 'so2' in ccc.lower() and ('lbs' in ccc.lower()\n+ or 'pounds' in ccc.lower()) and (\n+ 'rate' not in ccc.lower()):\n+ rcolumn = self.rename(ccc, 'so2_lbs', rcolumn, verbose)\n+ elif 'nox' in ccc.lower() and ('lbs' in ccc.lower()\n+ or 'pounds' in ccc.lower()) and (\n+ 'rate' not in ccc.lower()):\n+ rcolumn = self.rename(ccc, 'nox_lbs', rcolumn, verbose)\n+ elif 'co2' in ccc.lower() and ('short' in ccc.lower()\n+ and 'tons' in ccc.lower()):\n+ rcolumn = self.rename(ccc, 'co2_short_tons', rcolumn, verbose)\n+ elif 'date' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'date', rcolumn, verbose)\n+ elif 'hour' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'hour', rcolumn, verbose)\n+ elif 'lat' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'latitude', rcolumn, verbose)\n+ elif 'lon' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'longitude', rcolumn, verbose)\n+ elif 'state' in ccc.lower():\n+ rcolumn = self.rename(ccc, 'state_name', rcolumn, verbose)\n+ else:\n+ rcolumn.append(ccc.strip().lower())\n+ return rcolumn\n+\n+ def rename(self, ccc, newname, rcolumn, verbose):\n+ \"\"\"\n+ keeps track of original and new column names in the namehash attribute\n+ Parameters:\n+ ----------\n+ ccc: str\n+ newname: str\n+ rcolumn: list of str\n+ verbose: boolean\n+ Returns\n+ ------\n+ rcolumn: list of str\n+ \"\"\"\n+ # dictionary with key as the newname and value as the original name\n+ self.namehash[newname] = ccc\n+ rcolumn.append(newname)\n+ if verbose:\n+ print(ccc + ' to ' + newname)\n+ return rcolumn\n+\n+ def add_info(self, dftemp):\n+ \"\"\"\n+ -------------Load supplmental data-----------------------\n+ Add location (latitude longitude) and time UTC information to dataframe\n+ dftemp.\n+ cemsinfo.csv contains info on facility id, lat, lon, time offset from\n+ UTC.\n+ allows transformation from local time to UTC.\n+ If not all power stations are found in the cemsinfo.csv file,\n+ then Nan will be written in lat, lon and 'time' column.\n+\n+ Parameters\n+ ----------\n+ dftemp: pandas dataframe\n+\n+ Returns\n+ ----------\n+ dftemp: pandas dataframe\n+ \"\"\"\n+ basedir = os.path.abspath(os.path.dirname(__file__))[:-3]\n+ iname = os.path.join(basedir, 'data', 'cemsinfo.csv')\n+ # iname = os.path.join(basedir, 'data', 'cem_facility_loc.csv')\n+ method = 1\n+ # TO DO: Having trouble with pytest throwing an error when using the\n+ # apply on the dataframe.\n+ # runs ok, but pytest fails. Tried several differnt methods.\n+ if os.path.isfile(iname):\n+ sinfo = pd.read_csv(iname, sep=',', header=0)\n+ try:\n+ dftemp.drop(['latitude', 'longitude'], axis=1, inplace=True)\n+ except Exception:\n+ pass\n+ dfnew = pd.merge(\n+ dftemp,\n+ sinfo,\n+ how='left',\n+ left_on=['orispl_code'],\n+ right_on=['orispl_code'])\n+ # print('---------z-----------')\n+ # print(dfnew.columns.values)\n+ # remove stations which do not have a time offset.\n+ dfnew.dropna(axis=0, subset=['time_offset'], inplace=True)\n+ if method == 1:\n+ # this runs ok but fails pytest\n+ def i2o(x):\n+ return datetime.timedelta(hours=x['time_offset'])\n+\n+ dfnew['time_offset'] = dfnew.apply(i2o, axis=1)\n+ dfnew['time'] = dfnew['time local'] + dfnew['time_offset']\n+ elif method == 2:\n+ # this runs ok but fails pytest\n+ def utc(x):\n+ return pd.Timestamp(x['time local']) + datetime.timedelta(\n+ hours=x['time_offset'])\n+\n+ dfnew['time'] = dfnew.apply(utc, axis=1)\n+ elif method == 3:\n+ # this runs ok but fails pytest\n+ def utc(x, y):\n+ return x + datetime.timedelta(hours=y)\n+\n+ dfnew['time'] = dfnew.apply(\n+ lambda row: utc(row['time local'], row['time_offset']),\n+ axis=1)\n+ # remove the time_offset column.\n+ dfnew.drop(['time_offset'], axis=1, inplace=True)\n+ mlist = dftemp.columns.values.tolist()\n+ # merge the dataframes back together to include rows with no info\n+ # in the cemsinfo.csv\n+ dftemp = pd.merge(\n+ dftemp, dfnew, how='left', left_on=mlist, right_on=mlist)\n+ return dftemp\n+ # return dfnew\n+\n+ def load(self, efile, verbose=True):\n+ \"\"\"\n+ loads information found in efile into a pandas dataframe.\n+ Parameters\n+ ----------\n+ efile: string\n+ name of csv file to open or url of csv file.\n+ verbose: boolean\n+ if TRUE prints out information\n+ \"\"\"\n+\n+ # pandas read_csv can read either from a file or url.\n+ dftemp = pd.read_csv(efile, sep=',', index_col=False, header=0)\n+ columns = list(dftemp.columns.values)\n+ columns = self.columns_rename(columns, verbose)\n+ dftemp.columns = columns\n+ if verbose:\n+ print(columns)\n+ dfmt = get_date_fmt(dftemp['date'][0], verbose=verbose)\n+\n+ # create column with datetime information\n+ # from column with month-day-year and column with hour.\n+ dftime = dftemp.apply(lambda x:\n+ pd.datetime.strptime(\"{0} {1}\".format(x['date'],\n+ x['hour']),\n+ dfmt), axis=1)\n+ dftemp = pd.concat([dftime, dftemp], axis=1)\n+ dftemp.rename(columns={0: 'time local'}, inplace=True)\n+ dftemp.drop(['date', 'hour'], axis=1, inplace=True)\n+\n+ # -------------Load supplmental data-----------------------\n+ # contains info on facility id, lat, lon, time offset from UTC.\n+ # allows transformation from local time to UTC.\n+ dftemp = self.add_info(dftemp)\n+\n+ if ['year'] in columns:\n+ dftemp.drop(['year'], axis=1, inplace=True)\n+ if self.df.empty:\n+ self.df = dftemp\n+ if verbose:\n+ print('Initializing pandas dataframe. Loading ' + efile)\n+ else:\n+ self.df = self.df.append(dftemp)\n+ if verbose:\n+ print('Appending to pandas dataframe. Loading ' + efile)\n+ # if verbose: print(dftemp[0:10])\n+ return dftemp\ndiff --git a/monet/obs/crn_mod.py b/monet/obs/crn_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/crn_mod.py\n@@ -0,0 +1,477 @@\n+\"\"\"\n+Data is taken from the Climate Reference Network. This is to expand validation\n+ of the NOAA ARL model validation leveraging inhouse datasets.\n+\n+ Data available at https://www.ncdc.noaa.gov/crn/qcdatasets.html\n+\n+ Here we use the hourly data.\n+\n+ Field# Name Units\n+ ---------------------------------------------\n+ 1 WBANNO XXXXX\n+ 2 UTC_DATE YYYYMMDD\n+ 3 UTC_TIME HHmm\n+ 4 LST_DATE YYYYMMDD\n+ 5 LST_TIME HHmm\n+ 6 CRX_VN XXXXXX\n+ 7 LONGITUDE Decimal_degrees\n+ 8 LATITUDE Decimal_degrees\n+ 9 T_CALC Celsius\n+ 10 T_HR_AVG Celsius\n+ 11 T_MAX Celsius\n+ 12 T_MIN Celsius\n+ 13 P_CALC mm\n+ 14 SOLARAD W/m^2\n+ 15 SOLARAD_FLAG X\n+ 16 SOLARAD_MAX W/m^2\n+ 17 SOLARAD_MAX_FLAG X\n+ 18 SOLARAD_MIN W/m^2\n+ 19 SOLARAD_MIN_FLAG X\n+ 20 SUR_TEMP_TYPE X\n+ 21 SUR_TEMP Celsius\n+ 22 SUR_TEMP_FLAG X\n+ 23 SUR_TEMP_MAX Celsius\n+ 24 SUR_TEMP_MAX_FLAG X\n+ 25 SUR_TEMP_MIN Celsius\n+ 26 SUR_TEMP_MIN_FLAG X\n+ 27 RH_HR_AVG %\n+ 28 RH_HR_AVG_FLAG X\n+ 29 SOIL_MOISTURE_5 m^3/m^3\n+ 30 SOIL_MOISTURE_10 m^3/m^3\n+ 31 SOIL_MOISTURE_20 m^3/m^3\n+ 32 SOIL_MOISTURE_50 m^3/m^3\n+ 33 SOIL_MOISTURE_100 m^3/m^3\n+ 34 SOIL_TEMP_5 Celsius\n+ 35 SOIL_TEMP_10 Celsius\n+ 36 SOIL_TEMP_20 Celsius\n+ 37 SOIL_TEMP_50 Celsius\n+ 38 SOIL_TEMP_100 Celsius\n+============================================\n+Daily Data\n+============================================\n+ Field# Name Units\n+---------------------------------------------\n+ 1 WBANNO XXXXX\n+ 2 LST_DATE YYYYMMDD\n+ 3 CRX_VN XXXXXX\n+ 4 LONGITUDE Decimal_degrees\n+ 5 LATITUDE Decimal_degrees\n+ 6 T_DAILY_MAX Celsius\n+ 7 T_DAILY_MIN Celsius\n+ 8 T_DAILY_MEAN Celsius\n+ 9 T_DAILY_AVG Celsius\n+ 10 P_DAILY_CALC mm\n+ 11 SOLARAD_DAILY MJ/m^2\n+ 12 SUR_TEMP_DAILY_TYPE X\n+ 13 SUR_TEMP_DAILY_MAX Celsius\n+ 14 SUR_TEMP_DAILY_MIN Celsius\n+ 15 SUR_TEMP_DAILY_AVG Celsius\n+ 16 RH_DAILY_MAX %\n+ 17 RH_DAILY_MIN %\n+ 18 RH_DAILY_AVG %\n+ 19 SOIL_MOISTURE_5_DAILY m^3/m^3\n+ 20 SOIL_MOISTURE_10_DAILY m^3/m^3\n+ 21 SOIL_MOISTURE_20_DAILY m^3/m^3\n+ 22 SOIL_MOISTURE_50_DAILY m^3/m^3\n+ 23 SOIL_MOISTURE_100_DAILY m^3/m^3\n+ 24 SOIL_TEMP_5_DAILY Celsius\n+ 25 SOIL_TEMP_10_DAILY Celsius\n+ 26 SOIL_TEMP_20_DAILY Celsius\n+ 27 SOIL_TEMP_50_DAILY Celsius\n+ 28 SOIL_TEMP_100_DAILY Celsius\n+\n+===============================================\n+ SUB HOURLY\n+ ==============================================\n+ Field# Name Units\n+---------------------------------------------\n+ 1 WBANNO XXXXX\n+ 2 UTC_DATE YYYYMMDD\n+ 3 UTC_TIME HHmm\n+ 4 LST_DATE YYYYMMDD\n+ 5 LST_TIME HHmm\n+ 6 CRX_VN XXXXXX\n+ 7 LONGITUDE Decimal_degrees\n+ 8 LATITUDE Decimal_degrees\n+ 9 AIR_TEMPERATURE Celsius\n+ 10 PRECIPITATION mm\n+ 11 SOLAR_RADIATION W/m^2\n+ 12 SR_FLAG X\n+ 13 SURFACE_TEMPERATURE Celsius\n+ 14 ST_TYPE X\n+ 15 ST_FLAG X\n+ 16 RELATIVE_HUMIDITY %\n+ 17 RH_FLAG X\n+ 18 SOIL_MOISTURE_5 m^3/m^3\n+ 19 SOIL_TEMPERATURE_5 Celsius\n+ 20 WETNESS Ohms\n+ 21 WET_FLAG X\n+ 22 WIND_1_5 m/s\n+ 23 WIND_FLAG X\n+\n+ \"\"\"\n+from __future__ import print_function\n+\n+import inspect\n+import os\n+from builtins import object, zip\n+\n+import pandas as pd\n+from future import standard_library\n+from numpy import array\n+\n+standard_library.install_aliases()\n+\n+\n+class crn(object):\n+ def __init__(self):\n+ self.dates = None\n+ self.daily = False\n+ self.ftp = None\n+ self.df = pd.DataFrame()\n+ self.se_states = array(\n+ ['AL', 'FL', 'GA', 'MS', 'NC', 'SC', 'TN', 'VA', 'WV'],\n+ dtype='|S14')\n+ self.ne_states = array(\n+ [\n+ 'CT', 'DE', 'DC', 'ME', 'MD', 'MA', 'NH', 'NJ', 'NY', 'PA',\n+ 'RI', 'VT'\n+ ],\n+ dtype='|S20')\n+ self.nc_states = array(\n+ ['IL', 'IN', 'IA', 'KY', 'MI', 'MN', 'MO', 'OH', 'WI'],\n+ dtype='|S9')\n+ self.sc_states = array(['AR', 'LA', 'OK', 'TX'], dtype='|S9')\n+ self.r_states = array(\n+ [\n+ 'AZ', 'CO', 'ID', 'KS', 'MT', 'NE', 'NV', 'NM', 'ND', 'SD',\n+ 'UT', 'WY'\n+ ],\n+ dtype='|S12')\n+ self.p_states = array(['CA', 'OR', 'WA'], dtype='|S10')\n+ self.objtype = 'CRN'\n+ self.monitor_file = inspect.getfile(\n+ self.__class__)[:-18] + 'data/stations.tsv'\n+ self.monitor_df = None\n+ self.baseurl = 'https://www1.ncdc.noaa.gov/pub/data/uscrn/products/'\n+ self.hcols = [\n+ 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n+ 'LONGITUDE', 'LATITUDE', 'T_CALC', 'T_AVG', 'T_MAX', 'T_MIN',\n+ 'P_CALC', 'SOLARAD', 'SOLARAD_FLAG', 'SOLARAD_MAX',\n+ 'SOLARAD_MAX_FLAG', 'SOLARAD_MIN', 'SOLARAD_MIN_FLAG',\n+ 'SUR_TEMP_TYPE', 'SUR_TEMP', 'SUR_TEMP_FLAG', 'SUR_TEMP_MAX',\n+ 'SUR_TEMP_MAX_FLAG', 'SUR_TEMP_MIN', 'SUR_TEMP_MIN_FLAG', 'RH_AVG',\n+ 'RH_AVG_FLAG', 'SOIL_MOISTURE_5', 'SOIL_MOISTURE_10',\n+ 'SOIL_MOISTURE_20', 'SOIL_MOISTURE_50', 'SOIL_MOISTURE_100',\n+ 'SOIL_TEMP_5', 'SOIL_TEMP_10', 'SOIL_TEMP_20', 'SOIL_TEMP_50',\n+ 'SOIL_TEMP_100'\n+ ]\n+ self.dcols = [\n+ 'WBANNO', 'LST_DATE', 'CRX_VN', 'LONGITUDE', 'LATITUDE', 'T_MAX',\n+ 'T_MIN', 'T_MEAN', 'T_AVG', 'P_CALC', 'SOLARAD', 'SUR_TEMP_TYPE',\n+ 'SUR_TEMP_MAX', 'SUR_TEMP_MAX', 'SUR_TEMP_MIN', 'SUR_TEMP_AVG',\n+ 'RH_MAX', 'RH_MIN', 'RH_AVG', 'SOIL_MOISTURE_5',\n+ 'SOIL_MOISTURE_10', 'SOIL_MOISTURE_20', 'SOIL_MOISTURE_50',\n+ 'SOIL_MOISTURE_100', 'SOIL_TEMP_5', 'SOIL_TEMP_10', 'SOIL_TEMP_20',\n+ 'SOIL_TEMP_50', 'SOIL_TEMP_100'\n+ ]\n+ self.shcols = [\n+ 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n+ 'LONGITUDE', 'LATITUDE', 'T_MEAN', 'P_CALC', 'SOLARAD',\n+ 'SOLARAD_FLAG', 'SUR_TEMP_AVG', 'SUR_TEMP_TYPE', 'SUR_TEMP_FLAG',\n+ 'RH_AVG', 'RH_FLAG', 'SOIL_MOISTURE_5', 'SOIL_TEMP_5', 'WETNESS',\n+ 'WET_FLAG', 'WIND', 'WIND_FLAG'\n+ ]\n+ self.citiation = 'Diamond, H. J., T. R. Karl, M. A. Palecki, C. B. Baker, J. E. Bell, R. D. Leeper, D. R. Easterling, J. H. '\n+ ' Lawrimore, T. P. Meyers, M. R. Helfert, G. Goodge, and P. W. Thorne,'\n+ ' 2013: U.S. Climate Reference Network after one decade of operations:'\n+ ' status and assessment. Bull. Amer. Meteor. Soc., 94, 489-498. '\n+ 'doi: 10.1175/BAMS-D-12-00170.1'\n+ self.citation2 = 'Bell, J. E., M. A. Palecki, C. B. Baker, W. G. '\n+ 'Collins, J. H. Lawrimore, R. D. Leeper, M. E. Hall, J. Kochendorfer, '\n+ 'T. P. Meyers, T. Wilson, and H. J. Diamond. 2013: U.S. Climate '\n+ 'Reference Network soil moisture and temperature observations. J. '\n+ 'Hydrometeorol., 14, 977-988. doi: 10.1175/JHM-D-12-0146.1'\n+\n+ def load_file(self, url):\n+ nanvals = [-99999, -9999.0]\n+ if 'CRND0103' in url:\n+ cols = self.dcols\n+ df = pd.read_csv(\n+ url,\n+ delim_whitespace=True,\n+ names=cols,\n+ parse_dates={'time_local': [1]},\n+ infer_datetime_format=True,\n+ na_values=nanvals)\n+ self.daily = True\n+ elif 'CRNS0101' in url:\n+ cols = self.shcols\n+ df = pd.read_csv(\n+ url,\n+ delim_whitespace=True,\n+ names=cols,\n+ parse_dates={\n+ 'time': ['UTC_DATE', 'UTC_TIME'],\n+ 'time_local': ['LST_DATE', 'LST_TIME']\n+ },\n+ infer_datetime_format=True,\n+ na_values=nanvals)\n+ else:\n+ cols = self.hcols\n+ df = pd.read_csv(\n+ url,\n+ delim_whitespace=True,\n+ names=cols,\n+ parse_dates={\n+ 'time': ['UTC_DATE', 'UTC_TIME'],\n+ 'time_local': ['LST_DATE', 'LST_TIME']\n+ },\n+ infer_datetime_format=True,\n+ na_values=nanvals)\n+ return df\n+\n+ def build_url(self,\n+ year,\n+ state,\n+ site,\n+ vector,\n+ daily=False,\n+ sub_hourly=False):\n+ if daily:\n+ beginning = self.baseurl + 'daily01/' + year + '/'\n+ fname = 'CRND0103-'\n+ elif sub_hourly:\n+ beginning = self.baseurl + 'subhourly01/' + year + '/'\n+ fname = 'CRNS0101-05-'\n+ else:\n+ beginning = self.baseurl + 'hourly02/' + year + '/'\n+ fname = 'CRNH0203-'\n+ rest = year + '-' + state + '_' + site + '_' + vector + '.txt'\n+ url = beginning + fname + rest\n+ fname = fname + rest\n+ return url, fname\n+\n+ @staticmethod\n+ def check_url(url):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ url : type\n+ Description of parameter `url`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import requests\n+ if requests.head(url).status_code < 400:\n+ return True\n+ else:\n+ return False\n+\n+ def build_urls(self, monitors, dates, daily=False, sub_hourly=False):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ monitors : type\n+ Description of parameter `monitors`.\n+ dates : type\n+ Description of parameter `dates`.\n+ daily : type\n+ Description of parameter `daily` (the default is False).\n+ sub_hourly : type\n+ Description of parameter `sub_hourly` (the default is False).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ print('Building and checking urls...')\n+ years = pd.DatetimeIndex(dates).year.unique().astype(str)\n+ urls = []\n+ fnames = []\n+ for i in monitors.index:\n+ for y in years:\n+ state = monitors.iloc[i].STATE\n+ site = monitors.iloc[i].LOCATION.replace(' ', '_')\n+ vector = monitors.iloc[i].VECTOR.replace(' ', '_')\n+ url, fname = self.build_url(\n+ y, state, site, vector, daily=daily, sub_hourly=sub_hourly)\n+ if self.check_url(url):\n+ urls.append(url)\n+ fnames.append(fname)\n+ print(url)\n+ return urls, fnames\n+\n+ def retrieve(self, url, fname):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ url : type\n+ Description of parameter `url`.\n+ fname : type\n+ Description of parameter `fname`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ \"\"\"rdate - datetime object. Uses year and month. Day and hour are not used.\n+ state - state abbreviation to retrieve data for\n+ Files are by year month and state.\n+ \"\"\"\n+ import wget\n+\n+ if not os.path.isfile(fname):\n+ print('Retrieving: ' + fname)\n+ print(url)\n+ print('\\n')\n+ wget.download(url)\n+ else:\n+ print('File Exists: ' + fname)\n+\n+ def add_data(self,\n+ dates,\n+ daily=False,\n+ sub_hourly=False,\n+ download=False,\n+ latlonbox=None):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ dates : type\n+ Description of parameter `dates`.\n+ daily : type\n+ Description of parameter `daily` (the default is False).\n+ sub_hourly : type\n+ Description of parameter `sub_hourly` (the default is False).\n+ download : type\n+ Description of parameter `download` (the default is False).\n+ latlonbox : type\n+ Description of parameter `latlonbox` (the default is None).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ import dask\n+ import dask.dataframe as dd\n+ if self.monitor_df is None:\n+ self.get_monitor_df()\n+ if latlonbox is not None: # get them all[latmin,lonmin,latmax,lonmax]\n+ mdf = self.monitor_df\n+ con = (mdf.LATITUDE >=\n+ latlonbox[0]) & (mdf.LATITUDE <= latlonbox[2]) & (\n+ mdf.LONGITUDE >= latlonbox[1]) & (mdf.LONGITUDE <=\n+ latlonbox[3])\n+ monitors = mdf.loc[con].copy()\n+ else:\n+ monitors = self.monitor_df.copy()\n+ urls, fnames = self.build_urls(\n+ monitors, dates, daily=daily, sub_hourly=sub_hourly)\n+ if download:\n+ for url, fname in zip(urls, fnames):\n+ self.retrieve(url, fname)\n+ dfs = [dask.delayed(self.load_file)(i) for i in fnames]\n+ else:\n+ dfs = [dask.delayed(self.load_file)(i) for i in urls]\n+ dff = dd.from_delayed(dfs)\n+ self.df = dff.compute()\n+ self.df = pd.merge(\n+ self.df,\n+ monitors,\n+ how='left',\n+ on=['WBANNO', 'LATITUDE', 'LONGITUDE'])\n+ if ~self.df.columns.isin(['time']).max():\n+ self.df['time'] = self.df.time_local + pd.to_timedelta(\n+ self.df.GMT_OFFSET, unit='H')\n+ id_vars = self.monitor_df.columns.append(\n+ pd.Index(['time', 'time_local']))\n+ keys = self.df.columns[self.df.columns.isin(id_vars)]\n+ self.df = pd.melt(\n+ self.df, id_vars=keys, var_name='variable',\n+ value_name='obs') # this stacks columns to be inline with MONET\n+ self.df.rename(columns={'WBANNO': 'siteid'}, inplace=True)\n+ self.change_units()\n+ self.df.columns = [i.lower() for i in self.df.columns]\n+\n+ def change_units(self):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ df : type\n+ Description of parameter `df`.\n+ param : type\n+ Description of parameter `param` (the default is 'O3').\n+ aqs_param : type\n+ Description of parameter `aqs_param` (the default is 'OZONE').\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ self.df['units'] = ''\n+ for i in self.df.variable.unique():\n+ if self.daily and i is 'SOLARAD':\n+ self.df.loc[self.df.variable == i, 'units'] = 'MJ/m^2'\n+ elif 'T_' in i:\n+ self.df.loc[self.df.variable == i, 'units'] = 'K'\n+ self.df.loc[self.df.variable == i, 'obs'] += 273.15\n+ elif 'FLAG' in i or 'TYPE' in i:\n+ pass\n+ elif 'TEMP' in i:\n+ self.df.loc[self.df.variable == i, 'units'] = 'K'\n+ self.df.loc[self.df.variable == i, 'obs'] += 273.15\n+ elif 'MOISTURE' in i:\n+ self.df.loc[self.df.variable == i, 'units'] = 'm^3/m^3'\n+ elif 'RH' in i:\n+ self.df.loc[self.df.variable == i, 'units'] = '%'\n+ elif 'P_CALC' is i:\n+ self.df.loc[self.df.variable == i, 'units'] = 'mm'\n+\n+ def set_daterange(self, begin='', end=''):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ begin : type\n+ Description of parameter `begin` (the default is '').\n+ end : type\n+ Description of parameter `end` (the default is '').\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ dates = pd.date_range(\n+ start=begin, end=end, freq='H').values.astype('M8[s]').astype('O')\n+ self.dates = dates\n+\n+ def get_monitor_df(self):\n+ \"\"\"Short summary.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ self.monitor_df = pd.read_csv(self.monitor_file, delimiter='\\t')\ndiff --git a/monet/obs/epa_util.py b/monet/obs/epa_util.py\n--- a/monet/obs/epa_util.py\n+++ b/monet/obs/epa_util.py\n@@ -1,9 +1,47 @@\n from __future__ import print_function\n-\n+from ..util import mystats\n from future import standard_library\n+import pandas as pd\n \n standard_library.install_aliases()\n \n+def convert_epa_unit(df, obscolumn='SO2', unit='UG/M3'):\n+ \"\"\"\n+ converts ppb to ug/m3 for SO2 in aqs and airnow datasets\n+ See 40 CFR Part 50.5, Appendix A-1 to part 50, appendix A=2 to Part 50.\n+ to convert from ppb to ug/m3 multiply by 2.6178.\n+\n+ Also will convert from ug/m3 to ppb.\n+\n+ Parameters\n+ ----------\n+ df : pandas dataframe\n+ self.df attribute from aqs or airnow class.\n+ obscolumn : string\n+ name of column with SO2 data in it.\n+ unit : string\n+ either 'UG/M3' or 'PPB' (not case sensitive)\n+ will convert data to this unit.\n+ inplace : boolean\n+ if TRUE then changes self.df attribute\n+\n+ Returns\n+ -------\n+ df : pandas dataframe\n+ returns dataframe identical to original but with data converted to new\n+ unit.\n+ \"\"\"\n+ factor = 2.6178\n+ ppb = 'ppb'\n+ ugm3 = 'ug/m3'\n+ if unit.lower() == ugm3:\n+ df = df[df['units'] == ppb] # find columns with units of 'ppb'\n+ df['units'] = unit.upper()\n+ df[obscolumn] = df[obscolumn] * factor\n+ elif unit.lower() == ppb:\n+ df = df[df['units'] == ugm3] # find columns with units of 'ppb'\n+ df[obscolumn] = df[obscolumn] / factor\n+ return df\n \n def check_cmaq_units(df, param='O3', aqs_param='OZONE'):\n \"\"\"Short summary.\n@@ -23,7 +61,8 @@ def check_cmaq_units(df, param='O3', aqs_param='OZONE'):\n Description of returned object.\n \n \"\"\"\n- aunit = df[df.Species == aqs_param].Units.unique()[0]\n+ aunit = df[df.variable == aqs_param].Units.unique()[0]\n+\n if aunit == 'UG/M3':\n fac = 1.\n elif aunit == 'PPB':\n@@ -61,13 +100,23 @@ def ensure_values_indomain(df, lon, lat):\n Description of returned object.\n \n \"\"\"\n- con = ((df.Latitude.values > lat.min()) & (df.Latitude.values < lat.max()) & (\n- df.Longitude.values > lon.min()) & (df.Longitude.values < lon.max()))\n+ con = ((df.Latitude.values > lat.min()) &\n+ (df.Latitude.values < lat.max()) &\n+ (df.Longitude.values > lon.min()) &\n+ (df.Longitude.values < lon.max()))\n+\n df = df[con].copy()\n return df\n \n \n-def write_table(self, df=None, param='OZONE', fname='table', threasholds=[70, 1e5], site=None, city=None,\n+\n+def write_table(self,\n+ df=None,\n+ param='OZONE',\n+ fname='table',\n+ threasholds=[70, 1e5],\n+ site=None,\n+ city=None,\n region=None,\n state=None,\n append=False,\n@@ -113,32 +162,36 @@ def write_table(self, df=None, param='OZONE', fname='table', threasholds=[70, 1e\n if df is None:\n print('Please provide a DataFrame')\n else:\n- df = df.groupby('Species').get_group(param)\n+ df = df.groupby('variable').get_group(param)\n if not isinstance(site, type(None)):\n try:\n- df = df.groupby('SCS').get_group(site)\n+ df = df.groupby('siteid').get_group(site)\n single = True\n name = site\n except KeyError:\n- print('Site Number not valid. Enter a valid SCS')\n+ print('Site Number not valid. Enter a valid siteid')\n return\n elif not isinstance(city, type(None)):\n try:\n single = True\n- names = df.get_group('MSA_Name').dropna().unique()\n+ names = df.get_group('msa_name').dropna().unique()\n name = [j for j in names if city.upper() in j.upper()]\n- df = df.groupby('Species').get_group(param).groupby('MSA_Name').get_group(name[0])\n+ df = df.groupby('variable').get_group(param).groupby(\n+ 'MSA_name').get_group(name[0])\n single = True\n except KeyError:\n print(' City either does not contain montiors for ' + param)\n- print(' or City Name is not valid. Enter a valid City name: df.MSA_Name.unique()')\n+ print(\n+ ' or City Name is not valid. Enter a valid City name: '\n+ 'df.msa_name.unique()')\n return\n elif not isinstance(state, type(None)):\n try:\n single = True\n- names = df.get_group('State_Name').dropna().unique()\n+ names = df.get_group('State_name').dropna().unique()\n name = [j for j in names if state.upper() in j.upper()]\n- df = df.groupby('Species').get_group(param).groupby('State_Name').get_group(name[0])\n+ df = df.groupby('variable').get_group(param).groupby(\n+ 'state_name').get_group(name[0])\n except KeyError:\n print('State not valid. Please enter valid 2 digit state')\n return\n@@ -172,9 +225,17 @@ def write_table(self, df=None, param='OZONE', fname='table', threasholds=[70, 1e\n except KeyError:\n pass\n pd.options.display.float_format = '{:,.3f}'.format\n- stats = ['Region', 'Label', 'N', 'Obs', 'Mod', 'MB', 'NMB', 'RMSE', 'R', 'IOA', 'POD', 'FAR']\n+ stats = [\n+ 'Region', 'Label', 'N', 'Obs', 'Mod', 'MB', 'NMB', 'RMSE', 'R',\n+ 'IOA', 'POD', 'FAR'\n+ ]\n if append:\n- dff = pd.read_csv(fname + '.txt', skiprows=3, index_col=0, sep='\\s+', names=stats)\n+ dff = pd.read_csv(\n+ fname + '.txt',\n+ skiprows=3,\n+ index_col=0,\n+ sep='\\s+',\n+ names=stats)\n dd = pd.concat([dd, dff]).sort_values(by=['Region'])\n \n out = StringIO()\n@@ -182,9 +243,11 @@ def write_table(self, df=None, param='OZONE', fname='table', threasholds=[70, 1e\n out.seek(0)\n with open(fname + '.txt', 'w') as f:\n if single:\n- f.write('This is the statistics table for parameter=' + param + ' for area ' + name + '\\n')\n+ f.write('This is the statistics table for parameter=' + param +\n+ ' for area ' + name + '\\n')\n else:\n- f.write('This is the statistics table for parameter=' + param + '\\n')\n+ f.write('This is the statistics table for parameter=' + param +\n+ '\\n')\n f.write('\\n')\n f.writelines(out.readlines())\n if html:\n@@ -201,7 +264,9 @@ def write_table(self, df=None, param='OZONE', fname='table', threasholds=[70, 1e\n lines = cssstyle.split('\\n')\n with open(fname + '.html', 'r') as f:\n for line in f.readlines():\n- lines.append(line.replace('class=\"dataframe\"', 'class=\"GenericTable hoverTable\"'))\n+ lines.append(\n+ line.replace('class=\"dataframe\"',\n+ 'class=\"GenericTable hoverTable\"'))\n f.close()\n with open(fname + '.html', 'w') as f:\n for line in lines:\n@@ -227,10 +292,14 @@ def get_region(df):\n from numpy import array, concatenate\n from pandas import DataFrame, merge\n se = array(['AL', 'FL', 'GA', 'MS', 'NC', 'SC', 'TN', 'VA', 'WV'])\n- ne = array(['CT', 'DE', 'DC', 'ME', 'MD', 'MA', 'NH', 'NJ', 'NY', 'PA', 'RI', 'VT'])\n+ ne = array([\n+ 'CT', 'DE', 'DC', 'ME', 'MD', 'MA', 'NH', 'NJ', 'NY', 'PA', 'RI', 'VT'\n+ ])\n nc = array(['IL', 'IN', 'IA', 'KY', 'MI', 'MN', 'MO', 'OH', 'WI'])\n sc = array(['AR', 'LA', 'OK', 'TX'])\n- r = array(['AZ', 'CO', 'ID', 'KS', 'MT', 'NE', 'NV', 'NM', 'ND', 'SD', 'UT', 'WY'])\n+ r = array([\n+ 'AZ', 'CO', 'ID', 'KS', 'MT', 'NE', 'NV', 'NM', 'ND', 'SD', 'UT', 'WY'\n+ ])\n p = array(['CA', 'OR', 'WA'])\n ner = array(['Northeast' for i in ne])\n ser = array(['Southeast' for i in se])\n@@ -240,11 +309,17 @@ def get_region(df):\n pr = array(['Pacific' for i in p])\n states = concatenate([se, ne, nc, sc, r, p])\n region = concatenate([ser, ner, ncr, scr, rr, pr])\n- dd = DataFrame({'State_Name': states, 'Region': region})\n- return merge(df, dd, how='left', on='State_Name')\n+ dd = DataFrame({'state_name': states, 'region': region})\n+ return merge(df, dd, how='left', on='state_name')\n \n \n-def get_epa_location_df(df, param, site='', city='', region='', epa_region='', state=''):\n+def get_epa_location_df(df,\n+ param,\n+ site='',\n+ city='',\n+ region='',\n+ epa_region='',\n+ state=''):\n \"\"\"Short summary.\n \n Parameters\n@@ -270,34 +345,266 @@ def get_epa_location_df(df, param, site='', city='', region='', epa_region='', s\n Description of returned object.\n \n \"\"\"\n- cityname = True\n- if 'MSA_Name' in df.columns:\n- cityname = True\n- else:\n- cityname = False\n- new = df.groupby('Species').get_group(param)\n+ new = df.groupby('variable').get_group(param)\n if site != '':\n- if site in new.SCS.unique():\n- df2 = new.loc[new.SCS == site]\n- title = df2.SCS.unique().astype('str')[0].zfill(9)\n+ if site in new.siteid.unique():\n+ df2 = new.loc[new.siteid == site]\n+ title = df2.siteid.unique().astype('str')[0].zfill(9)\n elif city != '':\n- names = df.MSA_Name.dropna().unique()\n+ names = df.msa_name.dropna().unique()\n for i in names:\n if i.upper().find(city.upper()) != -1:\n name = i\n print(name)\n- df2 = new[new['MSA_Name'] == name].copy().drop_duplicates()\n+ df2 = new[new['msa_name'] == name].copy().drop_duplicates()\n title = name\n elif state != '':\n- df2 = new[new['State_Name'].str.upper() == state.upper()].copy().drop_duplicates()\n+ df2 = new[new['state_name'].str.upper() ==\n+ state.upper()].copy().drop_duplicates()\n title = 'STATE: ' + state.upper()\n elif region != '':\n- df2 = new[new['Region'].str.upper() == region.upper()].copy().drop_duplicates()\n+ df2 = new[new['Region'].str.upper() ==\n+ region.upper()].copy().drop_duplicates()\n title = 'REGION: ' + region.upper()\n elif epa_region != '':\n- df2 = new[new['EPA_region'].str.upper() == epa_region.upper()].copy().drop_duplicates()\n+ df2 = new[new['EPA_region'].str.upper() ==\n+ epa_region.upper()].copy().drop_duplicates()\n title = 'EPA_REGION: ' + epa_region.upper()\n else:\n df2 = new\n title = 'Domain'\n return df2, title\n+\n+def regulatory_resample(df, col='model', pollutant_standard=None):\n+ from pandas import to_timedelta, concat\n+ df['time_local'] = df.time + to_timedelta(df.gmt_offset, unit='H')\n+ if df.variable.unique()[0] == 'CO':\n+ df1 = calc_daily_max(df, rolling_frequency=1)\n+ df1['pollutant_standard'] = 'CO 1-hour 1971'\n+ df2 = calc_daily_max(df, rolling_frequency=8)\n+ df2['pollutant_standard'] = 'CO 8-hour 1971'\n+ dfreturn = concat([df1, df2], ignore_index=True)\n+ elif df.variable.unique()[0] == 'OZONE':\n+ dfreturn = calc_daily_max(df, rolling_frequency=8)\n+ elif df.variable.unique()[0] == 'SO2':\n+ df1 = calc_daily_max(df, rolling_frequency=1)\n+ df1['pollutant_standard'] = 'SO2 1-hour 1971'\n+ df2 = calc_daily_max(df, rolling_frequency=3)\n+ df2['pollutant_standard'] = 'SO2 8-hour 1971'\n+ dfreturn = concat([df1, df2], ignore_index=True)\n+ elif df.variable.unique()[0] == 'NO2':\n+ dfreturn = calc_daily_max(df, rolling_frequency=1)\n+ else: # do daily average\n+ dfn = df.drop_duplicates(subset=['siteid'])\n+ df = df.groupby('siteid')[col].resample(\n+ 'D').mean().reset_index().rename(columns={'level_1': 'time_local'})\n+ dfreturn = df.merge(dfn, how='left', on='siteid')\n+ return dfreturn\n+\n+\n+def calc_daily_max(df, param=None, rolling_frequency=8):\n+ from pandas import Index, to_timedelta\n+ if param is None:\n+ temp = df.copy()\n+ else:\n+ temp = df.groupby('variable').get_group(param)\n+ temp.index = temp.time_local\n+ if rolling_frequency > 1:\n+ g = temp.groupby('siteid')['model', 'gmt_offset'].rolling(\n+ rolling_frequency, center=True, win_type='boxcar').mean()\n+ q = g.reset_index(level=0)\n+ k = q.groupby('siteid').resample('D').max().reset_index(\n+ level=1).reset_index(drop='siteid').dropna()\n+ else:\n+ k = temp.groupby('siteid')['model', 'gmt_offset'].resample(\n+ 'D').max().reset_index().rename({\n+ 'level_1': 'time_local'\n+ })\n+ columnstomerge = temp.columns[~temp.columns.isin(k.columns) *\n+ (temp.columns != 'time')].append(\n+ Index(['siteid']))\n+ if param is None:\n+ dff = k.merge(\n+ df[columnstomerge], on='siteid',\n+ how='left').drop_duplicates(subset=['siteid', 'time_local'])\n+ else:\n+ dff = k.merge(\n+ df.groupby('variable').get_group(param)[columnstomerge],\n+ on='siteid',\n+ how='left').drop_duplicates(subset=['siteid', 'time_local'])\n+ dff['time'] = dff.time_local - to_timedelta(dff.gmt_offset, unit='H')\n+ return dff\n+\n+\n+def convert_statenames_to_abv(df):\n+ d = {\n+ 'Alabama': 'AL',\n+ 'Alaska': 'AK',\n+ 'Arizona': 'AZ',\n+ 'Arkansas': 'AR',\n+ 'California': 'CA',\n+ 'Colorado': 'CO',\n+ 'Connecticut': 'CT',\n+ 'Delaware': 'DE',\n+ 'Florida': 'FL',\n+ 'Georgia': 'GA',\n+ 'Hawaii': 'HI',\n+ 'Idaho': 'ID',\n+ 'Illinois': 'IL',\n+ 'Indiana': 'IN',\n+ 'Iowa': 'IA',\n+ 'Kansas': 'KS',\n+ 'Kentucky': 'KY',\n+ 'Louisiana': 'LA',\n+ 'Maine': 'ME',\n+ 'Maryland': 'MD',\n+ 'Massachusetts': 'MA',\n+ 'Michigan': 'MI',\n+ 'Minnesota': 'MN',\n+ 'Mississippi': 'MS',\n+ 'Missouri': 'MO',\n+ 'Montana': 'MT',\n+ 'Nebraska': 'NE',\n+ 'Nevada': 'NV',\n+ 'New Hampshire': 'NH',\n+ 'New Jersey': 'NJ',\n+ 'New Mexico': 'NM',\n+ 'New York': 'NY',\n+ 'North Carolina': 'NC',\n+ 'North Dakota': 'ND',\n+ 'Ohio': 'OH',\n+ 'Oklahoma': 'OK',\n+ 'Oregon': 'OR',\n+ 'Pennsylvania': 'PA',\n+ 'Rhode Island': 'RI',\n+ 'South Carolina': 'SC',\n+ 'South Dakota': 'SD',\n+ 'state': 'Postal',\n+ 'Tennessee': 'TN',\n+ 'Texas': 'TX',\n+ 'Utah': 'UT',\n+ 'Vermont': 'VT',\n+ 'Virginia': 'VA',\n+ 'Washington': 'WA',\n+ 'West Virginia': 'WV',\n+ 'Wisconsin': 'WI',\n+ 'Wyoming': 'WY'\n+ }\n+ for i in d:\n+ df['state_name'].loc[df.state_name.isin([i])] = d[i]\n+ df['state_name'].loc[df.state_name.isin(['Canada'])] = 'CC'\n+ df['state_name'].loc[df.state_name.isin(['Mexico'])] = 'MM'\n+ return df\n+\n+\n+def read_monitor_file(network=None, airnow=False, drop_latlon=True):\n+ import pandas as pd\n+ import os\n+ if airnow:\n+ monitor_airnow_url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/today/monitoring_site_locations.dat'\n+ colsinuse = [\n+ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n+ 20, 21\n+ ]\n+ airnow = pd.read_csv(\n+ monitor_airnow_url,\n+ delimiter='|',\n+ header=None,\n+ usecols=colsinuse,\n+ dtype={0: str},\n+ encoding=\"ISO-8859-1\")\n+ airnow.columns = [\n+ 'siteid', 'Site_Code', 'Site_Name', 'Status', 'Agency',\n+ 'Agency_Name', 'EPA_region', 'latitude', 'longitude', 'Elevation',\n+ 'GMT_Offset', 'Country_Code', 'CMSA_Code', 'CMSA_Name', 'MSA_Code',\n+ 'MSA_Name', 'state_Code', 'state_Name', 'County_Code',\n+ 'County_Name', 'City_Code'\n+ ]\n+ airnow['airnow_flag'] = 'AIRNOW'\n+ airnow.columns = [i.lower() for i in airnow.columns]\n+ return airnow\n+ else:\n+ try:\n+ basedir = os.path.abspath(os.path.dirname(__file__))[:-3]\n+ fname = os.path.join(basedir, 'data',\n+ 'monitoring_site_locations.hdf')\n+ print('Monitor File Path: ' + fname)\n+ sss = pd.read_hdf(fname)\n+ # monitor_drop = ['state_code', u'county_code']\n+ # s.drop(monitor_drop, axis=1, inplace=True)\n+ except Exception:\n+ print('Monitor File Not Found... Reprocessing')\n+ baseurl = 'https://aqs.epa.gov/aqsweb/airdata/'\n+ site_url = baseurl + 'aqs_sites.zip'\n+ # has network info (CSN IMPROVE etc....)\n+ monitor_url = baseurl + 'aqs_monitors.zip'\n+ # Airnow monitor file\n+ monitor_airnow_url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/today/monitoring_site_locations.dat'\n+ colsinuse = [\n+ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n+ 19, 20, 21\n+ ]\n+ airnow = pd.read_csv(\n+ monitor_airnow_url,\n+ delimiter='|',\n+ header=None,\n+ usecols=colsinuse,\n+ dtype={0: str},\n+ encoding=\"ISO-8859-1\")\n+ airnow.columns = [\n+ 'siteid', 'Site_Code', 'Site_Name', 'Status', 'Agency',\n+ 'Agency_Name', 'EPA_region', 'latitude', 'longitude',\n+ 'Elevation', 'GMT_Offset', 'Country_Code', 'CMSA_Code',\n+ 'CMSA_Name', 'MSA_Code', 'MSA_Name', 'state_Code',\n+ 'state_Name', 'County_Code', 'County_Name', 'City_Code'\n+ ]\n+ airnow['airnow_flag'] = 'AIRNOW'\n+ airnow.columns = [i.lower() for i in airnow.columns]\n+ # Read EPA Site file\n+ site = pd.read_csv(site_url, encoding='ISO-8859-1')\n+ # read epa monitor file\n+ monitor = pd.read_csv(monitor_url, encoding='ISO-8859-1')\n+ # make siteid column\n+ site['siteid'] = site['State Code'].astype(str).str.zfill(\n+ 2) + site['County Code'].astype(str).str.zfill(\n+ 3) + site['Site Number'].astype(str).str.zfill(4)\n+ monitor['siteid'] = monitor['State Code'].astype(str).str.zfill(\n+ 2) + monitor['County Code'].astype(str).str.zfill(\n+ 3) + monitor['Site Number'].astype(str).str.zfill(4)\n+ site.columns = [i.replace(' ', '_') for i in site.columns]\n+ s = monitor.merge(\n+ site[['siteid', 'Land_Use', 'Location_Setting', 'GMT_Offset']],\n+ on=['siteid'],\n+ how='left')\n+ s.columns = [i.replace(' ', '_').lower() for i in s.columns]\n+ monitor_drop = [\n+ 'state_code', u'county_code', u'site_number',\n+ 'extraction_date', 'parameter_code', 'parameter_name', 'poc',\n+ 'last_sample_date', 'pqao', 'reporting_agency', 'exclusions',\n+ u'monitoring_objective', 'last_method_code', 'last_method',\n+ u'naaqs_primary_monitor', u'qa_primary_monitor'\n+ ]\n+ s.drop(monitor_drop, axis=1, inplace=True)\n+ # drop airnow keys for merge\n+ airnow_drop = [\n+ u'site_Code', u'site_Name', u'status', u'agency',\n+ 'agency_name', 'country_code', u'cmsa_code', 'state_code',\n+ u'county_code', u'city_code', u'latitude', u'longitude',\n+ 'gmt_offset', 'state_name', 'county_name'\n+ ]\n+ airnow_drop = [i.lower() for i in airnow_drop]\n+ airnow.drop(airnow_drop, axis=1, inplace=True)\n+ ss = pd.concat([s, airnow], ignore_index=True, sort=True)\n+ sss = convert_statenames_to_abv(ss).dropna(\n+ subset=['latitude', 'longitude'])\n+ if network is not None:\n+ sss = sss.loc[sss.networks.isin(\n+ [network])].drop_duplicates(subset=['siteid'])\n+ # Getting error that 'latitude' 'longitude' not contained in axis\n+ drop_latlon = False\n+ if drop_latlon:\n+ if pd.Series(sss.keys()).isin(['latitude', 'longitude']):\n+ return sss.drop(\n+ ['latitude', 'longitude'], axis=1).drop_duplicates()\n+ else:\n+ return sss.drop_duplicates()\ndiff --git a/monet/obs/goes.py b/monet/obs/goes.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/goes.py\n@@ -0,0 +1,55 @@\n+\"\"\" this will read the modis data\"\"\"\n+import xarray as xr\n+from ..grids import _geos_16_grid\n+\n+\n+def _get_swath_from_fname(fname):\n+ vert_grid_num = fname.split('.')[-4].split('v')[-1]\n+ hori_grid_num = fname.split('.')[-4].split('v')[0].split('h')[-1]\n+ return hori_grid_num, vert_grid_num\n+\n+\n+def _get_time_from_fname(fname):\n+ import pandas as pd\n+ u = pd.Series([fname.split('.')[-2]])\n+ date = pd.to_datetime(u, format='%Y%j%H%M%S')[0]\n+ return date\n+\n+\n+def _open_single_file(fname):\n+ # open the file\n+ dset = xr.open_dataset(fname)\n+ dset = dset.rename({'t': 'time'})\n+ # get the area def\n+ area = _geos_16_grid(dset)\n+ dset.attrs['area'] = area\n+ # get proj4 string\n+ dset.attrs['proj4_srs'] = area.proj_str\n+ # get longitude and latitudes\n+ lon, lat = area.get_lonlats_dask()\n+ dset.coords['longitude'] = (('y', 'x'), lon)\n+ dset.coords['latitude'] = (('y', 'x'), lat)\n+\n+ for i in dset.variables:\n+ dset[i].attrs['proj4_srs'] = area.proj_str\n+ dset[i].attrs['area'] = area\n+\n+ # expand dimensions for time\n+ dset = dset.expand_dims('time')\n+ return dset\n+\n+\n+def open_files(fname):\n+\n+ if isinstance(fname, str):\n+ # single file\n+ dset = _open_single_file(fname)\n+ else:\n+ # loop over dsets and combine\n+ dsets = []\n+ for i in fname:\n+ dsets.append(_open_single_file(i))\n+\n+ dset = xr.auto_combine(dsets, concat_dim='time')\n+\n+ return dset\ndiff --git a/monet/obs/icartt.py b/monet/obs/icartt.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/icartt.py\n@@ -0,0 +1,29 @@\n+\"\"\" This module opens data from the ICARTT format and reformats it for use in\n+MONET. The module makes use of Barron Henderson's PseudoNetCDF\n+(https://github.com/barronh/pseudonetcdf)and xarray to read the data. It is\n+noti ntended to read more than ONE file at a time \"\"\"\n+\n+import xarray as xr\n+from pandas import Series, Timestamp, to_timedelta\n+\n+possible_lats = [\n+ 'Lat', 'Latitude', 'lat', 'latitude', 'Latitude_Deg', 'Latitude_deg',\n+ 'Lat_deg', 'Lat_degree', 'Lat_Degree'\n+]\n+possible_lons = [\n+ 'Lon', 'Longitude', 'lon', 'longitude', 'Longitude_Deg', 'Longitude_deg',\n+ 'Lon_deg', 'Lon_degree', 'Lon_Degree', 'Long', 'Long_Deg'\n+]\n+\n+# TODO: def add_data(fname, time_label='UTC', lat_label=None, lon_label=None):\n+# dset = xr.open_dataset(fname, engine='pseudonetcdf')\n+# vars = Series(dset.variables)\n+# if lat_label is None and lon_label is None:\n+# if vars.isin(possible_lats).max():\n+# latvar = vars.loc[vars.isin(possible_lats)][0]\n+# lonvar = vars.loc[vars.isin(possible_lons)][0]\n+# dset.coords['longitude'] = dset[lonvar]\n+# dset.coords['latitude'] = dset[latvar]\n+# # get the datetimes\n+# start = dset.SDATE.replace(', ', '-')\n+# time = Timestamp(start) + to_timedelta(dset[time_name])\ndiff --git a/monet/obs/improve_mod.py b/monet/obs/improve_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/improve_mod.py\n@@ -0,0 +1,176 @@\n+from __future__ import print_function\n+\n+from builtins import object\n+\n+import pandas as pd\n+from numpy import NaN\n+\n+\n+class IMPROVE(object):\n+ \"\"\"Short summary.\n+\n+ Attributes\n+ ----------\n+ datestr : type\n+ Description of attribute `datestr`.\n+ df : type\n+ Description of attribute `df`.\n+ daily : type\n+ Description of attribute `daily`.\n+ se_states : type\n+ Description of attribute `se_states`.\n+ ne_states : type\n+ Description of attribute `ne_states`.\n+ nc_states : type\n+ Description of attribute `nc_states`.\n+ sc_states : type\n+ Description of attribute `sc_states`.\n+ r_states : type\n+ Description of attribute `r_states`.\n+ p_states : type\n+ Description of attribute `p_states`.\n+\n+ \"\"\"\n+\n+ def __init__(self):\n+ self.datestr = []\n+ self.df = None\n+ self.daily = True\n+\n+ def add_data(self, fname, add_meta=False, delimiter='\\t'):\n+ \"\"\" This assumes that you have downloaded the data from\n+ http://views.cira.colostate.edu/fed/DataWizard/Default.aspx\n+ The data is the IMPROVE Aerosol dataset\n+ Any number of sites\n+ Parameters included are All\n+ Fields include Dataset,Site,Date,Parameter,POC,Data_value,Unit,\n+ Latitude,Longitude,State,EPA Site Code Options are delimited\n+ ',' data only and normalized skinny format\n+\n+ Parameters\n+ ----------\n+ fname : type\n+ Description of parameter `fname`.\n+ output : type\n+ Description of parameter `output` (the default is '').\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from .epa_util import read_monitor_file\n+ f = open(fname, 'r')\n+ lines = f.readlines()\n+ skiprows = 0\n+ skip = False\n+ for i, line in enumerate(lines):\n+ if line == 'Data\\n':\n+ skip = True\n+ skiprows = i + 1\n+ break\n+ # if meta data is inlcuded\n+ if skip:\n+ df = pd.read_csv(\n+ fname,\n+ delimiter=delimiter,\n+ parse_dates=[2],\n+ infer_datetime_format=True,\n+ dtype={'EPACode': str},\n+ skiprows=skiprows)\n+ else:\n+ df = pd.read_csv(\n+ fname,\n+ delimiter=delimiter,\n+ parse_dates=[2],\n+ infer_datetime_format=True,\n+ dtype={'EPACode': str})\n+ df.rename(columns={'EPACode': 'epaid'}, inplace=True)\n+ df.rename(columns={'Val': 'Obs'}, inplace=True)\n+ df.rename(columns={'State': 'state_name'}, inplace=True)\n+ df.rename(columns={'ParamCode': 'variable'}, inplace=True)\n+ df.rename(columns={'SiteCode': 'siteid'}, inplace=True)\n+ df.rename(columns={'Unit': 'Units'}, inplace=True)\n+ df.rename(columns={'Date': 'time'}, inplace=True)\n+ df.drop('Dataset', axis=1, inplace=True)\n+ df['time'] = pd.to_datetime(df.time, format='%Y%m%d')\n+ df.columns = [i.lower() for i in df.columns]\n+ if pd.Series(df.keys()).isin(['epaid']).max():\n+ df['epaid'] = df.epaid.astype(str).str.zfill(9)\n+ if add_meta:\n+ monitor_df = read_monitor_file(network='IMPROVE') # .drop(\n+ # dropkeys, axis=1)\n+ df = df.merge(\n+ monitor_df, how='left', left_on='epaid', right_on='siteid')\n+ df.drop(['siteid_y', 'state_name_y'], inplace=True, axis=1)\n+ df.rename(\n+ columns={\n+ 'siteid_x': 'siteid',\n+ 'state_name_x': 'state_name'\n+ },\n+ inplace=True)\n+\n+ try:\n+ df.obs.loc[df.obs < df.mdl] = NaN\n+ except Exception:\n+ df.obs.loc[df.obs < -900] = NaN\n+ self.df = df\n+ return df.copy()\n+\n+ def load_hdf(self, fname, dates):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ fname : type\n+ Description of parameter `fname`.\n+ dates : type\n+ Description of parameter `dates`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ self.df = pd.read_hdf(fname)\n+ self.get_date_range(self.dates)\n+\n+ def get_date_range(self, dates):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ dates : type\n+ Description of parameter `dates`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ self.dates = dates\n+ con = (self.df.time >= dates[0]) & (self.df.time <= dates[-1])\n+ self.df = self.df.loc[con]\n+\n+ def set_daterange(self, begin='', end=''):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ begin : type\n+ Description of parameter `begin` (the default is '').\n+ end : type\n+ Description of parameter `end` (the default is '').\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ dates = pd.date_range(\n+ start=begin, end=end, freq='H').values.astype('M8[s]').astype('O')\n+ self.dates = dates\ndiff --git a/monet/obs/ish_mod.py b/monet/obs/ish_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/ish_mod.py\n@@ -0,0 +1,278 @@\n+\"\"\"Python module for reading NOAA ISH files\"\"\"\n+from __future__ import division, print_function\n+from builtins import object, zip\n+\n+import dask\n+import dask.dataframe as dd\n+import numpy as np\n+import pandas as pd\n+from dask.diagnostics import ProgressBar\n+from future import standard_library\n+from past.utils import old_div\n+\n+standard_library.install_aliases()\n+\n+ProgressBar().register()\n+\n+\n+class ISH(object):\n+ \"\"\"\n+ Integrated Surface Hourly (also known as ISD, Integrated Surface Data)\n+ \"\"\"\n+\n+ def __init__(self):\n+ self.WIDTHS = [\n+ 4, 11, 8, 4, 1, 6, 7, 5, 5, 5, 4, 3, 1, 1, 4, 1, 5, 1, 1, 1, 6, 1,\n+ 1, 1, 5, 1, 5, 1, 5, 1\n+ ]\n+ self.DTYPES = [('varlength', 'i2'), ('station_id',\n+ 'S11'), ('date', 'i4'), ('htime',\n+ 'i2'),\n+ ('source_flag',\n+ 'S1'), ('latitude', 'float'), ('longitude', 'float'),\n+ ('code', 'S5'), ('elev', 'i2'), ('call_letters', 'S5'),\n+ ('qc_process',\n+ 'S4'), ('wdir', 'i2'), ('wdir_quality',\n+ 'S1'), ('wdir_type',\n+ 'S1'), ('ws', 'i2'),\n+ ('ws_quality',\n+ 'S1'), ('ceiling',\n+ 'i4'), ('ceiling_quality',\n+ 'S1'), ('ceiling_code',\n+ 'S1'), ('ceiling_cavok',\n+ 'S1'), ('vsb', 'i4'),\n+ ('vsb_quality',\n+ 'S1'), ('vsb_variability',\n+ 'S1'), ('vsb_variability_quality',\n+ 'S1'), ('t', 'i2'), ('t_quality',\n+ 'S1'),\n+ ('dpt', 'i2'), ('dpt_quality',\n+ 'S1'), ('p', 'i4'), ('p_quality', 'S1')]\n+ self.NAMES, _ = list(zip(*self.DTYPES))\n+ self.history_file = 'https://www1.ncdc.noaa.gov/pub/data/noaa/'\n+ 'isd-history.csv'\n+ self.history = None\n+ self.daily = False\n+\n+ def delimit(self, file_object, delimiter=','):\n+ \"\"\"Iterate over the lines in a file yielding comma delimited versions.\n+\n+ Arguments\n+ ---------\n+ file_object : file or filename\n+\n+ \"\"\"\n+\n+ try:\n+ file_object = open(file_object)\n+ except TypeError:\n+ pass\n+\n+ for line in file_object:\n+ items = []\n+ index = 0\n+ for w in self.WIDTHS:\n+ items.append(line[index:index + w])\n+ index = index + w\n+ yield ','.join(items)\n+\n+ def _clean_column(self, series, missing=9999, multiplier=1):\n+ series = series.apply(float)\n+ series[series == missing] = np.nan\n+ return old_div(series, multiplier)\n+\n+ def _clean_column_by_name(self, frame, name, *args, **kwargs):\n+ frame[name] = self._clean_column(frame[name], *args, **kwargs)\n+ return frame\n+\n+ def _clean(self, frame):\n+ \"\"\"Clean up the data frame\"\"\"\n+\n+ # index by time\n+ frame['time'] = [\n+ pd.Timestamp('{:08}{:04}'.format(date, htime))\n+ for date, htime in zip(frame['date'], frame['htime'])\n+ ]\n+ # these fields were combined into 'time'\n+ frame.drop(['date', 'htime'], axis=1, inplace=True)\n+ frame.set_index('time', drop=True, inplace=True)\n+ frame = self._clean_column_by_name(frame, 'wdir', missing=999)\n+ frame = self._clean_column_by_name(frame, 'ws', multiplier=10)\n+ frame = self._clean_column_by_name(frame, 'ceiling', missing=99999)\n+ frame = self._clean_column_by_name(frame, 'vsb', missing=999999)\n+ frame = self._clean_column_by_name(frame, 't', multiplier=10)\n+ frame = self._clean_column_by_name(frame, 'dpt', multiplier=10)\n+ frame = self._clean_column_by_name(\n+ frame, 'p', multiplier=10, missing=99999)\n+ return frame\n+\n+ def read_data_frame(self, file_object):\n+ \"\"\"Create a data frame from an ISH file.\"\"\"\n+ frame_as_array = np.genfromtxt(\n+ file_object, delimiter=self.WIDTHS, dtype=self.DTYPES)\n+ frame = pd.DataFrame.from_records(frame_as_array)\n+ df = self._clean(frame)\n+ df.drop(['latitude', 'longitude'], axis=1, inplace=True)\n+ # df.latitude = self.history.groupby('station_id').get_group(\n+ # df.station_id[0]).LAT.values[0]\n+ # df.longitude = self.history.groupby('station_id').get_group(\n+ # df.station_id[0]).lon.values[0]\n+ # df['STATION_NAME'] = self.history.groupby('station_id').get_group(\n+ # df.station_id[0])['STATION NAME'].str.strip().values[0]\n+ index = (df.index >= self.dates.min()) & (df.index <= self.dates.max())\n+\n+ return df.loc[index, :].reset_index()\n+\n+ def read_ish_history(self):\n+ \"\"\" read ISH history file \"\"\"\n+ fname = self.history_file\n+ self.history = pd.read_csv(\n+ fname, parse_dates=['BEGIN', 'END'], infer_datetime_format=True)\n+ self.history.columns = [i.lower() for i in self.history.columns]\n+\n+ index1 = (self.history.end >= self.dates.min()) & (self.history.begin\n+ <= self.dates.max())\n+ self.history = self.history.loc[index1, :].dropna(\n+ subset=['lat', 'lon'])\n+\n+ self.history.loc[:, 'usaf'] = self.history.usaf.astype(\n+ 'str').str.zfill(6)\n+ self.history.loc[:, 'wban'] = self.history.wban.astype(\n+ 'str').str.zfill(5)\n+ self.history['station_id'] = self.history.usaf + self.history.wban\n+ self.history.rename(\n+ columns={\n+ 'lat': 'latitude',\n+ 'lon': 'longitude'\n+ }, inplace=True)\n+\n+ def subset_sites(self,\n+ latmin=32.65,\n+ lonmin=-113.3,\n+ latmax=34.5,\n+ lonmax=-110.4):\n+ \"\"\" find sites within designated region\"\"\"\n+ latindex = (self.history.latitude >= latmin) & (self.history.latitude\n+ <= latmax)\n+ lonindex = (self.history.longitude >= lonmin) & (self.history.longitude\n+ <= lonmax)\n+ dfloc = self.history.loc[latindex & lonindex, :]\n+ print('SUBSET')\n+ print(dfloc.latitude.unique())\n+ print(dfloc.longitude.unique())\n+ return dfloc\n+\n+ def add_data(self,\n+ dates,\n+ box=None,\n+ country=None,\n+ state=None,\n+ site=None,\n+ resample=True,\n+ window='H'):\n+ \"\"\"\n+ dates : list of datetime objects\n+ description\n+ box : list of floats\n+ [latmin, lonmin, latmax, lonmax]\n+ country :\n+ state :\n+ site :\n+ resample : boolean\n+ window :\n+ \"\"\"\n+ from numpy import NaN\n+ self.dates = pd.to_datetime(dates)\n+ idate = dates[0]\n+ year = idate.strftime('%Y')\n+ url = 'https://www1.ncdc.noaa.gov/pub/data/noaa/' + year + '/'\n+ if self.history is None:\n+ self.read_ish_history()\n+ self.history['fname'] = url + self.history.usaf + \\\n+ '-' + self.history.wban + '-' + year + '.gz'\n+ dfloc = self.history.copy()\n+ # if isinstance(box, None): # type(box) is not type(None):\n+ if box is not None: # type(box) is not type(None):\n+ print('Retrieving Sites in: ' + ' '.join(map(str, box)))\n+ dfloc = self.subset_sites(\n+ latmin=box[0], lonmin=box[1], latmax=box[2], lonmax=box[3])\n+ elif country is not None:\n+ print('Retrieving Country: ' + country)\n+ dfloc = self.history.loc[self.history.ctry == country, :]\n+ elif state is not None:\n+ print('Retrieving State: ' + state)\n+ dfloc = self.history.loc[self.history.STATE == state, :]\n+ elif site is not None:\n+ print('Retrieving Site: ' + site)\n+ dfloc = self.history.loc[self.history.station_id == site, :]\n+ print(dfloc.fname.unique())\n+ objs = self.get_url_file_objs(dfloc.fname.unique())\n+ # return objs,size,self.history.fname\n+ # dfs = []\n+ # for f in objs:\n+ # try:\n+ # dfs.append(self.read_data_frame(f))\n+ # except:\n+ # pass\n+\n+ print(' Reading ISH into pandas DataFrame...')\n+ dfs = [dask.delayed(self.read_data_frame)(f) for f in objs]\n+ dff = dd.from_delayed(dfs)\n+ self.df = dff.compute()\n+ self.df.loc[self.df.vsb == 99999, 'vsb'] = NaN\n+ if resample:\n+ print(' Resampling to every ' + window)\n+ self.df.index = self.df.time\n+ self.df = self.df.groupby('station_id').resample(\n+ 'H').mean().reset_index()\n+ # this was encoded as byte literal but in dfloc it is a string so could\n+ # not merge on station_id correctly.\n+ try:\n+ self.df['station_id'] = self.df['station_id'].str.decode(\"utf-8\")\n+ except RuntimeError:\n+ pass\n+ self.df = self.df.merge(\n+ dfloc[['station_id', 'latitude', 'longitude', 'station name']],\n+ on=['station_id'],\n+ how='left')\n+\n+ return self.df.copy()\n+\n+ def get_url_file_objs(self, fname):\n+ \"\"\"\n+\n+ \"\"\"\n+ import gzip\n+ import shutil\n+ import requests\n+ objs = []\n+ print(' Constructing ISH file objects from urls...')\n+ mmm = 0\n+ jjj = 0\n+ for iii in fname:\n+ # print i\n+ try:\n+ r2 = requests.get(iii, stream=True)\n+ temp = iii.split('/')\n+ temp = temp[-1]\n+ fname = 'isd.' + temp.replace('.gz', '')\n+ if r2.status_code != 404:\n+ objs.append(fname)\n+ with open(fname, 'wb') as fid:\n+ # TODO. currently shutil writes the file to the hard\n+ # drive. try to find way around this step, so file does\n+ # not need to be written and then read.\n+ gzip_file = gzip.GzipFile(fileobj=r2.raw)\n+ shutil.copyfileobj(gzip_file, fid)\n+ print('SUCCEEDED REQUEST for ' + iii)\n+ else:\n+ print('404 message ' + iii)\n+ mmm += 1\n+ except RuntimeError:\n+ jjj += 1\n+ print('REQUEST FAILED ' + iii)\n+ pass\n+ if jjj > 100:\n+ print('Over ' + str(jjj) + ' failed. break loop')\n+ break\n+ return objs\ndiff --git a/monet/obs/modis_swath.py b/monet/obs/modis_swath.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/modis_swath.py\n@@ -0,0 +1,36 @@\n+# MODIS Swath data\n+\"\"\" this will read the modis data\"\"\"\n+import xarray as xr\n+from ..grids import get_modis_latlon_from_swath_hv, get_sinu_area_def\n+\n+\n+def _get_swath_from_fname(fname):\n+ vert_grid_num = fname.split('.')[-4].split('v')[-1]\n+ hori_grid_num = fname.split('.')[-4].split('v')[0].split('h')[-1]\n+ return hori_grid_num, vert_grid_num\n+\n+\n+def _get_time_from_fname(fname):\n+ import pandas as pd\n+ u = pd.Series([fname.split('.')[-2]])\n+ date = pd.to_datetime(u, format='%Y%j%H%M%S')[0]\n+ return date\n+\n+\n+def open_single_file(fname):\n+ # first get the h,v from the file name\n+ h, v = _get_swath_from_fname(fname)\n+ # get the grid boundary\n+ timestamp = _get_time_from_fname(fname)\n+ # open the dataset\n+ dset = xr.open_dataset(fname)\n+ # rename x and y dimensions\n+ dset = dset.rename({'XDim:MOD_Grid_BRDF': 'x', 'YDim:MOD_Grid_BRDF': 'y'})\n+ # get lat lon from dset and h, v\n+ dset = get_modis_latlon_from_swath_hv(h, v, dset)\n+ # get the area_def\n+ dset.attrs['area'] = get_sinu_area_def(dset)\n+ # set the time\n+ dset['time'] = timestamp\n+\n+ return dset\ndiff --git a/monet/obs/nadp_mod.py b/monet/obs/nadp_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/nadp_mod.py\n@@ -0,0 +1,186 @@\n+\"\"\" READS NAPD DATA \"\"\"\n+from __future__ import division, print_function\n+\n+from builtins import object\n+\n+import pandas as pd\n+from numpy import NaN\n+\n+\n+class NADP(object):\n+ def __init__(self):\n+ self.weekly = True\n+ self.network = None\n+ self.df = pd.DataFrame()\n+ self.objtype = 'NADP'\n+ self.url = None\n+\n+ def build_url(self, network='NTN', siteid=None):\n+ baseurl = 'http://nadp.slh.wisc.edu/datalib/'\n+ if siteid is not None:\n+ siteid = siteid.upper() + '-'\n+ else:\n+ siteid = ''\n+ if network.lower() == 'amnet':\n+ url = 'http://nadp.slh.wisc.edu/datalib/AMNet/AMNet-All.zip'\n+ elif network.lower() == 'amon':\n+ url = 'http://nadp.slh.wisc.edu/dataLib/AMoN/csv/all-ave.csv'\n+ elif network.lower() == 'airmon':\n+ url = 'http://nadp.slh.wisc.edu/datalib/AIRMoN/AIRMoN-ALL.csv'\n+ else:\n+ if self.weekly:\n+ url = baseurl + network.lower(\n+ ) + '/weekly/' + siteid + network.upper() + '-All-w.csv'\n+ else:\n+ url = baseurl + network.lower(\n+ ) + '/annual/' + siteid + network.upper() + '-All-a.csv'\n+ return url\n+\n+ def network_names(self):\n+ print('Available Networks: AMNET, NTN, MDN, AIRMON, AMON')\n+\n+ def read_ntn(self, url):\n+ print('Reading NADP-NTN Data...')\n+ print(url)\n+ # header = self.get_columns()\n+ df = pd.read_csv(url, infer_datetime_format=True, parse_dates=[2, 3])\n+ df.columns = [i.lower() for i in df.columns]\n+ df.rename(\n+ columns={\n+ 'dateon': 'time',\n+ 'dateoff': 'time_off'\n+ }, inplace=True)\n+ try:\n+ meta = pd.read_csv('https://bit.ly/2sPMvaO')\n+ except RuntimeError:\n+ meta = pd.read_csv(self.__path__ + '/../../data/ntn-sites.csv')\n+ meta.columns = [i.lower() for i in meta.columns]\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ dfn = pd.merge(df, meta, on='siteid', how='left')\n+ dfn.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ dfn.loc[(dfn.flagmg == '<') | (dfn.mg < 0), 'mg'] = NaN\n+ dfn.loc[(dfn.flagbr == '<') | (dfn.br < 0), 'br'] = NaN\n+ dfn.loc[(dfn.flagso4 == '<') | (dfn.so4 < 0), 'so4'] = NaN\n+ dfn.loc[(dfn.flagcl == '<') | (dfn.cl < 0), 'cl'] = NaN\n+ dfn.loc[(dfn.flagno3 == '<') | (dfn.no3 < 0), 'no3'] = NaN\n+ dfn.loc[(dfn.flagnh4 == '<') | (dfn.nh4 < 0), 'nh4'] = NaN\n+ dfn.loc[(dfn.flagk == '<') | (dfn.k < 0), 'k'] = NaN\n+ dfn.loc[(dfn.flagna == '<') | (dfn.na < 0), 'na'] = NaN\n+ dfn.loc[(dfn.flagca == '<') | (dfn.ca < 0), 'ca'] = NaN\n+ return dfn\n+\n+ def read_mdn(self, url):\n+ print('Reading NADP-MDN Data...')\n+ # header = self.get_columns()\n+ df = pd.read_csv(url, infer_datetime_format=True, parse_dates=[1, 2])\n+ df.columns = [i.lower() for i in df.columns]\n+ df.rename(\n+ columns={\n+ 'dateon': 'time',\n+ 'dateoff': 'time_off'\n+ }, inplace=True)\n+ try:\n+ meta = pd.read_csv('https://bit.ly/2Lq6kgq')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ except RuntimeError:\n+ meta = pd.read_csv(self.__path__ + '/../../data/mdn-sites.csv')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ meta.columns = [i.lower() for i in meta.columns]\n+ dfn = pd.merge(df, meta, on='siteid', how='left')\n+ dfn.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ dfn.loc[dfn.qr == 'C', ['rgppt', 'svol', 'subppt', 'hgconc', 'hgdep'\n+ ]] = NaN\n+ return dfn\n+\n+ def read_airmon(self, url):\n+ print('Reading NADP-AIRMoN Data...')\n+ # header = self.get_columns()\n+ df = pd.read_csv(url, infer_datetime_format=True, parse_dates=[2, 3])\n+ df.columns = [i.lower() for i in df.columns]\n+ df.rename(\n+ columns={\n+ 'dateon': 'time',\n+ 'dateoff': 'time_off'\n+ }, inplace=True)\n+ try:\n+ meta = pd.read_csv('https://bit.ly/2xMlgTW')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ except RuntimeError:\n+ meta = pd.read_csv(self.__path__ + '/../../data/airmon-sites.csv')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ meta.columns = [i.lower() for i in meta.columns]\n+ dfn = pd.merge(df, meta, on='siteid', how='left')\n+ dfn.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ dfn.loc[dfn.qrcode == 'C', [\n+ 'subppt', 'pptnws', 'pptbel', 'svol', 'ca', 'mg', 'k', 'na', 'nh4',\n+ 'no3', 'cl', 'so4', 'po4', 'phlab', 'phfield', 'conduclab',\n+ 'conducfield'\n+ ]] = NaN\n+ return dfn\n+\n+ def read_amon(self, url):\n+ print('Reading NADP-AMoN Data...')\n+ # header = self.get_columns()\n+ df = pd.read_csv(url, infer_datetime_format=True, parse_dates=[2, 3])\n+ df.columns = [i.lower() for i in df.columns]\n+ df.rename(\n+ columns={\n+ 'startdate': 'time',\n+ 'enddate': 'time_off'\n+ }, inplace=True)\n+ try:\n+ meta = pd.read_csv('https://bit.ly/2sJmkCg')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ except RuntimeError:\n+ meta = pd.read_csv(self.__path__ + '/../../data/amon-sites.csv')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ meta.columns = [i.lower() for i in meta.columns]\n+ dfn = pd.merge(df, meta, on='siteid', how='left')\n+ dfn.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ dfn.loc[dfn.qr == 'C', ['airvol', 'conc']] = NaN\n+ return dfn\n+\n+ def read_amnet(self, url):\n+ print('Reading NADP-AMNet Data...')\n+ # header = self.get_columns()\n+ df = pd.read_csv(url, infer_datetime_format=True, parse_dates=[2, 3])\n+ df.columns = [i.lower() for i in df.columns]\n+ df.rename(\n+ columns={\n+ 'startdate': 'time',\n+ 'enddate': 'time_off'\n+ }, inplace=True)\n+ try:\n+ meta = pd.read_csv('https://bit.ly/2sJmkCg')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ except RuntimeError:\n+ meta = pd.read_csv(self.__path__ + '/../../data/amnet-sites.csv')\n+ meta.drop(['startdate', 'stopdate'], axis=1, inplace=True)\n+ meta.columns = [i.lower() for i in meta.columns]\n+ dfn = pd.merge(df, meta, on='siteid', how='left')\n+ dfn.dropna(subset=['latitude', 'longitude'], inplace=True)\n+ dfn.loc[dfn.qr == 'C', ['airvol', 'conc']] = NaN\n+ return dfn\n+\n+ def add_data(self, dates, network='NTN', siteid=None, weekly=True):\n+ url = self.build_url(network=network, siteid=siteid)\n+ if network.lower() == 'ntn':\n+ df = self.read_ntn(url)\n+ elif network.lower() == 'mdn':\n+ df = self.read_mdn(url)\n+ elif network.lower() == 'amon':\n+ df = self.read_amon(url)\n+ elif network.lower() == 'airmon':\n+ df = self.read_airmon(url)\n+ else:\n+ df = self.read_amnet(url)\n+ self.df = df\n+ self.df = self.df.loc[(self.df.time >= dates.min())\n+ & (self.df.time_off <= dates.max())]\n+\n+ return df\n+\n+ def set_daterange(self, begin='', end=''):\n+ dates = pd.date_range(start=begin, end=end, freq='H')\n+ self.dates = dates\n+ return dates\ndiff --git a/monet/obs/obs_util.py b/monet/obs/obs_util.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/obs_util.py\n@@ -0,0 +1,199 @@\n+\"\"\" Obs Utilities \"\"\"\n+\n+from __future__ import print_function\n+import numpy as np\n+import datetime\n+import sys\n+\n+\n+def find_near(df, latlon, distance=100, sid='site_num', drange=None):\n+ \"\"\"find all values in the df dataframe column sid which are within distance\n+ (km) of lat lon point. output dictionary with key as value in column sid\n+ and value tuple (latitude, longitude)\n+\n+ Parameters\n+ ----------\n+ latlon : tuple or list\n+ (longitude, latitude)\n+ distance : float\n+ kilometers\n+ sid: string\n+ name of column\n+ drange: tuple or list with two datetimes\n+ consider rows with dates between these two dates.\n+\n+ Returns\n+ --------\n+ lhash: dictionary\n+ key is the value in column sid and value is (latitude, longitude)\n+ position.\n+ \"\"\"\n+ degree2km = 111\n+ if drange:\n+ df = timefilter(df.copy(), drange)\n+ lhash = get_lhash(df, sid)\n+ for key in lhash.keys:\n+ xd = (lhash[key][1] - latlon[1]) * degree2km * np.cos(\n+ latlon[1] * np.pi / 180.0)\n+ yd = (lhash[key][0] - latlon[0]) * degree2km\n+ dd = (xd**2 + yd**2)**0.5\n+ if dd > distance:\n+ lhash.pop(key, None)\n+ return lhash\n+\n+\n+def write_datem(df,\n+ obscolumn='obs',\n+ dname='datemfile.txt',\n+ sitename='1',\n+ info=None,\n+ drange=None):\n+ \"\"\"returns string in datem format (See NOAA ARL).\n+ datem format has the following columns:\n+ Year, Month, Day, Hour, Duration, lat, lon, Concentration (units), site\n+ id, height\n+\n+ Parameters\n+ ----------\n+ obscolumn : string\n+ name of column with values to write in the Concentration column.\n+ dname : string\n+ name of the output file.\n+ sitename : string.\n+ If it is the name of a column in the dataframe then\n+ that column will be used to generate the site name column in the\n+ datem file. If is not the name of a column, then the string will\n+ be used as the site name.\n+ info : string\n+ will be written to the second line of the header.\n+ drange : list of two time stamp objects.\n+ Returns\n+ --------\n+ runstring: string\n+ string in datem format.\n+ \"\"\"\n+ if drange:\n+ df = timefilter(df, drange)\n+\n+ units = df['units'].tolist()\n+ units = list(set(units))\n+ sdate = datetime.datetime(2010, 1, 1, 0)\n+ if len(units) > 1:\n+ print('WARNING, more than one type of unit ', units)\n+ ustr = ''\n+ for uuu in units:\n+ ustr += uuu + ' '\n+ runstring = \"Beginning date \" + sdate.strftime(\n+ \"%Y %m %d %H:%M\") + \" UTC ---\"\n+ runstring += 'Information '\n+ if info:\n+ runstring += info + \"\\n\"\n+ else:\n+ runstring += \"\\n\"\n+ runstring += 'Year, Month, Day, Hour:Minute (UTC), Dur(hhmm) , LAT, LON, Concentration (' + \\\n+ ustr + \"), sid, height\\n\"\n+ lat = df['latitude']\n+ lon = df['longitude']\n+ cval = df[obscolumn]\n+ # print t2\n+ t1 = df['time']\n+ duration = ' 0100 '\n+ height = '20'\n+ if sitename in df.columns.values:\n+ sval = df[sitename]\n+ else:\n+ sval = [sitename] * len(cval)\n+ for val in zip(t1, lat, lon, cval, sval):\n+ runstring += val[0].strftime('%Y %m %d %H%M') + duration\n+ try:\n+ runstring += str(val[1]) + ' ' + str(val[2]) + ' '\n+ except RuntimeError:\n+ print('WARNING1', val[1])\n+ print(val[2])\n+ print(type(val[1]))\n+ print(type(val[2]))\n+ sys.exit()\n+ if isinstance(val[4], str):\n+ runstring += \"{:.3f}\".format(\n+ val[3]) + ' ' + val[4] + ' ' + height + \"\\n\"\n+ else:\n+ runstring += \"{:.3f}\".format(val[3]) + ' ' + \\\n+ \"{0:d}\".format(val[4]) + ' ' + height + \"\\n\"\n+\n+ with open(dname, 'w') as fid:\n+ fid.write(runstring)\n+ return runstring\n+\n+\n+def dropna(df, inplace=True):\n+ \"\"\"remove columns which have all Nans.\n+ TO DO: is this needed?\"\"\"\n+ return df.dropna(axis=1, inplace=inplace)\n+\n+\n+def get_lhash(df, idn):\n+ \"\"\"returns a dictionary with the key as the input column value and the\n+ value a tuple of (lat, lon) Useful for getting lat lon locations of\n+ different sites in a dataframe.\n+ \"\"\"\n+ if 'latitude' in list(df.columns.values):\n+ dftemp = df.copy()\n+ pairs = zip(dftemp[idn], zip(dftemp['latitude'], dftemp['longitude']))\n+ pairs = list(set(pairs))\n+ lhash = dict(pairs) # key is facility id and value is name.\n+ print(lhash)\n+ return lhash\n+\n+\n+def summarize(df, verbose=False):\n+ \"\"\"prints list of columns. if verbose prints list of unique values in each\n+ column\"\"\"\n+ columns = list(df.columns.values)\n+ if verbose:\n+ for ccc in columns:\n+ print(ccc)\n+ print(df[ccc].unique())\n+ print('-------------------------------')\n+ for ccc in columns:\n+ print(ccc)\n+\n+\n+def latlonfilter(df, llcrnr, urcrnr):\n+ \"\"\"\n+ removes rows from self.df with latitude longitude outside of the box\n+ described by llcrnr (lower left corner) and urcrnr (upper right corner)\n+ Parameters\n+ ----------\n+ llcrnr : tuple\n+ lower left corner. (latitude, longitude)\n+ urcrnr : tuple\n+ upper right corner (latittude, longitude)\n+ inplace: boolean\n+ if TRUE then replaces self.df attribute\n+ removes rows with latitude longitude outside of the box\n+ described by llcrnr (lower left corner) and urcrnr (upper right corner)\n+\n+ \"\"\"\n+ lat1 = llcrnr[0]\n+ lat2 = urcrnr[0]\n+ lon1 = llcrnr[1]\n+ lon2 = urcrnr[1]\n+ df = df[df['latitude'] < lat2]\n+ df = df[df['latitude'] > lat1]\n+ df = df[df['longitude'] > lon1]\n+ df = df[df['longitude'] < lon2]\n+ return df\n+\n+\n+def timefilter(df, daterange, inplace=True):\n+ \"\"\"removes rows with dates outside of the daterange from self.df\n+ Parameters\n+ ----------\n+ daterange: tuple\n+ (datetime, datetime)\n+ inplace: boolean\n+ if TRUE then replaces self.df attribute\n+ \"\"\"\n+ df = df[df['time'] > daterange[0]]\n+ df = df[df['time'] < daterange[1]]\n+ return df\ndiff --git a/monet/obs/tolnet_mod.py b/monet/obs/tolnet_mod.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/obs/tolnet_mod.py\n@@ -0,0 +1,116 @@\n+import os\n+from builtins import object\n+\n+import pandas as pd\n+import xarray as xr\n+\n+\n+class TOLNet(object):\n+ \"\"\"Short summary.\n+\n+ Attributes\n+ ----------\n+ objtype : type\n+ Description of attribute `objtype`.\n+ cwd : type\n+ Description of attribute `cwd`.\n+ dates : type\n+ Description of attribute `dates`.\n+ dset : type\n+ Description of attribute `dset`.\n+ daily : type\n+ Description of attribute `daily`.\n+\n+ \"\"\"\n+\n+ def __init__(self):\n+ self.objtype = 'TOLNET'\n+ self.cwd = os.getcwd()\n+ self.dates = pd.date_range(\n+ start='2017-09-25', end='2017-09-26', freq='H')\n+ self.dset = None\n+ self.daily = False\n+\n+ def add_data(self, fname):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ fname : type\n+ Description of parameter `fname`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from h5py import File\n+ f = File(fname)\n+ atts = f['INSTRUMENT_ATTRIBUTES']\n+ data = f['DATA']\n+ self.dset = self.make_xarray_dataset(data, atts)\n+ return self.dset\n+\n+ @staticmethod\n+ def make_xarray_dataset(data, atts):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ data : type\n+ Description of parameter `data`.\n+ atts : type\n+ Description of parameter `atts`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from numpy import NaN\n+ # altitude variables\n+ alt = data['ALT'][:].squeeze()\n+ altvars = [\n+ 'AirND', 'AirNDUncert', 'ChRange', 'Press', 'Temp', 'TempUncert',\n+ 'O3NDResol', 'PressUncert'\n+ ]\n+ # time variables\n+ tseries = pd.Series(data[\"TIME_MID_UT_UNIX\"][:].squeeze())\n+ time = pd.Series(pd.to_datetime(tseries, unit='ms'), name='time')\n+ tseries = pd.Series(data[\"TIME_START_UT_UNIX\"][:].squeeze())\n+ # stime = pd.to_datetime(tseries, unit='ms')\n+ tseries = pd.Series(data[\"TIME_STOP_UT_UNIX\"][:].squeeze())\n+ # etime = pd.to_datetime(tseries, unit='ms')\n+ # all other variables\n+ ovars = ['O3MR', 'O3ND', 'O3NDUncert', 'O3MRUncert', 'Precision']\n+ dset = {}\n+ for i in ovars:\n+ val = data[i][:]\n+ val[data[i][:] < -1.] = NaN\n+ dset[i] = (['z', 't'], val)\n+ for i in altvars:\n+ dset[i] = (['z'], data[i][:].squeeze())\n+\n+ # coords = {'time': time, 'z': alt, 'start_time': stime, 'end_time': etime}\n+ attributes = {}\n+ for i in list(atts.attrs.keys()):\n+ attributes[i] = atts.attrs[i]\n+ dataset = xr.Dataset(data_vars=dset, attrs=attributes)\n+ dataset['time'] = (['t'], time)\n+ dataset['t'] = dataset['time']\n+ dataset = dataset.drop('time').rename({'t': 'time'})\n+ dataset['z'] = alt\n+ # get latlon\n+ a, b = dataset.Location_Latitude.decode('ascii').split()\n+ if b == 'S':\n+ dataset['latitude'] = -1 * float(a)\n+ else:\n+ dataset['latitude'] = float(a)\n+ a, b = dataset.Location_Longitude.decode('ascii').split()\n+ if b == 'W':\n+ dataset['longitude'] = -1 * float(a)\n+ else:\n+ dataset['longitude'] = float(a)\n+ return dataset\ndiff --git a/monet/plots/__init__.py b/monet/plots/__init__.py\n--- a/monet/plots/__init__.py\n+++ b/monet/plots/__init__.py\n@@ -1,9 +1,10 @@\n from __future__ import absolute_import, print_function\n \n from . import colorbars, plots, taylordiagram\n+from .plots import *\n+from .mapgen import *\n+from .colorbars import *\n \n-__all__ = ['colorbars', 'plots', 'taylordiagram']\n-\n-__name__ = 'plots'\n+__all__ = ['colorbars', 'plots', 'taylordiagram', 'mapgen']\n \n # This is the driver for all verify objects\ndiff --git a/monet/plots/colorbars.py b/monet/plots/colorbars.py\n--- a/monet/plots/colorbars.py\n+++ b/monet/plots/colorbars.py\n@@ -1,31 +1,36 @@\n+\"\"\" colorbar helper functions\"\"\"\n from builtins import range\n import matplotlib.colors as mcolors\n import matplotlib.pyplot as plt\n-from matplotlib import cm\n from numpy import arange, linspace, vstack\n \n \n-def colorbar_index(ncolors, cmap, minval=None, maxval=None, dtype='int', basemap=None):\n+def colorbar_index(ncolors,\n+ cmap,\n+ minval=None,\n+ maxval=None,\n+ dtype='int',\n+ basemap=None):\n import matplotlib.cm as cm\n import numpy as np\n cmap = cmap_discretize(cmap, ncolors)\n mappable = cm.ScalarMappable(cmap=cmap)\n mappable.set_array([])\n mappable.set_clim(-0.5, ncolors + 0.5)\n- if type(basemap) is not None:\n+ if basemap is not None:\n colorbar = basemap.colorbar(mappable, format='%1.2g')\n else:\n colorbar = plt.colorbar(mappable, format='%1.2g', fontsize=12)\n colorbar.set_ticks(np.linspace(0, ncolors, ncolors))\n- if (type(minval) is None) & (type(maxval) is not None):\n+ if (minval is None) & (maxval is not None):\n colorbar.set_ticklabels(\n np.around(np.linspace(0, maxval, ncolors).astype(dtype), 2))\n- elif (type(minval) is None) & (type(maxval) is None):\n+ elif (minval is None) & (maxval is None):\n colorbar.set_ticklabels(\n np.around(np.linspace(0, ncolors, ncolors).astype(dtype), 2))\n else:\n- colorbar.set_ticklabels(np.around(np.linspace(\n- minval, maxval, ncolors).astype(dtype), 2))\n+ colorbar.set_ticklabels(\n+ np.around(np.linspace(minval, maxval, ncolors).astype(dtype), 2))\n \n return colorbar, cmap\n \n@@ -57,93 +62,138 @@ def cmap_discretize(cmap, N):\n # Return colormap object.\n return mcolors.LinearSegmentedColormap(cmap.name + \"_%d\" % N, cdict, 1024)\n \n-\n-def o3cmap():\n- # This function returns the colormap and bins for the ozone spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.OrRd(linspace(.2, 1, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('o3cmap', colors), arange(0, 140.5, .5)\n-\n-\n-def pm25cmap():\n- # This function returns the colormap and bins for the PM spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.OrRd(linspace(.2, 1, 128))\n- colors = vstack((colors1, colors2))\n- cc = mcolors.LinearSegmentedColormap.from_list('pm25cmap', colors), arange(0, 70.2, .2)\n- return cc\n-\n-\n-def wscmap():\n- # This function returns the colormap and bins for the PM spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.OrRd(linspace(.2, 1, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('wscmap', colors), arange(0, 40.2, .2)\n-\n-\n-def tempcmap():\n- # This function returns the colormap and bins for the PM spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.OrRd(linspace(.2, 1, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('tempcmap', colors), arange(250, 320.5, .5)\n-\n-\n-def sradcmap():\n- # This function returns the colormap and bins for the PM spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.plasma(linspace(.2, 1, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('sradcmap', colors), arange(0, 1410., 10)\n-\n-\n-def noxcmap():\n- # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.plasma_r(linspace(.042, .75, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('noxcmap', colors), arange(0, 40.2, .2)\n-\n-\n-def rhcmap():\n- # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.plasma_r(linspace(.042, .75, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('noxcmap', colors), arange(0, 100.5, .5)\n-\n-\n-def so2cmap():\n- # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.plasma_r(linspace(.042, .75, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('noxcmap', colors), arange(0, 14.1, .1)\n-\n-\n-def pm10cmap():\n- # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n- # this is designed to have a vmin =0 and vmax = 140\n- # return cmap,bins\n- colors1 = cm.viridis(linspace(0, 1, 128))\n- colors2 = cm.plasma_r(linspace(.042, .75, 128))\n- colors = vstack((colors1, colors2))\n- return mcolors.LinearSegmentedColormap.from_list('noxcmap', colors), arange(0, 150.5, .5)\n+# def o3cmap():\n+# import matplotlib.cm as cm\n+# # This function returns the colormap and bins for the ozone spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = cm.viridis(linspace(0, 1, 128))\n+# colors2 = cm.OrRd(linspace(.2, 1, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('o3cmap', colors), arange(\n+# 0, 140.5, .5)\n+#\n+#\n+# def pm25cmap():\n+# from matplotlib.cm import viridis, OrRd\n+# # This function returns the colormap and bins for the PM spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = OrRd(linspace(.2, 1, 128))\n+# colors = vstack((colors1, colors2))\n+# cc = mcolors.LinearSegmentedColormap.from_list('pm25cmap', colors), arange(\n+# 0, 70.2, .2)\n+# return cc\n+#\n+#\n+# def wscmap():\n+# from matplotlib.cm import viridis, OrRd\n+# # This function returns the colormap and bins for the PM spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = OrRd(linspace(.2, 1, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('wscmap', colors), arange(\n+# 0, 40.2, .2)\n+#\n+#\n+# def tempcmap():\n+# from matplotlib.cm import viridis, OrRd\n+# # This function returns the colormap and bins for the PM spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = OrRd(linspace(.2, 1, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('tempcmap',\n+# colors), arange(\n+# 250, 320.5, .5)\n+#\n+#\n+# def sradcmap():\n+# from matplotlib.cm import viridis, plasma_r\n+# # This function returns the colormap and bins for the PM spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = plasma_r(linspace(.2, 1, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('sradcmap',\n+# colors), arange(\n+# 0, 1410., 10)\n+#\n+#\n+# def noxcmap():\n+# \"\"\"Short summary.\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# from matplotlib.cm import viridis, plasma_r\n+# # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = plasma_r(linspace(.042, .75, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('noxcmap',\n+# colors), arange(\n+# 0, 40.2, .2)\n+#\n+#\n+# def rhcmap():\n+# \"\"\"Short summary.\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# from matplotlib.cm import viridis, plasma_r\n+# # This function returns the colormap and bins for the NO2/NO/NOx spatial\n+# # plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = plasma_r(linspace(.042, .75, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('noxcmap',\n+# colors), arange(\n+# 0, 100.5, .5)\n+#\n+#\n+# def so2cmap():\n+# \"\"\"Short summary.\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# from matplotlib.cm import viridis, plasma_r\n+# colors1 = viridis(linspace(0, 1, 128))\n+# colors2 = plasma_r(linspace(.042, .75, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('noxcmap',\n+# colors), arange(\n+# 0, 14.1, .1)\n+#\n+#\n+# def pm10cmap():\n+# import matplotlib.cm as cm\n+# # This function returns the colormap and bins for the NO2/NO/NOx spatial plots\n+# # this is designed to have a vmin =0 and vmax = 140\n+# # return cmap,bins\n+# colors1 = cm.viridis(linspace(0, 1, 128))\n+# colors2 = cm.plasma_r(linspace(.042, .75, 128))\n+# colors = vstack((colors1, colors2))\n+# return mcolors.LinearSegmentedColormap.from_list('noxcmap',\n+# colors), arange(\n+# 0, 150.5, .5)\ndiff --git a/monet/plots/mapgen.py b/monet/plots/mapgen.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/plots/mapgen.py\n@@ -0,0 +1,80 @@\n+\"\"\" map utilities \"\"\"\n+import cartopy.crs as ccrs\n+import cartopy.feature as cfeature\n+import matplotlib.pyplot as plt\n+\n+\n+def draw_map(ax=None,\n+ crs=None,\n+ natural_earth=False,\n+ coastlines=True,\n+ states=False,\n+ countries=True,\n+ resolution='10m',\n+ extent=None,\n+ **kwargs):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ ax : type\n+ Description of parameter `ax` (the default is None).\n+ natural_earth : bool\n+ Description of parameter `natural_earth` (the default is True).\n+ coastlines : bool\n+ Description of parameter `coastlines` (the default is True).\n+ states : bool\n+ Description of parameter `states` (the default is True).\n+ countries : bool\n+ Description of parameter `countries` (the default is True).\n+ state_resolutions : bool\n+ Description of parameter `state_resolutions` (the default is '10m').\n+ extent : [lon_min,lon_max,lat_min,lat_max]\n+ Description of parameter `extent` (the default is None).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ con2 = 'subplot_kw' in kwargs and 'projection' not in kwargs['subplot_kw']\n+ if ax is None and kwargs is not None and crs is None:\n+ if 'subplot_kw' not in kwargs:\n+ kwargs['subplot_kw'] = {'projection': ccrs.PlateCarree()}\n+ elif con2:\n+ kwargs['subplot_kw']['projection'] = ccrs.PlateCarree()\n+ f, ax = plt.subplots(figsize=(10, 5), **kwargs)\n+ elif ax is None and crs is not None:\n+ f, ax = plt.subplots(figsize=(10, 5), subplot_kw={'projection': crs})\n+ else:\n+ f, ax = plt.subplots(\n+ figsize=(10, 5), subplot_kw={'projection': ccrs.PlateCarree()})\n+ if natural_earth:\n+ # ax.stock_img()\n+ ax.add_feature(cfeature.OCEAN)\n+ ax.add_feature(cfeature.LAND)\n+ ax.add_feature(cfeature.LAKES)\n+ ax.add_feature(cfeature.RIVERS)\n+\n+ if states:\n+ states_provinces = cfeature.NaturalEarthFeature(\n+ category='cultural',\n+ name='admin_1_states_provinces_lines',\n+ scale=resolution,\n+ facecolor='none')\n+ ax.add_feature(states_provinces, edgecolor='black')\n+\n+ if coastlines:\n+ ax.coastlines(resolution)\n+\n+ if countries:\n+ ax.add_feature(cfeature.BORDERS)\n+\n+ if states:\n+ ax.add_feature(states_provinces)\n+\n+ if extent is not None:\n+ ax.set_extent(extent)\n+\n+ return ax\ndiff --git a/monet/plots/plots.py b/monet/plots/plots.py\n--- a/monet/plots/plots.py\n+++ b/monet/plots/plots.py\n@@ -1,10 +1,9 @@\n+\"\"\"plotting routines\"\"\"\n import matplotlib.pyplot as plt\n import seaborn as sns\n \n-import taylordiagram as td\n-from colorbars import colorbar_index\n-\n-from ..util import mystats\n+from . import taylordiagram as td\n+from .colorbars import colorbar_index\n \n # colors = ['#1e90ff','#045C5C','#00A847','#DB4291','#BB7E5D']\n colors = ['#1e90ff', '#DA70D6', '#228B22', '#FA8072', '#FF1493']\n@@ -14,27 +13,38 @@\n \n \n # CMAQ Spatial Plots\n+def make_spatial_plot(modelvar,\n+ m,\n+ dpi=None,\n+ plotargs={},\n+ ncolors=15,\n+ discrete=False):\n \n-\n-def make_spatial_plot(cmaqvar, m, dpi=None, plotargs={}, ncolors=15, discrete=False):\n # create figure\n f, ax = plt.subplots(1, 1, figsize=(11, 6), frameon=False)\n # determine colorbar\n if 'cmap' not in plotargs:\n plotargs['cmap'] = 'viridis'\n if discrete and 'vmin' in plotargs and 'vmax' in plotargs:\n- c, cmap = colorbar_index(ncolors, plotargs['cmap'], minval=plotargs['vmin'], maxval=plotargs['vmax'], basemap=m)\n+\n+ c, cmap = colorbar_index(\n+ ncolors,\n+ plotargs['cmap'],\n+ minval=plotargs['vmin'],\n+ maxval=plotargs['vmax'],\n+ basemap=m)\n plotargs['cmap'] = cmap\n- m.imshow(cmaqvar, **plotargs)\n+ m.imshow(modelvar, **plotargs)\n vmin, vmax = plotargs['vmin'], plotargs['vmax']\n elif discrete:\n- temp = m.imshow(cmaqvar, **plotargs)\n+ temp = m.imshow(modelvar, **plotargs)\n vmin, vmax = temp.get_clim()\n- c, cmap = colorbar_index(ncolors, plotargs['cmap'], minval=vmin, maxval=vmax, basemap=m)\n+ c, cmap = colorbar_index(\n+ ncolors, plotargs['cmap'], minval=vmin, maxval=vmax, basemap=m)\n plotargs['cmap'] = cmap\n- m.imshow(cmaqvar, vmin=vmin, vmax=vmax, **plotargs)\n+ m.imshow(modelvar, vmin=vmin, vmax=vmax, **plotargs)\n else:\n- temp = m.imshow(cmaqvar, **plotargs)\n+ temp = m.imshow(modelvar, **plotargs)\n c = m.colorbar()\n vmin, vmax = temp.get_clim()\n cmap = plotargs['cmap']\n@@ -44,10 +54,25 @@ def make_spatial_plot(cmaqvar, m, dpi=None, plotargs={}, ncolors=15, discrete=Fa\n m.drawcountries()\n return f, ax, c, cmap, vmin, vmax\n \n+def spatial(modelvar, **kwargs):\n+ if kwargs['ax'] is None:\n+ f, ax = plt.subplots(1, 1, figsize=(11, 6), frameon=False)\n+ kwargs['ax'] = ax\n+ ax = modelvar.plot(**kwargs)\n+ return ax\n+\n \n-def make_spatial_contours(cmaqvar, gridobj, date, m, dpi=None, savename='', discrete=True, ncolors=None, dtype='int',\n+def make_spatial_contours(modelvar,\n+ gridobj,\n+ date,\n+ m,\n+ dpi=None,\n+ savename='',\n+ discrete=True,\n+ ncolors=None,\n+ dtype='int',\n **kwargs):\n- fig = plt.figure(figsize=(11, 6), frameon=False)\n+ plt.figure(figsize=(11, 6), frameon=False)\n lat = gridobj.variables['LAT'][0, 0, :, :].squeeze()\n lon = gridobj.variables['LON'][0, 0, :, :].squeeze()\n # define map and draw boundries\n@@ -56,13 +81,17 @@ def make_spatial_contours(cmaqvar, gridobj, date, m, dpi=None, savename='', disc\n m.drawcountries()\n x, y = m(lon, lat)\n plt.axis('off')\n- m.contourf(x, y, cmaqvar, **kwargs)\n+ m.contourf(x, y, modelvar, **kwargs)\n cmap = kwargs['cmap']\n levels = kwargs['levels']\n if discrete:\n- c, cmap = colorbar_index(ncolors, cmap, minval=levels[0], maxval=levels[-1], basemap=m, dtype=dtype)\n- # m.contourf(x, y, cmaqvar, **kwargs,cmap=cmap)\n- # c, cmap = colorbar_index(ncolors, cmap, minval=vmin, maxval=vmax)\n+ c, cmap = colorbar_index(\n+ ncolors,\n+ cmap,\n+ minval=levels[0],\n+ maxval=levels[-1],\n+ basemap=m,\n+ dtype=dtype)\n else:\n c = m.colorbar()\n titstring = date.strftime('%B %d %Y %H')\n@@ -76,13 +105,15 @@ def make_spatial_contours(cmaqvar, gridobj, date, m, dpi=None, savename='', disc\n \n \n def wind_quiver(ws, wdir, gridobj, m, **kwargs):\n- import tools\n+ from . import tools\n+\n lat = gridobj.variables['LAT'][0, 0, :, :].squeeze()\n lon = gridobj.variables['LON'][0, 0, :, :].squeeze()\n # define map and draw boundries\n x, y = m(lon, lat)\n u, v = tools.wsdir2uv(ws, wdir)\n- quiv = m.quiver(x[::15, ::15], y[::15, ::15], u[::15, ::15], v[::15, ::15], **kwargs)\n+ quiv = m.quiver(x[::15, ::15], y[::15, ::15], u[::15, ::15], v[::15, ::15],\n+ **kwargs)\n return quiv\n \n \n@@ -93,7 +124,8 @@ def wind_barbs(ws, wdir, gridobj, m, **kwargs):\n # define map and draw boundries\n x, y = m(lon, lat)\n u, v = tools.wsdir2uv(ws, wdir)\n- m.barbs(x[::15, ::15], y[::15, ::15], u[::15, ::15], v[::15, ::15], **kwargs)\n+ m.barbs(x[::15, ::15], y[::15, ::15], u[::15, ::15], v[::15, ::15],\n+ **kwargs)\n \n \n def normval(vmin, vmax, cmap):\n@@ -103,33 +135,47 @@ def normval(vmin, vmax, cmap):\n norm = BoundaryNorm(boundaries=bounds, ncolors=cmap.N)\n return norm\n \n+# def spatial_scatter(df, m, discrete=False, plotargs={}, create_cbar=True):\n+# from .colorbars import cmap_discretize\n+# x, y = m(df.longitude.values, df.Latitude.values)\n+# s = 20\n+# if create_cbar:\n+# if discrete:\n+# cmap = cmap_discretize(cmap, ncolors)\n+# # s = 20\n+# if (type(plotargs(vmin)) == None) | (type(plotargs(vmax)) == None):\n+# plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n+# else:\n+# plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n+# else:\n+# plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n+# else:\n+# plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n+\n+# def spatial_stat_scatter(df,\n+# m,\n+# date,\n+# stat=mystats.MB,\n+# ncolors=15,\n+# fact=1.5,\n+# cmap='RdYlBu_r'):\n+# new = df[df.datetime == date]\n+# x, y = m(new.longitude.values, new.latitude.values)\n+# cmap = cmap_discretize(cmap, ncolors)\n+# colors = new.CMAQ - new.Obs\n+# ss = (new.Obs - new.CMAQ).abs() * fact\n+\n+\n+def spatial_bias_scatter(df,\n+ m,\n+ date,\n+ vmin=None,\n+ vmax=None,\n+ savename='',\n+ ncolors=15,\n+ fact=1.5,\n+ cmap='RdBu_r'):\n \n-def spatial_scatter(df, m, discrete=False, plotargs={}, create_cbar=True):\n- x, y = m(df.Longitude.values, df.Latitude.values)\n- s = 20\n- if create_cbar:\n- if discrete:\n- cmap = cmap_discretize(cmap, ncolors)\n- # s = 20\n- if (type(plotargs(vmin)) == None) | (type(plotargs(vmax)) == None):\n- plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n- else:\n- plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n- else:\n- plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n- else:\n- plt.scatter(x, y, c=df['Obs'].values, **plotargs)\n-\n-\n-def spatial_stat_scatter(df, m, date, stat=mystats.MB, ncolors=15, fact=1.5, cmap='RdYlBu_r'):\n- new = df[df.datetime == date]\n- x, y = m(new.Longitude.values, new.Latitude.values)\n- cmap = cmap_discretize(cmap, ncolors)\n- colors = new.CMAQ - new.Obs\n- ss = (new.Obs - new.CMAQ).abs() * fact\n-\n-\n-def spatial_bias_scatter(df, m, date, vmin=None, vmax=None, savename='', ncolors=15, fact=1.5, cmap='RdBu_r'):\n from scipy.stats import scoreatpercentile as score\n from numpy import around\n # plt.figure(figsize=(11, 6), frameon=False)\n@@ -138,40 +184,60 @@ def spatial_bias_scatter(df, m, date, vmin=None, vmax=None, savename='', ncolors\n diff = (df.CMAQ - df.Obs)\n top = around(score(diff.abs(), per=95))\n new = df[df.datetime == date]\n- x, y = m(new.Longitude.values, new.Latitude.values)\n- c, cmap = colorbar_index(ncolors, cmap, minval=top * -1, maxval=top, basemap=m)\n+ x, y = m(new.longitude.values, new.latitude.values)\n+ c, cmap = colorbar_index(\n+ ncolors, cmap, minval=top * -1, maxval=top, basemap=m)\n+\n c.ax.tick_params(labelsize=13)\n # cmap = cmap_discretize(cmap, ncolors)\n colors = new.CMAQ - new.Obs\n ss = (new.CMAQ - new.Obs).abs() / top * 100.\n ss[ss > 300] = 300.\n- plt.scatter(x, y, c=colors, s=ss, vmin=-1. * top, vmax=top, cmap=cmap, edgecolors='k', linewidths=.25, alpha=.7)\n- if savename != '':\n- plt.savefig(savename + date + '.jpg', dpi=75.)\n- plt.close()\n- return f, ax, c\n-\n+ plt.scatter(\n+ x,\n+ y,\n+ c=colors,\n+ s=ss,\n+ vmin=-1. * top,\n+ vmax=top,\n+ cmap=cmap,\n+ edgecolors='k',\n+ linewidths=.25,\n+ alpha=.7)\n \n-def eight_hr_spatial_scatter(df, m, date, savename=''):\n- fig = plt.figure(figsize=(11, 6), frameon=False)\n- m.drawcoastlines(linewidth=.3)\n- m.drawstates()\n- m.drawcountries()\n-\n- plt.axis('off')\n- new = df[df.datetime_local == date]\n- x, y = m(new.Longitude.values, new.Latitude.values)\n- cmap = plt.cm.get_cmap('plasma')\n- norm = normval(-40, 40., cmap)\n- ss = (new.Obs - new.CMAQ).abs() / top * 100.\n- colors = new.Obs - new.CMAQ\n- m.scatter(x, y, s=ss, c=colors, norm=norm, cmap=cmap)\n if savename != '':\n plt.savefig(savename + date + '.jpg', dpi=75.)\n plt.close()\n+ return f, ax, c\n \n-\n-def timeseries_param(df, col='Obs', ax=None, sample='H', plotargs={}, fillargs={}, title='', label=None):\n+# def eight_hr_spatial_scatter(df, m, date, savename=''):\n+# fig = plt.figure(figsize=(11, 6), frameon=False)\n+# m.drawcoastlines(linewidth=.3)\n+# m.drawstates()\n+# m.drawcountries()\n+#\n+# plt.axis('off')\n+# new = df[df.datetime_local == date]\n+# x, y = m(new.longitude.values, new.latitude.values)\n+# cmap = plt.cm.get_cmap('plasma')\n+# norm = normval(-40, 40., cmap)\n+# ss = (new.Obs - new.CMAQ).abs() / top * 100.\n+# colors = new.Obs - new.CMAQ\n+# m.scatter(x, y, s=ss, c=colors, norm=norm, cmap=cmap)\n+# if savename != '':\n+# plt.savefig(savename + date + '.jpg', dpi=75.)\n+# plt.close()\n+\n+\n+def timeseries(df,\n+ x='time',\n+ y='obs',\n+ ax=None,\n+ plotargs={},\n+ fillargs={'alpha': .2},\n+ title='',\n+ ylabel=None,\n+ label=None):\n \"\"\"Short summary.\n \n Parameters\n@@ -199,273 +265,58 @@ def timeseries_param(df, col='Obs', ax=None, sample='H', plotargs={}, fillargs={\n Description of returned object.\n \n \"\"\"\n- import pandas as pd\n-\n if ax is None:\n f, ax = plt.subplots(figsize=(11, 6), frameon=False)\n \n sns.set_palette(sns.color_palette(colors))\n sns.set_style('ticks')\n- df.index = df.datetime\n- m = df.groupby(pd.Grouper(freq=sample)).mean()\n- e = df.groupby(pd.Grouper(freq=sample)).std()\n- species = df.Species[0]\n- unit = df.Units[0]\n- upper = m[col] + e[col]\n- lower = m[col] - e[col]\n- lower.loc[lower < 0] = 0\n- lower = lower.values\n- if col == 'Obs':\n- plotargs['color'] = 'darkslategrey'\n- if col == 'Obs':\n- fillargs['color'] = 'darkslategrey'\n- if col != 'Obs' and 'color' not in plotargs:\n- plotargs['color'] = None\n-\n- m[col].plot(ax=ax, **plotargs)\n- ax.fill_between(m[col].index, lower, upper, **fillargs)\n- if label is None:\n- ax.set_ylabel(species + ' (' + unit + ')')\n+ df.index = df[x]\n+ m = df.groupby('time').mean() # mean values for each sample time period\n+ e = df.groupby('time').std() # std values for each sample time period\n+ variable = df.variable[0]\n+ if df.columns.isin(['units']).max():\n+ unit = df.units[0]\n else:\n- ax.set_ylabel(label)\n- plt.set_xlabel('')\n- plt.legend()\n- plt.title(title)\n- plt.tight_layout()\n- return ax\n-\n-\n-def timeseries_error_param(df, col='Obs', ax=None, resample=False, freq='H', plotargs={}, fillargs={}, title='',\n- label=None):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- df : pandas DataFrame\n- pandas dataframe with a column labeled datetime\n- col : string\n- Description of parameter `col` (the default is 'Obs').\n- ax : matplotlib axis handle\n- pass a matplotlib axis handle. Default none creates a new figure and axes handle.\n- resample : bool\n- Set to true or false to resample the dataframe. (the default is 'H' plotargs)\n- freq : str\n- String for the default frequency to resample. See http://pandas.pydata.org/pandas-docs/stable/timeseries.html for more documentation (the default is 'H' plotargs).\n- fillargs : dictionary\n- (the default is {}).\n- title : type\n- Description of parameter `title` (the default is '').\n- label : type\n- Description of parameter `label` (the default is None).\n-\n- Returns\n- -------\n- type\n- Description of returned object. \"\"\"\n- import pandas as pd\n-\n- if ax is None:\n- f, ax = plt.subplots(figsize=(11, 6), frameon=False)\n-\n- sns.set_palette(sns.color_palette(colors))\n- sns.set_style('ticks')\n- df.index = df.datetime\n- m = df.groupby(pd.Grouper(freq=sample)).mean()\n- e = df.groupby(pd.Grouper(freq=sample)).std()\n- species = df.Species[0]\n- unit = df.Units[0]\n- upper = m[col] + e[col]\n- lower = m[col] - e[col]\n+ unit = 'None'\n+ upper = m[y] + e[y]\n+ lower = m[y] - e[y]\n lower.loc[lower < 0] = 0\n lower = lower.values\n- if col == 'Obs':\n- plotargs['color'] = 'darkslategrey'\n- if col == 'Obs':\n- fillargs['color'] = 'darkslategrey'\n- if col != 'Obs' and 'color' not in plotargs:\n- plotargs['color'] = None\n-\n- m[col].plot(ax=ax, **plotargs)\n- ax.fill_between(m[col].index, lower, upper, **fillargs)\n- if label is None:\n- ax.set_ylabel(species + ' (' + unit + ')')\n+ if 'alpha' not in fillargs:\n+ fillargs['alpha'] = 0.2\n+ if label is not None:\n+ m.rename(columns={y: label}, inplace=True)\n+ else:\n+ label = y\n+ m[label].plot(ax=ax, **plotargs)\n+ ax.fill_between(m[label].index, lower, upper, **fillargs)\n+ if ylabel is None:\n+ ax.set_ylabel(variable + ' (' + unit + ')')\n else:\n ax.set_ylabel(label)\n+ ax.set_xlabel('')\n plt.legend()\n plt.title(title)\n plt.tight_layout()\n return ax\n \n-\n-# def timeseries_error_param(df, title='', fig=None, label=None, footer=True, sample='H'):\n-# \"\"\"\n-#\n-# :param df:\n-# :param title:\n-# :param fig:\n-# :param label:\n-# :param footer:\n-# :param sample:\n-# \"\"\"\n-# import matplotlib.dates as mdates\n-# from numpy import sqrt\n-# sns.set_style('ticks')\n-#\n-# df.index = df.datetime\n-# if fig is None:\n-# plt.figure(figsize=(13, 8))\n-#\n-# species = df.Species.unique().astype('|S8')[0]\n-# units = df.Units.unique().astype('|S8')[0]\n-#\n-# mb = (df.CMAQ - df.Obs).resample(sample).mean()\n-# rmse = sqrt((df.CMAQ - df.Obs) ** 2).resample(sample).mean()\n-#\n-# a = plt.plot(mb, label='Mean Bias', color='dodgerblue')\n-# ax = plt.gca().axes\n-# ax2 = ax.twinx()\n-# b = ax2.plot(rmse, label='RMSE', color='tomato')\n-# lns = a + b\n-# labs = [l.get_label() for l in lns]\n-# plt.legend(lns, labs, loc='best')\n-#\n-# ax.set_xlabel('UTC Time (mm/dd HH)')\n-# ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d %H'))\n-# plt.title(title)\n-# ylabel = species + ' (' + units + ')'\n-# ax.set_ylabel('MB ' + ylabel, color='dodgerblue')\n-# ax2.set_ylabel('RMSE ' + ylabel, color='tomato')\n-# if footer:\n-# footer_text(df)\n-# plt.tight_layout()\n-# plt.grid(alpha=.5)\n-# else:\n-# ax1 = fig.get_axes()[0]\n-# ax2 = fig.get_axes()[1]\n-# mb = (df.CMAQ - df.Obs).resample(sample).mean()\n-# rmse = sqrt((df.CMAQ - df.Obs) ** 2).resample(sample).mean()\n-# ax1.plot(mb, label=label + ' MB')\n-# ax2.plot(rmse, label=label + ' RMSE')\n-# lns = ax1.get_lines()[:] + ax2.get_lines()[1:]\n-# labs = [l.get_label() for l in lns]\n-# plt.legend(lns, labs, loc='best')\n-\n-\n-def timeseries_rmse_param(df, title='', fig=None, label=None, footer=True, sample='H'):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- df : type\n- Description of parameter `df`.\n- title : type\n- Description of parameter `title` (the default is '').\n- fig : type\n- Description of parameter `fig` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n- sample : type\n- Description of parameter `sample` (the default is 'H').\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- import matplotlib.dates as mdates\n- from numpy import sqrt\n- sns.set_style('ticks')\n- df.index = df.datetime\n- if fig is None:\n- plt.figure(figsize=(13, 8))\n- species = df.Species.unique().astype('|S8')[0]\n- units = df.Units.unique().astype('|S8')[0]\n- rmse = sqrt((df.CMAQ - df.Obs) ** 2).resample(sample).mean()\n- plt.plot(rmse, color='dodgerblue', label=label)\n- ylabel = species + ' (' + units + ')'\n- plt.gca().axes.set_ylabel('RMSE ' + ylabel)\n- if footer:\n- footer_text(df)\n- ax = plt.gca().axes\n- ax.set_xlabel('UTC Time (mm/dd HH)')\n- ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d %H'))\n- plt.tight_layout()\n- plt.grid(alpha=.5)\n- else:\n- ax = fig.get_axes()[0]\n- rmse = sqrt((df.CMAQ - df.Obs) ** 2).resample(sample).mean()\n- ax.plot(rmse, label=label)\n- plt.legend(loc='best')\n-\n-\n-def timeseries_mb_param(df, title='', fig=None, label=None, footer=True, sample='H'):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- df : type\n- Description of parameter `df`.\n- title : type\n- Description of parameter `title` (the default is '').\n- fig : type\n- Description of parameter `fig` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n- sample : type\n- Description of parameter `sample` (the default is 'H').\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- import matplotlib.dates as mdates\n- sns.set_style('ticks')\n- df.index = df.datetime\n- if fig is None:\n- plt.figure(figsize=(13, 8))\n- species = df.Species.unique().astype('|S8')[0]\n- units = df.Units.unique().astype('|S8')[0]\n- mb = (df.CMAQ - df.Obs).resample(sample).mean()\n- plt.plot(mb, color='dodgerblue', label=label)\n- ylabel = species + ' (' + units + ')'\n- plt.gca().axes.set_ylabel('MB ' + ylabel)\n- plt.gca().axes.set_xlabel('UTC Time (mm/dd HH)')\n- plt.gca().axes.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d %H'))\n- if footer:\n- footer_text(df)\n- plt.tight_layout()\n- plt.grid(alpha=.5)\n- else:\n- ax = fig.get_axes()[0]\n- rmse = (df.CMAQ - df.Obs).resample(sample).mean()\n- ax.plot(rmse, label=label)\n- plt.legend(loc='best')\n-\n-\n-def kdeplots_param(df, title=None, fig=None, label=None, footer=True, cumulative=False):\n+def kdeplot(df, title=None, label=None, ax=None, **kwargs):\n \"\"\"Short summary.\n \n Parameters\n ----------\n df : type\n Description of parameter `df`.\n+ col : type\n+ Description of parameter `col` (the default is 'obs').\n title : type\n Description of parameter `title` (the default is None).\n- fig : type\n- Description of parameter `fig` (the default is None).\n label : type\n Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n- cumulative : type\n- Description of parameter `cumulative` (the default is False).\n+ ax : type\n+ Description of parameter `ax` (the default is ax).\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n \n Returns\n -------\n@@ -473,98 +324,29 @@ def kdeplots_param(df, title=None, fig=None, label=None, footer=True, cumulative\n Description of returned object.\n \n \"\"\"\n- from scipy.stats import scoreatpercentile as score\n sns.set_style('ticks')\n \n- if fig is None:\n-\n- if cumulative:\n- plt.figure(figsize=(13, 8))\n- sns.kdeplot(df.Obs, color='darkslategrey', cumulative=True, label='Obs')\n- sns.kdeplot(df.CMAQ, color='dodgerblue', cumulative=True, label=label)\n- else:\n- maxval1 = score(df.CMAQ.values, per=99.5)\n- maxval2 = score(df.Obs.values, per=99.5)\n- maxval = max([maxval1, maxval2])\n- plt.figure(figsize=(13, 8))\n- sns.kdeplot(df.Obs, color='darkslategrey')\n- sns.kdeplot(df.CMAQ, color='dodgerblue', label=label)\n-\n+ if ax is None:\n+ f, ax = plt.subplots(figsize=(11, 6), frameon=False)\n sns.despine()\n- if not cumulative:\n- plt.xlim([0, maxval])\n- plt.xlabel(df.Species.unique()[0] + ' (' + df.Units.unique()[0] + ')')\n- plt.title(title)\n- plt.gca().axes.set_ylabel('P(' + df.Species.unique()[0] + ')')\n- if footer:\n- footer_text(df)\n- plt.tight_layout()\n- plt.grid(alpha=.5)\n- else:\n- ax = fig.get_axes()[0]\n- sns.kdeplot(df.CMAQ, ax=ax, label=label, cumulative=cumulative)\n-\n-\n-def diffpdfs_param(df, title=None, fig=None, label=None, footer=True):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- df : type\n- Description of parameter `df`.\n- title : type\n- Description of parameter `title` (the default is None).\n- fig : type\n- Description of parameter `fig` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- from scipy.stats import scoreatpercentile as score\n- sns.set_style('ticks')\n \n- maxval = score(df.CMAQ.values - df.Obs.values, per=99.9)\n- minval = score(df.CMAQ.values - df.Obs.values, per=.1)\n- if fig is None:\n- plt.figure(figsize=(10, 7))\n- if label == 'None':\n- label = 'CMAQ - Obs'\n- sns.kdeplot(df.CMAQ.values - df.Obs.values, color='darkslategrey', label=label)\n- sns.despine()\n- plt.xlim([minval, maxval])\n- plt.xlabel(df.Species.unique()[0] + ' Difference (' + df.Units.unique()[0] + ')')\n- plt.title(title)\n- plt.gca().axes.set_ylabel('P( Model - Obs )')\n- if footer:\n- footer_text(df)\n- plt.tight_layout()\n- else:\n- ax = fig.get_axes()[0]\n- sns.kdeplot(df.CMAQ.values - df.Obs.values, ax=ax, label=label)\n+ ax = sns.kdeplot(df, ax=ax, label=label, **kwargs)\n+ return ax\n \n \n-def scatter_param(df, title=None, fig=None, label=None, footer=True):\n+def scatter(df, x=None, y=None, title=None, label=None, ax=None, **kwargs):\n \"\"\"Short summary.\n \n Parameters\n ----------\n df : type\n Description of parameter `df`.\n- title : type\n- Description of parameter `title` (the default is None).\n- fig : type\n- Description of parameter `fig` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n+ x : type\n+ Description of parameter `x` (the default is 'obs').\n+ y : type\n+ Description of parameter `y` (the default is 'model').\n+ **kwargs : type\n+ Description of parameter `**kwargs`.\n \n Returns\n -------\n@@ -572,114 +354,36 @@ def scatter_param(df, title=None, fig=None, label=None, footer=True):\n Description of returned object.\n \n \"\"\"\n- from numpy import max, arange, linspace, isnan\n- from scipy.stats import scoreatpercentile as score\n- from scipy.stats import linregress\n sns.set_style('ticks')\n \n- species, units = df.Species.unique()[0], df.Units.unique()[0]\n- mask = ~isnan(df.Obs.values) & ~isnan(df.CMAQ.values)\n- maxval1 = score(df.CMAQ.values[mask], per=99.5)\n- maxval2 = score(df.Obs.values[mask], per=99.5)\n- maxval = max([maxval1, maxval2])\n- print maxval\n- if fig is None:\n- plt.figure(figsize=(10, 7))\n-\n- plt.scatter(df.Obs, df.CMAQ, c='cornflowerblue', marker='o', edgecolors='w', alpha=.3, label=label)\n- x = arange(0, maxval + 1)\n- if maxval <= 10.:\n- x = linspace(0, maxval, 25)\n- plt.plot(x, x, '--', color='slategrey')\n- tt = linregress(df.Obs.values[mask], df.CMAQ.values[mask])\n- plt.plot(x, tt[0] * x + tt[1], color='tomato')\n-\n- plt.xlim([0, maxval])\n- plt.ylim([0, maxval])\n- plt.xlabel('Obs ' + species + ' (' + units + ')')\n- plt.title(title)\n- plt.gca().axes.set_ylabel('Model ' + species + ' (' + units + ')')\n- if footer:\n- footer_text(df)\n- plt.tight_layout()\n- plt.grid(alpha=.5)\n- else:\n- ax = fig.get_axes()[0]\n- l, = ax.scatter(df.Obs, df.CMAQ, marker='o', edgecolors='w', alpha=.3, label=label)\n- tt = linregress(df.Obs.values, df.CMAQ.values)\n- ax.plot(df.Obs.unique(), tt[0] * df.Obs.unique() + tt[1], color=l.get_color())\n- plt.legend(loc='Best')\n-\n-\n-def diffscatter_param(df, title=None, fig=None, label=None, footer=True):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- df : type\n- Description of parameter `df`.\n- title : type\n- Description of parameter `title` (the default is None).\n- fig : type\n- Description of parameter `fig` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is True).\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- from scipy.stats import scoreatpercentile as score\n- from numpy import isnan\n- sns.set_style('ticks')\n- df = df.dropna()\n- mask = ~isnan(df.Obs.values) & ~isnan(df.CMAQ.values)\n- if fig is None:\n- species, units = df.Species.unique()[0], df.Units.unique()[0]\n- maxval = score(df.Obs.values[mask], per=99.9)\n- minvaly = score(df.CMAQ.values[mask] - df.Obs.values[mask], per=.1)\n- maxvaly = score(df.CMAQ.values[mask] - df.Obs.values[mask], per=99.9)\n- plt.figure(figsize=(10, 7))\n-\n- plt.scatter(df.Obs.values[mask], df.CMAQ.values[mask] - df.Obs.values[mask], c='cornflowerblue', marker='o',\n- edgecolors='w', alpha=.3, label=label)\n- plt.plot((0, maxval), (0, 0), '--', color='darkslategrey')\n-\n- plt.xlim([0, maxval])\n- plt.ylim([minvaly, maxvaly])\n- plt.xlabel('Obs ' + species + ' (' + units + ')')\n- plt.title(title)\n- plt.gca().axes.set_ylabel('Model - Obs ' + species + ' (' + units + ')')\n- if footer:\n- footer_text(df)\n- plt.tight_layout()\n- else:\n- ax = fig.get_axes()[0]\n- mask = ~isnan(df.Obs.values) & ~isnan(df.CMAQ.values)\n- ax.scatter(df.Obs.values[mask], df.CMAQ.values[mask] - df.Obs.values[mask], marker='o', edgecolors='w',\n- alpha=.3, label=label)\n- plt.legend(loc='best')\n+ if ax is None:\n+ f, ax = plt.subplots(figsize=(8, 6), frameon=False)\n+ ax = sns.regplot(data=df, x=x, y=y, label=label, **kwargs)\n+ plt.title(title)\n+ return ax\n \n \n-def taylordiagram(df, marker='o', label='CMAQ', addon=False, dia=None):\n+def taylordiagram(df,\n+ marker='o',\n+ col1='obs',\n+ col2='model',\n+ label='CMAQ',\n+ addon=False,\n+ dia=None):\n from numpy import corrcoef\n \n- df = df.drop_duplicates().dropna(subset=['Obs', 'CMAQ'])\n+ df = df.drop_duplicates().dropna(subset=[col1, col2])\n \n if not addon and dia is None:\n f = plt.figure(figsize=(12, 10))\n sns.set_style('ticks')\n- obsstd = df.Obs.std()\n+ obsstd = df[col1].std()\n \n dia = td.TaylorDiagram(obsstd, fig=f, rect=111, label='Obs')\n plt.grid(linewidth=1, alpha=.5)\n-\n- cc = corrcoef(df.Obs.values, df.CMAQ.values)[0, 1]\n- dia.add_sample(df.CMAQ.std(), cc, marker=marker, zorder=9, ls=None, label=label)\n+ cc = corrcoef(df[col1].values, df[col2].values)[0, 1]\n+ dia.add_sample(\n+ df[col2].std(), cc, marker=marker, zorder=9, ls=None, label=label)\n contours = dia.add_contours(colors='0.5')\n plt.clabel(contours, inline=1, fontsize=10)\n plt.grid(alpha=.5)\n@@ -687,12 +391,15 @@ def taylordiagram(df, marker='o', label='CMAQ', addon=False, dia=None):\n plt.tight_layout()\n \n elif not addon and dia is not None:\n- print 'Do you want to add this on? if so please turn the addon keyword to True'\n+ print('Do you want to add this on? if so please turn '\n+ 'the addon keyword to True')\n elif addon and dia is None:\n- print 'Please pass the previous Taylor Diagram Instance with dia keyword...'\n+ print('Please pass the previous Taylor Diagram Instance with dia '\n+ 'keyword...')\n else:\n cc = corrcoef(df.Obs.values, df.CMAQ.values)[0, 1]\n- dia.add_sample(df.CMAQ.std(), cc, marker=marker, zorder=9, ls=None, label=label)\n+ dia.add_sample(\n+ df.CMAQ.std(), cc, marker=marker, zorder=9, ls=None, label=label)\n plt.legend(fontsize='small', loc='best')\n plt.tight_layout()\n return dia\ndiff --git a/monet/plots/taylordiagram.py b/monet/plots/taylordiagram.py\n--- a/monet/plots/taylordiagram.py\n+++ b/monet/plots/taylordiagram.py\n@@ -1,24 +1,18 @@\n-#!/usr/bin/env python\n-# Copyright: This document has been placed in the public domain.\n-\n \"\"\"\n Taylor diagram (Taylor, 2001) test implementation.\n http://www-pcmdi.llnl.gov/about/staff/Taylor/CV/Taylor_diagram_primer.htm\n \"\"\"\n-from __future__ import division\n-from __future__ import print_function\n-\n-from builtins import zip\n-from builtins import map\n-from builtins import object\n-from past.utils import old_div\n+from __future__ import division, print_function\n \n-__version__ = \"Time-stamp: <2012-02-17 20:59:35 ycopin>\"\n-__author__ = \"Yannick Copin \"\n+from builtins import map, object, zip\n \n import matplotlib.pyplot as PLT\n import numpy as NP\n import seaborn as sns\n+from past.utils import old_div\n+\n+__version__ = \"Time-stamp: <2012-02-17 20:59:35 ycopin>\"\n+__author__ = \"Yannick Copin \"\n \n colors = ['#DA70D6', '#228B22', '#FA8072', '#FF1493']\n sns.set_palette(sns.color_palette(colors))\n@@ -53,13 +47,16 @@ def __init__(self, refstd, fig=None, rect=111, label='_'):\n # Standard deviation axis extent\n self.smin = 0\n self.smax = 1.5 * self.refstd\n-\n- ghelper = FA.GridHelperCurveLinear(tr,\n- extremes=(0, old_div(NP.pi, 2), # 1st quadrant\n- self.smin, self.smax),\n- grid_locator1=gl1,\n- tick_formatter1=tf1,\n- )\n+ ghelper = FA.GridHelperCurveLinear(\n+ tr,\n+ extremes=(\n+ 0,\n+ old_div(NP.pi, 2), # 1st quadrant\n+ self.smin,\n+ self.smax),\n+ grid_locator1=gl1,\n+ tick_formatter1=tf1,\n+ )\n \n if fig is None:\n fig = PLT.figure()\n@@ -91,8 +88,8 @@ def __init__(self, refstd, fig=None, rect=111, label='_'):\n \n # Add reference point and stddev contour\n print(\"Reference std:\", self.refstd)\n- l, = self.ax.plot([0], self.refstd, 'k*',\n- ls='', ms=10, label=label)\n+ l, = self.ax.plot(\n+ [0], self.refstd, 'r*', ls='', ms=14, label=label, zorder=10)\n t = NP.linspace(0, old_div(NP.pi, 2))\n r = NP.zeros_like(t) + self.refstd\n self.ax.plot(t, r, 'k--', label='_')\n@@ -104,9 +101,8 @@ def add_sample(self, stddev, corrcoef, *args, **kwargs):\n \"\"\"Add sample (stddev,corrcoeff) to the Taylor diagram. args\n and kwargs are directly propagated to the Figure.plot\n command.\"\"\"\n-\n- l, = self.ax.plot(NP.arccos(corrcoef), stddev,\n- *args, **kwargs) # (theta,radius)\n+ l, = self.ax.plot(NP.arccos(corrcoef), stddev, *args,\n+ **kwargs) # (theta,radius)\n self.samplePoints.append(l)\n \n return l\n@@ -114,10 +110,12 @@ def add_sample(self, stddev, corrcoef, *args, **kwargs):\n def add_contours(self, levels=5, **kwargs):\n \"\"\"Add constant centered RMS difference contours.\"\"\"\n \n- rs, ts = NP.meshgrid(NP.linspace(self.smin, self.smax),\n- NP.linspace(0, old_div(NP.pi, 2)))\n+ rs, ts = NP.meshgrid(\n+ NP.linspace(self.smin, self.smax), NP.linspace(\n+ 0, old_div(NP.pi, 2)))\n # Compute centered RMS difference\n- rms = NP.sqrt(self.refstd ** 2 + rs ** 2 - 2 * self.refstd * rs * NP.cos(ts))\n+ rms = NP.sqrt(self.refstd**2 + rs**2 -\n+ 2 * self.refstd * rs * NP.cos(ts))\n \n contours = self.ax.contour(ts, rs, rms, levels, **kwargs)\n \ndiff --git a/monet/util/__init__.py b/monet/util/__init__.py\n--- a/monet/util/__init__.py\n+++ b/monet/util/__init__.py\n@@ -1,7 +1,7 @@\n from __future__ import absolute_import, print_function\n \n-from . import mystats # , tools\n+from . import mystats, tools, interp_util, resample\n \n-__all__ = ['mystats', 'tools']\n+__all__ = ['mystats', 'tools', 'interp_util', 'resample']\n \n-__name__ = 'util'\n+#__name__ = 'util'\ndiff --git a/monet/util/interp_util.py b/monet/util/interp_util.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/util/interp_util.py\n@@ -0,0 +1,276 @@\n+\"\"\" Interpolation functions \"\"\"\n+from __future__ import print_function\n+\n+from builtins import str, zip\n+\n+\n+def lonlat_to_swathdefinition(longitude=None, latitude=None):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ longitude : type\n+ Description of parameter `longitude`.\n+ latitude : type\n+ Description of parameter `latitude`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from pyresample.geometry import SwathDefinition\n+ from numpy import vstack\n+ if len(longitude.shape) < 2:\n+ lons = vstack(longitude)\n+ lats = vstack(latitude)\n+ else:\n+ lons = longitude\n+ lats = latitude\n+ return SwathDefinition(lons=lons, lats=lats)\n+\n+\n+def nearest_point_swathdefinition(longitude=None, latitude=None):\n+ \"\"\"Creates a pyreample.geometry.SwathDefinition for a single point.\n+\n+ Parameters\n+ ----------\n+ longitude : float\n+ longitude.\n+ latitude : float\n+ latitude.\n+\n+ Returns\n+ -------\n+ pyreample.geometry.SwathDefinition\n+\n+\n+ \"\"\"\n+ from pyresample.geometry import SwathDefinition\n+ from numpy import vstack\n+ lons = vstack([longitude])\n+ lats = vstack([latitude])\n+ return SwathDefinition(lons=lons, lats=lats)\n+\n+\n+def constant_lat_swathdefition(longitude=None, latitude=None):\n+ \"\"\"Creates a pyreample.geometry.SwathDefinition with a constant latitude along\n+ the longitude array. Longitude can be a 1d or 2d np.array or xr.DataArray\n+\n+ Parameters\n+ ----------\n+ longitude : numpy.array or xarray.DataArray\n+ Array of longitude values\n+ latitude : float\n+ latitude for constant\n+\n+ Returns\n+ -------\n+ pyreample.geometry.SwathDefinition\n+\n+ \"\"\"\n+ from pyresample import geometry\n+ from xarray import DataArray\n+ from numpy import vstack\n+ if len(longitude.shape) < 2:\n+ lons = vstack(longitude)\n+ else:\n+ lons = longitude\n+ lats = lons * 0. + latitude\n+ if isinstance(lats, DataArray):\n+ lats.name = 'lats'\n+ return geometry.SwathDefinition(lons=lons, lats=lats)\n+\n+\n+def constant_lon_swathdefition(longitude=None, latitude=None):\n+ \"\"\"Creates a pyreample.geometry.SwathDefinition with a constant longitude along\n+ the latitude array. latitude can be a 1d or 2d np.array or xr.DataArray\n+\n+ Parameters\n+ ----------\n+ longitude :\n+ latitude for constant\n+ latitude : numpy.array or xarray.DataArray\n+ Array of longitude values\n+\n+ Returns\n+ -------\n+ pyreample.geometry.SwathDefinition\n+\n+ \"\"\"\n+ from pyresample import geometry\n+ from xarray import DataArray\n+ from numpy import vstack\n+ if len(latitude.shape) < 2:\n+ lats = vstack(latitude)\n+ else:\n+ lats = latitude\n+ lons = lats * 0. + longitude\n+ if isinstance(lats, DataArray):\n+ lons.name = 'lons'\n+ return geometry.SwathDefinition(lons=lons, lats=lats)\n+\n+\n+def get_smops_area_def(nx=1440, ny=720):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ nx : type\n+ Description of parameter `nx` (the default is 1440).\n+ ny : type\n+ Description of parameter `ny` (the default is 720).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from pyproj import Proj\n+ from pyresample import utils\n+ p = Proj(\n+ proj='eqc',\n+ lat_ts=0.,\n+ lat_0=0.,\n+ lon_0=0.,\n+ x_0=0.,\n+ y_0=0.,\n+ a=6378137,\n+ b=6378137,\n+ units='m')\n+ proj4_args = p.srs\n+ area_name = 'Global .25 degree SMOPS Grid'\n+ area_id = 'smops'\n+ proj_id = area_id\n+ aa = p([-180, 180], [-90, 90])\n+ area_extent = (aa[0][0], aa[1][0], aa[0][1], aa[1][1])\n+ area_def = utils.get_area_def(area_id, area_name, proj_id, proj4_args, nx,\n+ ny, area_extent)\n+ return area_def\n+\n+\n+def get_gfs_area_def(nx=1440, ny=721):\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ nx : type\n+ Description of parameter `nx` (the default is 1440).\n+ ny : type\n+ Description of parameter `ny` (the default is 721).\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ from pyresample import utils\n+ from pyproj import Proj\n+ # proj4_args = '+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0\n+ # +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m'\n+ p = Proj(\n+ proj='eqc',\n+ lat_ts=0.,\n+ lat_0=0.,\n+ lon_0=0.,\n+ x_0=0.,\n+ y_0=0.,\n+ a=6378137,\n+ b=6378137,\n+ units='m')\n+ proj4_args = p.srs\n+ area_name = 'Global .25 degree SMOPS Grid'\n+ area_id = 'smops'\n+ proj_id = area_id\n+ aa = p([0, 360 - .25], [-90, 90.])\n+ area_extent = (aa[0][0], aa[1][0], aa[0][1], aa[1][1])\n+ area_def = utils.get_area_def(area_id, area_name, proj_id, proj4_args, nx,\n+ ny, area_extent)\n+ return area_def\n+\n+\n+def geotiff_meta_to_areadef(meta):\n+ \"\"\"\n+ Transform (Rasterio) geotiff meta dictionary to pyresample area definition\n+ Arguments:\n+ meta (dictionary) : dictionary containing projection and image geometry\n+ information (formed by Rasterio)\n+ Returns:\n+ area_def (pyresample.geometry.AreaDefinition) : Area definition object\n+ \"\"\"\n+ import pyresample\n+ area_id = \"\"\n+ name = \"\"\n+ proj_id = \"Generated from GeoTIFF\"\n+ proj_dict = meta['crs']\n+ proj_dict_with_string_values = dict(\n+ list(\n+ zip([str(key) for key in list(proj_dict.keys())],\n+ [str(value) for value in list(proj_dict.values())])))\n+ x_size = meta['width']\n+ x_res = meta['transform'][0]\n+ y_res = meta['transform'][4] * -1\n+ y_size = meta['height']\n+ x_ll = meta['transform'][2]\n+ y_ur = meta['transform'][5]\n+ y_ll = y_ur - y_size * y_res\n+ x_ur = x_ll + x_size * x_res\n+ area_extent = [x_ll, y_ll, x_ur, y_ur]\n+ print(area_extent, x_size, y_size, x_res, y_res)\n+\n+ area_def = pyresample.geometry.AreaDefinition(\n+ area_id, name, proj_id, proj_dict_with_string_values, x_size, y_size,\n+ area_extent)\n+ # print(area_extent, x_size, y_size)\n+ return area_def\n+\n+\n+def geotiff_meta_to_areadef2(meta):\n+ \"\"\"\n+ Transform (Rasterio) geotiff meta dictionary to pyresample area definition\n+ Arguments:\n+ meta (dictionary) : dictionary containing projection and image geometry\n+ information (formed by Rasterio)\n+ Returns:\n+ area_def (pyresample.geometry.AreaDefinition) : Area definition object\n+ \"\"\"\n+ import pyresample\n+ area_id = \"\"\n+ name = \"\"\n+ proj_id = \"Generated from GeoTIFF\"\n+ proj_dict = meta['crs']\n+ proj_dict_with_string_values = dict(\n+ list(\n+ zip([str(key) for key in list(proj_dict.keys())],\n+ [str(value) for value in list(proj_dict.values())])))\n+ x_size = meta['width']\n+ x_res = 50000.\n+ y_res = 50000.\n+ y_size = meta['height']\n+ x_ll = meta['transform'][2]\n+ y_ur = meta['transform'][5]\n+ y_ll = y_ur - y_size * y_res\n+ x_ur = x_ll + x_size * x_res\n+ area_extent = [x_ll, y_ll, x_ur, y_ur]\n+ print(area_extent, x_size, y_size, x_res, y_res)\n+\n+ area_def = pyresample.geometry.AreaDefinition(\n+ area_id, name, proj_id, proj_dict_with_string_values, x_size, y_size,\n+ area_extent)\n+ return area_def\n+ \"\"\"Short summary.\n+\n+ Parameters\n+ ----------\n+ meta : type\n+ Description of parameter `meta`.\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\ndiff --git a/monet/util/mystats.py b/monet/util/mystats.py\n--- a/monet/util/mystats.py\n+++ b/monet/util/mystats.py\n@@ -18,27 +18,33 @@ def STDP(obs, mod, axis=None):\n \n def MNB(obs, mod, axis=None):\n \"\"\" Mean Normalized Bias (%)\"\"\"\n- return np.ma.masked_invalid(old_div((mod - obs), obs)).mean(axis=axis) * 100.\n+ return np.ma.masked_invalid(old_div(\n+ (mod - obs), obs)).mean(axis=axis) * 100.\n+\n \n \n def MNE(obs, mod, axis=None):\n \"\"\" Mean Normalized Gross Error (%)\"\"\"\n- return np.ma.masked_invalid(old_div(np.ma.abs(mod - obs), obs)).mean(axis=axis) * 100.\n-\n+ return np.ma.masked_invalid(old_div(np.ma.abs(mod - obs),\n+ obs)).mean(axis=axis) * 100.\n \n def MdnNB(obs, mod, axis=None):\n \"\"\" Median Normalized Bias (%)\"\"\"\n- return np.ma.median(np.ma.masked_invalid(old_div((mod - obs), obs)), axis=axis) * 100.\n-\n+ return np.ma.median(\n+ np.ma.masked_invalid(old_div((mod - obs), obs)), axis=axis) * 100.\n \n def MdnNE(obs, mod, axis=None):\n \"\"\" Median Normalized Gross Error (%)\"\"\"\n- return np.ma.median(np.ma.masked_invalid(old_div(np.ma.abs(mod - obs), obs)), axis=axis) * 100.\n+ return np.ma.median(\n+ np.ma.masked_invalid(old_div(np.ma.abs(mod - obs), obs)),\n+ axis=axis) * 100.\n \n \n-def NMdnE(obs, mod, axis=None):\n+def NMdnGE(obs, mod, axis=None):\n \"\"\" Normalized Median Gross Error (%)\"\"\"\n- return np.ma.masked_invalid(old_div(np.ma.abs(mod - obs).mean(axis=axis), obs.mean(axis=axis))) * 100.\n+ return np.ma.masked_invalid(\n+ old_div(np.ma.abs(mod - obs).mean(axis=axis),\n+ obs.mean(axis=axis))) * 100.\n \n \n def NO(obs, mod, axis=None):\n@@ -114,12 +120,15 @@ def NMB(obs, mod, axis=None):\n \n def NMdnB(obs, mod, axis=None):\n \"\"\" Normalized Median Bias (%)\"\"\"\n- return np.ma.median(mod - obs, axis=axis) / np.ma.median(obs, axis=axis) * 100.\n+ return np.ma.median(\n+ mod - obs, axis=axis) / np.ma.median(\n+ obs, axis=axis) * 100.\n \n \n def FB(obs, mod, axis=None):\n \"\"\" Fractional Bias (%)\"\"\"\n- return ((np.ma.masked_invalid(old_div((mod - obs), (mod + obs)))).mean(axis=axis) * 2.) * 100.\n+ return ((np.ma.masked_invalid(old_div(\n+ (mod - obs), (mod + obs)))).mean(axis=axis) * 2.) * 100.\n \n \n def ME(obs, mod, axis=None):\n@@ -145,73 +154,93 @@ def WDMdnE(obs, mod, axis=None):\n \n def NME(obs, mod, axis=None):\n \"\"\" Normalized Mean Error (%)\"\"\"\n- out = (old_div(np.ma.abs(mod - obs).sum(axis=axis), obs.sum(axis=axis))) * 100\n+ out = (old_div(np.ma.abs(mod - obs).sum(axis=axis),\n+ obs.sum(axis=axis))) * 100\n return out\n \n \n def NMdnE(obs, mod, axis=None):\n \"\"\" Normalized Median Error (%)\"\"\"\n- out = np.ma.median(np.ma.abs(mod - obs), axis=axis) / np.ma.median(obs, axis=axis) * 100\n+ out = np.ma.median(\n+ np.ma.abs(mod - obs), axis=axis) / np.ma.median(\n+ obs, axis=axis) * 100\n return out\n \n \n def FE(obs, mod, axis=None):\n \"\"\" Fractional Error (%)\"\"\"\n- return (old_div(np.ma.abs(mod - obs), (mod + obs))).mean(axis=axis) * 2. * 100.\n+ return (old_div(np.ma.abs(mod - obs),\n+ (mod + obs))).mean(axis=axis) * 2. * 100.\n \n \n def USUTPB(obs, mod, axis=None):\n \"\"\" Unpaired Space/Unpaired Time Peak Bias (%)\"\"\"\n- return (old_div((mod.max(axis=axis) - obs.max(axis=axis)), obs.max(axis=axis))) * 100.\n+ return (old_div(\n+ (mod.max(axis=axis) - obs.max(axis=axis)), obs.max(axis=axis))) * 100.\n \n \n def USUTPE(obs, mod, axis=None):\n \"\"\" Unpaired Space/Unpaired Time Peak Error (%)\"\"\"\n- return (old_div(np.ma.abs(mod.max(axis=axis) - obs.max(axis=axis)), obs.max(axis=axis))) * 100.\n+ return (old_div(\n+ np.ma.abs(mod.max(axis=axis) - obs.max(axis=axis)),\n+ obs.max(axis=axis))) * 100.\n \n \n def MNPB(obs, mod, paxis, axis=None):\n \"\"\" Mean Normalized Peak Bias (%)\"\"\"\n- return (old_div((mod.max(axis=paxis) - obs.max(axis=paxis)), obs.max(axis=paxis))).mean(axis=axis) * 100.\n+ return (old_div(\n+ (mod.max(axis=paxis) - obs.max(axis=paxis)),\n+ obs.max(axis=paxis))).mean(axis=axis) * 100.\n \n \n def MdnNPB(obs, mod, paxis, axis=None):\n \"\"\" Median Normalized Peak Bias (%)\"\"\"\n- return np.ma.median(old_div((mod.max(axis=paxis) - obs.max(axis=paxis)), obs.max(axis=paxis)), axis=axis) * 100.\n+ return np.ma.median(\n+ old_div(\n+ (mod.max(axis=paxis) - obs.max(axis=paxis)), obs.max(axis=paxis)),\n+ axis=axis) * 100.\n \n \n def MNPE(obs, mod, paxis, axis=None):\n \"\"\" Mean Normalized Peak Error (%)\"\"\"\n- return (old_div((np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))), obs.max(axis=paxis))).mean(axis=axis) * 100.\n-\n+ return (old_div(\n+ (np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))),\n+ obs.max(axis=paxis))).mean(axis=axis) * 100.\n \n def MdnNPE(obs, mod, paxis, axis=None):\n \"\"\" Median Normalized Peak Bias (%)\"\"\"\n- return np.ma.median(old_div((np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))), obs.max(axis=paxis)),\n- axis=axis) * 100.\n+ return np.ma.median(\n+ old_div(\n+ (np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))),\n+ obs.max(axis=paxis)),\n+ axis=axis) * 100.\n \n \n def NMPB(obs, mod, paxis, axis=None):\n \"\"\" Normalized Mean Peak Bias (%)\"\"\"\n- return (mod.max(axis=paxis) - obs.max(axis=paxis)).mean(axis=axis) / obs.max(axis=paxis).mean(axis=axis) * 100.\n+ return (mod.max(axis=paxis) - obs.max(axis=paxis)\n+ ).mean(axis=axis) / obs.max(axis=paxis).mean(axis=axis) * 100.\n \n \n def NMdnPB(obs, mod, paxis, axis=None):\n \"\"\" Normalized Median Peak Bias (%)\"\"\"\n- return np.ma.median((mod.max(axis=paxis) - obs.max(axis=paxis)), axis=axis) / np.ma.median(obs.max(axis=paxis),\n- axis=axis) * 100.\n+ return np.ma.median(\n+ (mod.max(axis=paxis) - obs.max(axis=paxis)), axis=axis) / np.ma.median(\n+ obs.max(axis=paxis), axis=axis) * 100.\n \n \n def NMPE(obs, mod, paxis, axis=None):\n \"\"\" Normalized Mean Peak Error (%)\"\"\"\n- return (np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))).mean(axis=axis) / obs.max(axis=paxis).mean(\n- axis=axis) * 100.\n+ return (np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis))\n+ ).mean(axis=axis) / obs.max(axis=paxis).mean(axis=axis) * 100.\n \n \n def NMdnPE(obs, mod, paxis, axis=None):\n \"\"\" Normalized Median Peak Bias (%)\"\"\"\n- return np.ma.median(np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis)), axis=axis) / np.ma.median(\n- obs.max(axis=paxis), axis=axis) * 100.\n+ return np.ma.median(\n+ np.ma.abs(mod.max(axis=paxis) - obs.max(axis=paxis)),\n+ axis=axis) / np.ma.median(\n+ obs.max(axis=paxis), axis=axis) * 100.\n \n \n def PSUTMNPB(obs, mod, axis=None):\n@@ -259,19 +288,19 @@ def R2(obs, mod, axis=None):\n from scipy.stats import pearsonr\n if axis is None:\n obsc, modc = matchedcompressed(obs, mod)\n- return pearsonr(obsc, modc)[0] ** 2\n+ return pearsonr(obsc, modc)[0]**2\n else:\n raise ValueError('Not ready yet')\n \n \n def RMSE(obs, mod, axis=None):\n \"\"\" Root Mean Square Error (model unit)\"\"\"\n- return np.ma.sqrt(((mod - obs) ** 2).mean(axis=axis))\n+ return np.ma.sqrt(((mod - obs)**2).mean(axis=axis))\n \n \n def WDRMSE(obs, mod, axis=None):\n \"\"\" Wind Direction Root Mean Square Error (model unit)\"\"\"\n- return np.ma.sqrt(((circlebias(mod - obs)) ** 2).mean(axis=axis))\n+ return np.ma.sqrt(((circlebias(mod - obs))**2).mean(axis=axis))\n \n \n def RMSEs(obs, mod, axis=None):\n@@ -316,13 +345,17 @@ def RMSEu(obs, mod, axis=None):\n \n def d1(obs, mod, axis=None):\n \"\"\" Modified Index of Agreement, d1\"\"\"\n- return 1.0 - old_div((np.ma.abs(obs - mod)).sum(axis=axis), (\n- np.ma.abs(mod - obs.mean(axis=axis)) + np.ma.abs(obs - obs.mean(axis=axis))).sum(axis=axis))\n+ return 1.0 - old_div(\n+ (np.ma.abs(obs - mod)).sum(axis=axis),\n+ (np.ma.abs(mod - obs.mean(axis=axis)) +\n+ np.ma.abs(obs - obs.mean(axis=axis))).sum(axis=axis))\n \n \n def E1(obs, mod, axis=None):\n \"\"\" Modified Coefficient of Efficiency, E1\"\"\"\n- return 1.0 - old_div((np.ma.abs(obs - mod)).sum(axis=axis), (np.ma.abs(obs - obs.mean(axis=axis))).sum(axis=axis))\n+ return 1.0 - old_div(\n+ (np.ma.abs(obs - mod)).sum(axis=axis),\n+ (np.ma.abs(obs - obs.mean(axis=axis))).sum(axis=axis))\n \n \n def IOA(obs, mod, axis=None):\n@@ -330,8 +363,10 @@ def IOA(obs, mod, axis=None):\n obsmean = obs.mean(axis=axis)\n if not axis is None:\n obsmean = np.expand_dims(obsmean, axis=axis)\n- return 1.0 - old_div((np.ma.abs(obs - mod) ** 2).sum(axis=axis), (\n- (np.ma.abs(mod - obsmean) + np.ma.abs(obs - obsmean)) ** 2).sum(axis=axis))\n+ return 1.0 - old_div(\n+ (np.ma.abs(obs - mod)**2).sum(axis=axis),\n+ ((np.ma.abs(mod - obsmean) + np.ma.abs(obs - obsmean)) **\n+ 2).sum(axis=axis))\n \n \n def circlebias(b):\n@@ -351,7 +386,9 @@ def WDIOA(obs, mod, axis=None):\n \n ohat = circlebias(obs - obsmean)\n \n- return 1.0 - old_div((np.ma.abs(b) ** 2).sum(axis=axis), ((np.ma.abs(bhat) + np.ma.abs(ohat)) ** 2).sum(axis=axis))\n+ return 1.0 - old_div(\n+ (np.ma.abs(b)**2).sum(axis=axis),\n+ ((np.ma.abs(bhat) + np.ma.abs(ohat))**2).sum(axis=axis))\n \n \n def AC(obs, mod, axis=None):\n@@ -360,7 +397,8 @@ def AC(obs, mod, axis=None):\n if not axis is None:\n obs_bar = np.expand_dims(obs_bar, axis=axis)\n p1 = ((mod - obs_bar) * (obs - obs_bar)).sum(axis=axis)\n- p2 = (((mod - obs_bar) ** 2).sum(axis=axis) * ((obs - obs_bar) ** 2).sum(axis=axis)) ** 0.5\n+ p2 = (((mod - obs_bar)**2).sum(axis=axis) * (\n+ (obs - obs_bar)**2).sum(axis=axis))**0.5\n return old_div(p1, p2)\n \n \n@@ -370,7 +408,8 @@ def WDAC(obs, mod, axis=None):\n if not axis is None:\n obs_bar = np.expand_dims(obs_bar, axis=axis)\n p1 = (circlebias(mod - obs_bar) * circlebias(obs - obs_bar)).sum(axis=axis)\n- p2 = ((circlebias(mod - obs_bar) ** 2).sum(axis=axis) * (circlebias(obs - obs_bar) ** 2).sum(axis=axis)) ** 0.5\n+ p2 = ((circlebias(mod - obs_bar)**2).sum(axis=axis) *\n+ (circlebias(obs - obs_bar)**2).sum(axis=axis))**0.5\n return old_div(p1, p2)\n \n \n@@ -410,8 +449,10 @@ def scores(obs, mod, minval, maxval=1.0e5):\n d['obs'] = obs\n d['mod'] = mod\n df = DataFrame(d)\n- ct = crosstab((df['mod'] > minval) & (df['mod'] < maxval), (df['obs'] > minval) & (df['obs'] < maxval),\n- margins=True)\n+ ct = crosstab(\n+ (df['mod'] > minval) & (df['mod'] < maxval),\n+ (df['obs'] > minval) & (df['obs'] < maxval),\n+ margins=True)\n # print ct\n a = ct[1][1].astype('float')\n b = ct[1][0].astype('float')\ndiff --git a/monet/util/resample.py b/monet/util/resample.py\nnew file mode 100644\n--- /dev/null\n+++ b/monet/util/resample.py\n@@ -0,0 +1,144 @@\n+from pyresample.kd_tree import XArrayResamplerNN\n+from pyresample.bilinear.xarr import XArrayResamplerBilinear\n+import xarray as xr\n+from pyresample.geometry import SwathDefinition, AreaDefinition\n+\n+\n+def _ensure_swathdef_compatability(defin):\n+ \"\"\"ensures the SwathDefinition is compatible with XArrayResamplerNN.\n+\n+ Parameters\n+ ----------\n+ defin : pyresample SwathDefinition\n+ a pyresample.geometry.SwathDefinition instance\n+\n+ Returns\n+ -------\n+ type\n+ Description of returned object.\n+\n+ \"\"\"\n+ if isinstance(defin.lons, xr.DataArray):\n+ return defin # do nothing\n+ else:\n+ defin.lons = xr.DataArray(defin.lons, dims=['y', 'x']).chunk()\n+ defin.lats = xr.DataArray(defin.lons, dims=['y', 'x']).chunk()\n+ return defin\n+\n+\n+def _check_swath_or_area(defin):\n+ \"\"\"Checks for a SwathDefinition or AreaDefinition. If AreaDefinition do\n+ nothing else ensure compatability with XArrayResamplerNN\n+\n+ Parameters\n+ ----------\n+ defin : pyresample SwathDefinition or AreaDefinition\n+ Description of parameter `defin`.\n+\n+ Returns\n+ -------\n+ pyresample.geometry\n+ SwathDefinition or AreaDefinition\n+\n+ \"\"\"\n+ try:\n+ if isinstance(defin, SwathDefinition):\n+ newswath = _ensure_swathdef_compatability(defin)\n+ elif isinstance(defin, AreaDefinition):\n+ newswath = defin\n+ else:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('grid definition must be a pyresample SwathDefinition or '\n+ 'AreaDefinition')\n+ return\n+ return newswath\n+\n+\n+def _reformat_resampled_data(orig, new, target_grid):\n+ \"\"\"reformats the resampled data array filling in coords, name and attrs .\n+\n+ Parameters\n+ ----------\n+ orig : xarray.DataArray\n+ original input DataArray.\n+ new : xarray.DataArray\n+ resampled xarray.DataArray\n+ target_grid : pyresample.geometry\n+ target grid is the target SwathDefinition or AreaDefinition\n+\n+ Returns\n+ -------\n+ xarray.DataArray\n+ reformated xarray.DataArray\n+\n+ \"\"\"\n+ target_lon, target_lat = target_grid.get_lonlats_dask()\n+ new.name = orig.name\n+ new['latitude'] = (('y', 'x'), target_lat)\n+ new['longitude'] = (('y', 'x'), target_lon)\n+ new.attrs['area'] = target_grid\n+ return new\n+\n+\n+def resample_dataset(data,\n+ target_grid,\n+ radius_of_influence=100e3,\n+ resample_cache=None,\n+ return_neighbor_info=False,\n+ neighbours=1,\n+ epsilon=0,\n+ interp='nearest'):\n+ # first get the source grid definition\n+ try:\n+ if 'area' in data.attrs:\n+ source_grid = data.attrs['area']\n+ else:\n+ raise RuntimeError\n+ except RuntimeError:\n+ print('Must include pyresample.gemoetry in the data.attrs area_def or '\n+ 'area')\n+ return\n+\n+ # check for SwathDefinition or AreaDefinition\n+ # if swath ensure it is xarray.DataArray and not numpy for chunking\n+ source_grid = _check_swath_or_area(source_grid)\n+\n+ # set kwargs for XArrayResamplerNN\n+ kwargs = dict(\n+ source_geo_def=source_grid,\n+ target_geo_def=target_grid,\n+ radius_of_influence=radius_of_influence,\n+ neighbours=neighbours,\n+ epsilon=epsilon)\n+ if interp is 'nearest':\n+ resampler = XArrayResamplerNN(**kwargs)\n+ else:\n+ resampler = XArrayResamplerBilinear(**kwargs)\n+\n+ # check if resample cash is none else assume it is a dict with keys\n+ #[valid_input_index, valid_output_index, index_array, distance_array]\n+ # else generate the data\n+ if resample_cache is None:\n+ valid_input_index, valid_output_index, index_array, distance_array = resampler.get_neighbour_info(\n+ )\n+ else:\n+ resampler.valid_input_index = resample_cache['valid_input_index']\n+ resampler.valid_output_index = resample_cache['valid_output_index']\n+ resampler.index_array = resample_cache['index_array']\n+ resampler.distance_array = resample_cache['distance_array']\n+\n+ # now store the resampled data temporarily in temp\n+ temp = resampler.get_sample_from_neighbour_info(data)\n+\n+ # reformat data from temp\n+ out = _reformat_resampled_data(data, temp, target_grid)\n+ if return_neighbor_info:\n+ resample_cache = dict(\n+ valid_input_index=valid_input_index,\n+ valid_output_index=valid_output_index,\n+ index_array=index_array,\n+ distance_array=distance_array)\n+ return out, resample_cache\n+ else:\n+ return out\ndiff --git a/monet/util/tools.py b/monet/util/tools.py\n--- a/monet/util/tools.py\n+++ b/monet/util/tools.py\n@@ -3,7 +3,6 @@\n from builtins import range\n \n import numpy as np\n-from past.utils import old_div\n \n __author__ = 'barry'\n \n@@ -74,3 +73,16 @@ def wsdir2uv(ws, wdir):\n u = -ws * sin(wdir * pi / 180.)\n v = -ws * cos(wdir * pi / 180.)\n return u, v\n+\n+def long_to_wide(df):\n+ from pandas import Series, merge\n+ w = df.pivot_table(\n+ values='obs', index=['time', 'siteid'],\n+ columns='variable').reset_index()\n+ cols = Series(df.columns)\n+ g = df.groupby('variable')\n+ for name, group in g:\n+ w[name + '_unit'] = group.units.unique()[0]\n+ #mergeon = hstack((index.values, df.variable.unique()))\n+ return merge(w, df, on=['siteid', 'time'])\n+\ndiff --git a/monet/verification/__init__.py b/monet/verification/__init__.py\n--- a/monet/verification/__init__.py\n+++ b/monet/verification/__init__.py\n@@ -1,7 +1,7 @@\n from __future__ import absolute_import, print_function\n \n-from . import combine, interpolation, verify\n+from . import verify\n \n-__all__ = ['combine', 'interpolation', 'verify']\n+__all__ = ['verify']\n \n __name__ = 'verification'\ndiff --git a/monet/verification/verify.py b/monet/verification/verify.py\n--- a/monet/verification/verify.py\n+++ b/monet/verification/verify.py\n@@ -1,204 +1,436 @@\n-from __future__ import absolute_import, print_function\n+\"\"\"This needs to be modularized for plotting\"\"\"\n+# from __future__ import absolute_import, print_function\n+#\n+# from builtins import object\n+#\n+# import pandas as pd\n+#\n+# from ..plots import plots\n+#\n+#\n+# class VERIFY(object):\n+# def __init__(self, input, obs=None, model=None):\n+# self.dset = input\n+# self.obs = obs\n+# self.model = model\n+# self.default_scatter_args = {'s': 20, 'edgecolors': 'w', 'lw': .25}\n+#\n+# def point(self,\n+# param,\n+# plot_type=None,\n+# label=None,\n+# title=None,\n+# ax=None,\n+# plotargs={},\n+# fillargs={'alpha': .2},\n+# marker='o',\n+# **kwargs):\n+# if isinstance(self.dset, pd.DataFrame):\n+# if self.obs.objtype is 'AQS' or self.obs.objtype is 'AirNow':\n+# df, title = self.subset_epa(self.dset, param, **kwargs)\n+# elif self.obs.objtype is 'CRN' or self.obs.objtype is 'ISH':\n+# df, title = self.subset_crn(self.dset, **kwargs)\n+# else:\n+# df = self.pair\n+# if title is not None:\n+# title = ''\n+# df.index = df.time\n+# print(plot_type)\n+# if plot_type.lower() == 'timeseries':\n+# ax = self._point_plot(\n+# df,\n+# col1='model',\n+# label=label,\n+# title=title,\n+# timeseries=True,\n+# plotargs=plotargs,\n+# fillargs=fillargs,\n+# ax=ax)\n+# plotargs['color'] = 'darkslategrey'\n+# fillargs['color'] = 'darkslategrey'\n+# ax = self._point_plot(\n+# df,\n+# col1='obs',\n+# ax=ax,\n+# title=title,\n+# timeseries=True,\n+# plotargs=plotargs,\n+# fillargs=fillargs)\n+# elif plot_type.lower() == 'scatter':\n+# kwargs['x'] = 'obs'\n+# kwargs['y'] = 'model'\n+# ax = self._point_plot(\n+# df,\n+# col1='obs',\n+# col2='model',\n+# label=label,\n+# title=title,\n+# scatter=True)\n+# elif plot_type.lower == 'box':\n+# ax = self._point_plot(\n+# df,\n+# col1='obs',\n+# col2='model',\n+# label=label,\n+# title=title,\n+# box=True,\n+# plotargs=plotargs)\n+# elif plot_type.lower() == 'pdf':\n+# ax = self._point_plot(\n+# df,\n+# col1='model',\n+# label=label,\n+# title=title,\n+# pdf=True,\n+# plotargs=plotargs,\n+# ax=ax)\n+# plotargs['color'] = 'darkslategrey'\n+# ax = self._point_plot(\n+# df,\n+# col1='obs',\n+# label=self.obs.objtype,\n+# title=title,\n+# pdf=True,\n+# plotargs=plotargs,\n+# ax=ax)\n+# elif plot_type.lower() == 'taylor':\n+# ax = self._point_plot(\n+# df,\n+# col1='model',\n+# label=label,\n+# title=title,\n+# taylor=True,\n+# plotargs=plotargs,\n+# fillargs=fillargs,\n+# marker=marker)\n+# # elif\n+# return ax\n+#\n+# def _point_plot(self,\n+# df,\n+# label=None,\n+# title=None,\n+# ax=None,\n+# plotargs={},\n+# fillargs={},\n+# timeseries=False,\n+# scatter=False,\n+# pdf=False,\n+# taylor=False,\n+# box=False,\n+# col1=None,\n+# col2=None,\n+# marker='o',\n+# **kwargs):\n+# import matplotlib.pyplot as plt\n+# if timeseries:\n+# ax = plots.timeseries(\n+# df,\n+# y=col1,\n+# title=title,\n+# label=label,\n+# ax=ax,\n+# plotargs=plotargs,\n+# fillargs=fillargs)\n+# return ax\n+# if scatter:\n+# ax = plots.scatter(\n+# df, x=col1, y=col2, title=title, label=label, ax=ax, **kwargs)\n+# return ax\n+# if pdf:\n+# ax = plots.kdeplot(\n+# df[col1], title=title, label=label, ax=ax, **plotargs)\n+# ax.set_xlabel(df.variable.unique()[0] + ' (' +\n+# df.units.unique()[0] + ')')\n+# return ax\n+# if taylor:\n+# if marker is None:\n+# marker = 'o'\n+# if ax is None:\n+# dia = plots.taylordiagram(\n+# df, label=label, dia=ax, addon=False, marker=marker)\n+# return dia\n+# else:\n+# dia = plots.taylordiagram(\n+# df, label=label, dia=ax, addon=True, marker=marker)\n+# plt.legend()\n+# return dia\n+#\n+# def compare_surface(self, **kwargs):\n+# \"\"\"Short summary.\n+#\n+# Parameters\n+# ----------\n+# **kwargs : type\n+# Description of parameter `**kwargs`.\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# if (self.obs.objtype is 'AQS' or self.obs.objtype is 'AirNow') and (\n+# self.model.objtype is 'CMAQ' or self.model.objtype is 'CAMX'):\n+# self.compare_epa(**kwargs)\n+#\n+# def compare_spatial(self, **kwargs):\n+# \"\"\"Short summary.\n+#\n+# Parameters\n+# ----------\n+# **kwargs : type\n+# Description of parameter `**kwargs`.\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# if (self.obs.objtype is 'AQS' or self.obs.objtype is 'AIRNOW') and (\n+# self.model.objtype is 'CMAQ' or self.model.objtype is 'CAMX'):\n+# self.compare_epa_spatial(**kwargs)\n+#\n+# def compare_epa_spatial(self,\n+# model_param='O3',\n+# param='OZONE',\n+# date=None,\n+# imshow_args={},\n+# scatter_args={\n+# 's': 20,\n+# 'edgecolors': 'w',\n+# 'lw': .25\n+# },\n+# barbs_args={},\n+# barbs=False,\n+# Obs=True,\n+# ncolors=None,\n+# discrete=False,\n+# lay=None):\n+# \"\"\"Short summary.\n+#\n+# Parameters\n+# ----------\n+# model_param : type\n+# Description of parameter `model_param` (the default is 'O3').\n+# param : type\n+# Description of parameter `param` (the default is 'OZONE').\n+# date : type\n+# Description of parameter `date` (the default is None).\n+# imshow_args : type\n+# Description of parameter `imshow_args` (the default is {}).\n+# scatter_args : type\n+# Description of parameter `scatter_args` (the default is {'s': 20).\n+# 'edgecolors': 'w' : type\n+# Description of parameter `'edgecolors': 'w'`.\n+# 'lw': .25} : type\n+# Description of parameter `'lw': .25}`.\n+# barbs_args : type\n+# Description of parameter `barbs_args` (the default is {}).\n+# barbs : type\n+# Description of parameter `barbs` (the default is False).\n+# Obs : type\n+# Description of parameter `Obs` (the default is True).\n+# ncolors : type\n+# Description of parameter `ncolors` (the default is None).\n+# discrete : type\n+# Description of parameter `discrete` (the default is False).\n+# lay : type\n+# Description of parameter `lay` (the default is None).\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# :param param: variable Parameter: Acceptable variable: 'OZONE' 'PM2.5' 'CO' 'NOY' 'SO2' 'SO2' 'NOX'\n+# :param region: EPA Region: 'Northeast', 'Southeast', 'North_Central', 'South_Central', 'Rockies', 'Pacific'\n+# :param date: If not supplied will plot all time. Put in 'YYYY-MM-DD HH:MM' for single time\n+# :return:\n+# \"\"\"\n+# from numpy import where\n+# if Obs:\n+# try:\n+# g = self.obs.df.groupby('variable')\n+# df2 = g.get_group(param)\n+# except KeyError:\n+# print(param + ' variable not available!!!!')\n+# exit\n+# param = param.upper()\n+# v = self.model.get_var(param=model_param, lay=lay)\n+# m = self.cmaq.map\n+# dts = v.time.to_index()\n+# if isinstance(date, type(None)):\n+# index = where(dts == dts[0])[0][0]\n+# else:\n+# index = where(dts.isin([date]))[0][0]\n+# f, ax, c, cmap, vmin, vmax = plots.make_spatial_plot2(\n+# self.model.dset[index, :, :].squeeze(),\n+# m,\n+# plotargs=imshow_args,\n+# ncolors=ncolors,\n+# discrete=discrete)\n+# plt.tight_layout()\n+# if Obs:\n+# scatter_args['vmin'] = vmin\n+# scatter_args['vmax'] = vmax\n+# scatter_args['cmap'] = cmap\n+# df2 = df2.loc[df2.datetime == dts[index]]\n+# plots.spatial_scatter(df2, m, plotargs=scatter_args)\n+# c.set_label(param + ' (' + g.get_group(param).Units.unique()[0] +\n+# ')')\n+#\n+# @staticmethod\n+# def subset_epa(df,\n+# param,\n+# site=None,\n+# city=None,\n+# state=None,\n+# region=None,\n+# epa_region=None):\n+# from ..obs.epa_util import get_epa_location_df\n+# if site is None and city is None and state is None and region is None and epa_region is None:\n+# df2 = df.copy()\n+# title = ' '\n+# else:\n+# df2, title = get_epa_location_df(\n+# df.copy(),\n+# param,\n+# site=site,\n+# city=city,\n+# state=state,\n+# region=region,\n+# epa_region=epa_region)\n+# return df2, title\n+#\n+# def compare_epa(self,\n+# param='OZONE',\n+# site='',\n+# city='',\n+# state='',\n+# epa_region='',\n+# region='',\n+# timeseries=False,\n+# scatter=False,\n+# pdfs=False,\n+# diffscatter=False,\n+# diffpdfs=False,\n+# timeseries_rmse=False,\n+# timeseries_mb=False,\n+# taylordiagram=False,\n+# ax=None,\n+# label=None,\n+# footer=False,\n+# dia=None,\n+# marker=None):\n+# \"\"\"Short summary.\n+#\n+# Parameters\n+# ----------\n+# param : type\n+# Description of parameter `param` (the default is 'OZONE').\n+# site : type\n+# Description of parameter `site` (the default is '').\n+# city : type\n+# Description of parameter `city` (the default is '').\n+# state : type\n+# Description of parameter `state` (the default is '').\n+# epa_region : type\n+# Description of parameter `epa_region` (the default is '').\n+# region : type\n+# Description of parameter `region` (the default is '').\n+# timeseries : type\n+# Description of parameter `timeseries` (the default is False).\n+# scatter : type\n+# Description of parameter `scatter` (the default is False).\n+# pdfs : type\n+# Description of parameter `pdfs` (the default is False).\n+# diffscatter : type\n+# Description of parameter `diffscatter` (the default is False).\n+# diffpdfs : type\n+# Description of parameter `diffpdfs` (the default is False).\n+# timeseries_rmse : type\n+# Description of parameter `timeseries_rmse` (the default is False).\n+# timeseries_mb : type\n+# Description of parameter `timeseries_mb` (the default is False).\n+# taylordiagram : type\n+# Description of parameter `taylordiagram` (the default is False).\n+# ax : type\n+# Description of parameter `ax` (the default is None).\n+# label : type\n+# Description of parameter `label` (the default is None).\n+# footer : type\n+# Description of parameter `footer` (the default is False).\n+# dia : type\n+# Description of parameter `dia` (the default is None).\n+# marker : type\n+# Description of parameter `marker` (the default is None).\n+#\n+# Returns\n+# -------\n+# type\n+# Description of returned object.\n+#\n+# \"\"\"\n+# from numpy import NaN\n+# from ..obs.epa_util import get_epa_location_df\n+# df2, title = get_epa_location_df(\n+# self.dset.copy(),\n+# param,\n+# site=site,\n+# city=city,\n+# state=state,\n+# region=region,\n+# epa_region=epa_region)\n+# df2 = df2.groupby('variable').get_group(param)\n+# if timeseries:\n+# if ax is None:\n+# ax = plots.timeseries_param(\n+# df2,\n+# col='Obs',\n+# title=title,\n+# label=label,\n+# ax=ax,\n+# plotargs={'color': 'darkslategrey'},\n+# fillargs={\n+# 'color': 'darkslategrey',\n+# 'alpha': .2\n+# })\n+# ax = plots.timeseries_param(\n+# df2,\n+# col='model',\n+# title=title,\n+# label=label,\n+# ax=ax,\n+# fillargs={'alpha': .2})\n+# if scatter:\n+# plots.scatter_param(\n+# df2, title=title, label=label, fig=fig, footer=footer)\n+# if pdfs:\n+# plots.kdeplots_param(\n+# df2, title=title, label=label, fig=fig, footer=footer)\n+# if diffscatter:\n+# plots.diffscatter_param(df2, title=title)\n+# if diffpdfs:\n+# plots.diffpdfs_param(\n+# df2, title=title, label=label, fig=fig, footer=footer)\n+# if timeseries_rmse:\n+# plots.timeseries_rmse_param(\n+# df2, title=title, label=label, fig=fig, footer=footer)\n+# if timeseries_mb:\n+# plots.timeseries_mb_param(\n+# df2, title=title, label=label, fig=fig, footer=footer)\n+# if taylordiagram:\n+# if marker is None:\n+# marker = 'o'\n+# if fig is None:\n+# dia = plots.taylordiagram(\n+# df2, label=label, dia=dia, addon=False, marker=marker)\n+# return dia\n+# else:\n+# dia = plots.taylordiagram(\n+# df2, label=label, dia=dia, addon=True, marker=marker)\n+# plt.legend()\n+# return dia\n \n-from builtins import object\n-\n-from ..plots import plots\n-\n-\n-class VERIFY(object):\n- def __init__(self, model=None, obs=None, dset=None):\n- self.model = model\n- self.obs = obs\n- self.dset = dset\n-\n- def compare_surface(self, **kwargs):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- **kwargs : type\n- Description of parameter `**kwargs`.\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- if (self.obs.objtype is 'AQS' or self.obs.objtype is 'AirNow') and (\n- self.model.objtype is 'CMAQ' or self.model.objtype is 'CAMX'):\n- self.compare_epa(**kwargs)\n-\n- def compare_spatial(self, **kwargs):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- **kwargs : type\n- Description of parameter `**kwargs`.\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- if (obs.objtype is 'AQS' or obs.objtype is 'AIRNOW') and (model.objtype is 'CMAQ' or model.objtype is 'CAMX'):\n- self.compare_epa_spatial(**kwargs)\n-\n- def compare_epa_spatial(self, model_param='O3', param='OZONE', date=None, imshow_args={},\n- scatter_args={'s': 20, 'edgecolors': 'w', 'lw': .25}, barbs_args={}, barbs=False, Obs=True,\n- ncolors=None, discrete=False, lay=None):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- model_param : type\n- Description of parameter `model_param` (the default is 'O3').\n- param : type\n- Description of parameter `param` (the default is 'OZONE').\n- date : type\n- Description of parameter `date` (the default is None).\n- imshow_args : type\n- Description of parameter `imshow_args` (the default is {}).\n- scatter_args : type\n- Description of parameter `scatter_args` (the default is {'s': 20).\n- 'edgecolors': 'w' : type\n- Description of parameter `'edgecolors': 'w'`.\n- 'lw': .25} : type\n- Description of parameter `'lw': .25}`.\n- barbs_args : type\n- Description of parameter `barbs_args` (the default is {}).\n- barbs : type\n- Description of parameter `barbs` (the default is False).\n- Obs : type\n- Description of parameter `Obs` (the default is True).\n- ncolors : type\n- Description of parameter `ncolors` (the default is None).\n- discrete : type\n- Description of parameter `discrete` (the default is False).\n- lay : type\n- Description of parameter `lay` (the default is None).\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- :param param: Species Parameter: Acceptable Species: 'OZONE' 'PM2.5' 'CO' 'NOY' 'SO2' 'SO2' 'NOX'\n- :param region: EPA Region: 'Northeast', 'Southeast', 'North_Central', 'South_Central', 'Rockies', 'Pacific'\n- :param date: If not supplied will plot all time. Put in 'YYYY-MM-DD HH:MM' for single time\n- :return:\n- \"\"\"\n- if Obs:\n- try:\n- g = df.groupby('Species')\n- df2 = g.get_group(param)\n- except KeyError:\n- print(param + ' Species not available!!!!')\n- exit\n- param = param.upper()\n- v = self.model.get_var(param=model_param, lay=lay)\n- m = self.cmaq.map\n- dts = v.time.to_index()\n- if isinstance(date, type(None)):\n- index = where(dts == dts[0])[0][0]\n- else:\n- index = where(dts.isin([date]))[0][0]\n- f, ax, c, cmap, vmin, vmax = plots.make_spatial_plot2(cmaq[index, :, :].squeeze(), m, plotargs=imshow_args,\n- ncolors=ncolors, discrete=discrete)\n- plt.tight_layout()\n- if Obs:\n- scatter_args['vmin'] = vmin\n- scatter_args['vmax'] = vmax\n- scatter_args['cmap'] = cmap\n- df2 = df2.loc[df2.datetime == dts[index]]\n- plots.spatial_scatter(df2, m, plotargs=scatter_args)\n- c.set_label(param + ' (' + g.get_group(param).Units.unique()[0] + ')')\n-\n- def compare_epa(self, param='OZONE', site='', city='', state='', epa_region='', region='', timeseries=False,\n- scatter=False, pdfs=False, diffscatter=False, diffpdfs=False, timeseries_rmse=False,\n- timeseries_mb=False,\n- taylordiagram=False, ax=None, label=None, footer=False, dia=None, marker=None):\n- \"\"\"Short summary.\n-\n- Parameters\n- ----------\n- param : type\n- Description of parameter `param` (the default is 'OZONE').\n- site : type\n- Description of parameter `site` (the default is '').\n- city : type\n- Description of parameter `city` (the default is '').\n- state : type\n- Description of parameter `state` (the default is '').\n- epa_region : type\n- Description of parameter `epa_region` (the default is '').\n- region : type\n- Description of parameter `region` (the default is '').\n- timeseries : type\n- Description of parameter `timeseries` (the default is False).\n- scatter : type\n- Description of parameter `scatter` (the default is False).\n- pdfs : type\n- Description of parameter `pdfs` (the default is False).\n- diffscatter : type\n- Description of parameter `diffscatter` (the default is False).\n- diffpdfs : type\n- Description of parameter `diffpdfs` (the default is False).\n- timeseries_rmse : type\n- Description of parameter `timeseries_rmse` (the default is False).\n- timeseries_mb : type\n- Description of parameter `timeseries_mb` (the default is False).\n- taylordiagram : type\n- Description of parameter `taylordiagram` (the default is False).\n- ax : type\n- Description of parameter `ax` (the default is None).\n- label : type\n- Description of parameter `label` (the default is None).\n- footer : type\n- Description of parameter `footer` (the default is False).\n- dia : type\n- Description of parameter `dia` (the default is None).\n- marker : type\n- Description of parameter `marker` (the default is None).\n-\n- Returns\n- -------\n- type\n- Description of returned object.\n-\n- \"\"\"\n- from numpy import NaN\n- from ..obs.epa_util import get_epa_location_df\n- df2, title = get_epa_location_df(self.dset.copy(), param, site=site, city=city, state=state, region=region,\n- epa_region=epa_region)\n- df2 = df2.groupby('Species').get_group(param)\n- if timeseries:\n- if ax is None:\n- ax = plots.timeseries_param(df2, col='Obs', title=title, label=label, ax=ax,\n- plotargs={'color': 'darkslategrey'},\n- fillargs={'color': 'darkslategrey', 'alpha': .2})\n- ax = plots.timeseries_param(df2, col='model', title=title, label=label, ax=ax, fillargs={'alpha': .2})\n- if scatter:\n- plots.scatter_param(df2, title=title, label=label, fig=fig, footer=footer)\n- if pdfs:\n- plots.kdeplots_param(df2, title=title, label=label, fig=fig, footer=footer)\n- if diffscatter:\n- plots.diffscatter_param(df2, title=title)\n- if diffpdfs:\n- plots.diffpdfs_param(df2, title=title, label=label, fig=fig, footer=footer)\n- if timeseries_rmse:\n- plots.timeseries_rmse_param(df2, title=title, label=label, fig=fig, footer=footer)\n- if timeseries_mb:\n- plots.timeseries_mb_param(df2, title=title, label=label, fig=fig, footer=footer)\n- if taylordiagram:\n- if marker is None:\n- marker = 'o'\n- if fig is None:\n- dia = plots.taylordiagram(df2, label=label, dia=dia, addon=False, marker=marker)\n- return dia\n- else:\n- dia = plots.taylordiagram(df2, label=label, dia=dia, addon=True, marker=marker)\n- plt.legend()\n- return dia\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -11,7 +11,7 @@\n \n setup(\n name='monet',\n- version='1.2',\n+ version='2.0',\n url='https://github.com/noaa-oar-arl/MONET',\n license='MIT',\n author='Barry D. Baker',\n@@ -19,8 +19,16 @@\n maintainer='Barry Baker',\n maintainer_email='barry.baker@noaa.gov',\n packages=find_packages(),\n- keywords=['model','verification','hysplit','cmaq','atmosphere','camx','evaluation'],\n+ keywords=[\n+ 'model', 'verification', 'hysplit', 'cmaq', 'atmosphere', 'camx',\n+ 'evaluation'\n+ ],\n description='The Model and Observation Evaluation Toolkit (MONET)',\n- install_requires=['numpy', 'pandas', 'wget', 'pyresample', 'netcdf4', 'pynio', 'xarray', 'dask', 'matplotlib', 'seaborn', 'pseudonetcdf'],\n- dependency_links=[\"git+ssh://git@github.com/barronh/pseudonetcdf.git@develop\", \"git+ssh://git@github.com/barronh/xarray.git@pnc-backend\"]\n-)\n+ install_requires=[\n+ 'numpy', 'pandas', 'pyresample', 'netcdf4', 'xarray', 'dask',\n+ 'matplotlib', 'seaborn', 'pseudonetcdf', 'cartopy', 'future', 'sphinx',\n+ 'pandoc'\n+ ],\n+ dependency_links=[\n+ \"git+ssh://git@github.com/barronh/pseudonetcdf.git\",\n+ ])\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2018-09-04T14:29:21Z"} diff --git a/PythonDataset/test/msmtools-task-instances.jsonl.all b/PythonDataset/test/msmtools-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..74baa515b1953e40cc4b00189df2515848c150cc --- /dev/null +++ b/PythonDataset/test/msmtools-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "markovmodel/msmtools", "pull_number": 117, "instance_id": "markovmodel__msmtools-117", "issue_numbers": "", "base_commit": "e6ea742c9a17d57071d1651647915caf724d439f", "patch": "diff --git a/msmtools/estimation/sparse/effective_counts.py b/msmtools/estimation/sparse/effective_counts.py\n--- a/msmtools/estimation/sparse/effective_counts.py\n+++ b/msmtools/estimation/sparse/effective_counts.py\n@@ -199,12 +199,7 @@ def statistical_inefficiencies(dtrajs, lag, C=None, truncate_acf=True, mact=2.0,\n # compute inefficiencies\n I, J = C.nonzero()\n if n_jobs > 1:\n- try:\n- from multiprocess.pool import Pool, MapResult\n- except ImportError:\n- raise RuntimeError('using multiple jobs requires the multiprocess library. '\n- 'Install it with conda or pip')\n-\n+ from multiprocessing.pool import Pool, MapResult\n from contextlib import closing\n import tempfile\n \n", "test_patch": "diff --git a/msmtools/estimation/tests/test_effective_count_matrix.py b/msmtools/estimation/tests/test_effective_count_matrix.py\n--- a/msmtools/estimation/tests/test_effective_count_matrix.py\n+++ b/msmtools/estimation/tests/test_effective_count_matrix.py\n@@ -27,13 +27,6 @@\n \n \"\"\"Unit tests for the transition_matrix module\"\"\"\n \n-have_multiprocess_lib = True\n-try:\n- import multiprocess\n- del multiprocess\n-except ImportError:\n- have_multiprocess_lib = False\n-\n \n class TestEffectiveCountMatrix(unittest.TestCase):\n \n@@ -70,9 +63,7 @@ def test_multitraj(self):\n assert np.array_equal(C.nonzero(), Ceff.nonzero())\n assert np.all(Ceff.toarray() <= C.toarray())\n \n- @unittest.skipIf(not have_multiprocess_lib, 'multiprocess lib missing')\n def test_multitraj_njobs(self):\n- import _multiprocess\n dtrajs = [[1, 0, 1, 0, 1, 1, 0, 0, 0, 1], [2], [0, 1, 0, 1]]\n # lag 1\n C = count_matrix(dtrajs, 1)\n@@ -94,8 +85,8 @@ def test_multitraj_njobs(self):\n assert np.array_equal(Ceff2.shape, C.shape)\n assert np.array_equal(C.nonzero(), Ceff2.nonzero())\n assert np.all(Ceff2.toarray() <= C.toarray())\n-\n- @unittest.skipIf(os.getenv('CI', False), 'need physical processors >=2, dont have on CI')\n+ \n+ @unittest.skipIf(os.getenv('CI', False), 'need physical cores')\n def test_njobs_speedup(self):\n artificial_dtraj = [np.random.randint(0, 100, size=10000) for _ in range(10)]\n import time\n", "problem_statement": "", "hints_text": "", "created_at": "2018-11-09T13:28:34Z"} diff --git a/PythonDataset/test/py-evm-task-instances.jsonl.all b/PythonDataset/test/py-evm-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..a8c680d8c1dc6c39d9fa2ecb8aa07dc297013134 --- /dev/null +++ b/PythonDataset/test/py-evm-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "ethereum/py-evm", "pull_number": 527, "instance_id": "ethereum__py-evm-527", "issue_numbers": "", "base_commit": "3f42b6dcf794d7200118e85e8251e4c17f2bca1c", "patch": "diff --git a/evm/db/backends/base.py b/evm/db/backends/base.py\n--- a/evm/db/backends/base.py\n+++ b/evm/db/backends/base.py\n@@ -8,6 +8,10 @@ class BaseDB(metaclass=ABCMeta):\n \n @abstractmethod\n def get(self, key):\n+ \"\"\"Return the value for the given key.\n+\n+ Raises KeyError if key doesn't exist.\n+ \"\"\"\n raise NotImplementedError(\n \"The `get` method must be implemented by subclasses of BaseDB\"\n )\n@@ -20,6 +24,7 @@ def set(self, key, value):\n \n @abstractmethod\n def exists(self, key):\n+ \"\"\"Return True if the key exists or False if it doesn't.\"\"\"\n raise NotImplementedError(\n \"The `exists` method must be implemented by subclasses of BaseDB\"\n )\ndiff --git a/evm/db/backends/level.py b/evm/db/backends/level.py\n--- a/evm/db/backends/level.py\n+++ b/evm/db/backends/level.py\n@@ -10,23 +10,24 @@ def __init__(self, db_path=None):\n if not db_path:\n raise TypeError(\"Please specifiy a valid path for your database.\")\n try:\n- import leveldb\n+ import plyvel\n except ImportError:\n- raise ImportError(\"LevelDB requires the leveldb \\\n+ raise ImportError(\"LevelDB requires the plyvel \\\n library which is not available for import.\")\n self.db_path = db_path\n- self.db = leveldb.LevelDB(db_path, create_if_missing=True, error_if_exists=False)\n+ self.db = plyvel.DB(db_path, create_if_missing=True, error_if_exists=False)\n \n def get(self, key):\n- # 'Get' Returns a bytearray which needs to be converted to straight bytes\n- return bytes(self.db.Get(key))\n+ v = self.db.get(key)\n+ if v is None:\n+ raise KeyError(key)\n+ return v\n \n def set(self, key, value):\n- self.db.Put(key, value)\n+ self.db.put(key, value)\n \n- # Returns False instead of KeyError if key doesn't exist\n def exists(self, key):\n- return bool(self.db.Get(key, default=False))\n+ return self.db.get(key) is not None\n \n def delete(self, key):\n- self.db.Delete(key)\n+ self.db.delete(key)\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -34,10 +34,10 @@\n \"coincurve>=7.0.0,<8.0.0\",\n ],\n 'leveldb': [\n- \"leveldb>=0.194,<1.0.0\",\n+ \"plyvel==1.0.4\",\n ],\n 'trinity': [\n- \"leveldb>=0.194,<1.0.0\",\n+ \"plyvel==1.0.4\",\n \"coincurve>=7.0.0,<8.0.0\",\n \"web3>=4.0.0b11,<5.0.0\",\n ],\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2018-04-03T11:01:52Z"} diff --git a/PythonDataset/test/py-trello-task-instances.jsonl.all b/PythonDataset/test/py-trello-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..145d82e744c7c52221a37015821f068dfa2a00f3 --- /dev/null +++ b/PythonDataset/test/py-trello-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "sarumont/py-trello", "pull_number": 52, "instance_id": "sarumont__py-trello-52", "issue_numbers": "", "base_commit": "81f93a2272a7855410c78b194316f64e757f6bf7", "patch": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -4,7 +4,7 @@\n \n setup(\n name = \"py-trello\",\n- version = \"0.1.5\",\n+ version = \"0.2.2\",\n \n description = 'Python wrapper around the Trello API',\n long_description = open('README.rst').read(),\n@@ -19,8 +19,12 @@\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n+ 'Programming Language :: Python 2',\n+ 'Programming Language :: Python 2.7',\n+ 'Programming Language :: Python 3',\n+ 'Programming Language :: Python 3.3',\n ],\n- install_requires = ['httplib2 >= 0.9', 'oauth2',],\n+ install_requires = [\"requests\", \"requests-oauthlib >= 0.4.1\",],\n packages = find_packages(),\n include_package_data = True,\n ) \ndiff --git a/trello/__init__.py b/trello/__init__.py\n--- a/trello/__init__.py\n+++ b/trello/__init__.py\n@@ -1,14 +1,7 @@\n-from httplib2 import Http\n-from urllib import urlencode\n from datetime import datetime\n-import exceptions\n import json\n-import oauth2 as oauth\n-import os\n-import random\n-import time\n-import urlparse\n-import urllib2\n+import requests\n+from requests_oauthlib import OAuth1\n \n \n class ResourceUnavailable(Exception):\n@@ -17,10 +10,10 @@ class ResourceUnavailable(Exception):\n def __init__(self, msg, http_response):\n Exception.__init__(self)\n self._msg = msg\n- self._status = http_response.status\n+ self._status = http_response.status_code\n \n def __str__(self):\n- return \"Resource unavailable: %s (HTTP status: %s)\" % (\n+ return \"%s (HTTP status: %s)\" % (\n self._msg, self._status)\n \n \n@@ -46,22 +39,18 @@ def __init__(self, api_key, api_secret=None, token=None, token_secret=None):\n :token_secret: the OAuth client secret for the given OAuth token\n \"\"\"\n \n- if api_key and api_secret and token and token_secret:\n- # oauth\n- self.oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)\n- self.oauth_token = oauth.Token(key=token, secret=token_secret)\n- self.client = oauth.Client(self.oauth_consumer, self.oauth_token)\n-\n- elif api_key:\n- self.client = Http()\n-\n- if token is None:\n- self.public_only = True\n+ # client key and secret for oauth1 session\n+ if api_key or token:\n+ self.oauth = OAuth1(client_key=api_key, client_secret=api_secret,\n+ resource_owner_key=token, resource_owner_secret=token_secret)\n else:\n- self.public_only = False\n+ self.oauth = None\n \n+ self.public_only = token is None\n self.api_key = api_key\n- self.auth_token = token\n+ self.api_secret = api_secret\n+ self.resource_owner_key = token\n+ self.resource_owner_secret = token_secret\n \n def info_for_all_boards(self, actions):\n \"\"\"\n@@ -81,33 +70,6 @@ def logout(self):\n \n raise NotImplementedError()\n \n- def build_url(self, path, query={}):\n- \"\"\"\n- Builds a Trello URL.\n-\n- :path: URL path\n- :params: dict of key-value pairs for the query string\n- \"\"\"\n- url = 'https://api.trello.com/1'\n- if path[0:1] != '/':\n- url += '/'\n- url += path\n-\n- if hasattr(self, 'oauth_token'):\n- url += '?'\n- url += \"key=\" + self.oauth_consumer.key\n- url += \"&token=\" + self.oauth_token.key\n- else:\n- url += '?'\n- url += \"key=\" + self.api_key\n- if self.public_only is False:\n- url += \"&token=\" + self.auth_token\n-\n- if len(query) > 0:\n- url += '&' + urlencode(query)\n-\n- return url\n-\n def list_boards(self):\n \"\"\"\n Returns all boards for your Trello user\n@@ -135,14 +97,14 @@ def get_board(self, board_id):\n def add_board(self, board_name):\n obj = self.fetch_json('/boards', http_method='POST',\n post_args={'name': board_name})\n- board = Board(self, obj['id'], name=obj['name'].encode('utf-8'))\n+ board = Board(self, obj['id'], name=obj['name'])\n board.closed = obj['closed']\n return board\n \n def get_list(self, list_id):\n obj = self.fetch_json('/lists/' + list_id)\n list = List(self.get_board(obj['idBoard']), obj['id'],\n- name=obj['name'].encode('utf-8'))\n+ name=obj['name'])\n list.closed = obj['closed']\n return list\n \n@@ -153,32 +115,43 @@ def fetch_json(\n self,\n uri_path,\n http_method='GET',\n- headers={},\n- query_params={},\n- post_args={}):\n+ headers=None,\n+ query_params=None,\n+ post_args=None):\n \"\"\" Fetch some JSON from Trello \"\"\"\n \n- if http_method in (\"POST\", \"PUT\", \"DELETE\"):\n- headers['Content-Type'] = 'application/json'\n+ # explicit values here to avoid mutable default values\n+ if headers is None:\n+ headers = {}\n+ if query_params is None:\n+ query_params = {}\n+ if post_args is None:\n+ post_args = {}\n \n+ # set content type and accept headers to handle JSON\n+ if http_method in (\"POST\", \"PUT\", \"DELETE\"):\n+ headers['Content-Type'] = 'application/json; charset=utf-8'\n headers['Accept'] = 'application/json'\n- url = self.build_url(uri_path, query_params)\n- response, content = self.client.request(\n- url,\n- http_method,\n- headers=headers,\n- body=json.dumps(post_args))\n \n- # error checking\n- if response.status == 401:\n- raise Unauthorized(url, response)\n- if response.status != 200:\n- raise ResourceUnavailable(url, response)\n- return json.loads(content)\n+ # construct the full URL without query parameters\n+ if uri_path[0] == '/':\n+ uri_path = uri_path[1:]\n+ url = 'https://api.trello.com/1/%s' % uri_path\n+\n+ # perform the HTTP requests, if possible uses OAuth authentication\n+ response = requests.request(http_method, url, params=query_params,\n+ headers=headers, data=json.dumps(post_args), auth=self.oauth)\n+\n+ if response.status_code == 401:\n+ raise Unauthorized(\"%s at %s\" % (response.text, url), response)\n+ if response.status_code != 200:\n+ raise ResourceUnavailable(\"%s at %s\" % (response.text, url), response)\n+\n+ return response.json()\n \n def _board_from_json(self, json):\n- board = Board(self, json['id'], name=json['name'].encode('utf-8'))\n- board.description = json.get('desc', '').encode('utf-8')\n+ board = Board(self, json['id'], name=json['name'])\n+ board.description = json.get('desc', '')\n board.closed = json['closed']\n board.url = json['url']\n return board\n@@ -188,13 +161,13 @@ def list_hooks(self, token=None):\n Returns a list of all hooks associated with a specific token. If you don't pass in a token,\n it tries to use the token associated with the TrelloClient object (if it exists)\n \"\"\"\n+ token = token or self.resource_owner_key\n \n- if token is None and self.auth_token is None:\n+ if token is None:\n raise TokenError(\"You need to pass an auth token in to list hooks.\")\n else:\n- using_token = token if self.auth_token is None else self.auth_token\n- url = \"/tokens/%s/webhooks\" % using_token\n- return self._existing_hook_objs(self.fetch_json(url), using_token)\n+ url = \"/tokens/%s/webhooks\" % token\n+ return self._existing_hook_objs(self.fetch_json(url), token)\n \n def _existing_hook_objs(self, hooks, token):\n \"\"\"\n@@ -216,29 +189,22 @@ def create_hook(self, callback_url, id_model, desc=None, token=None):\n There seems to be some sort of bug that makes you unable to create a\n hook using httplib2, so I'm using urllib2 for that instead.\n \"\"\"\n+ token = token or self.resource_owner_key\n \n- if token is None and self.auth_token is None:\n- raise TokenError(\n- \"You need to pass an auth token in to create a hook.\")\n+ if token is None:\n+ raise TokenError(\"You need to pass an auth token in to create a hook.\")\n+\n+ url = \"https://trello.com/1/tokens/%s/webhooks/\" % token\n+ data = {'callbackURL': callback_url, 'idModel': id_model,\n+ 'description': desc}\n+\n+ response = requests.post(url, data=data, auth=self.oauth)\n+\n+ if response.status_code == 200:\n+ hook_id = response.json()['id']\n+ return WebHook(self, token, hook_id, desc, id_model, callback_url, True)\n else:\n- using_token = token if self.auth_token is None else self.auth_token\n- url = \"https://trello.com/1/tokens/%s/webhooks/?key=%s\" % (\n- using_token, self.api_key)\n- data = urlencode({'callbackURL': callback_url, 'idModel': id_model,\n- \"description\": desc})\n-\n- # TODO - error checking for invalid responses\n- # Before spending too much time doing that with urllib2, might be worth trying\n- # and getting it working with urllib2 for consistency\n- req = urllib2.Request(url, data)\n- response = urllib2.urlopen(req)\n-\n- if response.code == 200:\n- hook_id = json.loads(response.read())['id']\n- return WebHook(self, using_token, hook_id, desc, id_model,\n- callback_url, True)\n- else:\n- return False\n+ return False\n \n \n class Board(object):\n@@ -263,7 +229,7 @@ def __repr__(self):\n def fetch(self):\n \"\"\"Fetch all attributes for this board\"\"\"\n json_obj = self.client.fetch_json('/boards/' + self.id)\n- self.name = json_obj['name'].encode('utf-8')\n+ self.name = json_obj['name']\n self.description = json_obj.get('desc', '')\n self.closed = json_obj['closed']\n self.url = json_obj['url']\n@@ -298,7 +264,7 @@ def get_lists(self, list_filter):\n query_params={'cards': 'none', 'filter': list_filter})\n lists = list()\n for obj in json_obj:\n- l = List(self, obj['id'], name=obj['name'].encode('utf-8'))\n+ l = List(self, obj['id'], name=obj['name'])\n l.closed = obj['closed']\n lists.append(l)\n \n@@ -314,7 +280,7 @@ def add_list(self, name):\n '/lists',\n http_method='POST',\n post_args={'name': name, 'idBoard': self.id}, )\n- list = List(self, obj['id'], name=obj['name'].encode('utf-8'))\n+ list = List(self, obj['id'], name=obj['name'])\n list.closed = obj['closed']\n return list\n \n@@ -358,9 +324,9 @@ def get_cards(self, filters=None):\n cards = list()\n for card_json in json_obj:\n card = Card(self, card_json['id'],\n- name=card_json['name'].encode('utf-8'))\n+ name=card_json['name'])\n \n- for card_key, card_val in card_json.iteritems():\n+ for card_key, card_val in card_json.items():\n if card_key in ['id', 'name']:\n continue\n \n@@ -400,7 +366,7 @@ def __repr__(self):\n def fetch(self):\n \"\"\"Fetch all attributes for this list\"\"\"\n json_obj = self.client.fetch_json('/lists/' + self.id)\n- self.name = json_obj['name'].encode('utf-8')\n+ self.name = json_obj['name']\n self.closed = json_obj['closed']\n \n def list_cards(self):\n@@ -408,8 +374,8 @@ def list_cards(self):\n json_obj = self.client.fetch_json('/lists/' + self.id + '/cards')\n cards = list()\n for c in json_obj:\n- card = Card(self, c['id'], name=c['name'].encode('utf-8'))\n- card.description = c.get('desc', '').encode('utf-8')\n+ card = Card(self, c['id'], name=c['name'])\n+ card.description = c.get('desc', '')\n card.closed = c['closed']\n card.url = c['url']\n card.member_ids = c['idMembers']\n@@ -506,14 +472,14 @@ def fetch(self):\n json_obj = self.client.fetch_json(\n '/cards/' + self.id,\n query_params={'badges': False})\n- self.name = json_obj['name'].encode('utf-8')\n+ self.name = json_obj['name']\n self.description = json_obj.get('desc', '')\n self.closed = json_obj['closed']\n self.url = json_obj['url']\n- self.member_ids = json_obj['idMembers']\n- self.short_id = json_obj['idShort']\n- self.list_id = json_obj['idList']\n- self.board_id = json_obj['idBoard']\n+ self.idMembers = json_obj['idMembers']\n+ self.idShort = json_obj['idShort']\n+ self.idList = json_obj['idList']\n+ self.idBoard = json_obj['idBoard']\n self.labels = json_obj['labels']\n self.badges = json_obj['badges']\n self.due = json_obj['due']\n@@ -600,7 +566,7 @@ def change_board(self, board_id, list_id=None):\n http_method='PUT',\n post_args=args)\n \n- def add_checklist(self, title, items, itemstates=[]):\n+ def add_checklist(self, title, items, itemstates=None):\n \n \"\"\"Add a checklist to this card\n \n@@ -609,6 +575,9 @@ def add_checklist(self, title, items, itemstates=[]):\n :itemstates: a list of the state (True/False) of each item\n :return: the checklist\n \"\"\"\n+ if itemstates is None:\n+ itemstates = []\n+\n json_obj = self.client.fetch_json(\n '/cards/' + self.id + '/checklists',\n http_method='POST',\n@@ -649,13 +618,13 @@ def fetch(self):\n json_obj = self.client.fetch_json(\n '/members/' + self.id,\n query_params={'badges': False})\n- self.status = json_obj['status'].encode('utf-8')\n+ self.status = json_obj['status']\n self.id = json_obj.get('id', '')\n self.bio = json_obj.get('bio', '')\n self.url = json_obj.get('url', '')\n- self.username = json_obj['username'].encode('utf-8')\n- self.full_name = json_obj['fullName'].encode('utf-8')\n- self.initials = json_obj['initials'].encode('utf-8')\n+ self.username = json_obj['username']\n+ self.full_name = json_obj['fullName']\n+ self.initials = json_obj['initials']\n return self\n \n \ndiff --git a/trello/util.py b/trello/util.py\n--- a/trello/util.py\n+++ b/trello/util.py\n@@ -1,10 +1,8 @@\n import os\n-import urlparse\n \n-import oauth2 as oauth\n+from requests_oauthlib import OAuth1Session\n \n-\n-def create_oauth_token():\n+def create_oauth_token(expiration=None, scope=None, key=None, secret=None):\n \"\"\"\n Script to obtain an OAuth token from Trello.\n \n@@ -19,44 +17,46 @@ def create_oauth_token():\n authorize_url = 'https://trello.com/1/OAuthAuthorizeToken'\n access_token_url = 'https://trello.com/1/OAuthGetAccessToken'\n \n- expiration = os.environ.get('TRELLO_EXPIRATION', None)\n- scope = os.environ.get('TRELLO_SCOPE', 'read,write')\n- trello_key = os.environ['TRELLO_API_KEY']\n- trello_secret = os.environ['TRELLO_API_SECRET']\n-\n- consumer = oauth.Consumer(trello_key, trello_secret)\n- client = oauth.Client(consumer)\n+ expiration = expiration or os.environ.get('TRELLO_EXPIRATION', \"30days\")\n+ scope = scope or os.environ.get('TRELLO_SCOPE', 'read,write')\n+ trello_key = key or os.environ['TRELLO_API_KEY']\n+ trello_secret = secret or os.environ['TRELLO_API_SECRET']\n \n # Step 1: Get a request token. This is a temporary token that is used for\n # having the user authorize an access token and to sign the request to obtain\n # said access token.\n \n- resp, content = client.request(request_token_url, \"GET\")\n- if resp['status'] != '200':\n- raise Exception(\"Invalid response %s.\" % resp['status'])\n-\n- request_token = dict(urlparse.parse_qsl(content))\n+ session = OAuth1Session(client_key=trello_key, client_secret=trello_secret)\n+ response = session.fetch_request_token(request_token_url)\n+ resource_owner_key, resource_owner_secret = response.get('oauth_token'), response.get('oauth_token_secret')\n \n- print \"Request Token:\"\n- print \" - oauth_token = %s\" % request_token['oauth_token']\n- print \" - oauth_token_secret = %s\" % request_token['oauth_token_secret']\n- print\n+ print(\"Request Token:\")\n+ print(\" - oauth_token = %s\" % resource_owner_key)\n+ print(\" - oauth_token_secret = %s\" % resource_owner_secret)\n+ print(\"\")\n \n # Step 2: Redirect to the provider. Since this is a CLI script we do not\n # redirect. In a web application you would redirect the user to the URL\n # below.\n \n- print \"Go to the following link in your browser:\"\n- print \"{authorize_url}?oauth_token={oauth_token}&scope={scope}&expiration={expiration}\".format(\n+ print(\"Go to the following link in your browser:\")\n+ print(\"{authorize_url}?oauth_token={oauth_token}&scope={scope}&expiration={expiration}\".format(\n authorize_url=authorize_url,\n- oauth_token=request_token['oauth_token'],\n+ oauth_token=resource_owner_key,\n expiration=expiration,\n scope=scope,\n- )\n+ ))\n \n # After the user has granted access to you, the consumer, the provider will\n # redirect you to whatever URL you have told them to redirect to. You can\n # usually define this in the oauth_callback argument as well.\n+\n+ # Python 3 compatibility (raw_input was renamed to input)\n+ try:\n+ raw_input\n+ except NameError:\n+ raw_input = input\n+\n accepted = 'n'\n while accepted.lower() == 'n':\n accepted = raw_input('Have you authorized me? (y/n) ')\n@@ -67,20 +67,17 @@ def create_oauth_token():\n # request token to sign this request. After this is done you throw away the\n # request token and use the access token returned. You should store this\n # access token somewhere safe, like a database, for future use.\n- token = oauth.Token(request_token['oauth_token'],\n- request_token['oauth_token_secret'])\n- token.set_verifier(oauth_verifier)\n- client = oauth.Client(consumer, token)\n-\n- resp, content = client.request(access_token_url, \"POST\")\n- access_token = dict(urlparse.parse_qsl(content))\n-\n- print \"Access Token:\"\n- print \" - oauth_token = %s\" % access_token['oauth_token']\n- print \" - oauth_token_secret = %s\" % access_token['oauth_token_secret']\n- print\n- print \"You may now access protected resources using the access tokens above.\"\n- print\n+ session = OAuth1Session(client_key=trello_key, client_secret=trello_secret,\n+ resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret,\n+ verifier=oauth_verifier)\n+ access_token = session.fetch_access_token(access_token_url)\n+\n+ print(\"Access Token:\")\n+ print(\" - oauth_token = %s\" % access_token['oauth_token'])\n+ print(\" - oauth_token_secret = %s\" % access_token['oauth_token_secret'])\n+ print(\"\")\n+ print(\"You may now access protected resources using the access tokens above.\")\n+ print(\"\")\n \n if __name__ == '__main__':\n create_oauth_token()\n", "test_patch": "diff --git a/test/test_trello.py b/test/test_trello.py\n--- a/test/test_trello.py\n+++ b/test/test_trello.py\n@@ -2,133 +2,163 @@\n import unittest\n import os\n \n-class TrelloClientTestCase(unittest.TestCase):\n \n-\t\"\"\"\n+class TrelloClientTestCase(unittest.TestCase):\n+ \"\"\"\n \tTests for TrelloClient API. Note these test are in order to preserve dependencies, as an API\n \tintegration cannot be tested independently.\n \t\"\"\"\n \n-\tdef setUp(self):\n-\t\tself._trello = TrelloClient(os.environ['TRELLO_API_KEY'],\n+ def setUp(self):\n+ self._trello = TrelloClient(os.environ['TRELLO_API_KEY'],\n token=os.environ['TRELLO_TOKEN'])\n \n-\tdef test01_list_boards(self):\n-\t\tself.assertEquals(\n-\t\t\t\tlen(self._trello.list_boards()),\n-\t\t\t\tint(os.environ['TRELLO_TEST_BOARD_COUNT']))\n-\n-\tdef test10_board_attrs(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\tself.assertIsNotNone(b.id, msg=\"id not provided\")\n-\t\t\tself.assertIsNotNone(b.name, msg=\"name not provided\")\n-\t\t\tself.assertIsNotNone(b.description, msg=\"description not provided\")\n-\t\t\tself.assertIsNotNone(b.closed, msg=\"closed not provided\")\n-\t\t\tself.assertIsNotNone(b.url, msg=\"url not provided\")\n-\n-\tdef test20_board_all_lists(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\ttry:\n-\t\t\t\tb.all_lists()\n-\t\t\texcept Exception as e:\n-\t\t\t\tself.fail(\"Caught Exception getting lists\")\n-\n-\tdef test21_board_open_lists(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\ttry:\n-\t\t\t\tb.open_lists()\n-\t\t\texcept Exception as e:\n-\t\t\t\tself.fail(\"Caught Exception getting open lists\")\n-\n-\tdef test22_board_closed_lists(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\ttry:\n-\t\t\t\tb.closed_lists()\n-\t\t\texcept Exception as e:\n-\t\t\t\tself.fail(\"Caught Exception getting closed lists\")\n-\n-\tdef test30_list_attrs(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\tfor l in b.all_lists():\n-\t\t\t\tself.assertIsNotNone(l.id, msg=\"id not provided\")\n-\t\t\t\tself.assertIsNotNone(l.name, msg=\"name not provided\")\n-\t\t\t\tself.assertIsNotNone(l.closed, msg=\"closed not provided\")\n-\t\t\tbreak # only need to test one board's lists\n-\n-\tdef test40_list_cards(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tfor b in boards:\n-\t\t\tfor l in b.all_lists():\n-\t\t\t\tfor c in l.list_cards():\n-\t\t\t\t\tself.assertIsNotNone(c.id, msg=\"id not provided\")\n-\t\t\t\t\tself.assertIsNotNone(c.name, msg=\"name not provided\")\n-\t\t\t\t\tself.assertIsNotNone(c.description, msg=\"description not provided\")\n-\t\t\t\t\tself.assertIsNotNone(c.closed, msg=\"closed not provided\")\n-\t\t\t\t\tself.assertIsNotNone(c.url, msg=\"url not provided\")\n-\t\t\t\tbreak\n-\t\t\tbreak\n-\t\tpass\n-\n-\tdef test50_add_card(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tboard_id = None\n-\t\tfor b in boards:\n-\t\t\tif b.name != os.environ['TRELLO_TEST_BOARD_NAME']:\n-\t\t\t\tcontinue\n-\n-\t\t\tfor l in b.open_lists():\n-\t\t\t\ttry:\n-\t\t\t\t\tname = \"Testing from Python - no desc\"\n-\t\t\t\t\tcard = l.add_card(name)\n-\t\t\t\texcept Exception as e:\n-\t\t\t\t\tprint str(e)\n-\t\t\t\t\tself.fail(\"Caught Exception adding card\")\n-\n-\t\t\t\tself.assertIsNotNone(card, msg=\"card is None\")\n-\t\t\t\tself.assertIsNotNone(card.id, msg=\"id not provided\")\n-\t\t\t\tself.assertEquals(card.name, name)\n-\t\t\t\tself.assertIsNotNone(card.closed, msg=\"closed not provided\")\n-\t\t\t\tself.assertIsNotNone(card.url, msg=\"url not provided\")\n-\t\t\t\tbreak\n-\t\t\tbreak\n-\t\tif not card:\n-\t\t\tself.fail(\"No card created\")\n-\n-\tdef test51_add_card(self):\n-\t\tboards = self._trello.list_boards()\n-\t\tboard_id = None\n-\t\tfor b in boards:\n-\t\t\tif b.name != os.environ['TRELLO_TEST_BOARD_NAME']:\n-\t\t\t\tcontinue\n-\n-\t\t\tfor l in b.open_lists():\n-\t\t\t\ttry:\n-\t\t\t\t\tname = \"Testing from Python\"\n-\t\t\t\t\tdescription = \"Description goes here\"\n-\t\t\t\t\tcard = l.add_card(name, description)\n-\t\t\t\texcept Exception as e:\n-\t\t\t\t\tprint str(e)\n-\t\t\t\t\tself.fail(\"Caught Exception adding card\")\n-\n-\t\t\t\tself.assertIsNotNone(card, msg=\"card is None\")\n-\t\t\t\tself.assertIsNotNone(card.id, msg=\"id not provided\")\n-\t\t\t\tself.assertEquals(card.name, name)\n-\t\t\t\tself.assertEquals(card.description, description)\n-\t\t\t\tself.assertIsNotNone(card.closed, msg=\"closed not provided\")\n-\t\t\t\tself.assertIsNotNone(card.url, msg=\"url not provided\")\n-\t\t\t\tbreak\n-\t\t\tbreak\n-\t\tif not card:\n-\t\t\tself.fail(\"No card created\")\n+ def test01_list_boards(self):\n+ self.assertEquals(\n+ len(self._trello.list_boards()),\n+ int(os.environ['TRELLO_TEST_BOARD_COUNT']))\n+\n+ def test10_board_attrs(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ self.assertIsNotNone(b.id, msg=\"id not provided\")\n+ self.assertIsNotNone(b.name, msg=\"name not provided\")\n+ self.assertIsNotNone(b.description, msg=\"description not provided\")\n+ self.assertIsNotNone(b.closed, msg=\"closed not provided\")\n+ self.assertIsNotNone(b.url, msg=\"url not provided\")\n+\n+ def test20_board_all_lists(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ try:\n+ b.all_lists()\n+ except Exception as e:\n+ self.fail(\"Caught Exception getting lists\")\n+\n+ def test21_board_open_lists(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ try:\n+ b.open_lists()\n+ except Exception as e:\n+ self.fail(\"Caught Exception getting open lists\")\n+\n+ def test22_board_closed_lists(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ try:\n+ b.closed_lists()\n+ except Exception as e:\n+ self.fail(\"Caught Exception getting closed lists\")\n+\n+ def test30_list_attrs(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ for l in b.all_lists():\n+ self.assertIsNotNone(l.id, msg=\"id not provided\")\n+ self.assertIsNotNone(l.name, msg=\"name not provided\")\n+ self.assertIsNotNone(l.closed, msg=\"closed not provided\")\n+ break # only need to test one board's lists\n+\n+ def test40_list_cards(self):\n+ boards = self._trello.list_boards()\n+ for b in boards:\n+ for l in b.all_lists():\n+ for c in l.list_cards():\n+ self.assertIsNotNone(c.id, msg=\"id not provided\")\n+ self.assertIsNotNone(c.name, msg=\"name not provided\")\n+ self.assertIsNotNone(c.description, msg=\"description not provided\")\n+ self.assertIsNotNone(c.closed, msg=\"closed not provided\")\n+ self.assertIsNotNone(c.url, msg=\"url not provided\")\n+ break\n+ break\n+ pass\n+\n+\n+ def test50_add_card(self):\n+ boards = self._trello.list_boards()\n+ board_id = None\n+ for b in boards:\n+ if b.name != os.environ['TRELLO_TEST_BOARD_NAME']:\n+ continue\n+\n+ for l in b.open_lists():\n+ try:\n+ name = \"Testing from Python - no desc\"\n+ card = l.add_card(name)\n+ except Exception as e:\n+ print(str(e))\n+ self.fail(\"Caught Exception adding card\")\n+\n+ self.assertIsNotNone(card, msg=\"card is None\")\n+ self.assertIsNotNone(card.id, msg=\"id not provided\")\n+ self.assertEquals(card.name, name)\n+ self.assertIsNotNone(card.closed, msg=\"closed not provided\")\n+ self.assertIsNotNone(card.url, msg=\"url not provided\")\n+ break\n+ break\n+ if not card:\n+ self.fail(\"No card created\")\n+\n+ def test51_add_card(self):\n+ boards = self._trello.list_boards()\n+ board_id = None\n+ for b in boards:\n+ if b.name != os.environ['TRELLO_TEST_BOARD_NAME']:\n+ continue\n+\n+ for l in b.open_lists():\n+ try:\n+ name = \"Testing from Python\"\n+ description = \"Description goes here\"\n+ card = l.add_card(name, description)\n+ except Exception as e:\n+ print(str(e))\n+ self.fail(\"Caught Exception adding card\")\n+\n+ self.assertIsNotNone(card, msg=\"card is None\")\n+ self.assertIsNotNone(card.id, msg=\"id not provided\")\n+ self.assertEquals(card.name, name)\n+ self.assertEquals(card.description, description)\n+ self.assertIsNotNone(card.closed, msg=\"closed not provided\")\n+ self.assertIsNotNone(card.url, msg=\"url not provided\")\n+ break\n+ break\n+ if not card:\n+ self.fail(\"No card created\")\n+\n+\n+ def test52_get_cards(self):\n+ boards = [board for board in self._trello.list_boards() if board.name == os.environ['TRELLO_TEST_BOARD_NAME']]\n+ self.assertEquals(len(boards), 1, msg=\"Test board not found\")\n+\n+ board = boards[0]\n+ cards = board.get_cards()\n+ self.assertEqual(len(cards), 2, msg=\"Unexpected number of cards in testboard\")\n+\n+ for card in cards:\n+ if card.name == 'Testing from Python':\n+ self.assertEqual(card.description, 'Description goes here')\n+ elif card.name == 'Testing from Python - no desc':\n+ self.assertEqual(card.description, '')\n+ else:\n+ self.fail(msg='Unexpected card found')\n+\n+\n+ def test60_delete_cards(self):\n+ boards = [board for board in self._trello.list_boards() if board.name == os.environ['TRELLO_TEST_BOARD_NAME']]\n+ self.assertEquals(len(boards), 1, msg=\"Test board not found\")\n+\n+ board = boards[0]\n+ cards = board.get_cards()\n+ for card in cards:\n+ card.delete()\n+\n \n def suite():\n-\ttests = ['test01_list_boards', 'test10_board_attrs', 'test20_add_card']\n-\treturn unittest.TestSuite(map(TrelloClientTestCase, tests))\n+ tests = ['test01_list_boards', 'test10_board_attrs', 'test20_add_card']\n+ return unittest.TestSuite(map(TrelloClientTestCase, tests))\n+\n \n if __name__ == \"__main__\":\n-\tunittest.main()\n+ unittest.main()\n", "problem_statement": "", "hints_text": "", "created_at": "2014-07-11T14:34:33Z"} diff --git a/PythonDataset/test/python-gvm-task-instances.jsonl.all b/PythonDataset/test/python-gvm-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..df601994b1ea6ebce9c7baf0cf73c70af1ff1882 --- /dev/null +++ b/PythonDataset/test/python-gvm-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "greenbone/python-gvm", "pull_number": 198, "instance_id": "greenbone__python-gvm-198", "issue_numbers": "", "base_commit": "5a85d62b76db8cc726864e981e4a1f1fbd6bb3f9", "patch": "diff --git a/gvm/__init__.py b/gvm/__init__.py\n--- a/gvm/__init__.py\n+++ b/gvm/__init__.py\n@@ -18,23 +18,7 @@\n \"\"\"\n Main module of python-gvm.\n \"\"\"\n-from pathlib import Path\n-\n-from pkg_resources import safe_version\n-\n-import toml\n-\n-\n-def get_version_from_pyproject_toml() -> str:\n- path = Path(__file__)\n- pyproject_toml_path = path.parent.parent / 'pyproject.toml'\n-\n- if pyproject_toml_path.exists():\n- pyproject_toml = toml.loads(pyproject_toml_path.read_text())\n- if 'tool' in pyproject_toml and 'poetry' in pyproject_toml['tool']:\n- return pyproject_toml['tool']['poetry']['version']\n-\n- raise RuntimeError('Version information not found in pyproject.toml file.')\n+from .__version__ import __version__\n \n \n def get_version() -> str:\n@@ -47,5 +31,4 @@ def get_version() -> str:\n .. _PEP440:\n https://www.python.org/dev/peps/pep-0440\n \"\"\"\n- str_version = get_version_from_pyproject_toml()\n- return safe_version(str_version)\n+ return __version__\ndiff --git a/gvm/__version__.py b/gvm/__version__.py\nnew file mode 100644\n--- /dev/null\n+++ b/gvm/__version__.py\n@@ -0,0 +1,5 @@\n+# pylint: disable=invalid-name\n+\n+# THIS IS AN AUTOGENERATED FILE. DO NOT TOUCH!\n+\n+__version__ = \"20.4.dev1\"\ndiff --git a/gvm/utils.py b/gvm/utils.py\n--- a/gvm/utils.py\n+++ b/gvm/utils.py\n@@ -1,5 +1,5 @@\n # -*- coding: utf-8 -*-\n-# Copyright (C) 2018 - 2019 Greenbone Networks GmbH\n+# Copyright (C) 2018 - 2020 Greenbone Networks GmbH\n #\n # SPDX-License-Identifier: GPL-3.0-or-later\n #\n@@ -21,25 +21,3 @@\n \n def deprecation(message: str):\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n-\n-\n-def get_version_string(version: tuple) -> str:\n- \"\"\"Create a version string from a version tuple\n-\n- Arguments:\n- version: version as tuple e.g. (1, 2, 0, dev, 5)\n-\n- Returns:\n- The version tuple converted into a string representation\n- \"\"\"\n- if len(version) > 4:\n- ver = \".\".join(str(x) for x in version[:4])\n- ver += str(version[4])\n-\n- if len(version) > 5:\n- # support (1, 2, 3, 'beta', 2, 'dev', 1)\n- ver += \".{0}{1}\".format(str(version[5]), str(version[6]))\n-\n- return ver\n- else:\n- return \".\".join(str(x) for x in version)\ndiff --git a/gvm/version.py b/gvm/version.py\nnew file mode 100644\n--- /dev/null\n+++ b/gvm/version.py\n@@ -0,0 +1,280 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import argparse\n+import re\n+import sys\n+\n+from pathlib import Path\n+\n+import tomlkit\n+\n+from packaging.version import Version, InvalidVersion\n+\n+\n+from gvm import get_version\n+\n+\n+def strip_version(version: str) -> str:\n+ \"\"\"\n+ Strips a leading 'v' from a version string\n+\n+ E.g. v1.2.3 will be converted to 1.2.3\n+ \"\"\"\n+ if version and version[0] == 'v':\n+ return version[1:]\n+\n+ return version\n+\n+\n+def safe_version(version: str) -> str:\n+ \"\"\"\n+ Returns the version as a string in `PEP440`_ compliant\n+ format.\n+\n+ .. _PEP440:\n+ https://www.python.org/dev/peps/pep-0440\n+ \"\"\"\n+ try:\n+ return str(Version(version))\n+ except InvalidVersion:\n+ version = version.replace(' ', '.')\n+ return re.sub('[^A-Za-z0-9.]+', '-', version)\n+\n+\n+def get_version_from_pyproject_toml(pyproject_toml_path: Path = None) -> str:\n+ \"\"\"\n+ Return the version information from the [tool.poetry] section of the\n+ pyproject.toml file. The version may be in non standardized form.\n+ \"\"\"\n+ if not pyproject_toml_path:\n+ path = Path(__file__)\n+ pyproject_toml_path = path.parent.parent / 'pyproject.toml'\n+\n+ if not pyproject_toml_path.exists():\n+ raise RuntimeError('pyproject.toml file not found.')\n+\n+ pyproject_toml = tomlkit.parse(pyproject_toml_path.read_text())\n+ if (\n+ 'tool' in pyproject_toml\n+ and 'poetry' in pyproject_toml['tool']\n+ and 'version' in pyproject_toml['tool']['poetry']\n+ ):\n+ return pyproject_toml['tool']['poetry']['version']\n+\n+ raise RuntimeError('Version information not found in pyproject.toml file.')\n+\n+\n+def get_version_string(version: tuple) -> str:\n+ \"\"\"Create a version string from a version tuple\n+\n+ Arguments:\n+ version: version as tuple e.g. (1, 2, 0, dev, 5)\n+\n+ Returns:\n+ The version tuple converted into a string representation\n+ \"\"\"\n+ if len(version) > 4:\n+ ver = \".\".join(str(x) for x in version[:4])\n+ ver += str(version[4])\n+\n+ if len(version) > 5:\n+ # support (1, 2, 3, 'beta', 2, 'dev', 1)\n+ ver += \".{0}{1}\".format(str(version[5]), str(version[6]))\n+\n+ return ver\n+ else:\n+ return \".\".join(str(x) for x in version)\n+\n+\n+def print_version(pyproject_toml_path: Path = None) -> None:\n+ pyproject_version = get_version_from_pyproject_toml(\n+ pyproject_toml_path=pyproject_toml_path\n+ )\n+\n+ print(pyproject_version)\n+\n+\n+def versions_equal(new_version: str, old_version: str) -> bool:\n+ \"\"\"\n+ Checks if new_version and old_version are equal\n+ \"\"\"\n+ return safe_version(old_version) == safe_version(new_version)\n+\n+\n+def is_version_pep440_compliant(version: str) -> bool:\n+ \"\"\"\n+ Checks if the provided version is a PEP 440 compliant version string\n+ \"\"\"\n+ return version == safe_version(version)\n+\n+\n+def update_pyproject_version(\n+ new_version: str, pyproject_toml_path: Path,\n+) -> None:\n+ \"\"\"\n+ Update the version in the pyproject.toml file\n+ \"\"\"\n+ version = safe_version(new_version)\n+\n+ pyproject_toml = tomlkit.parse(pyproject_toml_path.read_text())\n+\n+ if 'tool' not in pyproject_toml:\n+ tool_table = tomlkit.table()\n+ pyproject_toml['tool'] = tool_table\n+\n+ if 'poetry' not in pyproject_toml['tool']:\n+ poetry_table = tomlkit.table()\n+ pyproject_toml['tool'].add('poetry', poetry_table)\n+\n+ pyproject_toml['tool']['poetry']['version'] = version\n+\n+ pyproject_toml_path.write_text(tomlkit.dumps(pyproject_toml))\n+\n+\n+def update_version_file(new_version: str, version_file_path: Path) -> None:\n+ \"\"\"\n+ Update the version file with the new version\n+ \"\"\"\n+ version = safe_version(new_version)\n+\n+ text = \"\"\"# pylint: disable=invalid-name\n+\n+# THIS IS AN AUTOGENERATED FILE. DO NOT TOUCH!\n+\n+__version__ = \"{}\"\\n\"\"\".format(\n+ version\n+ )\n+ version_file_path.write_text(text)\n+\n+\n+def _update_python_gvm_version(\n+ new_version: str, pyproject_toml_path: Path, *, force: bool = False\n+):\n+ if not pyproject_toml_path.exists():\n+ sys.exit(\n+ 'Could not find pyproject.toml file in the current working dir.'\n+ )\n+\n+ cwd_path = Path.cwd()\n+ python_gvm_version = get_version()\n+ pyproject_version = get_version_from_pyproject_toml(\n+ pyproject_toml_path=pyproject_toml_path\n+ )\n+ version_file_path = cwd_path / 'gvm' / '__version__.py'\n+\n+ if not pyproject_toml_path.exists():\n+ sys.exit(\n+ 'Could not find __version__.py file at {}.'.format(\n+ version_file_path\n+ )\n+ )\n+\n+ if not force and versions_equal(new_version, python_gvm_version):\n+ print('Version is already up-to-date.')\n+ sys.exit(0)\n+\n+ update_pyproject_version(\n+ new_version=new_version, pyproject_toml_path=pyproject_toml_path\n+ )\n+\n+ update_version_file(\n+ new_version=new_version, version_file_path=version_file_path,\n+ )\n+\n+ print(\n+ 'Updated version from {} to {}'.format(\n+ pyproject_version, safe_version(new_version)\n+ )\n+ )\n+\n+\n+def _verify_version(version: str, pyproject_toml_path: Path) -> None:\n+ python_gvm_version = get_version()\n+ pyproject_version = get_version_from_pyproject_toml(\n+ pyproject_toml_path=pyproject_toml_path\n+ )\n+ if not is_version_pep440_compliant(python_gvm_version):\n+ sys.exit(\"The version in gvm/__version__.py is not PEP 440 compliant.\")\n+\n+ if pyproject_version != python_gvm_version:\n+ sys.exit(\n+ \"The version set in the pyproject.toml file \\\"{}\\\" doesn't \"\n+ \"match the python-gvm version \\\"{}\\\"\".format(\n+ pyproject_version, python_gvm_version\n+ )\n+ )\n+\n+ if version != 'current':\n+ provided_version = strip_version(version)\n+ if provided_version != python_gvm_version:\n+ sys.exit(\n+ \"Provided version \\\"{}\\\" does not match the python-gvm \"\n+ \"version \\\"{}\\\"\".format(provided_version, python_gvm_version)\n+ )\n+\n+ print('OK')\n+\n+\n+def main():\n+ parser = argparse.ArgumentParser(\n+ description='Version handling utilities for python-gvm.', prog='version'\n+ )\n+\n+ subparsers = parser.add_subparsers(\n+ title='subcommands',\n+ description='valid subcommands',\n+ help='additional help',\n+ dest='command',\n+ )\n+\n+ verify_parser = subparsers.add_parser('verify')\n+ verify_parser.add_argument('version', help='version string to compare')\n+\n+ subparsers.add_parser('show')\n+\n+ update_parser = subparsers.add_parser('update')\n+ update_parser.add_argument('version', help='version string to use')\n+ update_parser.add_argument(\n+ '--force',\n+ help=\"don't check if version is already set\",\n+ action=\"store_true\",\n+ )\n+\n+ args = parser.parse_args()\n+\n+ if not getattr(args, 'command', None):\n+ parser.print_usage()\n+ sys.exit(0)\n+\n+ pyproject_toml_path = Path.cwd() / 'pyproject.toml'\n+\n+ if args.command == 'update':\n+ _update_python_gvm_version(\n+ args.version,\n+ pyproject_toml_path=pyproject_toml_path,\n+ force=args.force,\n+ )\n+ elif args.command == 'show':\n+ print_version(pyproject_toml_path=pyproject_toml_path)\n+ elif args.command == 'verify':\n+ _verify_version(args.version, pyproject_toml_path=pyproject_toml_path)\n+\n+\n+if __name__ == '__main__':\n+ main()\n", "test_patch": "diff --git a/tests/version/__init__.py b/tests/version/__init__.py\nnew file mode 100644\ndiff --git a/tests/version/test_get_version_from_pyproject_toml.py b/tests/version/test_get_version_from_pyproject_toml.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_get_version_from_pyproject_toml.py\n@@ -0,0 +1,79 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+from gvm.version import get_version_from_pyproject_toml\n+\n+\n+class GetVersionFromPyprojectTomlTestCase(unittest.TestCase):\n+ def test_pyproject_toml_file_not_exists(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.exists.return_value = False\n+\n+ with self.assertRaisesRegex(\n+ RuntimeError, 'pyproject.toml file not found'\n+ ):\n+ get_version_from_pyproject_toml(fake_path)\n+\n+ fake_path.exists.assert_called_with()\n+\n+ def test_no_poerty_section(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.exists.return_value = True\n+ fake_path.read_text.return_value = ''\n+\n+ with self.assertRaisesRegex(\n+ RuntimeError, 'Version information not found in pyproject.toml file'\n+ ):\n+ get_version_from_pyproject_toml(fake_path)\n+\n+ fake_path.exists.assert_called_with()\n+ fake_path.read_text.assert_called_with()\n+\n+ def test_empty_poerty_section(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.exists.return_value = True\n+ fake_path.read_text.return_value = '[tool.poetry]'\n+\n+ with self.assertRaisesRegex(\n+ RuntimeError, 'Version information not found in pyproject.toml file'\n+ ):\n+ get_version_from_pyproject_toml(fake_path)\n+\n+ fake_path.exists.assert_called_with()\n+ fake_path.read_text.assert_called_with()\n+\n+ def test_get_version(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.exists.return_value = True\n+ fake_path.read_text.return_value = '[tool.poetry]\\nversion = \"1.2.3\"'\n+\n+ version = get_version_from_pyproject_toml(fake_path)\n+\n+ self.assertEqual(version, '1.2.3')\n+\n+ fake_path.exists.assert_called_with()\n+ fake_path.read_text.assert_called_with()\ndiff --git a/tests/utils/test_get_version_string.py b/tests/version/test_get_version_string.py\nsimilarity index 97%\nrename from tests/utils/test_get_version_string.py\nrename to tests/version/test_get_version_string.py\n--- a/tests/utils/test_get_version_string.py\n+++ b/tests/version/test_get_version_string.py\n@@ -18,7 +18,7 @@\n \n import unittest\n \n-from gvm.utils import get_version_string\n+from gvm.version import get_version_string\n \n \n class TestGetVersionString(unittest.TestCase):\ndiff --git a/tests/version/test_is_version_pep440_compliant.py b/tests/version/test_is_version_pep440_compliant.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_is_version_pep440_compliant.py\n@@ -0,0 +1,45 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from gvm.version import is_version_pep440_compliant\n+\n+\n+class IsVersionPep440CompliantTestCase(unittest.TestCase):\n+ def test_is_compliant(self):\n+ self.assertTrue(is_version_pep440_compliant('1.2.3.dev1'))\n+ self.assertTrue(is_version_pep440_compliant('1.2.3.dev0'))\n+ self.assertTrue(is_version_pep440_compliant('20.4'))\n+ self.assertTrue(is_version_pep440_compliant('1.2'))\n+ self.assertTrue(is_version_pep440_compliant('1.2.0a0'))\n+ self.assertTrue(is_version_pep440_compliant('1.2.0a1'))\n+ self.assertTrue(is_version_pep440_compliant('1.2.0b0'))\n+ self.assertTrue(is_version_pep440_compliant('1.2.0b1'))\n+\n+ def test_is_not_compliant(self):\n+ self.assertFalse(is_version_pep440_compliant('1.2.3dev1'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3dev'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3dev0'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3alpha'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3alpha0'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3.a0'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3beta'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3beta0'))\n+ self.assertFalse(is_version_pep440_compliant('1.2.3.b0'))\n+ self.assertFalse(is_version_pep440_compliant('20.04'))\ndiff --git a/tests/version/test_safe_version.py b/tests/version/test_safe_version.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_safe_version.py\n@@ -0,0 +1,55 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from gvm.version import safe_version\n+\n+\n+class SafeVersionTestCase(unittest.TestCase):\n+ def test_dev_versions(self):\n+ self.assertEqual(safe_version('1.2.3dev'), '1.2.3.dev0')\n+ self.assertEqual(safe_version('1.2.3dev1'), '1.2.3.dev1')\n+ self.assertEqual(safe_version('1.2.3.dev'), '1.2.3.dev0')\n+\n+ def test_alpha_versions(self):\n+ self.assertEqual(safe_version('1.2.3alpha'), '1.2.3a0')\n+ self.assertEqual(safe_version('1.2.3.alpha'), '1.2.3a0')\n+ self.assertEqual(safe_version('1.2.3a'), '1.2.3a0')\n+ self.assertEqual(safe_version('1.2.3.a1'), '1.2.3a1')\n+ self.assertEqual(safe_version('1.2.3a1'), '1.2.3a1')\n+\n+ def test_beta_versions(self):\n+ self.assertEqual(safe_version('1.2.3beta'), '1.2.3b0')\n+ self.assertEqual(safe_version('1.2.3.beta'), '1.2.3b0')\n+ self.assertEqual(safe_version('1.2.3b'), '1.2.3b0')\n+ self.assertEqual(safe_version('1.2.3.b1'), '1.2.3b1')\n+ self.assertEqual(safe_version('1.2.3b1'), '1.2.3b1')\n+\n+ def test_caldav_versions(self):\n+ self.assertEqual(safe_version('22.04'), '22.4')\n+ self.assertEqual(safe_version('22.4'), '22.4')\n+ self.assertEqual(safe_version('22.10'), '22.10')\n+ self.assertEqual(safe_version('22.04dev1'), '22.4.dev1')\n+ self.assertEqual(safe_version('22.10dev1'), '22.10.dev1')\n+\n+ def test_release_versions(self):\n+ self.assertEqual(safe_version('1'), '1')\n+ self.assertEqual(safe_version('1.2'), '1.2')\n+ self.assertEqual(safe_version('1.2.3'), '1.2.3')\n+ self.assertEqual(safe_version('22.4'), '22.4')\ndiff --git a/tests/version/test_strip_version.py b/tests/version/test_strip_version.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_strip_version.py\n@@ -0,0 +1,31 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from gvm.version import strip_version\n+\n+\n+class StripVersionTestCase(unittest.TestCase):\n+ def test_version_string_without_v(self):\n+ self.assertEqual(strip_version('1.2.3'), '1.2.3')\n+ self.assertEqual(strip_version('1.2.3dev'), '1.2.3dev')\n+\n+ def test_version_string_with_v(self):\n+ self.assertEqual(strip_version('v1.2.3'), '1.2.3')\n+ self.assertEqual(strip_version('v1.2.3dev'), '1.2.3dev')\ndiff --git a/tests/version/test_update_pyproject_version.py b/tests/version/test_update_pyproject_version.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_update_pyproject_version.py\n@@ -0,0 +1,79 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+import tomlkit\n+from gvm.version import update_pyproject_version\n+\n+\n+class UpdatePyprojectVersionTestCase(unittest.TestCase):\n+ def test_empty_pyproject_toml(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.read_text.return_value = \"\"\n+\n+ update_pyproject_version('20.04dev1', pyproject_toml_path=fake_path)\n+\n+ text = fake_path.write_text.call_args[0][0]\n+\n+ toml = tomlkit.parse(text)\n+\n+ self.assertEqual(toml['tool']['poetry']['version'], '20.4.dev1')\n+\n+ def test_empty_tool_section(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.read_text.return_value = \"[tool]\"\n+\n+ update_pyproject_version('20.04dev1', pyproject_toml_path=fake_path)\n+\n+ text = fake_path.write_text.call_args[0][0]\n+\n+ toml = tomlkit.parse(text)\n+\n+ self.assertEqual(toml['tool']['poetry']['version'], '20.4.dev1')\n+\n+ def test_empty_tool_poetry_section(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.read_text.return_value = \"[tool.poetry]\"\n+\n+ update_pyproject_version('20.04dev1', pyproject_toml_path=fake_path)\n+\n+ text = fake_path.write_text.call_args[0][0]\n+\n+ toml = tomlkit.parse(text)\n+\n+ self.assertEqual(toml['tool']['poetry']['version'], '20.4.dev1')\n+\n+ def test_override_existing_version(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n+ fake_path.read_text.return_value = '[tool.poetry]\\nversion = \"1.2.3\"'\n+\n+ update_pyproject_version('20.04dev1', pyproject_toml_path=fake_path)\n+\n+ text = fake_path.write_text.call_args[0][0]\n+\n+ toml = tomlkit.parse(text)\n+\n+ self.assertEqual(toml['tool']['poetry']['version'], '20.4.dev1')\ndiff --git a/verify-version.py b/tests/version/test_update_version_file.py\nsimilarity index 57%\nrename from verify-version.py\nrename to tests/version/test_update_version_file.py\n--- a/verify-version.py\n+++ b/tests/version/test_update_version_file.py\n@@ -16,32 +16,23 @@\n # You should have received a copy of the GNU General Public License\n # along with this program. If not, see .\n \n-import sys\n+import unittest\n \n-from gvm import get_version\n+from pathlib import Path\n+from unittest.mock import MagicMock\n \n+from gvm.version import update_version_file\n \n-def strip_version(version: str) -> str:\n- if not version:\n- return version\n \n- if version[0] == 'v':\n- return version[1:]\n+class UpdateVersionFileTestCase(unittest.TestCase):\n+ def test_update_version_file(self):\n+ fake_path_class = MagicMock(spec=Path)\n+ fake_path = fake_path_class.return_value\n \n+ update_version_file('22.04dev1', fake_path)\n \n-def main():\n- if len(sys.argv) < 2:\n- sys.exit('Missing argument for version.')\n- return\n+ text = fake_path.write_text.call_args[0][0]\n \n- p_version = strip_version(sys.argv[1])\n- version = get_version()\n- if p_version != version:\n- sys.exit(\n- \"Provided version: {} does not match the python-gvm \"\n- \"version: {}\".format(p_version, version)\n- )\n+ *_, version_line, _last_line = text.split('\\n')\n \n-\n-if __name__ == '__main__':\n- main()\n+ self.assertEqual(version_line, '__version__ = \"22.4.dev1\"')\ndiff --git a/tests/version/test_versions_equal.py b/tests/version/test_versions_equal.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/version/test_versions_equal.py\n@@ -0,0 +1,37 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (C) 2020 Greenbone Networks GmbH\n+#\n+# SPDX-License-Identifier: GPL-3.0-or-later\n+#\n+# This program is free software: you can redistribute it and/or modify\n+# it under the terms of the GNU General Public License as published by\n+# the Free Software Foundation, either version 3 of the License, or\n+# (at your option) any later version.\n+#\n+# This program is distributed in the hope that it will be useful,\n+# but WITHOUT ANY WARRANTY; without even the implied warranty of\n+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n+# GNU General Public License for more details.\n+#\n+# You should have received a copy of the GNU General Public License\n+# along with this program. If not, see .\n+\n+import unittest\n+\n+from gvm.version import versions_equal\n+\n+\n+class VersionEqualTestCase(unittest.TestCase):\n+ def test_version_equal(self):\n+ self.assertTrue(versions_equal('1.2.3', '1.2.3'))\n+ self.assertTrue(versions_equal('1.2.3a', '1.2.3a0'))\n+ self.assertTrue(versions_equal('1.2.3a0', '1.2.3.a0'))\n+ self.assertTrue(versions_equal('1.2.3dev1', '1.2.3.dev1'))\n+\n+ def test_version_not_equal(self):\n+ self.assertFalse(versions_equal('1.2.3', '1.2'))\n+ self.assertFalse(versions_equal('1.2.3a', '1.2.3a1'))\n+ self.assertFalse(versions_equal('1.2.3a0', '1.2.3.a1'))\n+ self.assertFalse(versions_equal('1.2.3dev', '1.2.3dev1'))\n+ self.assertFalse(versions_equal('1.2.3dev', '1.2.3.dev1'))\n+ self.assertFalse(versions_equal('1.2.3.dev1', '1.2.3.dev2'))\n", "problem_statement": "", "hints_text": "", "created_at": "2020-04-01T13:55:00Z"} diff --git a/PythonDataset/test/python-slack-sdk-task-instances.jsonl.all b/PythonDataset/test/python-slack-sdk-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..51fbfd0bf27a2437baff7c6f6303e9d85436b5d5 --- /dev/null +++ b/PythonDataset/test/python-slack-sdk-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "slackapi/python-slack-sdk", "pull_number": 836, "instance_id": "slackapi__python-slack-sdk-836", "issue_numbers": "", "base_commit": "2defee516b105112af592dc545a376a893345002", "patch": "diff --git a/tutorial/PythOnBoardingBot/app.py b/tutorial/PythOnBoardingBot/app.py\n--- a/tutorial/PythOnBoardingBot/app.py\n+++ b/tutorial/PythOnBoardingBot/app.py\n@@ -1,7 +1,7 @@\n import os\n import logging\n from flask import Flask\n-from slack import WebClient\n+from slack_sdk.web import WebClient\n from slackeventsapi import SlackEventAdapter\n from onboarding_tutorial import OnboardingTutorial\n \ndiff --git a/tutorial/PythOnBoardingBot/async_app.py b/tutorial/PythOnBoardingBot/async_app.py\n--- a/tutorial/PythOnBoardingBot/async_app.py\n+++ b/tutorial/PythOnBoardingBot/async_app.py\n@@ -4,7 +4,8 @@\n import ssl as ssl_lib\n \n import certifi\n-import slack\n+from slack_sdk.web import WebClient\n+from slack_sdk.rtm import RTMClient\n \n from onboarding_tutorial import OnboardingTutorial\n \n@@ -15,7 +16,7 @@\n onboarding_tutorials_sent = {}\n \n \n-async def start_onboarding(web_client: slack.WebClient, user_id: str, channel: str):\n+async def start_onboarding(web_client: WebClient, user_id: str, channel: str):\n # Create a new onboarding tutorial.\n onboarding_tutorial = OnboardingTutorial(channel)\n \n@@ -39,7 +40,7 @@ async def start_onboarding(web_client: slack.WebClient, user_id: str, channel: s\n # ================ Team Join Event =============== #\n # When the user first joins a team, the type of the event will be 'team_join'.\n # Here we'll link the onboarding_message callback to the 'team_join' event.\n-@slack.RTMClient.run_on(event=\"team_join\")\n+@RTMClient.run_on(event=\"team_join\")\n async def onboarding_message(**payload):\n \"\"\"Create and send an onboarding welcome message to new users. Save the\n time stamp of this message so we can update this message in the future.\n@@ -62,7 +63,7 @@ async def onboarding_message(**payload):\n # When a users adds an emoji reaction to the onboarding message,\n # the type of the event will be 'reaction_added'.\n # Here we'll link the update_emoji callback to the 'reaction_added' event.\n-@slack.RTMClient.run_on(event=\"reaction_added\")\n+@RTMClient.run_on(event=\"reaction_added\")\n async def update_emoji(**payload):\n \"\"\"Update the onboarding welcome message after receiving a \"reaction_added\"\n event from Slack. Update timestamp for welcome message as well.\n@@ -91,7 +92,7 @@ async def update_emoji(**payload):\n # =============== Pin Added Events ================ #\n # When a users pins a message the type of the event will be 'pin_added'.\n # Here we'll link the update_pin callback to the 'reaction_added' event.\n-@slack.RTMClient.run_on(event=\"pin_added\")\n+@RTMClient.run_on(event=\"pin_added\")\n async def update_pin(**payload):\n \"\"\"Update the onboarding welcome message after receiving a \"pin_added\"\n event from Slack. Update timestamp for welcome message as well.\n@@ -120,7 +121,7 @@ async def update_pin(**payload):\n # ============== Message Events ============= #\n # When a user sends a DM, the event type will be 'message'.\n # Here we'll link the message callback to the 'message' event.\n-@slack.RTMClient.run_on(event=\"message\")\n+@RTMClient.run_on(event=\"message\")\n async def message(**payload):\n \"\"\"Display the onboarding welcome message after receiving a message\n that contains \"start\".\n@@ -143,7 +144,7 @@ async def message(**payload):\n slack_token = os.environ[\"SLACK_BOT_TOKEN\"]\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n- rtm_client = slack.RTMClient(\n+ rtm_client = RTMClient(\n token=slack_token, ssl=ssl_context, run_async=True, loop=loop\n )\n loop.run_until_complete(rtm_client.start())\ndiff --git a/tutorial/PythOnBoardingBot/onboarding_tutorial.py b/tutorial/PythOnBoardingBot/onboarding_tutorial.py\n--- a/tutorial/PythOnBoardingBot/onboarding_tutorial.py\n+++ b/tutorial/PythOnBoardingBot/onboarding_tutorial.py\n@@ -1,9 +1,6 @@\n class OnboardingTutorial:\n \"\"\"Constructs the onboarding message and stores the state of which tasks were completed.\"\"\"\n \n- # TODO: Create a better message builder:\n- # https://github.com/slackapi/python-slackclient/issues/392\n- # https://github.com/slackapi/python-slackclient/pull/400\n WELCOME_BLOCK = {\n \"type\": \"section\",\n \"text\": {\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2020-10-07T06:40:16Z"} diff --git a/PythonDataset/test/python-sshpubkeys-task-instances.jsonl.all b/PythonDataset/test/python-sshpubkeys-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..045606e10c8eb1807931dc348af5b9b492234a11 --- /dev/null +++ b/PythonDataset/test/python-sshpubkeys-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "ojarva/python-sshpubkeys", "pull_number": 39, "instance_id": "ojarva__python-sshpubkeys-39", "issue_numbers": "", "base_commit": "2a3cce903ddedddd6f0f3cb231730e8c7f875430", "patch": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -9,7 +9,7 @@\n \n setup(\n name='sshpubkeys',\n- version='2.2.0',\n+ version='2.3.0',\n description='SSH public key parser',\n long_description=long_description,\n url='https://github.com/ojarva/python-sshpubkeys',\n@@ -37,7 +37,7 @@\n keywords='ssh pubkey public key openssh ssh-rsa ssh-dss ssh-ed25519',\n packages=[\"sshpubkeys\"],\n test_suite=\"tests\",\n- install_requires=['pycrypto>=2.6', 'ecdsa>=0.13'],\n+ install_requires=['cryptography>=2.1.4', 'ecdsa>=0.13'],\n \n extras_require={\n 'dev': ['twine', 'wheel'],\ndiff --git a/sshpubkeys/keys.py b/sshpubkeys/keys.py\n--- a/sshpubkeys/keys.py\n+++ b/sshpubkeys/keys.py\n@@ -22,8 +22,9 @@\n import sys\n import warnings\n import ecdsa\n-\n-from Crypto.PublicKey import RSA, DSA\n+from cryptography.hazmat.backends import default_backend\n+from cryptography.hazmat.primitives.asymmetric.dsa import DSAPublicNumbers, DSAParameterNumbers\n+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers\n \n from .exceptions import * # pylint:disable=wildcard-import,unused-wildcard-import\n \n@@ -43,7 +44,7 @@ class SSHKey(object): # pylint:disable=too-many-instance-attributes\n DSA_MIN_LENGTH_STRICT = 1024\n DSA_MAX_LENGTH_STRICT = 1024\n DSA_MIN_LENGTH_LOOSE = 1\n- DSA_MAX_LENGTH_LOOSE = 16384\n+ DSA_MAX_LENGTH_LOOSE = 3072\n \n DSA_N_LENGTH = 160\n \n@@ -274,8 +275,8 @@ def _process_ssh_rsa(self, data):\n unpacked_e = self._parse_long(raw_e)\n unpacked_n = self._parse_long(raw_n)\n \n- self.rsa = RSA.construct((unpacked_n, unpacked_e))\n- self.bits = self.rsa.size() + 1\n+ self.rsa = RSAPublicNumbers(unpacked_e, unpacked_n).public_key(default_backend())\n+ self.bits = self.rsa.key_size\n \n if self.strict_mode:\n min_length = self.RSA_MIN_LENGTH_STRICT\n@@ -297,10 +298,8 @@ def _process_ssh_dss(self, data):\n current_position, value = self._unpack_by_int(data, current_position)\n data_fields[item] = self._parse_long(value)\n \n- self.dsa = DSA.construct((data_fields[\"y\"], data_fields[\"g\"], data_fields[\"p\"], data_fields[\"q\"]))\n- self.bits = self.dsa.size() + 1\n-\n q_bits = self._bits_in_number(data_fields[\"q\"])\n+ p_bits = self._bits_in_number(data_fields[\"p\"])\n if q_bits != self.DSA_N_LENGTH:\n raise InvalidKeyError(\"Incorrect DSA key parameters: bits(p)=%s, q=%s\" % (self.bits, q_bits))\n if self.strict_mode:\n@@ -309,10 +308,15 @@ def _process_ssh_dss(self, data):\n else:\n min_length = self.DSA_MIN_LENGTH_LOOSE\n max_length = self.DSA_MAX_LENGTH_LOOSE\n- if self.bits < min_length:\n- raise TooShortKeyError(\"%s key can not be shorter than %s bits (was %s)\" % (self.key_type, min_length, self.bits))\n- if self.bits > max_length:\n- raise TooLongKeyError(\"%s key data can not be longer than %s bits (was %s)\" % (self.key_type, max_length, self.bits))\n+ if p_bits < min_length:\n+ raise TooShortKeyError(\"%s key can not be shorter than %s bits (was %s)\" % (self.key_type, min_length, p_bits))\n+ if p_bits > max_length:\n+ raise TooLongKeyError(\"%s key data can not be longer than %s bits (was %s)\" % (self.key_type, max_length, p_bits))\n+\n+ dsa_parameters = DSAParameterNumbers(data_fields[\"p\"], data_fields[\"q\"], data_fields[\"g\"])\n+ self.dsa = DSAPublicNumbers(data_fields[\"y\"], dsa_parameters).public_key(default_backend())\n+ self.bits = self.dsa.key_size\n+\n return current_position\n \n def _process_ecdsa_sha(self, data):\n", "test_patch": "diff --git a/tests/invalid_keys.py b/tests/invalid_keys.py\n--- a/tests/invalid_keys.py\n+++ b/tests/invalid_keys.py\n@@ -7,7 +7,8 @@\n [\"ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAEAgDGrGaNv7i+sGSelzf+7JsCECa9a0sqSg8q4foGkjeV6RkS2tWvKXoT9rICjEdXXodj0CCVhe/V7dmAO0AK8KM0mcvPfTSC8zH1ZBsqaFFTWwmBD01fbH9axrrg3hM0f+AL4bMMWUdxdNrVo90s8PKU6k/HmUNLVx4gC6uQ4A6YczvOVZkuJ4f7HDYK/v1LNTRNeAkw94YpSIZVAoTOZN943+fRCE9cm155pwmFsS+wfzK9+jjhGXNEK0xooiVBRwQM7qetN076vV5FiiM0LO1qYi5JrIqK/70ske86x2mMhMkOe6jqQQbt32PFVmYqYJWcAYXz+bhcQw6oru0c6gNq53aGOnuqI0uh/zV2XH+cN4c8ABcOplzH5YQEUepNVzxylkvpWxdg/ZzR1pvyu5C8RkJWrE3AlCwpix1ak2xTDzgc3rwTTggNSYqvzmYq0mYJhZk2VWsLVxUgdxfwC3LvIHMXSTU9iU2Aqrlhy7bJAqxQFKWy05wsIOI6raPBLqZnPmJ76Ld9aXTrhBFfIDiigr9ZVsVAdOvmyAGCIj4x3Xnlol/3lN0M2+OSV1SU/5ZrS6dIlXPZDak/OXHU0iIFIODhYU5r8EI1M6BI/jsgQ8HatXmOJkfnIkVP0HxD1KvoAFKjVG5sM9KG12LqsnzfD1KL6PzxpOOgoVgznpOjSzVmPKAkU8N/r6R4VIAmZqxpF8Hlzqg/Gfh5kf6CJXXx8OQt1Z/DAsfnl3LvHFNuE8GgXgrUE022W9pV4oONgojc97JSgBXaFkK885UnJKTceAdGQvChEhsU1j3TiyKPox6ICGpoC2nGONJoDE8VQ8dE/YiZmqkZ1lJWX07EwevrIcnz1UBHFaR72aiAADRYClsitLA5+1mnydVstkQ8XQuuKNOFT7miaWUzRHwj9BYGb7oGhNd9oi1VTVjH/5Yq1UiHHESGaIjeLi5uG2KguDFpcvy2ngtUy3ZbvDj+DVOLL+3vAlycRPjN0nBE4e/J6UqdpLg0DbG56zNj86aU0ZgL8kL8NRkFHyV+5zG5iLFkGklbm4nwCxSW/bVT0PFD1is6JbtIk5i+liS+hiuzSF6NGouSuxDy95yWSG8/84fgPDFtvXtOD7Kl4P7EpEAL+VBZnremT9I8tRl1wOHxJKe7jbEcWC2zkuHNlju0Nv5SFijF9c+krRbHDYEzsxPpdqlI4gPtDFdkKwaKN6BrsxBsz9u+PhS1AloUYcxKRqWbqHuDBrKmxnhOgFqJ9ITX0RajtrApt1LfkSBXcFrVEx2nhQkGa6VwjcX/zw2I2iuJFOCQmc9udHIlyaCCSe1PqOIbOlOk5h/Gl1QvRNwSIgf9dZ05lZr6dc+VX8YGdyHsjQ==\", InvalidTypeError, \"rsa_key_no_match\", [\"loose\", \"strict\"]],\n [\"ssh-dss AAAAB3NzaC1kc3MAAACAwQBAoKCAoECggSAgAOAAwOCg4AEAIMBAgMBAYSBg4GBggKAgwOBAwEDBAMCgwECg4GCBAAEhAABhIOCBIIEAQECg4GEAoQEgQQBgAGEAYQEAgCDAoCDgoIDBICAAAOCgwGDhAAAAwQEBIKCAYEBA4ODg4EDggSAgAGEgAQCAAOAAAAAgAAAAAAAAAAAAAAAAAACEAYKAgICCAIMAAYCBAYICAoAAAACAgKEgQCEhIKDgISCAAIDgwGEgASEg4GAgwQDAoCEAAEDBICDhAAABACCgIACBAIBAwOEgQEAA4KBBAOAAIIDAIQAgoGBgYGCgYCCAYEEgoEEgAABAIACAIAChAKCgoKAhIMDAgMEBIIDgAQEgwCDAAMBA4KAgACBAgCCgIGBAoGAAAACAwKAgAIBgIIBhAIBgQSAAgMAAQICggQDg4SCgoACgASCAwKCAYSAAoMCAYAEAoKBgoQEBIAAgICBAoMDBAMEgYIAgYKDggSDAoQDgQEAgAOBgQAAggQCAoCAgwAEBIEDgYABAgOEAwECAQECAAQDAAECBIGBAgEBA4AAgQSEBAKA=\", InvalidKeyError, \"invalid_q_for_dsa\", [\"loose\", \"strict\"]],\n [\"ssh-dss AAAAB3NzaC1kc3MAAACAgIBAAIBgQJAwgJCAQCBwICAwYFAwcEBQMBBwUHAgcCAAkEAQQECQkBAgkGAwcEAAkIAAMAAwAJAAcABQQCAwIHAwIIAwYAAwICCQkAAAUHAwIBCAMBBQcCAQAFBggEBAQDAgIHAwUJAwkFCQUDBwkIAQEGAwICAQADAwcJAAEJAAAAAgAAAAAAAAAAAAAAAAhIIAggODBAAEgwIAhIGChIICBAAAAACAwQJBAcECQQBAQIGBAEHBQEGBgYCAAQGCAIECQMHBwAIAAIDBAMIBgEEAQADBwIDAgcABAYHBwMDAgcABQgABwAHAAkBBwYAAwYJBwgAAwQFCQICAQgFAQICAgAIAwQHBQYJBQADAgAIAgMHBwkJAQEFBAMGAQAGBQQHAggBAQIA=\", MalformedDataError, \"missing_y_from_dsa\", [\"loose\", \"strict\"]],\n-\n+ ['ssh-dss AAAAB3NzaC1kc3MAAAIBANmIbHMDdrRAyd9rMdYoAAxxTIIke8xxS7txH16etsax8YlUEojvIEKRS/C5hulXw+fZYjdz0vjhTamoRo76ML2qz4X2lh96tJxoHVMVtXTdSDKfra4VuTp1mkYr6ycH9h7PEop+9WuB/Jx9ua/OCQ6cB6QePvg/XEaoKETHqrH7IilfJfBeLGgZc76q6+xjw5Qwtmu5nyImd17dWCa4ECdGw7NlbuuZHUs0/TfcJ/UHHuBgj1FKHEINBu3bcZdYKsyOm0VmxRw9Kkvh7qobBMXaNN9l3YvySTsSSbEWboK7jcFEC904i+hHxuYRa/K1x4v8SDaiOkxuJHGOCbfK/TaQdnyUBA2OEgt3MIuQGzc0xSXE5rEkLcjjkadkLA79Z/kajTNWzx54PT1qv6jP8kaa9OCzI+9aml+Lw2dtyDdBN3UDdSZj/823ABEm/zEgifziFrJbz32y3cdza9Jj/EcHCxDiN66Ghj2uLBERhXDxBWPZPoPlKeH+Bk/X/2CqA2H51RgLHtsVvqdrIWSXpAYYpGDaLnsG0yfsSrjGGIs6S9My+1ZSJPE0x568g6vbsTkuLJ70HwY4nhb/yuT0CuzPXsHnzKifzWMZldJki2KDowbJXye2ZJkz6PoknxC1ygT76AFxFvnZUHBMQQxrzV7j3op9jVhsvutyxueHB0efAAAAFQD8bGMGSx8iUNR+mdFoociqqhTuHQAAAgBEg7s1ZDHOuD04RlPNl9dMKOVZpDTdvVI0sKyWvWoxbImwQIBdE+DGZnrWD7/IxosU43J0hE+HcoADou2uJLGcxks8lcRBvdH4d4bVisT/+DsOwPuJKbHNwkV4De9ZmdGEvahQcHFI7KO9HNWWOWMl7opb6KUjRFYWkzF77vVRUw+FdZe4k3zrdHLrv3/+nLPuI7qxqyr+4HpntA4udx9mMVvKBL6ZgaDiXjET43NaFGmnIg9XXoiVj1xtk+dpFDc02gvskHr3zl2G79+FRBYHhMjzlJMrH85bmIIhGPZwFsCWBOupbeXTkDhzDBjcn5NYBhTHmpIcISv5N/anscs4ptUBnS9QbaZNaLTC/4IaNgLvI+iEvGxOml2uMHLu5njJENhB/T1nlDIiTMCk/8cfT8+Rnx/AUjdT3cOxnygYwHeFAc935EmPzh/li2CY+3p43Ihbd5V30MNWTvGGQzs4+7eCqOe+bhkh8EefCnh9yGCKkFZSH0JEoqkTr8842vXBhaQG4cT9e5UTKSkDigJdMb2Fp26jI3EdRbAWD46/Zp7CQkbKrQJxo7OzWUC7UY0oM2ka4jXvrf+SIL7/ith2gILOwzIH5MSM7A9AgQ6TdEvFQ7mQoWnCB2kTjB831qrPFKO21EP+iUrtCslDri2KfSw91l8Fv2Aro8A4pC7/wwAAAgB/hMtSA+nXw7691YNE7howbEEBdUS+5xP5KygfzSkruA6NvzQxC/V+6hHJ8i5oCgdhJ8KvVx2QeXe7M5QHDu3Tj3PWRi9oINwMlN1ZKRHY3FPoHBHje3uvL9hgOZUOqWTY7iuqEuX9TaL5Mu9dXsdBkjWuQYKfh1rnhnRWaH+ViPpQxv8ZMVQ0+tWSQWVpkM72lZIyZtgVOuHcRyImN1zHeps6ibNpfJ7UaHY1IA7DczWD0qGR8yawyhCVQ0KtbVVBscA18SO5c4VroJI/je9/ls61d190BAWEJnacEXHEtAuVJRbUWIzldlWy6NM4E+mg1R7Wy9FESxvviXUap2jAh+60og6TVvpgOHhw+BGc6pBgzkxhY46MvgOuOSr7V9ikk6h11IFTn2wHTB14NibS+fA8NOadAHB6OklY7pEMgadSgFC3kOzKpHeoEPosnHr7TgtiGwOhfAVlr/DbsgQnoQaMHdMAaJ1iTAMhwDZNpFSzgU5WjUnMQjydJKkDo/3OUksrMyEXR4kHt0vbmLBKmUVSX02MpQqEzXNPqxEbjfg7jYezZfjbsN36bD87BLpjZhlxkDECvTKPD45Af3di0Cams7tlc0RJxnj8TvMhG9NTjsIjaqLGCLZHeF0rnWE9nteKO8JLGBXgv/12nOUy66NwIbiTohTJvsIYaIyXCA==',InvalidKeyLengthError, \"too_long_dsa_4096\", [\"loose\", \"strict\"]],\n+ ['ssh-dss AAAAB3NzaC1kc3MAAAgBAP9jN4kCDNCxQ6hKKIswzKPtiP2HTA/yHDOe4Vs4xfXINs464QV3ah0gIgx4i0uNidZL07msPbXihrmJT97fPhT/6Qa9SsqKQ3k9fxJIe1CyEQ+/2dJtGO1uwrLkymTSqa+PyQJ8WS+bVEgYfmGGvGyxClYkK1Qcny0h9+k5GEHnUzVKe0giwWk2DGFHBZqjaskTNJtcgGVdm9jYbZDnSPC+ovJ04rTnzgPwHY/GqBSt/lk8MLidEqgZ5RFN7Ytlx1/hZIw1jpiQmQms9lrLVXN1PqA+WSoIPjhLKOUoG6HMBNvH3XSdA00dxRJ92F4QX+hGKUt/I5fLf2JluObjRqodfTua5iU254TTQ9XNk0JvVmty2FvJ+8E2MPd2VQ5KnTSghkn0JodBBxLoEbt9EatZn4wCzWw82rtvxzPnRS50fgw6UDbt4H9JEIlVOMKzxLY9C4G3+Es0qe7MlWzEEZsGQdFU9jjSBxj1Tg5Wz8ZzsCDZ9nZtAY9crhknFOj7/NAW56n+i1TZTmbEK0WtMO8Vjcl2MXOyQxo8PhAzshNBcX4KHcnkRjZOFGnKBAo02K9WUg1ATKvhGKhXOC6BGQ1a+7vdaqcZ+YeV9ByDK+TbnN5Jv8f2JvNzwFwIjTScmZ+nVY+NmANOEu71JDy4YzndpxodHjtT6ewT1oYXQGBi4w8XiC6R6tGTCLu3ho9dm7egeF2J1Llrf1HhHGTudYh+dbg3OoN9VLpYSA2erD3m5+2LQ2zzYmYoMWL0RUk00dPdosrkuoRTEYG6SXILFlXoar83VOhn01Kdh6mMzRFUvBX3wGFU5t7G9PR6KzPCreLpFDvuBmNrMwgkVspOhn4palbsbshm4zhfL7W1tovrfhkXk81LYYHj7Ir+uv0sDwOY2kgH/5RUxaz2SH5zQwbyc21PftDPIyNGvGBUm6Srn4slaeC9egHn/oKCZ0PZwb/FIBafl8I9QJ7rATX03Aq1QSF5/iNvJDeEZTuK6WzvW4CSHgDM+TfYJzUHo/YfUS8SQ1/HeES99rpB+7qdmmT5WSbN4Nr4+CGWEpdAnIknB6jaf8zZBDHUPOMnwjReHxIe/cWDBua/+PTwPGp5/314gKYz+iQJWI6WDHoX87YiWZNOq43QCxX8KRHfYB8e3Bg1ftEIz8bg0VrH1ucsnuJ3L31eoHGmgr3J2qIzctwA74zzNR+BparwxgHxKD21UzIHekmA0kkC5A1Pt7+HLW570WFphMMmh1xBpKEiP0R/h76NYkbfA1FYpsAVvwUGdLNI0qC/UrTAXpw1B6I0oyqH5hypityc0ys+LG2RSa9n0kyx6+EbtCTep5nzaBO53jTJCzqnUeloFW9fM76yWg7Sgm9Upt/g+Fw1XDpZZF+54EnRfLj6ajBRcDN+o9gQ9oBXGv4fiUtRipapEwdjlQyhoWe6Wt49pYyA8ai+ASK3DAuA6czVpbltlbVt7ouv4wawxLvFd+MapvH4R28Uyb2BM3Ceq9afY9mPOyWUv26BpBJcq6LRnYlz5asaw2nsJ6v5y8Y6POjKfAb6q9qvyNxVC8AtIesMLLheL3RBUFTY0Iz7B1oRCtLEjOi4KEc+440c7jrNUxPM4Gw9hZbosuCR2yzIafjRfvmPfmFgGVFrPTVW1pP8yKSdrpnYkZbUeCI+QENbqJHe55hB0kacCsLChNRuGUPg84F7spGlLV/l7f554kjoDgaI+rO3Vb59mDCnr1zGVzdsPCfeyHz+s9LL1+KwnXCX0DDJfET90axiPCZ36IIhaBdCRJJwkmxN6koHSMf6Jbcby6IWOuwJDjK/502Z59Isx7r6R7VLiomi4lkOfk/j8Sg6dmH1bb9jAXduQSSsofxRRFX2rRbcGr7HNWbWmat4a4X4a+2dRwm/JlHBtgiDeuWNSIz8laNJCnuFvbFds+sB4WczL4s1h/VAdMiMFXXwVfoyMAh2CsYPnsUbKTy4/J3AfIleX+5kdkipAed4a9EWU+auyIdqpSiNItv/ewQvbcnknbG82TmsG5whsO4A0D37OasbRE23P2w9rMqD6Wg8w5O4bKabX5AHdMOWn1kVNThsCsTar5eC9PIOMgic17Vofq4p31GE78VxS4tQlgzCFp3x9HxiFZGmkmJqBn+CaWIQxHaujRr4eQ1GVhmMgrxck+Oe0cAx7Cd1BWPHGRps1LO3EetG3JJE6qrGtkJmp4Dvq9abmKY1m3qXDxEJfMLFe6et+y7tPrmtsm/zMkpLFF8qQCHTetwWzkHzZcfyQMLdzJMb1IWmbn7KXS4AsU18KDfa2V7PZhiUn2fHMZFMjGdJmBs9LoX1aZ4Wf3UuTv5nU76xE3MXxQmVzM3itWs/yhmeFwkHFdA93Vlr/70uxiZSBf+Uz/9o6xJZi+urdPw9TBfYRvfHEP0Ifcl/TDCA5ZF9M/X2LGimGXRhlMIMXK+ng2sa9OTpYgiEzP8etpGK2kB8GvTdm5ymdUXm21uZ8Q6VjGViOohVz9V8R2pBrcNKQN6Z5eJ5eyR9tPyseye0OAXWFrkSztx+IrghbzalHC5udjkJdO7tYPJqpK0oxdLWTttJxw5a1ZprF4s7spvimGEGlXiBZbs2gMWY8UHj+tAwFZstdhGWeCYt9QaVP7pn5+FoROJy5Zmki2WWWaJAhwDn/Q7N0guGzvjpioprlMGgAfhGicyMZvbcLfNt+65Deozu9ztQoZpCiJRHZSUesbt7hF1fAAAAFQCwLEFVVTPnDmAyuuZ3DbxwYtiggQAACAEAp/cjRofm8fa1N+vcONr/FV1z0b9TabyWsjmw8OKFlYhvAZ+l9iHw2VYK8SR9IBOiUDAz4WsF01wT5UKNW1M4HGDoNDIawTqjBERb+81vbTr5lmU0pMaCcJD3Y1iku1ioNQsKV/tnRClNnQ4SvV+hmCwjEJGTFAISn1I5yn7WbwElC9BzpGH3OaShl+t8twsXx/H4uenegZIZBoRyrd7DlRo3epIcSsFx3xS3XAeu6yIcPcf9xONm87ZElLNEBQ+TqZq5w9reH4HFD0GgYq7ZcJ8Ux2zaPPnPEiCsPkZN0aVfOumM6qnrGijlEBOSuqmSPNoRboM3LSfgnSECgiLCVvbRlAIGqEIaCGbnw1p/DcprelAHf7bwSHfehjYf0FVTq7vvXFDz/vO2+8EojLbmhnE3ZFi/0opLa54X16Dcpe25prkIv92VIWLuMsPbHCazroNujejv3U+1jvQ4kJn+jATx5LSo1k9rlJtIQsxRvu5000Ac+HtBZq7dM8IahItp4ltEcHWUVhpQUhoRpz2NDqW4CgosKMnTwRKArbgEXy0wlbVtI3E9vQqvAcklaP4kaiLazJaOqNYP/V+WTCuan3weArOu+GC30QfCaSGtUDVj0TxHkGWjGW4l8rYnyktW1AtGGcHiVXM/aAV6WAAPzYHdJF3RFO79aJnVaXEbW38etFy5A2I2Va5zyJwMduIFKK5yLCG30B9BtG8NpPzcTd4cq7UeFcSQX79Fw/ifpZvzj3b4nT/JmudVDfimLSAgO5Q5oSbCHVHkZEvFzWBtue0KinoGs/ykqLmXN+q4BZIGucYsU/CNBmrgWPoXHAJEmHr3GzVH6lvAmuve5Ye1xco89CPHouUAezHuliJ6+7yXJ3+AP0y3zH3AcdLRIvz7yGDXKCD/m+VZpo8eq0WM0BWHT8Zze15Kf6iMLS60vHRanutOiLumh+AWQDwDc0abtG6tYOPGw5lKcmou/HuDOXJUyQYeba2l/Y761kVzVLC8FluqZovu7WaM9Wzl/Ofr/H4aNOMWwALvWDsd6wn+Hzc+wwpiZiGL59anNOZMecgye6nMZMoIIx8b2h0tR5TJffX2tCDwlGAudTCCU8Tna/+IzWytS7zUdQEE5UBfwi7pAeIfu4P/KlYP4LLocEN5kM+xxas1xM/MIQxXbvhr4LBq8paHl/Ed2LzjxLnix1C+i0REkyX7CADvsw8uvxDk3VqAVOO2hVyFOmtmaqex/lDa0ga486OJWw+i9Ei4Cxb/c8sno2C20ABjiHnXbZVKJWV7bSvMqgq4VBcDyhH9s/OUVIz3sdZw7BFok2RzQ8GtGAXNmDrtqUT3zGo+4NeYucIMnZ4zamhdz+krS+aMuNEcth1xsnX0omN4COMtIkIQKuPrYDfi220KGFUP4sUJ3zxkzVENFiF+c4bh6aMZrh096sZx+Sf+ZNWm/8ZpuOEJOuhpcvaGsLmbN2FjuyJoa0ZcsUi7w0NpClJzVHnnaXrWOmaVGAeNRQ0YIQHiXmAmlX6ZqCwiWD1rNJHkDunhwRDerexExdy7qkORMKwHQOenyy+L6YUflT4rj8lw9exHA6MpPpFvLCv9rN31sDO26WzI1i4Iekz8WGyMgsoY4a8iSrNFbh59dku+NmVc/MrQ3LCgXQ2NZTZwmGwxfQfRxDnBVy8aMZga9OQQ372GWPJeYnGpOSeTMQOidT6khTEoraY32Cq9jqQpCuRdAOjPSBu3uufxORjZHBFbCetT7khHwfsqQlcXpsDfy06leNbPT2tXKlcGzmq1zElTZq0Vdlx9dOX3NwrJBMmYJ8hR6TJeTfMPABwg8OqU/RPDAsKfC6QziDt+iTkH1JFkobrG9x3C48ydzB3FZi/6ulPO558kpA3xkVFDx1V7yQyXu+8z96qvgrpig84wzCQbVIAr4P6dVyPBGrkc6Z/mElo2wTRRM4bYoGdkBFA0H4mMXSDUPc4QbgAafbFiI9aS/dV6cx4LQrpp/XwpyMlhT9ZFF0pj3/6mev44h2qq/P2fGS2B6ntZZXrdQ5a7q3AZ4bz+ggvOC3qJHsUl9MD158ABf29rSzUU2YcP3C1snKNrMw1aWCN+aT9tWzb0WztupAeHqEqGxiWEPxZNaQkU/BEqL8QkzhmV3xuqxQ9Jc72HDptQJthIPtrHnDzGoj7x3pu24W/PbHa8iDZz8dHf8U068M0QsopuOSY59TwDKUkwsBrHbgglos/2D57duWkq+xo36LK+uiKenvoEGqry7Vgz8xEMpQqvyY/9m1H3J/NLQCeE/si/o2bUPNaBYIO6acjqCk+JDObhL1RDJeeN1h602hQ0r5+FqEJDwwZxllYBM2bPPMZVD51yPm1GcbXHWA0JTKuJyLqk0XtLiUokHCqCezLm4Uwr44lS3nqNOMyyG0GdBItJms1X1ZPSR6pnIwbc4OF9fCWJQMN1BNRFpoOpFxvsPhAi6Y8MgHrKxBtR4xUEWVXJ1oJIDhDRtXsBgOUmi0kPWMZ7yCaql30OlAq/rSpkIm4wTQhMQO7kJrRzB8qmvWGzjjC85aMxbXMnOYu0xYlhoeqspnrqUXGJcgB+4o0w/olkbEKp0XNSEWcB8DRVhvsUaK2hCc+DpQeg4te0Hf3SPhGbl2aKeFBl3TnYmpMa+2H87QK4+9Vhs29Gsd7MYmSNWby36lOmc6Y7m1QWnWdn7srFzhLppumIWKWjRdcWjewW0zGaPjdX/cNik/oAAAgBANkBODfTinYNlvuuzT5FGsG1ZSu1YWgbrPw959qGRpuBgMUtFsf1PKe5UM76P9EbTNBMPCt4k+PFFwtpEtLZKeQ3Ieng+XPvXGhMISa5aV/7mB+/JGY0dd3F9Vux15sNqM8mrCniGjCps+lE6nkm6suQJB2SVnmfdM4UJ6FnR+4yDlmc6eZVyz1Qk8gh5ujz6/o/scwEp5VfUspj9u34TP7bSzp1CDjsI//3c3rgoaMwIiFH7SVenxI4c7a3e0Yxj+NRDuOruswTNwSmcSAvhiro0ZboALQRirwCLA/0JUckWYOYd1WM5H7+PQZAuyFHXe/hK61fP8pjFf3hcG7lLfLEk6gki+u91l0ZXrWb2AgMMHxNf3myUqK1SbIGm3q05JbXfCPPk7rra26gPKa48b9J81AIWrVbS5AK7Pe1Hp+mmZaGFBgBcZR/5sZxkb5BNeyipI71Vtq4EW1duBeVQ++Z+1wgIg/NDvW1JS1TrCvvwBqcZ02KWrD3XKtnfICoXhAUCeof+QbxM36GVwnF4OUnxhV/7+SOyl3xh+nGW/28Ir9400UPWIhu2B5CPuW8SUelpWJG3Mkn13yLwBC1bcHspi3lSTdS8nETarAiBZqq5l0ZftqaJ5pRWayPtWI0oq4XNoQrAEW3lqtUDOPUXO/d7hJuYTNOigs3o6bAjzsj4VhGp6Q92icjR3neeRtshN76cb2hX+Hang+WYgme1r6OGhsifr0uHwslVuMYHyUAWEaKTylz9MzY8lqz9+gtKXFy1AcII0KnCMIYggH2QFHC9hnlXyWNkshne/euNj4tI7cxzZNyHsJp6zxqmfLI+JvpM3pVBz/ANJ/cQMbRQsGEuqgiPOP2Pbje4KMdRLDAFI43F4U9Bkjd/3Qe/6oK7/ZrQ/nfxGpdX97z0Ek4kfxdHu3HLZeegVZgz5s1rgZfAqAMnXoc7UEZHtKYicwiWg5Suzwhsbb8H4z6maJt/6o8tVHbxqSqYBszIdciBGYebQXvJDCCjIclNdHY224ejeEIB6zNm4lcin7yLxW2cuxoYsNeWUT3oBt1x3cvAjQdx+839yIONUKbTmUyKrcrIRYIp2jqdQQx+UqeyhflSkbySNCNv1V2YSy4WkbukzjQ/w9CNhYm01kHAZDDd5nDm5tkrDZJxKxwwqHazukaLOk0FgjnYtTieMrATNFS9H61u0NdYdkgLfJ8ap9qhJZsZ3I+LJOJAuu4rP5YCUrgRaWjAzhDINhfucorSHOu/qXs5wwc7MnhxaeAkhGMqm2V/t5GDo1sl5LkH47ER4jG3h2l+KDlYcH2AGyQfV9CQSt/Tyq5z6beXhWCouJZp1HhFVyZEwKXsVYxReWjz5h3dvAlENY9QFI1yeSWLzuJYdvr+WPiYbWvr2zDhQK5s7YEcbVLDZTI51gjL6emvEr3mg5g2PHAkYl2lPx5xRxexcAL9uk8JUGUeJCulso2RSK/hFYM2dG7FW+RcROW2H9xtVHtDSVxbyX520BB4oh9aaMLK7PK4gA3fyKaQBEzxUaKbpdpsU8lu066DV7xQIYVOG4HRl1RCBJgjFm8D/XiSYLUsa2iuF64zthagWkeRCLyr+MQ8MThL5SP3ryTYqxOsFiLIJGsI7zEdMuaoq2BI6N0KqTlb2iVa+BgOcFPE0QGe50ICkHXy3jda/5h1oH/TjvS7DsWoAcMQFZt+XP5KJOCz33uvVQrVsDDyCoCk5Iyj2jWzSxyO8lhYrdGUezY41sWaHQM4bbqARRrnZFymA5Bl3kBxfkKvtXATbIcBtR8OET5VxUeUaUfjvka2hoFSTf8JyqNUb8/iNie3jr1alo5/rXL8QaC2X3mJ3liCuyen1EoQvQqzbGuHg238+gVznlGjlGIMBw1MgNuvzOziTZd8Oh0NtIwMn4FMcMk6sx3EbYIHvfVaSkceAylMf5zpMXymuNvZzXccBtwkzMGT4i3XazdC9a9tdd5SzAMKrjkaviM9+Z8gA2SQgLUR75gozqeh9QsuOnOZxmkOB+YVfnRUej53cm5e7fbUm4a6pv2+r7/Xpi9GCXIeX6Sfdk5jmr9jTQ++7f5WeAhPPgGJEHkP1NhAldK5NpnBo5nYRpvxrNkAhk1sHlDoptdplbXaMoMjSgqk4MrWN3WBHmqtJkGC9RJmj+N2QZMqaXTd1X/LOzP0skHbZ4r/OI4cCOFdRWlTDKrCXdLLtSW6OMTyWj94feWw0i6nwXGzgFbhos4Jsr5+WrYxo1pVat8k+b4j5acvUdpL543IRV3fNJgTyGgn/maw7skokyK2jFXGkHfaE2E4cYlX6qohFNTs3YJbBBvw7NcPmBtAGnvjb6UpJPlB3Fl/bmSwilO7knFd+8EV8SfmXhyF2Izvj2he9ncxd0P9Q1MhRSGmnfsULj6bT4nvzIr9l61GUaaEN6A55g6s8px1xmnyXVSZcW1rP1df2P4RhlgbfQ7Q9beZbO8CRdOFRzAjLjn87K4QDZK3EyzfGz9ZqcDYjfesByqAptLY9s0yzdNdfFS7RqC5v9MklMJLgOYXHBYPLNJzrKjvbaKYEacA3vNwRvFOTxKJ8lha9Ir1o8hu4urWUE6Mu3GGttCmFenF7jVE6Qf4Fgpt8OKSk4cVXPP/2w+vpeAki2hCBNDhpVmOWVsc0uvibEQjoFB62TYkUeSR1e9P2bjCVsXei526CLAogC497trRRTYlQiviNjUcB+26JshoF1nmwuw', InvalidKeyLengthError, \"too_long_dsa_16384\", [\"loose\", \"strict\"]],\n [\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAEAgDGrGaNv7i+sGSelzf+7JsCECa9a0sqSg8q4foGkjeV6RkS2tWvKXoT9rICjEdXXodj0CCVhe/V7dmAO0AK8KM0mcvPfTSC8zH1ZBsqaFFTWwmBD01fbH9axrrg3hM0f+AL4bMMWUdxdNrVo90s8PKU6k/HmUNLVx4gC6uQ4A6YczvOVZkuJ4f7HDYK/v1LNTRNeAkw94YpSIZVAoTOZN943+fRCE9cm155pwmFsS+wfzK9+jjhGXNEK0xooiVBRwQM7qetN076vV5FiiM0LO1qYi5JrIqK/70ske86x2mMhMkOe6jqQQbt32PFVmYqYJWcAYXz+bhcQw6oru0c6gNq53aGOnuqI0uh/zV2XH+cN4c8ABcOplzH5YQEUepNVzxylkvpWxdg/ZzR1pvyu5C8RkJWrE3AlCwpix1ak2xTDzgc3rwTTggNSYqvzmYq0mYJhZk2VWsLVxUgdxfwC3LvIHMXSTU9iU2Aqrlhy7bJAqxQFKWy05wsIOI6raPBLqZnPmJ76Ld9aXTrhBFfIDiigr9ZVsVAdOvmyAGCIj4x3Xnlol/3lN0M2+OSV1SU/5ZrS6dIlXPZDak/OXHU0iIFIODhYU5r8EI1M6BI/jsgQ8HatXmOJkfnIkVP0HxD1KvoAFKjVG5sM9KG12LqsnzfD1KL6PzxpOOgoVgznpOjSzVmPKAkU8N/r6R4VIAmZqxpF8Hlzqg/Gfh5kf6CJXXx8OQt1Z/DAsfnl3LvHFNuE8GgXgrUE022W9pV4oONgojc97JSgBXaFkK885UnJKTceAdGQvChEhsU1j3TiyKPox6ICGpoC2nGONJoDE8VQ8dE/YiZmqkZ1lJWX07EwevrIcnz1UBHFaR72aiAADRYClsitLA5+1mnydVstkQ8XQuuKNOFT7miaWUzRHwj9BYGb7oGhNd9oi1VTVjH/5Yq1UiHHESGaIjeLi5uG2KguDFpcvy2ngtUy3ZbvDj+DVOLL+3vAlycRPjN0nBE4e/J6UqdpLg0DbG56zNj86aU0ZgL8kL8NRkFHyV+5zG5iLFkGklbm4nwCxSW/bVT0PFD1is6JbtIk5i+liS+hiuzSF6NGouSuxDy95yWSG8/84fgPDFtvXtOD7Kl4P7EpEAL+VBZnremT9I8tRl1wOHxJKe7jbEcWC2zkuHNlju0Nv5SFijF9c+krRbHDYEzsxPpdqlI4gPtDFdkKwaKN6BrsxBsz9u+PhS1AloUYcxKRqWbqHuDBrKmxnhOgFqJ9ITX0RajtrApt1LfkSBXcFrVEx2nhQkGa6VwjcX/zw2I2iuJFOCQmc9udHIlyaCCSe1PqOIbOlOk5h/Gl1QvRNwSIgf9dZ05lZr6dc+VX8YGdyHsjQ=\", InvalidKeyError, \"broken_rsa_base64\", [\"loose\", \"strict\"]],\n \n [\"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAH0GODBKRjsFB/1v3pDRGpA6xR+QpOJg9vat0brlbUNA=\",\ndiff --git a/tests/valid_keys.py b/tests/valid_keys.py\n--- a/tests/valid_keys.py\n+++ b/tests/valid_keys.py\n@@ -23,18 +23,6 @@\n 'SHA256:sgF5bepZnGBURoJcg+ON18F1LwvAmnUYlHoJUgYZVKs',\n 'dsa_3072',\n [\"loose\"]],\n- ['ssh-dss AAAAB3NzaC1kc3MAAAIBANmIbHMDdrRAyd9rMdYoAAxxTIIke8xxS7txH16etsax8YlUEojvIEKRS/C5hulXw+fZYjdz0vjhTamoRo76ML2qz4X2lh96tJxoHVMVtXTdSDKfra4VuTp1mkYr6ycH9h7PEop+9WuB/Jx9ua/OCQ6cB6QePvg/XEaoKETHqrH7IilfJfBeLGgZc76q6+xjw5Qwtmu5nyImd17dWCa4ECdGw7NlbuuZHUs0/TfcJ/UHHuBgj1FKHEINBu3bcZdYKsyOm0VmxRw9Kkvh7qobBMXaNN9l3YvySTsSSbEWboK7jcFEC904i+hHxuYRa/K1x4v8SDaiOkxuJHGOCbfK/TaQdnyUBA2OEgt3MIuQGzc0xSXE5rEkLcjjkadkLA79Z/kajTNWzx54PT1qv6jP8kaa9OCzI+9aml+Lw2dtyDdBN3UDdSZj/823ABEm/zEgifziFrJbz32y3cdza9Jj/EcHCxDiN66Ghj2uLBERhXDxBWPZPoPlKeH+Bk/X/2CqA2H51RgLHtsVvqdrIWSXpAYYpGDaLnsG0yfsSrjGGIs6S9My+1ZSJPE0x568g6vbsTkuLJ70HwY4nhb/yuT0CuzPXsHnzKifzWMZldJki2KDowbJXye2ZJkz6PoknxC1ygT76AFxFvnZUHBMQQxrzV7j3op9jVhsvutyxueHB0efAAAAFQD8bGMGSx8iUNR+mdFoociqqhTuHQAAAgBEg7s1ZDHOuD04RlPNl9dMKOVZpDTdvVI0sKyWvWoxbImwQIBdE+DGZnrWD7/IxosU43J0hE+HcoADou2uJLGcxks8lcRBvdH4d4bVisT/+DsOwPuJKbHNwkV4De9ZmdGEvahQcHFI7KO9HNWWOWMl7opb6KUjRFYWkzF77vVRUw+FdZe4k3zrdHLrv3/+nLPuI7qxqyr+4HpntA4udx9mMVvKBL6ZgaDiXjET43NaFGmnIg9XXoiVj1xtk+dpFDc02gvskHr3zl2G79+FRBYHhMjzlJMrH85bmIIhGPZwFsCWBOupbeXTkDhzDBjcn5NYBhTHmpIcISv5N/anscs4ptUBnS9QbaZNaLTC/4IaNgLvI+iEvGxOml2uMHLu5njJENhB/T1nlDIiTMCk/8cfT8+Rnx/AUjdT3cOxnygYwHeFAc935EmPzh/li2CY+3p43Ihbd5V30MNWTvGGQzs4+7eCqOe+bhkh8EefCnh9yGCKkFZSH0JEoqkTr8842vXBhaQG4cT9e5UTKSkDigJdMb2Fp26jI3EdRbAWD46/Zp7CQkbKrQJxo7OzWUC7UY0oM2ka4jXvrf+SIL7/ith2gILOwzIH5MSM7A9AgQ6TdEvFQ7mQoWnCB2kTjB831qrPFKO21EP+iUrtCslDri2KfSw91l8Fv2Aro8A4pC7/wwAAAgB/hMtSA+nXw7691YNE7howbEEBdUS+5xP5KygfzSkruA6NvzQxC/V+6hHJ8i5oCgdhJ8KvVx2QeXe7M5QHDu3Tj3PWRi9oINwMlN1ZKRHY3FPoHBHje3uvL9hgOZUOqWTY7iuqEuX9TaL5Mu9dXsdBkjWuQYKfh1rnhnRWaH+ViPpQxv8ZMVQ0+tWSQWVpkM72lZIyZtgVOuHcRyImN1zHeps6ibNpfJ7UaHY1IA7DczWD0qGR8yawyhCVQ0KtbVVBscA18SO5c4VroJI/je9/ls61d190BAWEJnacEXHEtAuVJRbUWIzldlWy6NM4E+mg1R7Wy9FESxvviXUap2jAh+60og6TVvpgOHhw+BGc6pBgzkxhY46MvgOuOSr7V9ikk6h11IFTn2wHTB14NibS+fA8NOadAHB6OklY7pEMgadSgFC3kOzKpHeoEPosnHr7TgtiGwOhfAVlr/DbsgQnoQaMHdMAaJ1iTAMhwDZNpFSzgU5WjUnMQjydJKkDo/3OUksrMyEXR4kHt0vbmLBKmUVSX02MpQqEzXNPqxEbjfg7jYezZfjbsN36bD87BLpjZhlxkDECvTKPD45Af3di0Cams7tlc0RJxnj8TvMhG9NTjsIjaqLGCLZHeF0rnWE9nteKO8JLGBXgv/12nOUy66NwIbiTohTJvsIYaIyXCA==',\n- 4096,\n- 'MD5:ca:b0:46:93:9e:0b:25:73:50:29:85:48:a4:b0:64:a6',\n- 'SHA256:yYiuSoa3x+MDucep2aaFSb+rAULOPUB0WLll6ppyaws',\n- 'dsa_4096',\n- [\"loose\"]],\n- ['ssh-dss AAAAB3NzaC1kc3MAAAgBAP9jN4kCDNCxQ6hKKIswzKPtiP2HTA/yHDOe4Vs4xfXINs464QV3ah0gIgx4i0uNidZL07msPbXihrmJT97fPhT/6Qa9SsqKQ3k9fxJIe1CyEQ+/2dJtGO1uwrLkymTSqa+PyQJ8WS+bVEgYfmGGvGyxClYkK1Qcny0h9+k5GEHnUzVKe0giwWk2DGFHBZqjaskTNJtcgGVdm9jYbZDnSPC+ovJ04rTnzgPwHY/GqBSt/lk8MLidEqgZ5RFN7Ytlx1/hZIw1jpiQmQms9lrLVXN1PqA+WSoIPjhLKOUoG6HMBNvH3XSdA00dxRJ92F4QX+hGKUt/I5fLf2JluObjRqodfTua5iU254TTQ9XNk0JvVmty2FvJ+8E2MPd2VQ5KnTSghkn0JodBBxLoEbt9EatZn4wCzWw82rtvxzPnRS50fgw6UDbt4H9JEIlVOMKzxLY9C4G3+Es0qe7MlWzEEZsGQdFU9jjSBxj1Tg5Wz8ZzsCDZ9nZtAY9crhknFOj7/NAW56n+i1TZTmbEK0WtMO8Vjcl2MXOyQxo8PhAzshNBcX4KHcnkRjZOFGnKBAo02K9WUg1ATKvhGKhXOC6BGQ1a+7vdaqcZ+YeV9ByDK+TbnN5Jv8f2JvNzwFwIjTScmZ+nVY+NmANOEu71JDy4YzndpxodHjtT6ewT1oYXQGBi4w8XiC6R6tGTCLu3ho9dm7egeF2J1Llrf1HhHGTudYh+dbg3OoN9VLpYSA2erD3m5+2LQ2zzYmYoMWL0RUk00dPdosrkuoRTEYG6SXILFlXoar83VOhn01Kdh6mMzRFUvBX3wGFU5t7G9PR6KzPCreLpFDvuBmNrMwgkVspOhn4palbsbshm4zhfL7W1tovrfhkXk81LYYHj7Ir+uv0sDwOY2kgH/5RUxaz2SH5zQwbyc21PftDPIyNGvGBUm6Srn4slaeC9egHn/oKCZ0PZwb/FIBafl8I9QJ7rATX03Aq1QSF5/iNvJDeEZTuK6WzvW4CSHgDM+TfYJzUHo/YfUS8SQ1/HeES99rpB+7qdmmT5WSbN4Nr4+CGWEpdAnIknB6jaf8zZBDHUPOMnwjReHxIe/cWDBua/+PTwPGp5/314gKYz+iQJWI6WDHoX87YiWZNOq43QCxX8KRHfYB8e3Bg1ftEIz8bg0VrH1ucsnuJ3L31eoHGmgr3J2qIzctwA74zzNR+BparwxgHxKD21UzIHekmA0kkC5A1Pt7+HLW570WFphMMmh1xBpKEiP0R/h76NYkbfA1FYpsAVvwUGdLNI0qC/UrTAXpw1B6I0oyqH5hypityc0ys+LG2RSa9n0kyx6+EbtCTep5nzaBO53jTJCzqnUeloFW9fM76yWg7Sgm9Upt/g+Fw1XDpZZF+54EnRfLj6ajBRcDN+o9gQ9oBXGv4fiUtRipapEwdjlQyhoWe6Wt49pYyA8ai+ASK3DAuA6czVpbltlbVt7ouv4wawxLvFd+MapvH4R28Uyb2BM3Ceq9afY9mPOyWUv26BpBJcq6LRnYlz5asaw2nsJ6v5y8Y6POjKfAb6q9qvyNxVC8AtIesMLLheL3RBUFTY0Iz7B1oRCtLEjOi4KEc+440c7jrNUxPM4Gw9hZbosuCR2yzIafjRfvmPfmFgGVFrPTVW1pP8yKSdrpnYkZbUeCI+QENbqJHe55hB0kacCsLChNRuGUPg84F7spGlLV/l7f554kjoDgaI+rO3Vb59mDCnr1zGVzdsPCfeyHz+s9LL1+KwnXCX0DDJfET90axiPCZ36IIhaBdCRJJwkmxN6koHSMf6Jbcby6IWOuwJDjK/502Z59Isx7r6R7VLiomi4lkOfk/j8Sg6dmH1bb9jAXduQSSsofxRRFX2rRbcGr7HNWbWmat4a4X4a+2dRwm/JlHBtgiDeuWNSIz8laNJCnuFvbFds+sB4WczL4s1h/VAdMiMFXXwVfoyMAh2CsYPnsUbKTy4/J3AfIleX+5kdkipAed4a9EWU+auyIdqpSiNItv/ewQvbcnknbG82TmsG5whsO4A0D37OasbRE23P2w9rMqD6Wg8w5O4bKabX5AHdMOWn1kVNThsCsTar5eC9PIOMgic17Vofq4p31GE78VxS4tQlgzCFp3x9HxiFZGmkmJqBn+CaWIQxHaujRr4eQ1GVhmMgrxck+Oe0cAx7Cd1BWPHGRps1LO3EetG3JJE6qrGtkJmp4Dvq9abmKY1m3qXDxEJfMLFe6et+y7tPrmtsm/zMkpLFF8qQCHTetwWzkHzZcfyQMLdzJMb1IWmbn7KXS4AsU18KDfa2V7PZhiUn2fHMZFMjGdJmBs9LoX1aZ4Wf3UuTv5nU76xE3MXxQmVzM3itWs/yhmeFwkHFdA93Vlr/70uxiZSBf+Uz/9o6xJZi+urdPw9TBfYRvfHEP0Ifcl/TDCA5ZF9M/X2LGimGXRhlMIMXK+ng2sa9OTpYgiEzP8etpGK2kB8GvTdm5ymdUXm21uZ8Q6VjGViOohVz9V8R2pBrcNKQN6Z5eJ5eyR9tPyseye0OAXWFrkSztx+IrghbzalHC5udjkJdO7tYPJqpK0oxdLWTttJxw5a1ZprF4s7spvimGEGlXiBZbs2gMWY8UHj+tAwFZstdhGWeCYt9QaVP7pn5+FoROJy5Zmki2WWWaJAhwDn/Q7N0guGzvjpioprlMGgAfhGicyMZvbcLfNt+65Deozu9ztQoZpCiJRHZSUesbt7hF1fAAAAFQCwLEFVVTPnDmAyuuZ3DbxwYtiggQAACAEAp/cjRofm8fa1N+vcONr/FV1z0b9TabyWsjmw8OKFlYhvAZ+l9iHw2VYK8SR9IBOiUDAz4WsF01wT5UKNW1M4HGDoNDIawTqjBERb+81vbTr5lmU0pMaCcJD3Y1iku1ioNQsKV/tnRClNnQ4SvV+hmCwjEJGTFAISn1I5yn7WbwElC9BzpGH3OaShl+t8twsXx/H4uenegZIZBoRyrd7DlRo3epIcSsFx3xS3XAeu6yIcPcf9xONm87ZElLNEBQ+TqZq5w9reH4HFD0GgYq7ZcJ8Ux2zaPPnPEiCsPkZN0aVfOumM6qnrGijlEBOSuqmSPNoRboM3LSfgnSECgiLCVvbRlAIGqEIaCGbnw1p/DcprelAHf7bwSHfehjYf0FVTq7vvXFDz/vO2+8EojLbmhnE3ZFi/0opLa54X16Dcpe25prkIv92VIWLuMsPbHCazroNujejv3U+1jvQ4kJn+jATx5LSo1k9rlJtIQsxRvu5000Ac+HtBZq7dM8IahItp4ltEcHWUVhpQUhoRpz2NDqW4CgosKMnTwRKArbgEXy0wlbVtI3E9vQqvAcklaP4kaiLazJaOqNYP/V+WTCuan3weArOu+GC30QfCaSGtUDVj0TxHkGWjGW4l8rYnyktW1AtGGcHiVXM/aAV6WAAPzYHdJF3RFO79aJnVaXEbW38etFy5A2I2Va5zyJwMduIFKK5yLCG30B9BtG8NpPzcTd4cq7UeFcSQX79Fw/ifpZvzj3b4nT/JmudVDfimLSAgO5Q5oSbCHVHkZEvFzWBtue0KinoGs/ykqLmXN+q4BZIGucYsU/CNBmrgWPoXHAJEmHr3GzVH6lvAmuve5Ye1xco89CPHouUAezHuliJ6+7yXJ3+AP0y3zH3AcdLRIvz7yGDXKCD/m+VZpo8eq0WM0BWHT8Zze15Kf6iMLS60vHRanutOiLumh+AWQDwDc0abtG6tYOPGw5lKcmou/HuDOXJUyQYeba2l/Y761kVzVLC8FluqZovu7WaM9Wzl/Ofr/H4aNOMWwALvWDsd6wn+Hzc+wwpiZiGL59anNOZMecgye6nMZMoIIx8b2h0tR5TJffX2tCDwlGAudTCCU8Tna/+IzWytS7zUdQEE5UBfwi7pAeIfu4P/KlYP4LLocEN5kM+xxas1xM/MIQxXbvhr4LBq8paHl/Ed2LzjxLnix1C+i0REkyX7CADvsw8uvxDk3VqAVOO2hVyFOmtmaqex/lDa0ga486OJWw+i9Ei4Cxb/c8sno2C20ABjiHnXbZVKJWV7bSvMqgq4VBcDyhH9s/OUVIz3sdZw7BFok2RzQ8GtGAXNmDrtqUT3zGo+4NeYucIMnZ4zamhdz+krS+aMuNEcth1xsnX0omN4COMtIkIQKuPrYDfi220KGFUP4sUJ3zxkzVENFiF+c4bh6aMZrh096sZx+Sf+ZNWm/8ZpuOEJOuhpcvaGsLmbN2FjuyJoa0ZcsUi7w0NpClJzVHnnaXrWOmaVGAeNRQ0YIQHiXmAmlX6ZqCwiWD1rNJHkDunhwRDerexExdy7qkORMKwHQOenyy+L6YUflT4rj8lw9exHA6MpPpFvLCv9rN31sDO26WzI1i4Iekz8WGyMgsoY4a8iSrNFbh59dku+NmVc/MrQ3LCgXQ2NZTZwmGwxfQfRxDnBVy8aMZga9OQQ372GWPJeYnGpOSeTMQOidT6khTEoraY32Cq9jqQpCuRdAOjPSBu3uufxORjZHBFbCetT7khHwfsqQlcXpsDfy06leNbPT2tXKlcGzmq1zElTZq0Vdlx9dOX3NwrJBMmYJ8hR6TJeTfMPABwg8OqU/RPDAsKfC6QziDt+iTkH1JFkobrG9x3C48ydzB3FZi/6ulPO558kpA3xkVFDx1V7yQyXu+8z96qvgrpig84wzCQbVIAr4P6dVyPBGrkc6Z/mElo2wTRRM4bYoGdkBFA0H4mMXSDUPc4QbgAafbFiI9aS/dV6cx4LQrpp/XwpyMlhT9ZFF0pj3/6mev44h2qq/P2fGS2B6ntZZXrdQ5a7q3AZ4bz+ggvOC3qJHsUl9MD158ABf29rSzUU2YcP3C1snKNrMw1aWCN+aT9tWzb0WztupAeHqEqGxiWEPxZNaQkU/BEqL8QkzhmV3xuqxQ9Jc72HDptQJthIPtrHnDzGoj7x3pu24W/PbHa8iDZz8dHf8U068M0QsopuOSY59TwDKUkwsBrHbgglos/2D57duWkq+xo36LK+uiKenvoEGqry7Vgz8xEMpQqvyY/9m1H3J/NLQCeE/si/o2bUPNaBYIO6acjqCk+JDObhL1RDJeeN1h602hQ0r5+FqEJDwwZxllYBM2bPPMZVD51yPm1GcbXHWA0JTKuJyLqk0XtLiUokHCqCezLm4Uwr44lS3nqNOMyyG0GdBItJms1X1ZPSR6pnIwbc4OF9fCWJQMN1BNRFpoOpFxvsPhAi6Y8MgHrKxBtR4xUEWVXJ1oJIDhDRtXsBgOUmi0kPWMZ7yCaql30OlAq/rSpkIm4wTQhMQO7kJrRzB8qmvWGzjjC85aMxbXMnOYu0xYlhoeqspnrqUXGJcgB+4o0w/olkbEKp0XNSEWcB8DRVhvsUaK2hCc+DpQeg4te0Hf3SPhGbl2aKeFBl3TnYmpMa+2H87QK4+9Vhs29Gsd7MYmSNWby36lOmc6Y7m1QWnWdn7srFzhLppumIWKWjRdcWjewW0zGaPjdX/cNik/oAAAgBANkBODfTinYNlvuuzT5FGsG1ZSu1YWgbrPw959qGRpuBgMUtFsf1PKe5UM76P9EbTNBMPCt4k+PFFwtpEtLZKeQ3Ieng+XPvXGhMISa5aV/7mB+/JGY0dd3F9Vux15sNqM8mrCniGjCps+lE6nkm6suQJB2SVnmfdM4UJ6FnR+4yDlmc6eZVyz1Qk8gh5ujz6/o/scwEp5VfUspj9u34TP7bSzp1CDjsI//3c3rgoaMwIiFH7SVenxI4c7a3e0Yxj+NRDuOruswTNwSmcSAvhiro0ZboALQRirwCLA/0JUckWYOYd1WM5H7+PQZAuyFHXe/hK61fP8pjFf3hcG7lLfLEk6gki+u91l0ZXrWb2AgMMHxNf3myUqK1SbIGm3q05JbXfCPPk7rra26gPKa48b9J81AIWrVbS5AK7Pe1Hp+mmZaGFBgBcZR/5sZxkb5BNeyipI71Vtq4EW1duBeVQ++Z+1wgIg/NDvW1JS1TrCvvwBqcZ02KWrD3XKtnfICoXhAUCeof+QbxM36GVwnF4OUnxhV/7+SOyl3xh+nGW/28Ir9400UPWIhu2B5CPuW8SUelpWJG3Mkn13yLwBC1bcHspi3lSTdS8nETarAiBZqq5l0ZftqaJ5pRWayPtWI0oq4XNoQrAEW3lqtUDOPUXO/d7hJuYTNOigs3o6bAjzsj4VhGp6Q92icjR3neeRtshN76cb2hX+Hang+WYgme1r6OGhsifr0uHwslVuMYHyUAWEaKTylz9MzY8lqz9+gtKXFy1AcII0KnCMIYggH2QFHC9hnlXyWNkshne/euNj4tI7cxzZNyHsJp6zxqmfLI+JvpM3pVBz/ANJ/cQMbRQsGEuqgiPOP2Pbje4KMdRLDAFI43F4U9Bkjd/3Qe/6oK7/ZrQ/nfxGpdX97z0Ek4kfxdHu3HLZeegVZgz5s1rgZfAqAMnXoc7UEZHtKYicwiWg5Suzwhsbb8H4z6maJt/6o8tVHbxqSqYBszIdciBGYebQXvJDCCjIclNdHY224ejeEIB6zNm4lcin7yLxW2cuxoYsNeWUT3oBt1x3cvAjQdx+839yIONUKbTmUyKrcrIRYIp2jqdQQx+UqeyhflSkbySNCNv1V2YSy4WkbukzjQ/w9CNhYm01kHAZDDd5nDm5tkrDZJxKxwwqHazukaLOk0FgjnYtTieMrATNFS9H61u0NdYdkgLfJ8ap9qhJZsZ3I+LJOJAuu4rP5YCUrgRaWjAzhDINhfucorSHOu/qXs5wwc7MnhxaeAkhGMqm2V/t5GDo1sl5LkH47ER4jG3h2l+KDlYcH2AGyQfV9CQSt/Tyq5z6beXhWCouJZp1HhFVyZEwKXsVYxReWjz5h3dvAlENY9QFI1yeSWLzuJYdvr+WPiYbWvr2zDhQK5s7YEcbVLDZTI51gjL6emvEr3mg5g2PHAkYl2lPx5xRxexcAL9uk8JUGUeJCulso2RSK/hFYM2dG7FW+RcROW2H9xtVHtDSVxbyX520BB4oh9aaMLK7PK4gA3fyKaQBEzxUaKbpdpsU8lu066DV7xQIYVOG4HRl1RCBJgjFm8D/XiSYLUsa2iuF64zthagWkeRCLyr+MQ8MThL5SP3ryTYqxOsFiLIJGsI7zEdMuaoq2BI6N0KqTlb2iVa+BgOcFPE0QGe50ICkHXy3jda/5h1oH/TjvS7DsWoAcMQFZt+XP5KJOCz33uvVQrVsDDyCoCk5Iyj2jWzSxyO8lhYrdGUezY41sWaHQM4bbqARRrnZFymA5Bl3kBxfkKvtXATbIcBtR8OET5VxUeUaUfjvka2hoFSTf8JyqNUb8/iNie3jr1alo5/rXL8QaC2X3mJ3liCuyen1EoQvQqzbGuHg238+gVznlGjlGIMBw1MgNuvzOziTZd8Oh0NtIwMn4FMcMk6sx3EbYIHvfVaSkceAylMf5zpMXymuNvZzXccBtwkzMGT4i3XazdC9a9tdd5SzAMKrjkaviM9+Z8gA2SQgLUR75gozqeh9QsuOnOZxmkOB+YVfnRUej53cm5e7fbUm4a6pv2+r7/Xpi9GCXIeX6Sfdk5jmr9jTQ++7f5WeAhPPgGJEHkP1NhAldK5NpnBo5nYRpvxrNkAhk1sHlDoptdplbXaMoMjSgqk4MrWN3WBHmqtJkGC9RJmj+N2QZMqaXTd1X/LOzP0skHbZ4r/OI4cCOFdRWlTDKrCXdLLtSW6OMTyWj94feWw0i6nwXGzgFbhos4Jsr5+WrYxo1pVat8k+b4j5acvUdpL543IRV3fNJgTyGgn/maw7skokyK2jFXGkHfaE2E4cYlX6qohFNTs3YJbBBvw7NcPmBtAGnvjb6UpJPlB3Fl/bmSwilO7knFd+8EV8SfmXhyF2Izvj2he9ncxd0P9Q1MhRSGmnfsULj6bT4nvzIr9l61GUaaEN6A55g6s8px1xmnyXVSZcW1rP1df2P4RhlgbfQ7Q9beZbO8CRdOFRzAjLjn87K4QDZK3EyzfGz9ZqcDYjfesByqAptLY9s0yzdNdfFS7RqC5v9MklMJLgOYXHBYPLNJzrKjvbaKYEacA3vNwRvFOTxKJ8lha9Ir1o8hu4urWUE6Mu3GGttCmFenF7jVE6Qf4Fgpt8OKSk4cVXPP/2w+vpeAki2hCBNDhpVmOWVsc0uvibEQjoFB62TYkUeSR1e9P2bjCVsXei526CLAogC497trRRTYlQiviNjUcB+26JshoF1nmwuw',\n- 16384,\n- 'MD5:0c:21:bb:98:84:43:4f:e8:62:27:fe:dc:2a:51:48:36',\n- 'SHA256:3j/qJWuiGWbNRvtN+HZTXC6VuRmNsDHrLA1F+Ow8gbg',\n- 'valid_dsa_16384',\n- [\"loose\"]],\n ['ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAIAGVQSlWHuzZCaZOdUFTZHeLCZFmqK729sGT2Ymc36zhyV1MK8oPcUqsqCWX8HOYODOBv80tdjsSH7kbm1UGcv8FgzJuCmhVslozru/SGsuRJWwjLIyHYKXx/KT3jHngzL1tQwdBk5uqZx9pekQ9xnvbXkUzucf7LZ/8MvTdQJPSqPX/3KdwUw3eiQoVGMSeKunukSAs9jbtlex8SN2ubqsuBEMtY7YUD4zLSWzkQ26L+dEhmYr1+WGVYD7t16vQT/3WZsqa6MWHF6q0OJTojsHWc0TILYmeI8jQJ2uR64TjgmsEug7egbgoK1oBZwhChzdemI0reJ66VS01OwJxpVKKXlHPZlnjMwF4jvWTCE6vwBG/BjVHFyVNZ987XAJLmoP5TY53cnoFykyKbfd6Knwm7hBXrdBz+ZVYzVoDPewfkkYYiKh490GiWKLuKN35th5DMglNrXgtdeHZDm4VwAXPsWwMs/FXyIhPmq5M27HqLb/e4ELkrIf5XGJM+tVaQxUfvQU4/TWGwTqgd3V5k5gGWR8ekmpVWWspcnrzM4aks2vxSLuDUQOnyLJ9RYjVfMePZ0uctN298+Zf1QTLewAnbvDC//kiZmgy+Yt7Go8Eg56CY1lFrWHZ/LQNf/0j8VGlTUPTg9uYWFNj3VGkTXSGEco7XSOPFQCkvkzoVaAxWeiNm7ECIUkIBusAOEqhhzJfpOirlgXxbrpK40NXJGvAPMo82HLA48WLBG7RcpzIIk/BDdhOBsM90crljGNmCs3Y4KbQX6CaxTUAUtRt8ydDP9V7qNkAsWgDp3uIOT8HjMP9K8PBTarwnZziGBx+ZlgqdYkxeOgXMiLhNKZl2VlmAeS9ojfK7azpCd+b0MuwvBfkvI1BtbJph/1gtyLTXv4JSUbZurZVES9xGh9Wf6fX5MroZhQ9SZry6xzOpCK7SlJJTwSQKLzNby0hLGBs7S6ew/DCFfAZEa1SJrubX+y4ogW4AcdSo6wKW6XdlCXivT8bvSdQRAbU+eVWDAdbi8fvq5BQuxEU+qtoxX+eZHF3PFVJWoPlGtKanEHJa/LyAXtrRVFKh79HlK/0PgGurS4Eco2ZHOuFz48yTrxPQMrhetfwCU8yRed6Ocrw0yJ2P/QtSw4+/EPWT3eyTL/8EN/ZY/6mOAPWksScZjgwM/a+BpaZsM2IS0SUPRaFmyr2QaAgqM34B2muukx4J1nrGzNgdwGXwgHeTtHekRLTUTKpr0ZVMhNoz/Nu/1ypwr/oSN5mnn9JuFKzTnsPVhjgEpywPSYppJFltJfxo82Ya2bi/CdYfGD9+KPR3gdppjx6eUPgimvgYS5zr+HmINMZEba84+Zi2JNdTjiOSfHGdb/RvnY/4FX7sB2/rCzaRlIpM5kUlM8EvzvSAN2l6Gn2Kjau2e5hZKwVxIq8bUmwKkCw2bq3hlHWsnCClp9kIWtnV8xGKvd9dBEryEMDWM2DDjJenxGPifrOHgfwEbfHKWkQu1JfxEhmNpjtppkzooVkgs5Pcq9dlOjoDZziEGAiAeXRFDqvoP0hOViHYrV/I0SlIfZ+p9YxLNJo/6FNI3d+ifTzYB7GyCrqI+cR83qesi+XIaTBZXsVxGYFG1+fADy5DLhdeaHDx6638kPHTxUoZhHMYs443cJZTjsg8F7LH5diN69kh4IxEo0t6RpvaQx0gb/03N5jjyY7rNVy6QYAeS7b116IO68lzWwnOhWdDbgjMKC9Il0wtKEhlGirYum1gBC6cqR9SDOTwCtXsNwDllxU0VvLJu8Fwk/KAaxZwT6ZwIJQPD9LtXcpFsiZGX4mOW2n+AMachk6gKve0ZH0BNDQzcShSdIgWl2bOxd0R1XcDDCbcd0oQHhECrNe8Nx64ObhW38U2WOg8QYCGLVsys/afkKkado4Kw6zDOA0baROXNPup6gWesEgEfKsMqkcIYu9tEbB2JoCRwFgZorDP0VroJphscWYpVXNlMtavP/DgU6yiOVFZtg5HaBat1DREQzvrk8fLxd+jOAo6CwSXsQDC9ebXKFEXjlCD2igQUtFqV7Wz8HEyl6hA5shBWUSgdVKIsspRC9PeksJrlCPzx/5d9whBZzr8uaFaM7f20nhAgzIki7XSKlN0/a/nw8WUlQMbMx98n5LY0whtmj429k8zAI8jEIrVyCQjzEss2FKIuw836acH+XF/e501UGlIAoFvj4/OBKfx/+L68ujo7PUDPcuFlu8mZ2I6tohHKriJYeZcRryeT/zXpQs28AN1QWDfFDNSQGFkrUoLuMUYSjMx0ftb6LDw/Ilaz3/zJzz4PtECutPgKtrtqYxYyDVHbyn6fBiECtHnSXd3b9dp3iFI4t8VBFOEIcX01Mdgjvum5Pb6KxJf58pcUBQUeI+Bg1aHR+ojh5ZeqEYFr2ojdSD/0WehwUPF8IGCPVCaTKksh2yPyR174LDD05UoWvm8hc1CLhuuASq6xPrAXhcZlEl7zTJXWKD356j9OvLItEFQqolsIhS2m/W8pWzCPtY9je3bWyB+vzN3BquSuLoriIcZrF7FL7f+ZVGQDmNhIKGalojIOlzyRIHXKEV89gQHU88lWWAEc0MNP80Ag0/avrp35myUbWoP4Elkm3UjUvZHWOiWCDABEoaGlnexVgtQctJ42ZnQIztGp+hvgmezJWtqKrtfiIW6G2N+3O2pLoDubejswrG9k7OhtK358XF1YOxzIGyFPTvEODhe0Zv9 ojarva@ojar-laptop.local',\n 16383,\n 'MD5:b6:ff:d9:90:61:a7:73:77:49:cc:b1:41:ca:c1:3b:a5',\n", "problem_statement": "", "hints_text": "", "created_at": "2018-02-21T20:06:04Z"} diff --git a/PythonDataset/test/quality-time-task-instances.jsonl.all b/PythonDataset/test/quality-time-task-instances.jsonl.all new file mode 100644 index 0000000000000000000000000000000000000000..adcd5e74eb6a819d1c078541bc533a31022b718e --- /dev/null +++ b/PythonDataset/test/quality-time-task-instances.jsonl.all @@ -0,0 +1 @@ +{"repo": "ICTU/quality-time", "pull_number": 1102, "instance_id": "ICTU__quality-time-1102", "issue_numbers": "", "base_commit": "6df08864df270b6956cc78502aa3d9c0446038d5", "patch": "diff --git a/components/collector/src/base_collectors/__init__.py b/components/collector/src/base_collectors/__init__.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/__init__.py\n@@ -0,0 +1,8 @@\n+\"\"\"Metric collectors.\"\"\"\n+\n+from .api_source_collector import JenkinsPluginSourceUpToDatenessCollector\n+from .file_source_collector import CSVFileSourceCollector, HTMLFileSourceCollector, JSONFileSourceCollector, \\\n+ XMLFileSourceCollector\n+from .metrics_collector import MetricsCollector\n+from .source_collector import SourceCollector, LocalSourceCollector, UnmergedBranchesSourceCollector, \\\n+ SourceUpToDatenessCollector\ndiff --git a/components/collector/src/base_collectors/api_source_collector.py b/components/collector/src/base_collectors/api_source_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/api_source_collector.py\n@@ -0,0 +1,16 @@\n+\"\"\"API source collector base classes.\"\"\"\n+\n+from datetime import datetime\n+\n+from collector_utilities.type import Response, URL\n+from .source_collector import SourceUpToDatenessCollector\n+\n+\n+class JenkinsPluginSourceUpToDatenessCollector(SourceUpToDatenessCollector):\n+ \"\"\"Base class for Jenkins plugin source up-to-dateness collectors.\"\"\"\n+\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/api/json\")\n+\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return datetime.fromtimestamp(float((await response.json())[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/base_collectors/cached_client_session.py b/components/collector/src/base_collectors/cached_client_session.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/cached_client_session.py\n@@ -0,0 +1,29 @@\n+\"\"\"Cached client session.\"\"\"\n+\n+import asyncio\n+from typing import Any, cast\n+\n+import aiohttp\n+from aiohttp.client import _RequestContextManager\n+from aiohttp.typedefs import StrOrURL\n+\n+\n+class CachedClientSession(aiohttp.ClientSession):\n+ \"\"\"Cached version of client session.\"\"\"\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ # We don't need a fancy cache with time-to-live or a max size because a new session is created every time the\n+ # collector wakes up (once every minute by default).\n+ self.__cache = dict()\n+\n+ async def get( # type: ignore\n+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any) -> '_RequestContextManager':\n+ \"\"\"Retrieve the url, using a cache.\"\"\"\n+ if url in self.__cache:\n+ if isinstance(self.__cache[url], asyncio.Event):\n+ await self.__cache[url].wait() # URL is being retrieved, wait for it\n+ else:\n+ event = self.__cache[url] = asyncio.Event() # Make other callers wait until the URL is retrieved\n+ self.__cache[url] = await super().get(url, allow_redirects=allow_redirects, **kwargs)\n+ event.set() # Signal other callers the URL has been retrieved\n+ return cast(_RequestContextManager, self.__cache[url])\ndiff --git a/components/collector/src/base_collectors/file_source_collector.py b/components/collector/src/base_collectors/file_source_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/file_source_collector.py\n@@ -0,0 +1,64 @@\n+\"\"\"File source collector base classes.\"\"\"\n+\n+import asyncio\n+import io\n+import itertools\n+import zipfile\n+from abc import ABC\n+from typing import cast, Dict, List\n+\n+from collector_utilities.type import Response, Responses, URL\n+from .source_collector import FakeResponse, SourceCollector\n+\n+\n+class FileSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve files.\"\"\"\n+\n+ file_extensions: List[str] = [] # Subclass responsibility\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ responses = await super()._get_source_responses(*urls)\n+ if not urls[0].endswith(\".zip\"):\n+ return responses\n+ unzipped_responses = await asyncio.gather(*[self.__unzip(response) for response in responses])\n+ return list(itertools.chain(*unzipped_responses))\n+\n+ def _headers(self) -> Dict[str, str]:\n+ headers = super()._headers()\n+ if token := cast(str, self._parameter(\"private_token\")):\n+ # GitLab needs this header, see\n+ # https://docs.gitlab.com/ee/api/jobs.html#download-a-single-artifact-file-by-job-id\n+ headers[\"Private-Token\"] = token\n+ return headers\n+\n+ @classmethod\n+ async def __unzip(cls, response: Response) -> Responses:\n+ \"\"\"Unzip the response content and return a (new) response for each applicable file in the zip archive.\"\"\"\n+ with zipfile.ZipFile(io.BytesIO(await response.read())) as response_zipfile:\n+ names = [name for name in response_zipfile.namelist() if name.split(\".\")[-1].lower() in cls.file_extensions]\n+ responses = [FakeResponse(response_zipfile.read(name)) for name in names]\n+ return cast(Responses, responses)\n+\n+\n+class CSVFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve CSV files.\"\"\"\n+\n+ file_extensions = [\"csv\"]\n+\n+\n+class HTMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve HTML files.\"\"\"\n+\n+ file_extensions = [\"html\", \"htm\"]\n+\n+\n+class JSONFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve JSON files.\"\"\"\n+\n+ file_extensions = [\"json\"]\n+\n+\n+class XMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve XML files.\"\"\"\n+\n+ file_extensions = [\"xml\"]\ndiff --git a/components/collector/src/base_collectors/metrics_collector.py b/components/collector/src/base_collectors/metrics_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/metrics_collector.py\n@@ -0,0 +1,136 @@\n+\"\"\"Metrics collector.\"\"\"\n+\n+from datetime import datetime, timedelta\n+import asyncio\n+import logging\n+import os\n+import traceback\n+from typing import cast, Any, Dict, Final, NoReturn\n+\n+import aiohttp\n+\n+from collector_utilities.functions import timer\n+from collector_utilities.type import JSON, URL\n+from .cached_client_session import CachedClientSession\n+from .source_collector import SourceCollector\n+\n+\n+async def get(session: aiohttp.ClientSession, api: URL) -> JSON:\n+ \"\"\"Get data from the API url.\"\"\"\n+ try:\n+ response = await session.get(api)\n+ return cast(JSON, await response.json())\n+ except Exception as reason: # pylint: disable=broad-except\n+ logging.error(\"Getting data from %s failed: %s\", api, reason)\n+ logging.error(traceback.format_exc())\n+ return {}\n+\n+\n+async def post(session: aiohttp.ClientSession, api: URL, data) -> None:\n+ \"\"\"Post the JSON data to the api url.\"\"\"\n+ try:\n+ await session.post(api, json=data)\n+ except Exception as reason: # pylint: disable=broad-except\n+ logging.error(\"Posting %s to %s failed: %s\", data, api, reason)\n+ logging.error(traceback.format_exc())\n+\n+\n+class MetricsCollector:\n+ \"\"\"Collect measurements for all metrics.\"\"\"\n+ def __init__(self) -> None:\n+ self.server_url: Final[URL] = \\\n+ URL(f\"http://{os.environ.get('SERVER_HOST', 'localhost')}:{os.environ.get('SERVER_PORT', '5001')}\")\n+ self.data_model: JSON = dict()\n+ self.next_fetch: Dict[str, datetime] = dict()\n+ self.last_parameters: Dict[str, Any] = dict()\n+\n+ @staticmethod\n+ def record_health(filename: str = \"/tmp/health_check.txt\") -> None:\n+ \"\"\"Record the current date and time in a file to allow for health checks.\"\"\"\n+ try:\n+ with open(filename, \"w\") as health_check:\n+ health_check.write(datetime.now().isoformat())\n+ except OSError as reason:\n+ logging.error(\"Could not write health check time stamp to %s: %s\", filename, reason)\n+\n+ async def start(self) -> NoReturn:\n+ \"\"\"Start fetching measurements indefinitely.\"\"\"\n+ max_sleep_duration = int(os.environ.get(\"COLLECTOR_SLEEP_DURATION\", 60))\n+ measurement_frequency = int(os.environ.get(\"COLLECTOR_MEASUREMENT_FREQUENCY\", 15 * 60))\n+ timeout = aiohttp.ClientTimeout(total=120)\n+ async with CachedClientSession(timeout=timeout, raise_for_status=True) as session:\n+ self.data_model = await self.fetch_data_model(session, max_sleep_duration)\n+ while True:\n+ self.record_health()\n+ logging.info(\"Collecting...\")\n+ async with CachedClientSession(\n+ timeout=timeout, connector=aiohttp.TCPConnector(limit_per_host=20),\n+ raise_for_status=True) as session:\n+ with timer() as collection_timer:\n+ await self.collect_metrics(session, measurement_frequency)\n+ sleep_duration = max(0, max_sleep_duration - collection_timer.duration)\n+ logging.info(\n+ \"Collecting took %.1f seconds. Sleeping %.1f seconds...\", collection_timer.duration, sleep_duration)\n+ await asyncio.sleep(sleep_duration)\n+\n+ async def fetch_data_model(self, session: aiohttp.ClientSession, sleep_duration: int) -> JSON:\n+ \"\"\"Fetch the data model.\"\"\"\n+ while True:\n+ self.record_health()\n+ logging.info(\"Loading data model...\")\n+ if data_model := await get(session, URL(f\"{self.server_url}/api/v2/datamodel\")):\n+ return data_model\n+ logging.warning(\"Loading data model failed, trying again in %ss...\", sleep_duration)\n+ await asyncio.sleep(sleep_duration)\n+\n+ async def collect_metrics(self, session: aiohttp.ClientSession, measurement_frequency: int) -> None:\n+ \"\"\"Collect measurements for all metrics.\"\"\"\n+ metrics = await get(session, URL(f\"{self.server_url}/api/v2/metrics\"))\n+ next_fetch = datetime.now() + timedelta(seconds=measurement_frequency)\n+ tasks = [self.collect_metric(session, metric_uuid, metric, next_fetch)\n+ for metric_uuid, metric in metrics.items() if self.__can_and_should_collect(metric_uuid, metric)]\n+ await asyncio.gather(*tasks)\n+\n+ async def collect_metric(\n+ self, session: aiohttp.ClientSession, metric_uuid, metric, next_fetch: datetime) -> None:\n+ \"\"\"Collect measurements for the metric and post it to the server.\"\"\"\n+ self.last_parameters[metric_uuid] = metric\n+ self.next_fetch[metric_uuid] = next_fetch\n+ measurement = await self.collect_sources(session, metric)\n+ measurement[\"metric_uuid\"] = metric_uuid\n+ await post(session, URL(f\"{self.server_url}/api/v2/measurements\"), measurement)\n+\n+ async def collect_sources(self, session: aiohttp.ClientSession, metric):\n+ \"\"\"Collect the measurements from the metric's sources.\"\"\"\n+ collectors = []\n+ for source in metric[\"sources\"].values():\n+ collector_class = SourceCollector.get_subclass(source[\"type\"], metric[\"type\"])\n+ collectors.append(collector_class(session, source, self.data_model).get())\n+ measurements = await asyncio.gather(*collectors)\n+ for measurement, source_uuid in zip(measurements, metric[\"sources\"]):\n+ measurement[\"source_uuid\"] = source_uuid\n+ return dict(sources=measurements)\n+\n+ def __can_and_should_collect(self, metric_uuid: str, metric) -> bool:\n+ \"\"\"Return whether the metric can and needs to be measured.\"\"\"\n+ if not self.__can_collect(metric):\n+ return False\n+ return self.__should_collect(metric_uuid, metric)\n+\n+ def __can_collect(self, metric) -> bool:\n+ \"\"\"Return whether the user has specified all mandatory parameters for all sources.\"\"\"\n+ sources = metric.get(\"sources\")\n+ for source in sources.values():\n+ parameters = self.data_model.get(\"sources\", {}).get(source[\"type\"], {}).get(\"parameters\", {})\n+ for parameter_key, parameter in parameters.items():\n+ if parameter.get(\"mandatory\") and metric[\"type\"] in parameter.get(\"metrics\") and \\\n+ not source.get(\"parameters\", {}).get(parameter_key):\n+ return False\n+ return bool(sources)\n+\n+ def __should_collect(self, metric_uuid: str, metric) -> bool:\n+ \"\"\"Return whether the metric should be collected, either because the user changed the configuration or because\n+ it has been collected too long ago.\"\"\"\n+ if self.last_parameters.get(metric_uuid) != metric:\n+ return True\n+ return self.next_fetch.get(metric_uuid, datetime.min) <= datetime.now()\ndiff --git a/components/collector/src/source_collectors/source_collector.py b/components/collector/src/base_collectors/source_collector.py\nsimilarity index 60%\nrename from components/collector/src/source_collectors/source_collector.py\nrename to components/collector/src/base_collectors/source_collector.py\n--- a/components/collector/src/source_collectors/source_collector.py\n+++ b/components/collector/src/base_collectors/source_collector.py\n@@ -1,32 +1,32 @@\n \"\"\"Source collector base classes.\"\"\"\n \n-import io\n+import asyncio\n+import json\n import logging\n import traceback\n import urllib\n-import zipfile\n from abc import ABC, abstractmethod\n from datetime import datetime\n from http import HTTPStatus\n-from typing import cast, Dict, Final, List, Optional, Set, Tuple, Type, Union\n+from typing import cast, Any, Dict, Final, List, Optional, Set, Tuple, Type, Union\n \n-import requests\n+import aiohttp\n \n from collector_utilities.functions import days_ago, tokenless, stable_traceback\n-from collector_utilities.type import ErrorMessage, Entities, Measurement, Response, Responses, URL, Value\n+from collector_utilities.type import ErrorMessage, Entities, JSON, Measurement, Response, Responses, URL, Value\n \n \n class SourceCollector(ABC):\n \"\"\"Base class for source collectors. Source collectors are subclasses of this class that know how to collect the\n measurement data for one specific metric from one specific source.\"\"\"\n \n- TIMEOUT = 10 # Default timeout of 10 seconds\n MAX_ENTITIES = 100 # The maximum number of entities (e.g. violations, warnings) to send to the server\n API_URL_PARAMETER_KEY = \"url\"\n source_type = \"\" # The source type is set on the subclass, when the subclass is registered\n subclasses: Set[Type[\"SourceCollector\"]] = set()\n \n- def __init__(self, source, datamodel) -> None:\n+ def __init__(self, session: aiohttp.ClientSession, source, datamodel) -> None:\n+ self._session = session\n self._datamodel: Final = datamodel\n self.__parameters: Final[Dict[str, Union[str, List[str]]]] = source.get(\"parameters\", {})\n \n@@ -45,30 +45,22 @@ def get_subclass(cls, source_type: str, metric_type: str) -> Type[\"SourceCollect\n return matching_subclasses[0]\n raise LookupError(f\"Couldn't find collector subclass for source {source_type} and metric {metric_type}\")\n \n- def get(self) -> Measurement:\n+ async def get(self) -> Measurement:\n \"\"\"Return the measurement from this source.\"\"\"\n- responses, api_url, connection_error = self.__safely_get_source_responses()\n- value, total, entities, parse_error = self.__safely_parse_source_responses(responses)\n- landing_url = self._landing_url(responses)\n+ responses, api_url, connection_error = await self.__safely_get_source_responses()\n+ value, total, entities, parse_error = await self.__safely_parse_source_responses(responses)\n+ landing_url = await self.__safely_parse_landing_url(responses)\n return dict(api_url=api_url, landing_url=landing_url, value=value, total=total, entities=entities,\n connection_error=connection_error, parse_error=parse_error)\n \n- def _landing_url(self, responses: Responses) -> URL: # pylint: disable=unused-argument\n- \"\"\"Return the user supplied landing url parameter if there is one, otherwise translate the url parameter into\n- a default landing url.\"\"\"\n- if landing_url := cast(str, self.__parameters.get(\"landing_url\", \"\")).rstrip(\"/\"):\n- return URL(landing_url)\n- url = cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\")\n- return URL(url[:-(len(\"xml\"))] + \"html\" if url.endswith(\".xml\") else url)\n-\n- def _api_url(self) -> URL:\n+ async def _api_url(self) -> URL:\n \"\"\"Translate the url parameter into the API url.\"\"\"\n return URL(cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\"))\n \n def _parameter(self, parameter_key: str, quote: bool = False) -> Union[str, List[str]]:\n \"\"\"Return the parameter value.\"\"\"\n \n- def quote_if_needed(parameter_value):\n+ def quote_if_needed(parameter_value: str) -> str:\n \"\"\"Quote the string if needed.\"\"\"\n return urllib.parse.quote(parameter_value, safe=\"\") if quote else parameter_value\n \n@@ -84,30 +76,30 @@ def quote_if_needed(parameter_value):\n value = cast(str, value).rstrip(\"/\")\n return quote_if_needed(value) if isinstance(value, str) else [quote_if_needed(v) for v in value]\n \n- def __safely_get_source_responses(self) -> Tuple[Responses, URL, ErrorMessage]:\n+ async def __safely_get_source_responses(self) -> Tuple[Responses, URL, ErrorMessage]:\n \"\"\"Connect to the source and get the data, without failing. This method should not be overridden\n because it makes sure the collection of source data never causes the collector to fail.\"\"\"\n responses: Responses = []\n api_url = URL(\"\")\n error = None\n try:\n- responses = self._get_source_responses(api_url := self._api_url())\n- for response in responses:\n- response.raise_for_status()\n+ responses = await self._get_source_responses(api_url := await self._api_url())\n logging.info(\"Retrieved %s\", tokenless(api_url) or self.__class__.__name__)\n except Exception as reason: # pylint: disable=broad-except\n error = stable_traceback(traceback.format_exc())\n logging.warning(\"Failed to retrieve %s: %s\", tokenless(api_url) or self.__class__.__name__, reason)\n return responses, api_url, error\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Open the url. Can be overridden if a post request is needed or multiple requests need to be made.\"\"\"\n- return [\n- requests.get(api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials(), headers=self._headers())]\n-\n- def _headers(self) -> Dict[str, str]: # pylint: disable=no-self-use\n- \"\"\"Return the headers for the request.\"\"\"\n- return dict()\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Open the url. Can be overridden if a post request is needed or serial requests need to be made.\"\"\"\n+ kwargs: Dict[str, Any] = dict()\n+ credentials = self._basic_auth_credentials()\n+ if credentials is not None:\n+ kwargs[\"auth\"] = aiohttp.BasicAuth(credentials[0], credentials[1])\n+ if headers := self._headers():\n+ kwargs[\"headers\"] = headers\n+ tasks = [self._session.get(url, **kwargs) for url in urls]\n+ return list(await asyncio.gather(*tasks))\n \n def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n \"\"\"Return the basic authentication credentials, if any.\"\"\"\n@@ -117,7 +109,11 @@ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n password = cast(str, self.__parameters.get(\"password\", \"\"))\n return (username, password) if username and password else None\n \n- def __safely_parse_source_responses(\n+ def _headers(self) -> Dict[str, str]: # pylint: disable=no-self-use\n+ \"\"\"Return the headers for the get request.\"\"\"\n+ return {}\n+\n+ async def __safely_parse_source_responses(\n self, responses: Responses) -> Tuple[Value, Value, Entities, ErrorMessage]:\n \"\"\"Parse the data from the responses, without failing. This method should not be overridden because it\n makes sure that the parsing of source data never causes the collector to fail.\"\"\"\n@@ -125,95 +121,72 @@ def __safely_parse_source_responses(\n value, total, error = None, None, None\n if responses:\n try:\n- value, total, entities = self._parse_source_responses(responses)\n+ value, total, entities = await self._parse_source_responses(responses)\n except Exception: # pylint: disable=broad-except\n error = stable_traceback(traceback.format_exc())\n return value, total, entities[:self.MAX_ENTITIES], error\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n \"\"\"Parse the responses to get the measurement value, the total value, and the entities for the metric.\n This method can be overridden by collectors to parse the retrieved sources data.\"\"\"\n # pylint: disable=assignment-from-none,no-self-use,unused-argument\n return None, \"100\", [] # pragma nocover\n \n+ async def __safely_parse_landing_url(self, responses: Responses) -> URL:\n+ \"\"\"Parse the responses to get the landing url, without failing. This method should not be overridden because\n+ it makes sure that the parsing of source data never causes the collector to fail.\"\"\"\n+ try:\n+ return await self._landing_url(responses)\n+ except Exception: # pylint: disable=broad-except\n+ return await self._api_url()\n \n-class FileSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve files.\"\"\"\n-\n- file_extensions: List[str] = [] # Subclass responsibility\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- if not api_url.endswith(\".zip\"):\n- return responses\n- unzipped_responses = []\n- for response in responses:\n- unzipped_responses.extend(self.__unzip(response))\n- return unzipped_responses\n-\n- def _headers(self) -> Dict[str, str]:\n- headers = super()._headers()\n- if token := cast(str, self._parameter(\"private_token\")):\n- # GitLab needs this header, see\n- # https://docs.gitlab.com/ee/api/jobs.html#download-a-single-artifact-file-by-job-id\n- headers[\"Private-Token\"] = token\n- return headers\n-\n- @classmethod\n- def __unzip(cls, response: Response) -> Responses:\n- \"\"\"Unzip the response content and return a (new) response for each applicable file in the zip archive.\"\"\"\n- responses = []\n- with zipfile.ZipFile(io.BytesIO(response.content)) as response_zipfile:\n- names = [name for name in response_zipfile.namelist() if name.split(\".\")[-1].lower() in cls.file_extensions]\n- for name in names:\n- unzipped_response = requests.Response()\n- unzipped_response.raw = io.BytesIO(response_zipfile.read(name))\n- unzipped_response.status_code = HTTPStatus.OK\n- responses.append(unzipped_response)\n- return responses\n-\n-\n-class HTMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve HTML files.\"\"\"\n-\n- file_extensions = [\"html\", \"htm\"]\n-\n+ async def _landing_url(self, responses: Responses) -> URL: # pylint: disable=unused-argument\n+ \"\"\"Return the user supplied landing url parameter if there is one, otherwise translate the url parameter into\n+ a default landing url.\"\"\"\n+ if landing_url := cast(str, self.__parameters.get(\"landing_url\", \"\")).rstrip(\"/\"):\n+ return URL(landing_url)\n+ url = cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\")\n+ return URL(url[:-(len(\"xml\"))] + \"html\" if url.endswith(\".xml\") else url)\n \n-class JSONFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve JSON files.\"\"\"\n \n- file_extensions = [\"json\"]\n+class FakeResponse: # pylint: disable=too-few-public-methods\n+ \"\"\"Fake a response because aiohttp.ClientResponse can not easily be instantiated directly. \"\"\"\n+ status = HTTPStatus.OK\n \n+ def __init__(self, contents: bytes = bytes()) -> None:\n+ super().__init__()\n+ self.contents = contents\n \n-class XMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve XML files.\"\"\"\n+ async def json(self) -> JSON:\n+ \"\"\"Return the JSON version of the contents.\"\"\"\n+ return cast(JSON, json.loads(self.contents))\n \n- file_extensions = [\"xml\"]\n+ async def text(self) -> str:\n+ \"\"\"Return the text version of the contents.\"\"\"\n+ return str(self.contents.decode())\n \n \n class LocalSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for source collectors that do not need to access the network but return static or user-supplied\n data.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- fake_response = requests.Response()\n- fake_response.status_code = HTTPStatus.OK\n- return [fake_response] # Return a fake response so that the parse methods will be called\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ return [cast(Response, FakeResponse())] # Return a fake response so that the parse methods will be called\n \n \n class UnmergedBranchesSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for unmerged branches source collectors.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = [\n dict(key=branch[\"name\"], name=branch[\"name\"], commit_age=str(days_ago(self._commit_datetime(branch))),\n commit_date=str(self._commit_datetime(branch).date()))\n- for branch in self._unmerged_branches(responses)]\n+ for branch in await self._unmerged_branches(responses)]\n return str(len(entities)), \"100\", entities\n \n @abstractmethod\n- def _unmerged_branches(self, responses: Responses) -> List:\n- \"\"\"Return the list of unmerged branch.\"\"\"\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ \"\"\"Return the list of unmerged branches.\"\"\"\n \n @abstractmethod\n def _commit_datetime(self, branch) -> datetime:\n@@ -223,9 +196,10 @@ def _commit_datetime(self, branch) -> datetime:\n class SourceUpToDatenessCollector(SourceCollector):\n \"\"\"Base class for source up-to-dateness collectors.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- return str(days_ago(min(self._parse_source_response_date_time(response) for response in responses))), \"100\", []\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ date_times = await asyncio.gather(*[self._parse_source_response_date_time(response) for response in responses])\n+ return str(days_ago(min(date_times))), \"100\", []\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n \"\"\"Parse the date time from the source.\"\"\"\n raise NotImplementedError # pragma: nocover\ndiff --git a/components/collector/src/collector_utilities/functions.py b/components/collector/src/collector_utilities/functions.py\n--- a/components/collector/src/collector_utilities/functions.py\n+++ b/components/collector/src/collector_utilities/functions.py\n@@ -4,8 +4,8 @@\n import hashlib\n import re\n import urllib\n-from datetime import datetime, timedelta\n-from typing import cast, Collection, Pattern, Tuple\n+from datetime import datetime\n+from typing import cast, Collection, Generator, Pattern, Tuple\n from xml.etree.ElementTree import Element # nosec, Element is not available from defusedxml, but only used as type\n \n from defusedxml import ElementTree\n@@ -13,24 +13,24 @@\n from .type import Namespaces, Response, URL\n \n \n-def parse_source_response_xml(response: Response, allowed_root_tags: Collection[str] = None) -> Element:\n+async def parse_source_response_xml(response: Response, allowed_root_tags: Collection[str] = None) -> Element:\n \"\"\"Parse the XML from the source response.\"\"\"\n- tree = cast(Element, ElementTree.fromstring(response.text))\n+ tree = cast(Element, ElementTree.fromstring(await response.text()))\n if allowed_root_tags and tree.tag not in allowed_root_tags:\n raise AssertionError(f'The XML root element should be one of \"{allowed_root_tags}\" but is \"{tree.tag}\"')\n return tree\n \n \n-def parse_source_response_xml_with_namespace(\n+async def parse_source_response_xml_with_namespace(\n response: Response, allowed_root_tags: Collection[str] = None) -> Tuple[Element, Namespaces]:\n \"\"\"Parse the XML with namespace from the source response.\"\"\"\n- tree = parse_source_response_xml(response, allowed_root_tags)\n+ tree = await parse_source_response_xml(response, allowed_root_tags)\n # ElementTree has no API to get the namespace so we extract it from the root tag:\n namespaces = dict(ns=tree.tag.split('}')[0][1:])\n return tree, namespaces\n \n \n-Substitution = Tuple[Pattern, str]\n+Substitution = Tuple[Pattern[str], str]\n MEMORY_ADDRESS_SUB: Substitution = (re.compile(r\" at 0x[0-9abcdef]+>\"), \">\")\n TOKEN_SUB: Substitution = (re.compile(r\"token=[0-9a-zA-Z]+\"), \"token=\")\n KEY_SUB: Substitution = (re.compile(r\"key=[0-9abcdef]+\"), \"key=\")\n@@ -92,17 +92,17 @@ def match_string_or_regular_expression(string: str, strings_and_or_regular_expre\n \n class Clock: # pylint: disable=too-few-public-methods\n \"\"\"Class to keep track of time.\"\"\"\n- def __init__(self):\n+ def __init__(self) -> None:\n self.start = datetime.now()\n- self.duration = timedelta()\n+ self.duration = 0.0\n \n- def stop(self):\n+ def stop(self) -> None:\n \"\"\"Stop the clock.\"\"\"\n self.duration = (datetime.now() - self.start).total_seconds()\n \n \n @contextlib.contextmanager\n-def timer():\n+def timer() -> Generator[Clock, None, None]:\n \"\"\"Timer context manager.\"\"\"\n clock = Clock()\n yield clock\ndiff --git a/components/collector/src/collector_utilities/type.py b/components/collector/src/collector_utilities/type.py\n--- a/components/collector/src/collector_utilities/type.py\n+++ b/components/collector/src/collector_utilities/type.py\n@@ -2,7 +2,8 @@\n \n from typing import Any, Dict, List, NewType, Optional, Union\n \n-import requests\n+import aiohttp\n+\n \n Entity = Dict[str, Union[int, float, str]] # pylint: disable=invalid-name\n Entities = List[Entity]\n@@ -12,7 +13,7 @@\n JSON = Dict[str, Any]\n Namespaces = Dict[str, str] # Namespace prefix to Namespace URI mapping\n Measurement = Dict[str, Any]\n-Response = requests.Response\n+Response = aiohttp.ClientResponse\n Responses = List[Response]\n URL = NewType(\"URL\", str)\n Value = Optional[str]\ndiff --git a/components/collector/src/metric_collectors/__init__.py b/components/collector/src/metric_collectors/__init__.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/__init__.py\n+++ /dev/null\n@@ -1,4 +0,0 @@\n-\"\"\"Metric collectors.\"\"\"\n-\n-from .metric_collector import MetricCollector\n-from .metrics_collector import MetricsCollector\ndiff --git a/components/collector/src/metric_collectors/metric_collector.py b/components/collector/src/metric_collectors/metric_collector.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/metric_collector.py\n+++ /dev/null\n@@ -1,33 +0,0 @@\n-\"\"\"Collector base class.\"\"\"\n-\n-from typing import Dict, Final\n-\n-from source_collectors.source_collector import SourceCollector\n-from collector_utilities.type import Measurement\n-\n-\n-class MetricCollector:\n- \"\"\"Base class for collecting measurements from multiple sources for a metric.\"\"\"\n-\n- def __init__(self, metric, datamodel=None) -> None:\n- self.metric: Final = metric\n- self.datamodel: Final = datamodel\n- self.collectors: Dict[str, SourceCollector] = dict()\n- for source_uuid, source in self.metric[\"sources\"].items():\n- collector_class = SourceCollector.get_subclass(source['type'], self.metric['type'])\n- self.collectors[source_uuid] = collector_class(source, datamodel)\n-\n- def can_collect(self) -> bool:\n- \"\"\"Return whether the user has specified all mandatory parameters for all sources.\"\"\"\n- sources = self.metric.get(\"sources\")\n- for source in sources.values():\n- parameters = self.datamodel.get(\"sources\", {}).get(source[\"type\"], {}).get(\"parameters\", {})\n- for parameter_key, parameter in parameters.items():\n- if parameter.get(\"mandatory\") and self.metric[\"type\"] in parameter.get(\"metrics\") and \\\n- not source.get(\"parameters\", {}).get(parameter_key):\n- return False\n- return bool(sources)\n-\n- def get(self) -> Measurement:\n- \"\"\"Connect to the sources to get and parse the measurements for the metric.\"\"\"\n- return dict(sources=[{**self.collectors[uuid].get(), \"source_uuid\": uuid} for uuid in self.metric[\"sources\"]])\ndiff --git a/components/collector/src/metric_collectors/metrics_collector.py b/components/collector/src/metric_collectors/metrics_collector.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/metrics_collector.py\n+++ /dev/null\n@@ -1,94 +0,0 @@\n-\"\"\"Metrics collector.\"\"\"\n-\n-from datetime import datetime, timedelta\n-import logging\n-import os\n-import time\n-from typing import cast, Any, Dict, Final, NoReturn\n-\n-import requests\n-\n-from collector_utilities.functions import timer\n-from collector_utilities.type import JSON, URL\n-from .metric_collector import MetricCollector\n-\n-\n-def get(api: URL) -> JSON:\n- \"\"\"Get data from the API url.\"\"\"\n- try:\n- return cast(JSON, requests.get(api).json())\n- except Exception as reason: # pylint: disable=broad-except\n- logging.error(\"Getting data from %s failed: %s\", api, reason)\n- return {}\n-\n-\n-def post(api: URL, data) -> None:\n- \"\"\"Post the JSON data to the api url.\"\"\"\n- try:\n- requests.post(api, json=data)\n- except Exception as reason: # pylint: disable=broad-except\n- logging.error(\"Posting %s to %s failed: %s\", data, api, reason)\n-\n-\n-class MetricsCollector:\n- \"\"\"Collect measurements for all metrics.\"\"\"\n- def __init__(self) -> None:\n- self.server_url: Final[URL] = \\\n- URL(f\"http://{os.environ.get('SERVER_HOST', 'localhost')}:{os.environ.get('SERVER_PORT', '5001')}\")\n- self.data_model: JSON = dict()\n- self.next_fetch: Dict[str, datetime] = dict()\n- self.last_parameters: Dict[str, Any] = dict()\n-\n- @staticmethod\n- def record_health(filename: str = \"/tmp/health_check.txt\") -> None:\n- \"\"\"Record the current date and time in a file to allow for health checks.\"\"\"\n- try:\n- with open(filename, \"w\") as health_check:\n- health_check.write(datetime.now().isoformat())\n- except OSError as reason:\n- logging.error(\"Could not write health check time stamp to %s: %s\", filename, reason)\n-\n- def start(self) -> NoReturn:\n- \"\"\"Start fetching measurements indefinitely.\"\"\"\n- max_sleep_duration = int(os.environ.get(\"COLLECTOR_SLEEP_DURATION\", 60))\n- measurement_frequency = int(os.environ.get(\"COLLECTOR_MEASUREMENT_FREQUENCY\", 15 * 60))\n- self.data_model = self.fetch_data_model(max_sleep_duration)\n- while True:\n- self.record_health()\n- logging.info(\"Collecting...\")\n- with timer() as collection_timer:\n- self.fetch_measurements(measurement_frequency)\n- sleep_duration = max(0, max_sleep_duration - collection_timer.duration)\n- logging.info(\n- \"Collecting took %.1f seconds. Sleeping %.1f seconds...\", collection_timer.duration, sleep_duration)\n- time.sleep(sleep_duration)\n-\n- def fetch_data_model(self, sleep_duration: int) -> JSON:\n- \"\"\"Fetch the data model.\"\"\"\n- while True:\n- self.record_health()\n- logging.info(\"Loading data model...\")\n- if data_model := get(URL(f\"{self.server_url}/api/v2/datamodel\")):\n- return data_model\n- logging.warning(\"Loading data model failed, trying again in %ss...\", sleep_duration)\n- time.sleep(sleep_duration)\n-\n- def fetch_measurements(self, measurement_frequency: int) -> None:\n- \"\"\"Fetch the metrics and their measurements.\"\"\"\n- metrics = get(URL(f\"{self.server_url}/api/v2/metrics\"))\n- for metric_uuid, metric in metrics.items():\n- if not (collector := MetricCollector(metric, self.data_model)).can_collect():\n- continue\n- if self.__skip(metric_uuid, metric):\n- continue\n- measurement = collector.get()\n- self.last_parameters[metric_uuid] = metric\n- self.next_fetch[metric_uuid] = datetime.now() + timedelta(seconds=measurement_frequency)\n- measurement[\"metric_uuid\"] = metric_uuid\n- post(URL(f\"{self.server_url}/api/v2/measurements\"), measurement)\n-\n- def __skip(self, metric_uuid: str, metric) -> bool:\n- \"\"\"Return whether the metric needs to be measured.\"\"\"\n- if self.last_parameters.get(metric_uuid) != metric:\n- return False # Don't skip if metric parameters changed\n- return self.next_fetch.get(metric_uuid, datetime.min) > datetime.now()\ndiff --git a/components/collector/src/quality_time_collector.py b/components/collector/src/quality_time_collector.py\n--- a/components/collector/src/quality_time_collector.py\n+++ b/components/collector/src/quality_time_collector.py\n@@ -1,18 +1,18 @@\n \"\"\"Measurement collector.\"\"\"\n \n+import asyncio\n import logging\n-from typing import NoReturn\n \n-from metric_collectors import MetricsCollector\n+from base_collectors import MetricsCollector\n # Make sure subclasses are registered\n from source_collectors import * # lgtm [py/polluting-import] pylint: disable=unused-wildcard-import,wildcard-import\n \n \n-def collect(log_level: int = None) -> NoReturn:\n+async def collect(log_level: int = None) -> None:\n \"\"\"Collect the measurements indefinitely.\"\"\"\n logging.getLogger().setLevel(log_level or logging.ERROR)\n- MetricsCollector().start()\n+ await MetricsCollector().start()\n \n \n if __name__ == \"__main__\":\n- collect(logging.INFO) # pragma: nocover\n+ asyncio.run(collect(logging.INFO)) # pragma: nocover\ndiff --git a/components/collector/src/source_collectors/__init__.py b/components/collector/src/source_collectors/__init__.py\n--- a/components/collector/src/source_collectors/__init__.py\n+++ b/components/collector/src/source_collectors/__init__.py\n@@ -1,39 +1,44 @@\n \"\"\"Metric collectors per source.\"\"\"\n \n-from .anchore import AnchoreSecurityWarnings, AnchoreSourceUpToDateness\n-from .axe_csv import AxeCSVAccessibility\n-from .azure_devops import AzureDevopsIssues, AzureDevopsReadyUserStoryPoints\n-from .bandit import BanditSecurityWarnings, BanditSourceUpToDateness\n-from .calendar import CalendarSourceUpToDateness\n-from .composer import ComposerDependencies\n-from .cxsast import CxSASTSecurityWarnings, CxSASTSourceUpToDateness\n-from .gitlab import GitLabFailedJobs, GitLabUnusedJobs, GitLabSourceUpToDateness, GitLabUnmergedBranches\n-from .jacoco import JacocoSourceUpToDateness, JacocoUncoveredBranches, JacocoUncoveredLines\n-from .jacoco_jenkins_plugin import (\n+from .api_source_collectors.azure_devops import AzureDevopsIssues, AzureDevopsReadyUserStoryPoints\n+from .api_source_collectors.cxsast import CxSASTSecurityWarnings, CxSASTSourceUpToDateness\n+from .api_source_collectors.gitlab import (\n+ GitLabFailedJobs, GitLabUnusedJobs, GitLabSourceUpToDateness, GitLabUnmergedBranches)\n+from .api_source_collectors.jacoco_jenkins_plugin import (\n JacocoJenkinsPluginUncoveredBranches, JacocoJenkinsPluginUncoveredLines, JacocoJenkinsPluginSourceUpToDateness)\n-from .jenkins import JenkinsFailedJobs, JenkinsJobs\n-from .jenkins_test_report import JenkinsTestReportSourceUpToDateness, JenkinsTestReportTests\n-from .jira import JiraIssues, JiraManualTestDuration, JiraManualTestExecution, JiraReadyUserStoryPoints\n-from .junit import JUnitSourceUpToDateness, JUnitTests\n-from .manual_number import ManualNumber\n-from .ncover import NCoverSourceUpToDateness\n-from .ojaudit import OJAuditViolations\n-from .openvas import OpenVASSecurityWarnings, OpenVASSourceUpToDateness\n-from .owasp_dependency_check import OWASPDependencyCheckSecurityWarnings, OWASPDependencyCheckSourceUpToDateness\n-from .owasp_dependency_check_jenkins_plugin import (\n+from .api_source_collectors.jenkins import JenkinsFailedJobs, JenkinsJobs\n+from .api_source_collectors.jenkins_test_report import JenkinsTestReportSourceUpToDateness, JenkinsTestReportTests\n+from .api_source_collectors.jira import (\n+ JiraIssues, JiraManualTestDuration, JiraManualTestExecution, JiraReadyUserStoryPoints)\n+from .api_source_collectors.owasp_dependency_check_jenkins_plugin import (\n OWASPDependencyCheckJenkinsPluginSecurityWarnings, OWASPDependencyCheckJenkinsPluginSourceUpToDateness)\n-from .owasp_zap import OWASPZAPSecurityWarnings, OWASPZAPSourceUpToDateness\n-from .performancetest_runner import (\n+from .api_source_collectors.quality_time import QualityTimeMetrics\n+from .api_source_collectors.sonarqube import (\n+ SonarQubeDuplicatedLines, SonarQubeComplexUnits, SonarQubeCommentedOutCode, SonarQubeLOC, SonarQubeLongUnits,\n+ SonarQubeManyParameters, SonarQubeSourceUpToDateness, SonarQubeSuppressedViolations, SonarQubeTests,\n+ SonarQubeUncoveredBranches, SonarQubeUncoveredLines, SonarQubeViolations)\n+from .api_source_collectors.trello import TrelloIssues, TrelloSourceUpToDateness\n+from .api_source_collectors.wekan import WekanIssues, WekanSourceUpToDateness\n+\n+from .file_source_collectors.anchore import AnchoreSecurityWarnings, AnchoreSourceUpToDateness\n+from .file_source_collectors.axe_csv import AxeCSVAccessibility\n+from .file_source_collectors.bandit import BanditSecurityWarnings, BanditSourceUpToDateness\n+from .file_source_collectors.composer import ComposerDependencies\n+from .file_source_collectors.jacoco import JacocoSourceUpToDateness, JacocoUncoveredBranches, JacocoUncoveredLines\n+from .file_source_collectors.junit import JUnitSourceUpToDateness, JUnitTests\n+from .file_source_collectors.ncover import NCoverSourceUpToDateness\n+from .file_source_collectors.ojaudit import OJAuditViolations\n+from .file_source_collectors.openvas import OpenVASSecurityWarnings, OpenVASSourceUpToDateness\n+from .file_source_collectors.owasp_dependency_check import (\n+ OWASPDependencyCheckSecurityWarnings, OWASPDependencyCheckSourceUpToDateness)\n+from .file_source_collectors.owasp_zap import OWASPZAPSecurityWarnings, OWASPZAPSourceUpToDateness\n+from .file_source_collectors.performancetest_runner import (\n PerformanceTestRunnerPerformanceTestDuration, PerformanceTestRunnerPerformanceTestStability,\n PerformanceTestRunnerScalability, PerformanceTestRunnerSlowTransactions, PerformanceTestRunnerSourceUpToDateness,\n PerformanceTestRunnerTests)\n-from .pyupio_safety import PyupioSafetySecurityWarnings\n-from .quality_time import QualityTimeMetrics\n-from .random_number import Random\n-from .robot_framework import RobotFrameworkTests, RobotFrameworkSourceUpToDateness\n-from .sonarqube import (\n- SonarQubeDuplicatedLines, SonarQubeComplexUnits, SonarQubeCommentedOutCode, SonarQubeLOC,\n- SonarQubeLongUnits, SonarQubeManyParameters, SonarQubeSourceUpToDateness, SonarQubeSuppressedViolations,\n- SonarQubeTests, SonarQubeUncoveredBranches, SonarQubeUncoveredLines, SonarQubeViolations)\n-from .trello import TrelloIssues, TrelloSourceUpToDateness\n-from .wekan import WekanIssues, WekanSourceUpToDateness\n+from .file_source_collectors.pyupio_safety import PyupioSafetySecurityWarnings\n+from .file_source_collectors.robot_framework import RobotFrameworkTests, RobotFrameworkSourceUpToDateness\n+\n+from .local_source_collectors.calendar import CalendarSourceUpToDateness\n+from .local_source_collectors.manual_number import ManualNumber\n+from .local_source_collectors.random_number import Random\ndiff --git a/components/collector/src/source_collectors/azure_devops.py b/components/collector/src/source_collectors/api_source_collectors/azure_devops.py\nsimilarity index 63%\nrename from components/collector/src/source_collectors/azure_devops.py\nrename to components/collector/src/source_collectors/api_source_collectors/azure_devops.py\n--- a/components/collector/src/source_collectors/azure_devops.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/azure_devops.py\n@@ -6,14 +6,14 @@\n \n from abc import ABC\n from datetime import datetime\n-from typing import cast, Final, List, Tuple\n+from typing import cast, Any, Dict, Final, List, Tuple\n \n from dateutil.parser import parse\n-import requests\n+import aiohttp\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n from collector_utilities.type import Entities, Job, Response, Responses, URL, Value\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector, UnmergedBranchesSourceCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector, UnmergedBranchesSourceCollector\n \n \n class AzureDevopsIssues(SourceCollector):\n@@ -22,43 +22,44 @@ class AzureDevopsIssues(SourceCollector):\n MAX_IDS_PER_WORK_ITEMS_API_CALL: Final[int] = 200 # See\n # https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/list?view=azure-devops-rest-5.1\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/wit/wiql?api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/_apis/wit/wiql?api-version=4.1\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override because we need to do a post request and need to separately get the entities.\"\"\"\n- auth = self._basic_auth_credentials()\n- response = requests.post(api_url, timeout=self.TIMEOUT, auth=auth, json=dict(query=self._parameter(\"wiql\")))\n- ids = [str(work_item[\"id\"]) for work_item in response.json().get(\"workItems\", [])]\n+ auth = aiohttp.BasicAuth(str(self._parameter(\"private_token\")))\n+ response = await self._session.post(urls[0], auth=auth, json=dict(query=self._parameter(\"wiql\")))\n+ ids = [str(work_item[\"id\"]) for work_item in (await response.json()).get(\"workItems\", [])]\n if not ids:\n return [response]\n ids_string = \",\".join(ids[:min(self.MAX_IDS_PER_WORK_ITEMS_API_CALL, self.MAX_ENTITIES)])\n- work_items_url = URL(f\"{super()._api_url()}/_apis/wit/workitems?ids={ids_string}&api-version=4.1\")\n- return [response, requests.get(work_items_url, timeout=self.TIMEOUT, auth=auth)]\n+ work_items_url = URL(f\"{await super()._api_url()}/_apis/wit/workitems?ids={ids_string}&api-version=4.1\")\n+ work_items = await super()._get_source_responses(work_items_url)\n+ return [response] + work_items\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value = str(len(responses[0].json()[\"workItems\"]))\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value = str(len((await responses[0].json())[\"workItems\"]))\n entities = [\n dict(\n key=str(work_item[\"id\"]), project=work_item[\"fields\"][\"System.TeamProject\"],\n title=work_item[\"fields\"][\"System.Title\"], work_item_type=work_item[\"fields\"][\"System.WorkItemType\"],\n state=work_item[\"fields\"][\"System.State\"], url=work_item[\"url\"])\n- for work_item in self._work_items(responses)]\n+ for work_item in await self._work_items(responses)]\n return value, \"100\", entities\n \n @staticmethod\n- def _work_items(responses: Responses):\n+ async def _work_items(responses: Responses):\n \"\"\"Return the work items, if any.\"\"\"\n- return responses[1].json()[\"value\"] if len(responses) > 1 else []\n+ return (await responses[1].json())[\"value\"] if len(responses) > 1 else []\n \n \n class AzureDevopsReadyUserStoryPoints(AzureDevopsIssues):\n \"\"\"Collector to get ready user story points from Azure Devops Server.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n value = 0\n- for entity, work_item in zip(entities, self._work_items(responses)):\n+ for entity, work_item in zip(entities, await self._work_items(responses)):\n entity[\"story_points\"] = story_points = work_item[\"fields\"].get(\"Microsoft.VSTS.Scheduling.StoryPoints\")\n value += 0 if story_points is None else story_points\n return str(round(value)), total, entities\n@@ -67,30 +68,29 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class AzureDevopsRepositoryBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Azure DevOps collectors that work with repositories.\"\"\"\n \n- def _repository_id(self) -> str:\n+ async def _repository_id(self) -> str:\n \"\"\"Return the repository id belonging to the repository.\"\"\"\n- api_url = str(super()._api_url())\n+ api_url = str(await super()._api_url())\n repository = self._parameter(\"repository\") or api_url.rsplit(\"/\", 1)[-1]\n- repositories_url = f\"{api_url}/_apis/git/repositories?api-version=4.1\"\n- repositories = requests.get(repositories_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n- repositories.raise_for_status()\n- return str([r for r in repositories.json()[\"value\"] if repository in (r[\"name\"], r[\"id\"])][0][\"id\"])\n+ repositories_url = URL(f\"{api_url}/_apis/git/repositories?api-version=4.1\")\n+ repositories = (await (await super()._get_source_responses(repositories_url))[0].json())[\"value\"]\n+ return str([r for r in repositories if repository in (r[\"name\"], r[\"id\"])][0][\"id\"])\n \n \n class AzureDevopsUnmergedBranches(UnmergedBranchesSourceCollector, AzureDevopsRepositoryBase):\n \"\"\"Collector for unmerged branches.\"\"\"\n \n- def _api_url(self) -> URL:\n- api_url = str(super()._api_url())\n- return URL(f\"{api_url}/_apis/git/repositories/{self._repository_id()}/stats/branches?api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ api_url = str(await super()._api_url())\n+ return URL(f\"{api_url}/_apis/git/repositories/{await self._repository_id()}/stats/branches?api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- landing_url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ landing_url = str(await super()._landing_url(responses))\n repository = self._parameter(\"repository\") or landing_url.rsplit(\"/\", 1)[-1]\n return URL(f\"{landing_url}/_git/{repository}/branches\")\n \n- def _unmerged_branches(self, responses: Responses) -> List:\n- return [branch for branch in responses[0].json()[\"value\"] if not branch[\"isBaseVersion\"] and\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ return [branch for branch in (await responses[0].json())[\"value\"] if not branch[\"isBaseVersion\"] and\n int(branch[\"aheadCount\"]) > 0 and\n days_ago(self._commit_datetime(branch)) > int(cast(str, self._parameter(\"inactive_days\"))) and\n not match_string_or_regular_expression(branch[\"name\"], self._parameter(\"branches_to_ignore\"))]\n@@ -102,35 +102,36 @@ def _commit_datetime(self, branch) -> datetime:\n class AzureDevopsSourceUpToDateness(SourceUpToDatenessCollector, AzureDevopsRepositoryBase):\n \"\"\"Collector class to measure the up-to-dateness of a repo or folder/file in a repo.\"\"\"\n \n- def _api_url(self) -> URL:\n- api_url = str(super()._api_url())\n- repository_id = self._repository_id()\n+ async def _api_url(self) -> URL:\n+ api_url = str(await super()._api_url())\n+ repository_id = await self._repository_id()\n path = self._parameter(\"file_path\", quote=True)\n branch = self._parameter(\"branch\", quote=True)\n search_criteria = \\\n f\"searchCriteria.itemPath={path}&searchCriteria.itemVersion.version={branch}&searchCriteria.$top=1\"\n return URL(f\"{api_url}/_apis/git/repositories/{repository_id}/commits?{search_criteria}&api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- landing_url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ landing_url = str(await super()._landing_url(responses))\n repository = self._parameter(\"repository\") or landing_url.rsplit(\"/\", 1)[-1]\n path = self._parameter(\"file_path\", quote=True)\n branch = self._parameter(\"branch\", quote=True)\n return URL(f\"{landing_url}/_git/{repository}?path={path}&version=GB{branch}\")\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(response.json()[\"value\"][0][\"committer\"][\"date\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await response.json())[\"value\"][0][\"committer\"][\"date\"])\n \n \n class AzureDevopsTests(SourceCollector):\n \"\"\"Collector for the tests metric.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/test/runs?automated=true&includeRunDetails=true&$top=1&api-version=5.1\")\n+ async def _api_url(self) -> URL:\n+ api_url = await super()._api_url()\n+ return URL(f\"{api_url}/_apis/test/runs?automated=true&includeRunDetails=true&$top=1&api-version=5.1\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n test_results = cast(List[str], self._parameter(\"test_result\"))\n- runs = responses[0].json().get(\"value\", [])\n+ runs = (await responses[0].json()).get(\"value\", [])\n test_count, highest_build_nr_seen = 0, 0\n for run in runs:\n build_nr = int(run.get(\"build\", {}).get(\"id\", \"-1\"))\n@@ -143,18 +144,18 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n return str(test_count), \"100\", []\n \n \n-class AxureDevopsJobs(SourceCollector):\n+class AzureDevopsJobs(SourceCollector):\n \"\"\"Base class for job collectors.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/build/definitions?includeLatestBuilds=true&api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/_apis/build/definitions?includeLatestBuilds=true&api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/_build\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/_build\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = []\n- for job in responses[0].json()[\"value\"]:\n+ for job in (await responses[0].json())[\"value\"]:\n if self._ignore_job(job):\n continue\n name = self.__job_name(job)\n@@ -190,7 +191,7 @@ def __job_name(job: Job) -> str:\n return \"/\".join(job[\"path\"].strip(r\"\\\\\").split(r\"\\\\\") + [job[\"name\"]]).strip(\"/\")\n \n \n-class AzureDevopsFailedJobs(AxureDevopsJobs):\n+class AzureDevopsFailedJobs(AzureDevopsJobs):\n \"\"\"Collector for the failed jobs metric.\"\"\"\n \n def _ignore_job(self, job: Job) -> bool:\n@@ -199,7 +200,7 @@ def _ignore_job(self, job: Job) -> bool:\n return self._latest_build_result(job) not in self._parameter(\"failure_type\")\n \n \n-class AzureDevopsUnusedJobs(AxureDevopsJobs):\n+class AzureDevopsUnusedJobs(AzureDevopsJobs):\n \"\"\"Collector for the unused jobs metric.\"\"\"\n \n def _ignore_job(self, job: Job) -> bool:\ndiff --git a/components/collector/src/source_collectors/api_source_collectors/cxsast.py b/components/collector/src/source_collectors/api_source_collectors/cxsast.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/source_collectors/api_source_collectors/cxsast.py\n@@ -0,0 +1,85 @@\n+\"\"\"Collectors for the Checkmarx CxSAST product.\"\"\"\n+\n+from abc import ABC\n+from typing import cast, Dict, Optional, Tuple\n+\n+from dateutil.parser import parse\n+import aiohttp\n+\n+from collector_utilities.type import Entities, Response, Responses, URL, Value\n+from collector_utilities.functions import days_ago\n+from base_collectors import SourceCollector\n+\n+\n+class CxSASTBase(SourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for CxSAST collectors.\"\"\"\n+\n+ def __init__(self, *args, **kwargs) -> None:\n+ self.__token: Optional[str] = None\n+ self.__project_id: Optional[str] = None\n+ self._scan_id: Optional[str] = None\n+ super().__init__(*args, **kwargs)\n+\n+ def _headers(self) -> Dict[str, str]:\n+ headers = super()._headers()\n+ headers[\"Authorization\"] = f\"Bearer {self.__token}\"\n+ return headers\n+\n+ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n+ return None\n+\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ api_url = await self._api_url()\n+ return URL(f\"{api_url}/CxWebClient/ViewerMain.aspx?scanId={self._scan_id}&ProjectID={self.__project_id}\") \\\n+ if responses else api_url\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n+ # See https://checkmarx.atlassian.net/wiki/spaces/KC/pages/1187774721/Using+the+CxSAST+REST+API+v8.6.0+and+up\n+ credentials = dict( # nosec, The client secret is not really secret, see previous url\n+ username=cast(str, self._parameter(\"username\")),\n+ password=cast(str, self._parameter(\"password\")),\n+ grant_type=\"password\", scope=\"sast_rest_api\", client_id=\"resource_owner_client\",\n+ client_secret=\"014DF517-39D1-4453-B7B3-9930C563627C\")\n+ token_response = await self.__api_post(\"auth/identity/connect/token\", credentials)\n+ self.__token = (await token_response.json())['access_token']\n+ project_api = URL(f\"{await self._api_url()}/cxrestapi/projects\")\n+ project_response = (await super()._get_source_responses(project_api))[0]\n+ self.__project_id = await self.__get_project_id(project_response)\n+ scan_api = URL(\n+ f\"{await self._api_url()}/cxrestapi/sast/scans?projectId={self.__project_id}&scanStatus=Finished&last=1\")\n+ scan_response = (await super()._get_source_responses(scan_api))[0]\n+ self._scan_id = (await scan_response.json())[0][\"id\"]\n+ return [scan_response]\n+\n+ async def __get_project_id(self, project_response: Response) -> str:\n+ \"\"\"Return the project id that belongs to the project parameter.\"\"\"\n+ project_name_or_id = self._parameter(\"project\")\n+ projects = await project_response.json()\n+ return str([project for project in projects if project_name_or_id in (project[\"name\"], project[\"id\"])][0][\"id\"])\n+\n+ async def __api_post(self, api: str, data) -> aiohttp.ClientResponse:\n+ \"\"\"Post to the API and return the response.\"\"\"\n+ return await self._session.post(f\"{await self._api_url()}/cxrestapi/{api}\", data=data)\n+\n+\n+class CxSASTSourceUpToDateness(CxSASTBase):\n+ \"\"\"Collector class to measure the up-to-dateness of a Checkmarx CxSAST scan.\"\"\"\n+\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ scan = (await responses[0].json())[0]\n+ return str(days_ago(parse(scan[\"dateAndTime\"][\"finishedOn\"]))), \"100\", []\n+\n+\n+class CxSASTSecurityWarnings(CxSASTBase):\n+ \"\"\"Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.\"\"\"\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ await super()._get_source_responses(*urls) # Get token\n+ stats_api = URL(f\"{await self._api_url()}/cxrestapi/sast/scans/{self._scan_id}/resultsStatistics\")\n+ return await SourceCollector._get_source_responses(self, stats_api) # pylint: disable=protected-access\n+\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ stats = await responses[0].json()\n+ severities = self._parameter(\"severities\")\n+ return str(sum(stats.get(f\"{severity.lower()}Severity\", 0) for severity in severities)), \"100\", []\ndiff --git a/components/collector/src/source_collectors/gitlab.py b/components/collector/src/source_collectors/api_source_collectors/gitlab.py\nsimilarity index 56%\nrename from components/collector/src/source_collectors/gitlab.py\nrename to components/collector/src/source_collectors/api_source_collectors/gitlab.py\n--- a/components/collector/src/source_collectors/gitlab.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/gitlab.py\n@@ -1,24 +1,25 @@\n \"\"\"GitLab metric source.\"\"\"\n \n+import asyncio\n+import itertools\n from abc import ABC\n from datetime import datetime\n-from typing import cast, Iterator, List, Optional, Set, Tuple\n+from typing import cast, Any, Dict, List, Optional, Set, Sequence, Tuple\n from urllib.parse import quote\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n-from collector_utilities.type import Job, Entities, Response, Responses, URL, Value\n-from .source_collector import SourceCollector, UnmergedBranchesSourceCollector\n+from collector_utilities.type import Job, Entities, Responses, URL, Value\n+from base_collectors import SourceCollector, UnmergedBranchesSourceCollector\n \n \n class GitLabBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for GitLab collectors.\"\"\"\n \n- def _gitlab_api_url(self, api: str) -> URL:\n+ async def _gitlab_api_url(self, api: str) -> URL:\n \"\"\"Return a GitLab API url with private token, if present in the parameters.\"\"\"\n- url = super()._api_url()\n+ url = await super()._api_url()\n project = self._parameter(\"project\", quote=True)\n api_url = f\"{url}/api/v4/projects/{project}/{api}\"\n sep = \"&\" if \"?\" in api_url else \"?\"\n@@ -34,29 +35,32 @@ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n class GitLabJobsBase(GitLabBase):\n \"\"\"Base class for GitLab job collectors.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"jobs\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"jobs\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ jobs = await self.__jobs(responses)\n entities = [\n dict(\n key=job[\"id\"], name=job[\"name\"], url=job[\"web_url\"], build_status=job[\"status\"], branch=job[\"ref\"],\n stage=job[\"stage\"], build_date=str((build_date := parse(job[\"created_at\"])).date()),\n build_age=str(days_ago(build_date)))\n- for job in self.__jobs(responses)]\n+ for job in jobs]\n return str(len(entities)), \"100\", entities\n \n- def __jobs(self, responses: Responses) -> Iterator[Job]:\n+ async def __jobs(self, responses: Responses) -> Sequence[Job]:\n \"\"\"Return the jobs to count.\"\"\"\n+ jobs: List[Job] = []\n jobs_seen: Set[Tuple[str, str, str]] = set()\n for response in responses:\n- for job in response.json():\n+ for job in await response.json():\n job_fingerprint = job[\"name\"], job[\"stage\"], job[\"ref\"]\n if job_fingerprint in jobs_seen:\n continue\n jobs_seen.add(job_fingerprint)\n if self._count_job(job):\n- yield job\n+ jobs.append(job)\n+ return jobs\n \n def _count_job(self, job: Job) -> bool: # pylint: disable=no-self-use,unused-argument\n \"\"\"Return whether to count the job.\"\"\"\n@@ -84,66 +88,67 @@ def _count_job(self, job: Job) -> bool:\n class GitLabSourceUpToDateness(GitLabBase):\n \"\"\"Collector class to measure the up-to-dateness of a repo or folder/file in a repo.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(\n- f\"{responses[0].json()['web_url']}/blob/{self._parameter('branch', quote=True)}/\"\n- f\"{self._parameter('file_path', quote=True)}\") if responses else super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ if not responses:\n+ return await super()._landing_url(responses)\n+ web_url = (await responses[0].json())[\"web_url\"]\n+ branch = self._parameter('branch', quote=True)\n+ file_path = self._parameter('file_path', quote=True)\n+ return URL(f\"{web_url}/blob/{branch}/{file_path}\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override to get the last commit metadata of the file or, if the file is a folder, of the files in the folder,\n recursively.\"\"\"\n \n- def get_commits_recursively(file_path: str, first_call: bool = True) -> Responses:\n+ async def get_commits_recursively(file_path: str, first_call: bool = True) -> Responses:\n \"\"\"Get the commits of files recursively.\"\"\"\n- tree_api = self._gitlab_api_url(\n+ tree_api = await self._gitlab_api_url(\n f\"repository/tree?path={file_path}&ref={self._parameter('branch', quote=True)}\")\n- tree_response = super(GitLabSourceUpToDateness, self)._get_source_responses(tree_api)[0]\n- tree_response.raise_for_status()\n- tree = tree_response.json()\n+ tree_response = (await super(GitLabSourceUpToDateness, self)._get_source_responses(tree_api))[0]\n+ tree = await tree_response.json()\n file_paths = [quote(item[\"path\"], safe=\"\") for item in tree if item[\"type\"] == \"blob\"]\n folder_paths = [quote(item[\"path\"], safe=\"\") for item in tree if item[\"type\"] == \"tree\"]\n if not tree and first_call:\n file_paths = [file_path]\n- commit_responses = [self.__last_commit(file_path) for file_path in file_paths]\n- for folder_path in folder_paths:\n- commit_responses.extend(get_commits_recursively(folder_path, first_call=False))\n- return commit_responses\n+ commits = [self.__last_commit(file_path) for file_path in file_paths] + \\\n+ [get_commits_recursively(folder_path, first_call=False) for folder_path in folder_paths]\n+ return list(itertools.chain(*(await asyncio.gather(*commits))))\n \n # First, get the project info so we can use the web url as landing url\n- responses = super()._get_source_responses(api_url)\n- responses[0].raise_for_status()\n+ responses = await super()._get_source_responses(*urls)\n # Then, collect the commits\n- responses.extend(get_commits_recursively(str(self._parameter(\"file_path\", quote=True))))\n+ responses.extend(await get_commits_recursively(str(self._parameter(\"file_path\", quote=True))))\n return responses\n \n- def __last_commit(self, file_path: str) -> Response:\n- files_api_url = self._gitlab_api_url(\n+ async def __last_commit(self, file_path: str) -> Responses:\n+ files_api_url = await self._gitlab_api_url(\n f\"repository/files/{file_path}?ref={self._parameter('branch', quote=True)}\")\n- response = requests.head(files_api_url)\n+ response = await self._session.head(files_api_url)\n last_commit_id = response.headers[\"X-Gitlab-Last-Commit-Id\"]\n- commit_api_url = self._gitlab_api_url(f\"repository/commits/{last_commit_id}\")\n- return requests.get(commit_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n+ commit_api_url = await self._gitlab_api_url(f\"repository/commits/{last_commit_id}\")\n+ return await super()._get_source_responses(commit_api_url)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n commit_responses = responses[1:]\n- value = str(days_ago(max(parse(response.json()[\"committed_date\"]) for response in commit_responses)))\n+ value = str(days_ago(max([parse((await response.json())[\"committed_date\"]) for response in commit_responses])))\n return value, \"100\", []\n \n \n class GitLabUnmergedBranches(GitLabBase, UnmergedBranchesSourceCollector):\n \"\"\"Collector class to measure the number of unmerged branches.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"repository/branches\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"repository/branches\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{str(super()._landing_url(responses))}/{self._parameter('project')}/-/branches\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{str(await super()._landing_url(responses))}/{self._parameter('project')}/-/branches\")\n \n- def _unmerged_branches(self, responses: Responses) -> List:\n- return [branch for branch in responses[0].json() if not branch[\"default\"] and not branch[\"merged\"] and\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ branches = await responses[0].json()\n+ return [branch for branch in branches if not branch[\"default\"] and not branch[\"merged\"] and\n days_ago(self._commit_datetime(branch)) > int(cast(str, self._parameter(\"inactive_days\"))) and\n not match_string_or_regular_expression(branch[\"name\"], self._parameter(\"branches_to_ignore\"))]\n \ndiff --git a/components/collector/src/source_collectors/jacoco_jenkins_plugin.py b/components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\nsimilarity index 51%\nrename from components/collector/src/source_collectors/jacoco_jenkins_plugin.py\nrename to components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\n--- a/components/collector/src/source_collectors/jacoco_jenkins_plugin.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\n@@ -1,18 +1,17 @@\n \"\"\"Jacoco Jenkins plugin coverage report collector.\"\"\"\n \n-from datetime import datetime\n from typing import Tuple\n \n-from collector_utilities.type import Entities, Response, Responses, URL, Value\n+from collector_utilities.type import Entities, Responses, URL, Value\n \n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector\n \n \n class JacocoJenkinsPluginBaseClass(SourceCollector):\n \"\"\"Base class for Jacoco Jenkins plugin collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/jacoco\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/jacoco\")\n \n \n class JacocoJenkinsPluginCoverageBaseClass(JacocoJenkinsPluginBaseClass):\n@@ -20,11 +19,11 @@ class JacocoJenkinsPluginCoverageBaseClass(JacocoJenkinsPluginBaseClass):\n \n coverage_type = \"subclass responsibility\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/jacoco/api/json\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/jacoco/api/json\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- line_coverage = responses[0].json()[f\"{self.coverage_type}Coverage\"]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ line_coverage = (await responses[0].json())[f\"{self.coverage_type}Coverage\"]\n return str(line_coverage[\"missed\"]), str(line_coverage[\"total\"]), []\n \n \n@@ -40,11 +39,5 @@ class JacocoJenkinsPluginUncoveredBranches(JacocoJenkinsPluginCoverageBaseClass)\n coverage_type = \"branch\"\n \n \n-class JacocoJenkinsPluginSourceUpToDateness(JacocoJenkinsPluginBaseClass, SourceUpToDatenessCollector):\n+class JacocoJenkinsPluginSourceUpToDateness(JacocoJenkinsPluginBaseClass, JenkinsPluginSourceUpToDatenessCollector):\n \"\"\"Collector for the up to dateness of the Jacoco Jenkins plugin coverage report.\"\"\"\n-\n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/api/json\")\n-\n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return datetime.fromtimestamp(float(response.json()[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/source_collectors/jenkins.py b/components/collector/src/source_collectors/api_source_collectors/jenkins.py\nsimilarity index 91%\nrename from components/collector/src/source_collectors/jenkins.py\nrename to components/collector/src/source_collectors/api_source_collectors/jenkins.py\n--- a/components/collector/src/source_collectors/jenkins.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jenkins.py\n@@ -5,24 +5,24 @@\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n from collector_utilities.type import Job, Jobs, Entities, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class JenkinsJobs(SourceCollector):\n \"\"\"Collector to get job counts from Jenkins.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n job_attrs = \"buildable,color,url,name,builds[result,timestamp]\"\n return URL(f\"{url}/api/json?tree=jobs[{job_attrs},jobs[{job_attrs},jobs[{job_attrs}]]]\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = [\n dict(\n key=job[\"name\"], name=job[\"name\"], url=job[\"url\"], build_status=self._build_status(job),\n build_age=str(days_ago(self._build_datetime(job))) if self._build_datetime(job) > datetime.min else \"\",\n build_date=str(self._build_datetime(job).date()) if self._build_datetime(job) > datetime.min else \"\")\n- for job in self.__jobs(responses[0].json()[\"jobs\"])]\n+ for job in self.__jobs((await responses[0].json())[\"jobs\"])]\n return str(len(entities)), \"100\", entities\n \n def __jobs(self, jobs: Jobs, parent_job_name: str = \"\") -> Iterator[Job]:\ndiff --git a/components/collector/src/source_collectors/jira.py b/components/collector/src/source_collectors/api_source_collectors/jira.py\nsimilarity index 82%\nrename from components/collector/src/source_collectors/jira.py\nrename to components/collector/src/source_collectors/api_source_collectors/jira.py\n--- a/components/collector/src/source_collectors/jira.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jira.py\n@@ -6,7 +6,7 @@\n \n from collector_utilities.functions import days_ago\n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class JiraIssues(SourceCollector):\n@@ -16,14 +16,14 @@ def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._field_ids = {}\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n jql = str(self._parameter(\"jql\", quote=True))\n fields = self._fields()\n return URL(f\"{url}/rest/api/2/search?jql={jql}&fields={fields}&maxResults=500\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n jql = str(self._parameter(\"jql\", quote=True))\n return URL(f\"{url}/issues/?jql={jql}\")\n \n@@ -33,16 +33,15 @@ def _parameter(self, parameter_key: str, quote: bool = False) -> Union[str, List\n parameter_value = self._field_ids.get(parameter_value, parameter_value)\n return parameter_value\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- fields_url = URL(f\"{super()._api_url()}/rest/api/2/field\")\n- response = super()._get_source_responses(fields_url)[0]\n- response.raise_for_status()\n- self._field_ids = dict((field[\"name\"], field[\"id\"]) for field in response.json())\n- return super()._get_source_responses(api_url)\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ fields_url = URL(f\"{await super()._api_url()}/rest/api/2/field\")\n+ response = (await super()._get_source_responses(fields_url))[0]\n+ self._field_ids = dict((field[\"name\"], field[\"id\"]) for field in await response.json())\n+ return await super()._get_source_responses(*urls)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n url = URL(str(self._parameter(\"url\")))\n- json = responses[0].json()\n+ json = await responses[0].json()\n entities = [self._create_entity(issue, url) for issue in json.get(\"issues\", []) if self._include_issue(issue)]\n return str(json.get(\"total\", 0)), \"100\", entities\n \n@@ -62,8 +61,8 @@ def _fields(self) -> str: # pylint: disable=no-self-use\n class JiraManualTestExecution(JiraIssues):\n \"\"\"Collector for the number of manual test cases that have not been executed recently enough.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n return str(len(entities)), total, entities\n \n def _create_entity(self, issue: Dict, url: URL) -> Entity:\n@@ -97,8 +96,8 @@ class JiraFieldSumBase(JiraIssues):\n field_parameter = \"subclass responsibility\"\n entity_key = \"subclass responsibility\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n value = str(round(sum(float(entity[self.entity_key]) for entity in entities)))\n return value, total, entities\n \ndiff --git a/components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py b/components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\nsimilarity index 61%\nrename from components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py\nrename to components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\n--- a/components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\n@@ -1,23 +1,23 @@\n \"\"\"OWASP Dependency Check Jenkins plugin metric collector.\"\"\"\n \n-from datetime import datetime\n from typing import Dict, Tuple\n \n-from collector_utilities.type import Entities, Entity, Response, Responses, Value, URL\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from collector_utilities.type import Entities, Entity, Responses, Value, URL\n+from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector\n \n \n class OWASPDependencyCheckJenkinsPluginSecurityWarnings(SourceCollector):\n \"\"\"OWASP Dependency Check Jenkins plugin security warnings collector.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult/api/json?depth=1\")\n+ async def _api_url(self) -> URL:\n+ api_url = await super()._api_url()\n+ return URL(f\"{api_url}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult/api/json?depth=1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n severities = self._parameter(\"severities\")\n warnings = [warning for warning in json.get(\"warnings\", []) if warning[\"priority\"].lower() in severities]\n entities: Dict[str, Entity] = dict()\n@@ -39,11 +39,5 @@ def __highest_severity(self, severity1: str, severity2: str) -> str:\n return severity1 if severities.index(severity1) >= severities.index(severity2) else severity2\n \n \n-class OWASPDependencyCheckJenkinsPluginSourceUpToDateness(SourceUpToDatenessCollector):\n+class OWASPDependencyCheckJenkinsPluginSourceUpToDateness(JenkinsPluginSourceUpToDatenessCollector):\n \"\"\"Collector to get the age of the OWASP Dependency Check Jenkins plugin report.\"\"\"\n-\n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/api/json\")\n-\n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return datetime.fromtimestamp(float(response.json()[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/source_collectors/quality_time.py b/components/collector/src/source_collectors/api_source_collectors/quality_time.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/quality_time.py\nrename to components/collector/src/source_collectors/api_source_collectors/quality_time.py\n--- a/components/collector/src/source_collectors/quality_time.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/quality_time.py\n@@ -1,42 +1,43 @@\n \"\"\"Collector for Quality-time.\"\"\"\n \n-from functools import lru_cache\n from typing import Any, Dict, List, Tuple\n from urllib import parse\n \n from collector_utilities.type import Entity, Entities, Measurement, Response, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class QualityTimeMetrics(SourceCollector):\n \"\"\"Collector to get the \"metrics\" metric from Quality-time.\"\"\"\n \n- def _api_url(self) -> URL:\n- parts = parse.urlsplit(super()._api_url())\n+ def __init__(self, *args, **kwargs):\n+ self.__metrics_and_entities: List[Tuple[Dict[str, Dict], Entity]] = []\n+ super().__init__(*args, **kwargs)\n+\n+ async def _api_url(self) -> URL:\n+ parts = parse.urlsplit(await super()._api_url())\n netloc = f\"{parts.netloc.split(':')[0]}\"\n return URL(parse.urlunsplit((parts.scheme, netloc, \"/api/v2\", \"\", \"\")))\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n # First, get the report(s):\n- responses = super()._get_source_responses(URL(f\"{api_url}/reports\"))\n+ responses = await super()._get_source_responses(URL(f\"{urls[0]}/reports\"))\n # Then, add the measurements for each of the applicable metrics:\n- for _, entity in self.__get_metrics_and_entities(responses[0]):\n- responses.extend(super()._get_source_responses(URL(f\"{api_url}/measurements/{entity['key']}\")))\n- return responses\n+ self.__metrics_and_entities = await self.__get_metrics_and_entities(responses[0])\n+ measurement_urls = [URL(f\"{urls[0]}/measurements/{entity['key']}\") for _, entity in self.__metrics_and_entities]\n+ return responses + await super()._get_source_responses(*measurement_urls)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- metrics_and_entities = self.__get_metrics_and_entities(responses[0])\n- entities = self.__get_entities(responses[1:], metrics_and_entities)\n- return str(len(entities)), str(len(metrics_and_entities)), entities\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ entities = await self.__get_entities(responses[1:])\n+ return str(len(entities)), str(len(self.__metrics_and_entities)), entities\n \n- def __get_entities(\n- self, responses: Responses, metrics_and_entities: List[Tuple[Dict[str, Dict], Entity]]) -> Entities:\n+ async def __get_entities(self, responses: Responses) -> Entities:\n \"\"\"Get the metric entities from the responses.\"\"\"\n- last_measurements = self.__get_last_measurements(responses)\n+ last_measurements = await self.__get_last_measurements(responses)\n status_to_count = self._parameter(\"status\")\n- landing_url = self._landing_url(responses)\n+ landing_url = await self._landing_url(responses)\n entities: Entities = []\n- for metric, entity in metrics_and_entities:\n+ for metric, entity in self.__metrics_and_entities:\n status, value = self.__get_status_and_value(metric, last_measurements.get(str(entity[\"key\"]), {}))\n if status in status_to_count:\n entity[\"report_url\"] = report_url = f\"{landing_url}/{metric['report_uuid']}\"\n@@ -54,11 +55,11 @@ def __get_entities(\n return entities\n \n @staticmethod\n- def __get_last_measurements(responses: Responses) -> Dict[str, Measurement]:\n+ async def __get_last_measurements(responses: Responses) -> Dict[str, Measurement]:\n \"\"\"Return the last measurements by metric UUID for easy lookup.\"\"\"\n last_measurements = dict()\n for response in responses:\n- if measurements := response.json()[\"measurements\"]:\n+ if measurements := (await response.json())[\"measurements\"]:\n last_measurement = measurements[-1]\n last_measurements[last_measurement[\"metric_uuid\"]] = last_measurement\n return last_measurements\n@@ -70,14 +71,13 @@ def __get_status_and_value(metric, measurement: Measurement) -> Tuple[str, Value\n scale_data = measurement.get(scale, {})\n return scale_data.get(\"status\") or \"unknown\", scale_data.get(\"value\")\n \n- @lru_cache(maxsize=2)\n- def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str, Dict], Entity]]:\n+ async def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str, Dict], Entity]]:\n \"\"\"Get the relevant metrics from the reports response.\"\"\"\n tags = set(self._parameter(\"tags\"))\n metric_types = self._parameter(\"metric_type\")\n source_types = set(self._parameter(\"source_type\"))\n metrics_and_entities = []\n- for report in self.__get_reports(response):\n+ for report in await self.__get_reports(response):\n for subject_uuid, subject in report.get(\"subjects\", {}).items():\n for metric_uuid, metric in subject.get(\"metrics\", {}).items():\n if self.__metric_is_to_be_measured(metric, metric_types, source_types, tags):\n@@ -87,10 +87,10 @@ def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str,\n metrics_and_entities.append((metric, entity))\n return metrics_and_entities\n \n- def __get_reports(self, response) -> List[Dict[str, Any]]:\n+ async def __get_reports(self, response: Response) -> List[Dict[str, Any]]:\n \"\"\"Get the relevant reports from the reports response.\"\"\"\n report_titles_or_ids = set(self._parameter(\"reports\"))\n- reports = list(response.json()[\"reports\"])\n+ reports = list((await response.json())[\"reports\"])\n return [report for report in reports if (report_titles_or_ids & {report[\"title\"], report[\"report_uuid\"]})] \\\n if report_titles_or_ids else reports\n \ndiff --git a/components/collector/src/source_collectors/sonarqube.py b/components/collector/src/source_collectors/api_source_collectors/sonarqube.py\nsimilarity index 69%\nrename from components/collector/src/source_collectors/sonarqube.py\nrename to components/collector/src/source_collectors/api_source_collectors/sonarqube.py\n--- a/components/collector/src/source_collectors/sonarqube.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/sonarqube.py\n@@ -4,26 +4,29 @@\n from typing import Dict, List, Tuple\n \n from dateutil.parser import isoparse\n-import requests\n \n from collector_utilities.type import URL, Entities, Entity, Response, Responses, Value\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector\n+\n+\n+class SonarQubeException(Exception):\n+ \"\"\"Something went wrong collecting information from SonarQube.\"\"\"\n \n \n class SonarQubeCollector(SourceCollector):\n \"\"\"Base class for SonarQube collectors.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n # SonarQube sometimes gives results (e.g. zero violations) even if the component does not exist, so we\n # check whether the component specified by the user actually exists before getting the data.\n- url = SourceCollector._api_url(self)\n+ url = await SourceCollector._api_url(self)\n component = self._parameter(\"component\")\n show_component_url = URL(f\"{url}/api/components/show?component={component}\")\n- response = super()._get_source_responses(show_component_url)[0]\n- json = response.json()\n+ response = (await super()._get_source_responses(show_component_url))[0]\n+ json = await response.json()\n if \"errors\" in json:\n- raise Exception(json[\"errors\"][0][\"msg\"])\n- return super()._get_source_responses(api_url)\n+ raise SonarQubeException(json[\"errors\"][0][\"msg\"])\n+ return await super()._get_source_responses(*urls)\n \n \n class SonarQubeViolations(SonarQubeCollector):\n@@ -31,15 +34,15 @@ class SonarQubeViolations(SonarQubeCollector):\n \n rules_parameter = \"\" # Subclass responsibility\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n landing_url = f\"{url}/project/issues?id={component}&resolved=false&branch={branch}\"\n return URL(landing_url + self.__rules_url_parameter())\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n severities = \",\".join([severity.upper() for severity in self._parameter(\"severities\")])\n@@ -55,27 +58,27 @@ def __rules_url_parameter(self) -> str:\n rules = self._parameter(self.rules_parameter) if self.rules_parameter else []\n return f\"&rules={','.join(rules)}\" if rules else \"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n value = 0\n entities: Entities = []\n for response in responses:\n- json = response.json()\n+ json = await response.json()\n value += int(json.get(\"total\", 0))\n- entities.extend([self._entity(issue) for issue in json.get(\"issues\", [])])\n+ entities.extend([await self._entity(issue) for issue in json.get(\"issues\", [])])\n return str(value), \"100\", entities\n \n- def __issue_landing_url(self, issue_key: str) -> URL:\n+ async def __issue_landing_url(self, issue_key: str) -> URL:\n \"\"\"Generate a landing url for the issue.\"\"\"\n- url = super()._landing_url([])\n+ url = await super()._landing_url([])\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/project/issues?id={component}&issues={issue_key}&open={issue_key}&branch={branch}\")\n \n- def _entity(self, issue) -> Entity:\n+ async def _entity(self, issue) -> Entity:\n \"\"\"Create an entity from an issue.\"\"\"\n return dict(\n key=issue[\"key\"],\n- url=self.__issue_landing_url(issue[\"key\"]),\n+ url=await self.__issue_landing_url(issue[\"key\"]),\n message=issue[\"message\"],\n severity=issue[\"severity\"].lower(),\n type=issue[\"type\"].lower(),\n@@ -97,23 +100,21 @@ class SonarQubeViolationsWithPercentageScale(SonarQubeViolations):\n \n total_metric = \"\" # Subclass responsibility\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Next to the violations, also get the total number of units as basis for the percentage scale.\"\"\"\n- responses = super()._get_source_responses(api_url)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n- base_api_url = SonarQubeCollector._api_url(self) # pylint: disable=protected-access\n+ base_api_url = await SonarQubeCollector._api_url(self) # pylint: disable=protected-access\n total_metric_api_url = URL(\n f\"{base_api_url}/api/measures/component?component={component}&metricKeys={self.total_metric}&\"\n f\"branch={branch}\")\n- return responses + [\n- requests.get(total_metric_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())]\n+ return await super()._get_source_responses(*(urls + (total_metric_api_url,)))\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value, _, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value, _, entities = await super()._parse_source_responses(responses)\n measures: List[Dict[str, str]] = []\n for response in responses:\n- measures.extend(response.json().get(\"component\", {}).get(\"measures\", []))\n+ measures.extend((await response.json()).get(\"component\", {}).get(\"measures\", []))\n return value, str(sum(int(measure[\"value\"]) for measure in measures)), entities\n \n \n@@ -143,26 +144,23 @@ class SonarQubeSuppressedViolations(SonarQubeViolations):\n \n rules_parameter = \"suppression_rules\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"In addition to the suppressed rules, also get issues closed as false positive and won't fix from SonarQube\n as well as the total number of violations.\"\"\"\n- responses = super()._get_source_responses(api_url)\n- url = SourceCollector._api_url(self) # pylint: disable=protected-access\n+ url = await SourceCollector._api_url(self) # pylint: disable=protected-access\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n all_issues_api_url = URL(f\"{url}/api/issues/search?componentKeys={component}&branch={branch}\")\n resolved_issues_api_url = URL(f\"{all_issues_api_url}&status=RESOLVED&resolutions=WONTFIX,FALSE-POSITIVE&ps=500\")\n- for issues_api_url in (resolved_issues_api_url, all_issues_api_url):\n- responses.append(requests.get(issues_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials()))\n- return responses\n+ return await super()._get_source_responses(*(urls + (resolved_issues_api_url, all_issues_api_url)))\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value, _, entities = super()._parse_source_responses(responses[:-1])\n- return value, str(responses[-1].json()[\"total\"]), entities\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value, _, entities = await super()._parse_source_responses(responses[:-1])\n+ return value, str((await responses[-1].json())[\"total\"]), entities\n \n- def _entity(self, issue) -> Entity:\n+ async def _entity(self, issue) -> Entity:\n \"\"\"Also add the resolution to the entity.\"\"\"\n- entity = super()._entity(issue)\n+ entity = await super()._entity(issue)\n resolution = issue.get(\"resolution\", \"\").lower()\n entity[\"resolution\"] = dict(wontfix=\"won't fix\").get(resolution, resolution)\n return entity\n@@ -175,23 +173,23 @@ class SonarQubeMetricsBaseClass(SonarQubeCollector):\n # the metric value, the second for the total value (used for calculating a percentage).\n metricKeys = \"\" # Subclass responsibility\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n metric = self._metric_keys().split(\",\")[0]\n return URL(f\"{url}/component_measures?id={component}&metric={metric}&branch={branch}\")\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(\n f\"{url}/api/measures/component?component={component}&metricKeys={self._metric_keys()}&branch={branch}\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n metric_keys = self._metric_keys().split(\",\")\n- metrics = self.__get_metrics(responses)\n+ metrics = await self.__get_metrics(responses)\n value = str(metrics[metric_keys[0]])\n total = str(metrics[metric_keys[1]]) if len(metric_keys) > 1 else \"100\"\n return value, total, []\n@@ -201,10 +199,13 @@ def _metric_keys(self) -> str:\n return self.metricKeys\n \n @staticmethod\n- def __get_metrics(responses: Responses) -> Dict[str, int]:\n+ async def __get_metrics(responses: Responses) -> Dict[str, int]:\n \"\"\"Get the metric(s) from the responses.\"\"\"\n- measures = responses[0].json()[\"component\"][\"measures\"]\n- return dict((measure[\"metric\"], int(measure[\"value\"])) for measure in measures)\n+ measures = (await responses[0].json())[\"component\"][\"measures\"]\n+ # Without the local variable, coverage.py thinks: \"line xyz didn't return from function '__get_metrics',\n+ # because the return on line xyz wasn't executed\"\n+ metrics = dict((measure[\"metric\"], int(measure[\"value\"])) for measure in measures)\n+ return metrics\n \n \n class SonarQubeDuplicatedLines(SonarQubeMetricsBaseClass):\n@@ -235,31 +236,32 @@ class SonarQubeUncoveredBranches(SonarQubeMetricsBaseClass):\n class SonarQubeTests(SonarQubeCollector):\n \"\"\"SonarQube collector for the tests metric.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n metric_keys = \"tests,test_errors,test_failures,skipped_tests\"\n return URL(f\"{url}/api/measures/component?component={component}&metricKeys={metric_keys}&branch={branch}\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/component_measures?id={component}&metric=tests&branch={branch}\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- tests = self.__nr_of_tests(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ tests = await self.__nr_of_tests(responses)\n value = str(sum(tests[test_result] for test_result in self._parameter(\"test_result\")))\n test_results = self._datamodel[\"sources\"][self.source_type][\"parameters\"][\"test_result\"][\"values\"]\n total = str(sum(tests[test_result] for test_result in test_results))\n return value, total, []\n \n @staticmethod\n- def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n+ async def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n \"\"\"Return the number of tests by test result.\"\"\"\n measures = dict(\n- (measure[\"metric\"], int(measure[\"value\"])) for measure in responses[0].json()[\"component\"][\"measures\"])\n+ (measure[\"metric\"], int(measure[\"value\"]))\n+ for measure in (await responses[0].json())[\"component\"][\"measures\"])\n errored = measures.get(\"test_errors\", 0)\n failed = measures.get(\"test_failures\", 0)\n skipped = measures.get(\"skipped_tests\", 0)\n@@ -270,17 +272,17 @@ def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n class SonarQubeSourceUpToDateness(SonarQubeCollector, SourceUpToDatenessCollector):\n \"\"\"SonarQube source up-to-dateness.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/api/project_analyses/search?project={component}&branch={branch}\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/project/activity?id={component}&branch={branch}\")\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return isoparse(response.json()[\"analyses\"][0][\"date\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return isoparse((await response.json())[\"analyses\"][0][\"date\"])\ndiff --git a/components/collector/src/source_collectors/trello.py b/components/collector/src/source_collectors/api_source_collectors/trello.py\nsimilarity index 75%\nrename from components/collector/src/source_collectors/trello.py\nrename to components/collector/src/source_collectors/api_source_collectors/trello.py\n--- a/components/collector/src/source_collectors/trello.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/trello.py\n@@ -5,44 +5,43 @@\n from typing import cast, Tuple\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Response, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector\n \n \n class TrelloBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Trello collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(responses[0].json()[\"url\"] if responses else \"https://trello.com\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL((await responses[0].json())[\"url\"] if responses else \"https://trello.com\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n- api = f\"1/boards/{self.__board_id()}?fields=id,url,dateLastActivity&lists=open&\" \\\n+ api = f\"1/boards/{await self.__board_id()}?fields=id,url,dateLastActivity&lists=open&\" \\\n \"list_fields=name&cards=visible&card_fields=name,dateLastActivity,due,idList,url\"\n- return [requests.get(self.__url_with_auth(api), timeout=self.TIMEOUT)]\n+ return await super()._get_source_responses(await self.__url_with_auth(api))\n \n- def __board_id(self) -> str:\n+ async def __board_id(self) -> str:\n \"\"\"Return the id of the board specified by the user.\"\"\"\n- url = self.__url_with_auth(\"1/members/me/boards?fields=name\")\n- boards = requests.get(url, timeout=self.TIMEOUT).json()\n+ url = await self.__url_with_auth(\"1/members/me/boards?fields=name\")\n+ boards = await (await super()._get_source_responses(url))[0].json()\n return str([board for board in boards if self._parameter(\"board\") in board.values()][0][\"id\"])\n \n- def __url_with_auth(self, api_part: str) -> str:\n+ async def __url_with_auth(self, api_part: str) -> URL:\n \"\"\"Return the authentication URL parameters.\"\"\"\n sep = \"&\" if \"?\" in api_part else \"?\"\n api_key = self._parameter(\"api_key\")\n token = self._parameter(\"token\")\n- return f\"{self._api_url()}/{api_part}{sep}key={api_key}&token={token}\"\n+ return URL(f\"{await self._api_url()}/{api_part}{sep}key={api_key}&token={token}\")\n \n \n class TrelloIssues(TrelloBase):\n \"\"\"Collector to get issues (cards) from Trello.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n cards = json[\"cards\"]\n lists = {lst[\"id\"]: lst[\"name\"] for lst in json[\"lists\"]}\n entities = [self.__card_to_entity(card, lists) for card in cards if not self.__ignore_card(card, lists)]\n@@ -82,8 +81,8 @@ def __card_to_entity(card, lists) -> Entity:\n class TrelloSourceUpToDateness(TrelloBase, SourceUpToDatenessCollector):\n \"\"\"Collector to measure how up-to-date a Trello board is.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- json = response.json()\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ json = await response.json()\n cards = json[\"cards\"]\n lists = {lst[\"id\"]: lst[\"name\"] for lst in json[\"lists\"]}\n dates = [json[\"dateLastActivity\"]] + \\\ndiff --git a/components/collector/src/source_collectors/wekan.py b/components/collector/src/source_collectors/api_source_collectors/wekan.py\nsimilarity index 52%\nrename from components/collector/src/source_collectors/wekan.py\nrename to components/collector/src/source_collectors/api_source_collectors/wekan.py\n--- a/components/collector/src/source_collectors/wekan.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/wekan.py\n@@ -4,48 +4,71 @@\n from datetime import datetime\n from typing import cast, Dict, List, Tuple\n \n-import cachetools.func\n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n+\n+\n+WekanCard = Dict[str, str]\n+WekanBoard = Dict[str, str]\n+WekanList = Dict[str, str]\n \n \n class WekanBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Wekan collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- api_url = self._api_url()\n- return URL(f\"{api_url}/b/{self._board_id(responses[0].json()['token'])}\") if responses else api_url\n+ def __init__(self, *args, **kwargs) -> None:\n+ self.__token = \"\"\n+ self._board: WekanBoard = {}\n+ self._board_url = \"\"\n+ self._lists: List[WekanList] = []\n+ self._cards: Dict[str, List[WekanCard]] = {}\n+ super().__init__(*args, **kwargs)\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Override because we want to do a post request to login.\"\"\"\n- credentials = dict(username=self._parameter(\"username\"), password=self._parameter(\"password\"))\n- return [requests.post(f\"{api_url}/users/login\", data=credentials, timeout=self.TIMEOUT)]\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ api_url = await self._api_url()\n+ return URL(f\"{api_url}/b/{self._board['_id']}\") if responses else api_url\n \n- def _board_id(self, token) -> str:\n- \"\"\"Return the id of the board specified by the user.\"\"\"\n- api_url = self._api_url()\n- user_id = self._get_json(URL(f\"{api_url}/api/user\"), token)[\"_id\"]\n- boards = self._get_json(URL(f\"{api_url}/api/users/{user_id}/boards\"), token)\n- return str([board for board in boards if self._parameter(\"board\") in board.values()][0][\"_id\"])\n+ def _headers(self) -> Dict[str, str]:\n+ return dict(Authorization=f\"Bearer {self.__token}\")\n \n- def _lists(self, board_url: str, token: str) -> List:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Override because we want to do a post request to login.\"\"\"\n+ credentials = dict(username=self._parameter(\"username\"), password=self._parameter(\"password\"))\n+ response = await self._session.post(f\"{urls[0]}/users/login\", data=credentials)\n+ self.__token = (await response.json())[\"token\"]\n+ await self.__get_board()\n+ await self.__get_lists()\n+ await self.__get_cards()\n+ return [response]\n+\n+ async def __get_board(self) -> None:\n+ \"\"\"Return the board specified by the user.\"\"\"\n+ api_url = await self._api_url()\n+ user_id = (await self._get_json(URL(f\"{api_url}/api/user\")))[\"_id\"]\n+ boards = await self._get_json(URL(f\"{api_url}/api/users/{user_id}/boards\"))\n+ self._board = [board for board in boards if self._parameter(\"board\") in board.values()][0]\n+ self._board_url = f\"{api_url}/api/boards/{self._board['_id']}\"\n+\n+ async def __get_lists(self) -> None:\n \"\"\"Return the lists on the board.\"\"\"\n- return [lst for lst in self._get_json(URL(f\"{board_url}/lists\"), token) if not self.__ignore_list(lst)]\n-\n- def _cards(self, list_url: str, token: str) -> List:\n- \"\"\"Return the cards on the board.\"\"\"\n- cards = self._get_json(URL(f\"{list_url}/cards\"), token)\n- full_cards = [self._get_json(URL(f\"{list_url}/cards/{card['_id']}\"), token) for card in cards]\n- return [card for card in full_cards if not self._ignore_card(card)]\n-\n- @cachetools.func.ttl_cache(ttl=60)\n- def _get_json(self, api_url: URL, token: str):\n+ self._lists = [\n+ lst for lst in await self._get_json(URL(f\"{self._board_url}/lists\"))\n+ if not self.__ignore_list(lst)]\n+\n+ async def __get_cards(self) -> None:\n+ \"\"\"Get the cards for the list.\"\"\"\n+ for lst in self._lists:\n+ list_url = f\"{self._board_url}/lists/{lst['_id']}\"\n+ cards = await self._get_json(URL(f\"{list_url}/cards\"))\n+ full_cards = [await self._get_json(URL(f\"{list_url}/cards/{card['_id']}\")) for card in cards]\n+ self._cards[lst[\"_id\"]] = [card for card in full_cards if not self._ignore_card(card)]\n+\n+ async def _get_json(self, api_url: URL):\n \"\"\"Get the JSON from the API url.\"\"\"\n- return requests.get(api_url, timeout=self.TIMEOUT, headers=dict(Authorization=f\"Bearer {token}\")).json()\n+ return await (await super()._get_source_responses(api_url))[0].json()\n \n def __ignore_list(self, card_list) -> bool:\n \"\"\"Return whether the list should be ignored.\"\"\"\n@@ -62,14 +85,12 @@ def _ignore_card(self, card: Dict) -> bool: # pylint: disable=unused-argument,n\n class WekanIssues(WekanBase):\n \"\"\"Collector to get issues (cards) from Wekan.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- token = responses[0].json()['token']\n- api_url = self._api_url()\n- board_url = f\"{api_url}/api/boards/{self._board_id(token)}\"\n- board_slug = self._get_json(URL(board_url), token)[\"slug\"]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ api_url = await self._api_url()\n+ board_slug = self._board[\"slug\"]\n entities: Entities = []\n- for lst in self._lists(board_url, token):\n- for card in self._cards(f\"{board_url}/lists/{lst['_id']}\", token):\n+ for lst in self._lists:\n+ for card in self._cards.get(lst[\"_id\"], []):\n entities.append(self.__card_to_entity(card, api_url, board_slug, lst[\"title\"]))\n return str(len(entities)), \"100\", entities\n \n@@ -105,13 +126,9 @@ def __card_to_entity(card, api_url: URL, board_slug: str, list_title: str) -> En\n class WekanSourceUpToDateness(WekanBase):\n \"\"\"Collector to measure how up-to-date a Wekan board is.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- token = responses[0].json()['token']\n- board_url = f\"{self._api_url()}/api/boards/{self._board_id(token)}\"\n- board = self._get_json(URL(board_url), token)\n- dates = [board.get(\"createdAt\"), board.get(\"modifiedAt\")]\n- for lst in self._lists(board_url, token):\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ dates = [self._board.get(\"createdAt\"), self._board.get(\"modifiedAt\")]\n+ for lst in self._lists:\n dates.extend([lst.get(\"createdAt\"), lst.get(\"updatedAt\")])\n- list_url = f\"{board_url}/lists/{lst['_id']}\"\n- dates.extend([card[\"dateLastActivity\"] for card in self._cards(list_url, token)])\n+ dates.extend([card[\"dateLastActivity\"] for card in self._cards.get(lst[\"_id\"], [])])\n return str(days_ago(parse(max([date for date in dates if date])))), \"100\", []\ndiff --git a/components/collector/src/source_collectors/cxsast.py b/components/collector/src/source_collectors/cxsast.py\ndeleted file mode 100644\n--- a/components/collector/src/source_collectors/cxsast.py\n+++ /dev/null\n@@ -1,93 +0,0 @@\n-\"\"\"Collectors for the Checkmarx CxSAST product.\"\"\"\n-\n-from abc import ABC\n-from typing import cast, Final, Tuple\n-\n-from dateutil.parser import parse\n-import requests\n-\n-from collector_utilities.type import Entities, Response, Responses, URL, Value\n-from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n-\n-\n-class CxSASTBase(SourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for CxSAST collectors.\"\"\"\n-\n- TOKEN_RESPONSE: Final[int] = 0\n- PROJECT_RESPONSE: Final[int] = 1\n- SCAN_RESPONSE: Final[int] = 2\n-\n- def _landing_url(self, responses: Responses) -> URL:\n- api_url = self._api_url()\n- if len(responses) > self.SCAN_RESPONSE:\n- project_id = self.__project_id(responses[self.PROJECT_RESPONSE])\n- scan_id = self._scan_id(responses)\n- return URL(f\"{api_url}/CxWebClient/ViewerMain.aspx?scanId={scan_id}&ProjectID={project_id}\")\n- return api_url\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n- # See https://checkmarx.atlassian.net/wiki/spaces/KC/pages/1187774721/Using+the+CxSAST+REST+API+v8.6.0+and+up\n- credentials = dict( # nosec, The client secret is not really secret, see previous url\n- username=cast(str, self._parameter(\"username\")),\n- password=cast(str, self._parameter(\"password\")),\n- grant_type=\"password\", scope=\"sast_rest_api\", client_id=\"resource_owner_client\",\n- client_secret=\"014DF517-39D1-4453-B7B3-9930C563627C\")\n- token_response = self._api_post(\"auth/identity/connect/token\", credentials)\n- token = token_response.json()['access_token']\n- project_response = self._api_get(f\"projects\", token)\n- project_id = self.__project_id(project_response)\n- scan_response = self._api_get(f\"sast/scans?projectId={project_id}&scanStatus=Finished&last=1\", token)\n- return [token_response, project_response, scan_response]\n-\n- def __project_id(self, project_response: Response) -> str:\n- \"\"\"Return the project id that belongs to the project parameter.\"\"\"\n- project_name_or_id = self._parameter(\"project\")\n- projects = project_response.json()\n- return str([project for project in projects if project_name_or_id in (project[\"name\"], project[\"id\"])][0][\"id\"])\n-\n- def _scan_id(self, responses: Responses) -> str:\n- \"\"\"Return the scan id.\"\"\"\n- return str(responses[self.SCAN_RESPONSE].json()[0][\"id\"])\n-\n- def _api_get(self, api: str, token: str) -> Response:\n- \"\"\"Open the API and return the response.\"\"\"\n- response = requests.get(\n- f\"{self._api_url()}/cxrestapi/{api}\", headers=dict(Authorization=f\"Bearer {token}\"), timeout=self.TIMEOUT)\n- response.raise_for_status()\n- return response\n-\n- def _api_post(self, api: str, data, token: str = None) -> Response:\n- \"\"\"Post to the API and return the response.\"\"\"\n- headers = dict(Authorization=f\"Bearer {token}\") if token else dict()\n- response = requests.post(f\"{self._api_url()}/cxrestapi/{api}\", data=data, headers=headers, timeout=self.TIMEOUT)\n- response.raise_for_status()\n- return response\n-\n-\n-class CxSASTSourceUpToDateness(CxSASTBase):\n- \"\"\"Collector class to measure the up-to-dateness of a Checkmarx CxSAST scan.\"\"\"\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- scan = responses[self.SCAN_RESPONSE].json()[0]\n- return str(days_ago(parse(scan[\"dateAndTime\"][\"finishedOn\"]))), \"100\", []\n-\n-\n-class CxSASTSecurityWarnings(CxSASTBase):\n- \"\"\"Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.\"\"\"\n-\n- STATS_RESPONSE = 3\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- token = responses[self.TOKEN_RESPONSE].json()[\"access_token\"]\n- scan_id = self._scan_id(responses)\n- # Get the statistics of the last scan; this is a single API call:\n- responses.append(self._api_get(f\"sast/scans/{scan_id}/resultsStatistics\", token))\n- return responses\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- stats = responses[self.STATS_RESPONSE].json()\n- severities = self._parameter(\"severities\")\n- return str(sum(stats.get(f\"{severity.lower()}Severity\", 0) for severity in severities)), \"100\", []\ndiff --git a/components/collector/src/source_collectors/file_source_collectors/__init__.py b/components/collector/src/source_collectors/file_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/src/source_collectors/anchore.py b/components/collector/src/source_collectors/file_source_collectors/anchore.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/anchore.py\nrename to components/collector/src/source_collectors/file_source_collectors/anchore.py\n--- a/components/collector/src/source_collectors/anchore.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/anchore.py\n@@ -7,17 +7,17 @@\n \n from collector_utilities.functions import md5_hash\n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import JSONFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JSONFileSourceCollector, SourceUpToDatenessCollector\n \n \n class AnchoreSecurityWarnings(JSONFileSourceCollector):\n \"\"\"Anchore collector for security warnings.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = self._parameter(\"severities\")\n entities = []\n for response in responses:\n- json = response.json()\n+ json = await response.json()\n vulnerabilities = json.get(\"vulnerabilities\", []) if isinstance(json, dict) else []\n entities.extend([\n dict(\n@@ -36,7 +36,7 @@ class AnchoreSourceUpToDateness(JSONFileSourceCollector, SourceUpToDatenessColle\n \n API_URL_PARAMETER_KEY = \"details_url\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- details = response.json()\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ details = await response.json()\n return parse(details[0][\"analyzed_at\"]) \\\n if isinstance(details, list) and details and \"analyzed_at\" in details[0] else datetime.now(timezone.utc)\ndiff --git a/components/collector/src/source_collectors/axe_csv.py b/components/collector/src/source_collectors/file_source_collectors/axe_csv.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/axe_csv.py\nrename to components/collector/src/source_collectors/file_source_collectors/axe_csv.py\n--- a/components/collector/src/source_collectors/axe_csv.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/axe_csv.py\n@@ -6,32 +6,30 @@\n from typing import Dict, List, Tuple\n \n from collector_utilities.functions import md5_hash\n-from collector_utilities.type import Responses, Value, Entities\n-from .source_collector import FileSourceCollector\n+from collector_utilities.type import Entities, Responses, Value\n+from base_collectors import CSVFileSourceCollector\n \n \n-class AxeCSVAccessibility(FileSourceCollector):\n+class AxeCSVAccessibility(CSVFileSourceCollector):\n \"\"\"Collector class to get accessibility violations.\"\"\"\n \n- file_extensions = [\"csv\"]\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = [\n dict(\n url=str(row[\"URL\"]), violation_type=row[\"Violation Type\"], impact=row[\"Impact\"],\n element=row[\"DOM Element\"], page=re.sub(r'http[s]?://[^/]+', '', row['URL']),\n description=row[\"Messages\"], help=row[\"Help\"])\n- for row in self.__parse_csv(responses)]\n+ for row in await self.__parse_csv(responses)]\n for entity in entities:\n entity[\"key\"] = md5_hash(\",\".join(str(value) for value in entity.values()))\n return str(len(entities)), \"100\", entities\n \n- def __parse_csv(self, responses: Responses) -> List[Dict[str, str]]:\n+ async def __parse_csv(self, responses: Responses) -> List[Dict[str, str]]:\n \"\"\"Parse the CSV and return the rows and parsed items .\"\"\"\n impact_levels = self._parameter(\"impact\")\n violation_types = self._parameter(\"violation_type\")\n rows = []\n for response in responses:\n- csv_text = response.text.strip()\n+ csv_text = (await response.text()).strip()\n rows.extend(list(csv.DictReader(StringIO(csv_text, newline=\"\"))))\n return [row for row in rows if row[\"Impact\"] in impact_levels and row[\"Violation Type\"] in violation_types]\ndiff --git a/components/collector/src/source_collectors/bandit.py b/components/collector/src/source_collectors/file_source_collectors/bandit.py\nsimilarity index 72%\nrename from components/collector/src/source_collectors/bandit.py\nrename to components/collector/src/source_collectors/file_source_collectors/bandit.py\n--- a/components/collector/src/source_collectors/bandit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/bandit.py\n@@ -6,13 +6,13 @@\n from dateutil.parser import parse\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import JSONFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JSONFileSourceCollector, SourceUpToDatenessCollector\n \n \n class BanditSecurityWarnings(JSONFileSourceCollector):\n \"\"\"Bandit collector for security warnings.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = self._parameter(\"severities\")\n confidence_levels = self._parameter(\"confidence_levels\")\n entities = []\n@@ -25,7 +25,8 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n issue_severity=warning[\"issue_severity\"].capitalize(),\n issue_confidence=warning[\"issue_confidence\"].capitalize(),\n more_info=warning[\"more_info\"])\n- for warning in response.json().get(\"results\", []) if warning[\"issue_severity\"].lower() in severities\n+ for warning in (await response.json()).get(\"results\", [])\n+ if warning[\"issue_severity\"].lower() in severities\n and warning[\"issue_confidence\"].lower() in confidence_levels])\n return str(len(entities)), \"100\", entities\n \n@@ -33,5 +34,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class BanditSourceUpToDateness(JSONFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Bandit collector for source up-to-dateness.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(response.json()[\"generated_at\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await response.json())[\"generated_at\"])\ndiff --git a/components/collector/src/source_collectors/composer.py b/components/collector/src/source_collectors/file_source_collectors/composer.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/composer.py\nrename to components/collector/src/source_collectors/file_source_collectors/composer.py\n--- a/components/collector/src/source_collectors/composer.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/composer.py\n@@ -3,17 +3,17 @@\n from typing import Dict, List, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import JSONFileSourceCollector\n+from base_collectors import JSONFileSourceCollector\n \n \n class ComposerDependencies(JSONFileSourceCollector):\n \"\"\"Composer collector for dependencies.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n statuses = self._parameter(\"latest_version_status\")\n installed_dependencies: List[Dict[str, str]] = []\n for response in responses:\n- installed_dependencies.extend(response.json().get(\"installed\", []))\n+ installed_dependencies.extend((await response.json()).get(\"installed\", []))\n entities: Entities = [\n dict(\n key=f'{dependency[\"name\"]}@{dependency.get(\"version\", \"?\")}',\ndiff --git a/components/collector/src/source_collectors/jacoco.py b/components/collector/src/source_collectors/file_source_collectors/jacoco.py\nsimilarity index 78%\nrename from components/collector/src/source_collectors/jacoco.py\nrename to components/collector/src/source_collectors/file_source_collectors/jacoco.py\n--- a/components/collector/src/source_collectors/jacoco.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/jacoco.py\n@@ -6,7 +6,7 @@\n from defusedxml import ElementTree\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class JacocoCoverageBaseClass(XMLFileSourceCollector):\n@@ -14,10 +14,10 @@ class JacocoCoverageBaseClass(XMLFileSourceCollector):\n \n coverage_type = \"Subclass responsibility (Jacoco has: line, branch, instruction, complexity, method, class)\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n missed, covered = 0, 0\n for response in responses:\n- tree = ElementTree.fromstring(response.text)\n+ tree = ElementTree.fromstring(await response.text())\n counter = [c for c in tree.findall(\"counter\") if c.get(\"type\").lower() == self.coverage_type][0]\n missed += int(counter.get(\"missed\"))\n covered += int(counter.get(\"covered\"))\n@@ -39,8 +39,8 @@ class JacocoUncoveredBranches(JacocoCoverageBaseClass):\n class JacocoSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Jacoco report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = ElementTree.fromstring(response.text)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = ElementTree.fromstring(await response.text())\n session_info = tree.find(\".//sessioninfo\")\n timestamp = session_info.get(\"dump\") if session_info is not None else \"0\"\n return datetime.utcfromtimestamp(int(timestamp) / 1000.)\ndiff --git a/components/collector/src/source_collectors/junit.py b/components/collector/src/source_collectors/file_source_collectors/junit.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/junit.py\nrename to components/collector/src/source_collectors/file_source_collectors/junit.py\n--- a/components/collector/src/source_collectors/junit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/junit.py\n@@ -7,18 +7,18 @@\n \n from collector_utilities.type import Entity, Entities, Response, Responses, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class JUnitTests(XMLFileSourceCollector):\n \"\"\"Collector for JUnit tests.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = []\n test_statuses_to_count = cast(List[str], self._parameter(\"test_result\"))\n junit_status_nodes = dict(errored=\"error\", failed=\"failure\", skipped=\"skipped\")\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n for test_case in tree.findall(\".//testcase\"):\n for test_result, junit_status_node in junit_status_nodes.items():\n if test_case.find(junit_status_node) is not None:\n@@ -39,7 +39,7 @@ def __entity(case_node, case_result: str) -> Entity:\n class JUnitSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Junit report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = parse_source_response_xml(response)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = await parse_source_response_xml(response)\n test_suite = tree if tree.tag == \"testsuite\" else tree.findall(\"testsuite\")[0]\n return parse(test_suite.get(\"timestamp\", \"\"))\ndiff --git a/components/collector/src/source_collectors/ncover.py b/components/collector/src/source_collectors/file_source_collectors/ncover.py\nsimilarity index 75%\nrename from components/collector/src/source_collectors/ncover.py\nrename to components/collector/src/source_collectors/file_source_collectors/ncover.py\n--- a/components/collector/src/source_collectors/ncover.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/ncover.py\n@@ -9,16 +9,16 @@\n from bs4 import BeautifulSoup\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import HTMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import HTMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class NCoverBase(HTMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for NCover collectors.\"\"\"\n \n @staticmethod\n- def _find_script(response: Response, text: str) -> str:\n+ async def _find_script(response: Response, text: str) -> str:\n \"\"\"Return the script containing the text.\"\"\"\n- for script in BeautifulSoup(response.text, \"html.parser\").find_all(\"script\", type=\"text/javascript\"):\n+ for script in BeautifulSoup(await response.text(), \"html.parser\").find_all(\"script\", type=\"text/javascript\"):\n if text in script.string:\n return str(script.string)\n return \"\" # pragma: nocover\n@@ -29,10 +29,10 @@ class NCoverCoverageBase(NCoverBase, ABC): # pylint: disable=abstract-method\n \n coverage_type = \"Subclass responsibility\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n covered, total = 0, 0\n for response in responses:\n- script = self._find_script(response, \"ncover.execution.stats = \")\n+ script = await self._find_script(response, \"ncover.execution.stats = \")\n json_string = script.strip()[len('ncover.execution.stats = '):].strip(\";\")\n coverage = json.loads(json_string)[f\"{self.coverage_type}Coverage\"]\n covered += int(coverage[\"coveredPoints\"])\n@@ -56,8 +56,8 @@ class NCoverUncoveredBranches(NCoverCoverageBase):\n class NCoverSourceUpToDateness(NCoverBase, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the NCover report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- script = self._find_script(response, \"ncover.createDateTime\")\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ script = await self._find_script(response, \"ncover.createDateTime\")\n match = re.search(r\"ncover\\.createDateTime = '(\\d+)'\", script)\n timestamp = match.group(1) if match else \"\"\n return datetime.fromtimestamp(float(timestamp) / 1000)\ndiff --git a/components/collector/src/source_collectors/ojaudit.py b/components/collector/src/source_collectors/file_source_collectors/ojaudit.py\nsimilarity index 93%\nrename from components/collector/src/source_collectors/ojaudit.py\nrename to components/collector/src/source_collectors/file_source_collectors/ojaudit.py\n--- a/components/collector/src/source_collectors/ojaudit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/ojaudit.py\n@@ -5,7 +5,7 @@\n \n from collector_utilities.type import Namespaces, Entities, Entity, Responses, Value\n from collector_utilities.functions import sha1_hash, parse_source_response_xml_with_namespace\n-from .source_collector import XMLFileSourceCollector\n+from base_collectors import XMLFileSourceCollector\n \n \n ModelFilePaths = Dict[str, str] # Model id to model file path mapping\n@@ -18,12 +18,12 @@ def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.violation_counts: Dict[str, int] = dict() # Keep track of the number of duplicated violations per key\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = cast(List[str], self._parameter(\"severities\"))\n count = 0\n entities = []\n for response in responses:\n- tree, namespaces = parse_source_response_xml_with_namespace(response)\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response)\n entities.extend(self.__violations(tree, namespaces, severities))\n for severity in severities:\n count += int(tree.findtext(f\"./ns:{severity}-count\", default=\"0\", namespaces=namespaces))\ndiff --git a/components/collector/src/source_collectors/openvas.py b/components/collector/src/source_collectors/file_source_collectors/openvas.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/openvas.py\nrename to components/collector/src/source_collectors/file_source_collectors/openvas.py\n--- a/components/collector/src/source_collectors/openvas.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/openvas.py\n@@ -8,17 +8,17 @@\n \n from collector_utilities.type import Entities, Response, Responses, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OpenVASSecurityWarnings(XMLFileSourceCollector):\n \"\"\"Collector to get security warnings from OpenVAS.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = []\n severities = cast(List[str], self._parameter(\"severities\"))\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n entities.extend(\n [dict(key=result.attrib[\"id\"], name=result.findtext(\"name\", default=\"\"),\n description=result.findtext(\"description\", default=\"\"),\n@@ -37,6 +37,6 @@ def __results(element: Element, severities: List[str]) -> List[Element]:\n class OpenVASSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OpenVAS report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = parse_source_response_xml(response)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = await parse_source_response_xml(response)\n return isoparse(tree.findtext(\"creation_time\", default=\"\"))\ndiff --git a/components/collector/src/source_collectors/owasp_dependency_check.py b/components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/owasp_dependency_check.py\nrename to components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\n--- a/components/collector/src/source_collectors/owasp_dependency_check.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\n@@ -7,9 +7,9 @@\n \n from dateutil.parser import isoparse\n \n-from collector_utilities.type import Namespaces, Entity, Entities, Response, Responses, URL, Value\n+from collector_utilities.type import Namespaces, Entity, Entities, Response, Responses, Value\n from collector_utilities.functions import sha1_hash, parse_source_response_xml_with_namespace\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OWASPDependencyCheckBase(XMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n@@ -18,22 +18,15 @@ class OWASPDependencyCheckBase(XMLFileSourceCollector, ABC): # pylint: disable=\n allowed_root_tags = [f\"{{https://jeremylong.github.io/DependencyCheck/dependency-check.{version}.xsd}}analysis\"\n for version in (\"2.0\", \"2.1\", \"2.2\")]\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- for response in responses:\n- if not response.encoding:\n- response.encoding = \"utf-8\" # Assume UTF-8, detecting encoding on large XML files is very slow.\n- return responses\n-\n \n class OWASPDependencyCheckSecurityWarnings(OWASPDependencyCheckBase):\n \"\"\"Collector to get security warnings from OWASP Dependency Check.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- landing_url = self._landing_url(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ landing_url = await self._landing_url(responses)\n entities = []\n for response in responses:\n- tree, namespaces = parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n entities.extend(\n [self.__parse_entity(dependency, index, namespaces, landing_url) for (index, dependency)\n in self.__vulnerable_dependencies(tree, namespaces)])\n@@ -75,6 +68,6 @@ def __vulnerabilities(self, element: Element, namespaces: Namespaces) -> List[El\n class OWASPDependencyCheckSourceUpToDateness(OWASPDependencyCheckBase, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OWASP Dependency Check report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree, namespaces = parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n return isoparse(tree.findtext(\".//ns:reportDate\", default=\"\", namespaces=namespaces))\ndiff --git a/components/collector/src/source_collectors/owasp_zap.py b/components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/owasp_zap.py\nrename to components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\n--- a/components/collector/src/source_collectors/owasp_zap.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\n@@ -9,17 +9,17 @@\n \n from collector_utilities.functions import hashless, md5_hash, parse_source_response_xml\n from collector_utilities.type import Entities, Entity, Response, Responses, URL, Value\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OWASPZAPSecurityWarnings(XMLFileSourceCollector):\n \"\"\"Collector to get security warnings from OWASP ZAP.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Dict[str, Entity] = {}\n tag_re = re.compile(r\"<[^>]*>\")\n risks = cast(List[str], self._parameter(\"risks\"))\n- for alert in self.__alerts(responses, risks):\n+ for alert in await self.__alerts(responses, risks):\n alert_key = \":\".join(\n [alert.findtext(id_tag, default=\"\") for id_tag in (\"pluginid\", \"cweid\", \"wascid\", \"sourceid\")])\n name = alert.findtext(\"name\", default=\"\")\n@@ -42,11 +42,11 @@ def __stable(self, url: URL) -> URL:\n return URL(stable_url)\n \n @staticmethod\n- def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n+ async def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n \"\"\"Return a list of the alerts with one of the specified risk levels.\"\"\"\n alerts = []\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n for risk in risks:\n alerts.extend(tree.findall(f\".//alertitem[riskcode='{risk}']\"))\n return alerts\n@@ -55,5 +55,5 @@ def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n class OWASPZAPSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OWASP ZAP report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(parse_source_response_xml(response).get(\"generated\", \"\"))\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await parse_source_response_xml(response)).get(\"generated\", \"\"))\ndiff --git a/components/collector/src/source_collectors/performancetest_runner.py b/components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\nsimilarity index 67%\nrename from components/collector/src/source_collectors/performancetest_runner.py\nrename to components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\n--- a/components/collector/src/source_collectors/performancetest_runner.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\n@@ -7,23 +7,23 @@\n from bs4 import BeautifulSoup, Tag\n \n from collector_utilities.type import Entities, Entity, Response, Responses, Value\n-from .source_collector import HTMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import HTMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class PerformanceTestRunnerBaseClass(HTMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for performance test runner collectors.\"\"\"\n \n @staticmethod\n- def _soup(response: Response):\n+ async def _soup(response: Response):\n \"\"\"Return the HTML soup.\"\"\"\n- return BeautifulSoup(response.text, \"html.parser\")\n+ return BeautifulSoup(await response.text(), \"html.parser\")\n \n \n class PerformanceTestRunnerSlowTransactions(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the number of slow transactions in a Performancetest-runner performance test report.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- entities = [self.__entity(transaction) for transaction in self.__slow_transactions(responses)]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ entities = [self.__entity(transaction) for transaction in await self.__slow_transactions(responses)]\n return str(len(entities)), \"100\", entities\n \n @staticmethod\n@@ -33,12 +33,12 @@ def __entity(transaction) -> Entity:\n threshold = \"high\" if transaction.select(\"td.red.evaluated\") else \"warning\"\n return dict(key=name, name=name, threshold=threshold)\n \n- def __slow_transactions(self, responses: Responses) -> List[Tag]:\n+ async def __slow_transactions(self, responses: Responses) -> List[Tag]:\n \"\"\"Return the slow transactions in the performance test report.\"\"\"\n thresholds = self._parameter(\"thresholds\")\n slow_transactions: List[Tag] = []\n for response in responses:\n- soup = self._soup(response)\n+ soup = await self._soup(response)\n for color in thresholds:\n slow_transactions.extend(soup.select(f\"tr.transaction:has(> td.{color}.evaluated)\"))\n return slow_transactions\n@@ -47,19 +47,20 @@ def __slow_transactions(self, responses: Responses) -> List[Tag]:\n class PerformanceTestRunnerSourceUpToDateness(PerformanceTestRunnerBaseClass, SourceUpToDatenessCollector):\n \"\"\"Collector for the performance test report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- datetime_parts = [int(part) for part in self._soup(response).find(id=\"start_of_the_test\").string.split(\".\")]\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ datetime_parts = [\n+ int(part) for part in (await self._soup(response)).find(id=\"start_of_the_test\").string.split(\".\")]\n return datetime(*datetime_parts) # type: ignore\n \n \n class PerformanceTestRunnerPerformanceTestDuration(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the performance test duration.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n durations = []\n for response in responses:\n hours, minutes, seconds = [\n- int(part) for part in self._soup(response).find(id=\"duration\").string.split(\":\", 2)]\n+ int(part) for part in (await self._soup(response)).find(id=\"duration\").string.split(\":\", 2)]\n durations.append(60 * hours + minutes + round(seconds / 60.))\n return str(sum(durations)), \"100\", []\n \n@@ -67,31 +68,31 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class PerformanceTestRunnerPerformanceTestStability(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the performance test stability.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n trend_breaks = []\n for response in responses:\n- trend_breaks.append(int(self._soup(response).find(id=\"trendbreak_stability\").string))\n+ trend_breaks.append(int((await self._soup(response)).find(id=\"trendbreak_stability\").string))\n return str(min(trend_breaks)), \"100\", []\n \n \n class PerformanceTestRunnerTests(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the number of performance test transactions.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n count = 0\n statuses = self._parameter(\"test_result\")\n for response in responses:\n- count += sum(int(self._soup(response).find(id=status).string) for status in statuses)\n+ count += sum([int((await self._soup(response)).find(id=status).string) for status in statuses])\n return str(count), \"100\", []\n \n \n class PerformanceTestRunnerScalability(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the scalability metric.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n trend_breaks = []\n for response in responses:\n- breaking_point = int(self._soup(response).find(id=\"trendbreak_scalability\").string)\n+ breaking_point = int((await self._soup(response)).find(id=\"trendbreak_scalability\").string)\n if breaking_point == 100:\n raise AssertionError(\n \"No performance scalability breaking point occurred (breaking point is at 100%, expected < 100%)\")\ndiff --git a/components/collector/src/source_collectors/pyupio_safety.py b/components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\nsimilarity index 79%\nrename from components/collector/src/source_collectors/pyupio_safety.py\nrename to components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\n--- a/components/collector/src/source_collectors/pyupio_safety.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\n@@ -3,7 +3,7 @@\n from typing import Final, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import JSONFileSourceCollector\n+from base_collectors import JSONFileSourceCollector\n \n \n class PyupioSafetySecurityWarnings(JSONFileSourceCollector):\n@@ -15,7 +15,7 @@ class PyupioSafetySecurityWarnings(JSONFileSourceCollector):\n VULNERABILITY: Final[int] = 3\n KEY: Final[int] = 4\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n \"\"\"Return a list of warnings.\"\"\"\n entities = []\n for response in responses:\n@@ -23,5 +23,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n [dict(\n key=warning[self.KEY], package=warning[self.PACKAGE], installed=warning[self.INSTALLED],\n affected=warning[self.AFFECTED], vulnerability=warning[self.VULNERABILITY])\n- for warning in response.json()])\n+ for warning in await response.json()])\n return str(len(entities)), \"100\", entities\ndiff --git a/components/collector/src/source_collectors/robot_framework.py b/components/collector/src/source_collectors/file_source_collectors/robot_framework.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/robot_framework.py\nrename to components/collector/src/source_collectors/file_source_collectors/robot_framework.py\n--- a/components/collector/src/source_collectors/robot_framework.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/robot_framework.py\n@@ -8,26 +8,26 @@\n \n from collector_utilities.type import Entities, Response, Responses, URL, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class RobotFrameworkBaseClass(XMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Robot Framework collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = str(await super()._landing_url(responses))\n return URL(url.replace(\"output.html\", \"report.html\"))\n \n \n class RobotFrameworkTests(RobotFrameworkBaseClass):\n \"\"\"Collector for Robot Framework tests.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n count = 0\n entities: Entities = []\n test_results = cast(List[str], self._parameter(\"test_result\"))\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n stats = tree.findall(\"statistics/total/stat\")[1]\n for test_result in test_results:\n count += int(stats.get(test_result, 0))\n@@ -39,5 +39,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class RobotFrameworkSourceUpToDateness(RobotFrameworkBaseClass, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Robot Framework report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(parse_source_response_xml(response).get(\"generated\", \"\"))\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await parse_source_response_xml(response)).get(\"generated\", \"\"))\ndiff --git a/components/collector/src/source_collectors/local_source_collectors/__init__.py b/components/collector/src/source_collectors/local_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/src/source_collectors/calendar.py b/components/collector/src/source_collectors/local_source_collectors/calendar.py\nsimilarity index 69%\nrename from components/collector/src/source_collectors/calendar.py\nrename to components/collector/src/source_collectors/local_source_collectors/calendar.py\n--- a/components/collector/src/source_collectors/calendar.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/calendar.py\n@@ -4,11 +4,11 @@\n from typing import cast\n \n from collector_utilities.type import Response\n-from .source_collector import LocalSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import LocalSourceCollector, SourceUpToDatenessCollector\n \n \n class CalendarSourceUpToDateness(SourceUpToDatenessCollector, LocalSourceCollector):\n \"\"\"Collector class to get the number of days since a user-specified date.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n return datetime.fromisoformat(cast(str, self._parameter(\"date\")))\ndiff --git a/components/collector/src/source_collectors/manual_number.py b/components/collector/src/source_collectors/local_source_collectors/manual_number.py\nsimilarity index 66%\nrename from components/collector/src/source_collectors/manual_number.py\nrename to components/collector/src/source_collectors/local_source_collectors/manual_number.py\n--- a/components/collector/src/source_collectors/manual_number.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/manual_number.py\n@@ -3,11 +3,11 @@\n from typing import Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import LocalSourceCollector\n+from base_collectors import LocalSourceCollector\n \n \n class ManualNumber(LocalSourceCollector):\n \"\"\"Manual number metric collector.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n return str(self._parameter(\"number\")), \"100\", []\ndiff --git a/components/collector/src/source_collectors/random_number.py b/components/collector/src/source_collectors/local_source_collectors/random_number.py\nsimilarity index 74%\nrename from components/collector/src/source_collectors/random_number.py\nrename to components/collector/src/source_collectors/local_source_collectors/random_number.py\n--- a/components/collector/src/source_collectors/random_number.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/random_number.py\n@@ -4,7 +4,7 @@\n from typing import Final, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import LocalSourceCollector\n+from base_collectors import LocalSourceCollector\n \n \n class Random(LocalSourceCollector):\n@@ -12,6 +12,6 @@ class Random(LocalSourceCollector):\n MIN: Final[int] = 1\n MAX: Final[int] = 99\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n value = random.randint(self.MIN, self.MAX) # nosec, random generator is not used for security purpose\n return str(value), \"100\", []\n", "test_patch": "diff --git a/components/collector/tests/metric_collectors/__init__.py b/components/collector/src/source_collectors/api_source_collectors/__init__.py\nsimilarity index 100%\nrename from components/collector/tests/metric_collectors/__init__.py\nrename to components/collector/src/source_collectors/api_source_collectors/__init__.py\ndiff --git a/components/collector/src/source_collectors/jenkins_test_report.py b/components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\nsimilarity index 73%\nrename from components/collector/src/source_collectors/jenkins_test_report.py\nrename to components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\n--- a/components/collector/src/source_collectors/jenkins_test_report.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\n@@ -4,11 +4,10 @@\n from typing import cast, Dict, Final, List, Tuple\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n TestCase = Dict[str, str]\n@@ -21,11 +20,11 @@ class JenkinsTestReportTests(SourceCollector):\n JENKINS_TEST_REPORT_COUNTS: Final[Dict[str, str]] = dict(\n failed=\"failCount\", passed=\"passCount\", skipped=\"skipCount\")\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/testReport/api/json\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/testReport/api/json\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n statuses = cast(List[str], self._parameter(\"test_result\"))\n status_counts = [self.JENKINS_TEST_REPORT_COUNTS[status] for status in statuses]\n results = [report[\"result\"] for report in json[\"childReports\"]] if \"childReports\" in json else [json]\n@@ -56,15 +55,14 @@ def __status(case: TestCase) -> str:\n class JenkinsTestReportSourceUpToDateness(SourceCollector):\n \"\"\"Collector to get the age of the Jenkins test report.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- test_report_url = URL(f\"{api_url}/lastSuccessfulBuild/testReport/api/json\")\n- job_url = URL(f\"{api_url}/lastSuccessfulBuild/api/json\")\n- return [requests.get(url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n- for url in (test_report_url, job_url)]\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ test_report_url = URL(f\"{urls[0]}/lastSuccessfulBuild/testReport/api/json\")\n+ job_url = URL(f\"{urls[0]}/lastSuccessfulBuild/api/json\")\n+ return await super()._get_source_responses(test_report_url, job_url)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- timestamps = [suite.get(\"timestamp\") for suite in responses[0].json().get(\"suites\", [])\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ timestamps = [suite.get(\"timestamp\") for suite in (await responses[0].json()).get(\"suites\", [])\n if suite.get(\"timestamp\")]\n report_datetime = parse(max(timestamps)) if timestamps else \\\n- datetime.fromtimestamp(float(responses[1].json()[\"timestamp\"]) / 1000.)\n+ datetime.fromtimestamp(float((await responses[1].json())[\"timestamp\"]) / 1000.)\n return str(days_ago(report_datetime)), \"100\", []\ndiff --git a/components/collector/tests/base_collectors/__init__.py b/components/collector/tests/base_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/base_collectors/test_cached_client_session.py b/components/collector/tests/base_collectors/test_cached_client_session.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/tests/base_collectors/test_cached_client_session.py\n@@ -0,0 +1,34 @@\n+\"\"\"Unit tests for the client session with cached GET requests.\"\"\"\n+\n+import asyncio\n+from unittest.mock import patch\n+\n+import aiounittest\n+\n+from base_collectors.cached_client_session import CachedClientSession\n+\n+\n+class CachedClientSessionTest(aiounittest.AsyncTestCase):\n+ \"\"\"Unit tests for the cached client session class.\"\"\"\n+\n+ async def get(self, *args, **kwargs): # pylint: disable=unused-argument\n+ \"\"\"Fake the session.get method.\"\"\"\n+ self.get_calls += 1 # pylint: disable=no-member\n+ await asyncio.sleep(0)\n+\n+ @patch(\"aiohttp.ClientSession.get\", new=get)\n+ async def test_get_same_url_once(self):\n+ \"\"\"Test that the url is retrieved once.\"\"\"\n+ async with CachedClientSession() as session:\n+ session.get_calls = 0\n+ await session.get(\"https://url\")\n+ self.assertEqual(1, session.get_calls)\n+\n+ @patch(\"aiohttp.ClientSession.get\", new=get)\n+ async def test_get_same_url_twice(self):\n+ \"\"\"Test that the url is retrieved only once.\"\"\"\n+ async with CachedClientSession() as session:\n+ session.get_calls = 0\n+ await asyncio.gather(session.get(\"https://url\"), session.get(\"https://url\"))\n+ await asyncio.gather(session.get(\"https://url\"), session.get(\"https://url\"))\n+ self.assertEqual(1, session.get_calls)\ndiff --git a/components/collector/tests/metric_collectors/test_metrics_collector.py b/components/collector/tests/base_collectors/test_metrics_collector.py\nsimilarity index 56%\nrename from components/collector/tests/metric_collectors/test_metrics_collector.py\nrename to components/collector/tests/base_collectors/test_metrics_collector.py\n--- a/components/collector/tests/metric_collectors/test_metrics_collector.py\n+++ b/components/collector/tests/base_collectors/test_metrics_collector.py\n@@ -1,31 +1,29 @@\n \"\"\"Unit tests for the collector main script.\"\"\"\n \n import logging\n-import unittest\n from datetime import datetime\n from typing import Tuple\n-from unittest.mock import patch, mock_open, Mock\n+from unittest.mock import patch, mock_open, AsyncMock, Mock\n+\n+import aiohttp\n+import aiounittest\n \n import quality_time_collector\n-from metric_collectors import MetricsCollector\n-from source_collectors import source_collector\n+from base_collectors import MetricsCollector, SourceCollector\n from collector_utilities.type import Entities, Responses, Value\n \n \n-class CollectorTest(unittest.TestCase):\n+class CollectorTest(aiounittest.AsyncTestCase):\n \"\"\"Unit tests for the collection methods.\"\"\"\n \n def setUp(self):\n- class SourceMetric(source_collector.SourceCollector): # pylint: disable=unused-variable\n+ class SourceMetric(SourceCollector): # pylint: disable=unused-variable\n \"\"\"Register a fake collector automatically.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n return \"42\", \"84\", []\n \n- self.data_model_response = Mock()\n self.data_model = dict(sources=dict(source=dict(parameters=dict(url=dict(mandatory=True, metrics=[\"metric\"])))))\n- self.data_model_response.json.return_value = self.data_model\n- self.metrics_response = Mock()\n self.metrics_collector = MetricsCollector()\n self.url = \"https://url\"\n self.measurement_api_url = \"http://localhost:5001/api/v2/measurements\"\n@@ -34,34 +32,39 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n def tearDown(self):\n logging.disable(logging.NOTSET)\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_fetch_without_sources(self, mocked_get, mocked_post):\n+ async def fetch_measurements(self, mock_async_get_request, number=1):\n+ \"\"\"Fetch the measurements with patched get method.\"\"\"\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ async with aiohttp.ClientSession() as session:\n+ for _ in range(number):\n+ await self.metrics_collector.collect_metrics(session, 60)\n+\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_without_sources(self, mocked_post):\n \"\"\"Test fetching measurement for a metric without sources.\"\"\"\n- self.metrics_response.json.return_value = dict(\n- metric_uuid=dict(type=\"metric\", addition=\"sum\", sources=dict()))\n- mocked_get.return_value = self.metrics_response\n- self.metrics_collector.fetch_measurements(60)\n+ metrics = dict(metric_uuid=dict(type=\"metric\", addition=\"sum\", sources=dict()))\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_not_called()\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\", Mock(side_effect=RuntimeError))\n- def test_fetch_with_get_error(self, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_with_get_error(self, mocked_post):\n \"\"\"Test fetching measurement when getting fails.\"\"\"\n- self.metrics_collector.fetch_measurements(60)\n+ await self.fetch_measurements(Mock(side_effect=RuntimeError))\n mocked_post.assert_not_called()\n \n- @patch(\"requests.post\", side_effect=RuntimeError)\n- @patch(\"requests.get\")\n- def test_fetch_with_post_error(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\", side_effect=RuntimeError)\n+ async def test_fetch_with_post_error(self, mocked_post):\n \"\"\"Test fetching measurement when posting fails.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.metrics_response, Mock()]\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_called_once_with(\n self.measurement_api_url,\n json=dict(\n@@ -70,18 +73,20 @@ def test_fetch_with_post_error(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n+ @patch(\"asyncio.sleep\", Mock(side_effect=RuntimeError))\n @patch(\"builtins.open\", mock_open())\n- @patch(\"time.sleep\", Mock(side_effect=RuntimeError))\n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_collect(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_collect(self, mocked_post):\n \"\"\"Test the collect method.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.data_model_response, self.metrics_response, Mock()]\n- self.assertRaises(RuntimeError, quality_time_collector.collect)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [self.data_model, metrics]\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ with self.assertRaises(RuntimeError):\n+ await quality_time_collector.collect()\n mocked_post.assert_called_once_with(\n self.measurement_api_url,\n json=dict(\n@@ -90,28 +95,29 @@ def test_collect(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n- @patch(\"requests.get\")\n- def test_missing_collector(self, mocked_get):\n+ async def test_missing_collector(self):\n \"\"\"Test that an exception is thrown if there's no collector for the source and metric type.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n type=\"metric\", addition=\"sum\",\n sources=dict(missing=dict(type=\"unknown_source\", parameters=dict(url=self.url)))))\n- mocked_get.return_value = self.metrics_response\n- self.assertRaises(LookupError, self.metrics_collector.fetch_measurements, 60)\n+ self.metrics_collector.data_model = self.data_model\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ with self.assertRaises(LookupError):\n+ await self.fetch_measurements(mock_async_get_request)\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_fetch_twice(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_twice(self, mocked_post):\n \"\"\"Test that the metric is skipped on the second fetch.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.metrics_response, Mock(), self.metrics_response]\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [metrics, metrics]\n+ await self.fetch_measurements(mock_async_get_request, number=2)\n mocked_post.assert_called_once_with(\n \"http://localhost:5001/api/v2/measurements\",\n json=dict(\n@@ -120,28 +126,30 @@ def test_fetch_twice(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_missing_mandatory_parameter(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_missing_mandatory_parameter(self, mocked_post):\n \"\"\"Test that a metric with sources but without a mandatory parameter is skipped.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n type=\"metric\", addition=\"sum\", sources=dict(missing=dict(type=\"source\", parameters=dict(url=\"\")))))\n- mocked_get.return_value = self.metrics_response\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_not_called()\n \n @patch(\"builtins.open\", mock_open())\n- @patch(\"requests.get\")\n- def test_fetch_data_model_after_failure(self, mocked_get):\n+ async def test_fetch_data_model_after_failure(self):\n \"\"\"Test that the data model is fetched on the second try.\"\"\"\n- mocked_get.side_effect = [None, self.data_model_response]\n- data_model = self.metrics_collector.fetch_data_model(0)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [RuntimeError, self.data_model]\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ async with aiohttp.ClientSession() as session:\n+ data_model = await self.metrics_collector.fetch_data_model(session, 0)\n self.assertEqual(self.data_model, data_model)\n \n @patch(\"builtins.open\", new_callable=mock_open)\n- @patch(\"metric_collectors.metrics_collector.datetime\")\n+ @patch(\"base_collectors.metrics_collector.datetime\")\n def test_writing_health_check(self, mocked_datetime, mocked_open):\n \"\"\"Test that the current time is written to the health check file.\"\"\"\n mocked_datetime.now.return_value = now = datetime.now()\ndiff --git a/components/collector/tests/source_collectors/api_source_collectors/__init__.py b/components/collector/tests/source_collectors/api_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/source_collectors/test_azure_devops.py b/components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\nsimilarity index 87%\nrename from components/collector/tests/source_collectors/test_azure_devops.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\n--- a/components/collector/tests/source_collectors/test_azure_devops.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\n@@ -3,7 +3,7 @@\n from dateutil.parser import parse\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from ..source_collector_test_case import SourceCollectorTestCase\n \n \n class AzureDevopsTestCase(SourceCollectorTestCase):\n@@ -25,21 +25,21 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]))\n self.assert_measurement(response, value=\"2\")\n \n- def test_no_issues(self):\n+ async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n- response = self.collect(self.metric, post_request_json_return_value=dict(workItems=[]))\n+ response = await self.collect(self.metric, post_request_json_return_value=dict(workItems=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id\")]),\n get_request_json_return_value=dict(value=[self.work_item]))\n self.assert_measurement(\n@@ -55,16 +55,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"ready_user_story_points\", sources=self.sources, addition=\"sum\")\n \n- def test_story_points(self):\n+ async def test_story_points(self):\n \"\"\"Test that the number of story points are returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]))\n self.assert_measurement(response, value=\"4\")\n \n- def test_story_points_without_stories(self):\n+ async def test_story_points_without_stories(self):\n \"\"\"Test that the number of story points is zero when there are no work items.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[]),\n get_request_json_return_value=dict(value=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n@@ -82,14 +82,14 @@ def setUp(self):\n self.metric = dict(type=\"unmerged_branches\", sources=self.sources, addition=\"sum\")\n self.repositories = dict(value=[dict(id=\"id\", name=\"project\")])\n \n- def test_no_branches_except_master(self):\n+ async def test_no_branches_except_master(self):\n \"\"\"Test that the number of unmerged branches is returned.\"\"\"\n branches = dict(value=[dict(name=\"master\", isBaseVersion=True)])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n self.assert_measurement(\n response, value=\"0\", entities=[], landing_url=\"https://azure_devops/org/project/_git/project/branches\")\n \n- def test_unmerged_branches(self):\n+ async def test_unmerged_branches(self):\n \"\"\"Test that the number of unmerged branches is returned.\"\"\"\n timestamp = \"2019-09-03T20:43:00Z\"\n branches = dict(\n@@ -99,11 +99,10 @@ def test_unmerged_branches(self):\n commit=dict(committer=dict(date=timestamp))),\n dict(name=\"ignored_branch\", isBaseVersion=False, aheadCount=1,\n commit=dict(committer=dict(date=timestamp)))])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n expected_age = str(days_ago(parse(timestamp)))\n self.assert_measurement(\n- response,\n- value=\"1\",\n+ response, value=\"1\",\n entities=[dict(name=\"branch\", key=\"branch\", commit_age=expected_age, commit_date=\"2019-09-03\")],\n landing_url=\"https://azure_devops/org/project/_git/project/branches\")\n \n@@ -111,7 +110,7 @@ def test_unmerged_branches(self):\n class AzureDevopsSourceUpToDatenessTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure DevOps Server source up-to-dateness collector.\"\"\"\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the age of the file is returned.\"\"\"\n sources = dict(\n source_id=dict(\n@@ -123,27 +122,24 @@ def test_age(self):\n repositories = dict(value=[dict(id=\"id\", name=\"repo\")])\n timestamp = \"2019-09-03T20:43:00Z\"\n commits = dict(value=[dict(committer=dict(date=timestamp))])\n- response = self.collect(\n- metric, get_request_json_side_effect=[repositories, commits])\n+ response = await self.collect(metric, get_request_json_side_effect=[repositories, commits])\n expected_age = str(days_ago(parse(timestamp)))\n self.assert_measurement(\n- response,\n- value=expected_age,\n+ response, value=expected_age,\n landing_url=\"https://azure_devops/org/project/_git/repo?path=README.md&version=GBmaster\")\n \n \n class AzureDevopsTestsTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure DevOps Server tests collector.\"\"\"\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n sources = dict(\n source_id=dict(\n type=\"azure_devops\", parameters=dict(url=\"https://azure_devops\", private_token=\"xxx\", test_result=[])))\n metric = dict(type=\"tests\", sources=sources, addition=\"sum\")\n- response = self.collect(\n- metric,\n- get_request_json_return_value=dict(\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(\n value=[\n dict(build=dict(id=\"1\"), passedTests=2),\n dict(build=dict(id=\"2\"), passedTests=2, notApplicableTests=1),\n@@ -151,14 +147,14 @@ def test_nr_of_tests(self):\n dict(build=dict(id=\"2\"), passedTests=1)]))\n self.assert_measurement(response, value=\"4\")\n \n- def test_nr_of_failed_tests(self):\n+ async def test_nr_of_failed_tests(self):\n \"\"\"Test that the number of failed tests is returned.\"\"\"\n sources = dict(\n source_id=dict(\n type=\"azure_devops\",\n parameters=dict(url=\"https://azure_devops\", private_token=\"xxx\", test_result=[\"failed\"])))\n metric = dict(type=\"tests\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(value=[dict(build=dict(id=\"1\"), unanalyzedTests=4)]))\n self.assert_measurement(response, value=\"4\")\n \n@@ -166,7 +162,7 @@ def test_nr_of_failed_tests(self):\n class AzureDevopsFailedJobsTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure Devops Server failed jobs collector.\"\"\"\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned, that pipelines can be ignored by status, by name, and by\n regular expression.\"\"\"\n sources = dict(\n@@ -176,7 +172,7 @@ def test_nr_of_failed_jobs(self):\n url=\"https://azure_devops\", private_token=\"xxx\", failure_type=[\"failed\"],\n jobs_to_ignore=[\"ignore_by_name\", \"folder/ignore.*\"])))\n metric = dict(type=\"failed_jobs\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n value=[\n@@ -196,7 +192,7 @@ def test_nr_of_failed_jobs(self):\n dict(name=r\"folder/pipeline\", key=r\"folder/pipeline\", url=\"https://azure_devops/build\",\n build_date=\"2019-11-15\", build_age=str(expected_age), build_status=\"failed\")])\n \n- def test_nr_of_unused_jobs(self):\n+ async def test_nr_of_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned, that pipelines can be ignored by name and by\n regular expression.\"\"\"\n sources = dict(\n@@ -206,7 +202,7 @@ def test_nr_of_unused_jobs(self):\n url=\"https://azure_devops\", private_token=\"xxx\",\n jobs_to_ignore=[\"ignore_by_name\", \"folder/ignore.*\"])))\n metric = dict(type=\"unused_jobs\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n value=[\ndiff --git a/components/collector/tests/source_collectors/test_cxsast.py b/components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\nsimilarity index 73%\nrename from components/collector/tests/source_collectors/test_cxsast.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\n--- a/components/collector/tests/source_collectors/test_cxsast.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class CxSASTTestCase(SourceCollectorTestCase):\n@@ -22,35 +22,37 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the age of the last finished scan is returned.\"\"\"\n get_json = [\n- [dict(name=\"project\", id=\"id\")], [dict(dateAndTime=dict(finishedOn=\"2019-01-01T09:06:12+00:00\"))],\n- [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")]]\n- post_json = [dict(access_token=\"token\")] * 2\n- response = self.collect(\n- self.metric, get_request_json_side_effect=get_json, post_request_json_side_effect=post_json)\n+ [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")],\n+ [dict(dateAndTime=dict(finishedOn=\"2019-01-01T09:06:12+00:00\"))]]\n+ post_json = dict(access_token=\"token\")\n+ response = await self.collect(\n+ self.metric, get_request_json_side_effect=get_json, post_request_json_return_value=post_json)\n expected_age = (datetime.now(timezone.utc) - datetime(2019, 1, 1, 9, 6, 9, tzinfo=timezone.utc)).days\n self.assert_measurement(\n response, value=str(expected_age),\n landing_url=\"https://checkmarx/CxWebClient/ViewerMain.aspx?scanId=scan_id&ProjectID=id\")\n \n- def test_landing_url_without_response(self):\n+ async def test_landing_url_without_response(self):\n \"\"\"Test that a default landing url is returned when connecting to the source fails.\"\"\"\n- response = self.collect(self.metric, post_request_side_effect=RuntimeError)\n+ response = await self.collect(self.metric, post_request_side_effect=RuntimeError)\n self.assert_measurement(response, landing_url=\"https://checkmarx\", connection_error=\"Traceback\")\n \n \n class CxSASTSecurityWarningsTest(CxSASTTestCase):\n \"\"\"Unit tests for the security warnings collector.\"\"\"\n \n- def test_nr_of_warnings(self):\n+ async def test_nr_of_warnings(self):\n \"\"\"Test that the number of security warnings is returned.\"\"\"\n metric = dict(type=\"security_warnings\", sources=self.sources, addition=\"sum\")\n get_json = [\n [dict(name=\"project\", id=\"id\")], [dict(id=1000)],\n dict(highSeverity=1, mediumSeverity=2, lowSeverity=3, infoSeverity=4),\n [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")]]\n- post_json = [dict(access_token=\"token\")] * 2 + [dict(reportId=\"1\")]\n- response = self.collect(metric, get_request_json_side_effect=get_json, post_request_json_side_effect=post_json)\n+ post_json = dict(access_token=\"token\")\n+ response = await self.collect(\n+ metric, get_request_json_side_effect=get_json,\n+ post_request_json_return_value=post_json)\n self.assert_measurement(response, value=\"10\", entities=[])\ndiff --git a/components/collector/tests/source_collectors/test_gitlab.py b/components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\nsimilarity index 75%\nrename from components/collector/tests/source_collectors/test_gitlab.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\n--- a/components/collector/tests/source_collectors/test_gitlab.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\n@@ -1,9 +1,9 @@\n \"\"\"Unit tests for the GitLab source.\"\"\"\n \n from datetime import datetime, timezone\n-from unittest.mock import Mock, patch\n+from unittest.mock import AsyncMock, Mock, patch\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class GitLabTestCase(SourceCollectorTestCase):\n@@ -33,43 +33,43 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"failed_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_nr_of_failed_jobs_without_failed_jobs(self):\n+ async def test_nr_of_failed_jobs_without_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n self.gitlab_jobs_json[0][\"status\"] = \"success\"\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_private_token(self):\n+ async def test_private_token(self):\n \"\"\"Test that the private token is used.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"private_token\"] = \"token\"\n- response = self.collect(self.metric)\n+ response = await self.collect(self.metric)\n self.assert_measurement(\n response,\n api_url=\"https://gitlab/api/v4/projects/namespace%2Fproject/jobs?per_page=100&private_token=token\",\n parse_error=\"Traceback\")\n \n- def test_ignore_previous_runs_of_jobs(self):\n+ async def test_ignore_previous_runs_of_jobs(self):\n \"\"\"Test that previous runs of the same job are ignored.\"\"\"\n self.gitlab_jobs_json.insert(\n 0,\n dict(id=\"2\", status=\"success\", name=\"name\", stage=\"stage\", created_at=\"2019-03-31T19:51:39.927Z\",\n web_url=\"https://gitlab/jobs/2\", ref=\"master\"))\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n \n class GitLabUnusedJobsTest(GitLabTestCase):\n \"\"\"Unit tests for the GitLab unused jobs metric.\"\"\"\n \n- def test_nr_of_unused_jobs(self):\n+ async def test_nr_of_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned.\"\"\"\n metric = dict(type=\"unused_jobs\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n@@ -84,19 +84,19 @@ def setUp(self):\n self.head_response = Mock()\n self.head_response.headers = {\"X-Gitlab-Last-Commit-Id\": \"commit-sha\"}\n \n- def test_source_up_to_dateness_file(self):\n+ async def test_source_up_to_dateness_file(self):\n \"\"\"Test that the age of a file in a repo can be measured.\"\"\"\n- with patch(\"requests.head\", return_value=self.head_response):\n- response = self.collect(\n+ with patch(\"aiohttp.ClientSession.head\", AsyncMock(return_value=self.head_response)):\n+ response = await self.collect(\n self.metric,\n get_request_json_side_effect=[[], self.commit_json, dict(web_url=\"https://gitlab.com/project\")])\n self.assert_measurement(\n response, value=str(self.expected_age), landing_url=\"https://gitlab.com/project/blob/branch/file\")\n \n- def test_source_up_to_dateness_folder(self):\n+ async def test_source_up_to_dateness_folder(self):\n \"\"\"Test that the age of a folder in a repo can be measured.\"\"\"\n- with patch(\"requests.head\", side_effect=[self.head_response, self.head_response]):\n- response = self.collect(\n+ with patch(\"aiohttp.ClientSession.head\", AsyncMock(side_effect=[self.head_response, self.head_response])):\n+ response = await self.collect(\n self.metric,\n get_request_json_side_effect=[\n [dict(type=\"blob\", path=\"file.txt\"), dict(type=\"tree\", path=\"folder\")],\n@@ -105,11 +105,16 @@ def test_source_up_to_dateness_folder(self):\n self.assert_measurement(\n response, value=str(self.expected_age), landing_url=\"https://gitlab.com/project/blob/branch/file\")\n \n+ async def test_landing_url_on_failure(self):\n+ \"\"\"Test that the landing url is the API url when GitLab cannot be reached.\"\"\"\n+ response = await self.collect(self.metric, get_request_json_side_effect=[ConnectionError])\n+ self.assert_measurement(response, landing_url=\"https://gitlab\", connection_error=\"Traceback\")\n+\n \n class GitlabUnmergedBranchesTest(GitLabTestCase):\n \"\"\"Unit tests for the unmerged branches metric.\"\"\"\n \n- def test_unmerged_branches(self):\n+ async def test_unmerged_branches(self):\n \"\"\"Test that the number of unmerged branches can be measured.\"\"\"\n metric = dict(type=\"unmerged_branches\", sources=self.sources, addition=\"sum\")\n gitlab_json = [\n@@ -121,7 +126,7 @@ def test_unmerged_branches(self):\n dict(name=\"active_unmerged_branch\", default=False, merged=False,\n commit=dict(committed_date=datetime.now(timezone.utc).isoformat())),\n dict(name=\"merged_branch\", default=False, merged=True)]\n- response = self.collect(metric, get_request_json_return_value=gitlab_json)\n+ response = await self.collect(metric, get_request_json_return_value=gitlab_json)\n expected_age = str((datetime.now(timezone.utc) - datetime(2019, 4, 2, 9, 33, 4, tzinfo=timezone.utc)).days)\n expected_entities = [\n dict(key=\"unmerged_branch\", name=\"unmerged_branch\", commit_age=expected_age, commit_date=\"2019-04-02\")]\ndiff --git a/components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py b/components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\nsimilarity index 67%\nrename from components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\n--- a/components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JaCoCoJenkinsPluginTest(SourceCollectorTestCase):\n@@ -13,21 +13,22 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jacoco_jenkins_plugin\", parameters=dict(url=\"https://jenkins/job\")))\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the total number of lines are returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=dict(lineCoverage=dict(total=6, missed=2)))\n+ response = await self.collect(metric, get_request_json_return_value=dict(lineCoverage=dict(total=6, missed=2)))\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches and the total number of branches are returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=dict(branchCoverage=dict(total=6, missed=2)))\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(branchCoverage=dict(total=6, missed=2)))\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source up to dateness is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n+ response = await self.collect(metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_jenkins.py b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\nsimilarity index 79%\nrename from components/collector/tests/source_collectors/test_jenkins.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\n--- a/components/collector/tests/source_collectors/test_jenkins.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JenkinsTestCase(SourceCollectorTestCase):\n@@ -25,7 +25,7 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"failed_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n jenkins_json = dict(\n jobs=[\n@@ -35,47 +35,47 @@ def test_nr_of_failed_jobs(self):\n dict(\n name=\"child_job\", url=\"https://child_job\", buildable=True, color=\"red\",\n builds=self.builds)])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"2\")\n \n- def test_failed_jobs(self):\n+ async def test_failed_jobs(self):\n \"\"\"Test that the failed jobs are returned.\"\"\"\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_ignore_jobs(self):\n+ async def test_ignore_jobs(self):\n \"\"\"Test that a failed job can be ignored.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"jobs_to_ignore\"] = [\"job2\"]\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds),\n dict(name=\"job2\", url=self.job2_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_ignore_jobs_by_regular_expression(self):\n+ async def test_ignore_jobs_by_regular_expression(self):\n \"\"\"Test that failed jobs can be ignored by regular expression.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"jobs_to_ignore\"] = [\"job.\"]\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds),\n dict(name=\"job2\", url=self.job2_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_no_builds(self):\n+ async def test_no_builds(self):\n \"\"\"Test no builds.\"\"\"\n jenkins_json = dict(jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"notbuilt\", builds=[])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, entities=[])\n \n \n@@ -86,16 +86,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"unused_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_unused_jobs(self):\n+ async def test_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned.\"\"\"\n jenkins_json = dict(\n jobs=[dict(\n name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=[dict(timestamp=\"1548311610349\")])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"1\")\n \n- def test_unbuild_job(self):\n+ async def test_unbuild_job(self):\n \"\"\"Test that jobs without builds are ignored.\"\"\"\n jenkins_json = dict(jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\")])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"0\")\ndiff --git a/components/collector/tests/source_collectors/test_jenkins_test_report.py b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\nsimilarity index 83%\nrename from components/collector/tests/source_collectors/test_jenkins_test_report.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\n--- a/components/collector/tests/source_collectors/test_jenkins_test_report.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JenkinsTestReportTest(SourceCollectorTestCase):\n@@ -13,21 +13,21 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jenkins_test_report\", parameters=dict(url=\"https://jenkins/job\")))\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=1, passCount=1, suites=[dict(\n cases=[dict(status=\"FAILED\", name=\"tc1\", className=\"c1\"),\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])])\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(\n response, value=\"2\",\n entities=[\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")])\n \n- def test_nr_of_tests_with_aggregated_report(self):\n+ async def test_nr_of_tests_with_aggregated_report(self):\n \"\"\"Test that the number of tests is returned when the test report is an aggregated report.\"\"\"\n jenkins_json = dict(\n childReports=[\n@@ -39,14 +39,14 @@ def test_nr_of_tests_with_aggregated_report(self):\n dict(status=\"FAILED\", name=\"tc1\", className=\"c1\"),\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])]))])\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(\n response, value=\"2\",\n entities=[\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")])\n \n- def test_nr_of_passed_tests(self):\n+ async def test_nr_of_passed_tests(self):\n \"\"\"Test that the number of passed tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=1, passCount=1, suites=[dict(\n@@ -54,11 +54,11 @@ def test_nr_of_passed_tests(self):\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])])\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"passed\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n expected_entities = [dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")]\n self.assert_measurement(response, value=\"1\", entities=expected_entities)\n \n- def test_nr_of_failed_tests(self):\n+ async def test_nr_of_failed_tests(self):\n \"\"\"Test that the number of failed tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=2, suites=[dict(\n@@ -67,24 +67,24 @@ def test_nr_of_failed_tests(self):\n dict(status=\"PASSED\", name=\"tc3\", className=\"c3\")])])\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"failed\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"failed\")]\n self.assert_measurement(response, value=\"2\", entities=expected_entities)\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(suites=[dict(timestamp=\"2019-04-02T08:52:50\")]))\n expected_age = (datetime.now() - datetime(2019, 4, 2, 8, 52, 50)).days\n self.assert_measurement(response, value=str(expected_age))\n \n- def test_source_up_to_dateness_without_timestamps(self):\n+ async def test_source_up_to_dateness_without_timestamps(self):\n \"\"\"Test that the job age in days is returned if the test report doesn't contain timestamps.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_side_effect=[dict(suites=[dict(timestamp=None)]), dict(timestamp=\"1565284457173\")])\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\ndiff --git a/components/collector/tests/source_collectors/test_jira.py b/components/collector/tests/source_collectors/api_source_collectors/test_jira.py\nsimilarity index 89%\nrename from components/collector/tests/source_collectors/test_jira.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jira.py\n--- a/components/collector/tests/source_collectors/test_jira.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jira.py\n@@ -5,7 +5,7 @@\n from dateutil.parser import parse\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JiraTestCase(SourceCollectorTestCase):\n@@ -30,16 +30,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n issues_json = dict(total=42)\n- response = self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n self.assert_measurement(response, value=\"42\")\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n issues_json = dict(total=1, issues=[dict(key=\"key\", id=\"id\", fields=dict(summary=\"Summary\"))])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n self.assert_measurement(response, entities=[dict(key=\"id\", summary=\"Summary\", url=\"https://jira/browse/key\")])\n \n \n@@ -51,7 +51,7 @@ def setUp(self):\n self.too_long_ago_summary = \"Tested too long ago according to its own desired frequency\"\n self.metric = dict(type=\"manual_test_execution\", addition=\"sum\", sources=self.sources)\n \n- def test_nr_of_test_cases(self):\n+ async def test_nr_of_test_cases(self):\n \"\"\"Test that the number of test cases is returned.\"\"\"\n comment_updated = \"2019-10-02T11:07:02.444+0200\"\n test_cases_json = dict(\n@@ -69,7 +69,7 @@ def test_nr_of_test_cases(self):\n comment=dict(comments=[dict(updated=str(datetime.now()-timedelta(days=10)))]),\n desired_test_frequency=\"5\",\n summary=self.too_long_ago_summary))])\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=[self.fields_json, test_cases_json])\n expected_days = str(days_ago(parse(comment_updated)))\n self.assert_measurement(\n@@ -80,7 +80,7 @@ def test_nr_of_test_cases(self):\n dict(key=\"id4\", summary=self.too_long_ago_summary,\n url=\"https://jira/browse/key4\", days_untested=\"10\", desired_test_frequency=\"5\")])\n \n- def test_nr_of_test_cases_with_field_name(self):\n+ async def test_nr_of_test_cases_with_field_name(self):\n \"\"\"Test that the number of test cases is returned when the field name for the test frequency is specified\n by name.\"\"\"\n fields_json = [dict(name=\"Required test frequency\", id=\"custom_field_001\")]\n@@ -91,7 +91,7 @@ def test_nr_of_test_cases_with_field_name(self):\n fields=dict(\n comment=dict(comments=[dict(updated=str(datetime.now()-timedelta(days=10)))]),\n custom_field_001=\"5\", summary=self.too_long_ago_summary))])\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=[fields_json, test_cases_json])\n self.assert_measurement(\n response, value=\"1\",\n@@ -103,14 +103,14 @@ def test_nr_of_test_cases_with_field_name(self):\n class JiraReadyUserStoryPointsTest(JiraTestCase):\n \"\"\"Unit tests for the Jira ready story points collector.\"\"\"\n \n- def test_nr_story_points(self):\n+ async def test_nr_story_points(self):\n \"\"\"Test that the number of story points is returned.\"\"\"\n metric = dict(type=\"ready_user_story_points\", addition=\"sum\", sources=self.sources)\n user_stories_json = dict(\n issues=[\n dict(key=\"1\", id=\"1\", fields=dict(summary=\"user story 1\", field=10)),\n dict(key=\"2\", id=\"2\", fields=dict(summary=\"user story 2\", field=32))])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[self.fields_json, user_stories_json])\n self.assert_measurement(\n response, value=\"42\",\n@@ -122,7 +122,7 @@ def test_nr_story_points(self):\n class JiraManualTestDurationTest(JiraTestCase):\n \"\"\"Unit tests for the Jira manual test duration collector.\"\"\"\n \n- def test_duration(self):\n+ async def test_duration(self):\n \"\"\"Test that the duration is returned.\"\"\"\n metric = dict(type=\"manual_test_duration\", addition=\"sum\", sources=self.sources)\n test_cases_json = dict(\n@@ -130,7 +130,7 @@ def test_duration(self):\n dict(key=\"1\", id=\"1\", fields=dict(summary=\"test 1\", field=10)),\n dict(key=\"2\", id=\"2\", fields=dict(summary=\"test 2\", field=15)),\n dict(key=\"3\", id=\"3\", fields=dict(summary=\"test 3\", field=None))])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[self.fields_json, test_cases_json])\n self.assert_measurement(\n response, value=\"25\",\ndiff --git a/components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py b/components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\nsimilarity index 88%\nrename from components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n--- a/components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class OWASPDependencyCheckJenkinsPluginTest(SourceCollectorTestCase):\n@@ -15,10 +15,10 @@ def setUp(self):\n type=\"owasp_dependency_check_jenkins_plugin\",\n parameters=dict(url=\"https://jenkins/job\", severities=[\"critical\", \"high\", \"normal\"])))\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test that the number of security warnings is returned.\"\"\"\n metric = dict(type=\"security_warnings\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n warnings=[\n@@ -33,10 +33,10 @@ def test_warnings(self):\n dict(key=\"/f4\", file_path=\"/f4\", highest_severity=\"Critical\", nr_vulnerabilities=1)]\n self.assert_measurement(response, value=\"3\", entities=expected_entities)\n \n- def test_up_to_dateness(self):\n+ async def test_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_quality_time.py b/components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\nsimilarity index 95%\nrename from components/collector/tests/source_collectors/test_quality_time.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\n--- a/components/collector/tests/source_collectors/test_quality_time.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\n@@ -1,12 +1,12 @@\n \"\"\"Unit tests for the Quality-time source collector(s).\"\"\"\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class QualityTimeMetricsTest(SourceCollectorTestCase):\n \"\"\"Fixture for Quality-time metrics unit tests.\"\"\"\n \n- def test_nr_of_metrics(self):\n+ async def test_nr_of_metrics(self):\n \"\"\"Test that the number of metrics is returned.\"\"\"\n sources = dict(\n source_id=dict(\n@@ -46,7 +46,7 @@ def test_nr_of_metrics(self):\n measurements1 = dict(measurements=[dict(metric_uuid=\"m1\", count=dict(status=\"target_met\", value=\"0\"))])\n measurements2 = dict(measurements=[dict(metric_uuid=\"m2\", count=dict(status=\"target_not_met\", value=\"20\"))])\n measurements3 = dict(measurements=[])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[reports, measurements1, measurements2, measurements3])\n # The count should be one because the user selected metrics from report \"r1\", with status \"target_not_met\",\n # metric type \"tests\" or \"violations\", source type \"sonarqube\" or \"junit\", and tag \"security\".\ndiff --git a/components/collector/tests/source_collectors/test_sonarqube.py b/components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_sonarqube.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\n--- a/components/collector/tests/source_collectors/test_sonarqube.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime, timedelta, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class SonarQubeTest(SourceCollectorTestCase):\n@@ -13,7 +13,7 @@ def setUp(self):\n self.sources = dict(source_id=dict(type=\"sonarqube\", parameters=dict(url=\"https://sonar\", component=\"id\")))\n self.tests_landing_url = \"https://sonar/component_measures?id=id&metric=tests&branch=master\"\n \n- def test_violations(self):\n+ async def test_violations(self):\n \"\"\"Test that the number of violations is returned.\"\"\"\n json = dict(\n total=\"2\",\n@@ -21,7 +21,7 @@ def test_violations(self):\n dict(key=\"a\", message=\"a\", component=\"a\", severity=\"INFO\", type=\"BUG\"),\n dict(key=\"b\", message=\"b\", component=\"b\", severity=\"MAJOR\", type=\"CODE_SMELL\")])\n metric = dict(type=\"violations\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n expected_entities = [\n dict(component=\"a\", key=\"a\", message=\"a\", severity=\"info\", type=\"bug\",\n url=\"https://sonar/project/issues?id=id&issues=a&open=a&branch=master\"),\n@@ -31,11 +31,11 @@ def test_violations(self):\n response, value=\"2\", entities=expected_entities,\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master\")\n \n- def test_commented_out_code(self):\n+ async def test_commented_out_code(self):\n \"\"\"Test that the number of lines with commented out code is returned.\"\"\"\n json = dict(total=\"2\")\n metric = dict(type=\"commented_out_code\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"2\", total=\"100\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=abap:S125,apex:S125,\"\n@@ -44,14 +44,15 @@ def test_commented_out_code(self):\n \"scala:S125,squid:CommentedOutCodeLine,swift:S125,typescript:S125,\"\n \"Web:AvoidCommentedOutCodeCheck,xml:S125\")\n \n- def test_complex_units(self):\n+ async def test_complex_units(self):\n \"\"\"Test that the number of lines with commented out code is returned.\"\"\"\n complex_units_json = dict(total=\"2\")\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"complex_units\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n- get_request_json_side_effect=[{}, complex_units_json, functions_json, complex_units_json, functions_json])\n+ get_request_json_side_effect=[\n+ {}, complex_units_json, functions_json, complex_units_json, functions_json, complex_units_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=csharpsquid:S1541,\"\n@@ -60,58 +61,58 @@ def test_complex_units(self):\n \"scala:S3776,squid:MethodCyclomaticComplexity,squid:S3776,typescript:S1541,typescript:S3776,\"\n \"vbnet:S1541,vbnet:S3776\")\n \n- def test_tests(self):\n+ async def test_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"tests\", value=\"88\")]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"88\", landing_url=self.tests_landing_url)\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the number of lines to cover are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[dict(metric=\"uncovered_lines\", value=\"100\"), dict(metric=\"lines_to_cover\", value=\"1000\")]))\n metric = dict(type=\"uncovered_lines\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"100\", total=\"1000\",\n landing_url=\"https://sonar/component_measures?id=id&metric=uncovered_lines&branch=master\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches and the number of branches to cover are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[\n dict(metric=\"uncovered_conditions\", value=\"10\"), dict(metric=\"conditions_to_cover\", value=\"200\")]))\n metric = dict(type=\"uncovered_branches\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"10\", total=\"200\",\n landing_url=\"https://sonar/component_measures?id=id&metric=uncovered_conditions&branch=master\")\n \n- def test_duplicated_lines(self):\n+ async def test_duplicated_lines(self):\n \"\"\"Test that the number of duplicated lines and the total number of lines are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[\n dict(metric=\"duplicated_lines\", value=\"10\"), dict(metric=\"lines\", value=\"100\")]))\n metric = dict(type=\"duplicated_lines\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"10\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=duplicated_lines&branch=master\")\n \n- def test_many_parameters(self):\n+ async def test_many_parameters(self):\n \"\"\"Test that the number of functions with too many parameters is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"rules\"] = [\"rule1\"]\n many_parameters_json = dict(total=\"2\", issues=[])\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"many_parameters\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_side_effect=[\n- {}, many_parameters_json, functions_json, many_parameters_json, functions_json])\n+ {}, many_parameters_json, functions_json, many_parameters_json, functions_json, many_parameters_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=c:S107,csharpsquid:S107,\"\n@@ -119,14 +120,15 @@ def test_many_parameters(self):\n \"plsql:PlSql.FunctionAndProcedureExcessiveParameters,python:S107,squid:S00107,tsql:S107,\"\n \"typescript:S107\")\n \n- def test_long_units(self):\n+ async def test_long_units(self):\n \"\"\"Test that the number of long units is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"rules\"] = [\"rule1\"]\n long_units_json = dict(total=\"2\", issues=[])\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"long_units\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n- metric, get_request_json_side_effect=[{}, long_units_json, functions_json, long_units_json, functions_json])\n+ response = await self.collect(\n+ metric, get_request_json_side_effect=[\n+ {}, long_units_json, functions_json, long_units_json, functions_json, long_units_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=abap:S104,c:FileLoc,\"\n@@ -136,17 +138,17 @@ def test_long_units(self):\n \"squid:S2972,swift:S104,typescript:S104,typescript:S138,vbnet:S104,vbnet:S138,\"\n \"Web:FileLengthCheck,Web:LongJavaScriptCheck\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the number of days since the last analysis is returned.\"\"\"\n json = dict(analyses=[dict(date=\"2019-03-29T14:20:15+0100\")])\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n timezone_info = timezone(timedelta(hours=1))\n expected_age = (datetime.now(timezone_info) - datetime(2019, 3, 29, 14, 20, 15, tzinfo=timezone_info)).days\n self.assert_measurement(\n response, value=str(expected_age), landing_url=\"https://sonar/project/activity?id=id&branch=master\")\n \n- def test_suppressed_violations(self):\n+ async def test_suppressed_violations(self):\n \"\"\"Test that the number of suppressed violations includes both suppressed issues as well as suppressed rules.\"\"\"\n violations_json = dict(\n total=\"1\", issues=[dict(key=\"a\", message=\"a\", component=\"a\", severity=\"INFO\", type=\"BUG\")])\n@@ -156,7 +158,7 @@ def test_suppressed_violations(self):\n dict(key=\"b\", message=\"b\", component=\"b\", severity=\"MAJOR\", type=\"CODE_SMELL\", resolution=\"WONTFIX\")])\n total_violations_json = dict(total=\"4\")\n metric = dict(type=\"suppressed_violations\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[{}, violations_json, wont_fix_json, total_violations_json])\n expected_entities = [\n dict(component=\"a\", key=\"a\", message=\"a\", severity=\"info\", type=\"bug\",\n@@ -168,52 +170,53 @@ def test_suppressed_violations(self):\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=csharpsquid:S1309,\"\n \"php:NoSonar,Pylint:I0011,Pylint:I0020,squid:NoSonar,squid:S1309,squid:S1310,squid:S1315\")\n \n- def test_loc_returns_ncloc_by_default(self):\n+ async def test_loc_returns_ncloc_by_default(self):\n \"\"\"Test that the number of lines of non-comment code is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"ncloc\", value=\"1234\")]))\n metric = dict(type=\"loc\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"1234\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=ncloc&branch=master\")\n \n- def test_loc_all_lines(self):\n+ async def test_loc_all_lines(self):\n \"\"\"Test that the number of lines of code is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lines_to_count\"] = \"all lines\"\n json = dict(component=dict(measures=[dict(metric=\"lines\", value=\"1234\")]))\n metric = dict(type=\"loc\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"1234\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=lines&branch=master\")\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"tests\", value=\"123\")]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"123\", total=\"123\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_skipped_tests(self):\n+ async def test_nr_of_skipped_tests(self):\n \"\"\"Test that the number of skipped tests is returned.\"\"\"\n json = dict(\n component=dict(measures=[dict(metric=\"tests\", value=\"123\"), dict(metric=\"skipped_tests\", value=\"4\")]))\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"skipped\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"4\", total=\"123\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_tests_without_tests(self):\n+ async def test_nr_of_tests_without_tests(self):\n \"\"\"Test that the collector throws an exception if there are no tests.\"\"\"\n json = dict(component=dict(measures=[]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=None, total=None, parse_error=\"KeyError\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_tests_with_faulty_component(self):\n+ async def test_nr_of_tests_with_faulty_component(self):\n \"\"\"Test that the measurement fails if the component does not exist.\"\"\"\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=dict(errors=[dict(msg=\"No such component\")]))\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(errors=[dict(msg=\"No such component\")]))\n self.assert_measurement(\n response, value=None, total=None, connection_error=\"No such component\", landing_url=self.tests_landing_url)\ndiff --git a/components/collector/tests/source_collectors/test_trello.py b/components/collector/tests/source_collectors/api_source_collectors/test_trello.py\nsimilarity index 79%\nrename from components/collector/tests/source_collectors/test_trello.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_trello.py\n--- a/components/collector/tests/source_collectors/test_trello.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_trello.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class TrelloTestCase(SourceCollectorTestCase):\n@@ -45,28 +45,28 @@ def setUp(self):\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n self.json = [[dict(id=\"board1\", name=\"Board1\")], self.cards, self.cards]\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the number of issues and the individual issues are returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_issues_with_ignored_list(self):\n+ async def test_issues_with_ignored_list(self):\n \"\"\"Test that lists can be ignored when counting issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n- def test_overdue_issues(self):\n+ async def test_overdue_issues(self):\n \"\"\"Test overdue issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"overdue\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n- def test_inactive_issues(self):\n+ async def test_inactive_issues(self):\n \"\"\"Test inactive issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"inactive\"]\n self.cards[\"cards\"][0][\"dateLastActivity\"] = datetime.now().isoformat()\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n \n@@ -78,13 +78,13 @@ def setUp(self):\n self.metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n self.side_effect = [[dict(id=\"board1\", name=\"Board1\")], self.cards, self.cards]\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the source up to dateness is the number of days since the most recent change.\"\"\"\n- response = self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 3, 3)).days))\n \n- def test_age_with_ignored_lists(self):\n+ async def test_age_with_ignored_lists(self):\n \"\"\"Test that lists can be ignored when measuring the source up to dateness.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 2, 10)).days))\ndiff --git a/components/collector/tests/source_collectors/test_wekan.py b/components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_wekan.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\n--- a/components/collector/tests/source_collectors/test_wekan.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n from typing import Dict\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class WekanTestCase(SourceCollectorTestCase):\n@@ -19,8 +19,7 @@ def setUp(self):\n inactive_days=\"90\", lists_to_ignore=[])))\n self.json = [\n dict(_id=\"user_id\"),\n- [dict(_id=\"board1\", title=\"Board 1\")],\n- dict(slug=\"board-slug\"),\n+ [dict(_id=\"board1\", title=\"Board 1\", slug=\"board-slug\")],\n [self.list(1), self.list(2), self.list(3, archived=True)],\n [self.card(1), self.card(2)],\n self.full_card(1),\n@@ -59,36 +58,36 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the number of issues and the individual issues are returned and that archived cards are ignored.\"\"\"\n- self.json[6][\"archived\"] = True\n- response = self.collect(\n+ self.json[5][\"archived\"] = True\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_issues_with_ignored_list(self):\n+ async def test_issues_with_ignored_list(self):\n \"\"\"Test that lists can be ignored when counting issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list2\"]\n- self.json[6][\"archived\"] = True\n+ self.json[5][\"archived\"] = True\n del self.entities[1]\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"1\", entities=self.entities)\n \n- def test_overdue_issues(self):\n+ async def test_overdue_issues(self):\n \"\"\"Test overdue issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"overdue\"]\n- self.entities[0][\"due_date\"] = self.json[5][\"dueAt\"] = \"2019-01-01\"\n- self.entities[1][\"due_date\"] = self.json[8][\"dueAt\"] = \"2019-02-02\"\n- response = self.collect(\n+ self.entities[0][\"due_date\"] = self.json[4][\"dueAt\"] = \"2019-01-01\"\n+ self.entities[1][\"due_date\"] = self.json[7][\"dueAt\"] = \"2019-02-02\"\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_inactive_issues(self):\n+ async def test_inactive_issues(self):\n \"\"\"Test inactive issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"inactive\"]\n- self.json[6][\"dateLastActivity\"] = datetime.now().isoformat()\n- response = self.collect(\n+ self.json[5][\"dateLastActivity\"] = datetime.now().isoformat()\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n@@ -96,10 +95,10 @@ def test_inactive_issues(self):\n class WekanSourceUpToDatenessTest(WekanTestCase):\n \"\"\"Unit tests for the Wekan source up-to-dateness collector.\"\"\"\n \n- def test_age_with_ignored_lists(self):\n+ async def test_age_with_ignored_lists(self):\n \"\"\"Test that lists can be ignored when measuring the number of days since the last activity.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 1, 1)).days))\ndiff --git a/components/collector/tests/source_collectors/file_source_collectors/__init__.py b/components/collector/tests/source_collectors/file_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/source_collectors/test_anchore.py b/components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\nsimilarity index 81%\nrename from components/collector/tests/source_collectors/test_anchore.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\n--- a/components/collector/tests/source_collectors/test_anchore.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\n@@ -5,7 +5,7 @@\n import zipfile\n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class AnchoreTestCase(SourceCollectorTestCase):\n@@ -34,18 +34,18 @@ def setUp(self):\n key=\"1fe53aa1061841cbd9fcdab1179191dc\", cve=\"CVE-000\", url=\"https://cve\", fix=\"None\", severity=\"Low\",\n package=\"package\")]\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test the number of security warnings.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.vulnerabilities_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.vulnerabilities_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"anchore.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_anchore_report:\n zipped_anchore_report.writestr(\"vuln.json\", json.dumps(self.vulnerabilities_json))\n zipped_anchore_report.writestr(\"details.json\", json.dumps(self.details_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n@@ -57,16 +57,16 @@ def setUp(self):\n self.metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"max\")\n self.expected_age = (datetime.now(tz=timezone.utc) - datetime(2020, 2, 7, 22, 53, 43, tzinfo=timezone.utc)).days\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.details_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.details_json)\n self.assert_measurement(response, value=str(self.expected_age))\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"details_url\"] = \"anchore.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_anchore_report:\n zipped_anchore_report.writestr(\"vuln.json\", json.dumps(self.vulnerabilities_json))\n zipped_anchore_report.writestr(\"details.json\", json.dumps(self.details_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=str(self.expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_axe_csv.py b/components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\nsimilarity index 78%\nrename from components/collector/tests/source_collectors/test_axe_csv.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\n--- a/components/collector/tests/source_collectors/test_axe_csv.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\n@@ -4,7 +4,7 @@\n import zipfile\n \n from collector_utilities.functions import md5_hash\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class AxeCSVAccessibilityTest(SourceCollectorTestCase):\n@@ -41,44 +41,44 @@ def setUp(self):\n for entity in self.expected_entities:\n entity[\"key\"] = md5_hash(\",\".join(str(value) for value in entity.values()))\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"2\", entities=self.expected_entities)\n \n- def test_no_issues(self):\n+ async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n- response = self.collect(self.metric, get_request_text=\"\")\n+ response = await self.collect(self.metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_filter_by_impact(self):\n+ async def test_filter_by_impact(self):\n \"\"\"Test that violations can be filtered by impact level.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"impact\"] = [\"serious\", \"critical\"]\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"1\")\n \n- def test_filter_by_violation_type(self):\n+ async def test_filter_by_violation_type(self):\n \"\"\"Test that violations can be filtered by violation type.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"violation_type\"] = \\\n [\"aria-input-field-name\", \"area-hidden-focus\"]\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"1\")\n \n- def test_zipped_csv(self):\n+ async def test_zipped_csv(self):\n \"\"\"Test that a zip archive with CSV files is processed correctly.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"url\"] = \"https://axecsv.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_axe_csv:\n for index in range(2):\n zipped_axe_csv.writestr(f\"axe{index}.csv\", self.csv)\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"4\", entities=self.expected_entities + self.expected_entities)\n \n- def test_empty_line(self):\n+ async def test_empty_line(self):\n \"\"\"Test that empty lines are ignored.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.csv + \"\\n\\n\")\n+ response = await self.collect(self.metric, get_request_text=self.csv + \"\\n\\n\")\n self.assert_measurement(response, value=\"2\", entities=self.expected_entities)\n \n- def test_embedded_newlines(self):\n+ async def test_embedded_newlines(self):\n \"\"\"Test that embedded newlines are ignored.\"\"\"\n violation_with_newline = 'url3,aria-hidden-focus,moderate,help3,html3,\"messages3\\nsecond line\",dom3\\n'\n expected_entity = {\n@@ -91,5 +91,5 @@ def test_embedded_newlines(self):\n 'help': 'help3'\n }\n expected_entity[\"key\"] = md5_hash(\",\".join(str(value) for value in expected_entity.values()))\n- response = self.collect(self.metric, get_request_text=self.csv + violation_with_newline)\n+ response = await self.collect(self.metric, get_request_text=self.csv + violation_with_newline)\n self.assert_measurement(response, value=\"3\", entities=self.expected_entities + [expected_entity])\ndiff --git a/components/collector/tests/source_collectors/test_bandit.py b/components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\nsimilarity index 77%\nrename from components/collector/tests/source_collectors/test_bandit.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\n--- a/components/collector/tests/source_collectors/test_bandit.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\n@@ -5,7 +5,7 @@\n import zipfile\n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class BanditTestCase(SourceCollectorTestCase):\n@@ -40,46 +40,46 @@ def setUp(self):\n issue_severity=\"Low\", issue_confidence=\"Medium\",\n more_info=\"https://bandit/b106_hardcoded_password_funcarg.html\")]\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test the number of security warnings.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_warnings_with_high_severity(self):\n+ async def test_warnings_with_high_severity(self):\n \"\"\"Test the number of high severity security warnings.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"severities\"] = [\"high\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_warnings_with_high_confidence(self):\n+ async def test_warnings_with_high_confidence(self):\n \"\"\"Test the number of high confidence security warnings.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"confidence_levels\"] = [\"high\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"bandit.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_bandit_report:\n zipped_bandit_report.writestr(\n \"bandit.json\", json.dumps(self.bandit_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_report_in_gitlab(self):\n+ async def test_report_in_gitlab(self):\n \"\"\"Test that a private token can be added to the request header for accessing a report in GitLab.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"private_token\"] = \"token\"\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n class BanditSourceUpToDatenessTest(BanditTestCase):\n \"\"\"Unit tests for the source up to dateness metric.\"\"\"\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"max\")\n bandit_json = dict(generated_at=\"2019-07-12T07:38:47Z\")\n- response = self.collect(metric, get_request_json_return_value=bandit_json)\n+ response = await self.collect(metric, get_request_json_return_value=bandit_json)\n expected_age = (datetime.now(tz=timezone.utc) - datetime(2019, 7, 12, 7, 38, 47, tzinfo=timezone.utc)).days\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_composer.py b/components/collector/tests/source_collectors/file_source_collectors/test_composer.py\nsimilarity index 81%\nrename from components/collector/tests/source_collectors/test_composer.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_composer.py\n--- a/components/collector/tests/source_collectors/test_composer.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_composer.py\n@@ -1,6 +1,6 @@\n \"\"\"Unit tests for the Composer source.\"\"\"\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class ComposerDependenciesTest(SourceCollectorTestCase):\n@@ -22,13 +22,13 @@ def setUp(self):\n self.sources = dict(source_id=dict(type=\"composer\", parameters=dict(url=\"composer.json\")))\n self.metric = dict(type=\"dependencies\", sources=self.sources, addition=\"sum\")\n \n- def test_dependencies(self):\n+ async def test_dependencies(self):\n \"\"\"Test that the number of dependencies is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.composer_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.composer_json)\n self.assert_measurement(response, value=\"2\", total=\"2\", entities=self.expected_entities)\n \n- def test_dependencies_by_status(self):\n+ async def test_dependencies_by_status(self):\n \"\"\"Test that the number of dependencies can be filtered by status.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"latest_version_status\"] = [\"safe update possible\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.composer_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.composer_json)\n self.assert_measurement(response, value=\"1\", total=\"2\", entities=self.expected_entities[:1])\ndiff --git a/components/collector/tests/source_collectors/test_jacoco.py b/components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\nsimilarity index 77%\nrename from components/collector/tests/source_collectors/test_jacoco.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\n--- a/components/collector/tests/source_collectors/test_jacoco.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JaCoCoTest(SourceCollectorTestCase):\n@@ -14,33 +14,33 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jacoco\", parameters=dict(url=\"https://jacoco/\")))\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the total number of lines are returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches is returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"4\", total=\"10\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text='')\n+ response = await self.collect(metric, get_request_text='')\n expected_age = (datetime.utcnow() - datetime.utcfromtimestamp(1553821197.442)).days\n self.assert_measurement(response, value=str(expected_age))\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zipped report can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"https://jacoco.zip\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_jacoco_report:\n zipped_jacoco_report.writestr(\n \"jacoco.xml\", \"\")\n- response = self.collect(metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"2\", total=\"6\")\ndiff --git a/components/collector/tests/source_collectors/test_junit.py b/components/collector/tests/source_collectors/file_source_collectors/test_junit.py\nsimilarity index 83%\nrename from components/collector/tests/source_collectors/test_junit.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_junit.py\n--- a/components/collector/tests/source_collectors/test_junit.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_junit.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JUnitTestReportTest(SourceCollectorTestCase):\n@@ -29,35 +29,35 @@ def setUp(self):\n dict(key=\"tc4\", name=\"tc4\", class_name=\"cn\", test_result=\"errored\"),\n dict(key=\"tc5\", name=\"tc5\", class_name=\"cn\", test_result=\"skipped\")]\n \n- def test_tests(self):\n+ async def test_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.junit_xml)\n+ response = await self.collect(self.metric, get_request_text=self.junit_xml)\n self.assert_measurement(response, value=\"5\", entities=self.expected_entities)\n \n- def test_failed_tests(self):\n+ async def test_failed_tests(self):\n \"\"\"Test that the failed tests are returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"failed\"]\n- response = self.collect(self.metric, get_request_text=self.junit_xml)\n+ response = await self.collect(self.metric, get_request_text=self.junit_xml)\n self.assert_measurement(\n response, value=\"1\", entities=[dict(key=\"tc3\", name=\"tc3\", class_name=\"cn\", test_result=\"failed\")])\n \n- def test_zipped_junit_report(self):\n+ async def test_zipped_junit_report(self):\n \"\"\"Test that the number of tests is returned from a zip with JUnit reports.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"junit.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_bandit_report:\n zipped_bandit_report.writestr(\"junit.xml\", self.junit_xml)\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"5\", entities=self.expected_entities)\n \n \n class JUnitSourceUpToDatenessTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the source up-to-dateness metric.\"\"\"\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n sources = dict(source_id=dict(type=\"junit\", parameters=dict(url=\"junit.xml\")))\n metric = dict(type=\"source_up_to_dateness\", sources=sources, addition=\"max\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text='')\n expected_age = (datetime.now() - datetime(2009, 12, 19, 17, 58, 59)).days\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_ncover.py b/components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_ncover.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\n--- a/components/collector/tests/source_collectors/test_ncover.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class NCoverTest(SourceCollectorTestCase):\n@@ -25,16 +25,16 @@ def setUp(self):\n };\n \"\"\"\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered sequence points is returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=self.ncover_html)\n+ response = await self.collect(metric, get_request_text=self.ncover_html)\n self.assert_measurement(response, value=f\"{17153-14070}\", total=\"17153\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches is returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=\"\"\"\n+ response = await self.collect(metric, get_request_text=\"\"\"\n \n@@ -48,19 +48,19 @@ def test_uncovered_branches(self):\n \"\"\")\n self.assert_measurement(response, value=f\"{12034-9767}\", total=\"12034\")\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that the coverage can be read from a zip with NCover reports.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"https://report.zip\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_ncover_report:\n zipped_ncover_report.writestr(\"ncover.html\", self.ncover_html)\n- response = self.collect(metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=f\"{17153-14070}\", total=\"17153\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=\"\"\"\n+ response = await self.collect(metric, get_request_text=\"\"\"\n