# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select
        if len(self.qs_args) == 0:
            self.log.warn('No params in request. Must be a bot.')
            return None, False

        def get(key, default=None, from_encoding=None):
            value = self.qs_args.get(key, [default])[0]
            if value and value == b'undefined':
                value = None
            if value is not None:
                if from_encoding:
                    value = value.decode(from_encoding)
                else:
                    value = try_decode(value)
            return value

        visit = None
        kind = get('d')
        if kind == 'e':
            raise RuntimeError('Problem in tracker: "%s"' % get('r'))
        uuid = get('_')
        if uuid and '; ' in uuid:
            uuid = uuid.split('; ')[0]
        platform, browser, version = parse_ua(self.ua)
        if kind == 'c':
            try:
                id = db.execute(
                    select([visits.c.id])
                    .where(visits.c.uuid == uuid)
                    .order_by(desc(visits.c.date))
                ).fetchone()['id']

# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


# Path: pystil/tracking.py
from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select

        if len(self.qs_args) == 0:
            self.log.warn('No params in request. Must be a bot.')
            return None, False

        def get(key, default=None, from_encoding=None):
            value = self.qs_args.get(key, [default])[0]
            if value and value == b'undefined':
                value = None
            if value is not None:
                if from_encoding:
                    value = value.decode(from_encoding)
                else:
                    value = try_decode(value)
            return value

        visit = None
        kind = get('d')
        if kind == 'e':
            raise RuntimeError('Problem in tracker: "%s"' % get('r'))
        uuid = get('_')
        if uuid and '; ' in uuid:
            uuid = uuid.split('; ')[0]
        platform, browser, version = parse_ua(self.ua)
        if kind == 'c':
            try:
                id = db.execute(
                    select([visits.c.id])
                    .where(visits.c.uuid == uuid)
                    .order_by(desc(visits.c.date))
                ).fetchone()['id']

            except: