Example #1
0
def partition_current_users(users):
    ret = {
        'staying': [],
        'leaving': []
    }
    user_stints = [user['stints'] for user in users]
    end_dates = []
    for stints in user_stints:
        if stints != []:
            for stint in stints:
                if stint['end_date'] is not None and stint['type'] == 'retreat':
                    end_dates.append(stint['end_date'])
    end_dates = sorted(list(set(end_dates)))
    end_dates = end_dates[::-1]
    staying_date = datetime.strptime(end_dates[0], "%Y-%m-%d")
    leaving_date = datetime.strptime(end_dates[1], "%Y-%m-%d")
    for u in users:
        # Batchlings have   is_recurser = True,      is_faculty = False
        # Faculty have      is_recurser = ?,         is_faculty = True
        # Residents have    is_recurser = False,     is_faculty = False
        if ((u['is_recurser'] and not u['is_faculty']) or
            (not u['is_faculty'] and not u['is_recurser'] and config.get(config.INCLUDE_RESIDENTS, False)) or
                (u['is_faculty'] and config.get(config.INCLUDE_FACULTY, False))):
            if u['end_date'] == staying_date:
                ret['staying'].append(u)
            elif u['end_date'] == leaving_date:
                ret['leaving'].append(u)
            else:
                pass
    return ret
Example #2
0
def partition_current_users(users):
    ret = {
        'staying': [],
        'leaving': []
    }
    user_stints = [user['stints'] for user in users]
    end_dates = []
    for stints in user_stints:
        if stints != []:
            for stint in stints:
                if stint['end_date'] is not None and stint['type'] == 'retreat':
                    end_dates.append(stint['end_date'])
    end_dates = sorted(list(set(end_dates)))
    end_dates = end_dates[::-1]
    staying_date = datetime.strptime(end_dates[0], "%Y-%m-%d")
    leaving_date = datetime.strptime(end_dates[1], "%Y-%m-%d")
    for u in users:
        # Batchlings have   is_hacker_schooler = True,      is_faculty = False
        # Faculty have      is_hacker_schooler = ?,         is_faculty = True
        # Residents have    is_hacker_schooler = False,     is_faculty = False
        if ((u['is_hacker_schooler'] and not u['is_faculty']) or
            (not u['is_faculty'] and not u['is_hacker_schooler'] and config.get(config.INCLUDE_RESIDENTS, False)) or
            (u['is_faculty'] and config.get(config.INCLUDE_FACULTY, False))):
            if u['end_date'] == staying_date:
                ret['staying'].append(u)
            elif u['end_date'] == leaving_date:
                ret['leaving'].append(u)
            else:
                pass
    return ret
Example #3
0
def getLogger(name, parent=None):
    """ Create a logger with some sane configuration
    Args:
        name (str): name of logger. Should be the name of the file.
        parent (str): name of parent logger to inherit its properties
    """
    if parent:
        # create child logger that inherits properties from father
        logger = logging.getLogger(parent + "." + name)
    else:
        # create parent logger with new properties
        logger = logging.getLogger(name)
        logger.setLevel(logging.DEBUG)
        # create file handler which logs even debug messages
        # fh = logging.FileHandler(config.get("path","log_file"))
        fh = handlers.TimedRotatingFileHandler(config.get("path", "log_file"),
                                               when='midnight')
        fh.setLevel(logging.DEBUG)
        # create formatter and add it to the handler
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(fh)
    return logger
Example #4
0
def flush_expired(max_age=None):
    """Remove items from the cache which are older than `max_age`, which can be a
    `datetime.timedelta` or a number of seconds."""
    if max_age is None:
        max_age = config.get(config.CACHE_TIMEOUT,
                             datetime.timedelta(seconds=60 * 60 * 24))
    elif not isinstance(max_age, datetime.timedelta):
        max_age = datetime.timedelta(seconds=max_age)
    (db.session.query(Cache).filter(
        Cache.last_updated >= (datetime.datetime.now() + max_age)).delete())
    db.session.commit()
Example #5
0
def flush_expired(max_age=None):
    """Remove items from the cache which are older than `max_age`, which can be a
    `datetime.timedelta` or a number of seconds."""
    if max_age is None:
        max_age = config.get(config.CACHE_TIMEOUT, datetime.timedelta(seconds=60 * 60 * 24))
    elif not isinstance(max_age, datetime.timedelta):
        max_age = datetime.timedelta(seconds=max_age)
    (db
     .session
     .query(Cache)
     .filter(Cache.last_updated >= (datetime.datetime.now() + max_age))
     .delete())
    db.session.commit()
Example #6
0
def get(key, max_age=None):
    """Get a value from the cache, provided it is no  older than `max_age`, which
    can be a `datetime.timedelta` or a number of seconds. If the item is not in the
    cache, raises a `NotInCache` exception."""
    if max_age is None:
        max_age = config.get(config.CACHE_TIMEOUT, datetime.timedelta(seconds=60 * 60 * 24))
    elif not isinstance(max_age, datetime.timedelta):
        max_age = datetime.timedelta(seconds=max_age)
    db_row = Cache.query.filter(
        Cache.key == key,
        Cache.last_updated >= (datetime.datetime.now() - max_age)).one_or_none()
    if db_row is None:
        raise NotInCache
    return db_row.value
Example #7
0
## NOTE: depends spatialite dynamic library `libsqlite3-mod-spatialite'
##
## Usage:
##      import spatialite
##      output = spatialite.execute("select HEX(GeomFromText(?));",
##                                  ('POINT(788703.57 4645636.3)',))
## The output is a a tuple of lists. To get the 2nd field from 3rd row just use output[2][1] (0-based index)

import sqlite3.dbapi2 as db

from backend import config

### Constants ###

# full path of sqlite3 database
DB = config.get("path", "geodb")

# full path of libspatialite.so.7
SPATIALPLUGIN = config.get("path", "libspatialite")
# creating/connecting the test_db
con = db.connect(DB, check_same_thread=False)
con.enable_load_extension(True)
con.load_extension(SPATIALPLUGIN)
con.enable_load_extension(False)


def execute(sql, args=()):
    """
        Execute sql using args for sql substitution

        Args:
Example #8
0
def runserver():

    bottle.run(host=config.get("server", "host"),
               port=config.get("server", "port"),
               debug=config.getboolean("server", "debug"))