from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)
f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):
        if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)
f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)
f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):
        if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        re


from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)
f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):
        if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)

from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()

f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):
        if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):
        try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


try:
            return country_converters[name].convert(self.alpha2)
        except KeyError:
            raise AttributeError(name)

from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream  # @UnresolvedImport
from .converters import ConverterManager
from . import basestr

COUNTRIES = {}
COUNTRY_MATRIX = []

#: The namedtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])

f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
    iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
    COUNTRIES[iso_country.alpha2] = iso_country.name
    COUNTRY_MATRIX.append(iso_country)
f.close()

class CountryConverterManager(ConverterManager):
    """:class:`~babelfish.converters.ConverterManager` for country converters"""
    entry_point = 'babelfish.country_converters'
    internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']

country_converters = CountryConverterManager()

class CountryMeta(type):
    """The :class:`Country` metaclass

    Dynamically redirect :meth:`Country.frommycode` to :meth:`Country.fromcode` with the ``mycode`` `converter`

    """
    def __getattr__(cls, name):
        if name.startswith('from'):
            return partial(cls.fromcode, converter=name[4:])
        return type.__getattribute__(cls, name)

class Country(CountryMeta(str('CountryBase'), (object,), {})):
    """A country on Earth

    A country is represented by a 2-letter code from the ISO-3166 standard

    :param string country: 2-letter ISO-3166 country code

    """
    def __init__(self, country):
        if country not in COUNTRIES:
            raise ValueError('%r is not a valid country' % country)

        #: ISO-3166 2-letter country code
        self.alpha2 = country

    @classmethod
    def fromcode(cls, code, converter):
        """Create a :class:`Country` by its `code` using `converter` to
        :meth:`~babelfish.converters.CountryReverseConverter.reverse` it

        :param string code: the code to reverse
        :param string converter: name of the :class:`~babelfish.converters.CountryReverseConverter` to use
        :return: the corresponding :class:`Country` instance
        :rtype: :class:`Country`

        """
        return cls(country_converters[converter].reverse(code))

    def __getstate__(self):
        return self.alpha2

    def __setstate__(self, state):
        self.alpha2 = state

    def __getattr__(self, name):

    def __hash__(self):
        return hash(self.alpha2)

    def __eq__(self, other):
        if isinstance(other, basestr):
            return str(self) == other
        if not isinstance(other, Country):
            return False
        return self.alpha2 == other.alpha2

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return '<Country [%s]>' % self

    def __str__(self):
        return self.alpha2


def create_user_project_settings_if_not_exists(project, user,
                                               homepage=Section.timeline):

from django.apps import apps
from django.db import IntegrityError
from django.utils.translation import ugettext as _

from taiga.base import exceptions as exc
from taiga.projects.settings.choices import Section

def user_project_settings_exists(project, user) -> bool:
    """
    Check if policy exists for specified project
    and user.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    qs = model_cls.objects.filter(project=project,
                                  user=user)
    return qs.exists()

def create_user_project_settings(project, user, homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

"""
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        result = model_cls.objects.get_or_create(
            project=project,
            user=user,
            defaults={"homepage": homepage}
        )
        return result[0]
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


"""
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

from django.apps import apps
from django.db import IntegrityError
from django.utils.translation import ugettext as _

from taiga.base import exceptions as exc
from taiga.projects.settings.choices import Section

def user_project_settings_exists(project, user) -> bool:
    """
    Check if policy exists for specified project
    and user.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    qs = model_cls.objects.filter(project=project,
                                  user=user)
    return qs.exists()

def create_user_project_settings(project, user, homepage=Section.timeline):

def create_user_project_settings_if_not_exists(project, user,
                                               homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        result = model_cls.objects.get_or_create(
            project=project,
            user=user,
            defaults={"homepage": homepage}
        )
        return result[0]
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

def create_user_project_settings_if_not_exists(project, user,
                                               homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        result = model_cls.objects.get_or_create(
            project=project,
            user=user,
            defaults={"homepage": homepage}
        )
        return result[0]
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


from django.apps import apps
from django.db import IntegrityError
from django.utils.translation import ugettext as _

from taiga.base import exceptions as exc
from taiga.projects.settings.choices import Section

def user_project_settings_exists(project, user) -> bool:
    """
    Check if policy exists for specified project
    and user.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    qs = model_cls.objects.filter(project=project,
                                  user=user)
    return qs.exists()

def create_user_project_settings(project, user, homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """

    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

def create_user_project_settings_if_not_exists(project, user,
                                               homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        result = model_cls.objects.get_or_create(
            project=project,
            user=user,
            defaults={"homepage": homepage}
        )
        return result[0]
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

from django.apps import apps
from django.db import IntegrityError
from django.utils.translation import ugettext as _

from taiga.base import exceptions as exc
from taiga.projects.settings.choices import Section

def user_project_settings_exists(project, user) -> bool:
    """
    Check if policy exists for specified project
    and user.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    qs = model_cls.objects.filter(project=project,
                                  user=user)
    return qs.exists()

def create_user_project_settings(project, user, homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")


from django.apps import apps
from django.db import IntegrityError
from django.utils.translation import ugettext as _

from taiga.base import exceptions as exc
from taiga.projects.settings.choices import Section

def user_project_settings_exists(project, user) -> bool:
    """
    Check if policy exists for specified project
    and user.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    qs = model_cls.objects.filter(project=project,
                                  user=user)
    return qs.exist

def create_user_project_settings(project, user, homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e

def create_user_project_settings_if_not_exists(project, user,
                                               homepage=Section.timeline):
    """
    Given a project and user, create notification policy for it.
    """
    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        result = model_cls.objects.get_or_create(
            project=project,
            user=user,
            defaults={"homepage": homepage}
        )
        return result[0]
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


    model_cls = apps.get_model("settings", "UserProjectSettings")
    try:
        return model_cls.objects.create(project=project,
                                        user=user,
                                        homepage=homepage)
    except IntegrityError as e:
        raise exc.IntegrityError(
            _("Notify exists for specified user and project")) from e


def simple_binary_search_internally(arr, low, high, value):

# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0
    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

"""
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)
    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


"""
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0
    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)
    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


"""
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0

    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)
    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0

    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)
    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0
    high = n - 1


# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0
    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid

    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


    low = 0
    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """


if arr[mid] == value:
        return mid

# create by oldman
"""
>>> a = [1, 2,3 ,4, 5, 6, 7, 8]
>>> simple_binary_search(a, 8, 4)
3
>>> simple_binary_search_internally(a,0,7,4)
3
"""

def simple_binary_search(arr, n, value):
    """
    简单的二分查找
    :param arr:
    :param n:
    :param value:
    :return:
    """
    low = 0
    high = n - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)

    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


while low <= high:
        mid = (low + high) // 2
        if arr[mid] == value:
            return mid
        elif arr[mid] < value:
            low = mid + 1
        else:
            high = mid - 1

    return -1

def simple_binary_search_internally(arr, low, high, value):
    """
    简单二分查找的递归实现
    :param arr: 有序数组
    :param low:
    :param high:
    :param value: 查找值
    :return:
    """
    if low > high:
        return -1
    mid = low + ((high - low) >> 1)
    if arr[mid] == value:
        return mid
    if arr[mid] < value:
        return simple_binary_search_internally(arr, mid+1, high, value)
    else:
        return simple_binary_search_internally()


from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():


browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():

    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3

    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))


for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:
            try:
                place1 = i.text
            except:
                price1 == None
            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []

        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


try:
                place1 = i.text
            except:
                price1 == None

from selenium import webdriver
import re
from selenium.webdriver.common.by import  By
from selenium.webdriver.support.ui import WebDriverWait
import time
from lxml import etree
from time import sleep
import random
from selenium.webdriver.support import expected_conditions as EC
chrome_driver = r"D:\ProgramData\Anaconda3\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
browser = webdriver.Chrome(executable_path=chrome_driver)
wait=WebDriverWait(browser,3)

def search():
    browser.get('https://www.taobao.com')
    browser.find_element_by_name('q').send_keys('美食')
    sleep(2)
    browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()  ##搜索按钮
    browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click() #点击密码登录
    sleep(3)
    browser.find_element_by_xpath('//*[@id="J_OtherLogin"]/a[1]').click() #点击微博登录
    sleep(3)
    browser.find_element_by_name('username').send_keys('微博号')
    browser.find_element_by_name('password').send_keys('微博密码')

    browser.find_element_by_xpath('//*[@id="pl_login_logged"]/div/div[7]/div[1]/a').click()
    sleep(2)

    total=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]')
    print(total.text)
    sleep(3)
    get_products(1)
    return total.text

def database():
    coon = pymysql.connect(
        host='localhost', user='root', passwd='',
        port=3306, db='taobao', charset='utf8'
    )
    cur = coon.cursor()  # 建立游标
    return cur, coon

def get_products(page):
        price = browser.find_elements_by_xpath('//div[@class="price g_price g_price-highlight"]/strong')
        title = browser.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[2]/a')
        place = browser.find_elements_by_xpath('//div[@class="row row-3 g-clearfix"]/div[2]')
        buy_num = browser.find_elements_by_xpath('//div[@class="row row-1 g-clearfix"]/div[2]')
        shop=browser.find_elements_by_xpath('//div[@class="shop"]/a/span[2]')
        print('第', page, '页,共有---', len(price), '个数据')

        prices = []
        for i in price:
            try:
                price1 = i.text
            except:
                price1 == None
            prices.append(price1)
        print(prices)
        titles=[]
        for i in title:
            try:
                title1 = i.text
            except:
                title1==None
            titles.append(title1)
        print(titles)

        places = []
        for i in place:

            places.append(place1)
        print(places)

        buy_nums = []
        for i in buy_num:
            try:
                buy_num1 = i.text
            except:
                buy_num1 == None
            buy_nums.append(buy_num1)
        print(buy_nums)

        shops = []
        for i in shop:
            try:
                shop1 = i.text
            except:
                shop1 == None
            shops.append(shop1)
        print(shops)
        cur,coon=database()
        for i in range(len(price)):
            try:
                shop=shops[i]
                buy_num=buy_nums[i]
                price=prices[i]
                title=titles[i]
                place=places[i]
                ss = (str(shop),str(title), str(price), str(place), str(buy_num))
                print(ss)
                sql = "insert into taobao_food(shop,title,price,place,buy_num) VALUE('%s','%s','%s','%s','%s')" % ss
                cur.execute(sql)
            except:
                pass
        coon.commit()
        print('------------------------------页数-------------------------------------')

import pymysql

def next_page(page_number):
    try:
        input=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        submit=browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]')
        input.clear()
        input.send_keys(page_number)
        submit.click()
        print('第' + str(page_number) + '页正在翻------------')
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))
        get_products(page_number)
    except TimeoutError:
        next_page(page_number)
def main():
    total=search()
    time.sleep(random.uniform(8, 0))
    total=int(re.compile('(\d+)').search(total).group(1))
    for i  in range(87,total+1):
        next_page(i)
        time.sleep(random.uniform(8, 10))

if __name__ == '__main__':
    main()


from __future__ import unicode_literals

import json

from django.db import connection
from django.db.models import Count, F
from django.http import HttpResponse

from django.views.generic import TemplateView

from candidates.models import MembershipExtra
from elections.mixins import ElectionMixin
from elections.models import Election
from popolo.models import Membership, Person

from .models import get_attention_needed_posts

def get_prior_election_data(
        total_current, current_election,
        total_prior, prior_election
):
    # Find all those people who are standing in both elections:
    persons_standing_again = list(Person.objects \
        .filter(memberships__extra__election=current_election) \
        .filter(memberships__extra__election=prior_election) \
        .prefetch_related('memberships', 'memberships__extra')
    )
    # Now see how many are standing for the same party in both:
    standing_again = len(persons_standing_again)
    new_candidates = total_current - standing_again
    standing_again_same_party = 0
    for p in persons_standing_again:
        current_party = None
        prior_party = None
        for m in p.memberships.all():
            try:
                extra = m.extra
                if extra.election_id == current_election.id:
                    current_party = m.on_behalf_of_id
                elif extra.election_id == prior_election.id:
                    prior_party = m.on_behalf_of_id
            except MembershipExtra.DoesNotExist:
                # We need this because some memberships may not have
                # an extra.
                pass
        if current_party == prior_party:
            standing_again_same_party += 1
    standing_again_different_party = \
        standing_again - standing_again_same_party
    return {
        'name': prior_election.name,
        'percentage': 100 * float(total_current) / total_prior,
        'new_candidates': new_candidates,
        'standing_again': standing_again,
        'standing_again_different_party': standing_again_different_party,
        'standing_again_same_party': standing_again_same_party,
    }

def get_counts():
    election_id_to_candidates = {
        d['extra__election']: d['count']
        for d in Membership.objects \
            .filter(role=F('extra__election__candidate_membership_role')) \
            .values('extra__election') \
            .annotate(count=Count('extra__election'))
    }
    grouped_elections = Election.group_and_order_elections()
    past_elections = [
        election_data['election']
        for era_data in grouped_elections
        for role_data in era_data['roles']
        for election_data in role_data['elections']
        if not era_data['current']
    ]
    for era_data in grouped_elections:
        for role_data in era_data['roles']:
            for election_data in role_data['elections']:
                e = election_data['election']
                total = election_id_to_candidates.get(e.id, 0)
                election_counts = {
                    'id': e.slug,
                    'html_id': e.slug.replace('.', '-'),
                    'name': e.name,
                    'total': total,
                }
                if era_data['current']:
                    election_counts['prior_elections'] = [
                        get_prior_election_data(
                            total, e,
                            election_id_to_candidates.get(pe.id, 0), pe
                        )
                        for pe in past_elections
                        if pe.for_post_role == e.for_post_role
                    ]
                election_data.update(election_counts)
                del election_data['election']
    return grouped_elections

class ReportsHomeView(TemplateView):
    template_name = "reports.html"

    def get_context_data(self, **kwargs):
        context = super(ReportsHomeView, self).get_context_data(**kwargs)
        context['all_elections'] = get_counts()
        return context

    def get(self, *args, **kwargs):
        if self.request.GET.get('format') == "json":
            return HttpResponse(
                json.dumps(get_counts()),
                content_type="application/json"
            )
        return super(ReportsHomeView, self).get(*args, **kwargs)

class PartyCountsView(ElectionMixin, TemplateView):
    template_name = "party_counts.html"

    def get_context_data(self, **kwargs):
        context = super(PartyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()
        cursor.execute('''
SELECT oe.slug, o.name, count(m.id) AS count
  FROM popolo_organization o
    INNER JOIN candidates_organizationextra oe ON o.id = oe.base_id
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me ON me.base_id = m.id
        INNER JOIN elections_election ee ON me.election_id = ee.id AND ee.id = %s)
      ON o.id = m.on_behalf_of_id
  WHERE o.classification = 'Party'
  GROUP BY oe.slug, o.name
  ORDER BY count DESC, o.name;
        ''', [self.election_data.id])
        context['party_counts'] = [
            {
                'party_slug': row[0],
                'party_name': row[1],
                'count': row[2],
            }
            for row in cursor.fetchall()
        ]
        return context

class ConstituencyCountsView(ElectionMixin, TemplateView):
    template_name = "constituency_counts.html"

    def get_context_data(self, **kwargs):
        from candidates.election_specific import shorten_post_label
        context = super(ConstituencyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()
        cursor.execute('''
SELECT pe.slug, p.label, count(m.id) as count
  FROM popolo_post p
    INNER JOIN candidates_postextra pe ON pe.base_id = p.id
    INNER JOIN candidates_postextraelection cppee ON cppee.postextra_id = pe.id
    INNER JOIN elections_election ee ON cppee.election_id = ee.id AND ee.id = %s
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me
        ON me.base_id = m.id)
      ON m.role = ee.candidate_membership_role AND m.post_id = p.id AND
         me.election_id = ee.id
  GROUP BY pe.slug, p.label
  ORDER BY count DESC;
        ''', [self.election_data.id])
        context['post_counts'] = [
            {
                'post_slug': row[0],
                'post_label': row[1],
                'count': row[2],
                'post_short_label': shorten_post_label(row[1]),
            }
            for row in cursor.fetchall()
        ]
        return context

class AttentionNeededView(TemplateView):
    template_name = "attention_needed.html"

context = super(AttentionNeededView, self).get_context_data(**kwargs)
        context['post_counts'] = get_attention_needed_posts()
        return context


if self.request.GET.get('format') == "json":
            return HttpResponse(
                json.dumps(get_counts()),
                content_type="application/json"
            )
        return super(ReportsHomeView, self).get(*args, **kwargs)

from __future__ import unicode_literals

import json

from django.db import connection
from django.db.models import Count, F
from django.http import HttpResponse

from django.views.generic import TemplateView

from candidates.models import MembershipExtra
from elections.mixins import ElectionMixin
from elections.models import Election
from popolo.models import Membership, Person

from .models import get_attention_needed_posts

def get_prior_election_data(
        total_current, current_election,
        total_prior, prior_election
):
    # Find all those people who are standing in both elections:
    persons_standing_again = list(Person.objects \
        .filter(memberships__extra__election=current_election) \
        .filter(memberships__extra__election=prior_election) \
        .prefetch_related('memberships', 'memberships__extra')
    )
    # Now see how many are standing for the same party in both:
    standing_again = len(persons_standing_again)
    new_candidates = total_current - standing_again
    standing_again_same_party = 0
    for p in persons_standing_again:
        current_party = None
        prior_party = None
        for m in p.memberships.all():
            try:
                extra = m.extra
                if extra.election_id == current_election.id:
                    current_party = m.on_behalf_of_id
                elif extra.election_id == prior_election.id:
                    prior_party = m.on_behalf_of_id
            except MembershipExtra.DoesNotExist:
                # We need this because some memberships may not have
                # an extra.
                pass
        if current_party == prior_party:
            standing_again_same_party += 1
    standing_again_different_party = \
        standing_again - standing_again_same_party
    return {
        'name': prior_election.name,
        'percentage': 100 * float(total_current) / total_prior,
        'new_candidates': new_candidates,
        'standing_again': standing_again,
        'standing_again_different_party': standing_again_different_party,
        'standing_again_same_party': standing_again_same_party,
    }

def get_counts():
    election_id_to_candidates = {
        d['extra__election']: d['count']
        for d in Membership.objects \
            .filter(role=F('extra__election__candidate_membership_role')) \
            .values('extra__election') \
            .annotate(count=Count('extra__election'))
    }
    grouped_elections = Election.group_and_order_elections()
    past_elections = [
        election_data['election']
        for era_data in grouped_elections
        for role_data in era_data['roles']
        for election_data in role_data['elections']
        if not era_data['current']
    ]
    for era_data in grouped_elections:
        for role_data in era_data['roles']:
            for election_data in role_data['elections']:
                e = election_data['election']
                total = election_id_to_candidates.get(e.id, 0)
                election_counts = {
                    'id': e.slug,
                    'html_id': e.slug.replace('.', '-'),
                    'name': e.name,
                    'total': total,
                }
                if era_data['current']:
                    election_counts['prior_elections'] = [
                        get_prior_election_data(
                            total, e,
                            election_id_to_candidates.get(pe.id, 0), pe
                        )
                        for pe in past_elections
                        if pe.for_post_role == e.for_post_role
                    ]
                election_data.update(election_counts)
                del election_data['election']
    return grouped_elections

class ReportsHomeView(TemplateView):
    template_name = "reports.html"

    def get_context_data(self, **kwargs):
        context = super(ReportsHomeView, self).get_context_data(**kwargs)
        context['all_elections'] = get_counts()
        return context

    def get(self, *args, **kwargs):

class PartyCountsView(ElectionMixin, TemplateView):
    template_name = "party_counts.html"

    def get_context_data(self, **kwargs):
        context = super(PartyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()
        cursor.execute('''
SELECT oe.slug, o.name, count(m.id) AS count
  FROM popolo_organization o
    INNER JOIN candidates_organizationextra oe ON o.id = oe.base_id
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me ON me.base_id = m.id
        INNER JOIN elections_election ee ON me.election_id = ee.id AND ee.id = %s)
      ON o.id = m.on_behalf_of_id
  WHERE o.classification = 'Party'
  GROUP BY oe.slug, o.name
  ORDER BY count DESC, o.name;
        ''', [self.election_data.id])
        context['party_counts'] = [
            {
                'party_slug': row[0],
                'party_name': row[1],
                'count': row[2],
            }
            for row in cursor.fetchall()
        ]
        return context

class ConstituencyCountsView(ElectionMixin, TemplateView):
    template_name = "constituency_counts.html"

    def get_context_data(self, **kwargs):
        from candidates.election_specific import shorten_post_label
        context = super(ConstituencyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()
        cursor.execute('''
SELECT pe.slug, p.label, count(m.id) as count
  FROM popolo_post p
    INNER JOIN candidates_postextra pe ON pe.base_id = p.id
    INNER JOIN candidates_postextraelection cppee ON cppee.postextra_id = pe.id
    INNER JOIN elections_election ee ON cppee.election_id = ee.id AND ee.id = %s
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me
        ON me.base_id = m.id)
      ON m.role = ee.candidate_membership_role AND m.post_id = p.id AND
         me.election_id = ee.id
  GROUP BY pe.slug, p.label
  ORDER BY count DESC;
        ''', [self.election_data.id])
        context['post_counts'] = [
            {
                'post_slug': row[0],
                'post_label': row[1],
                'count': row[2],
                'post_short_label': shorten_post_label(row[1]),
            }
            for row in cursor.fetchall()
        ]
        return context

class AttentionNeededView(TemplateView):
    template_name = "attention_needed.html"

    def get_context_data(self, **kwargs):
        context = super(AttentionNeededView, self).get_context_data(**kwargs)
        context['post_counts'] = get_attention_needed_posts()
        return context


context = super(PartyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()

from __future__ import unicode_literals

import json

from django.db import connection
from django.db.models import Count, F
from django.http import HttpResponse

from django.views.generic import TemplateView

from candidates.models import MembershipExtra
from elections.mixins import ElectionMixin
from elections.models import Election
from popolo.models import Membership, Person

from .models import get_attention_needed_posts

def get_prior_election_data(
        total_current, current_election,
        total_prior, prior_election
):
    # Find all those people who are standing in both elections:
    persons_standing_again = list(Person.objects \
        .filter(memberships__extra__election=current_election) \
        .filter(memberships__extra__election=prior_election) \
        .prefetch_related('memberships', 'memberships__extra')
    )
    # Now see how many are standing for the same party in both:
    standing_again = len(persons_standing_again)
    new_candidates = total_current - standing_again
    standing_again_same_party = 0
    for p in persons_standing_again:
        current_party = None
        prior_party = None
        for m in p.memberships.all():
            try:
                extra = m.extra
                if extra.election_id == current_election.id:
                    current_party = m.on_behalf_of_id
                elif extra.election_id == prior_election.id:
                    prior_party = m.on_behalf_of_id
            except MembershipExtra.DoesNotExist:
                # We need this because some memberships may not have
                # an extra.
                pass
        if current_party == prior_party:
            standing_again_same_party += 1
    standing_again_different_party = \
        standing_again - standing_again_same_party
    return {
        'name': prior_election.name,
        'percentage': 100 * float(total_current) / total_prior,
        'new_candidates': new_candidates,
        'standing_again': standing_again,
        'standing_again_different_party': standing_again_different_party,
        'standing_again_same_party': standing_again_same_party,
    }

def get_counts():
    election_id_to_candidates = {
        d['extra__election']: d['count']
        for d in Membership.objects \
            .filter(role=F('extra__election__candidate_membership_role')) \
            .values('extra__election') \
            .annotate(count=Count('extra__election'))
    }
    grouped_elections = Election.group_and_order_elections()
    past_elections = [
        election_data['election']
        for era_data in grouped_elections
        for role_data in era_data['roles']
        for election_data in role_data['elections']
        if not era_data['current']
    ]
    for era_data in grouped_elections:
        for role_data in era_data['roles']:
            for election_data in role_data['elections']:
                e = election_data['election']
                total = election_id_to_candidates.get(e.id, 0)
                election_counts = {
                    'id': e.slug,
                    'html_id': e.slug.replace('.', '-'),
                    'name': e.name,
                    'total': total,
                }
                if era_data['current']:
                    election_counts['prior_elections'] = [
                        get_prior_election_data(
                            total, e,
                            election_id_to_candidates.get(pe.id, 0), pe
                        )
                        for pe in past_elections
                        if pe.for_post_role == e.for_post_role
                    ]
                election_data.update(election_counts)
                del election_data['election']
    return grouped_elections

class ReportsHomeView(TemplateView):
    template_name = "reports.html"

    def get_context_data(self, **kwargs):
        context = super(ReportsHomeView, self).get_context_data(**kwargs)
        context['all_elections'] = get_counts()
        return context

    def get(self, *args, **kwargs):
        if self.request.GET.get('format') == "json":
            return HttpResponse(
                json.dumps(get_counts()),
                content_type="application/json"
            )
        return super(ReportsHomeView, self).get(*args, **kwargs)

class PartyCountsView(ElectionMixin, TemplateView):
    template_name = "party_counts.html"

    def get_context_data(self, **kwargs):

        cursor.execute('''
SELECT oe.slug, o.name, count(m.id) AS count
  FROM popolo_organization o
    INNER JOIN candidates_organizationextra oe ON o.id = oe.base_id
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me ON me.base_id = m.id
        INNER JOIN elections_election ee ON me.election_id = ee.id AND ee.id = %s)
      ON o.id = m.on_behalf_of_id
  WHERE o.classification = 'Party'
  GROUP BY oe.slug, o.name
  ORDER BY count DESC, o.name;
        ''', [self.election_data.id])
        context['party_counts'] = [
            {
                'party_slug': row[0],
                'party_name': row[1],
                'count': row[2],
            }
            for row in cursor.fetchall()
        ]
        return context

class ConstituencyCountsView(ElectionMixin, TemplateView):
    template_name = "constituency_counts.html"

    def get_context_data(self, **kwargs):
        from candidates.election_specific import shorten_post_label
        context = super(ConstituencyCountsView, self).get_context_data(**kwargs)
        cursor = connection.cursor()
        cursor.execute('''
SELECT pe.slug, p.label, count(m.id) as count
  FROM popolo_post p
    INNER JOIN candidates_postextra pe ON pe.base_id = p.id
    INNER JOIN candidates_postextraelection cppee ON cppee.postextra_id = pe.id
    INNER JOIN elections_election ee ON cppee.election_id = ee.id AND ee.id = %s
    LEFT OUTER JOIN
      (popolo_membership m
        INNER JOIN candidates_membershipextra me
        ON me.base_id = m.id)
      ON m.role = ee.candidate_membership_role AND m.post_id = p.id AND
         me.election_id = ee.id
  GROUP BY pe.slug, p.label
  ORDER BY count DESC;
        ''', [self.election_data.id])
        context['post_counts'] = [
            {
                'post_slug': row[0],
                'post_label': row[1],
                'count': row[2],
                'post_short_label': shorten_post_label(row[1]),
            }
            for row in cursor.fetchall()
        ]
        return context

class AttentionNeededView(TemplateView):
    template_name = "attention_needed.html"

    def get_context_data(self, **kwargs):
        context = super(AttentionNeededView, self).get_context_data(**kwargs)
        context['post_counts'] = get_attention_needed_posts()
        return context