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

#  Copyright (C) 2016-2017 GEM Foundation

#  OpenQuake is free software: you can redistribute it and/or modify it
#  under the terms of the GNU Affero General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

#  OpenQuake is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

#  You should have received a copy of the GNU Affero General Public License
#  along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import time
import sqlite3
import logging
import threading
import subprocess

from openquake.baselib import config, sap, zeromq as z, workerpool as w
from openquake.baselib.general import socket_ready, detach_process
from openquake.baselib.parallel import safely_call
from openquake.commonlib import logs
from openquake.server.db import actions
from openquake.server import dbapi
from openquake.server import __file__ as server_path

db = dbapi.Db(sqlite3.connect, os.path.expanduser(config.dbserver.file),
              isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES,
              timeout=20)
# NB: I am increasing the timeout from 5 to 20 seconds to see if the random
# OperationalError: "database is locked" disappear in the WebUI tests

ZMQ = os.environ.get(
    'OQ_DISTRIBUTE', config.distribution.oq_distribute) == 'zmq'

DBSERVER_PORT = int(os.environ.get('OQ_DBSERVER_PORT') or config.dbserver.port)

class DbServer(object):
    """
    A server collecting the received commands into a queue
    """
    def __init__(self, db, address, num_workers=5):
        self.db = db
        self.master_host = address[0]
        self.frontend = 'tcp://%s:%s' % address
        self.backend = 'inproc://dbworkers'
        self.num_workers = num_workers
        self.pid = os.getpid()
        self.master = w.WorkerMaster(**config.zworkers)

    def dworker(self, sock):
        # a database worker responding to commands
        for cmd_ in sock:
            cmd, args = cmd_[0], cmd_[1:]
            if cmd == 'getpid':
                sock.send((self.pid, None, None))
                continue
            try:
                func = getattr(actions, cmd)
            except AttributeError:
                sock.send(('Invalid command ' + cmd, ValueError, None))
            else:
                sock.send(safely_call(func, (self.db,) + args))

    def start(self):
        """
        Start database worker threads
        """
        # give a nice name to the process
        w.setproctitle('oq-dbserver')

        dworkers = []
        for _ in range(self.num_workers):
            sock = z.Socket(self.backend, z.zmq.REP, 'connect')
            threading.Thread(target=self.dworker, args=(sock,)).start()
            dworkers.append(sock)
        logging.warn('DB server started with %s on %s, pid %d',
                     sys.executable, self.frontend, self.pid)
        if ZMQ:
            # start task_in->task_out streamer thread
            c = config.zworkers
            threading.Thread(
                target=w.streamer,
                args=(self.master_host, c.task_in_port, c.task_out_port)
            ).start()
            logging.warn('Task streamer started from %s -> %s',
                         c.task_in_port, c.task_out_port)

            # start zworkers and wait a bit for them
            msg = self.master.start()
            logging.warn(msg)
            time.sleep(1)

        # start frontend->backend proxy for the database workers
        try:
            z.zmq.proxy(z.bind(self.frontend, z.zmq.ROUTER),
                        z.bind(self.backend, z.zmq.DEALER))
        except (KeyboardInterrupt, z.zmq.ZMQError):
            for sock in dworkers:
                sock.running = False
            logging.warn('DB server stopped')
        finally:
            self.stop()

    def stop(self):
        """Stop the DbServer and the zworkers if any"""
        if ZMQ:
            logging.warn(self.master.stop())
            z.context.term()
        self.db.close()

def different_paths(path1, path2):
    path1 = os.path.realpath(path1)  # expand symlinks
    path2 = os.path.realpath(path2)  # expand symlinks
    # don't care about the extension (it may be .py or .pyc)
    return os.path.splitext(path1)[0] != os.path.splitext(path2)[0]

def get_status(address=None):
    """
    Check if the DbServer is up.

    :param address: pair (hostname, port)
    :returns: 'running' or 'not-running'
    """
    address = address or (config.dbserver.host, DBSERVER_PORT)
    return 'running' if socket_ready(address) else 'not-running'

def check_foreign():
    """
    Check if we the DbServer is the right one
    """
    if not config.dbserver.multi_user:
        remote_server_path = logs.dbcmd('get_path')
        if different_paths(server_path, remote_server_path):
            return('You are trying to contact a DbServer from another'
                   ' instance (got %s, expected %s)\n'
                   'Check the configuration or stop the foreign'
                   ' DbServer instance') % (remote_server_path, server_path)

def ensure_on():
    """
    Start the DbServer if it is off
    """
    if get_status() == 'not-running':
        if config.dbserver.multi_user:
            sys.exit('Please start the DbServer: '
                     'see the documentation for details')
        # otherwise start the DbServer automatically; NB: I tried to use
        # multiprocessing.Process(target=run_server).start() and apparently
        # it works, but then run-demos.sh hangs after the end of the first
        # calculation, but only if the DbServer is started by oq engine (!?)
        subprocess.Popen([sys.executable, '-m', 'openquake.server.dbserver',
                          '-l', 'INFO'])

        # wait for the dbserver to start
        waiting_seconds = 10
        while get_status() == 'not-running':
            if waiting_seconds == 0:
                sys.exit('The DbServer cannot be started after 10 seconds. '
                         'Please check the configuration')
            time.sleep(1)
            waiting_seconds -= 1

@sap.Script
def run_server(dbpath=os.path.expanduser(config.dbserver.file),
               dbhostport=None, logfile=config.dbserver.log,
               loglevel='WARN'):
    """
    Run the DbServer on the given database file and port. If not given,
    use the settings in openquake.cfg.
    """
    if dbhostport:  # assume a string of the form "dbhost:port"
        dbhost, port = dbhostport.split(':')
        addr = (dbhost, int(port))
    else:
        addr = (config.dbserver.host, DBSERVER_PORT)

    # create the db directory if needed
    dirname = os.path.dirname(dbpath)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    # create and upgrade the db if needed
    db('PRAGMA foreign_keys = ON')  # honor ON DELETE CASCADE
    actions.upgrade_db(db)
    # the line below is needed to work around a very subtle bug of sqlite;
    # we need new connections, see https://github.com/gem/oq-engine/pull/3002
    db.close()

    # configure logging and start the server
    logging.basicConfig(level=getattr(logging, loglevel), filename=logfile)
    DbServer(db, addr).start()  # expects to be killed with CTRL-C

run_server.arg('dbpath', 'dbpath')
run_server.arg('dbhostport', 'dbhost:port')
run_server.arg('logfile', 'log file')
run_server.opt('loglevel', 'WARN or INFO')

if __name__ == '__main__':
    if hasattr(os, 'fork'):
        # needed for https://github.com/gem/oq-engine/issues/3211
        detach_process()
    run_server.callfunc()
<commit_msg>Detach dbserver only in single user mode<commit_after>#  -*- coding: utf-8 -*-
#  vim: tabstop=4 shiftwidth=4 softtabstop=4

#  Copyright (C) 2016-2017 GEM Foundation

#  OpenQuake is free software: you can redistribute it and/or modify it
#  under the terms of the GNU Affero General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

#  OpenQuake is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

#  You should have received a copy of the GNU Affero General Public License
#  along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import time
import sqlite3
import logging
import threading
import subprocess

from openquake.baselib import config, sap, zeromq as z, workerpool as w
from openquake.baselib.general import socket_ready, detach_process
from openquake.baselib.parallel import safely_call
from openquake.commonlib import logs
from openquake.server.db import actions
from openquake.server import dbapi
from openquake.server import __file__ as server_path

db = dbapi.Db(sqlite3.connect, os.path.expanduser(config.dbserver.file),
              isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES,
              timeout=20)
# NB: I am increasing the timeout from 5 to 20 seconds to see if the random
# OperationalError: "database is locked" disappear in the WebUI tests

ZMQ = os.environ.get(
    'OQ_DISTRIBUTE', config.distribution.oq_distribute) == 'zmq'

DBSERVER_PORT = int(os.environ.get('OQ_DBSERVER_PORT') or config.dbserver.port)

class DbServer(object):
    """
    A server collecting the received commands into a queue
    """
    def __init__(self, db, address, num_workers=5):
        self.db = db
        self.master_host = address[0]
        self.frontend = 'tcp://%s:%s' % address
        self.backend = 'inproc://dbworkers'
        self.num_workers = num_workers
        self.pid = os.getpid()
        self.master = w.WorkerMaster(**config.zworkers)

    def dworker(self, sock):
        # a database worker responding to commands
        for cmd_ in sock:
            cmd, args = cmd_[0], cmd_[1:]
            if cmd == 'getpid':
                sock.send((self.pid, None, None))
                continue
            try:
                func = getattr(actions, cmd)
            except AttributeError:
                sock.send(('Invalid command ' + cmd, ValueError, None))
            else:
                sock.send(safely_call(func, (self.db,) + args))

    def start(self):
        """
        Start database worker threads
        """
        # give a nice name to the process
        w.setproctitle('oq-dbserver')

        dworkers = []
        for _ in range(self.num_workers):
            sock = z.Socket(self.backend, z.zmq.REP, 'connect')
            threading.Thread(target=self.dworker, args=(sock,)).start()
            dworkers.append(sock)
        logging.warn('DB server started with %s on %s, pid %d',
                     sys.executable, self.frontend, self.pid)
        if ZMQ:
            # start task_in->task_out streamer thread
            c = config.zworkers
            threading.Thread(
                target=w.streamer,
                args=(self.master_host, c.task_in_port, c.task_out_port)
            ).start()
            logging.warn('Task streamer started from %s -> %s',
                         c.task_in_port, c.task_out_port)

            # start zworkers and wait a bit for them
            msg = self.master.start()
            logging.warn(msg)
            time.sleep(1)

        # start frontend->backend proxy for the database workers
        try:
            z.zmq.proxy(z.bind(self.frontend, z.zmq.ROUTER),
                        z.bind(self.backend, z.zmq.DEALER))
        except (KeyboardInterrupt, z.zmq.ZMQError):
            for sock in dworkers:
                sock.running = False
            logging.warn('DB server stopped')
        finally:
            self.stop()

    def stop(self):
        """Stop the DbServer and the zworkers if any"""
        if ZMQ:
            logging.warn(self.master.stop())
            z.context.term()
        self.db.close()

def different_paths(path1, path2):
    path1 = os.path.realpath(path1)  # expand symlinks
    path2 = os.path.realpath(path2)  # expand symlinks
    # don't care about the extension (it may be .py or .pyc)
    return os.path.splitext(path1)[0] != os.path.splitext(path2)[0]

def get_status(address=None):
    """
    Check if the DbServer is up.

    :param address: pair (hostname, port)
    :returns: 'running' or 'not-running'
    """
    address = address or (config.dbserver.host, DBSERVER_PORT)
    return 'running' if socket_ready(address) else 'not-running'

def check_foreign():
    """
    Check if we the DbServer is the right one
    """
    if not config.dbserver.multi_user:
        remote_server_path = logs.dbcmd('get_path')
        if different_paths(server_path, remote_server_path):
            return('You are trying to contact a DbServer from another'
                   ' instance (got %s, expected %s)\n'
                   'Check the configuration or stop the foreign'
                   ' DbServer instance') % (remote_server_path, server_path)

def ensure_on():
    """
    Start the DbServer if it is off
    """
    if get_status() == 'not-running':
        if config.dbserver.multi_user:
            sys.exit('Please start the DbServer: '
                     'see the documentation for details')
        # otherwise start the DbServer automatically; NB: I tried to use
        # multiprocessing.Process(target=run_server).start() and apparently
        # it works, but then run-demos.sh hangs after the end of the first
        # calculation, but only if the DbServer is started by oq engine (!?)
        subprocess.Popen([sys.executable, '-m', 'openquake.server.dbserver',
                          '-l', 'INFO'])

        # wait for the dbserver to start
        waiting_seconds = 10
        while get_status() == 'not-running':
            if waiting_seconds == 0:
                sys.exit('The DbServer cannot be started after 10 seconds. '
                         'Please check the configuration')
            time.sleep(1)
            waiting_seconds -= 1

@sap.Script
def run_server(dbpath=os.path.expanduser(config.dbserver.file),
               dbhostport=None, logfile=config.dbserver.log,
               loglevel='WARN'):
    """
    Run the DbServer on the given database file and port. If not given,
    use the settings in openquake.cfg.
    """
    if dbhostport:  # assume a string of the form "dbhost:port"
        dbhost, port = dbhostport.split(':')
        addr = (dbhost, int(port))
    else:
        addr = (config.dbserver.host, DBSERVER_PORT)

    # create the db directory if needed
    dirname = os.path.dirname(dbpath)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    # create and upgrade the db if needed
    db('PRAGMA foreign_keys = ON')  # honor ON DELETE CASCADE
    actions.upgrade_db(db)
    # the line below is needed to work around a very subtle bug of sqlite;
    # we need new connections, see https://github.com/gem/oq-engine/pull/3002
    db.close()

    # configure logging and start the server
    logging.basicConfig(level=getattr(logging, loglevel), filename=logfile)
    DbServer(db, addr).start()  # expects to be killed with CTRL-C

run_server.arg('dbpath', 'dbpath')
run_server.arg('dbhostport', 'dbhost:port')
run_server.arg('logfile', 'log file')
run_server.opt('loglevel', 'WARN or INFO')

if __name__ == '__main__':
    if hasattr(os, 'fork') and not config.dbserver.multi_user:
        # needed for https://github.com/gem/oq-engine/issues/3211
        # but only if multi_user = False, otherwise init/supervisor
        # will loose control of the process
        detach_process()
    run_server.callfunc()
<|endoftext|>


<commit_before>#
#  Copyright 2019 The FATE Authors. 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.
#

import copy
import numpy as np

from federatedml.model_base import ModelBase
from federatedml.param.scorecard_param import ScorecardParam
from federatedml.util.consts import FLOAT_ZERO
from federatedml.util import LOGGER

class Scorecard(ModelBase):
    def __init__(self):
        super().__init__()
        self.model_param = ScorecardParam()
        self.metric_name = "scorecard"
        self.metric_namespace = "train"
        self.metric_type = "SCORECARD"

    def _init_model(self, params):
        self.model_param = params
        self.method = params.method
        self.offset = params.offset
        self.factor = params.factor
        self.factor_base = params.factor_base
        self.upper_limit_ratio = params.upper_limit_ratio
        self.lower_limit_value = params.lower_limit_value
        self.need_run = params.need_run

    @staticmethod
    def compute_credit_score(predict_result, offset, factor, factor_base, upper_limit_value, lower_limit_value):
        predict_score = predict_result[2]

        # deal with special predict score values
        if abs(predict_score - 0) <= FLOAT_ZERO and predict_score >= 0:
            credit_score = upper_limit_value
        elif abs(predict_score - 1) <= FLOAT_ZERO and predict_score > 0:
            credit_score = lower_limit_value
        elif predict_score > 1 or predict_score < 0:
            credit_score = -1
        else:
            odds = (1 - predict_score) / predict_score
            credit_score = offset + factor / np.log(factor_base) * np.log(odds)

        # credit score should be within range
        if credit_score > upper_limit_value:
            credit_score = upper_limit_value
        if credit_score < lower_limit_value:
            credit_score = lower_limit_value

        credit_score = round(credit_score, 2)

        return [predict_result[0], predict_result[1], predict_score, credit_score]

    def _set_summary(self):
        formula = f"Score = {self.offset} + {self.factor} / ln({self.factor_base}) * ln(Odds)"
        self.set_summary({"scorecard_compute_formula": formula})
        LOGGER.info(f"Scorecard Computation Formula: {formula}")

    def fit(self, prediction_result):
        LOGGER.info(f"Start Scorecard Transform, method: {self.method}")

        offset, factor, factor_base = self.offset, self.factor, self.factor_base
        if factor_base != 2:
            LOGGER.warning(f"scorecard param 'factor_base' given is {factor_base}, which is not equal to 2.")
        upper_limit_value, lower_limit_value = self.upper_limit_ratio * offset, self.lower_limit_value
        score_result = prediction_result.mapValues(lambda v: Scorecard.compute_credit_score(v, offset, factor,
                                                                                factor_base,
                                                                                upper_limit_value,
                                                                                lower_limit_value))
        result_schema = copy.deepcopy(prediction_result.schema)
        result_schema["header"] = ["label", "predict_result", "predict_score", "credit_score"]
        """
        result_schema = {"header": ["label", "predict_result", "predict_score", "credit_score"],
                         "sid_name": schema.get('sid_name')}
        """
        score_result.schema = result_schema

        self._set_summary()
        LOGGER.info(f"Finish Scorecard Transform!")

        return score_result
<commit_msg>edit scorecard<commit_after>#
#  Copyright 2019 The FATE Authors. 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.
#

import copy
import numpy as np

from federatedml.model_base import ModelBase
from federatedml.param.scorecard_param import ScorecardParam
from federatedml.util.consts import FLOAT_ZERO
from federatedml.util import LOGGER
from federatedml.feature.instance import Instance

class Scorecard(ModelBase):
    def __init__(self):
        super().__init__()
        self.model_param = ScorecardParam()
        self.metric_name = "scorecard"
        self.metric_namespace = "train"
        self.metric_type = "SCORECARD"
        self.use_match_id = False

    def _init_model(self, params):
        self.model_param = params
        self.method = params.method
        self.offset = params.offset
        self.factor = params.factor
        self.factor_base = params.factor_base
        self.upper_limit_ratio = params.upper_limit_ratio
        self.lower_limit_value = params.lower_limit_value
        self.need_run = params.need_run

    @staticmethod
    def compute_credit_score(result, offset, factor, factor_base, upper_limit_value, lower_limit_value,
                             use_match_id=False):
        predict_result = result
        if use_match_id:
            predict_result = result.features
        predict_score = predict_result[2]

        # deal with special predict score values
        if abs(predict_score - 0) <= FLOAT_ZERO and predict_score >= 0:
            credit_score = upper_limit_value
        elif abs(predict_score - 1) <= FLOAT_ZERO and predict_score > 0:
            credit_score = lower_limit_value
        elif predict_score > 1 or predict_score < 0:
            credit_score = -1
        else:
            odds = (1 - predict_score) / predict_score
            credit_score = offset + factor / np.log(factor_base) * np.log(odds)

        # credit score should be within range
        if credit_score > upper_limit_value:
            credit_score = upper_limit_value
        if credit_score < lower_limit_value:
            credit_score = lower_limit_value

        credit_score = round(credit_score, 2)
        if use_match_id:
            credit_result = copy.deepcopy(result)
            credit_result.features = [predict_result[0], predict_result[1], predict_score, credit_score]
        else:
            credit_result = [predict_result[0], predict_result[1], predict_score, credit_score]

        return credit_result

    def _set_summary(self):
        formula = f"Score = {self.offset} + {self.factor} / ln({self.factor_base}) * ln(Odds)"
        self.set_summary({"scorecard_compute_formula": formula})
        LOGGER.info(f"Scorecard Computation Formula: {formula}")

    def fit(self, prediction_result):
        LOGGER.info(f"Start Scorecard Transform, method: {self.method}")

        offset, factor, factor_base = self.offset, self.factor, self.factor_base
        if factor_base != 2:
            LOGGER.warning(f"scorecard param 'factor_base' given is {factor_base}, which is not equal to 2.")
        upper_limit_value, lower_limit_value = self.upper_limit_ratio * offset, self.lower_limit_value
        if isinstance(prediction_result.first()[1], Instance):
            self.use_match_id = True
        score_result = prediction_result.mapValues(lambda v: Scorecard.compute_credit_score(v, offset, factor,
                                                                                factor_base,
                                                                                upper_limit_value,
                                                                                lower_limit_value,
                                                                                self.use_match_id))
        result_schema = copy.deepcopy(prediction_result.schema)
        result_schema["header"] = ["label", "predict_result", "predict_score", "credit_score"]
        """
        result_schema = {"header": ["label", "predict_result", "predict_score", "credit_score"],
                         "sid_name": schema.get('sid_name')}
        """
        score_result.schema = result_schema

        self._set_summary()
        LOGGER.info(f"Finish Scorecard Transform!")

        return score_result
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    app.models
    ~~~~~~~~~~

    Provides the SQLAlchemy models
"""
from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import savalidation.validators as val

from datetime import datetime as dt
from app import db
from savalidation import ValidationMixin

class HDRO(db.Model, ValidationMixin):
    # auto keys
    id = db.Column(db.Integer, primary_key=True)
    utc_created = db.Column(db.DateTime, nullable=False, default=dt.utcnow())
    utc_updated = db.Column(
        db.DateTime, nullable=False, default=dt.utcnow(), onupdate=dt.utcnow())

    # other keys
    rid = db.Column(db.String(16), nullable=False, index=True, unique=True)
    country = db.Column(db.String(32), nullable=False)
    indicator = db.Column(db.String(128), nullable=False)
    value = db.Column(db.Numeric, nullable=False)
    year = db.Column(db.Integer, nullable=False)

    # validation
    val.validates_constraints()

    def __repr__(self):
        return ('<HDRO(%r, %r)>' % (self.country, self.indicator))
<commit_msg>BUGFIX: fix model capitalization<commit_after># -*- coding: utf-8 -*-
"""
    app.models
    ~~~~~~~~~~

    Provides the SQLAlchemy models
"""
from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import savalidation.validators as val

from datetime import datetime as dt
from app import db
from savalidation import ValidationMixin

class Hdro(db.Model, ValidationMixin):
    # auto keys
    id = db.Column(db.Integer, primary_key=True)
    utc_created = db.Column(db.DateTime, nullable=False, default=dt.utcnow())
    utc_updated = db.Column(
        db.DateTime, nullable=False, default=dt.utcnow(), onupdate=dt.utcnow())

    # other keys
    rid = db.Column(db.String(16), nullable=False, index=True, unique=True)
    country = db.Column(db.String(32), nullable=False)
    indicator = db.Column(db.String(128), nullable=False)
    value = db.Column(db.Numeric, nullable=False)
    year = db.Column(db.Integer, nullable=False)

    # validation
    val.validates_constraints()

    def __repr__(self):
        return ('<HDRO(%r, %r)>' % (self.country, self.indicator))
<|endoftext|>


<commit_before>#Player Class
import pygame

class Player:
    def __init__(self):
        self.speed = 64
        self.texture = pygame.image.load("player.png")
        self.rect = (128, 128, 64, 64)
    def draw(self, surface):
        surface.blit(self.texture, self.rect)
    def update(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_KP4:
                self.rect.x -= self.speed
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_KP6:
                self.rect.x += self.speed
            if event.key == pygame.K_UP or event.key == pygame.K_KP8:
                self.rect.y -= self.speed
            elif event.key == pygame.K_DOWN or event.key == pygame.K_KP2:
                self.rect.y += self.speed
<commit_msg>Made player.rect a pygame.Rect<commit_after>#Player Class
import pygame

class Player:
    def __init__(self):
        self.speed = 64
        self.texture = pygame.image.load("player.png")
        self.rect = pygame.Rect(128, 128, 64, 64)
    def draw(self, surface):
        surface.blit(self.texture, self.rect)
    def update(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_KP4:
                self.rect.x -= self.speed
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_KP6:
                self.rect.x += self.speed
            if event.key == pygame.K_UP or event.key == pygame.K_KP8:
                self.rect.y -= self.speed
            elif event.key == pygame.K_DOWN or event.key == pygame.K_KP2:
                self.rect.y += self.speed
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

"""Qt dock window."""

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------

from collections import defaultdict
import logging

from six import string_types, PY3

from .qt import QtCore, QtGui
from ..utils.event import EventEmitter

logger = logging.getLogger(__name__)

# -----------------------------------------------------------------------------
# Qt utilities
# -----------------------------------------------------------------------------

def _title(widget):
    return str(widget.windowTitle()).lower()

def _show_shortcut(shortcut):
    if isinstance(shortcut, string_types):
        return shortcut
    elif isinstance(shortcut, (tuple, list)):
        return ', '.join(shortcut)

def _show_shortcuts(shortcuts, name=None):
    name = name or ''
    print()
    if name:
        name = ' for ' + name
    print('Keyboard shortcuts' + name)
    for name in sorted(shortcuts):
        print('{0:<40}: {1:s}'.format(name, _show_shortcut(shortcuts[name])))
    print()

# -----------------------------------------------------------------------------
# Companion class
# -----------------------------------------------------------------------------

class Actions(EventEmitter):
    """Handle GUI actions."""
    def __init__(self):
        super(Actions, self).__init__()
        self._dock = None
        self._actions = {}

    def reset(self):
        """Reset the actions.

        All actions should be registered here, as follows:

        ```python
        @actions.connect
        def on_reset():
            actions.add(...)
            actions.add(...)
            ...
        ```

        """
        self.remove_all()
        self.emit('reset')

    def attach(self, dock):
        """Attach a DockWindow."""
        self._dock = dock

        # Default exit action.
        @self.shortcut('ctrl+q')
        def exit():
            dock.close()

    @property
    def shortcuts(self):
        """A dictionary of action shortcuts."""
        return {name: action._shortcut_string
                for name, action in self._actions.items()}

    def show_shortcuts(self):
        """Print all shortcuts."""
        _show_shortcuts(self.shortcuts,
                        self._dock.title() if self._dock else None)

    def add(self, name, callback=None, shortcut=None,
            checkable=False, checked=False):
        """Add an action with a keyboard shortcut."""
        if name in self._actions:
            return
        action = QtGui.QAction(name, self._dock)
        action.triggered.connect(callback)
        action.setCheckable(checkable)
        action.setChecked(checked)
        if shortcut:
            if not isinstance(shortcut, (tuple, list)):
                shortcut = [shortcut]
            for key in shortcut:
                action.setShortcut(key)
        # HACK: add the shortcut string to the QAction object so that
        # it can be shown in show_shortcuts(). I don't manage to recover
        # the key sequence string from a QAction using Qt.
        action._shortcut_string = shortcut or ''
        if self._dock:
            self._dock.addAction(action)
        self._actions[name] = action
        if callback:
            setattr(self, name, callback)
        return action

    def remove(self, name):
        """Remove an action."""
        if self._dock:
            self._dock.removeAction(self._actions[name])
        del self._actions[name]
        delattr(self, name)

    def remove_all(self):
        """Remove all actions."""
        names = sorted(self._actions.keys())
        for name in names:
            self.remove(name)

    def shortcut(self, key=None, name=None):
        """Decorator to add a global keyboard shortcut."""
        def wrap(func):
            self.add(name or func.__name__, shortcut=key, callback=func)
        return wrap

class Snippets(object):
    # HACK: Unicode characters do not appear to work on Python 2
    cursor = '\u200A\u258C' if PY3 else ''

    # Allowed characters in snippet mode.
    _snippet_chars = 'abcdefghijklmnopqrstuvwxyz0123456789 ._,+*-=:()'

    def __init__(self):
        self._dock = None

    def attach(self, dock, actions):
        self._dock = dock
        self._actions = actions

        # Register snippet mode shortcut.
        @actions.connect
        def on_reset():
            @actions.shortcut(':')
            def enable_snippet_mode():
                self.mode_on()

    @property
    def command(self):
        """This is used to write a snippet message in the status bar.

        A cursor is appended at the end.

        """
        n = len(self._dock.status_message)
        n_cur = len(self.cursor)
        return self._dock.status_message[:n - n_cur]

    @command.setter
    def command(self, value):
        self._dock.status_message = value + self.cursor

    def run(self, snippet):
        """Executes a snippet.

        May be overriden.

        """
        assert snippet[0] == ':'
        snippet = snippet[1:]
        split = snippet.split(' ')
        cmd = split[0]
        snippet = snippet[len(cmd):].strip()
        func = self._snippets.get(cmd, None)
        if func is None:
            logger.info("The snippet `%s` could not be found.", cmd)
            return
        try:
            logger.info("Processing snippet `%s`.", cmd)
            func(self, snippet)
        except Exception as e:
            logger.warn("Error when executing snippet `%s`: %s.",
                        cmd, str(e))

    def _create_snippet_actions(self):
        """Delete all existing actions, and add mock ones for snippet
        keystrokes.

        Used to enable snippet mode.

        """
        self._actions.remove_all()

        # One action per allowed character.
        for i, char in enumerate(self._snippet_chars):

            def _make_func(char):
                def callback():
                    self.command += char
                return callback

            self._actions.add('snippet_{}'.format(i),
                              shortcut=char,
                              callback=_make_func(char),
                              )

        def backspace():
            if self.command == ':':
                return
            self.command = self.command[:-1]

        def enter():
            self.run(self.command)
            self.disable_snippet_mode()

        self._actions.add('snippet_backspace',
                          shortcut='backspace',
                          callback=backspace,
                          )
        self._actions.add('snippet_activate',
                          shortcut=('enter', 'return'),
                          callback=enter,
                          )
        self._actions.add('snippet_disable',
                          shortcut='escape',
                          callback=self.disable_snippet_mode,
                          )

    def mode_on(self):
        logger.info("Snippet mode enabled, press `escape` to leave this mode.")
        # Remove all existing actions, and replace them by snippet keystroke
        # actions.
        self._create_snippet_actions()
        self.command = ':'

    def mode_off(self):
        self._dock.status_message = ''
        # Reestablishes the shortcuts.
        self._actions.reset()
        logger.info("Snippet mode disabled.")

# -----------------------------------------------------------------------------
# Qt windows
# -----------------------------------------------------------------------------

class DockWidget(QtGui.QDockWidget):
    """A QDockWidget that can emit events."""
    def __init__(self, *args, **kwargs):
        super(DockWidget, self).__init__(*args, **kwargs)
        self._event = EventEmitter()

    def emit(self, *args, **kwargs):
        return self._event.emit(*args, **kwargs)

    def connect_(self, *args, **kwargs):
        self._event.connect(*args, **kwargs)

    def closeEvent(self, e):
        """Qt slot when the window is closed."""
        self.emit('close_widget')
        super(DockWidget, self).closeEvent(e)

class DockWindow(QtGui.QMainWindow):
    """A Qt main window holding docking Qt or VisPy widgets.

    `DockWindow` derives from `QMainWindow`.

    Events
    ------

    close_gui
    show_gui

    Note
    ----

    Use `connect_()`, not `connect()`, because of a name conflict with Qt.

    """
    def __init__(self,
                 position=None,
                 size=None,
                 title=None,
                 ):
        super(DockWindow, self).__init__()
        if title is None:
            title = 'phy'
        self.setWindowTitle(title)
        if position is not None:
            self.move(position[0], position[1])
        if size is not None:
            self.resize(QtCore.QSize(size[0], size[1]))
        self.setObjectName(title)
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setDockOptions(QtGui.QMainWindow.AllowTabbedDocks |
                            QtGui.QMainWindow.AllowNestedDocks |
                            QtGui.QMainWindow.AnimatedDocks
                            )
        # We can derive from EventEmitter because of a conflict with connect.
        self._event = EventEmitter()

        self._status_bar = QtGui.QStatusBar()
        self.setStatusBar(self._status_bar)

    # Events
    # -------------------------------------------------------------------------

    def emit(self, *args, **kwargs):
        return self._event.emit(*args, **kwargs)

    def connect_(self, *args, **kwargs):
        self._event.connect(*args, **kwargs)

    def unconnect_(self, *args, **kwargs):
        self._event.unconnect(*args, **kwargs)

    def closeEvent(self, e):
        """Qt slot when the window is closed."""
        res = self.emit('close_gui')
        # Discard the close event if False is returned by one of the callback
        # functions.
        if False in res:  # pragma: no cover
            e.ignore()
            return
        super(DockWindow, self).closeEvent(e)

    def show(self):
        """Show the window."""
        self.emit('show_gui')
        super(DockWindow, self).show()

    # Views
    # -------------------------------------------------------------------------

    def add_view(self,
                 view,
                 title='view',
                 position=None,
                 closable=True,
                 floatable=True,
                 floating=None,
                 # parent=None,  # object to pass in the raised events
                 **kwargs):
        """Add a widget to the main window."""

        try:
            from vispy.app import Canvas
            if isinstance(view, Canvas):
                view = view.native
        except ImportError:  # pragma: no cover
            pass

        # Create the dock widget.
        dockwidget = DockWidget(self)
        dockwidget.setObjectName(title)
        dockwidget.setWindowTitle(title)
        dockwidget.setWidget(view)

        # Set dock widget options.
        options = QtGui.QDockWidget.DockWidgetMovable
        if closable:
            options = options | QtGui.QDockWidget.DockWidgetClosable
        if floatable:
            options = options | QtGui.QDockWidget.DockWidgetFloatable

        dockwidget.setFeatures(options)
        dockwidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea |
                                   QtCore.Qt.RightDockWidgetArea |
                                   QtCore.Qt.TopDockWidgetArea |
                                   QtCore.Qt.BottomDockWidgetArea
                                   )

        q_position = {
            'left': QtCore.Qt.LeftDockWidgetArea,
            'right': QtCore.Qt.RightDockWidgetArea,
            'top': QtCore.Qt.TopDockWidgetArea,
            'bottom': QtCore.Qt.BottomDockWidgetArea,
        }[position or 'right']
        self.addDockWidget(q_position, dockwidget)
        if floating is not None:
            dockwidget.setFloating(floating)
        dockwidget.show()
        return dockwidget

    def list_views(self, title='', is_visible=True):
        """List all views which title start with a given string."""
        title = title.lower()
        children = self.findChildren(QtGui.QWidget)
        return [child for child in children
                if isinstance(child, QtGui.QDockWidget) and
                _title(child).startswith(title) and
                (child.isVisible() if is_visible else True) and
                child.width() >= 10 and
                child.height() >= 10
                ]

    def view_count(self):
        """Return the number of opened views."""
        views = self.list_views()
        counts = defaultdict(lambda: 0)
        for view in views:
            counts[_title(view)] += 1
        return dict(counts)

    # Status bar
    # -------------------------------------------------------------------------

    @property
    def status_message(self):
        """The message in the status bar."""
        return str(self._status_bar.currentMessage())

    @status_message.setter
    def status_message(self, value):
        self._status_bar.showMessage(str(value))

    # State
    # -------------------------------------------------------------------------

    def save_geometry_state(self):
        """Return picklable geometry and state of the window and docks.

        This function can be called in `on_close()`.

        """
        return {
            'geometry': self.saveGeometry(),
            'state': self.saveState(),
            'view_count': self.view_count(),
        }

    def restore_geometry_state(self, gs):
        """Restore the position of the main window and the docks.

        The dock widgets need to be recreated first.

        This function can be called in `on_show()`.

        """
        if gs.get('geometry', None):
            self.restoreGeometry((gs['geometry']))
        if gs.get('state', None):
            self.restoreState((gs['state']))
<commit_msg>WIP: refactor snippets<commit_after># -*- coding: utf-8 -*-

"""Qt dock window."""

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------

from collections import defaultdict
import logging

from six import string_types, PY3

from .qt import QtCore, QtGui
from ..utils.event import EventEmitter

logger = logging.getLogger(__name__)

# -----------------------------------------------------------------------------
# Qt utilities
# -----------------------------------------------------------------------------

def _title(widget):
    return str(widget.windowTitle()).lower()

def _show_shortcut(shortcut):
    if isinstance(shortcut, string_types):
        return shortcut
    elif isinstance(shortcut, (tuple, list)):
        return ', '.join(shortcut)

def _show_shortcuts(shortcuts, name=None):
    name = name or ''
    print()
    if name:
        name = ' for ' + name
    print('Keyboard shortcuts' + name)
    for name in sorted(shortcuts):
        print('{0:<40}: {1:s}'.format(name, _show_shortcut(shortcuts[name])))
    print()

# -----------------------------------------------------------------------------
# Companion class
# -----------------------------------------------------------------------------

class Actions(EventEmitter):
    """Handle GUI actions."""
    def __init__(self):
        super(Actions, self).__init__()
        self._dock = None
        self._actions = {}

    def reset(self):
        """Reset the actions.

        All actions should be registered here, as follows:

        ```python
        @actions.connect
        def on_reset():
            actions.add(...)
            actions.add(...)
            ...
        ```

        """
        self.remove_all()
        self.emit('reset')

    def attach(self, dock):
        """Attach a DockWindow."""
        self._dock = dock

        # Default exit action.
        @self.shortcut('ctrl+q')
        def exit():
            dock.close()

    def add(self, name, callback=None, shortcut=None,
            checkable=False, checked=False):
        """Add an action with a keyboard shortcut."""
        if name in self._actions:
            return
        action = QtGui.QAction(name, self._dock)
        action.triggered.connect(callback)
        action.setCheckable(checkable)
        action.setChecked(checked)
        if shortcut:
            if not isinstance(shortcut, (tuple, list)):
                shortcut = [shortcut]
            for key in shortcut:
                action.setShortcut(key)
        # HACK: add the shortcut string to the QAction object so that
        # it can be shown in show_shortcuts(). I don't manage to recover
        # the key sequence string from a QAction using Qt.
        action._shortcut_string = shortcut or ''
        if self._dock:
            self._dock.addAction(action)
        self._actions[name] = action
        if callback:
            setattr(self, name, callback)
        return action

    def remove(self, name):
        """Remove an action."""
        if self._dock:
            self._dock.removeAction(self._actions[name])
        del self._actions[name]
        delattr(self, name)

    def remove_all(self):
        """Remove all actions."""
        names = sorted(self._actions.keys())
        for name in names:
            self.remove(name)

    @property
    def shortcuts(self):
        """A dictionary of action shortcuts."""
        return {name: action._shortcut_string
                for name, action in self._actions.items()}

    def show_shortcuts(self):
        """Print all shortcuts."""
        _show_shortcuts(self.shortcuts,
                        self._dock.title() if self._dock else None)

    def shortcut(self, key=None, name=None):
        """Decorator to add a global keyboard shortcut."""
        def wrap(func):
            self.add(name or func.__name__, shortcut=key, callback=func)
        return wrap

class Snippets(object):
    # HACK: Unicode characters do not appear to work on Python 2
    cursor = '\u200A\u258C' if PY3 else ''

    # Allowed characters in snippet mode.
    _snippet_chars = 'abcdefghijklmnopqrstuvwxyz0123456789 ._,+*-=:()'

    def __init__(self):
        self._dock = None

    def attach(self, dock, actions):
        self._dock = dock
        self._actions = actions

        # Register snippet mode shortcut.
        @actions.connect
        def on_reset():
            @actions.shortcut(':')
            def enable_snippet_mode():
                self.mode_on()

    @property
    def command(self):
        """This is used to write a snippet message in the status bar.

        A cursor is appended at the end.

        """
        n = len(self._dock.status_message)
        n_cur = len(self.cursor)
        return self._dock.status_message[:n - n_cur]

    @command.setter
    def command(self, value):
        self._dock.status_message = value + self.cursor

    def _backspace(self):
        """Erase the last character in the snippet command."""
        if self.command == ':':
            return
        self.command = self.command[:-1]

    def _enter(self):
        """Disable the snippet mode and execute the command."""
        command = self.command
        self.disable_snippet_mode()
        self.run(command)

    def _create_snippet_actions(self):
        """Delete all existing actions, and add mock ones for snippet
        keystrokes.

        Used to enable snippet mode.

        """
        self._actions.remove_all()

        # One action per allowed character.
        for i, char in enumerate(self._snippet_chars):

            def _make_func(char):
                def callback():
                    self.command += char
                return callback

            self._actions.add('snippet_{}'.format(i), shortcut=char,
                              callback=_make_func(char))

        self._actions.add('snippet_backspace', shortcut='backspace',
                          callback=self._backspace)
        self._actions.add('snippet_activate', shortcut=('enter', 'return'),
                          callback=self._enter)
        self._actions.add('snippet_disable', shortcut='escape',
                          callback=self.disable_snippet_mode)

    def run(self, snippet):
        """Executes a snippet command.

        May be overriden.

        """
        assert snippet[0] == ':'
        snippet = snippet[1:]
        split = snippet.split(' ')
        cmd = split[0]
        snippet = snippet[len(cmd):].strip()
        func = self._snippets.get(cmd, None)
        if func is None:
            logger.info("The snippet `%s` could not be found.", cmd)
            return
        try:
            logger.info("Processing snippet `%s`.", cmd)
            func(self, snippet)
        except Exception as e:
            logger.warn("Error when executing snippet `%s`: %s.",
                        cmd, str(e))

    def mode_on(self):
        logger.info("Snippet mode enabled, press `escape` to leave this mode.")
        # Remove all existing actions, and replace them by snippet keystroke
        # actions.
        self._create_snippet_actions()
        self.command = ':'

    def mode_off(self):
        self._dock.status_message = ''
        # Reestablishes the shortcuts.
        self._actions.reset()
        logger.info("Snippet mode disabled.")

# -----------------------------------------------------------------------------
# Qt windows
# -----------------------------------------------------------------------------

class DockWidget(QtGui.QDockWidget):
    """A QDockWidget that can emit events."""
    def __init__(self, *args, **kwargs):
        super(DockWidget, self).__init__(*args, **kwargs)
        self._event = EventEmitter()

    def emit(self, *args, **kwargs):
        return self._event.emit(*args, **kwargs)

    def connect_(self, *args, **kwargs):
        self._event.connect(*args, **kwargs)

    def closeEvent(self, e):
        """Qt slot when the window is closed."""
        self.emit('close_widget')
        super(DockWidget, self).closeEvent(e)

class DockWindow(QtGui.QMainWindow):
    """A Qt main window holding docking Qt or VisPy widgets.

    `DockWindow` derives from `QMainWindow`.

    Events
    ------

    close_gui
    show_gui

    Note
    ----

    Use `connect_()`, not `connect()`, because of a name conflict with Qt.

    """
    def __init__(self,
                 position=None,
                 size=None,
                 title=None,
                 ):
        super(DockWindow, self).__init__()
        if title is None:
            title = 'phy'
        self.setWindowTitle(title)
        if position is not None:
            self.move(position[0], position[1])
        if size is not None:
            self.resize(QtCore.QSize(size[0], size[1]))
        self.setObjectName(title)
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setDockOptions(QtGui.QMainWindow.AllowTabbedDocks |
                            QtGui.QMainWindow.AllowNestedDocks |
                            QtGui.QMainWindow.AnimatedDocks
                            )
        # We can derive from EventEmitter because of a conflict with connect.
        self._event = EventEmitter()

        self._status_bar = QtGui.QStatusBar()
        self.setStatusBar(self._status_bar)

    # Events
    # -------------------------------------------------------------------------

    def emit(self, *args, **kwargs):
        return self._event.emit(*args, **kwargs)

    def connect_(self, *args, **kwargs):
        self._event.connect(*args, **kwargs)

    def unconnect_(self, *args, **kwargs):
        self._event.unconnect(*args, **kwargs)

    def closeEvent(self, e):
        """Qt slot when the window is closed."""
        res = self.emit('close_gui')
        # Discard the close event if False is returned by one of the callback
        # functions.
        if False in res:  # pragma: no cover
            e.ignore()
            return
        super(DockWindow, self).closeEvent(e)

    def show(self):
        """Show the window."""
        self.emit('show_gui')
        super(DockWindow, self).show()

    # Views
    # -------------------------------------------------------------------------

    def add_view(self,
                 view,
                 title='view',
                 position=None,
                 closable=True,
                 floatable=True,
                 floating=None,
                 # parent=None,  # object to pass in the raised events
                 **kwargs):
        """Add a widget to the main window."""

        try:
            from vispy.app import Canvas
            if isinstance(view, Canvas):
                view = view.native
        except ImportError:  # pragma: no cover
            pass

        # Create the dock widget.
        dockwidget = DockWidget(self)
        dockwidget.setObjectName(title)
        dockwidget.setWindowTitle(title)
        dockwidget.setWidget(view)

        # Set dock widget options.
        options = QtGui.QDockWidget.DockWidgetMovable
        if closable:
            options = options | QtGui.QDockWidget.DockWidgetClosable
        if floatable:
            options = options | QtGui.QDockWidget.DockWidgetFloatable

        dockwidget.setFeatures(options)
        dockwidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea |
                                   QtCore.Qt.RightDockWidgetArea |
                                   QtCore.Qt.TopDockWidgetArea |
                                   QtCore.Qt.BottomDockWidgetArea
                                   )

        q_position = {
            'left': QtCore.Qt.LeftDockWidgetArea,
            'right': QtCore.Qt.RightDockWidgetArea,
            'top': QtCore.Qt.TopDockWidgetArea,
            'bottom': QtCore.Qt.BottomDockWidgetArea,
        }[position or 'right']
        self.addDockWidget(q_position, dockwidget)
        if floating is not None:
            dockwidget.setFloating(floating)
        dockwidget.show()
        return dockwidget

    def list_views(self, title='', is_visible=True):
        """List all views which title start with a given string."""
        title = title.lower()
        children = self.findChildren(QtGui.QWidget)
        return [child for child in children
                if isinstance(child, QtGui.QDockWidget) and
                _title(child).startswith(title) and
                (child.isVisible() if is_visible else True) and
                child.width() >= 10 and
                child.height() >= 10
                ]

    def view_count(self):
        """Return the number of opened views."""
        views = self.list_views()
        counts = defaultdict(lambda: 0)
        for view in views:
            counts[_title(view)] += 1
        return dict(counts)

    # Status bar
    # -------------------------------------------------------------------------

    @property
    def status_message(self):
        """The message in the status bar."""
        return str(self._status_bar.currentMessage())

    @status_message.setter
    def status_message(self, value):
        self._status_bar.showMessage(str(value))

    # State
    # -------------------------------------------------------------------------

    def save_geometry_state(self):
        """Return picklable geometry and state of the window and docks.

        This function can be called in `on_close()`.

        """
        return {
            'geometry': self.saveGeometry(),
            'state': self.saveState(),
            'view_count': self.view_count(),
        }

    def restore_geometry_state(self, gs):
        """Restore the position of the main window and the docks.

        The dock widgets need to be recreated first.

        This function can be called in `on_show()`.

        """
        if gs.get('geometry', None):
            self.restoreGeometry((gs['geometry']))
        if gs.get('state', None):
            self.restoreState((gs['state']))
<|endoftext|>


<commit_before>"""This contains a set of tests for ParaTemp.CoordinateAnalysis"""

########################################################################
#                                                                      #
# This script was written by Thomas Heavey in 2017.                    #
#        theavey@bu.edu     thomasjheavey@gmail.com                    #
#                                                                      #
# Copyright 2017 Thomas J. Heavey IV                                   #
#                                                                      #
# 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.                                       #
#                                                                      #
########################################################################

from __future__ import absolute_import

import pytest
import numpy as np
import matplotlib

from paratemp.coordinate_analysis import _running_mean

matplotlib.use('agg')

def test_matplotlib_testing_backend():
    # Travis should fail if this isn't true, but hopefully this makes it
    # clearer as to why it failed.
    assert matplotlib.get_backend() == 'agg'

def test_running_mean():
    from ..paratemp import coordinate_analysis as ca
    tl = [0, 2, 4]
    assert (_running_mean(tl) == [1, 3]).all()

class TestXTCUniverse(object):

    @pytest.fixture
    def univ(self):
        from ..paratemp import coordinate_analysis as ca
        _univ = ca.Universe('tests/test-data/spc2.gro',
                            'tests/test-data/t-spc2-traj.xtc',
                            temp=205.)
        return _univ

    @pytest.fixture
    def univ_w_a(self, univ):
        univ.calculate_distances(a='4 5')
        return univ

    @pytest.fixture
    def univ_pbc(self):
        from ..paratemp import coordinate_analysis as ca
        _univ = ca.Universe('tests/test-data/spc2.gro',
                            'tests/test-data/spc2-traj-pbc.xtc',
                            temp=205.)
        return _univ

    @pytest.fixture
    def ref_a_dists(self):
        import pandas
        return pandas.read_csv('tests/ref-data/spc2-a-dists.csv',
                               index_col=0)

    @pytest.fixture
    def ref_a_pbc_dists(self):
        import pandas
        return pandas.read_csv('tests/ref-data/spc2-a-pbc-dists.csv',
                               index_col=0)

    @pytest.fixture
    def ref_delta_g(self):
        return np.load('tests/ref-data/spc2-fes1d-delta-gs.npy')

    @pytest.fixture
    def ref_bins(self):
        return np.load('tests/ref-data/spc2-fes1d-bins.npy')

    def test_distance_str(self, univ, ref_a_dists):
        univ.calculate_distances(a='4 5')
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_distance_list_int(self, univ, ref_a_dists):
        univ.calculate_distances(a=[4, 5])
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_distance_list_str(self, univ, ref_a_dists):
        univ.calculate_distances(a=['4', '5'])
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_calculate_distances_no_recalc(self, univ_w_a, capsys):
        univ_w_a.calculate_distances(a=[4, 5])
        out, err = capsys.readouterr()
        assert out == 'Nothing (new) to calculate here.\n'

    def test_calculate_distances_yes_recalc(self, univ_w_a):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        """
        univ_w_a.calculate_distances(a='5 5', recalculate=True)
        assert (np.array([0., 0.]) == univ_w_a.data['a']).all()

    def test_distance_pbc(self, univ_pbc, ref_a_pbc_dists):
        univ_pbc.calculate_distances(a='4 5')
        assert np.isclose(ref_a_pbc_dists['a'], univ_pbc.data['a']).all()

    def test_fes_1d_data_str(self, univ_w_a, ref_delta_g, ref_bins):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        :type ref_delta_g: pandas.DataFrame
        :type ref_bins: pandas.DataFrame
        """
        delta_g_str, bins_str, lines_str, fig_str, ax_str = \
            univ_w_a.fes_1d('a')
        assert (delta_g_str == ref_delta_g).all()
        assert (bins_str == ref_bins).all()

    def test_fes_1d_data_data(self, univ_w_a, ref_delta_g, ref_bins):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        :type ref_delta_g: pandas.DataFrame
        :type ref_bins: pandas.DataFrame
        """
        delta_g_data, bins_data, lines_data, fig_data, ax_data = \
            univ_w_a.fes_1d(univ_w_a.data['a'])
        assert (delta_g_data == ref_delta_g).all()
        assert (bins_data == ref_bins).all()

    def test_final_time_str(self, univ):
        assert univ.final_time_str == '2ps'
        univ._last_time = 1001.0
        assert univ.final_time_str == '1ns'
        univ._last_time = 32111222.12
        assert univ.final_time_str == '32us'
        univ._last_time = 5.1e12
        assert univ.final_time_str == '5100ms'

# TODO add further Universe tests
#       ignore_file_change=True
#       fes_2d
#       save_data
#       read_data
#       calculate_dihedrals
#       figure from fes_1d
#       figure from fes_2d
<commit_msg>put imports back in the right place<commit_after>"""This contains a set of tests for ParaTemp.CoordinateAnalysis"""

########################################################################
#                                                                      #
# This script was written by Thomas Heavey in 2017.                    #
#        theavey@bu.edu     thomasjheavey@gmail.com                    #
#                                                                      #
# Copyright 2017 Thomas J. Heavey IV                                   #
#                                                                      #
# 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.                                       #
#                                                                      #
########################################################################

from __future__ import absolute_import

import pytest
import numpy as np
import matplotlib

matplotlib.use('agg')

def test_matplotlib_testing_backend():
    # Travis should fail if this isn't true, but hopefully this makes it
    # clearer as to why it failed.
    assert matplotlib.get_backend() == 'agg'

def test_running_mean():
    from paratemp.coordinate_analysis import _running_mean
    tl = [0, 2, 4]
    assert (_running_mean(tl) == [1, 3]).all()

class TestXTCUniverse(object):

    @pytest.fixture
    def univ(self):
        from ..paratemp import coordinate_analysis as ca
        _univ = ca.Universe('tests/test-data/spc2.gro',
                            'tests/test-data/t-spc2-traj.xtc',
                            temp=205.)
        return _univ

    @pytest.fixture
    def univ_w_a(self, univ):
        univ.calculate_distances(a='4 5')
        return univ

    @pytest.fixture
    def univ_pbc(self):
        from ..paratemp import coordinate_analysis as ca
        _univ = ca.Universe('tests/test-data/spc2.gro',
                            'tests/test-data/spc2-traj-pbc.xtc',
                            temp=205.)
        return _univ

    @pytest.fixture
    def ref_a_dists(self):
        import pandas
        return pandas.read_csv('tests/ref-data/spc2-a-dists.csv',
                               index_col=0)

    @pytest.fixture
    def ref_a_pbc_dists(self):
        import pandas
        return pandas.read_csv('tests/ref-data/spc2-a-pbc-dists.csv',
                               index_col=0)

    @pytest.fixture
    def ref_delta_g(self):
        return np.load('tests/ref-data/spc2-fes1d-delta-gs.npy')

    @pytest.fixture
    def ref_bins(self):
        return np.load('tests/ref-data/spc2-fes1d-bins.npy')

    def test_distance_str(self, univ, ref_a_dists):
        univ.calculate_distances(a='4 5')
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_distance_list_int(self, univ, ref_a_dists):
        univ.calculate_distances(a=[4, 5])
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_distance_list_str(self, univ, ref_a_dists):
        univ.calculate_distances(a=['4', '5'])
        assert np.isclose(ref_a_dists, univ.data['a']).all()

    def test_calculate_distances_no_recalc(self, univ_w_a, capsys):
        univ_w_a.calculate_distances(a=[4, 5])
        out, err = capsys.readouterr()
        assert out == 'Nothing (new) to calculate here.\n'

    def test_calculate_distances_yes_recalc(self, univ_w_a):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        """
        univ_w_a.calculate_distances(a='5 5', recalculate=True)
        assert (np.array([0., 0.]) == univ_w_a.data['a']).all()

    def test_distance_pbc(self, univ_pbc, ref_a_pbc_dists):
        univ_pbc.calculate_distances(a='4 5')
        assert np.isclose(ref_a_pbc_dists['a'], univ_pbc.data['a']).all()

    def test_fes_1d_data_str(self, univ_w_a, ref_delta_g, ref_bins):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        :type ref_delta_g: pandas.DataFrame
        :type ref_bins: pandas.DataFrame
        """
        delta_g_str, bins_str, lines_str, fig_str, ax_str = \
            univ_w_a.fes_1d('a')
        assert (delta_g_str == ref_delta_g).all()
        assert (bins_str == ref_bins).all()

    def test_fes_1d_data_data(self, univ_w_a, ref_delta_g, ref_bins):
        """
        :type univ_w_a: ParaTemp.CoordinateAnalysis.Universe
        :type ref_delta_g: pandas.DataFrame
        :type ref_bins: pandas.DataFrame
        """
        delta_g_data, bins_data, lines_data, fig_data, ax_data = \
            univ_w_a.fes_1d(univ_w_a.data['a'])
        assert (delta_g_data == ref_delta_g).all()
        assert (bins_data == ref_bins).all()

    def test_final_time_str(self, univ):
        assert univ.final_time_str == '2ps'
        univ._last_time = 1001.0
        assert univ.final_time_str == '1ns'
        univ._last_time = 32111222.12
        assert univ.final_time_str == '32us'
        univ._last_time = 5.1e12
        assert univ.final_time_str == '5100ms'

# TODO add further Universe tests
#       ignore_file_change=True
#       fes_2d
#       save_data
#       read_data
#       calculate_dihedrals
#       figure from fes_1d
#       figure from fes_2d
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2017 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.

import os
import getpass

from openquake.baselib import config

try:
    import openquakeplatform
    STANDALONE = True
except ImportError:
    STANDALONE = False

DB_SECTION = config.dbserver

INSTALLED_APPS = ('openquake.server.db',)

OQSERVER_ROOT = os.path.dirname(__file__)

DEBUG = True
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'openquake.server.utils.oq_server_context_processor',
            ],
        },
    },
]

STATIC_URL = '/static/'

MEDIA_ROOT = '%(mediaroot)s'
STATIC_ROOT = '%(staticroot)s'

# Additional directories which hold static files
STATICFILES_DIRS = [
    os.path.join(OQSERVER_ROOT, 'static'),
]

DATABASE = {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.expanduser(DB_SECTION.get('file')),
    'LOG': os.path.expanduser(DB_SECTION.get('log')),
    'USER': getpass.getuser(),
    'HOST': DB_SECTION.get('host'),
    'PORT': DB_SECTION.get('port'),
}
DATABASES = {'default': DATABASE}

ALLOWED_HOSTS = ['*']

AUTHENTICATION_BACKENDS = ()

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Rome'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'f_6=^^_0%ygcpgmemxcp0p^xq%47yqe%u9pu!ad*2ym^zt+xq$'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)

LOCKDOWN = False
ACL_ON = False

# Add additional paths (as regular expressions) that don't require
# authentication.
AUTH_EXEMPT_URLS = ()

ROOT_URLCONF = 'openquake.server.urls'

INSTALLED_APPS += (
    'django.contrib.staticfiles',
    'openquake.server',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'openquake.server': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

FILE_UPLOAD_MAX_MEMORY_SIZE = 1

# OpenQuake Standalone tools (IPT, Taxtweb, Taxonomy Glossary)
STANDALONE_APPS = ()
if STANDALONE:
    INSTALLED_APPS += (
        'openquakeplatform',
    )

    STANDALONE_APPS += (
        'openquakeplatform_ipt',
        'openquakeplatform_taxtweb',
        'openquakeplatform_taxonomy',
    )

    INSTALLED_APPS += STANDALONE_APPS

    FILE_PATH_FIELD_DIRECTORY = os.path.join(os.path.expanduser('~'), 'oqdata')

    CONTEXT_PROCESSORS = TEMPLATES[0]['OPTIONS']['context_processors']
    CONTEXT_PROCESSORS.insert(0, 'django.template.context_processors.request')
    CONTEXT_PROCESSORS.append('openquakeplatform.utils.oq_context_processor')

try:
    # Try to load a local_settings.py from the current folder; this is useful
    # when packages are used. A custom local_settings.py can be placed in
    # /usr/share/openquake/engine, avoiding changes inside the python package
    from local_settings import *
except ImportError:
    # If no local_settings.py is availble in the current folder let's try to
    # load it from openquake/server/local_settings.py
    try:
        from openquake.server.local_settings import *
    except ImportError:
        # If a local_setting.py does not exist
        # settings in this file only will be used
        pass

if LOCKDOWN:

    ACL_ON = True

    AUTHENTICATION_BACKENDS += (
        'django.contrib.auth.backends.ModelBackend',
        # 'dpam.backends.PAMBackend',
    )

    MIDDLEWARE_CLASSES += (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'openquake.server.middleware.LoginRequiredMiddleware',
    )

    INSTALLED_APPS += (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.messages',
        'django.contrib.sessions',
        'django.contrib.admin',
        )

    # Official documentation suggests to override the entire TEMPLATES
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
                    'openquake.server.utils.oq_server_context_processor',
                ],
            },
        },
    ]

    LOGIN_REDIRECT_URL = '/engine'

    LOGIN_EXEMPT_URLS = ('/accounts/ajax_login/', )
<commit_msg>Get FILE_PATH_FIELD_DIRECTORY from datastore.get_datadir()<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2017 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.

import os
import getpass

from openquake.baselib import config, datastore

try:
    import openquakeplatform
    STANDALONE = True
except ImportError:
    STANDALONE = False

DB_SECTION = config.dbserver

INSTALLED_APPS = ('openquake.server.db',)

OQSERVER_ROOT = os.path.dirname(__file__)

DEBUG = True
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'openquake.server.utils.oq_server_context_processor',
            ],
        },
    },
]

STATIC_URL = '/static/'

MEDIA_ROOT = '%(mediaroot)s'
STATIC_ROOT = '%(staticroot)s'

# Additional directories which hold static files
STATICFILES_DIRS = [
    os.path.join(OQSERVER_ROOT, 'static'),
]

DATABASE = {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.expanduser(DB_SECTION.get('file')),
    'LOG': os.path.expanduser(DB_SECTION.get('log')),
    'USER': getpass.getuser(),
    'HOST': DB_SECTION.get('host'),
    'PORT': DB_SECTION.get('port'),
}
DATABASES = {'default': DATABASE}

ALLOWED_HOSTS = ['*']

AUTHENTICATION_BACKENDS = ()

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Rome'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'f_6=^^_0%ygcpgmemxcp0p^xq%47yqe%u9pu!ad*2ym^zt+xq$'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)

LOCKDOWN = False
ACL_ON = False

# Add additional paths (as regular expressions) that don't require
# authentication.
AUTH_EXEMPT_URLS = ()

ROOT_URLCONF = 'openquake.server.urls'

INSTALLED_APPS += (
    'django.contrib.staticfiles',
    'openquake.server',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'openquake.server': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

FILE_UPLOAD_MAX_MEMORY_SIZE = 1

# OpenQuake Standalone tools (IPT, Taxtweb, Taxonomy Glossary)
STANDALONE_APPS = ()
if STANDALONE:
    INSTALLED_APPS += (
        'openquakeplatform',
    )

    STANDALONE_APPS += (
        'openquakeplatform_ipt',
        'openquakeplatform_taxtweb',
        'openquakeplatform_taxonomy',
    )

    INSTALLED_APPS += STANDALONE_APPS

    FILE_PATH_FIELD_DIRECTORY = datastore.get_datadir()

    CONTEXT_PROCESSORS = TEMPLATES[0]['OPTIONS']['context_processors']
    CONTEXT_PROCESSORS.insert(0, 'django.template.context_processors.request')
    CONTEXT_PROCESSORS.append('openquakeplatform.utils.oq_context_processor')

try:
    # Try to load a local_settings.py from the current folder; this is useful
    # when packages are used. A custom local_settings.py can be placed in
    # /usr/share/openquake/engine, avoiding changes inside the python package
    from local_settings import *
except ImportError:
    # If no local_settings.py is availble in the current folder let's try to
    # load it from openquake/server/local_settings.py
    try:
        from openquake.server.local_settings import *
    except ImportError:
        # If a local_setting.py does not exist
        # settings in this file only will be used
        pass

if LOCKDOWN:

    ACL_ON = True

    AUTHENTICATION_BACKENDS += (
        'django.contrib.auth.backends.ModelBackend',
        # 'dpam.backends.PAMBackend',
    )

    MIDDLEWARE_CLASSES += (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'openquake.server.middleware.LoginRequiredMiddleware',
    )

    INSTALLED_APPS += (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.messages',
        'django.contrib.sessions',
        'django.contrib.admin',
        )

    # Official documentation suggests to override the entire TEMPLATES
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
                    'openquake.server.utils.oq_server_context_processor',
                ],
            },
        },
    ]

    LOGIN_REDIRECT_URL = '/engine'

    LOGIN_EXEMPT_URLS = ('/accounts/ajax_login/', )
<|endoftext|>


<commit_before>from haystack import indexes
from app.models import *

# ---------------------
# Champion Search Index
# ---------------------

class ChampionIndex (indexes.SearchIndex, indexes.Indexable) :
    text = indexes.CharField(document=True, use_template=True)
    id = models.IntegerField(model_attr='champion_id')
    name = indexes.CharField(model_attr='champion_name')
    role = indexes.CharField(model_attr='champion_role')
    title = indexes.CharField(model_attr='champion_title')
    lore = indexes.CharField(model_attr='champion_lore')
    image = indexes.CharField(model_attr='champion_image')
    passive_name = indexes.CharField(model_attr='champion_passive_name')
    passive_image = indexes.CharField(model_attr='champion_passive_image')
    passive_description = indexes.CharField(model_attr='champion_passive_description')
    q_name = indexes.CharField(model_attr='champion_q_name')
    q_image = indexes.CharField(model_attr='champion_q_image')
    q_description = indexes.CharField(model_attr='champion_q_description')
    w_name = indexes.CharField(model_attr='champion_w_name')
    w_image = indexes.CharField(model_attr='champion_w_image')
    w_description = indexes.CharField(model_attr='champion_w_description')
    e_name = indexes.CharField(model_attr='champion_e_name')
    e_image = indexes.CharField(model_attr='champion_e_image')
    e_description = indexes.CharField(model_attr='champion_e_description')
    r_name = indexes.CharField(model_attr='champion_r_name')
    r_image = indexes.CharField(model_attr='champion_r_image')
    r_description = indexes.CharField(model_attr='champion_r_description')
    recommended_items = indexes.CharField(model_attr='champion_recommended_items')

    def get_model (self) :
        return Champion

    def index_queryset (self, using=None) :
        """
        Used when the entire index for model is updated
        """
        return self.get_model().objects

# -----------------
# Item Search Index
# -----------------

# -------------------
# Player Search Index
# -------------------
<commit_msg>renamed search to search_indexes.py<commit_after><|endoftext|>