<commit_before># -*- coding: UTF-8 -*-
from django.db import DatabaseError
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
import math

class RecorridoManager(models.GeoManager):
    def get_recorridos_combinados(self, puntoA, puntoB, distanciaA, distanciaB, gap):
        distanciaA = int(distanciaA)
        distanciaB = int(distanciaB)
        gap = int(gap)
        if not isinstance(puntoA, Point):
            raise DatabaseError("get_recorridos: PuntoA Expected GEOS Point instance as parameter, %s given" % type(puntoA))
        if not isinstance(puntoB, Point):
            raise DatabaseError("get_recorridos: PuntoB Expected GEOS Point instance as parameter, %s given" % type(puntoB))
        if not isinstance(distanciaA, (int, long)):
            raise DatabaseError("get_recorridos: distanciaA Expected integer as parameter, %s given" % type(distanciaA))
        if not isinstance(distanciaB, (int, long)):
            raise DatabaseError("get_recorridos: distanciaB Expected integer as parameter, %s given" % type(distanciaB))
        if not isinstance(gap, (int, long)):
            raise DatabaseError("get_recorridos: gap Expected integer as parameter, %s given" % type(gap))
        puntoA.set_srid(4326)
        puntoB.set_srid(4326)

        params = {'puntoA': puntoA.ewkt, 'puntoB': puntoB.ewkt, 'rad1': distanciaA, 'rad2': distanciaB, 'gap': gap}
        query = """
            SELECT *
            FROM (
                SELECT
                    re1.id as id,
                    li1.nombre || ' ' || re1.nombre as nombre,
                    li2.nombre || ' ' || re2.nombre as nombre2,
                    re2.id as id2,
                    coalesce(re1.color_polilinea, li1.color_polilinea, '#000') as color_polilinea,
                    coalesce(re2.color_polilinea, li2.color_polilinea, '#000') as color_polilinea2,
                    coalesce(li1.foto, 'default') as foto,
                    coalesce(li2.foto, 'default') as foto2,
                    re1.inicio as inicio,
                    re2.inicio as inicio2,
                    re1.fin as fin,
                    re2.fin as fin2,
                    ST_AsText(
                        ST_Line_Substring(
                            re1.ruta,
                            ST_Line_Locate_Point(re1.ruta, %(puntoA)s),
                            ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta))
                            )::Geography
                        ) as ruta_corta,
                    ST_AsText(
                        ST_Line_Substring(
                            re2.ruta,
                            ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta)),
                            ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                            )::Geography
                        ) as ruta_corta2,
                    ST_Length(
                        ST_Line_Substring(
                            re1.ruta,
                            ST_Line_Locate_Point(re1.ruta, %(puntoA)s),
                            ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta))
                            )::Geography
                        ) as long_ruta,
                    ST_Length(
                        ST_Line_Substring(
                            re2.ruta,
                            ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta)),
                            ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                            )::Geography
                        ) as long_ruta2,
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s), re1.ruta) as long_pata,
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s), re2.ruta) as long_pata2,
                    ST_Distance_Sphere(re1.ruta, re2.ruta) as long_pata_transbordo

                FROM
                    core_recorrido as re1
                    join core_recorrido as re2 on (re1.id <> re2.id)
                    join core_linea li1 on li1.id = re1.linea_id
                    join core_linea li2 on li2.id = re2.linea_id
                WHERE
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s), re1.ruta) < %(rad1)s
                    and
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s), re2.ruta) < %(rad2)s
                    and
                        ST_Distance_Sphere(re1.ruta, re2.ruta) < %(gap)s
                    and
                        ST_Line_Locate_Point(re1.ruta, %(puntoA)s)
                        <
                        ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta) )
                    and
                        ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta) )
                        <
                        ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                ) as subquery
            ORDER BY (cast(long_pata as integer)*10 + cast(long_ruta as integer) + cast(long_ruta2 as integer)) ASC
        ;"""
        query_set = self.raw(query, params)
        return list(query_set)

    def get_recorridos(self, puntoA, puntoB, distanciaA, distanciaB):
        distanciaA = int(distanciaA)
        distanciaB = int(distanciaB)
        if not isinstance(puntoA, Point):
            raise DatabaseError("get_recorridos: PuntoA Expected GEOS Point instance as parameter, %s given" % type(puntoA))
        if not isinstance(puntoB, Point):
            raise DatabaseError("get_recorridos: PuntoB Expected GEOS Point instance as parameter, %s given" % type(puntoB))
        if not isinstance(distanciaA, (int, long)):
            raise DatabaseError("get_recorridos: distanciaA Expected integer as parameter, %s given" % type(distanciaA))
        if not isinstance(distanciaB, (int, long)):
            raise DatabaseError("get_recorridos: distanciaB Expected integer as parameter, %s given" % type(distanciaB))
        puntoA.set_srid(4326)
        puntoB.set_srid(4326)
        distanciaA = 0.0000111 * float(distanciaA)
        distanciaB = 0.0000111 * float(distanciaB)

        params = {'puntoA': puntoA.ewkt, 'puntoB': puntoB.ewkt, 'rad1': distanciaA, 'rad2': distanciaB}
        query = """
                SELECT
                    re.id,
                    li.nombre || ' ' || re.nombre as nombre,
                    ruta_corta,
                    round(long_ruta::numeric, 2) as long_ruta,
                    round(long_pata::numeric, 2) as long_pata,
                    coalesce(re.color_polilinea, li.color_polilinea, '#000') as color_polilinea,
                    coalesce(li.foto, 'default') as foto
                FROM
                    core_linea as li join
                    (
                        SELECT
                            id,
                            nombre,
                            ST_AsText(min_path(ruta_corta)) as ruta_corta,
                            min(long_ruta) as long_ruta,
                            min(long_pata) as long_pata,
                            linea_id,
                            color_polilinea
                        FROM
                        (
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) +
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ST_Line_Substring(ruta, 0, 0.5),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5),	%(puntoA)s),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5),	%(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ST_Line_Substring(ruta, 0, 0.5), %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ST_Line_Substring(ruta, 0, 0.5), %(rad2)s) and
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5), %(puntoA)s) <
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5), %(puntoB)s)
                                ) as primera_inner
                            )
                            UNION
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) + ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ST_Line_Substring(ruta, 0.5, 1),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1),	%(puntoA)s),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1),	%(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ST_Line_Substring(ruta, 0.5, 1), %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ST_Line_Substring(ruta, 0.5, 1), %(rad2)s) and
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1), %(puntoA)s) <
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1), %(puntoB)s)
                                ) as segunda_inner
                            )
                            UNION
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) + ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ruta,
                                            ST_Line_Locate_Point(ruta, %(puntoA)s),
                                            ST_Line_Locate_Point(ruta, %(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ruta, %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ruta, %(rad2)s) and
                                        ST_Line_Locate_Point(ruta, %(puntoA)s) <
                                        ST_Line_Locate_Point(ruta, %(puntoB)s)
                                ) as completa_inner
                            )
                        ) as interior
                        GROUP BY
                            id,
                            linea_id,
                            nombre,
                            color_polilinea
                    ) as re
                    on li.id = re.linea_id
                    ORDER BY
                        long_pata*10 + long_ruta asc
            ;"""

        query_set = self.raw(query, params)
        return list(query_set)

    def fuzzy_trgm_query(self, q):
        params = {"q": q}
        query = """
            SELECT
                set_limit(0.01);
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                similarity(l.nombre || ' ' || r.nombre, %(q)s) as similarity,
                Astext(r.ruta) as ruta_corta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
            WHERE
                (l.nombre || ' ' || r.nombre) %% %(q)s
            ORDER BY
                similarity DESC
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_fts_query(self, q):
        params = {"q": q}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                ts_rank_cd(to_tsvector('spanish', l.nombre || ' ' || r.nombre), query, 32) as similarity,
                Astext(r.ruta) as ruta_corta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                cross join plainto_tsquery('spanish', %(q)s) query
            WHERE
                query @@ to_tsvector('spanish', l.nombre || ' ' || r.nombre)
            ORDER BY
                similarity DESC
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_like_query(self, q, ciudad):
        params = {"q": q, "ci": ciudad}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                Astext(r.ruta) as ruta_corta,
                l.foto as foto,
                ST_Length(r.ruta::Geography) as long_ruta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                join catastro_ciudad_lineas as cl on (cl.linea_id = l.id )
                join catastro_ciudad as c on (c.id = cl.ciudad_id)
            WHERE
                (l.nombre || ' ' || r.nombre) ILIKE ('%%' || %(q)s || '%%')
                AND c.slug = %(ci)s
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_like_trgm_query(self, q, ciudad):
        params = {"q": q, "ci": ciudad}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                Astext(r.ruta) as ruta_corta,
                l.foto as foto,
                ST_Length(r.ruta::Geography) as long_ruta,
                similarity(l.nombre || ' ' || r.nombre, %(q)s) as similarity
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                join catastro_ciudad_lineas as cl on (cl.linea_id = l.id )
                join catastro_ciudad as c on (c.id = cl.ciudad_id)
            WHERE
                (l.nombre || ' ' || r.nombre) ILIKE ('%%' || %(q)s || '%%')
                AND c.slug = %(ci)s
            ORDER BY
                similarity DESC,
                (l.nombre || ' ' || r.nombre) ASC
            ;
        """
        query_set = self.raw(query, params)
        return query_set
<commit_msg>evitar que los trasbordos tildados maten al server :)<commit_after># -*- coding: UTF-8 -*-
from django.db import DatabaseError, connection
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
import math

class RecorridoManager(models.GeoManager):
    def get_recorridos_combinados(self, puntoA, puntoB, distanciaA, distanciaB, gap):
        distanciaA = int(distanciaA)
        distanciaB = int(distanciaB)
        gap = int(gap)
        if not isinstance(puntoA, Point):
            raise DatabaseError("get_recorridos: PuntoA Expected GEOS Point instance as parameter, %s given" % type(puntoA))
        if not isinstance(puntoB, Point):
            raise DatabaseError("get_recorridos: PuntoB Expected GEOS Point instance as parameter, %s given" % type(puntoB))
        if not isinstance(distanciaA, (int, long)):
            raise DatabaseError("get_recorridos: distanciaA Expected integer as parameter, %s given" % type(distanciaA))
        if not isinstance(distanciaB, (int, long)):
            raise DatabaseError("get_recorridos: distanciaB Expected integer as parameter, %s given" % type(distanciaB))
        if not isinstance(gap, (int, long)):
            raise DatabaseError("get_recorridos: gap Expected integer as parameter, %s given" % type(gap))
        puntoA.set_srid(4326)
        puntoB.set_srid(4326)
        connection.cursor().execute('SET STATEMENT_TIMEOUT=45000')

        params = {'puntoA': puntoA.ewkt, 'puntoB': puntoB.ewkt, 'rad1': distanciaA, 'rad2': distanciaB, 'gap': gap}
        query = """
            SELECT *
            FROM (
                SELECT
                    re1.id as id,
                    li1.nombre || ' ' || re1.nombre as nombre,
                    li2.nombre || ' ' || re2.nombre as nombre2,
                    re2.id as id2,
                    coalesce(re1.color_polilinea, li1.color_polilinea, '#000') as color_polilinea,
                    coalesce(re2.color_polilinea, li2.color_polilinea, '#000') as color_polilinea2,
                    coalesce(li1.foto, 'default') as foto,
                    coalesce(li2.foto, 'default') as foto2,
                    re1.inicio as inicio,
                    re2.inicio as inicio2,
                    re1.fin as fin,
                    re2.fin as fin2,
                    ST_AsText(
                        ST_Line_Substring(
                            re1.ruta,
                            ST_Line_Locate_Point(re1.ruta, %(puntoA)s),
                            ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta))
                            )::Geography
                        ) as ruta_corta,
                    ST_AsText(
                        ST_Line_Substring(
                            re2.ruta,
                            ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta)),
                            ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                            )::Geography
                        ) as ruta_corta2,
                    ST_Length(
                        ST_Line_Substring(
                            re1.ruta,
                            ST_Line_Locate_Point(re1.ruta, %(puntoA)s),
                            ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta))
                            )::Geography
                        ) as long_ruta,
                    ST_Length(
                        ST_Line_Substring(
                            re2.ruta,
                            ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta)),
                            ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                            )::Geography
                        ) as long_ruta2,
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s), re1.ruta) as long_pata,
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s), re2.ruta) as long_pata2,
                    ST_Distance_Sphere(re1.ruta, re2.ruta) as long_pata_transbordo

                FROM
                    core_recorrido as re1
                    join core_recorrido as re2 on (re1.id <> re2.id)
                    join core_linea li1 on li1.id = re1.linea_id
                    join core_linea li2 on li2.id = re2.linea_id
                WHERE
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s), re1.ruta) < %(rad1)s
                    and
                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s), re2.ruta) < %(rad2)s
                    and
                        ST_Distance_Sphere(re1.ruta, re2.ruta) < %(gap)s
                    and
                        ST_Line_Locate_Point(re1.ruta, %(puntoA)s)
                        <
                        ST_Line_Locate_Point(re1.ruta, ST_ClosestPoint(re1.ruta, re2.ruta) )
                    and
                        ST_Line_Locate_Point(re2.ruta, ST_ClosestPoint(re1.ruta, re2.ruta) )
                        <
                        ST_Line_Locate_Point(re2.ruta, %(puntoB)s)
                ) as subquery
            ORDER BY (cast(long_pata as integer)*10 + cast(long_ruta as integer) + cast(long_ruta2 as integer)) ASC
        ;"""
        query_set = self.raw(query, params)
        try:
            return list(query_set)
        except DatabaseError:
            return []

    def get_recorridos(self, puntoA, puntoB, distanciaA, distanciaB):
        distanciaA = int(distanciaA)
        distanciaB = int(distanciaB)
        if not isinstance(puntoA, Point):
            raise DatabaseError("get_recorridos: PuntoA Expected GEOS Point instance as parameter, %s given" % type(puntoA))
        if not isinstance(puntoB, Point):
            raise DatabaseError("get_recorridos: PuntoB Expected GEOS Point instance as parameter, %s given" % type(puntoB))
        if not isinstance(distanciaA, (int, long)):
            raise DatabaseError("get_recorridos: distanciaA Expected integer as parameter, %s given" % type(distanciaA))
        if not isinstance(distanciaB, (int, long)):
            raise DatabaseError("get_recorridos: distanciaB Expected integer as parameter, %s given" % type(distanciaB))
        puntoA.set_srid(4326)
        puntoB.set_srid(4326)
        distanciaA = 0.0000111 * float(distanciaA)
        distanciaB = 0.0000111 * float(distanciaB)

        params = {'puntoA': puntoA.ewkt, 'puntoB': puntoB.ewkt, 'rad1': distanciaA, 'rad2': distanciaB}
        query = """
                SELECT
                    re.id,
                    li.nombre || ' ' || re.nombre as nombre,
                    ruta_corta,
                    round(long_ruta::numeric, 2) as long_ruta,
                    round(long_pata::numeric, 2) as long_pata,
                    coalesce(re.color_polilinea, li.color_polilinea, '#000') as color_polilinea,
                    coalesce(li.foto, 'default') as foto
                FROM
                    core_linea as li join
                    (
                        SELECT
                            id,
                            nombre,
                            ST_AsText(min_path(ruta_corta)) as ruta_corta,
                            min(long_ruta) as long_ruta,
                            min(long_pata) as long_pata,
                            linea_id,
                            color_polilinea
                        FROM
                        (
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) +
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ST_Line_Substring(ruta, 0, 0.5),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5),	%(puntoA)s),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5),	%(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ST_Line_Substring(ruta, 0, 0.5), %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ST_Line_Substring(ruta, 0, 0.5), %(rad2)s) and
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5), %(puntoA)s) <
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0, 0.5), %(puntoB)s)
                                ) as primera_inner
                            )
                            UNION
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) + ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ST_Line_Substring(ruta, 0.5, 1),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1),	%(puntoA)s),
                                            ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1),	%(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ST_Line_Substring(ruta, 0.5, 1), %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ST_Line_Substring(ruta, 0.5, 1), %(rad2)s) and
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1), %(puntoA)s) <
                                        ST_Line_Locate_Point(ST_Line_Substring(ruta, 0.5, 1), %(puntoB)s)
                                ) as segunda_inner
                            )
                            UNION
                            (
                                SELECT
                                    *,
                                    ST_Length(ruta_corta::Geography) as long_ruta,
                                    ST_Distance_Sphere(ST_GeomFromText(%(puntoA)s),ruta_corta) + ST_Distance_Sphere(ST_GeomFromText(%(puntoB)s),ruta_corta) as long_pata
                                FROM
                                (
                                    SELECT
                                        *,
                                        ST_Line_Substring(
                                            ruta,
                                            ST_Line_Locate_Point(ruta, %(puntoA)s),
                                            ST_Line_Locate_Point(ruta, %(puntoB)s)
                                        ) as ruta_corta
                                    FROM
                                        core_recorrido
                                    WHERE
                                        ST_DWithin(ST_GeomFromText(%(puntoA)s), ruta, %(rad1)s) and
                                        ST_DWithin(ST_GeomFromText(%(puntoB)s), ruta, %(rad2)s) and
                                        ST_Line_Locate_Point(ruta, %(puntoA)s) <
                                        ST_Line_Locate_Point(ruta, %(puntoB)s)
                                ) as completa_inner
                            )
                        ) as interior
                        GROUP BY
                            id,
                            linea_id,
                            nombre,
                            color_polilinea
                    ) as re
                    on li.id = re.linea_id
                    ORDER BY
                        long_pata*10 + long_ruta asc
            ;"""

        query_set = self.raw(query, params)
        return list(query_set)

    def fuzzy_trgm_query(self, q):
        params = {"q": q}
        query = """
            SELECT
                set_limit(0.01);
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                similarity(l.nombre || ' ' || r.nombre, %(q)s) as similarity,
                Astext(r.ruta) as ruta_corta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
            WHERE
                (l.nombre || ' ' || r.nombre) %% %(q)s
            ORDER BY
                similarity DESC
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_fts_query(self, q):
        params = {"q": q}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                ts_rank_cd(to_tsvector('spanish', l.nombre || ' ' || r.nombre), query, 32) as similarity,
                Astext(r.ruta) as ruta_corta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                cross join plainto_tsquery('spanish', %(q)s) query
            WHERE
                query @@ to_tsvector('spanish', l.nombre || ' ' || r.nombre)
            ORDER BY
                similarity DESC
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_like_query(self, q, ciudad):
        params = {"q": q, "ci": ciudad}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                Astext(r.ruta) as ruta_corta,
                l.foto as foto,
                ST_Length(r.ruta::Geography) as long_ruta
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                join catastro_ciudad_lineas as cl on (cl.linea_id = l.id )
                join catastro_ciudad as c on (c.id = cl.ciudad_id)
            WHERE
                (l.nombre || ' ' || r.nombre) ILIKE ('%%' || %(q)s || '%%')
                AND c.slug = %(ci)s
            LIMIT
                10
            ;
        """
        query_set = self.raw(query, params)
        return query_set

    def fuzzy_like_trgm_query(self, q, ciudad):
        params = {"q": q, "ci": ciudad}
        query = """
            SELECT
                r.id,
                l.nombre || ' ' || r.nombre as nombre,
                Astext(r.ruta) as ruta_corta,
                l.foto as foto,
                ST_Length(r.ruta::Geography) as long_ruta,
                similarity(l.nombre || ' ' || r.nombre, %(q)s) as similarity
            FROM
                core_recorrido as r
                join core_linea as l on (r.linea_id = l.id)
                join catastro_ciudad_lineas as cl on (cl.linea_id = l.id )
                join catastro_ciudad as c on (c.id = cl.ciudad_id)
            WHERE
                (l.nombre || ' ' || r.nombre) ILIKE ('%%' || %(q)s || '%%')
                AND c.slug = %(ci)s
            ORDER BY
                similarity DESC,
                (l.nombre || ' ' || r.nombre) ASC
            ;
        """
        query_set = self.raw(query, params)
        return query_set
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2011, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# only, as published by the Free Software Foundation.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License version 3 for more details
# (a copy is included in the LICENSE file that accompanied this code).
#
# You should have received a copy of the GNU Lesser General Public License
# version 3 along with OpenQuake.  If not, see
# <http://www.gnu.org/licenses/lgpl-3.0.txt> for a copy of the LGPLv3 License.

"""
This module tests the hazard side of the deterministic
event based calculation.
"""

import math
import numpy
import unittest
import json

from utils import helpers

from openquake import java
from openquake import kvs
from openquake import job
from openquake import flags
from openquake import shapes

from openquake.hazard import deterministic as det

DETERMINISTIC_SMOKE_TEST = helpers.smoketest_file("deterministic/config.gem")
NUMBER_OF_CALC_KEY = "NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS"

def compute_ground_motion_field(self, random_generator):
    """Stubbed version of the method that computes the ground motion
    field calling java stuff."""

    hashmap = java.jclass("HashMap")()

    for site in self.sites_for_region():
        location = java.jclass("Location")(site.latitude, site.longitude)
        site = java.jclass("Site")(location)
        hashmap.put(site, 0.5)

    return hashmap

class DeterministicEventBasedMixinTestCase(unittest.TestCase):

    def setUp(self):
        flags.FLAGS.include_defaults = False

        self.engine = job.Job.from_file(DETERMINISTIC_SMOKE_TEST)
        self.engine.job_id = 1234

        self.engine.params[NUMBER_OF_CALC_KEY] = "1"

        # saving the default java implementation
        self.default = \
            det.DeterministicEventBasedMixin.compute_ground_motion_field

        kvs.flush()
        self.kvs_client = kvs.get_client(binary=False)

        self.grid = self.engine.region.grid

        self.engine.to_kvs()

    def tearDown(self):
        # restoring the default java implementation
        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            self.default

        flags.FLAGS.include_defaults = True

    def test_triggered_with_deterministic_calculation_mode(self):
        """The deterministic calculator is triggered.

        When CALCULATION_MODE is set to "Deterministic" the deterministic event
        based calculator is triggered.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        # True, True means that both mixins (hazard and risk) are triggered
        self.assertEqual([True, True], self.engine.launch())

    def test_the_hazard_subsystem_stores_gmfs_for_all_the_sites(self):
        """The hazard subsystem stores the computed gmfs in kvs.

        For each site in the region, a ground motion value is store
        in the underlying kvs system.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        self.engine.launch()
        decoder = json.JSONDecoder()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            # just one calculation is triggered in this test case
            self.assertEqual(1, self.kvs_client.llen(key))
            gmv = decoder.decode(self.kvs_client.lpop(key))
            self.assertEqual(0, self.kvs_client.llen(key))

            self.assertTrue(
                numpy.allclose(site.latitude, gmv["site_lat"]))

            self.assertTrue(
                numpy.allclose(site.longitude, gmv["site_lon"]))

    def test_multiple_computations_are_triggered(self):
        """The hazard subsystem is able to trigger multiple computations.

        Depending on the value specified by the user in the
        NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS key, the system
        calls the computation of the values for the entire region
        multiple times.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        self.engine.params["INTENSITY_MEASURE_TYPE"] = "MMI"
        self.engine.params[NUMBER_OF_CALC_KEY] = "3"

        self.engine.launch()
        decoder = json.JSONDecoder()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            self.assertEqual(3, self.kvs_client.llen(key))
            gmv = decoder.decode(self.kvs_client.lpop(key))
            self.assertEqual(0.5, gmv["mag"])

            # since the org.opensha.commons.geo.Location object
            # stores lat/lon in radians, values are not
            # exactly the same
            self.assertTrue(
                numpy.allclose(site.latitude, gmv["site_lat"]))

            self.assertTrue(
                numpy.allclose(site.longitude, gmv["site_lon"]))

    def test_transforms_a_java_gmf_to_dict(self):
        location1 = java.jclass("Location")(1.0, 2.0)
        location2 = java.jclass("Location")(1.1, 2.1)
        location3 = java.jclass("Location")(1.2, 2.2)

        site1 = java.jclass("Site")(location1)
        site2 = java.jclass("Site")(location2)
        site3 = java.jclass("Site")(location3)

        hashmap = java.jclass("HashMap")()

        hashmap.put(site1, 0.1)
        hashmap.put(site2, 0.2)
        hashmap.put(site3, 0.3)

        gmf_as_dict = det.gmf_to_dict(hashmap, "MMI")

        for gmv in gmf_as_dict:
            self.assertTrue(gmv["mag"] in (0.1, 0.2, 0.3))
            self.assertTrue(gmv["site_lon"] in (2.0, 2.1, 2.2))
            self.assertTrue(gmv["site_lat"] in (1.0, 1.1, 1.2))

    def test_the_number_of_calculation_must_be_greater_than_zero(self):
        self.engine.params[NUMBER_OF_CALC_KEY] = "0"
        self.assertRaises(ValueError, self.engine.launch)

        self.engine.params[NUMBER_OF_CALC_KEY] = "-1"
        self.assertRaises(ValueError, self.engine.launch)

    def test_simple_computation_using_the_java_calculator(self):
        self.engine.launch()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            self.assertTrue(kvs.get_keys(key))

    def test_when_measure_type_is_not_mmi_exp_is_stored(self):
        location = java.jclass("Location")(1.0, 2.0)
        site = java.jclass("Site")(location)

        hashmap = java.jclass("HashMap")()
        hashmap.put(site, 0.1)

        for gmv in det.gmf_to_dict(hashmap, "PGA"):
            self.assertEqual(math.exp(0.1), gmv["mag"])

    def test_when_measure_type_is_mmi_we_store_as_is(self):
        location = java.jclass("Location")(1.0, 2.0)
        site = java.jclass("Site")(location)

        hashmap = java.jclass("HashMap")()
        hashmap.put(site, 0.1)

        for gmv in det.gmf_to_dict(hashmap, "MMI"):
            self.assertEqual(0.1, gmv["mag"])

    def test_loads_the_rupture_model(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        self.assertEqual("org.opensha.sha.earthquake.EqkRupture",
                         calculator.rupture_model.__class__.__name__)

    def test_loads_the_gmpe(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        self.assertTrue("org.opensha.sha.imr.attenRelImpl.BA_2008_AttenRel",
                        calculator.gmpe.__class__.__name__)

    def test_the_same_calculator_is_used_between_multiple_invocations(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        gmf_calculator1 = calculator.gmf_calculator([shapes.Site(1.0, 1.0)])
        gmf_calculator2 = calculator.gmf_calculator([shapes.Site(1.0, 1.0)])

        self.assertTrue(gmf_calculator1 == gmf_calculator2)
<commit_msg>removed redundant job id<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2011, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# only, as published by the Free Software Foundation.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License version 3 for more details
# (a copy is included in the LICENSE file that accompanied this code).
#
# You should have received a copy of the GNU Lesser General Public License
# version 3 along with OpenQuake.  If not, see
# <http://www.gnu.org/licenses/lgpl-3.0.txt> for a copy of the LGPLv3 License.

"""
This module tests the hazard side of the deterministic
event based calculation.
"""

import math
import numpy
import unittest
import json

from utils import helpers

from openquake import java
from openquake import kvs
from openquake import job
from openquake import flags
from openquake import shapes

from openquake.hazard import deterministic as det

DETERMINISTIC_SMOKE_TEST = helpers.smoketest_file("deterministic/config.gem")
NUMBER_OF_CALC_KEY = "NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS"

def compute_ground_motion_field(self, random_generator):
    """Stubbed version of the method that computes the ground motion
    field calling java stuff."""

    hashmap = java.jclass("HashMap")()

    for site in self.sites_for_region():
        location = java.jclass("Location")(site.latitude, site.longitude)
        site = java.jclass("Site")(location)
        hashmap.put(site, 0.5)

    return hashmap

class DeterministicEventBasedMixinTestCase(unittest.TestCase):

    def setUp(self):
        flags.FLAGS.include_defaults = False

        self.engine = job.Job.from_file(DETERMINISTIC_SMOKE_TEST)

        self.engine.params[NUMBER_OF_CALC_KEY] = "1"

        # saving the default java implementation
        self.default = \
            det.DeterministicEventBasedMixin.compute_ground_motion_field

        kvs.flush()
        self.kvs_client = kvs.get_client(binary=False)

        self.grid = self.engine.region.grid

        self.engine.to_kvs()

    def tearDown(self):
        # restoring the default java implementation
        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            self.default

        flags.FLAGS.include_defaults = True

    def test_triggered_with_deterministic_calculation_mode(self):
        """The deterministic calculator is triggered.

        When CALCULATION_MODE is set to "Deterministic" the deterministic event
        based calculator is triggered.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        # True, True means that both mixins (hazard and risk) are triggered
        self.assertEqual([True, True], self.engine.launch())

    def test_the_hazard_subsystem_stores_gmfs_for_all_the_sites(self):
        """The hazard subsystem stores the computed gmfs in kvs.

        For each site in the region, a ground motion value is store
        in the underlying kvs system.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        self.engine.launch()
        decoder = json.JSONDecoder()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            # just one calculation is triggered in this test case
            self.assertEqual(1, self.kvs_client.llen(key))
            gmv = decoder.decode(self.kvs_client.lpop(key))
            self.assertEqual(0, self.kvs_client.llen(key))

            self.assertTrue(
                numpy.allclose(site.latitude, gmv["site_lat"]))

            self.assertTrue(
                numpy.allclose(site.longitude, gmv["site_lon"]))

    def test_multiple_computations_are_triggered(self):
        """The hazard subsystem is able to trigger multiple computations.

        Depending on the value specified by the user in the
        NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS key, the system
        calls the computation of the values for the entire region
        multiple times.
        """

        det.DeterministicEventBasedMixin.compute_ground_motion_field = \
            compute_ground_motion_field

        self.engine.params["INTENSITY_MEASURE_TYPE"] = "MMI"
        self.engine.params[NUMBER_OF_CALC_KEY] = "3"

        self.engine.launch()
        decoder = json.JSONDecoder()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            self.assertEqual(3, self.kvs_client.llen(key))
            gmv = decoder.decode(self.kvs_client.lpop(key))
            self.assertEqual(0.5, gmv["mag"])

            # since the org.opensha.commons.geo.Location object
            # stores lat/lon in radians, values are not
            # exactly the same
            self.assertTrue(
                numpy.allclose(site.latitude, gmv["site_lat"]))

            self.assertTrue(
                numpy.allclose(site.longitude, gmv["site_lon"]))

    def test_transforms_a_java_gmf_to_dict(self):
        location1 = java.jclass("Location")(1.0, 2.0)
        location2 = java.jclass("Location")(1.1, 2.1)
        location3 = java.jclass("Location")(1.2, 2.2)

        site1 = java.jclass("Site")(location1)
        site2 = java.jclass("Site")(location2)
        site3 = java.jclass("Site")(location3)

        hashmap = java.jclass("HashMap")()

        hashmap.put(site1, 0.1)
        hashmap.put(site2, 0.2)
        hashmap.put(site3, 0.3)

        gmf_as_dict = det.gmf_to_dict(hashmap, "MMI")

        for gmv in gmf_as_dict:
            self.assertTrue(gmv["mag"] in (0.1, 0.2, 0.3))
            self.assertTrue(gmv["site_lon"] in (2.0, 2.1, 2.2))
            self.assertTrue(gmv["site_lat"] in (1.0, 1.1, 1.2))

    def test_the_number_of_calculation_must_be_greater_than_zero(self):
        self.engine.params[NUMBER_OF_CALC_KEY] = "0"
        self.assertRaises(ValueError, self.engine.launch)

        self.engine.params[NUMBER_OF_CALC_KEY] = "-1"
        self.assertRaises(ValueError, self.engine.launch)

    def test_simple_computation_using_the_java_calculator(self):
        self.engine.launch()

        for site in self.engine.sites_for_region():
            point = self.grid.point_at(site)
            key = kvs.tokens.ground_motion_values_key(
                self.engine.id, point)

            self.assertTrue(kvs.get_keys(key))

    def test_when_measure_type_is_not_mmi_exp_is_stored(self):
        location = java.jclass("Location")(1.0, 2.0)
        site = java.jclass("Site")(location)

        hashmap = java.jclass("HashMap")()
        hashmap.put(site, 0.1)

        for gmv in det.gmf_to_dict(hashmap, "PGA"):
            self.assertEqual(math.exp(0.1), gmv["mag"])

    def test_when_measure_type_is_mmi_we_store_as_is(self):
        location = java.jclass("Location")(1.0, 2.0)
        site = java.jclass("Site")(location)

        hashmap = java.jclass("HashMap")()
        hashmap.put(site, 0.1)

        for gmv in det.gmf_to_dict(hashmap, "MMI"):
            self.assertEqual(0.1, gmv["mag"])

    def test_loads_the_rupture_model(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        self.assertEqual("org.opensha.sha.earthquake.EqkRupture",
                         calculator.rupture_model.__class__.__name__)

    def test_loads_the_gmpe(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        self.assertTrue("org.opensha.sha.imr.attenRelImpl.BA_2008_AttenRel",
                        calculator.gmpe.__class__.__name__)

    def test_the_same_calculator_is_used_between_multiple_invocations(self):
        calculator = det.DeterministicEventBasedMixin(None, None)
        calculator.params = self.engine.params

        gmf_calculator1 = calculator.gmf_calculator([shapes.Site(1.0, 1.0)])
        gmf_calculator2 = calculator.gmf_calculator([shapes.Site(1.0, 1.0)])

        self.assertTrue(gmf_calculator1 == gmf_calculator2)
<|endoftext|>


<commit_before>"""
Tests for F() query expression syntax.
"""

from django.db import models

class Employee(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s %s' % (self.firstname, self.lastname)

class Company(models.Model):
    name = models.CharField(max_length=100)
    num_employees = models.PositiveIntegerField()
    num_chairs = models.PositiveIntegerField()
    ceo = models.ForeignKey(
        Employee,
        related_name='company_ceo_set')
    point_of_contact = models.ForeignKey(
        Employee,
        related_name='company_point_of_contact_set',
        null=True)

    def __unicode__(self):
        return self.name

__test__ = {'API_TESTS': """
>>> from django.db.models import F

>>> Company(name='Example Inc.', num_employees=2300, num_chairs=5,
...     ceo=Employee.objects.create(firstname='Joe', lastname='Smith')).save()
>>> Company(name='Foobar Ltd.', num_employees=3, num_chairs=3,
...     ceo=Employee.objects.create(firstname='Frank', lastname='Meyer')).save()
>>> Company(name='Test GmbH', num_employees=32, num_chairs=1,
...     ceo=Employee.objects.create(firstname='Max', lastname='Mustermann')).save()

>>> company_query = Company.objects.values('name','num_employees','num_chairs').order_by('name','num_employees','num_chairs')

# We can filter for companies where the number of employees is greater than the
# number of chairs.
>>> company_query.filter(num_employees__gt=F('num_chairs'))
[{'num_chairs': 5, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 1, 'name': u'Test GmbH', 'num_employees': 32}]

# We can set one field to have the value of another field
# Make sure we have enough chairs
>>> _ = company_query.update(num_chairs=F('num_employees'))
>>> company_query
[{'num_chairs': 2300, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 3, 'name': u'Foobar Ltd.', 'num_employees': 3}, {'num_chairs': 32, 'name': u'Test GmbH', 'num_employees': 32}]

# We can perform arithmetic operations in expressions
# Make sure we have 2 spare chairs
>>> _ =company_query.update(num_chairs=F('num_employees')+2)
>>> company_query
[{'num_chairs': 2302, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 5, 'name': u'Foobar Ltd.', 'num_employees': 3}, {'num_chairs': 34, 'name': u'Test GmbH', 'num_employees': 32}]

# The relation of a foreign key can become copied over to an other foreign key.
>>> Company.objects.update(point_of_contact=F('ceo'))
3

>>> [c.point_of_contact for c in Company.objects.all()]
[<Employee: Joe Smith>, <Employee: Frank Meyer>, <Employee: Max Mustermann>]

>>> c = Company.objects.all()[0]
>>> c.point_of_contact = Employee.objects.create(firstname="Guido", lastname="van Rossum")
>>> c.save()

# F Expressions can also span joins
>>> Company.objects.filter(ceo__firstname=F('point_of_contact__firstname')).distinct()
[<Company: Foobar Ltd.>, <Company: Test GmbH>]

>>> _ = Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).update(name='foo')
>>> Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).get().name
u'foo'

>>> _ = Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).update(name=F('point_of_contact__lastname'))
Traceback (most recent call last):
...
FieldError: Joined field references are not permitted in this query

# F expressions can be used to update attributes on single objects
>>> test_gmbh = Company.objects.get(name='Test GmbH')
>>> test_gmbh.num_employees
32
>>> test_gmbh.num_employees = F('num_employees') + 4
>>> test_gmbh.save()
>>> test_gmbh = Company.objects.get(pk=test_gmbh.pk)
>>> test_gmbh.num_employees
36

# F expressions cannot be used to update attributes which are foreign keys, or
# attributes which involve joins.
>>> test_gmbh.point_of_contact = None
>>> test_gmbh.save()
>>> test_gmbh.point_of_contact is None
True
>>> test_gmbh.point_of_contact = F('ceo')
Traceback (most recent call last):
...
ValueError: Cannot assign "<django.db.models.expressions.F object at ...>": "Company.point_of_contact" must be a "Employee" instance.

>>> test_gmbh.point_of_contact = test_gmbh.ceo
>>> test_gmbh.save()
>>> test_gmbh.name = F('ceo__last_name')
>>> test_gmbh.save()
Traceback (most recent call last):
...
FieldError: Joined field references are not permitted in this query

# F expressions cannot be used to update attributes on objects which do not yet
# exist in the database
>>> acme = Company(name='The Acme Widget Co.', num_employees=12, num_chairs=5,
...     ceo=test_gmbh.ceo)
>>> acme.num_employees = F('num_employees') + 16
>>> acme.save()
Traceback (most recent call last):
...
TypeError: int() argument must be a string or a number, not 'ExpressionNode'

"""}
<commit_msg>Fix the expressions modeltest to work on Pythons earlier than 2.5.<commit_after>"""
Tests for F() query expression syntax.
"""

from django.db import models

class Employee(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s %s' % (self.firstname, self.lastname)

class Company(models.Model):
    name = models.CharField(max_length=100)
    num_employees = models.PositiveIntegerField()
    num_chairs = models.PositiveIntegerField()
    ceo = models.ForeignKey(
        Employee,
        related_name='company_ceo_set')
    point_of_contact = models.ForeignKey(
        Employee,
        related_name='company_point_of_contact_set',
        null=True)

    def __unicode__(self):
        return self.name

__test__ = {'API_TESTS': """
>>> from django.db.models import F

>>> Company(name='Example Inc.', num_employees=2300, num_chairs=5,
...     ceo=Employee.objects.create(firstname='Joe', lastname='Smith')).save()
>>> Company(name='Foobar Ltd.', num_employees=3, num_chairs=3,
...     ceo=Employee.objects.create(firstname='Frank', lastname='Meyer')).save()
>>> Company(name='Test GmbH', num_employees=32, num_chairs=1,
...     ceo=Employee.objects.create(firstname='Max', lastname='Mustermann')).save()

>>> company_query = Company.objects.values('name','num_employees','num_chairs').order_by('name','num_employees','num_chairs')

# We can filter for companies where the number of employees is greater than the
# number of chairs.
>>> company_query.filter(num_employees__gt=F('num_chairs'))
[{'num_chairs': 5, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 1, 'name': u'Test GmbH', 'num_employees': 32}]

# We can set one field to have the value of another field
# Make sure we have enough chairs
>>> _ = company_query.update(num_chairs=F('num_employees'))
>>> company_query
[{'num_chairs': 2300, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 3, 'name': u'Foobar Ltd.', 'num_employees': 3}, {'num_chairs': 32, 'name': u'Test GmbH', 'num_employees': 32}]

# We can perform arithmetic operations in expressions
# Make sure we have 2 spare chairs
>>> _ =company_query.update(num_chairs=F('num_employees')+2)
>>> company_query
[{'num_chairs': 2302, 'name': u'Example Inc.', 'num_employees': 2300}, {'num_chairs': 5, 'name': u'Foobar Ltd.', 'num_employees': 3}, {'num_chairs': 34, 'name': u'Test GmbH', 'num_employees': 32}]

# The relation of a foreign key can become copied over to an other foreign key.
>>> Company.objects.update(point_of_contact=F('ceo'))
3

>>> [c.point_of_contact for c in Company.objects.all()]
[<Employee: Joe Smith>, <Employee: Frank Meyer>, <Employee: Max Mustermann>]

>>> c = Company.objects.all()[0]
>>> c.point_of_contact = Employee.objects.create(firstname="Guido", lastname="van Rossum")
>>> c.save()

# F Expressions can also span joins
>>> Company.objects.filter(ceo__firstname=F('point_of_contact__firstname')).distinct()
[<Company: Foobar Ltd.>, <Company: Test GmbH>]

>>> _ = Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).update(name='foo')
>>> Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).get().name
u'foo'

>>> _ = Company.objects.exclude(ceo__firstname=F('point_of_contact__firstname')).update(name=F('point_of_contact__lastname'))
Traceback (most recent call last):
...
FieldError: Joined field references are not permitted in this query

# F expressions can be used to update attributes on single objects
>>> test_gmbh = Company.objects.get(name='Test GmbH')
>>> test_gmbh.num_employees
32
>>> test_gmbh.num_employees = F('num_employees') + 4
>>> test_gmbh.save()
>>> test_gmbh = Company.objects.get(pk=test_gmbh.pk)
>>> test_gmbh.num_employees
36

# F expressions cannot be used to update attributes which are foreign keys, or
# attributes which involve joins.
>>> test_gmbh.point_of_contact = None
>>> test_gmbh.save()
>>> test_gmbh.point_of_contact is None
True
>>> test_gmbh.point_of_contact = F('ceo')
Traceback (most recent call last):
...
ValueError: Cannot assign "<django.db.models.expressions.F object at ...>": "Company.point_of_contact" must be a "Employee" instance.

>>> test_gmbh.point_of_contact = test_gmbh.ceo
>>> test_gmbh.save()
>>> test_gmbh.name = F('ceo__last_name')
>>> test_gmbh.save()
Traceback (most recent call last):
...
FieldError: Joined field references are not permitted in this query

# F expressions cannot be used to update attributes on objects which do not yet
# exist in the database
>>> acme = Company(name='The Acme Widget Co.', num_employees=12, num_chairs=5,
...     ceo=test_gmbh.ceo)
>>> acme.num_employees = F('num_employees') + 16
>>> acme.save()
Traceback (most recent call last):
...
TypeError: int() argument must be a string or a number...

"""}
<|endoftext|>


<commit_before># coding=utf-8

from __future__ import unicode_literals

import re
import unittest

from ukpostcodeparser.parser import parse_uk_postcode

from faker import Factory
from faker.providers.address.de_DE import Provider as DeProvider
from faker.providers.address.el_GR import Provider as GrProvider
from faker.providers.address.hu_HU import Provider as HuProvider
from faker.providers.address.ja_JP import Provider as JaProvider
from faker.providers.address.ne_NP import Provider as NeProvider
from six import string_types

class TestDeDE(unittest.TestCase):
    """ Tests in addresses in the de_DE locale """

    def setUp(self):
        self.factory = Factory.create('de_DE')

    def test_city(self):
        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in DeProvider.cities

    def test_state(self):
        state = self.factory.state()
        assert isinstance(state, string_types)
        assert state in DeProvider.states

    def test_street_suffix_short(self):
        street_suffix_short = self.factory.street_suffix_short()
        assert isinstance(street_suffix_short, string_types)
        assert street_suffix_short in DeProvider.street_suffixes_short

    def test_street_suffix_long(self):
        street_suffix_long = self.factory.street_suffix_long()
        assert isinstance(street_suffix_long, string_types)
        assert street_suffix_long in DeProvider.street_suffixes_long

    def test_country(self):
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in DeProvider.countries

class TestElGR(unittest.TestCase):
    """ Tests addresses in the el_GR locale """

    def setUp(self):
        self.factory = Factory.create('el_GR')

    def test_line_address(self):
        address = self.factory.line_address()
        assert isinstance(address, string_types)

class TestEnGB(unittest.TestCase):
    """ Tests addresses in the en_GB locale """

    def setUp(self):
        self.factory = Factory.create('en_GB')

    def test_postcode(self):
        for _ in range(100):
            assert isinstance(parse_uk_postcode(self.factory.postcode()), tuple)

class TestHuHU(unittest.TestCase):
    """ Tests addresses in the hu_HU locale """

    def setUp(self):
        self.factory = Factory.create('hu_HU')

    def test_postcode_first_digit(self):
        # Hungarian postcodes begin with 'H-' followed by 4 digits.
        # The first digit may not begin with a zero.
        for _ in range(100):
            pcd = self.factory.postcode()
            assert pcd[2] > "0"

    def test_street_address(self):
        """ Tests the street address in the hu_HU locale """
        address = self.factory.address()
        assert isinstance(address, string_types)
        address_with_county = self.factory.street_address_with_county()
        assert isinstance(address_with_county, string_types)

class TestJaJP(unittest.TestCase):
    """ Tests addresses in the ja_JP locale """

    def setUp(self):
        self.factory = Factory.create('ja')

    def test_address(self):
        """ Test"""
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in JaProvider.countries

        prefecture = self.factory.prefecture()
        assert isinstance(prefecture, string_types)
        assert prefecture in JaProvider.prefectures

        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in JaProvider.cities

        town = self.factory.town()
        assert isinstance(town, string_types)
        assert town in JaProvider.towns

        chome = self.factory.chome()
        assert isinstance(chome, string_types)
        assert re.match("\d{1,2}丁目", chome)

        ban = self.factory.ban()
        assert isinstance(ban, string_types)
        assert re.match("\d{1,2}番", ban)

        gou = self.factory.gou()
        assert isinstance(gou, string_types)
        assert re.match("\d{1,2}号", gou)

        building_name = self.factory.building_name()
        assert isinstance(building_name, string_types)
        assert building_name in JaProvider.building_names

        zipcode = self.factory.zipcode()
        assert isinstance(zipcode, string_types)
        assert re.match("\d{3}-\d{4}", zipcode)

        address = self.factory.address()
        assert isinstance(address, string_types)

class TestNeNP(unittest.TestCase):
    """ Tests addresses in the ne_NP locale """

    def setUp(self):
        self.factory = Factory.create('ne_NP')

    def test_address(self):
        """ Tests the street address in ne_NP locale """
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in NeProvider.countries

        district = self.factory.district()
        assert isinstance(district, string_types)
        assert district in NeProvider.districts

        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in NeProvider.cities

class TestNoNO(unittest.TestCase):
    """ Tests the street address in no_NO locale """

    def setUp(self):
        self.factory = Factory.create('no_NO')

    def test_postcode(self):
        for _ in range(100):
            self.assertTrue(re.match(r'^[0-9]{4}$', self.factory.postcode()))

    def test_city_suffix(self):
        suffix = self.factory.city_suffix()
        assert isinstance(suffix, string_types)

    def test_street_suffix(self):
        suffix = self.factory.street_suffix()
        assert isinstance(suffix, string_types)

    def test_address(self):
        address = self.factory.address()
        assert isinstance(address, string_types)

class TestZhTW(unittest.TestCase):
    """ Tests addresses in the zh_tw locale """

    def setUp(self):
        self.factory = Factory.create('zh_TW')

    def test_address(self):
        country = self.factory.country()
        assert isinstance(country, string_types)

        street = self.factory.street_name()
        assert isinstance(street, string_types)

        city = self.factory.city()
        assert isinstance(city, string_types)

        address = self.factory.address()
        assert isinstance(address, string_types)

class TestZhCN(unittest.TestCase):
    """ Tests addresses in the zh_cn locale """

    def setUp(self):
        self.factory = Factory.create('zh_CN')

    def test_address(self):
        country = self.factory.country()
        assert isinstance(country, string_types)

        street = self.factory.street_name()
        assert isinstance(street, string_types)

        city = self.factory.street_address()
        assert isinstance(city, string_types)

        province = self.factory.province()
        assert isinstance(province, string_types)

        district = self.factory.district()
        assert isinstance(district, string_types)

        address = self.factory.address()
        assert isinstance(address, string_types)

        for _ in range(100):
            self.assertTrue(re.match(r'\d{5}', self.factory.postcode()))
<commit_msg>Implement city test<commit_after># coding=utf-8

from __future__ import unicode_literals

import re
import unittest

from ukpostcodeparser.parser import parse_uk_postcode

from faker import Factory
from faker.providers.address.de_DE import Provider as DeProvider
from faker.providers.address.el_GR import Provider as GrProvider
from faker.providers.address.hu_HU import Provider as HuProvider
from faker.providers.address.ja_JP import Provider as JaProvider
from faker.providers.address.ne_NP import Provider as NeProvider
from six import string_types

class TestDeDE(unittest.TestCase):
    """ Tests in addresses in the de_DE locale """

    def setUp(self):
        self.factory = Factory.create('de_DE')

    def test_city(self):
        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in DeProvider.cities

    def test_state(self):
        state = self.factory.state()
        assert isinstance(state, string_types)
        assert state in DeProvider.states

    def test_street_suffix_short(self):
        street_suffix_short = self.factory.street_suffix_short()
        assert isinstance(street_suffix_short, string_types)
        assert street_suffix_short in DeProvider.street_suffixes_short

    def test_street_suffix_long(self):
        street_suffix_long = self.factory.street_suffix_long()
        assert isinstance(street_suffix_long, string_types)
        assert street_suffix_long in DeProvider.street_suffixes_long

    def test_country(self):
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in DeProvider.countries

class TestElGR(unittest.TestCase):
    """ Tests addresses in the el_GR locale """

    def setUp(self):
        self.factory = Factory.create('el_GR')

    def test_line_address(self):
        address = self.factory.line_address()
        assert isinstance(address, string_types)

    def test_city(self):
        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in GrProvider.cities

class TestEnGB(unittest.TestCase):
    """ Tests addresses in the en_GB locale """

    def setUp(self):
        self.factory = Factory.create('en_GB')

    def test_postcode(self):
        for _ in range(100):
            assert isinstance(parse_uk_postcode(self.factory.postcode()), tuple)

class TestHuHU(unittest.TestCase):
    """ Tests addresses in the hu_HU locale """

    def setUp(self):
        self.factory = Factory.create('hu_HU')

    def test_postcode_first_digit(self):
        # Hungarian postcodes begin with 'H-' followed by 4 digits.
        # The first digit may not begin with a zero.
        for _ in range(100):
            pcd = self.factory.postcode()
            assert pcd[2] > "0"

    def test_street_address(self):
        """ Tests the street address in the hu_HU locale """
        address = self.factory.address()
        assert isinstance(address, string_types)
        address_with_county = self.factory.street_address_with_county()
        assert isinstance(address_with_county, string_types)

class TestJaJP(unittest.TestCase):
    """ Tests addresses in the ja_JP locale """

    def setUp(self):
        self.factory = Factory.create('ja')

    def test_address(self):
        """ Test"""
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in JaProvider.countries

        prefecture = self.factory.prefecture()
        assert isinstance(prefecture, string_types)
        assert prefecture in JaProvider.prefectures

        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in JaProvider.cities

        town = self.factory.town()
        assert isinstance(town, string_types)
        assert town in JaProvider.towns

        chome = self.factory.chome()
        assert isinstance(chome, string_types)
        assert re.match("\d{1,2}丁目", chome)

        ban = self.factory.ban()
        assert isinstance(ban, string_types)
        assert re.match("\d{1,2}番", ban)

        gou = self.factory.gou()
        assert isinstance(gou, string_types)
        assert re.match("\d{1,2}号", gou)

        building_name = self.factory.building_name()
        assert isinstance(building_name, string_types)
        assert building_name in JaProvider.building_names

        zipcode = self.factory.zipcode()
        assert isinstance(zipcode, string_types)
        assert re.match("\d{3}-\d{4}", zipcode)

        address = self.factory.address()
        assert isinstance(address, string_types)

class TestNeNP(unittest.TestCase):
    """ Tests addresses in the ne_NP locale """

    def setUp(self):
        self.factory = Factory.create('ne_NP')

    def test_address(self):
        """ Tests the street address in ne_NP locale """
        country = self.factory.country()
        assert isinstance(country, string_types)
        assert country in NeProvider.countries

        district = self.factory.district()
        assert isinstance(district, string_types)
        assert district in NeProvider.districts

        city = self.factory.city()
        assert isinstance(city, string_types)
        assert city in NeProvider.cities

class TestNoNO(unittest.TestCase):
    """ Tests the street address in no_NO locale """

    def setUp(self):
        self.factory = Factory.create('no_NO')

    def test_postcode(self):
        for _ in range(100):
            self.assertTrue(re.match(r'^[0-9]{4}$', self.factory.postcode()))

    def test_city_suffix(self):
        suffix = self.factory.city_suffix()
        assert isinstance(suffix, string_types)

    def test_street_suffix(self):
        suffix = self.factory.street_suffix()
        assert isinstance(suffix, string_types)

    def test_address(self):
        address = self.factory.address()
        assert isinstance(address, string_types)

class TestZhTW(unittest.TestCase):
    """ Tests addresses in the zh_tw locale """

    def setUp(self):
        self.factory = Factory.create('zh_TW')

    def test_address(self):
        country = self.factory.country()
        assert isinstance(country, string_types)

        street = self.factory.street_name()
        assert isinstance(street, string_types)

        city = self.factory.city()
        assert isinstance(city, string_types)

        address = self.factory.address()
        assert isinstance(address, string_types)

class TestZhCN(unittest.TestCase):
    """ Tests addresses in the zh_cn locale """

    def setUp(self):
        self.factory = Factory.create('zh_CN')

    def test_address(self):
        country = self.factory.country()
        assert isinstance(country, string_types)

        street = self.factory.street_name()
        assert isinstance(street, string_types)

        city = self.factory.street_address()
        assert isinstance(city, string_types)

        province = self.factory.province()
        assert isinstance(province, string_types)

        district = self.factory.district()
        assert isinstance(district, string_types)

        address = self.factory.address()
        assert isinstance(address, string_types)

        for _ in range(100):
            self.assertTrue(re.match(r'\d{5}', self.factory.postcode()))
<|endoftext|>


<commit_before>from django.contrib import admin

import machiavelli.models as machiavelli

class PlayerAdmin(admin.ModelAdmin):
	list_display = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')
	list_filter = ('game', 'done')
	ordering = ['game']

class PlayerInline(admin.TabularInline):
	model = machiavelli.Player
	extra = 0
	ordering = ['user__username']
	can_delete = False
	fields = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')
	readonly_fields = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')

class RevolutionAdmin(admin.ModelAdmin):
	list_display = ('game', 'government', 'opposition', 'active', 'overthrow')

class ScoreAdmin(admin.ModelAdmin):
	list_display = ('user', 'game', 'country', 'points', 'cities', 'position')
	list_filter = ('game', 'user', 'country')
	ordering = ['game']

class ScoreInline(admin.TabularInline):
	model = machiavelli.Score
	extra = 0
	ordering = ['user__username']
	can_delete = False
	fields = ('user', 'game', 'country', 'points', 'cities', 'position')
	readonly_fields = ('user', 'game', 'country', 'points', 'cities')

class UnitAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'must_retreat', 'power', 'loyalty', 'placed', 'paid')
	ordering = ['player']
	list_filter = ('player', 'must_retreat')

class SpecialUnitAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'cost', 'power', 'loyalty')

class GameAreaAdmin(admin.ModelAdmin):
	list_display = ('game', 'board_area', 'player', 'standoff', 'famine', 'storm')
	list_per_page = 73
	ordering = ['board_area']
	list_filter = ('player', )

class OrderAdmin(admin.ModelAdmin):
	list_display = ('player', '__unicode__', 'explain', 'confirmed')
	list_editable = ('confirmed', )
	list_filter = ('confirmed',)

class ConfigurationInline(admin.TabularInline):
	model = machiavelli.Configuration
	extra = 1

class GameAdmin(admin.ModelAdmin):
	list_display = ('pk', 'slug', 'slots', 'scenario', 'created_by', 'started', 'finished', 'player_list', 'version')
	inlines = [ ConfigurationInline, ScoreInline,]

	def player_list(self, obj):
		users = []
		for p in obj.player_set.filter(user__isnull=False):
			users.append(p.user.username)
		return ", ".join(users)

	player_list.short_description = 'Player list'

class LiveGameAdmin(admin.ModelAdmin):
	list_display = ('pk', 'slug', 'paused', 'extended_deadline', 'year', 'season', 'phase', 'next_phase_change', 'started', 'version')
	actions = ['redraw_map',
				'check_finished_phase',
				'pause',
				'resume',]
	inlines = [ ConfigurationInline, PlayerInline, ]

	def redraw_map(self, request, queryset):
		for obj in queryset:
			obj.make_map()
	redraw_map.short_description = "Redraw map"

	def check_finished_phase(self, request, queryset):
		for obj in queryset:
			obj.check_finished_phase()
	check_finished_phase.short_description = "Check finished phase"

	def pause(self, request, queryset):
		queryset.update(paused=True)
	pause.short_description = "Pause the games"

	def resume(self, request, queryset):
		queryset.update(paused=False)
	resume.short_description = "Resume paused games"

class RetreatOrderAdmin(admin.ModelAdmin):
	pass

class TurnLogAdmin(admin.ModelAdmin):
	ordering = ['-timestamp']
	list_display = ('game', 'timestamp')
	list_filter = ('game',)

class ExpenseAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'ducats', 'type', 'unit', 'area', 'confirmed')
	list_filter = ('player', 'type',)

class RebellionAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'garrisoned', 'repressed',)
	list_filter = ('player',)

class LoanAdmin(admin.ModelAdmin):
	list_display = ('player', 'debt', 'year', 'season', )

class AssassinAdmin(admin.ModelAdmin):
	pass

class AssassinationAdmin(admin.ModelAdmin):
	pass

class WhisperAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'user', 'game', 'order',)

class InvitationAdmin(admin.ModelAdmin):
	pass

class GameCommentAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'user', 'game', 'is_public')

admin.site.register(machiavelli.Game, GameAdmin)
admin.site.register(machiavelli.LiveGame, LiveGameAdmin)
admin.site.register(machiavelli.Unit, UnitAdmin)
admin.site.register(machiavelli.GameArea, GameAreaAdmin)
admin.site.register(machiavelli.Player, PlayerAdmin)
admin.site.register(machiavelli.Revolution, RevolutionAdmin)
admin.site.register(machiavelli.Score, ScoreAdmin)
admin.site.register(machiavelli.Order, OrderAdmin)
admin.site.register(machiavelli.RetreatOrder, RetreatOrderAdmin)
admin.site.register(machiavelli.TurnLog, TurnLogAdmin)
admin.site.register(machiavelli.Expense, ExpenseAdmin)
admin.site.register(machiavelli.Rebellion, RebellionAdmin)
admin.site.register(machiavelli.Loan, LoanAdmin)
admin.site.register(machiavelli.Assassin, AssassinAdmin)
admin.site.register(machiavelli.Assassination, AssassinationAdmin)
admin.site.register(machiavelli.Whisper, WhisperAdmin)
admin.site.register(machiavelli.Invitation, InvitationAdmin)
admin.site.register(machiavelli.GameComment, GameCommentAdmin)
<commit_msg>add Team class to admin<commit_after>from django.contrib import admin

import machiavelli.models as machiavelli

class PlayerAdmin(admin.ModelAdmin):
	list_display = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')
	list_filter = ('game', 'done')
	ordering = ['game']

class PlayerInline(admin.TabularInline):
	model = machiavelli.Player
	extra = 0
	ordering = ['user__username']
	can_delete = False
	fields = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')
	readonly_fields = ('user', 'game', 'contender', 'done', 'eliminated', 'conqueror', 'is_excommunicated', 'assassinated', 'defaulted', 'ducats')

class RevolutionAdmin(admin.ModelAdmin):
	list_display = ('game', 'government', 'opposition', 'active', 'overthrow')

class ScoreAdmin(admin.ModelAdmin):
	list_display = ('user', 'game', 'country', 'points', 'cities', 'position')
	list_filter = ('game', 'user', 'country')
	ordering = ['game']

class ScoreInline(admin.TabularInline):
	model = machiavelli.Score
	extra = 0
	ordering = ['user__username']
	can_delete = False
	fields = ('user', 'game', 'country', 'points', 'cities', 'position')
	readonly_fields = ('user', 'game', 'country', 'points', 'cities')

class UnitAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'must_retreat', 'power', 'loyalty', 'placed', 'paid')
	ordering = ['player']
	list_filter = ('player', 'must_retreat')

class SpecialUnitAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'cost', 'power', 'loyalty')

class GameAreaAdmin(admin.ModelAdmin):
	list_display = ('game', 'board_area', 'player', 'standoff', 'famine', 'storm')
	list_per_page = 73
	ordering = ['board_area']
	list_filter = ('player', )

class OrderAdmin(admin.ModelAdmin):
	list_display = ('player', '__unicode__', 'explain', 'confirmed')
	list_editable = ('confirmed', )
	list_filter = ('confirmed',)

class ConfigurationInline(admin.TabularInline):
	model = machiavelli.Configuration
	extra = 1

class GameAdmin(admin.ModelAdmin):
	list_display = ('pk', 'slug', 'slots', 'scenario', 'created_by', 'started', 'finished', 'player_list', 'version')
	inlines = [ ConfigurationInline, ScoreInline,]

	def player_list(self, obj):
		users = []
		for p in obj.player_set.filter(user__isnull=False):
			users.append(p.user.username)
		return ", ".join(users)

	player_list.short_description = 'Player list'

class LiveGameAdmin(admin.ModelAdmin):
	list_display = ('pk', 'slug', 'paused', 'extended_deadline', 'year', 'season', 'phase', 'next_phase_change', 'started', 'version')
	actions = ['redraw_map',
				'check_finished_phase',
				'pause',
				'resume',]
	inlines = [ ConfigurationInline, PlayerInline, ]

	def redraw_map(self, request, queryset):
		for obj in queryset:
			obj.make_map()
	redraw_map.short_description = "Redraw map"

	def check_finished_phase(self, request, queryset):
		for obj in queryset:
			obj.check_finished_phase()
	check_finished_phase.short_description = "Check finished phase"

	def pause(self, request, queryset):
		queryset.update(paused=True)
	pause.short_description = "Pause the games"

	def resume(self, request, queryset):
		queryset.update(paused=False)
	resume.short_description = "Resume paused games"

class RetreatOrderAdmin(admin.ModelAdmin):
	pass

class TurnLogAdmin(admin.ModelAdmin):
	ordering = ['-timestamp']
	list_display = ('game', 'timestamp')
	list_filter = ('game',)

class ExpenseAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'ducats', 'type', 'unit', 'area', 'confirmed')
	list_filter = ('player', 'type',)

class RebellionAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'player', 'garrisoned', 'repressed',)
	list_filter = ('player',)

class LoanAdmin(admin.ModelAdmin):
	list_display = ('player', 'debt', 'year', 'season', )

class AssassinAdmin(admin.ModelAdmin):
	pass

class AssassinationAdmin(admin.ModelAdmin):
	pass

class WhisperAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'user', 'game', 'order',)

class InvitationAdmin(admin.ModelAdmin):
	pass

class GameCommentAdmin(admin.ModelAdmin):
	list_display = ('__unicode__', 'user', 'game', 'is_public')

admin.site.register(machiavelli.Game, GameAdmin)
admin.site.register(machiavelli.LiveGame, LiveGameAdmin)
admin.site.register(machiavelli.Unit, UnitAdmin)
admin.site.register(machiavelli.GameArea, GameAreaAdmin)
admin.site.register(machiavelli.Player, PlayerAdmin)
admin.site.register(machiavelli.Revolution, RevolutionAdmin)
admin.site.register(machiavelli.Score, ScoreAdmin)
admin.site.register(machiavelli.Order, OrderAdmin)
admin.site.register(machiavelli.RetreatOrder, RetreatOrderAdmin)
admin.site.register(machiavelli.TurnLog, TurnLogAdmin)
admin.site.register(machiavelli.Expense, ExpenseAdmin)
admin.site.register(machiavelli.Rebellion, RebellionAdmin)
admin.site.register(machiavelli.Loan, LoanAdmin)
admin.site.register(machiavelli.Assassin, AssassinAdmin)
admin.site.register(machiavelli.Assassination, AssassinationAdmin)
admin.site.register(machiavelli.Whisper, WhisperAdmin)
admin.site.register(machiavelli.Invitation, InvitationAdmin)
admin.site.register(machiavelli.GameComment, GameCommentAdmin)
admin.site.register(machiavelli.Team)
<|endoftext|>


<commit_before>
import os
import object_detector.file_io as file_io
import shutil

def test_list_files():
    # Given the following directories and files
    TEST_DIR = "TestDirectory"

    os.mkdir(TEST_DIR)
    os.mkdir(TEST_DIR + "\\sub1")
    os.mkdir(TEST_DIR + "\\sub2")

    files_in_txt = [TEST_DIR+ "\\a.txt",
                    TEST_DIR+ "\\b.txt",
                    TEST_DIR+ "\\sub1\\a_in_sub1.txt",
                    TEST_DIR+ "\\sub2\\b_in_sub2.txt"]
    files_in_log = ["test.log"]

    for filename in files_in_txt + files_in_log:
        with open(filename, "w") as _: pass

    # When perform crop_bb()
    files_listed_in_txt = file_io.list_files(directory=TEST_DIR, pattern="*.txt", n_files_to_sample=None, recursive_option=True)

    # Then it should be have same elements with files_created.
    assert set(files_listed_in_txt) == set(files_in_txt)

    # Remove test files and directory
    shutil.rmtree(TEST_DIR)

if __name__ == "__main__":
    import nose
    nose.run()

<commit_msg>test templeat written<commit_after>
import os
import object_detector.file_io as file_io
import shutil

def test_list_files():
    # Given the following directories and files
    TEST_DIR = "TestDirectory"

    os.mkdir(TEST_DIR)
    os.mkdir(TEST_DIR + "\\sub1")
    os.mkdir(TEST_DIR + "\\sub2")

    files_in_txt = [TEST_DIR+ "\\a.txt",
                    TEST_DIR+ "\\b.txt",
                    TEST_DIR+ "\\sub1\\a_in_sub1.txt",
                    TEST_DIR+ "\\sub2\\b_in_sub2.txt"]
    files_in_log = ["test.log"]

    for filename in files_in_txt + files_in_log:
        with open(filename, "w") as _: pass

    # When perform crop_bb()
    files_listed_in_txt = file_io.list_files(directory=TEST_DIR, pattern="*.txt", n_files_to_sample=None, recursive_option=True)

    # Then it should be have same elements with files_created.
    assert set(files_listed_in_txt) == set(files_in_txt)

    # Remove test files and directory
    shutil.rmtree(TEST_DIR)

def test_FileJson_interface():
    # Given the files
    file_io.FileJson().write()
    file_io.FileJson().read()

def test_FileMat_interface():
    # Given the files
    file_io.FileJson().write()
    file_io.FileJson().read()

def test_FileHDF5_interface():
    # Given the files
    file_io.FileJson().write()
    file_io.FileJson().read()

if __name__ == "__main__":
    import nose
    nose.run()

<|endoftext|>


<commit_before>import pytest

class NestedObject(object):
    pykka_traversable = True
    inner = 'nested.inner'

class NestedObjectWithSlots(object):
    __slots__ = ['pykka_traversable', 'inner']

    def __init__(self):
        # Objects using '__slots__' cannot have class attributes.
        self.pykka_traversable = True
        self.inner = 'nested_with_slots.inner'

@pytest.fixture
def actor_class(runtime):
    class ActorWithTraversableObjects(runtime.actor_class):
        nested = NestedObject()
        nested_with_slots = NestedObjectWithSlots()

        @property
        def nested_object_property(self):
            return NestedObject()

    return ActorWithTraversableObjects

@pytest.fixture
def proxy(actor_class):
    proxy = actor_class.start().proxy()
    yield proxy
    proxy.stop()

def test_attr_of_traversable_attr_can_be_read(proxy):
    assert proxy.nested.inner.get() == 'nested.inner'

def test_traversable_object_returned_from_property_is_not_traversed(proxy):
    # In Pykka < 2, it worked like this:
    # assert proxy.nested_object_property.inner.get() == 'nested.inner'

    # In Pykka >= 2, the property getter always returns a future:
    assert proxy.nested_object_property.get().inner == 'nested.inner'

def test_traversable_object_using_slots_works(proxy):
    assert proxy.nested_with_slots.inner.get() == 'nested_with_slots.inner'
<commit_msg>proxy: Improve tests of traversable attrs<commit_after>import pytest

class NestedWithNoMarker(object):
    inner = 'nested_with_no_marker.inner'

class NestedWithAttrMarker(object):
    pykka_traversable = True
    inner = 'nested_with_attr_marker.inner'

class NestedWithAttrMarkerAndSlots(object):
    __slots__ = ['pykka_traversable', 'inner']

    def __init__(self):
        # Objects using '__slots__' cannot have class attributes.
        self.pykka_traversable = True
        self.inner = 'nested_with_attr_marker_and_slots.inner'

@pytest.fixture
def actor_class(runtime):
    class ActorWithTraversableObjects(runtime.actor_class):
        nested_with_no_marker = NestedWithNoMarker()
        nested_with_attr_marker = NestedWithAttrMarker()
        nested_with_attr_marker_and_slots = NestedWithAttrMarkerAndSlots()

        @property
        def nested_object_property(self):
            return NestedWithAttrMarker()

    return ActorWithTraversableObjects

@pytest.fixture
def proxy(actor_class):
    proxy = actor_class.start().proxy()
    yield proxy
    proxy.stop()

def test_attr_without_marker_cannot_be_traversed(proxy):
    with pytest.raises(AttributeError) as exc_info:
        proxy.nested_with_no_marker.inner.get()

    assert "object has no attribute 'inner'" in str(exc_info.value)

@pytest.mark.parametrize(
    'attr_name, expected',
    [
        ('nested_with_attr_marker', 'nested_with_attr_marker.inner'),
        (
            'nested_with_attr_marker_and_slots',
            'nested_with_attr_marker_and_slots.inner',
        ),
    ],
)
def test_attr_of_traversable_attr_can_be_read(proxy, attr_name, expected):
    attr = getattr(proxy, attr_name)

    assert attr.inner.get() == expected

def test_traversable_object_returned_from_property_is_not_traversed(proxy):
    # In Pykka < 2, it worked like this:
    # assert proxy.nested_object_property.inner.get() == 'nested.inner'

    # In Pykka >= 2, the property getter always returns a future:
    assert (
        proxy.nested_object_property.get().inner
        == 'nested_with_attr_marker.inner'
    )

<|endoftext|>