text:
from __future__ import unicode_literals

# core
from django.conf import settings
from django.db import connection
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
# slugs
from django.utils.text import slugify
# signals
from django.db.models.signals import post_save, pre_save, post_delete
from django.dispatch import receiver
# fts
from djorm_pgfulltext.models import SearchManager
from djorm_pgfulltext.fields import VectorField
# mapscript
# misc
import os
from utils.commons import normalizar_texto
# from mapcache.settings import MAPSERVER_URL
import urlparse
# from lxml import etree

# geodjango
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from django_extras.contrib.auth.models import SingleOwnerMixin

from layerimport.models import TablaGeografica
from utils.db import update_table_col

CONST_VECTOR = 'vector'
CONST_RASTER = 'raster'

TIPO_DE_CAPA_ENUM = (
    (CONST_VECTOR, CONST_VECTOR),
    (CONST_RASTER, CONST_RASTER),
)

class TipoDeGeometria(models.Model):
    nombre = models.CharField('Nombre', null=False, blank=False, unique=True, max_length=50)  # Punto/Linea/Poligono/Raster
    postgres_type = models.CharField('Postgres Type', null=False, blank=False, max_length=100)  # Point/LineString/Polygon/"Raster"
    mapserver_type = models.CharField('Mapserver Type', null=False, blank=False, max_length=50)  # POINT/LINE/POLYGON/RASTER

    class Meta:
        verbose_name = u'Tipo de Geometría'
        verbose_name_plural = u'Tipos de Geometría'

    def __unicode__(self):
        return unicode(self.nombre)

# TODO: el save de esta clase debe garantizar datos minimos necesarios de raster o bin de vector
class Capa(SingleOwnerMixin, models.Model):
    nombre = models.CharField('Nombre', null=False, blank=False, max_length=255)  # puede repetirse para distintos usuarios
    id_capa = models.CharField('Id capa', null=False, blank=False, unique=True, max_length=255)
    slug = models.SlugField('Slug', null=False, blank=True, max_length=255)

    tipo_de_capa = models.CharField('Tipo de capa', choices=TIPO_DE_CAPA_ENUM, default=CONST_VECTOR, max_length=10, null=False, blank=False)    # vector o raster?
    tipo_de_geometria = models.ForeignKey('TipoDeGeometria', null=False, blank=False)
    gdal_driver_shortname = models.CharField('Driver - Short Name', null=False, blank=True, max_length=100, default='')
    gdal_driver_longname = models.CharField('Driver - Long Name', null=False, blank=True, max_length=100, default='')
    gdal_metadata = JSONField(default=dict())  # guarda informacion de gdalinfo para rasters y podria extenderse a ogrinfo para vectores

    # si es raster...
    nombre_del_archivo = models.CharField('Nombre del archivo', null=True, default=True, max_length=255)
    cantidad_de_bandas = models.IntegerField(null=True, blank=True)
    size_height = models.IntegerField(null=True, blank=True)
    size_width = models.IntegerField(null=True, blank=True)

    # si es vector...
    conexion_postgres = models.ForeignKey('ConexionPostgres', null=True, blank=True)
    esquema = models.CharField('Esquema', null=True, blank=True, max_length=100)
    tabla = models.CharField('Tabla', null=True, blank=True, max_length=100)
    campo_geom = models.CharField(u'Campo de Geometría', null=True, blank=True, max_length=30, default='geom')
    cantidad_de_registros = models.IntegerField('Cantidad de registros', null=True, blank=True)  # read_only, 0 a n para vector, None para raster

    # comunes ...
    proyeccion_proj4 = models.CharField(null=False, blank=True, max_length=255, default='')
    srid = models.IntegerField('SRID', null=False, blank=False)
    extent_minx_miny = models.PointField('(Minx, Miny)', null=True, blank=True)  # extent en 4326 calculado por postgres en el signal de creacion
    extent_maxx_maxy = models.PointField('(Maxx, Maxy)', null=True, blank=True)  # extent en 4326 calculado por postgres en el signal de creacion
    layer_srs_extent = models.CharField('Original SRS Extent', null=False, blank=False, max_length=255, default='')  # extent en el srid original calculado por postgres en el signal de creacion

    # publico? TODO: me parece mejor modelarlo aparte ya que es el unico atributo variable
    wxs_publico = models.BooleanField(u'WMS/WFS Público?', null=False, default=False)

    # automaticos...
    timestamp_alta = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de alta')
    timestamp_modificacion = models.DateTimeField(auto_now=True, verbose_name='Fecha de última modificación')
    objects = models.GeoManager()

    class Meta:
        # unique_together = (('esquema', 'tabla'),)  # ya no puede serlo por permitir nulos al extender a rasters
        verbose_name = 'Capa'
        verbose_name_plural = 'Capas'

    def __unicode__(self):
        return unicode(self.nombre)

    @property
    def dame_titulo(self):
        return self.metadatos.titulo if self.metadatos.titulo != '' else self.nombre

    @property
    def dame_projection(self):
        return unicode(self.srid)

    @property
    def dame_descripcion(self):
        if self.metadatos.descripcion == '':
            return u'Sin descripción'
        else:
            return self.metadatos.descripcion
        # TODO: sacar de epok/commons.py funcion que trunca sin cortar palabras

    @property
    def dame_fuente(self):
        return self.metadatos.fuente

    @property
    def dame_contacto(self):
        return self.metadatos.contacto

    @property
    def dame_connection_string(self):
        if self.conexion_postgres is None:
            return settings.DEFAULT_DB_CONNECTION_STRING
        else:
            return self.conexion_postgres.dame_connection_string

    @property
    def dame_connection_type(self):
        if self.tipo_de_capa == CONST_RASTER:
            return 'RASTER'
        else:
            return 'POSTGIS'

    @property
    def dame_tipo_de_capa(self):
        if self.tipo_de_capa == CONST_RASTER:
            return 'RASTER'
        else:
            return 'VECTOR'

    @property
    def dame_download_url(self):
        if self.tipo_de_capa == CONST_RASTER:
            return os.path.join(settings.UPLOADED_RASTERS_URL, unicode(self.owner), self.nombre_del_archivo)
        else:
            return ''

    def dame_data(self, srid=None):
        if self.tipo_de_capa == CONST_VECTOR:
            if srid is not None:
                return "geom_proj from (select *, st_transform(%s, %d) as geom_proj from %s.%s) aa using unique gid using srid=%d" % (self.campo_geom, srid, self.esquema, self.id_capa, srid)
            else:
                return "%s from %s.%s" % (self.campo_geom, self.esquema, self.id_capa)
        elif self.tipo_de_capa == CONST_RASTER:
            data = os.path.join(settings.UPLOADED_RASTERS_PATH, unicode(self.owner), self.nombre_del_archivo)
            if self.gdal_driver_shortname in ('netCDF', 'HDF5'):
                prefijo_data = self.gdal_driver_shortname.upper()  # NETCDF|HDF5
                return '{}:{}'.format(prefijo_data, data)

            return data

    def dame_datasource_data(self):
        if self.tipo_de_capa == CONST_VECTOR:
            # Esto es solo copy & paste de arriba... cuando hagamos WMS-T hay que ver que va!
            return "%s from %s.%s" % (self.campo_geom, self.esquema, self.tabla)
        elif self.tipo_de_capa == CONST_RASTER:
            return "extent from (select * from layers_rasterdatasource where capa_id=%d) as g using unique id"%(self.id)

    def dame_extent(self, separador=',', srid=4326):
        # heuristica para arreglar thumbnails: corta por la mitad a la antartida (lo maximo es -90)
        print 'layer.dame_extent(srid=%s), original srid: %s'%(srid, self.srid)
        if srid == self.srid:
            return self.layer_srs_extent.replace(' ', separador)
        if srid == 3857:
            if self.extent_minx_miny.y < -70:
                self.extent_minx_miny.y = -70

        try:
            min = self.extent_minx_miny.transform(srid, clone=True)
            max = self.extent_maxx_maxy.transform(srid, clone=True)

            if separador == []:
                return [min, max]
            else:
                return separador.join([str(min.x), str(min.y)]) + separador + separador.join([str(max.x), str(max.y)])
        except Exception as e:
            print "Error intentando transformar coordenadas para capa %s, srid: %s"%(self.id_capa, srid)
            raise e

    @property
    def dame_datos(self):
        if self.tipo_de_capa == CONST_RASTER:
            return None
        cursor = connection.cursor()
        try:
            cursor.execute("SELECT %s from %s.%s limit 100" % (','.join(map(lambda x: '\"%s\"' % x, self.metadatos.dame_nombres_atributos())), self.esquema, self.tabla))
        except:
            cursor.execute("SELECT * from %s.%s limit 100" % (self.esquema, self.tabla))
        rows = cursor.fetchall()
        return rows

    def dame_sld_default(self):
        slds = self.archivosld_set.filter(default=True)
        if len(slds) > 0:
            default_sld = slds[0].filename.url
            return urlparse.urljoin(settings.SITE_URL, default_sld)
        return None

    def actualizar_atributos(self):
        cursor = connection.cursor()
        cursor.execute("SELECT * from utils.campos_de_tabla(%s,%s)", [self.esquema, self.tabla])
        rows = cursor.fetchall()
        for r in rows:
            try:
                attr = self.metadatos.atributo_set.get(nombre_del_campo=r[1])
                attr.tipo = r[2]
                attr.save()
            except:
                pass

    def actualizar_datasource(self, datasource):
        if self.tipo_de_capa == CONST_RASTER:
            self.nombre_del_archivo=datasource.nombre_del_archivo
            self.cantidad_de_bandas=datasource.cantidad_de_bandas
            self.size_height=datasource.size_height
            self.size_width=datasource.size_width
            self.gdal_metadata=datasource.gdal_metadata
            self.gdal_driver_shortname=datasource.gdal_driver_shortname
            self.gdal_driver_longname=datasource.gdal_driver_longname
            self.proyeccion_proj4=datasource.proyeccion_proj4
            self.srid=datasource.srid
        else:
            self.tabla=datasource.tabla
        self.save()

    def mostrarComoWMS(self):
        if (self.tipo_de_capa == 'raster'):
            return True # self.gdal_driver_shortname not in ('netCDF', 'HDF5')
        else:
            return len(VectorDataSource.objects.filter(capa=self)) > 1

    @property
    def dame_bandas(self):
        return list(self.mapa_set.all().filter(tipo_de_mapa='layer_raster_band').values('id', 'id_mapa', 'titulo'))

    def save(self, *args, **kwargs):
        # TODO: pensar: vamos a permitir que una capa pueda cambiar su nombre? esto cambaria el id con el tiempo, hay que actualizar las referencias en los mapfiles....si no queremos, hay que hacer algun truco:dirtyfields,compararcontra la base,etc
        # if self.slug == '':
        #     self.slug=slugify(unicode(self.nombre)).replace("-", "_")
        self.slug = slugify(unicode(self.nombre)).replace('-', '_')
        # el id_capa lo setea la aplicacion que hace el upload
        # self.id_capa=self.owner.username+'_'+self.slug

        super(Capa, self).save(*args, **kwargs)
        return True

class Categoria(models.Model):
    nombre = models.CharField('Nombre', null=False, blank=False, unique=True, max_length=50)
    descripcion = models.TextField(u'Descripción', null=False, blank=True, max_length=255)

    class Meta:
        verbose_name = 'Categoría'
        verbose_name_plural = 'Categorías'
        ordering = ['nombre']

    def __unicode__(self):
        return unicode(self.nombre)

class AreaTematica(models.Model):
    nombre = models.CharField('Nombre', null=False, blank=False, unique=True, max_length=50)
    descripcion = models.TextField(u'Descripción', null=False, blank=True, max_length=255)

    class Meta:
        verbose_name = 'Área Temática'
        verbose_name_plural = 'Áreas Temáticas'
        ordering = ['nombre']

    def __unicode__(self):
        return unicode(self.nombre)

class DataSource(SingleOwnerMixin, models.Model):
    capa = models.ForeignKey(Capa, null=False)
    proyeccion_proj4 = models.CharField(null=False, blank=True, max_length=255, default='')
    srid = models.IntegerField('SRID', null=False, blank=False)
    extent = models.MultiPolygonField(null=False, blank=False)
    timestamp_modificacion = models.DateTimeField(auto_now=True, verbose_name='Fecha de última modificación')
    objects = models.GeoManager()

    class Meta:
        abstract=True
        ordering = ['timestamp_modificacion']

    @property
    def is_only_datasource(self):
        num_ds = self.__class__.objects.filter(capa=self.capa).count()
        return num_ds == 1

class VectorDataSource(DataSource):
    capa = models.ForeignKey(Capa, null=False, related_name='vectordatasources')
    conexion_postgres = models.ForeignKey('ConexionPostgres', null=True, blank=True)
    esquema = models.CharField('Esquema', null=True, blank=True, max_length=100)
    tabla = models.CharField('Tabla', null=True, blank=True, max_length=100)
    campo_geom = models.CharField(u'Campo de Geometría', null=True, blank=True, max_length=30, default='geom')
    cantidad_de_registros = models.IntegerField('Cantidad de registros', null=True, blank=True)  # read_only, 0 a n para vector, None para raster
    data_datetime = models.DateTimeField('Fecha de los datos', auto_now=False, null=False, blank=False)
    objects = models.GeoManager()

class RasterDataSource(DataSource):
    capa = models.ForeignKey(Capa, null=False, related_name='rasterdatasources')
    nombre_del_archivo = models.CharField('Nombre del archivo', null=False, max_length=255)
    location = models.CharField('Ubicación del archivo', null=False, max_length=255)
    gdal_driver_shortname = models.CharField('Driver - Short Name', null=False, blank=True, max_length=100, default='')
    gdal_driver_longname = models.CharField('Driver - Long Name', null=False, blank=True, max_length=100, default='')
    gdal_metadata = JSONField(default=dict())  # guarda informacion de gdalinfo para rasters y podria extenderse a ogrinfo para vectores
    cantidad_de_bandas = models.IntegerField(null=True, blank=True)
    size_height = models.IntegerField(null=True, blank=True)
    size_width = models.IntegerField(null=True, blank=True)
    data_datetime = models.DateTimeField('Fecha de los datos', auto_now=False, null=False, blank=False)
    active = models.BooleanField(default=False, null=False, blank=False)
    objects = models.GeoManager()

    @property
    def dame_download_url(self):
        if self.capa.tipo_de_capa == CONST_RASTER:
            return os.path.join(settings.UPLOADED_RASTERS_URL, unicode(self.capa.owner), self.nombre_del_archivo)
        else:
            return ''

def get_newest_datasource_for_layer(capa):
    if capa.tipo_de_capa == CONST_RASTER:
        return RasterDataSource.objects.filter(capa=capa).order_by('-data_datetime').first()
    else:
        return VectorDataSource.objects.filter(capa=capa).order_by('-data_datetime').first()

class Escala(models.Model):
    nombre = models.CharField('Nombre', null=False, blank=False, unique=True, max_length=100)

    class Meta:
        verbose_name = 'Escala'
        verbose_name_plural = 'Escalas'
        ordering = ['nombre']

    def __unicode__(self):
        return unicode(self.nombre)

class Atributo(models.Model):
    nombre_del_campo = models.CharField('Nombre del Campo', null=False, blank=False, max_length=50)  # debe ser r/o
    tipo = models.CharField('Tipo', null=False, blank=True, max_length=50)  # lo que diga postgres!, debe ser r/o
    alias = models.CharField('Alias', null=False, blank=True, max_length=50)
    descripcion = models.TextField(u'Descripción', null=False, blank=True, max_length=1000)
    publicable = models.BooleanField(null=False, default=True)
    unico = models.BooleanField(null=False, default=False)
    metadatos = models.ForeignKey('Metadatos', null=False)

    class Meta:
        unique_together = (('nombre_del_campo', 'metadatos'),)
        verbose_name = 'Atributo'
        verbose_name_plural = 'Atributos'

    def __unicode__(self):
        return unicode(self.nombre_del_campo) + ('(%s)' % (unicode(self.alias)) if self.alias != '' else '')

    @property
    def dame_descripcion(self):
        descr = self.descripcion[:50]
        if descr == '':
            return 'Sin descripción'
        else:
            return descr + '...'  # TODO: sacar de epok/commons.py funcion que trunca sin cortar palabras

    def save(self, *args, **kwargs):
        self.alias = normalizar_texto(self.alias, False)  # sacamos espacios y caracteres especiales que traen problemas en WXS pero mantenemos mayusculas y minusculas
        if self.alias != '':  # si empieza con numero le agregamos un _ al inicio
            if self.alias[0].isdigit():
                self.alias = '_' + self.alias
        super(Atributo, self).save(*args, **kwargs)

class ConexionPostgres(models.Model):
    nombre = models.CharField('Nombre', null=False, blank=True, max_length=50)
    host = models.CharField('Host', null=False, blank=False, max_length=50)
    port = models.CharField('Port', null=False, blank=True, max_length=50)
    dbname = models.CharField('Database', null=False, blank=False, max_length=50)
    user = models.CharField('User', null=False, blank=False, max_length=50)
    password = models.CharField('Password', null=False, blank=False, max_length=50)

    class Meta:
        verbose_name = u'Conexión Postgres'
        verbose_name_plural = 'Conexiones Postgres'
        ordering = ['nombre']

    def __unicode__(self):
        if self.nombre != '':
            return unicode(self.nombre)
        """ Devuelve algo de la forma 'Nombre (user@host:port.dbname)' """
        conexion = '%s@%s' % (self.user, self.host)
        if self.port != '':
            conexion += ':%s' % (self.port)
        conexion += '.%s' % (self.dbname)
#        if self.nombre!='':
#            conexion='%s (%s)'%(unicode(self.nombre),conexion)
        return conexion
    # TODO: encriptamos conexiones? que implica?

    @property
    def dame_connection_string(self):
        return 'host=%s dbname=%s user=%s password=%s port=%s'\
            % (self.host, self.dbname, self.user, self.password, self.port)

class Metadatos(models.Model):
    capa = models.OneToOneField(Capa, null=False)
    nombre_capa = models.CharField('Nombre Capa', null=False, blank=True, max_length=255)  # TODO: ver si al final usamos solo slug
    slug_capa = models.CharField('Slug Capa', null=False, blank=True, max_length=255)

    titulo = models.CharField(u'Título', null=False, blank=False, max_length=255)  # title
    fuente = models.TextField(u'Fuente', null=False, blank=True, max_length=1000)  # attribution
    contacto = models.TextField(u'Contacto', null=False, blank=True, max_length=1000)  # contact organization
    descripcion = models.TextField(u'Descripción', null=False, blank=True, max_length=10000)  # abstract
    escala = models.ForeignKey(Escala, null=True, blank=True, on_delete=models.SET_NULL)
    palabras_claves = models.TextField(u'Palabras Claves', null=False, blank=True, max_length=10000)
    categorias = models.ManyToManyField('Categoria', blank=True, verbose_name=u'Categorías')
    area_tematica = models.ForeignKey('AreaTematica', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=u'Área Temática')

    fecha_de_relevamiento = models.CharField('Fecha de Relevamiento', null=False, blank=True, max_length=50)
    fecha_de_actualizacion = models.CharField(u'Fecha de Actualización', null=False, blank=True, max_length=50)
    frecuencia_de_actualizacion = models.CharField(u'Frecuencia de Actualización', null=False, blank=True, max_length=100)
    timestamp_alta = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de alta')
    timestamp_modificacion = models.DateTimeField(auto_now=True, verbose_name='Fecha de última modificación')

    input_search_index = models.TextField(null=False, blank=True, default='')
    search_index = VectorField()

    class Meta:
        verbose_name = 'Metadatos de Capa'
        verbose_name_plural = 'Metadatos de Capas'

    def __unicode__(self):
        try:
            return unicode(self.capa)
        except:
            return 'sin capa!'  # no deberia pasar por disenio

    # TODO: def save(self): obligar a mantener la capa original!
    def dame_gml_atributos(self):
        include_items = []
        items_aliases = []
        for a in self.atributo_set.all():
            if a.publicable and a.nombre_del_campo not in ('gid', 'geom'):
                include_items.append(a.nombre_del_campo.encode('UTF-8'))
                if a.alias != '':
                    items_aliases.append((a.nombre_del_campo.encode('UTF-8'), a.alias.encode('UTF-8')))
        return include_items, items_aliases

    def dame_nombres_atributos(self):
        include_items = []
        for a in self.atributo_set.all():
            if a.nombre_del_campo not in ('gid', 'geom'):
                include_items.append(a.nombre_del_campo)
        return include_items

    @property
    def dame_categorias(self):
        res = []
        for cat in self.categorias.all():
            res.append(cat.nombre)
        return res

    def actualizar_input_search_index(self):
        textos = []
        textos.append(self.capa.nombre)
        textos.append(self.capa.id_capa)
        textos.append(normalizar_texto(self.titulo))
        textos.append(normalizar_texto(self.palabras_claves))
        textos.append(normalizar_texto(self.descripcion))
        self.input_search_index = ' '.join(textos)

    def save(self, *args, **kwargs):
        self.actualizar_input_search_index()
        super(Metadatos, self).save(*args, **kwargs)

    objects = SearchManager(
        # fields = ('nombre_capa', 'slug_capa', 'titulo', 'palabras_claves'),
        fields=('input_search_index',),
        config='pg_catalog.spanish',  # this is default
        search_field='search_index',  # this is default
        auto_update_search_field=True
    )

@receiver(pre_save, sender=Capa)
def onCapaPreSave(sender, instance, **kwargs):
    print 'onCapaPreSave %s' % (str(instance))
    # carga inicial de campos read only de la capa
    # if instance.id is None: # Al haber actualizaciones hay que hacerlo siempre
    print '...carga inicial de datos read only'
    if instance.tipo_de_capa == CONST_VECTOR:
        cursor = connection.cursor()
        # esta escritura (segura y recomendada) no funciona porque internamente escapea strings con ' y no sirve para el FROM
        # cursor.execute("SELECT count(*) from %s.%s", [instance.esquema, instance.tabla])
        cursor.execute("SELECT count(*) from %s.%s" % (instance.esquema, instance.tabla))
        rows = cursor.fetchone()
        instance.cantidad_de_registros = int(rows[0])
        cursor.execute("SELECT GeometryType(%s) FROM %s.%s LIMIT 1" % (instance.campo_geom, instance.esquema, instance.tabla))
        rows = cursor.fetchone()
        instance.tipo_de_geometria = TipoDeGeometria.objects.get(postgres_type=rows[0])
        cursor.execute("SELECT st_extent(%s) from %s.%s;" % (instance.campo_geom, instance.esquema, instance.tabla))
        rows = cursor.fetchone()
        instance.layer_srs_extent = rows[0].replace('BOX(', '').replace(')', '').replace(',', ' ')
        cursor.execute("SELECT st_extent(st_transform(%s,4326)) from %s.%s;" % (instance.campo_geom, instance.esquema, instance.tabla))
        rows = cursor.fetchone()
        extent_capa = rows[0].replace('BOX(', '').replace(')', '').replace(',', ' ').split(' ')
        instance.extent_minx_miny = Point(float(extent_capa[0]), float(extent_capa[1]), srid=4326)
        instance.extent_maxx_maxy = Point(float(extent_capa[2]), float(extent_capa[3]), srid=4326)

@receiver(post_save, sender=Metadatos)
def onMetadatosPostSave(sender, instance, created, **kwargs):
    print 'onMetadatosPostSave'
    instance.capa.save()  # forzamos la actualizacion de la fecha de ultima modificacion de la capa y posterior borrado de mapfile

def get_sld_filename(instance, filename):
    return os.path.join('sld', instance.id_archivo_sld)

class ArchivoSLD(models.Model):
    id_archivo_sld = models.CharField('Id Archivo SLD', null=False, blank=False, unique=True, max_length=500)
    capa = models.ForeignKey('Capa', null=False)
    filename = models.FileField('Nombre de archivo SLD', upload_to=get_sld_filename, max_length=500)
    descripcion = models.TextField(u'Descripción', null=False, blank=True, max_length=10000)
    default = models.BooleanField(u'Activa', null=False, default=False)
    user_alta = models.CharField(u'Subido por', null=False, blank=True, max_length=50, default='')
    user_modificacion = models.CharField(u'Modificado por', null=False, blank=True, max_length=50, default='')
    timestamp_alta = models.DateTimeField('Fecha de alta', null=True, blank=True)
    timestamp_modificacion = models.DateTimeField('Fecha de última modificación', null=True, blank=True)

    class Meta:
        verbose_name = 'Archivo SLD'
        verbose_name_plural = 'Archivos SLD'

    def __unicode__(self):
        return unicode(self.id_archivo_sld)

@receiver(pre_save, sender=ArchivoSLD)
def onArchivoSLDPreSave(sender, instance, **kwargs):
    print 'onArchivoSLDPreSave %s' % (str(instance))
    # instance.id_archivo_sld = instance.capa.id_capa+'_'+instance.filename.name
    if instance.pk is None:  # si voy a crear un nuevo SLD:
        # 1 - defino el id, unico, garantizado por validacion previa en el form
        uploaded_filename = normalizar_texto(os.path.splitext(instance.filename.name)[0])
        instance.id_archivo_sld = (instance.capa.id_capa + '_' if not uploaded_filename.startswith(instance.capa.id_capa) else '') + uploaded_filename + '.sld'
        # 2 - lo marco como default si no hay otro
        if not instance.default and len(ArchivoSLD.objects.filter(capa=instance.capa).filter(default=True)) == 0:
            instance.default = True
    else:  # si voy a actualizar un SLD:
        try:
            # borro el SLD anterior
            old_filename = ArchivoSLD.objects.get(pk=instance.pk).filename
            if old_filename != instance.filename:
                os.remove(os.path.join(settings.MEDIA_ROOT, old_filename.name))
        except:
            pass

@receiver(post_delete, sender=VectorDataSource)
def onVectorDataSourcePostDelete(sender, instance, **kwargs):
    print "VectorDataSource para tabla %s borrado."%(instance.tabla)
    print "Borrando tabla geografica..."
    TablaGeografica.objects.filter(tabla=instance.tabla).delete()

@receiver(post_save, sender=VectorDataSource)
def onVectorDataSourcePostSave(sender, instance, **kwargs):
    print "Actualizacion de vector data source..."
    update_table_col(instance.esquema, instance.tabla, 'data_datetime', instance.data_datetime.isoformat())


text:
//********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************

#ifndef UML_SENDSIGNALACTION_HPP
#define UML_SENDSIGNALACTION_HPP

#include <map>

#include <memory>
#include <string>
// forward declarations
template<class T, class ... U> class Subset;

class AnyObject;
typedef std::shared_ptr<AnyObject> Any;

//*********************************
// generated Includes
#include <map> // used for Persistence
#include <vector> // used for Persistence
namespace persistence
{
	namespace interfaces
	{
		class XLoadHandler; // used for Persistence
		class XSaveHandler; // used for Persistence
	}
}

namespace uml
{
	class umlFactory;
}

//Forward Declaration for used types
namespace uml
{
	class Activity;
	class ActivityEdge;
	class ActivityGroup;
	class ActivityPartition;
	class Classifier;
	class Comment;
	class Constraint;
	class Dependency;
	class ExceptionHandler;
	class InputPin;
	class InterruptibleActivityRegion;
	class Namespace;
	class OutputPin;
	class Port;
	class Signal;
	class StringExpression;
	class StructuredActivityNode;
}

// namespace macro header include
#include "uml/uml.hpp"

// base class includes
#include "uml/InvocationAction.hpp"

// enum includes
#include "uml/VisibilityKind.hpp"

//*********************************
namespace uml
{
	/*!
	A SendSignalAction is an InvocationAction that creates a Signal instance and transmits it to the target object. Values from the argument InputPins are used to provide values for the attributes of the Signal. The requestor continues execution immediately after the Signal instance is sent out and cannot receive reply values.

From package UML::Actions.

	*/

	class UML_API SendSignalAction: virtual public InvocationAction
	{
		public:
 			SendSignalAction(const SendSignalAction &) {}

		protected:
			SendSignalAction(){}

		public:
			virtual std::shared_ptr<ecore::EObject> copy() const = 0;

			//destructor
			virtual ~SendSignalAction() {}

			//*********************************
			// Operations
			//*********************************
			/*!
			The number and order of argument InputPins must be the same as the number and order of attributes of the signal.
			argument->size()=signal.allAttributes()->size()
			*/

			virtual bool number_order(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context) = 0;
			/*!
			The type, ordering, and multiplicity of an argument InputPin must be the same as the corresponding attribute of the signal.
			let attribute: OrderedSet(Property) = signal.allAttributes() in
			Sequence{1..argument->size()}->forAll(i |
				argument->at(i).type.conformsTo(attribute->at(i).type) and
				argument->at(i).isOrdered = attribute->at(i).isOrdered and
				argument->at(i).compatibleWith(attribute->at(i)))
			*/

			virtual bool type_ordering_multiplicity(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context) = 0;
			/*!
			If onPort is not empty, the Port given by onPort must be an owned or inherited feature of the type of the target InputPin.
			not onPort->isEmpty() implies target.type.oclAsType(Classifier).allFeatures()->includes(onPort)
			*/

			virtual bool type_target_pin(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context) = 0;

			//*********************************
			// Attribute Getters & Setters
			//*********************************

			//*********************************
			// Reference Getters & Setters
			//*********************************
			/*!
			The Signal whose instance is transmitted to the target.

From package UML::Actions.

			*/

			virtual std::shared_ptr<uml::Signal> getSignal() const = 0;
			/*!
			The Signal whose instance is transmitted to the target.

From package UML::Actions.

			*/

			virtual void setSignal(std::shared_ptr<uml::Signal>) = 0;
			/*!
			The InputPin that provides the target object to which the Signal instance is sent.

From package UML::Actions.

			*/

			virtual std::shared_ptr<uml::InputPin> getTarget() const = 0;
			/*!
			The InputPin that provides the target object to which the Signal instance is sent.

From package UML::Actions.

			*/

			virtual void setTarget(std::shared_ptr<uml::InputPin>) = 0;

			//*********************************
			// Union Reference Getters
			//*********************************
			/*!
			ActivityGroups containing the ActivityNode.

From package UML::Activities.

			*/

			virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;
			/*!
			The ordered set of InputPins representing the inputs to the Action.

From package UML::Actions.

			*/

			virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;
			/*!
			The Elements owned by this Element.

From package UML::CommonStructure.

			*/

			virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;
			/*!
			The Element that owns this Element.

From package UML::CommonStructure.

			*/

			virtual std::weak_ptr<uml::Element> getOwner() const = 0;
			/*!
			The RedefinableElement that is being redefined by this element.

From package UML::Classification.

			*/

			virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0;

			//*********************************
			// Container Getter
			//*********************************
			virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;

			//*********************************
			// Persistence Functions
			//*********************************
			virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
			virtual void resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references) = 0;
			virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;

		protected:
			//*********************************
			// Attribute Members
			//*********************************

			//*********************************
			// Reference Members
			//*********************************
			/*!
			The Signal whose instance is transmitted to the target.

From package UML::Actions.

			*/

			std::shared_ptr<uml::Signal> m_signal;
			/*!
			The InputPin that provides the target object to which the Signal instance is sent.

From package UML::Actions.

			*/

			std::shared_ptr<uml::InputPin> m_target;
	};
}
#endif /* end of include guard: UML_SENDSIGNALACTION_HPP */

redpajama_set_name: RedPajamaGithub


text:
package com.interest.common.utils;

public class FileUtil {

	/**
	 * 根据给定的文件名,获取其后缀信息
	 * @param filename
	 * @return
	 */
	public static String getSuffixByFileName ( String fileName ) {

		return fileName.substring( fileName.lastIndexOf( "." ) + 1).toLowerCase();

	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Light.DependencyInjection.Registrations;
using Light.GuardClauses;

namespace Light.DependencyInjection.TypeResolving
{
    public struct ResolveExpressionContext
    {
        public readonly TypeKey RequestedTypeKey;
        public readonly Registration Registration;
        public readonly DependencyInjectionContainer Container;
        public readonly Type ResolvedGenericRegistrationType;
        public readonly TypeInfo RegistrationTypeInfo;
        public readonly TypeInfo ResolvedGenericRegistrationTypeInfo;
        public readonly DependencyOverrides DependencyOverrides;

        public ResolveExpressionContext(TypeKey requestedTypeKey,
                                        Registration registration,
                                        DependencyOverrides dependencyOverrides,
                                        DependencyInjectionContainer container)
        {
            RequestedTypeKey = requestedTypeKey.MustNotBeEmpty(nameof(requestedTypeKey));
            Registration = registration.MustNotBeNull(nameof(registration));
            DependencyOverrides = dependencyOverrides;
            Container = container.MustNotBeNull(nameof(container));
            RegistrationTypeInfo = registration.TypeKey.Type.GetTypeInfo();
            ResolvedGenericRegistrationType = null;
            ResolvedGenericRegistrationTypeInfo = null;

            // ReSharper disable once PossibleNullReferenceException
            if (RegistrationTypeInfo.IsGenericTypeDefinition == false)
                return;

            try
            {
                ResolvedGenericRegistrationType = registration.TargetType.MakeGenericType(RequestedType.GenericTypeArguments);
                ResolvedGenericRegistrationTypeInfo = ResolvedGenericRegistrationType.GetTypeInfo();
            }
            catch (Exception exception)
            {
                throw new ResolveException($"Could not resolve a concrete instance of the generic type definition \"{RegistrationType}\" using the type \"{RequestedType}\".", exception);
            }
        }

        public Type RequestedType => RequestedTypeKey.Type;
        public Type RegistrationType => Registration.TargetType;
        public Type InstanceType => ResolvedGenericRegistrationType ?? RegistrationType;
        public bool IsResolvingGenericTypeDefinition => RegistrationType.IsGenericTypeDefinition();

        public Type ResolveGenericTypeParameterIfNecessary(Type type)
        {
            return type.IsGenericTypeParameter() == false ? type : ResolveGenericTypeParameter(type);
        }

        private Type ResolveGenericTypeParameter(Type type)
        {
            for (var i = 0; i < RegistrationTypeInfo.GenericTypeParameters.Length; i++)
            {
                if (RegistrationTypeInfo.GenericTypeParameters[i] == type)
                    return ResolvedGenericRegistrationTypeInfo.GenericTypeArguments[i];
            }

            throw new ArgumentException($"The type \"{type}\" does not correspond to a generic parameter of type \"{RegistrationType}\".", nameof(type));
        }

        public T FindResolvedGenericMethod<T>(T genericMethods, IReadOnlyList<T> constructedMethods) where T : MethodBase
        {
            var parametersOfGenericMethod = genericMethods.GetParameters();
            for (var i = 0; i < constructedMethods.Count; i++)
            {
                var targetMethod = constructedMethods[i];
                var parameters = targetMethod.GetParameters();
                if (MatchParameters(parameters, parametersOfGenericMethod))
                    return targetMethod;
            }
            return null;
        }

        public bool MatchParameters(ParameterInfo[] constructedGenericTypeParameters,
                                    ParameterInfo[] genericTypeDefinitionParameters)
        {
            if (constructedGenericTypeParameters.Length != genericTypeDefinitionParameters.Length)
                return false;

            for (var i = 0; i < constructedGenericTypeParameters.Length; i++)
            {
                var firstParameter = constructedGenericTypeParameters[i];
                var secondParameter = genericTypeDefinitionParameters[i];
                var resolvedParameterType = ResolveGenericTypeParameterIfNecessary(secondParameter.ParameterType);
                resolvedParameterType = ResolveOpenConstructedGenericTypeIfNecessary(resolvedParameterType);

                if (resolvedParameterType != firstParameter.ParameterType)
                    return false;
            }
            return true;
        }

        public Type ResolveOpenConstructedGenericTypeIfNecessary(Type dependencyType)
        {
            var openConstructedGenericTypeInfo = dependencyType.GetTypeInfo();

            if (openConstructedGenericTypeInfo.IsOpenConstructedGenericType() == false)
                return dependencyType;

            var resolvedGenericParameters = new Type[openConstructedGenericTypeInfo.GenericTypeArguments.Length];
            for (var i = 0; i < resolvedGenericParameters.Length; i++)
            {
                var typeArgument = openConstructedGenericTypeInfo.GenericTypeArguments[i];
                if (typeArgument.IsGenericParameter == false)
                    resolvedGenericParameters[i] = typeArgument;
                else
                    resolvedGenericParameters[i] = ResolveGenericTypeParameter(typeArgument);
            }

            return dependencyType.GetGenericTypeDefinition().MakeGenericType(resolvedGenericParameters);
        }

        public Expression CreateInstantiationAndTrackDisposableExpression(Expression createInstanceExpression)
        {
            if (Registration.IsTrackingDisposables == false || InstanceType.IsImplementing(Constants.IDisposableType) == false)
                return createInstanceExpression;

            var createAndTrackExpressions = new Expression[3];
            var variableExpression = Expression.Variable(InstanceType);
            createAndTrackExpressions[0] = Expression.Assign(variableExpression, createInstanceExpression);
            createAndTrackExpressions[1] = Expression.Call(Expression.Field(Expression.Property(Constants.ResolveContextParameterExpression, Constants.ResolveContextContainerProperty),
                                                                            Constants.ContainerScopeField),
                                                           Constants.ScopeAddDisposableMethod,
                                                           Expression.Convert(variableExpression, Constants.IDisposableType));
            createAndTrackExpressions[2] = variableExpression;

            return Expression.Block(InstanceType, new[] { variableExpression }, createAndTrackExpressions);
        }
    }
}


text:
import inspect
import os.path

import eventlet
from oslo_config import cfg
from yaql.language import expressions as yaql_expressions
from yaql.language import specs
from yaql.language import utils
from yaql.language import yaqltypes
from yaql import yaql_interface

from murano.dsl import constants
from murano.dsl import dsl_types
from murano.dsl import helpers

CONF = cfg.CONF
NO_VALUE = utils.create_marker('NO_VALUE')

def name(dsl_name):
    def wrapper(cls):
        cls.__murano_name = dsl_name
        return cls
    return wrapper

class MuranoObjectParameter(yaqltypes.PythonType):
    def __init__(self, murano_class=None, nullable=False, version_spec=None,
                 decorate=True):
        self.murano_class = murano_class
        self.version_spec = version_spec
        self.decorate = decorate
        super(MuranoObjectParameter, self).__init__(
            (dsl_types.MuranoObject, MuranoObjectInterface), nullable)

    def check(self, value, context, *args, **kwargs):
        if not super(MuranoObjectParameter, self).check(
                value, context, *args, **kwargs):
            return False
        if value is None or isinstance(value, yaql_expressions.Expression):
            return True
        if isinstance(value, MuranoObjectInterface):
            value = value.object
        if not isinstance(value, dsl_types.MuranoObject):
            return False
        if self.murano_class:
            murano_class = self.murano_class
            if isinstance(murano_class, str):
                return helpers.is_instance_of(
                    value, murano_class,
                    self.version_spec or helpers.get_type(context))
            else:
                return murano_class.is_compatible(value)
        else:
            return True

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        result = super(MuranoObjectParameter, self).convert(
            value, sender, context, function_spec, engine, *args, **kwargs)
        if self.decorate:
            return MuranoObjectInterface.create(result)
        else:
            if isinstance(result, dsl_types.MuranoObject):
                return result
            return None if result is None else result.object

class ThisParameter(yaqltypes.HiddenParameterType, yaqltypes.SmartType):
    def __init__(self):
        super(ThisParameter, self).__init__(False)

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        return get_this(context)

class InterfacesParameter(yaqltypes.HiddenParameterType,
                          yaqltypes.SmartType):
    def __init__(self):
        super(InterfacesParameter, self).__init__(False)

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        this = helpers.get_this(context)
        return Interfaces(this)

class MuranoTypeParameter(yaqltypes.PythonType):
    def __init__(self, base_type=None, nullable=False, context=None,
                 resolve_strings=True, lazy=False):
        self._context = context
        self._base_type = base_type
        self._resolve_strings = resolve_strings
        self._lazy = lazy
        super(MuranoTypeParameter, self).__init__(
            (dsl_types.MuranoTypeReference, str), nullable)

    def check(self, value, context, *args, **kwargs):
        if not super(MuranoTypeParameter, self).check(
                value, context, *args, **kwargs):
            return False
        if isinstance(value, str):
            if not self._resolve_strings:
                return False
            value = helpers.get_class(value, context).get_reference()
        if isinstance(value, dsl_types.MuranoTypeReference):
            if not self._base_type:
                return True
            return self._base_type.is_compatible(value)
        return True

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):

        def implementation(ctx=None):
            value2 = value
            if ctx is None:
                ctx = self._context or context
            if isinstance(value2, yaql_expressions.Expression):
                value2 = value2(utils.NO_VALUE, ctx, engine)
            value2 = super(MuranoTypeParameter, self).convert(
                value2, sender, ctx, function_spec, engine)
            if isinstance(value2, str):
                value2 = helpers.get_class(value2, ctx).get_reference()
            if self._base_type and not self._base_type.is_compatible(value):
                raise ValueError('Value must be subtype of {0}'.format(
                    self._base_type.name
                ))
            return value2

        if self._lazy:
            return implementation
        return implementation()

class MuranoObjectInterface(dsl_types.MuranoObjectInterface):
    class DataInterface(object):
        def __init__(self, object_interface):
            object.__setattr__(self, '__object_interface', object_interface)

        def __getattr__(self, item):
            oi = getattr(self, '__object_interface')
            return oi[item]

        def __setattr__(self, key, value):
            oi = getattr(self, '__object_interface')
            oi[key] = value

    class CallInterface(object):
        def __init__(self, object_interface):
            self.__object_interface = object_interface

        def __getattr__(self, item):
            def func(*args, **kwargs):
                self._insert_instruction()
                with helpers.with_object_store(
                        self.__object_interface._object_store):
                    context = helpers.get_context()
                    obj = self.__object_interface.object
                    return to_mutable(obj.type.invoke(
                        item, obj, args, kwargs,
                        context), helpers.get_yaql_engine(context))
            return func

        @staticmethod
        def _insert_instruction():
            context = helpers.get_context()
            if context:
                frame = inspect.stack()[2]
                location = dsl_types.ExpressionFilePosition(
                    os.path.abspath(frame[1]), frame[2],
                    -1, frame[2], -1)
                context[constants.CTX_CURRENT_INSTRUCTION] = NativeInstruction(
                    frame[4][0].strip(), location)

    def __init__(self, mpl_object):
        self._object = mpl_object
        self._object_store = helpers.get_object_store()

    @staticmethod
    def create(mpl_object):
        if mpl_object is None or isinstance(mpl_object, MuranoObjectInterface):
            return mpl_object
        return MuranoObjectInterface(mpl_object)

    @property
    def object(self):
        return self._object

    @property
    def id(self):
        return self.object.object_id

    @property
    def owner(self):
        owner = self.object.owner
        return MuranoObjectInterface.create(owner)

    def find_owner(self, type, optional=False):
        if isinstance(type, str):
            type = helpers.get_class(type)
        elif isinstance(type, dsl_types.MuranoTypeReference):
            type = type.type
        owner = helpers.find_object_owner(
            self.object, lambda t: type.is_compatible(t))
        if owner:
            return MuranoObjectInterface(owner)
        if not optional:
            raise ValueError('Object is not owned by any instance of type '
                             '{0}'.format(type.name))
        return None

    @property
    def type(self):
        return self.object.type

    @property
    def package(self):
        return self.type.package

    @property
    def properties(self):
        return MuranoObjectInterface.DataInterface(self)

    @property
    def name(self):
        return self.object.name

    @property
    def extension(self):
        return self.object.extension

    def cast(self, murano_class, version_spec=None):
        return MuranoObjectInterface.create(
            helpers.cast(
                self.object, murano_class,
                version_spec or helpers.get_type()))

    def is_instance_of(self, murano_class, version_spec=None):
        return helpers.is_instance_of(
            self.object, murano_class,
            version_spec or helpers.get_type())

    def ancestors(self):
        return self.type.ancestors()

    def __getitem__(self, item):
        context = helpers.get_context()
        return to_mutable(
            self.object.get_property(item, context),
            helpers.get_yaql_engine(context))

    def __setitem__(self, key, value):
        context = helpers.get_context()
        value = helpers.evaluate(value, context)
        self.object.set_property(key, value, context)

    def __call__(self):
        return MuranoObjectInterface.CallInterface(self)

    def __repr__(self):
        return '<{0}>'.format(repr(self.object))

    def __eq__(self, other):
        if isinstance(other, MuranoObjectInterface):
            return self.object == other.object
        else:
            return False

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

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

class Interfaces(object):
    def __init__(self, mpl_object):
        self.__object = mpl_object

    def yaql(self, receiver=utils.NO_VALUE):
        return yaql_interface.YaqlInterface(
            helpers.get_context(), helpers.get_yaql_engine(), receiver)

    def this(self):
        return self.methods(self.__object)

    def methods(self, mpl_object):
        return MuranoObjectInterface.create(mpl_object)

    @property
    def execution_session(self):
        return helpers.get_execution_session()

    @property
    def caller(self):
        caller_context = helpers.get_caller_context()
        if caller_context is None:
            return None
        return get_this(caller_context)

    @property
    def attributes(self):
        executor = helpers.get_executor()
        return executor.attribute_store

    @property
    def class_config(self):
        return self.__object.type.package.get_class_config(
            self.__object.type.name)

    @property
    def package_loader(self):
        return helpers.get_package_loader()

class NativeInstruction(object):
    def __init__(self, instruction, location):
        self.instruction = instruction
        self.source_file_position = location

    def __str__(self):
        return self.instruction

def to_mutable(obj, yaql_engine=None):
    if yaql_engine is None:
        yaql_engine = helpers.get_yaql_engine()

    def converter(value, limit_func, engine, rec):
        if isinstance(value, dsl_types.MuranoObject):
            return MuranoObjectInterface.create(value)
        else:
            return utils.convert_output_data(value, limit_func, engine, rec)

    def limiter(it):
        return utils.limit_iterable(it, CONF.murano.dsl_iterators_limit)

    return converter(obj, limiter, yaql_engine, converter)

def meta(type_name, value):
    def wrapper(func):
        fd = specs.get_function_definition(func)
        mpl_meta = fd.meta.get(constants.META_MPL_META, [])
        mpl_meta.append({type_name: value})
        specs.meta(type_name, mpl_meta)(func)
    return wrapper

def get_this(context=None):
    this = helpers.get_this(context)
    return MuranoObjectInterface.create(this)

def get_execution_session():
    return helpers.get_execution_session()

def spawn(func, *args, **kwargs):
    context = helpers.get_context()
    object_store = helpers.get_object_store()

    def wrapper():
        with helpers.with_object_store(object_store):
            with helpers.contextual(context):
                return func(*args, **kwargs)

    return eventlet.spawn(wrapper)

def new(properties, owner=None, type=None):
    context = helpers.get_context()
    return helpers.get_object_store().load(
        properties, owner, type or get_this(context).type, context=context)


text:
angular.module('os.common.import.addctrl', ['os.common.import.importjob'])
  .controller('ImportObjectCtrl', function(
    $rootScope, $scope, $sce, $state, importDetail,
    Form, ImportJob, Alerts, Util, SettingUtil) {

    var maxTxnSize = undefined;

    function init() {
      $scope.importDetail = importDetail;
      $scope.importJob = new ImportJob({
        objectType: importDetail.objectType,
        importType: importDetail.importType || 'CREATE',
        csvType: importDetail.csvType || 'SINGLE_ROW_PER_OBJ',
        dateFormat: $rootScope.global.shortDateFmt,
        timeFormat: $rootScope.global.timeFmt,
        inputFileId: undefined,
        fieldSeparator: importDetail.objectType && importDetail.objectType.fieldSeparator,
        objectParams: importDetail.objectParams || {}
      });

      $scope.importJobsFileUrl = $sce.trustAsResourceUrl(ImportJob.url() + 'input-file');
      $scope.inputFileTmplUrl  = getInputTmplUrl($scope.importJob);
      $scope.fileImporter = {};
      $scope.submitting = false;

      if (importDetail.types && importDetail.types.length > 0) {
        $scope.onTypeSelect(importDetail.types[0]);
      }
    }

    function getInputTmplUrl(importJob) {
      var url = ImportJob.url() + 'input-file-template?' + getQueryParams(importJob);
      return $sce.trustAsResourceUrl(url);
    }

    function getQueryParams(importJob) {
      var qs = 'schema=' + importJob.objectType;
      angular.forEach(importJob.objectParams,
        function(value, key) {
          qs += '&' + key + '=' + value;
        }
      );

      return qs;
    }

    function handleTxnSizeExceeded(resp, fileId) {
      if (maxTxnSize == undefined) {
        SettingUtil.getSetting('common', 'import_max_records_per_txn').then(
          function(setting) {
            maxTxnSize = setting.value;
            warnTxnSizeExceeded(resp, fileId);
          }
        );
      } else {
        warnTxnSizeExceeded(resp, fileId);
      }
    }

    function warnTxnSizeExceeded(resp, fileId) {
      Util.showConfirm({
        ok: function () {
          submitJob(fileId, false);
        },

        title: "common.warning",
        isWarning: true,
        confirmMsg: "bulk_imports.txn_size_exceeded",
        input: { maxTxnSize: maxTxnSize, inputRecsCount: resp.totalRecords }
      });
    }

    function submitJob(fileId, atomic) {
      $scope.submitting = true;
      $scope.importJob.inputFileId = fileId;
      $scope.importJob.atomic = atomic;
      $scope.importJob.$saveOrUpdate().then(
        function(resp) {
          if (resp.status == 'TXN_SIZE_EXCEEDED') {
            $scope.submitting = false;
            handleTxnSizeExceeded(resp, fileId);
          } else {
            Alerts.success('bulk_imports.job_submitted', resp);
            $state.go(importDetail.onSuccess.state, importDetail.onSuccess.params);
          }
        },

        function(err) {
          $scope.submitting = false;
        }
      );
    }

    $scope.import = function() {
      $scope.submitting = true;
      $scope.fileImporter.submit().then(
        function(resp) {
          submitJob(resp.fileId, true);
        },

        function() {
          $scope.submitting = false;
        }
      );
    };

    $scope.onTypeSelect = function(objectType) {
      $scope.importDetail.objectType = objectType.type;
      $scope.importDetail.showImportType = objectType.showImportType;
      $scope.importDetail.showUpsert = objectType.showUpsert;
      $scope.importDetail.importType = objectType.importType;

      var importJob            = $scope.importJob;
      importJob.objectType     = objectType.type;
      importJob.importType     = objectType.importType || 'CREATE',
      importJob.csvType        = objectType.csvType || 'SINGLE_ROW_PER_OBJ',
      importJob.fieldSeparator = objectType.fieldSeparator;
      importJob.objectParams   = objectType.params;

      $scope.inputFileTmplUrl  = getInputTmplUrl(importJob);
    };

    $scope.onEntitySelect = function() {
      $scope.importJob.objectParams.entityId = importDetail.objectParams.entityId;
      $scope.inputFileTmplUrl = getInputTmplUrl($scope.importJob);
    }

    $scope.searchEntities = function(searchTerm) {
      importDetail.entitiesFn(searchTerm).then(
        function(entities) {
          importDetail.entities = entities;
        }
      );
    }

    init();
  });


text:
require 'remote_resource/attribute_key'

module RemoteResource
  # A value object representing an attribute defined in
  # RemoteResource::Base. An AttributeSpecification contains the
  # attributes' method name, its resource, and its API client that is used for
  # lookup. It also calculates its `key` which is used to lookup its value in
  # storage.
  #
  # scope is evaluated outside of this object and should remain unchanged
  # throughout its life cycle. scope is used in building the attribute's key and
  # its equality. target_object on the other hand is just a reference to the
  # object that scope was evaluated on. It may change throughout the attribute's
  # life cycle and is not used in determining equality.
  class AttributeSpecification
    attr_reader :name, :base_class
    delegate :client, :with_error_handling, to: :@base_class

    def initialize(name, base_class)
      @name = name
      @base_class = base_class
    end
    alias_method :method, :name

    def to_hash
      {
        name: @name,
        resource: resource_name,
        base_class: @base_class.class.symbol_name,
        location: location
      }
    end

    def resource_name
      @base_class.class.attributes[@name]
    end

    def resource(resource_client = nil)
      @base_class.send(:resource, resource_name, resource_client)
    end

    def location
      "#{@base_class.class.name}##{@name}"
    end

    def key
      @key ||= AttributeKey.new(@base_class.class.underscore, resource_name,
                                @base_class.scope, @name)
    end
  end
end


text:
"""Provides campaign object."""

from __future__ import absolute_import
from ..entity import Entity

class Campaign(Entity):
    """docstring for Campaign.

    When creating a new campaign, "zone_name" must be """
    collection = 'campaigns'
    resource = 'campaign'
    _relations = {
        'advertiser', 'ad_server', 'currency', 'merit_pixel', 'time_zone',
    }
    _conv = Entity._enum({'every', 'one', 'variable'}, 'variable')
    _freq_ints = Entity._enum({'hour', 'day', 'week', 'month',
                               'not-applicable'}, 'not-applicable')
    _freq_types = Entity._enum({'even', 'asap', 'no-limit'}, 'no-limit')
    _goal_cats = Entity._enum({'audience', 'engagement', 'response'}, None)
    _goal_types = Entity._enum({'spend', 'reach', 'cpc', 'cpe', 'cpa', 'roi'},
                               None)
    _serv_types = Entity._enum({'SELF', 'MANAGED'}, 'SELF')
    _pull = {
        'ad_server_fee': float,
        'ad_server_id': int,
        'ad_server_password': None,
        'ad_server_username': None,
        'advertiser_id': int,
        'agency_fee_pct': float,
        'conversion_type': None,
        'conversion_variable_minutes': int,
        'created_on': Entity._strpt,
        'currency_code': None,
        'dcs_data_is_campaign_level': Entity._int_to_bool,
        'end_date': Entity._strpt,
        'frequency_amount': int,
        'frequency_interval': None,
        'frequency_type': None,
        'goal_alert': float,
        'goal_category': None,
        'goal_type': None,
        'goal_value': float,
        'has_custom_attribution': Entity._int_to_bool,
        'id': int,
        'io_name': None,
        'io_reference_num': None,
        'initial_start_date': Entity._strpt,
        'margin_pct': float,
        'merit_pixel_id': int,
        'name': None,
        'pacing_alert': float,
        'pc_window_minutes': int,
        'pv_pct': float,
        'pv_window_minutes': int,
        'service_type': None,
        'spend_cap_amount': float,
        'spend_cap_automatic': Entity._int_to_bool,
        'spend_cap_enabled': Entity._int_to_bool,
        'start_date': Entity._strpt,
        'status': Entity._int_to_bool,
        'total_budget': float,
        'updated_on': Entity._strpt,
        'use_default_ad_server': Entity._int_to_bool,
        'use_mm_freq': Entity._int_to_bool,
        'version': int,
        'zone_name': None,
    }
    _push = _pull.copy()
    _push.update({
        'conversion_type': _conv,
        'dcs_data_is_campaign_level': int,
        'end_date': Entity._strft,
        'frequency_interval': _freq_ints,
        'frequency_type': _freq_types,
        'goal_category': _goal_cats,
        'goal_type': _goal_types,
        'has_custom_attribution': int,
        'initial_start_date': Entity._strft,
        'service_type': _serv_types,
        'spend_cap_automatic': int,
        'spend_cap_enabled': int,
        'start_date': Entity._strft,
        'status': int,
        'use_default_ad_server': int,
        'use_mm_freq': int,
    })

    def __init__(self, session, properties=None, **kwargs):
        super(Campaign, self).__init__(session, properties, **kwargs)


text:
'use strict';

import { Logging } from './logging.browser.js';

export function logToConsole(options) {
    return new Logging(options);
}


text:
/*
 * Debug statistics of the PCA200 driver
 */
struct istats {
	uint32_t	cmd_queue_full;
	uint32_t	get_stat_errors;
	uint32_t	clr_stat_errors;
	uint32_t	get_prom_errors;
	uint32_t	suni_reg_errors;
	uint32_t	tx_queue_full;
	uint32_t	tx_queue_almost_full;
	uint32_t	tx_pdu2big;
	uint32_t	tx_too_many_segs;
	uint32_t	tx_retry;
	uint32_t	fix_empty;
	uint32_t	fix_addr_copy;
	uint32_t	fix_addr_noext;
	uint32_t	fix_addr_ext;
	uint32_t	fix_len_noext;
	uint32_t	fix_len_copy;
	uint32_t	fix_len;
	uint32_t	rx_badvc;
	uint32_t	rx_closed;
};

/*
 * Addresses on the on-board RAM are expressed as offsets to the
 * start of that RAM.
 */
typedef uint32_t cardoff_t;

/*
 * The card uses a number of queues for communication with the host.
 * Parts of the queue are located on the card (pointers to the status
 * word and the ioblk and the command blocks), the rest in host memory.
 * Each of these queues forms a ring, where the head and tail pointers are
 * managed * either by the card or the host. For the receive queue the
 * head is managed by the card (and not used altogether by the host) and the
 * tail by the host - for all other queues its the other way around.
 * The host resident parts of the queue entries contain pointers to
 * the host resident status and the host resident ioblk (the latter not for
 * the command queue) as well as DMA addresses for supply to the card.
 */
struct fqelem {
	cardoff_t	card;		/* corresponding element on card */
	bus_addr_t	card_ioblk;	/* ioblk address to supply to card */
	volatile uint32_t *statp;		/* host status pointer */
	void		*ioblk;		/* host ioblk (not for commands) */
};

struct fqueue {
	struct fqelem	*chunk;		/* pointer to the element array */
	int		head;		/* queue head */
	int		tail;		/* queue tail */
};

/*
 * Queue manipulation macros
 */
#define	NEXT_QUEUE_ENTRY(HEAD,LEN) ((HEAD) = ((HEAD) + 1) % LEN)
#define	GET_QUEUE(Q,TYPE,IDX)    (&((TYPE *)(Q).chunk)[(IDX)])

/*
 * Now define structures for the different queues. Each of these structures
 * must start with a struct fqelem.
 */
struct txqueue {		/* transmit queue element */
	struct fqelem	q;
	struct mbuf	*m;	/* the chain we are transmitting */
	bus_dmamap_t	map;	/* map for the packet */
};

struct rxqueue {		/* receive queue element */
	struct fqelem	q;
};

struct supqueue {		/* supply queue element */
	struct fqelem	q;
};

struct cmdqueue;
struct fatm_softc;

typedef void (*completion_cb)(struct fatm_softc *, struct cmdqueue *);

struct cmdqueue {		/* command queue element */
	struct fqelem	q;
	completion_cb	cb;	/* call on command completion */
	int		error;	/* set if error occured */
};

/*
 * Card-DMA-able memory is managed by means of the bus_dma* functions.
 * To allocate a chunk of memory with a specific size and alignment one
 * has to:
 *	1. create a DMA tag
 *	2. allocate the memory
 *	3. load the memory into a map.
 * This finally gives the physical address that can be given to the card.
 * The card can DMA the entire 32-bit space without boundaries. We assume,
 * that all the allocations can be mapped in one contiguous segment. This
 * may be wrong in the future if we have more than 32 bit addresses.
 * Allocation is done at attach time and managed by the following structure.
 *
 * This could be done easier with the NetBSD bus_dma* functions. They appear
 * to be more useful and consistent.
 */
struct fatm_mem {
	u_int		size;		/* size */
	u_int		align;		/* alignment */
	bus_dma_tag_t	dmat;		/* DMA tag */
	void 		*mem;		/* memory block */
	bus_addr_t	paddr;		/* pysical address */
	bus_dmamap_t	map;		/* map */
};

/*
 * Each of these structures describes one receive buffer while the buffer
 * is on the card or in the receive return queue. These structures are
 * allocated at initialisation time together with the DMA maps. The handle that
 * is given to the card is the index into the array of these structures.
 */
struct rbuf {
	struct mbuf	*m;	/* the mbuf while we are on the card */
	bus_dmamap_t	map;	/* the map */
	LIST_ENTRY(rbuf) link;	/* the free list link */
};
LIST_HEAD(rbuf_list, rbuf);

/*
 * The driver maintains a list of all open VCCs. Because we
 * use only VPI=0 and a maximum VCI of 1024, the list is rather an array
 * than a list. We also store the atm pseudoheader flags here and the
 * rxhand (aka. protocol block).
 */
struct card_vcc {
	struct atmio_vcc param;		/* traffic parameters */
	void		*rxhand;
	u_int		vflags;
	uint32_t	ipackets;
	uint32_t	opackets;
	uint32_t	ibytes;
	uint32_t	obytes;
};

#define	FATM_VCC_OPEN		0x00010000	/* is open */
#define	FATM_VCC_TRY_OPEN	0x00020000	/* is currently opening */
#define	FATM_VCC_TRY_CLOSE	0x00040000	/* is currently closing */
#define	FATM_VCC_BUSY		0x00070000	/* one of the above */
#define	FATM_VCC_REOPEN		0x00080000	/* reopening during init */

/*
 * Finally the softc structure
 */
struct fatm_softc {
	struct ifnet	*ifp;		/* common part */
	struct mtx	mtx;		/* lock this structure */
	struct ifmedia	media;		/* media */
	struct callout	watchdog_timer;

	int		init_state;	/* initialisation step */
	int		memid;		/* resource id for card memory */
	struct resource *memres;	/* resource for card memory */
	bus_space_handle_t memh;	/* handle for card memory */
	bus_space_tag_t	memt;		/* tag for card memory */
	int		irqid;		/* resource id for interrupt */
	struct resource *irqres;	/* resource for interrupt */
	void		*ih;		/* interrupt handler */

	bus_dma_tag_t	parent_dmat;	/* parent DMA tag */
	struct fatm_mem	stat_mem;	/* memory for status blocks */
	struct fatm_mem	txq_mem;	/* TX descriptor queue */
	struct fatm_mem	rxq_mem;	/* RX descriptor queue */
	struct fatm_mem	s1q_mem;	/* Small buffer 1 queue */
	struct fatm_mem	l1q_mem;	/* Large buffer 1 queue */
	struct fatm_mem	prom_mem;	/* PROM memory */

	struct fqueue	txqueue;	/* transmission queue */
	struct fqueue	rxqueue;	/* receive queue */
	struct fqueue	s1queue;	/* SMALL S1 queue */
	struct fqueue	l1queue;	/* LARGE S1 queue */
	struct fqueue	cmdqueue;	/* command queue */

	/* fields for access to the SUNI registers */
	struct fatm_mem	reg_mem;	/* DMAable memory for readregs */
	struct cv	cv_regs;	/* to serialize access to reg_mem */

	/* fields for access to statistics */
	struct fatm_mem	sadi_mem;	/* sadistics memory */
	struct cv	cv_stat;	/* to serialize access to sadi_mem */

	u_int		flags;
#define	FATM_STAT_INUSE	0x0001
#define	FATM_REGS_INUSE	0x0002
	u_int		txcnt;		/* number of used transmit desc */
	int		retry_tx;	/* keep mbufs in queue if full */

	struct card_vcc	**vccs;		/* table of vccs */
	int		open_vccs;	/* number of vccs in use */
	int		small_cnt;	/* number of buffers owned by card */
	int		large_cnt;	/* number of buffers owned by card */
	uma_zone_t	vcc_zone;	/* allocator for VCCs */

	/* receiving */
	struct rbuf	*rbufs;		/* rbuf array */
	struct rbuf_list rbuf_free;	/* free rbufs list */
	struct rbuf_list rbuf_used;	/* used rbufs list */
	u_int		rbuf_total;	/* total number of buffs */
	bus_dma_tag_t	rbuf_tag;	/* tag for rbuf mapping */

	/* transmission */
	bus_dma_tag_t	tx_tag;		/* transmission tag */

	uint32_t	heartbeat;	/* last heartbeat */
	u_int		stop_cnt;	/* how many times checked */

	struct istats	istats;		/* internal statistics */

	/* SUNI state */
	struct utopia	utopia;

	/* sysctl support */
	struct sysctl_ctx_list sysctl_ctx;
	struct sysctl_oid *sysctl_tree;

#ifdef FATM_DEBUG
	/* debugging */
	u_int		debug;
#endif
};

#ifndef FATM_DEBUG
#define	FATM_LOCK(SC)		mtx_lock(&(SC)->mtx)
#define	FATM_UNLOCK(SC)		mtx_unlock(&(SC)->mtx)
#else
#define	FATM_LOCK(SC)	do {					\
	DBG(SC, LOCK, ("locking in line %d", __LINE__));	\
	mtx_lock(&(SC)->mtx);					\
    } while (0)
#define	FATM_UNLOCK(SC)	do {					\
	DBG(SC, LOCK, ("unlocking in line %d", __LINE__));	\
	mtx_unlock(&(SC)->mtx);					\
    } while (0)
#endif
#define	FATM_CHECKLOCK(SC)	mtx_assert(&sc->mtx, MA_OWNED)

/*
 * Macros to access host memory fields that are also access by the card.
 * These fields need to little-endian always.
 */
#define	H_GETSTAT(STATP)	(le32toh(*(STATP)))
#define	H_SETSTAT(STATP, S)	do { *(STATP) = htole32(S); } while (0)
#define	H_SETDESC(DESC, D)	do { (DESC) = htole32(D); } while (0)

#ifdef notyet
#define	H_SYNCSTAT_POSTREAD(SC, P)					\
	bus_dmamap_sync_size((SC)->stat_mem.dmat,			\
	    (SC)->stat_mem.map,						\
	    (volatile char *)(P) - (volatile char *)(SC)->stat_mem.mem,	\
	    sizeof(volatile uint32_t), BUS_DMASYNC_POSTREAD)

#define	H_SYNCSTAT_PREWRITE(SC, P)					\
	bus_dmamap_sync_size((SC)->stat_mem.dmat,			\
	    (SC)->stat_mem.map,						\
	    (volatile char *)(P) - (volatile char *)(SC)->stat_mem.mem,	\
	    sizeof(volatile uint32_t), BUS_DMASYNC_PREWRITE)

#define	H_SYNCQ_PREWRITE(M, P, SZ)					\
	bus_dmamap_sync_size((M)->dmat, (M)->map,			\
	    (volatile char *)(P) - (volatile char *)(M)->mem, (SZ),	\
	    BUS_DMASYNC_PREWRITE)

#define	H_SYNCQ_POSTREAD(M, P, SZ)					\
	bus_dmamap_sync_size((M)->dmat, (M)->map,			\
	    (volatile char *)(P) - (volatile char *)(M)->mem, (SZ),	\
	    BUS_DMASYNC_POSTREAD)
#else
#define	H_SYNCSTAT_POSTREAD(SC, P)	do { } while (0)
#define	H_SYNCSTAT_PREWRITE(SC, P)	do { } while (0)
#define	H_SYNCQ_PREWRITE(M, P, SZ)	do { } while (0)
#define	H_SYNCQ_POSTREAD(M, P, SZ)	do { } while (0)
#endif

/*
 * Macros to manipulate VPVCs
 */
#define	MKVPVC(VPI,VCI)	(((VPI) << 16) | (VCI))
#define	GETVPI(VPVC)		(((VPVC) >> 16) & 0xff)
#define	GETVCI(VPVC)		((VPVC) & 0xffff)

/*
 * These macros encapsulate the bus_space functions for better readabiliy.
 */
#define	WRITE4(SC, OFF, VAL) bus_space_write_4(SC->memt, SC->memh, OFF, VAL)
#define	WRITE1(SC, OFF, VAL) bus_space_write_1(SC->memt, SC->memh, OFF, VAL)

#define	READ4(SC, OFF) bus_space_read_4(SC->memt, SC->memh, OFF)
#define	READ1(SC, OFF) bus_space_read_1(SC->memt, SC->memh, OFF)

#define	BARRIER_R(SC) \
	bus_space_barrier(SC->memt, SC->memh, 0, FATMO_END, \
	    BUS_SPACE_BARRIER_READ)
#define	BARRIER_W(SC) \
	bus_space_barrier(SC->memt, SC->memh, 0, FATMO_END, \
	    BUS_SPACE_BARRIER_WRITE)
#define	BARRIER_RW(SC) \
	bus_space_barrier(SC->memt, SC->memh, 0, FATMO_END, \
	    BUS_SPACE_BARRIER_WRITE|BUS_SPACE_BARRIER_READ)

#ifdef FATM_DEBUG
#define	DBG(SC, FL, PRINT) do {						\
	if ((SC)->debug & DBG_##FL) { 					\
		if_printf(&(SC)->ifatm.ifnet, "%s: ", __func__);	\
		printf PRINT;						\
		printf("\n");						\
	}								\
    } while (0)
#define	DBGC(SC, FL, PRINT) do {					\
	if ((SC)->debug & DBG_##FL) 					\
		printf PRINT;						\
    } while (0)

enum {
	DBG_RCV		= 0x0001,
	DBG_XMIT	= 0x0002,
	DBG_VCC		= 0x0004,
	DBG_IOCTL	= 0x0008,
	DBG_ATTACH	= 0x0010,
	DBG_INIT	= 0x0020,
	DBG_DMA		= 0x0040,
	DBG_BEAT	= 0x0080,
	DBG_UART	= 0x0100,
	DBG_LOCK	= 0x0200,

	DBG_ALL		= 0xffff
};

#else
#define	DBG(SC, FL, PRINT)
#define	DBGC(SC, FL, PRINT)
#endif

/*
 * Configuration.
 *
 * This section contains tunable parameters and dependend defines.
 */
#define	FATM_CMD_QLEN		16		/* command queue length */
#ifndef TEST_DMA_SYNC
#define	FATM_TX_QLEN		128		/* transmit queue length */
#define	FATM_RX_QLEN		64		/* receive queue length */
#else
#define	FATM_TX_QLEN		8		/* transmit queue length */
#define	FATM_RX_QLEN		8		/* receive queue length */
#endif

#define	SMALL_SUPPLY_QLEN	16
#define	SMALL_POOL_SIZE		256
#define	SMALL_SUPPLY_BLKSIZE	8

#define	LARGE_SUPPLY_QLEN	16
#define	LARGE_POOL_SIZE		128
#define	LARGE_SUPPLY_BLKSIZE	8


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('upvote.statechip.StateChipHelpDialogController');

upvote.statechip.StateChipHelpDialogController = class {
  /**
   * @param {!md.$panel.MdPanelRef} mdPanelRef
   * @ngInject
   */
  constructor(mdPanelRef) {
    this.mdPanelRef_ = mdPanelRef;
  }

  /**
   * Close the help dialog.
   * @export
   */
  closeDialog() {
    this.mdPanelRef_ && this.mdPanelRef_.close();
  }
};


text:
{{title}} List

        <button type="button" class="btn btn-primary btn-xs" (click)="navigateToImport()" style="float:right; margin-right:6px;">
           Import
        </button>
        <button type="button" class="btn btn-primary btn-xs" (click)="dt.exportCSV()" style="float:right; margin-right:6px;">
           Export
        </button>
        <button type="button" class="btn btn-primary btn-xs" (click)="navigateToForm(0)" style="float:right; margin-right:6px;">
           Add
        </button>

      <ng-template let-data="rowData" pTemplate="body">

      </ng-template>


text:
require 'ffi_yajl'
require 'chef_zero/rest_base'

module ChefZero
  module Endpoints
    module OrganizationUserBase

      def self.get(obj, request, &block)
        result = obj.list_data(request).map(&block)
        obj.json_response(200, result)
      end

      def self.post(obj, request, key)
        json = FFI_Yajl::Parser.parse(request.body, :create_additions => false)
        username = json[key]
        orgname = request.rest_path[1]
        id = "#{username}-#{orgname}"

        if obj.exists_data?(request, [ 'organizations', orgname, 'users', username ])
          raise RestErrorResponse.new(409, "User #{username} is already in organization #{orgname}")
        end

        obj.create_data(request, request.rest_path, username, '{}')
        obj.json_response(201, { "uri" => obj.build_uri(request.base_uri, request.rest_path + [ id ]) })
      end

    end
  end
end


text:
<?php

namespace App\Http\Middleware;

use App\Project\Eloquent\Project;
use App\Acl\Acl;

use Closure;
use App\Sentinel\Sentinel;

class Privilege
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $permission)
    {
        // global permission check
        if ($permission === 'sys_admin')
        {
            if (! $this->globalCheck('sys_admin'))
            {
                return Response()->json(['ecode' => -10002, 'emsg' => 'permission denied.']);
            }
        }
        else if ($permission === 'view_project')
        {
            if ($request->isMethod('get'))
            {
                if (! $this->projectCheck($request, 'view_project'))
                {
                    return Response()->json(['ecode' => -10002, 'emsg' => 'permission denied.']);
                }
            }
        }
        // project permission check
        else
        {
            if (! $this->projectCheck($request, $permission))
            {
                return Response()->json(['ecode' => -10002, 'emsg' => 'permission denied.']);
            }
        }

        return $next($request);
    }

    /**
     * Handle an incoming request for global.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function globalCheck($permission)
    {
        return Sentinel::hasAccess($permission);

        //if ($permission == 'manage_user' && $request->isMethod('put'))
        //{
        //    if ($user->id == $request->id)
        //    {
        //        return true;
        //    }
        //}
        //else if ($permission == 'manage_project' && $request->isMethod('put'))
        //{
        //    $principal = Project::find($request->id)->first()->principal;
        //    if ($principal == $user->id)
        //    {
        //        return true;
        //    }
        //}
    }

    /**
     * Handle an incoming request for project.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function projectCheck($request, $permission)
    {
        $project_key = $request->project_key;
        if ($project_key === '$_sys_$')
        {
            return Sentinel::hasAccess('sys_admin');
        }

        $user = Sentinel::getUser();
        $isAllowed = Acl::isAllowed($user->id, $permission, $project_key);
        if (!$isAllowed)
        {
            if ($permission === 'manage_project' || $permission === 'view_project')
            {
                if ($user->email === 'admin@action.view')
                {
                     return true;
                }

                $project = Project::where('key', $project_key)->first();
                if ($project && isset($project->principal) && isset($project->principal['id']) && $project->principal['id'] === $user->id)
                {
                    return true;
                }
            }
        }
        return $isAllowed;
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic

    Friend Class Analyzer

        ''' <summary>
        ''' Analyzes method body for error conditions such as definite assignments, unreachable code etc...
        '''
        ''' This analysis is done when doing the full compile or when responding to GetCompileDiagnostics.
        ''' This method assume that the trees are already bound and will not do any rewriting/lowering
        ''' It is possible and common for this analysis to be done in the presence of errors.
        ''' </summary>
        Friend Shared Sub AnalyzeMethodBody(method As MethodSymbol,
                                            body As BoundBlock,
                                            diagnostics As DiagnosticBag)

            Debug.Assert(diagnostics IsNot Nothing)

            Dim diagBag As DiagnosticBag = diagnostics

            If method.IsImplicitlyDeclared AndAlso method.AssociatedSymbol IsNot Nothing AndAlso
               method.AssociatedSymbol.IsMyGroupCollectionProperty Then
                diagBag = DiagnosticBag.GetInstance()
            End If

            FlowAnalysisPass.Analyze(method, body, diagBag)

            ' the ForLoopVerification only just produces diagnostics. This should be done even if the
            ' tree already has diagnostics
            ForLoopVerification.VerifyForLoops(body, diagBag)

            If diagBag IsNot diagnostics Then
                DirectCast(method.AssociatedSymbol, SynthesizedMyGroupCollectionPropertySymbol).RelocateDiagnostics(diagBag, diagnostics)
                diagBag.Free()
            End If
        End Sub
    End Class
End Namespace


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>GW2NET.Newtonsoft</name>
    </assembly>
    <members>
        <member name="T:GW2NET.Common.Serializers.JsonSerializer`1">
            Provides methods for serializing JSON objects.
            <typeparam name="T">The type that is being serialized.</typeparam>
        </member>
        <member name="F:GW2NET.Common.Serializers.JsonSerializer`1.jsonSerializer">
            Infrastructure. Holds a reference to the Json.NET serializer.
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializer`1.#ctor(Newtonsoft.Json.JsonSerializer)">
            Initializes a new instance of the <see cref="T:GW2NET.Common.Serializers.JsonSerializer`1"/> class.
            <param name="jsonSerializer">The Json.NET serializer.</param>
            <exception cref="T:System.ArgumentNullException">The value of <see cref="F:GW2NET.Common.Serializers.JsonSerializer`1.jsonSerializer"/> is a null reference.</exception>
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializer`1.Deserialize(System.IO.Stream)">
            Converts the input stream to the specified type.
            <param name="stream">The input stream.</param>
            <exception cref="T:GW2NET.Common.SerializationException">A serialization error occurred.</exception>
            <returns>An instance of the specified type.</returns>
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializer`1.Serialize(`0,System.IO.Stream)">
            Converts the specified value to an output stream.
            <param name="value">An instance of the specified type.</param>
            <param name="stream">The output stream.</param>
            <exception cref="T:GW2NET.Common.SerializationException">A serialization error occurred.</exception>
        </member>
        <member name="T:GW2NET.Common.Serializers.JsonSerializerFactory">
            Provides factory methods for the JSON.NET serialization engine.
        </member>
        <member name="F:GW2NET.Common.Serializers.JsonSerializerFactory.jsonSerializerSettings">
            Backing field.
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializerFactory.#ctor">
            Initializes a new instance of the <see cref="T:GW2NET.Common.Serializers.JsonSerializerFactory"/> class.
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializerFactory.#ctor(Newtonsoft.Json.JsonSerializerSettings)">
            Initializes a new instance of the <see cref="T:GW2NET.Common.Serializers.JsonSerializerFactory"/> class.
            <param name="jsonSerializerSettings">The settings to be applied to the <see cref="T:Newtonsoft.Json.JsonSerializer"/>.</param>
        </member>
        <member name="M:GW2NET.Common.Serializers.JsonSerializerFactory.GetSerializer``1">
            Gets a serializer for the specified type.
            <typeparam name="T">The serialization type.</typeparam>
            <returns>The <see cref="T:GW2NET.Common.Serializers.ISerializer`1"/>.</returns>
        </member>
    </members>
</doc>


text:
package org.elasticsearch.xpack.watcher.input.chain;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.core.watcher.input.Input;
import org.elasticsearch.xpack.core.watcher.watch.Payload;
import org.elasticsearch.xpack.watcher.common.http.BasicAuth;
import org.elasticsearch.xpack.watcher.common.http.HttpRequestTemplate;
import org.elasticsearch.xpack.watcher.condition.ScriptCondition;
import org.elasticsearch.xpack.watcher.input.InputFactory;
import org.elasticsearch.xpack.watcher.input.InputRegistry;
import org.elasticsearch.xpack.watcher.input.http.HttpInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInputFactory;
import org.elasticsearch.xpack.watcher.test.WatcherTestUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.loggingAction;
import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.chainInput;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.httpInput;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.simpleInput;
import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule;
import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.interval;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;

public class ChainInputTests extends ESTestCase {

    /* note, first line does not need to be parsed
    "chain" : {
      "inputs" : [
        { "first" : { "simple" : { "foo" : "bar" } } },
        { "second" : { "simple" : { "spam" : "eggs" } } }
      ]
    }
     */
    public void testThatExecutionWorks() throws Exception {
        Map<String, InputFactory<?, ?, ?>> factories = new HashMap<>();
        factories.put("simple", new SimpleInputFactory());

        // hackedy hack...
        InputRegistry inputRegistry = new InputRegistry(factories);
        ChainInputFactory chainInputFactory = new ChainInputFactory(inputRegistry);
        factories.put("chain", chainInputFactory);

        XContentBuilder builder = jsonBuilder().startObject()
            .startArray("inputs")
            .startObject()
            .startObject("first")
            .startObject("simple")
            .field("foo", "bar")
            .endObject()
            .endObject()
            .endObject()
            .startObject()
            .startObject("second")
            .startObject("simple")
            .field("spam", "eggs")
            .endObject()
            .endObject()
            .endObject()
            .endArray()
            .endObject();

        // first pass JSON and check for correct inputs
        XContentParser parser = createParser(builder);
        parser.nextToken();
        ChainInput chainInput = chainInputFactory.parseInput("test", parser);

        assertThat(chainInput.getInputs(), hasSize(2));
        assertThat(chainInput.getInputs().get(0).v1(), is("first"));
        assertThat(chainInput.getInputs().get(0).v2(), instanceOf(SimpleInput.class));
        assertThat(chainInput.getInputs().get(1).v1(), is("second"));
        assertThat(chainInput.getInputs().get(1).v2(), instanceOf(SimpleInput.class));

        // now execute
        ExecutableChainInput executableChainInput = chainInputFactory.createExecutable(chainInput);
        WatchExecutionContext ctx = WatcherTestUtils.createWatchExecutionContext();
        ChainInput.Result result = executableChainInput.execute(ctx, new Payload.Simple());
        Payload payload = result.payload();
        assertThat(payload.data(), hasKey("first"));
        assertThat(payload.data(), hasKey("second"));
        assertThat(payload.data().get("first"), instanceOf(Map.class));
        assertThat(payload.data().get("second"), instanceOf(Map.class));

        // final payload check
        @SuppressWarnings("unchecked")
        Map<String, Object> firstPayload = (Map<String, Object>) payload.data().get("first");
        @SuppressWarnings("unchecked")
        Map<String, Object> secondPayload = (Map<String, Object>) payload.data().get("second");
        assertThat(firstPayload, hasEntry("foo", "bar"));
        assertThat(secondPayload, hasEntry("spam", "eggs"));
    }

    public void testToXContent() throws Exception {
        ChainInput chainedInput = chainInput().add("first", simpleInput("foo", "bar")).add("second", simpleInput("spam", "eggs")).build();

        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        chainedInput.toXContent(builder, ToXContent.EMPTY_PARAMS);

        assertThat(BytesReference.bytes(builder).utf8ToString(), is("""
            {"inputs":[{"first":{"simple":{"foo":"bar"}}},{"second":{"simple":{"spam":"eggs"}}}]}"""));

        // parsing it back as well!
        Map<String, InputFactory<?, ?, ?>> factories = new HashMap<>();
        factories.put("simple", new SimpleInputFactory());

        InputRegistry inputRegistry = new InputRegistry(factories);
        ChainInputFactory chainInputFactory = new ChainInputFactory(inputRegistry);
        factories.put("chain", chainInputFactory);

        XContentParser parser = createParser(builder);
        parser.nextToken();
        ChainInput parsedChainInput = ChainInput.parse("testWatchId", parser, inputRegistry);
        assertThat(parsedChainInput.getInputs(), hasSize(2));
        assertThat(parsedChainInput.getInputs().get(0).v1(), is("first"));
        assertThat(parsedChainInput.getInputs().get(0).v2(), is(instanceOf(SimpleInput.class)));
        assertThat(parsedChainInput.getInputs().get(1).v1(), is("second"));
        assertThat(parsedChainInput.getInputs().get(1).v2(), is(instanceOf(SimpleInput.class)));
    }

    public void testThatWatchSourceBuilderWorksWithChainInput() throws Exception {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);

        HttpInput.Builder httpInputBuilder = httpInput(
            HttpRequestTemplate.builder("theHost", 1234)
                .path("/index/_search")
                .body(Strings.toString(jsonBuilder().startObject().field("size", 1).endObject()))
                .auth(new BasicAuth("test", SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
        );

        ChainInput.Builder chainedInputBuilder = chainInput().add("foo", httpInputBuilder).add("bar", simpleInput("spam", "eggs"));

        watchBuilder().trigger(schedule(interval("5s")))
            .input(chainedInputBuilder)
            .condition(new ScriptCondition(mockScript("ctx.payload.hits.total.value == 1")))
            .addAction("_id", loggingAction("watch [{{ctx.watch_id}}] matched"))
            .toXContent(builder, ToXContent.EMPTY_PARAMS);

        // no exception means all good
    }

    public void testThatSerializationOfFailedInputWorks() throws Exception {
        ChainInput.Result chainedResult = new ChainInput.Result(new ElasticsearchException("foo"));

        XContentBuilder builder = jsonBuilder();
        chainedResult.toXContent(builder, ToXContent.EMPTY_PARAMS);
        assertThat(BytesReference.bytes(builder).utf8ToString(), containsString("\"type\":\"exception\""));
        assertThat(BytesReference.bytes(builder).utf8ToString(), containsString("\"reason\":\"foo\""));
    }

    /* https://github.com/elastic/x-plugins/issues/3736
       the issue here is, that first/second in this setup do not have a guaranteed order, so we have to throw an exception
    {
      "inputs" : [
        {
          "first" : { "simple" : { "foo" : "bar" } },
          "second" : { "simple" : { "spam" : "eggs" } }
        }
      ]
    }
     */
    public void testParsingShouldBeStrictWhenClosingInputs() throws Exception {
        Map<String, InputFactory<?, ?, ?>> factories = new HashMap<>();
        factories.put("simple", new SimpleInputFactory());

        InputRegistry inputRegistry = new InputRegistry(factories);
        ChainInputFactory chainInputFactory = new ChainInputFactory(inputRegistry);
        factories.put("chain", chainInputFactory);

        XContentBuilder builder = jsonBuilder().startObject()
            .startArray("inputs")
            .startObject()
            .startObject("first")
            .startObject("simple")
            .field("foo", "bar")
            .endObject()
            .endObject()
            .startObject("second")
            .startObject("simple")
            .field("spam", "eggs")
            .endObject()
            .endObject()
            .endObject()
            .endArray()
            .endObject();

        XContentParser parser = createParser(builder);
        parser.nextToken();
        ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> chainInputFactory.parseInput("test", parser));
        assertThat(
            e.getMessage(),
            containsString("Expected closing JSON object after parsing input [simple] named [first] in watch [test]")
        );
    }

    /* https://github.com/elastic/x-plugins/issues/3736
       make sure that after the name of a chained input there is always an object
    {
      "inputs" : [
        { "first" : [ { "simple" : { "foo" : "bar" } } ] }
      ]
    }
     */
    public void testParsingShouldBeStrictWhenStartingInputs() throws Exception {
        Map<String, InputFactory<?, ?, ?>> factories = new HashMap<>();
        factories.put("simple", new SimpleInputFactory());

        InputRegistry inputRegistry = new InputRegistry(factories);
        ChainInputFactory chainInputFactory = new ChainInputFactory(inputRegistry);
        factories.put("chain", chainInputFactory);

        XContentBuilder builder = jsonBuilder().startObject()
            .startArray("inputs")
            .startObject()
            .startArray("first")
            .startObject()
            .startObject("simple")
            .field("foo", "bar")
            .endObject()
            .endObject()
            .endArray()
            .endObject()
            .endArray()
            .endObject();

        XContentParser parser = createParser(builder);
        parser.nextToken();
        ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> chainInputFactory.parseInput("test", parser));
        assertThat(e.getMessage(), containsString("Expected starting JSON object after [first] in watch [test]"));
    }

    public void testThatXContentParametersArePassedToInputs() throws Exception {
        ToXContent.Params randomParams = new ToXContent.MapParams(Collections.singletonMap(randomAlphaOfLength(5), randomAlphaOfLength(5)));
        ChainInput chainInput = new ChainInput(Collections.singletonList(Tuple.tuple("whatever", new Input() {
            @Override
            public String type() {
                return "test";
            }

            @Override
            public XContentBuilder toXContent(XContentBuilder builder, Params params) {
                assertThat(params, sameInstance(randomParams));
                return builder;
            }
        })));

        try (XContentBuilder builder = jsonBuilder()) {
            chainInput.toXContent(builder, randomParams);
        }
    }
}


text: google-site-verification: google363ee2bdc5cfbafa.html


text:
package org.anddev.andengine.entity.scene.menu.item;

import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

/**
 * @author Nicolas Gramlich
 * @since 15:44:39 - 07.07.2010
 */
public class AnimatedSpriteMenuItem extends AnimatedSprite implements IMenuItem {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final int mID;

	// ===========================================================
	// Constructors
	// ===========================================================

	public AnimatedSpriteMenuItem(final int pID, final TiledTextureRegion pTiledTextureRegion) {
		super(0, 0, pTiledTextureRegion);
		this.mID = pID;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public int getID() {
		return this.mID;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public void onSelected() {
		/* Nothing. */
	}

	@Override
	public void onUnselected() {
		/* Nothing. */
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}