<commit_before>from django.utils.encoding import force_unicode
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from conf import settings
from django.db.models import BooleanField
from django.utils.translation import ugettext_lazy as _
from django.utils import translation
from django.db import connections
from django.db import transaction, reset_queries

__all__ = [
        'Point', 'Country', 'Region', 'Subregion',
        'City', 'Continente', 'District', 'PostalCode', 'AlternativeName', 'Place' 
]

def get_or_none(classmodel, **kwargs):
    try:
        return classmodel.objects.get(**kwargs)
    except classmodel.DoesNotExist:
        return None

class Place(models.Model):
    name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name")
    slug = models.CharField(max_length=200)
    alt_names = models.ManyToManyField('AlternativeName', blank=True)

    '''nao aparece mais para a interface do usuario'''
    deleted = BooleanField(default=False, verbose_name=_('deleted'))
    '''
    aparece na interface dos usuarios, mas nao participa das operacoes do sistema 
    exemplo: aparecer na busca de autocomplete, enviar newsletter com esse destino
    '''
    active = BooleanField(default=True, verbose_name=_('active'))
    #indica se aquele place eh oriundo da base do geonames
    #a dica eh fazer a carga inicial da base do geonames ai apartir dai
    #todo novo place tem geonames igual a False
    geonames = BooleanField(default=False, verbose_name=_('geonames'))

    objects = models.GeoManager()

    #utilizado para rankear os places, dessa forma em uma 
    #consulta pode-se ordenar os places segundo esse atributo
    ranking = models.IntegerField()

    #class Meta:
    #    abstract = True

    @property
    def subclass(self):
        for place in [City, District, Subregion, Region, Country, Continente]:
            p = get_or_none(place,pk=self.id) 
            if p:
                return p

        return self

    @property
    def hierarchy(self):
        """Get hierarchy, root first"""
        if isinstance(self,Place):
            subclass = self.subclass
        else:
            subclass = self
        list = subclass.parent.hierarchy if subclass.parent else []
        list.append(subclass)
        return list

    def get_absolute_url(self):
        h = self.hierarchy
        h.reverse()
        return "/".join([place.slug for place in h])

    def translated(self, language):
        alts = self.alt_names.filter(
            language__startswith=language[:2], #equiparando idiomas, ISO 639-1 soh possui duas letras
            active=True, 
            deleted=False
        ).order_by('-is_preferred')
        #pega a traducao dando prioridade as is_preferred
        return alts[0] if len(alts)>0 else self

    def __unicode__(self):
        h = self.hierarchy
        h.reverse()
        alt_h=[]
        for p in h:<commit_msg>get_absolute_slug<commit_after>from django.utils.encoding import force_unicode
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from conf import settings
from django.db.models import BooleanField
from django.utils.translation import ugettext_lazy as _
from django.utils import translation
from django.db import connections
from django.db import transaction, reset_queries

__all__ = [
        'Point', 'Country', 'Region', 'Subregion',
        'City', 'Continente', 'District', 'PostalCode', 'AlternativeName', 'Place' 
]

def get_or_none(classmodel, **kwargs):
    try:
        return classmodel.objects.get(**kwargs)
    except classmodel.DoesNotExist:
        return None

class Place(models.Model):
    name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name")
    slug = models.CharField(max_length=200)
    alt_names = models.ManyToManyField('AlternativeName', blank=True)

    '''nao aparece mais para a interface do usuario'''
    deleted = BooleanField(default=False, verbose_name=_('deleted'))
    '''
    aparece na interface dos usuarios, mas nao participa das operacoes do sistema 
    exemplo: aparecer na busca de autocomplete, enviar newsletter com esse destino
    '''
    active = BooleanField(default=True, verbose_name=_('active'))
    #indica se aquele place eh oriundo da base do geonames
    #a dica eh fazer a carga inicial da base do geonames ai apartir dai
    #todo novo place tem geonames igual a False
    geonames = BooleanField(default=False, verbose_name=_('geonames'))

    objects = models.GeoManager()

    #utilizado para rankear os places, dessa forma em uma 
    #consulta pode-se ordenar os places segundo esse atributo
    ranking = models.IntegerField()

    #class Meta:
    #    abstract = True

    @property
    def subclass(self):
        for place in [City, District, Subregion, Region, Country, Continente]:
            p = get_or_none(place,pk=self.id) 
            if p:
                return p

        return self

    @property
    def hierarchy(self):
        """Get hierarchy, root first"""
        if isinstance(self,Place):
            subclass = self.subclass
        else:
            subclass = self
        list = subclass.parent.hierarchy if subclass.parent else []
        list.append(subclass)
        return list

    def get_absolute_url(self):
        h = self.hierarchy
        h.reverse()
        return "/".join([place.slug for place in h])

    def get_absolute_slug(self):
        h = self.hierarchy
        return "-".join([place.slug for place in h])

    def translated(self, language):
        alts = self.alt_names.filter(
            language__startswith=language[:2], #equiparando idiomas, ISO 639-1 soh possui duas letras
            active=True, 
            deleted=False
        ).order_by('-is_preferred')
        #pega a traducao dando prioridade as is_preferred
        return alts[0] if len(alts)>0 else self

    def __unicode__(self):
        h = self.hierarchy
        h.reverse()
        alt_h=[]
        for p in h:
{'fraction_non_alphanumeric': 0.09078816095776522, 'fraction_numerical': 0.004323245759893582, 'mean_word_length': 2.923679060665362, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2079269', 'n_tokens_mistral': 1825, 'n_tokens_neox': 1762, 'n_words': 531}