<commit_before># -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico 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 General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import

import os
import re
from flask import send_from_directory, request
from flask import current_app as app
from werkzeug.exceptions import NotFound
from werkzeug.urls import url_parse

import indico.util.date_time as date_time_util
from indico.core.config import Config
from MaKaC.common.info import HelperMaKaCInfo
from indico.util.i18n import gettext, ngettext
from indico.core.logger import Logger
from MaKaC.i18n import _
from MaKaC.plugins.base import RHMapMemory
from MaKaC.webinterface.pages.error import WErrorWSGI

from indico.core.db import DBMgr
from indico.core.db.sqlalchemy import db
from indico.core.db.sqlalchemy.logging import apply_db_loggers
from indico.core.db.sqlalchemy.util import delete_all_tables
from indico.web.assets import core_env, register_all_css, register_all_js
from indico.web.flask.templating import EnsureUnicodeExtension, underline
from indico.web.flask.util import (XAccelMiddleware, make_compat_blueprint, ListConverter, url_for, url_rule_to_js,
                                   IndicoConfigWrapper)
from indico.web.flask.wrappers import IndicoFlask

from indico.web.flask.blueprints.legacy import legacy
from indico.web.flask.blueprints.rooms import rooms
from indico.web.flask.blueprints.api import api
from indico.web.flask.blueprints.misc import misc
from indico.web.flask.blueprints.user import user
from indico.web.flask.blueprints.oauth import oauth
from indico.web.flask.blueprints.category import category
from indico.web.flask.blueprints.category_management import category_mgmt
from indico.web.flask.blueprints.event import event_display, event_creation, event_mgmt
from indico.web.flask.blueprints.files import files
from indico.web.flask.blueprints.admin import admin
from indico.web.flask.blueprints.rooms_admin import rooms_admin

BLUEPRINTS = (legacy, api, misc, user, oauth, rooms, category, category_mgmt, event_display,
              event_creation, event_mgmt, files, admin, rooms_admin)
COMPAT_BLUEPRINTS = map(make_compat_blueprint, (misc, user, oauth, rooms, category, category_mgmt, event_display,
                                                event_creation, event_mgmt, files, admin, rooms_admin))

def fix_root_path(app):
    """Fix the app's root path when using namespace packages.

    Flask's get_root_path is not reliable in this case so we derive it from
    __name__ and __file__ instead."""

    # __name__:       'indico.web.flask.app'
    # __file__:  '..../indico/web/flask/app.py'
    # For each dot in the module name we go up one path segment
    up_segments = ['..'] * __name__.count('.')
    app.root_path = os.path.normpath(os.path.join(__file__, *up_segments))

def configure_app(app, set_path=False):
    cfg = Config.getInstance()
    app.config['DEBUG'] = cfg.getDebug()
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SESSION_COOKIE_NAME'] = 'indico_session'
    app.config['PERMANENT_SESSION_LIFETIME'] = cfg.getSessionLifetime()
    app.config['INDICO_SESSION_PERMANENT'] = cfg.getSessionLifetime() > 0
    app.config['INDICO_HTDOCS'] = cfg.getHtdocsDir()
    app.config['INDICO_COMPAT_ROUTES'] = cfg.getRouteOldUrls()
    if set_path:
        base = url_parse(cfg.getBaseURL())
        app.config['SERVER_NAME'] = base.netloc
        if base.path:
            app.config['APPLICATION_ROOT'] = base.path
    app.config['WTF_CSRF_ENABLED'] = False  # for forms of room booking
    static_file_method = cfg.getStaticFileMethod()
    if static_file_method:
        app.config['USE_X_SENDFILE'] = True
        method, args = static_file_method
        if method in ('xsendfile', 'lighttpd'):  # apache mod_xsendfile, lighttpd
            pass
        elif method in ('xaccelredirect', 'nginx'):  # nginx
            if not args or not hasattr(args, 'items'):
                raise ValueError('StaticFileMethod args must be a dict containing at least one mapping')
            app.wsgi_app = XAccelMiddleware(app.wsgi_app, args)
        else:
            raise ValueError('Invalid static file method: %s' % method)

def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), 'indico_config')
    app.add_template_global(config.getSystemIconURL, 'system_icon')
    # Filters (indico functions returning UTF8)
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    # Filters (new ones returning unicode)
    app.add_template_filter(underline)
    # i18n
    app.jinja_env.add_extension('jinja2.ext.i18n')
    app.jinja_env.install_gettext_callables(gettext, ngettext, True)
    # webassets
    app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
    app.jinja_env.assets_environment = core_env

def setup_assets():
    register_all_js(core_env)
    register_all_css(core_env, Config.getInstance().getCssStylesheetName())

def configure_db(app):
    cfg = Config.getInstance()
    db_uri = cfg.getSQLAlchemyDatabaseURI()

    if db_uri is None:
        raise Exception("No proper SQLAlchemy store has been configured."
                        " Please edit your indico.conf")

    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri

    # DB options
    app.config['SQLALCHEMY_ECHO'] = cfg.getSQLAlchemyEcho()
    app.config['SQLALCHEMY_RECORD_QUERIES'] = cfg.getSQLAlchemyRecordQueries()
    app.config['SQLALCHEMY_POOL_SIZE'] = cfg.getSQLAlchemyPoolSize()
    app.config['SQLALCHEMY_POOL_TIMEOUT'] = cfg.getSQLAlchemyPoolTimeout()
    app.config['SQLALCHEMY_POOL_RECYCLE'] = cfg.getSQLAlchemyPoolRecycle()
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = cfg.getSQLAlchemyMaxOverflow()
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = False

    with DBMgr.getInstance().global_connection(commit=True):
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        if cfg.getIsRoomBookingActive():
            minfo.setRoomBookingModuleActive(True)
        else:
            minfo.setRoomBookingModuleActive()

    db.init_app(app)
    apply_db_loggers(app.debug)
    if cfg.getCreateTables():
        with app.app_context():
            delete_all_tables(db)  # favorable to `drop_all` under foreign keys
            db.create_all()

def extend_url_map(app):
    app.url_map.converters['list'] = ListConverter

def add_handlers(app):
    app.register_error_handler(404, handle_404)
    app.register_error_handler(Exception, handle_exception)

def add_blueprints(app):
    for blueprint in BLUEPRINTS:
        app.register_blueprint(blueprint)

def add_compat_blueprints(app):
    for blueprint in COMPAT_BLUEPRINTS:
        app.register_blueprint(blueprint)

def add_plugin_blueprints(app):
    for blueprint in RHMapMemory()._blueprints:
        if not app.config['INDICO_COMPAT_ROUTES'] and blueprint.name.startswith('compat_'):
            continue
        app.register_blueprint(blueprint)

def handle_404(exception):
    try:
        if re.search(r'\.py(?:/\S+)?$', request.path):
            # While not dangerous per se, we never serve *.py files as static
            raise NotFound
        try:
            return send_from_directory(app.config['INDICO_HTDOCS'], request.path[1:], conditional=True)
        except UnicodeEncodeError:
            raise NotFound
    except NotFound:
        if exception.description == NotFound.description:
            # The default reason is too long and not localized
            msg = (_("Page not found"), _("The page you were looking for doesn't exist."))
        else:
            msg = (_("Page not found"), exception.description)
        return WErrorWSGI(msg).getHTML(), 404

def handle_exception(exception):
    Logger.get('wsgi').exception(exception.message or 'WSGI Exception')
    if app.debug:
        raise
    msg = (str(exception), _("An unexpected error ocurred."))
    return WErrorWSGI(msg).getHTML(), 500

def make_app(set_path=False, db_setup=True):
    # If you are reading this code and wonder how to access the app:
    # >>> from flask import current_app as app
    # This only works while inside an application context but you really shouldn't have any
    # reason to access it outside this method without being inside an application context.
    # When set_path is enabled, SERVER_NAME and APPLICATION_ROOT are set according to BaseURL
    # so URLs can be generated without an app context, e.g. in the indico shell
    app = IndicoFlask('indico', static_folder=None, template_folder='web/templates')
    fix_root_path(app)
    configure_app(app, set_path)
    setup_jinja(app)
    setup_assets()

    if db_setup:
        configure_db(app)

    extend_url_map(app)
    add_handlers(app)
    add_blueprints(app)
    if app.config['INDICO_COMPAT_ROUTES']:
        add_compat_blueprints(app)
    add_plugin_blueprints(app)
    return app
<commit_msg>configure mappers explicitly<commit_after># -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico 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 General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import

import os
import re

from flask import send_from_directory, request
from flask import current_app as app
from sqlalchemy.orm import configure_mappers
from werkzeug.exceptions import NotFound
from werkzeug.urls import url_parse

import indico.util.date_time as date_time_util
from indico.core.config import Config
from MaKaC.common.info import HelperMaKaCInfo
from indico.util.i18n import gettext, ngettext
from indico.core.logger import Logger
from MaKaC.i18n import _
from MaKaC.plugins.base import RHMapMemory
from MaKaC.webinterface.pages.error import WErrorWSGI

from indico.core.db import DBMgr
from indico.core.db.sqlalchemy import db
from indico.core.db.sqlalchemy.logging import apply_db_loggers
from indico.core.db.sqlalchemy.util import delete_all_tables
from indico.web.assets import core_env, register_all_css, register_all_js
from indico.web.flask.templating import EnsureUnicodeExtension, underline
from indico.web.flask.util import (XAccelMiddleware, make_compat_blueprint, ListConverter, url_for, url_rule_to_js,
                                   IndicoConfigWrapper)
from indico.web.flask.wrappers import IndicoFlask

from indico.web.flask.blueprints.legacy import legacy
from indico.web.flask.blueprints.rooms import rooms
from indico.web.flask.blueprints.api import api
from indico.web.flask.blueprints.misc import misc
from indico.web.flask.blueprints.user import user
from indico.web.flask.blueprints.oauth import oauth
from indico.web.flask.blueprints.category import category
from indico.web.flask.blueprints.category_management import category_mgmt
from indico.web.flask.blueprints.event import event_display, event_creation, event_mgmt
from indico.web.flask.blueprints.files import files
from indico.web.flask.blueprints.admin import admin
from indico.web.flask.blueprints.rooms_admin import rooms_admin

BLUEPRINTS = (legacy, api, misc, user, oauth, rooms, category, category_mgmt, event_display,
              event_creation, event_mgmt, files, admin, rooms_admin)
COMPAT_BLUEPRINTS = map(make_compat_blueprint, (misc, user, oauth, rooms, category, category_mgmt, event_display,
                                                event_creation, event_mgmt, files, admin, rooms_admin))

def fix_root_path(app):
    """Fix the app's root path when using namespace packages.

    Flask's get_root_path is not reliable in this case so we derive it from
    __name__ and __file__ instead."""

    # __name__:       'indico.web.flask.app'
    # __file__:  '..../indico/web/flask/app.py'
    # For each dot in the module name we go up one path segment
    up_segments = ['..'] * __name__.count('.')
    app.root_path = os.path.normpath(os.path.join(__file__, *up_segments))

def configure_app(app, set_path=False):
    cfg = Config.getInstance()
    app.config['DEBUG'] = cfg.getDebug()
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SESSION_COOKIE_NAME'] = 'indico_session'
    app.config['PERMANENT_SESSION_LIFETIME'] = cfg.getSessionLifetime()
    app.config['INDICO_SESSION_PERMANENT'] = cfg.getSessionLifetime() > 0
    app.config['INDICO_HTDOCS'] = cfg.getHtdocsDir()
    app.config['INDICO_COMPAT_ROUTES'] = cfg.getRouteOldUrls()
    if set_path:
        base = url_parse(cfg.getBaseURL())
        app.config['SERVER_NAME'] = base.netloc
        if base.path:
            app.config['APPLICATION_ROOT'] = base.path
    app.config['WTF_CSRF_ENABLED'] = False  # for forms of room booking
    static_file_method = cfg.getStaticFileMethod()
    if static_file_method:
        app.config['USE_X_SENDFILE'] = True
        method, args = static_file_method
        if method in ('xsendfile', 'lighttpd'):  # apache mod_xsendfile, lighttpd
            pass
        elif method in ('xaccelredirect', 'nginx'):  # nginx
            if not args or not hasattr(args, 'items'):
                raise ValueError('StaticFileMethod args must be a dict containing at least one mapping')
            app.wsgi_app = XAccelMiddleware(app.wsgi_app, args)
        else:
            raise ValueError('Invalid static file method: %s' % method)

def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), 'indico_config')
    app.add_template_global(config.getSystemIconURL, 'system_icon')
    # Filters (indico functions returning UTF8)
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    # Filters (new ones returning unicode)
    app.add_template_filter(underline)
    # i18n
    app.jinja_env.add_extension('jinja2.ext.i18n')
    app.jinja_env.install_gettext_callables(gettext, ngettext, True)
    # webassets
    app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
    app.jinja_env.assets_environment = core_env

def setup_assets():
    register_all_js(core_env)
    register_all_css(core_env, Config.getInstance().getCssStylesheetName())

def configure_db(app):
    cfg = Config.getInstance()
    db_uri = cfg.getSQLAlchemyDatabaseURI()

    if db_uri is None:
        raise Exception("No proper SQLAlchemy store has been configured."
                        " Please edit your indico.conf")

    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri

    # DB options
    app.config['SQLALCHEMY_ECHO'] = cfg.getSQLAlchemyEcho()
    app.config['SQLALCHEMY_RECORD_QUERIES'] = cfg.getSQLAlchemyRecordQueries()
    app.config['SQLALCHEMY_POOL_SIZE'] = cfg.getSQLAlchemyPoolSize()
    app.config['SQLALCHEMY_POOL_TIMEOUT'] = cfg.getSQLAlchemyPoolTimeout()
    app.config['SQLALCHEMY_POOL_RECYCLE'] = cfg.getSQLAlchemyPoolRecycle()
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = cfg.getSQLAlchemyMaxOverflow()
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = False

    with DBMgr.getInstance().global_connection(commit=True):
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        if cfg.getIsRoomBookingActive():
            minfo.setRoomBookingModuleActive(True)
        else:
            minfo.setRoomBookingModuleActive()

    db.init_app(app)
    apply_db_loggers(app.debug)
    configure_mappers()  # Make sure all backrefs are set
    if cfg.getCreateTables():
        with app.app_context():
            delete_all_tables(db)  # favorable to `drop_all` under foreign keys
            db.create_all()

def extend_url_map(app):
    app.url_map.converters['list'] = ListConverter

def add_handlers(app):
    app.register_error_handler(404, handle_404)
    app.register_error_handler(Exception, handle_exception)

def add_blueprints(app):
    for blueprint in BLUEPRINTS:
        app.register_blueprint(blueprint)

def add_compat_blueprints(app):
    for blueprint in COMPAT_BLUEPRINTS:
        app.register_blueprint(blueprint)

def add_plugin_blueprints(app):
    for blueprint in RHMapMemory()._blueprints:
        if not app.config['INDICO_COMPAT_ROUTES'] and blueprint.name.startswith('compat_'):
            continue
        app.register_blueprint(blueprint)

def handle_404(exception):
    try:
        if re.search(r'\.py(?:/\S+)?$', request.path):
            # While not dangerous per se, we never serve *.py files as static
            raise NotFound
        try:
            return send_from_directory(app.config['INDICO_HTDOCS'], request.path[1:], conditional=True)
        except UnicodeEncodeError:
            raise NotFound
    except NotFound:
        if exception.description == NotFound.description:
            # The default reason is too long and not localized
            msg = (_("Page not found"), _("The page you were looking for doesn't exist."))
        else:
            msg = (_("Page not found"), exception.description)
        return WErrorWSGI(msg).getHTML(), 404

def handle_exception(exception):
    Logger.get('wsgi').exception(exception.message or 'WSGI Exception')
    if app.debug:
        raise
    msg = (str(exception), _("An unexpected error ocurred."))
    return WErrorWSGI(msg).getHTML(), 500

def make_app(set_path=False, db_setup=True):
    # If you are reading this code and wonder how to access the app:
    # >>> from flask import current_app as app
    # This only works while inside an application context but you really shouldn't have any
    # reason to access it outside this method without being inside an application context.
    # When set_path is enabled, SERVER_NAME and APPLICATION_ROOT are set according to BaseURL
    # so URLs can be generated without an app context, e.g. in the indico shell
    app = IndicoFlask('indico', static_folder=None, template_folder='web/templates')
    fix_root_path(app)
    configure_app(app, set_path)
    setup_jinja(app)
    setup_assets()

    if db_setup:
        configure_db(app)

    extend_url_map(app)
    add_handlers(app)
    add_blueprints(app)
    if app.config['INDICO_COMPAT_ROUTES']:
        add_compat_blueprints(app)
    add_plugin_blueprints(app)
    return app
<|endoftext|>


<commit_before># coding: utf-8
# -----------------------------------------------------------------------------
# Copyright 2015 Esri
# 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.
# -----------------------------------------------------------------------------

# ==================================================
# IncidentDensityTestCase.py
# --------------------------------------------------
# requirments: ArcGIS X.X, Python 2.7 or Python 3.4
# author: ArcGIS Solutions
# company: Esri
# ==================================================
# history:
# 12/16/2015 - JH - initial creation
# ==================================================

import unittest
import arcpy
import os
import UnitTestUtilities
import Configuration
import DataDownload

class IncidentDensityTestCase(unittest.TestCase):
    ''' Test all tools and methods related to the Incident Density tool
    in the Incident Analysis toolbox'''

    inputPointFeatures = None
    inputBoundaryFeatures = None

    def setUp(self):
        if Configuration.DEBUG == True: print("     IncidentDensityTestCase.setUp")
        UnitTestUtilities.checkArcPy()

        Configuration.incidentDataPath = DataDownload.runDataDownload(Configuration.patternsPaths, Configuration.incidentGDBName, Configuration.incidentURL)
        if (Configuration.incidentScratchGDB == None) or (not arcpy.Exists(Configuration.incidentScratchGDB)):
            Configuration.incidentScratchGDB = UnitTestUtilities.createScratch(Configuration.incidentDataPath)
        Configuration.incidentInputGDB = os.path.join(Configuration.incidentDataPath, Configuration.incidentGDBName)

        UnitTestUtilities.checkFilePaths([Configuration.incidentDataPath, Configuration.incidentInputGDB, Configuration.patterns_ProToolboxPath, Configuration.patterns_DesktopToolboxPath])

        self.inputPointFeatures = os.path.join(Configuration.incidentInputGDB, "Incidents")
        self.inputBoundaryFeatures = os.path.join(Configuration.incidentInputGDB, "Districts")

    def tearDown(self):
        if Configuration.DEBUG == True: print("     IncidentDensityTestCase.tearDown")
        UnitTestUtilities.deleteScratch(Configuration.incidentScratchGDB)

    def test_incident_density_pro(self):
        if Configuration.DEBUG == True: print("     IncidentDensityTestCase.test_incident_density_pro")
        arcpy.AddMessage("Testing Incident Density (Pro).")
        self.test_incident_density(Configuration.patterns_ProToolboxPath)

    def test_incident_density_desktop(self):
        if Configuration.DEBUG == True: print("     IncidentDensityTestCase.test_incident_density_desktop")
        arcpy.AddMessage("Testing Incident Density (Desktop).")
        self.test_incident_density(Configuration.patterns_DesktopToolboxPath)

    def test_incident_density(self, toolboxPath):
        try:
            if Configuration.DEBUG == True: print("     IncidentDensityTestCase.test_incident_density")

            arcpy.CheckOutExtension("Spatial")
            arcpy.ImportToolbox(toolboxPath, "iaTools")

            runToolMsg = "Running tool (Incident Density)"
            arcpy.AddMessage(runToolMsg)
            Configuration.Logger.info(runToolMsg)

            outputDensity = os.path.join(Configuration.incidentScratchGDB, "outputDensity")
            arcpy.IncidentDensity_iaTools(self.inputPointFeatures, self.inputBoundaryFeatures, outputDensity)
            arcpy.CheckInExtension("Spatial")
            self.assertTrue(arcpy.Exists(outputDensity))

        except arcpy.ExecuteError:
            UnitTestUtilities.handleArcPyError()

        except:
            UnitTestUtilities.handleGeneralError()

            <commit_msg>Updated IncidentDensityTestCase for two method test only<commit_after># coding: utf-8
'''
-----------------------------------------------------------------------------
Copyright 2016 Esri
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.
-----------------------------------------------------------------------------

==================================================
IncidentDensityTestCase.py
--------------------------------------------------
requirments: ArcGIS X.X, Python 2.7 or Python 3.4
author: ArcGIS Solutions
company: Esri
==================================================
history:
12/16/2015 - JH - initial creation
==================================================
'''

import unittest
import arcpy
import os
import UnitTestUtilities
import Configuration
import DataDownload

class IncidentDensityTestCase(unittest.TestCase):
    ''' Test all tools and methods related to the Incident Density tool
    in the Incident Analysis toolbox'''

    inputPointFeatures = None
    inputBoundaryFeatures = None

    def setUp(self):
        if Configuration.DEBUG == True: print(".....IncidentDensityTestCase.setUp")
        UnitTestUtilities.checkArcPy()

        Configuration.incidentDataPath = DataDownload.runDataDownload(Configuration.patternsPaths, Configuration.incidentGDBName, Configuration.incidentURL)
        if (Configuration.incidentScratchGDB == None) or (not arcpy.Exists(Configuration.incidentScratchGDB)):
            Configuration.incidentScratchGDB = UnitTestUtilities.createScratch(Configuration.incidentDataPath)
        Configuration.incidentInputGDB = os.path.join(Configuration.incidentDataPath, Configuration.incidentGDBName)

        UnitTestUtilities.checkFilePaths([Configuration.incidentDataPath, Configuration.incidentInputGDB, Configuration.patterns_ProToolboxPath, Configuration.patterns_DesktopToolboxPath])

        self.inputPointFeatures = os.path.join(Configuration.incidentInputGDB, "Incidents")
        self.inputBoundaryFeatures = os.path.join(Configuration.incidentInputGDB, "Districts")

    def tearDown(self):
        if Configuration.DEBUG == True: print(".....IncidentDensityTestCase.tearDown")
        UnitTestUtilities.deleteScratch(Configuration.incidentScratchGDB)

    def test_incident_density_pro(self):
        '''test_incident_density_pro'''
        try:
            if Configuration.DEBUG == True: print(".....IncidentDensityTestCase.test_incident_density_pro")
            arcpy.CheckOutExtension("Spatial")
            arcpy.ImportToolbox(Configuration.patterns_ProToolboxPath, "iaTools")
            runToolMsg = "Running tool (Incident Density)"
            arcpy.AddMessage(runToolMsg)
            Configuration.Logger.info(runToolMsg)
            outputDensity = os.path.join(Configuration.incidentScratchGDB, "outputDensity")
            arcpy.IncidentDensity_iaTools(self.inputPointFeatures, self.inputBoundaryFeatures, outputDensity)
            arcpy.CheckInExtension("Spatial")
            self.assertTrue(arcpy.Exists(outputDensity))
        except arcpy.ExecuteError:
            UnitTestUtilities.handleArcPyError()
        except:
            UnitTestUtilities.handleGeneralError()

    def test_incident_density_desktop(self):
        '''test_incident_density_desktop'''
        try:
            if Configuration.DEBUG == True: print(".....IncidentDensityTestCase.test_incident_density_desktop")
            arcpy.CheckOutExtension("Spatial")
            arcpy.ImportToolbox(Configuration.patterns_DesktopToolboxPath, "iaTools")
            runToolMsg = "Running tool (Incident Density)"
            arcpy.AddMessage(runToolMsg)
            Configuration.Logger.info(runToolMsg)
            outputDensity = os.path.join(Configuration.incidentScratchGDB, "outputDensity")
            arcpy.IncidentDensity_iaTools(self.inputPointFeatures, self.inputBoundaryFeatures, outputDensity)
            arcpy.CheckInExtension("Spatial")
            self.assertTrue(arcpy.Exists(outputDensity))
        except arcpy.ExecuteError:
            UnitTestUtilities.handleArcPyError()
        except:
            UnitTestUtilities.handleGeneralError()
<|endoftext|>


<commit_before>try:
    import numpy as np
    numpy = True
except ImportError:
    print("The module numpy was not found.  Probabilities will not be reported in results.")

import pairsClasses as p
from strategies.chrisStrategies import FoldLowWithHigh
from strategies.chrisStrategies import Expectation
from random import shuffle

strategies = [FoldLowWithHigh(3,1),
              FoldLowWithHigh(4,8),
              Expectation()]
strat_names = ["Folder_3", "Folder_4_8", "Expectation"]
n_strats = len(strategies)

for i in range(n_strats):
    strategies[i].tourney_index = i
    strategies[i].tourney_name = strat_names[i]

losers = []
for i in range(100):
    # defaults to 5 players that always hit
    d = p.Dealer(n_strats)
    shuffle(strategies)
    for i in range(n_strats):
        d.gameState.players[i].strategy = strategies[i]
    # play a game and get the index of the losing strategy
    lost = d.gameState.players[d.play()].strategy.tourney_index
    losers.append(lost)

data = []
for i in range(n_strats):
    data.append(losers.count(i))

print("Games Lost:")
for i in range(n_strats):
    print(strat_names[i] + ":\t" + str(data[i]))

if numpy:
    prior = np.repeat(10, n_strats)
    posterior = prior + np.array(data)
    N = 10000
    draws = np.random.dirichlet(posterior, N)
    best = np.bincount(np.argmin(draws, axis = 1), minlength = n_strats) / N
    worst = np.bincount(np.argmax(draws, axis = 1), minlength = n_strats) / N

    print("\n\n\t\tP(best)\tP(worst)")
    for i in range(n_strats):
        print(strat_names[i] + "\t" + '%.2f' % best[i] + "\t" + '%.2f' % worst[i])

<commit_msg>Made tourney a function and added periodic updates.<commit_after>'''
Tourney.py
Runs a tournament of continuous pairs.
Dealer class and other game mechanics imported from pairsClasses.
Strategies to play in the tournament need to be imported, initialized,
and passed to tournament function.
'''
numpy = False
try:
    import numpy as np
    numpy = True
except ImportError:
    print("The module numpy was not found.  Probabilities will not be reported in results.")
import pairsClasses as p
from random import shuffle

# Specify strategies to import here
from strategies.chrisStrategies import FoldLowWithHigh
from strategies.chrisStrategies import Expectation

# Initalize strategies in list
strategies = [FoldLowWithHigh(3,1),
              FoldLowWithHigh(4,8),
              Expectation()]

# name strategies for reporting
strat_names = ["Folder_3", "Folder_4_8", "Expectation"]

# Remaining code does not need to change between tourneys
n_strats = len(strategies)

for i in range(n_strats):
    strategies[i].tourney_index = i
    strategies[i].tourney_name = strat_names[i]

losers = []

def tourney(strategies, games = 500, check = 50, prob = 0.95, prior = 500):
    early = False
    for i in range(games):
        if not i % check:
            if summary(i, prob, prior):
                early = True
                break
        d = p.Dealer(n_strats)
        shuffle(strategies)
        for j in range(n_strats):
            d.gameState.players[j].strategy = strategies[j]
        # play a game and get the index of the losing strategy
        lost = d.gameState.players[d.play()].strategy.tourney_index
        losers.append(lost)
    if not early:
        summary(games, 1, prior)

def summary(games, prob, prior):
    print("--------------------------------")
    print("Games Played:\t" + str(games))
    print("\n\t\tLost\tPercent")
    data = []
    for i in range(n_strats):
        data.append(losers.count(i))
        if games == 0:
            games = 1
        print(strat_names[i] + "\t" + str(data[i]) + "\t" + '%.2f' % (data[i] / games))

    if numpy:
        prior = np.repeat(prior, n_strats)
        posterior = prior + np.array(data)
        N = 10000
        draws = np.random.dirichlet(posterior, N)
        best = np.bincount(np.argmin(draws, axis = 1), minlength = n_strats) / N
        worst = np.bincount(np.argmax(draws, axis = 1), minlength = n_strats) / N

        print("\n\t\tP(best)\tP(worst)")
        for i in range(n_strats):
            print(strat_names[i] + "\t" + '%.2f' % best[i] + "\t" + '%.2f' % worst[i])
        if max(best) > prob and max(worst) > prob:
            print("Stopping early due to high probabilities of best and worst.  (Threshold set to " + str(prob) + ")")
            return True

tourney(strategies)
<|endoftext|>


<commit_before>#!/usr/bin/env python3

from time import strptime, mktime
from datetime import timedelta
import argparse

def OpenFile(InputFile):
    """Try to open the data file, raise an error if opening fails"""
    try:
        InputData = open(InputFile)
    except IOError as e:
        print("Got IOError, '{0}: {1}'".format(e.errno, e.strerror))
    else:
        return(InputData)

def GetTime(TimeType, PmSuspendFile):
    """Return a list of timestamps that the computer was suspended or resumed
    on. If the TimeType parameter is 'suspend', search for suspend string,
    if it is 'resume' search for resume string, cut the lines at
    DateFieldLength value
    """
    DataFile = OpenFile(PmSuspendFile)
    Time = list()

    for line in DataFile:
        if TimeType == 'suspend':
            if 'Running hooks for suspend' in line:
                Time.append(line[:DateFieldLength])
        elif TimeType == 'resume':
            if 'Running hooks for resume' in line:
                Time.append(line[:DateFieldLength])

    return(Time)

def GetDuration(PmSuspendFile):
    """Calculate the time the computer spent in suspend, returns Duration,
    SuspendTime and TimeDelta
    """
    Duration = list()
    SuspendTime = GetTime('suspend', PmSuspendFile)
    ResumeTime = GetTime('resume', PmSuspendFile)

    for (a, b) in zip(SuspendTime, ResumeTime):
        elema = mktime(strptime(a, DateFormat))
        elemb = mktime(strptime(b, DateFormat))
        elemc = timedelta(seconds=elemb - elema)
        Duration.append(elemc)

    return(Duration, SuspendTime, ResumeTime)

def PrintConsole(PmSuspendFile):
    """Print the gathered info out to console"""
    SuspendDuration, SuspendTime, ResumeTime = GetDuration(PmSuspendFile)

    if len(SuspendTime) == len(ResumeTime):

        print('{0:5}\t{1:30}\t{2:30}\t{3:10}'.format('Index', 'Suspend time',
              'Resume time', 'Duration'))

        for index, (suspend, resume, duration) in enumerate(
                zip(SuspendTime, ResumeTime, SuspendDuration)):
            print('{0:5}\t{1:30}\t{2:30}\t{3:10}'.format(index, suspend,
                                                         resume,
                                                         str(duration)))
    else:
        print("The length of SuspendTime and ResumeTime lists differs!")

def DoIt():
    """
    Set up the available program options
    Call the proper functions with proper parameters depending on user
    input
    """
    parser = argparse.ArgumentParser()

    parser.add_argument('-d', '--date', dest='DateFormat', help='Specify '
                        'the date format', default='%a %b %d %H:%M:%S %Z %Y',
                        type=str, action='store')
    parser.add_argument('-f', '--file', dest='PmSuspendFile', help='Specify '
                        'which file name to parse',
                        default='/var/log/pm-suspend.log', type=str,
                        action='store')
    parser.add_argument('-l', '--length', dest='DateFieldLength',
                        help='Specify the length of the date field in the '
                        'file', default=29, type=int, action='store')
    parser.add_argument('-o', '--output', dest='Output', help='Specify the '
                        'output destination', default='console', type=str,
                        action='store')

    args = parser.parse_args()

    if not args.DateFormat:
        parser.print_help()
    else:
        global DateFormat
        DateFormat = args.DateFormat

    if not args.DateFieldLength:
        parser.print_help()
    else:
        global DateFieldLength
        DateFieldLength = args.DateFieldLength

    if args.Output == 'console' and args.PmSuspendFile:
        PrintConsole(args.PmSuspendFile)

if __name__ == "__main__":
    DoIt()
<commit_msg>Per request from @spoljo, try to display the battery information if -b flag is specified, rearrange imports alphabetically<commit_after>#!/usr/bin/env python3

import argparse
from datetime import timedelta, datetime
from glob import glob
from time import strptime, mktime

def OpenFile(InputFile):
    """Try to open the data file, raise an error if opening fails"""
    try:
        InputData = open(InputFile)
    except IOError as e:
        print("Got IOError, '{0}: {1}'".format(e.errno, e.strerror))
    else:
        return(InputData)

def GetTime(TimeType, PmSuspendFile):
    """Return a list of timestamps that the computer was suspended or resumed
    on. If the TimeType parameter is 'suspend', search for suspend string,
    if it is 'resume' search for resume string, cut the lines at
    DateFieldLength value
    """
    DataFile = OpenFile(PmSuspendFile)
    Time = list()

    for line in DataFile:
        if TimeType == 'suspend':
            if 'Running hooks for suspend' in line:
                Time.append(line[:DateFieldLength])
        elif TimeType == 'resume':
            if 'Running hooks for resume' in line:
                Time.append(line[:DateFieldLength])

    return(Time)

def GetBatteryData(BatteryChargeFile):
    ChargeFile = OpenFile(BatteryChargeFile)
    TimeBatteryCharge = list()

    for line in ChargeFile:
        a, b, c = line.split()
        a = datetime.fromtimestamp(int(a)).strftime('%d.%m.%Y %H:%M:%S')
        TimeBatteryCharge.append([a, b, c])

    return(TimeBatteryCharge)

def PrintBatteryConsole(BatteryChargeFile):
    ChargeInfo = GetBatteryData(BatteryChargeFile)

    Time = list()
    Battery = list()
    State = list()
    for elem in ChargeInfo:
        Time.append(elem[0])
        Battery.append(elem[1])
        State.append(elem[2])

    print('{0:5}\t{1:25}\t{2:10}\t{3:20}'.format('Index', 'Time',
                                                 'Percentage', 'State'))
    if len(Time) == len(Battery) and len(Time) == len(State):
        for index, (a, b, c) in enumerate(zip(Time, Battery, State)):
            print('{0:5}\t{1:25}\t{2:10}\t{3:20}'.format(index, a, b, c))

def GetDuration(PmSuspendFile):
    """Calculate the time the computer spent in suspend, returns Duration,
    SuspendTime and TimeDelta
    """
    Duration = list()
    SuspendTime = GetTime('suspend', PmSuspendFile)
    ResumeTime = GetTime('resume', PmSuspendFile)

    for (a, b) in zip(SuspendTime, ResumeTime):
        elema = mktime(strptime(a, DateFormat))
        elemb = mktime(strptime(b, DateFormat))
        elemc = timedelta(seconds=elemb - elema)
        Duration.append(elemc)

    return(Duration, SuspendTime, ResumeTime)

def PrintConsole(PmSuspendFile):
    """Print the gathered info out to console"""
    SuspendDuration, SuspendTime, ResumeTime = GetDuration(PmSuspendFile)

    if len(SuspendTime) == len(ResumeTime):

        print('{0:5}\t{1:30}\t{2:30}\t{3:10}'.format('Index', 'Suspend time',
              'Resume time', 'Duration'))

        for index, (suspend, resume, duration) in enumerate(
                zip(SuspendTime, ResumeTime, SuspendDuration)):
            print('{0:5}\t{1:30}\t{2:30}\t{3:10}'.format(index, suspend,
                                                         resume,
                                                         str(duration)))
    else:
        print("The length of SuspendTime and ResumeTime lists differs!")

def DoIt():
    """
    Set up the available program options
    Call the proper functions with proper parameters depending on user
    input
    """
    parser = argparse.ArgumentParser()

    parser.add_argument('-b', '--battery', dest='Battery', help='Show the '
                        'battery charging/discharging information',
                        action='store_true')
    parser.add_argument('-d', '--date', dest='DateFormat', help='Specify '
                        'the date format', default='%a %b %d %H:%M:%S %Z %Y',
                        type=str, action='store')
    parser.add_argument('-f', '--file', dest='PmSuspendFile', help='Specify '
                        'which file name to parse',
                        default='/var/log/pm-suspend.log', type=str,
                        action='store')
    parser.add_argument('-l', '--length', dest='DateFieldLength',
                        help='Specify the length of the date field in the '
                        'file', default=29, type=int, action='store')
    parser.add_argument('-o', '--output', dest='Output', help='Specify the '
                        'output destination', default='console', type=str,
                        action='store')

    args = parser.parse_args()

    if not args.DateFormat:
        parser.print_help()
    else:
        global DateFormat
        DateFormat = args.DateFormat

    if not args.DateFieldLength:
        parser.print_help()
    else:
        global DateFieldLength
        DateFieldLength = args.DateFieldLength

    if args.Output == 'console' and args.PmSuspendFile:
        PrintConsole(args.PmSuspendFile)

    if args.Battery:
        try:
            BatteryInfoFile = glob('/var/lib/upower/history-charge-*.dat')
        except IOError as e:
            print("Got IOError, '{0}: {1}'".format(e.errno, e.strerror))
        else:
            PrintBatteryConsole(BatteryInfoFile[0])

if __name__ == "__main__":
    DoIt()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import os
from glob import glob

#-------------------
# To skip wrapping single precision atlas/lapack routines, set
# the following flag to True:

skip_single_routines = 0

#--------------------

tmpl_empty_clapack_pyf = '''
python module clapack
  usercode void empty_module(void) {}
  interface
    subroutine empty_module()
      intent(c) empty_module
    end subroutine empty_module
  end interface
end python module clapack
'''

def configuration(parent_package='',parent_path=None):
    from scipy_distutils.core import Extension
    from scipy_distutils.misc_util import dot_join, get_path, default_config_dict
    from scipy_distutils.system_info import get_info, dict_append

    package = 'lapack'
    config = default_config_dict(package,parent_package)
    local_path = get_path(__name__,parent_path)
    def local_join(*paths):
        return os.path.join(*((local_path,)+paths))
    def local_glob(path):
        return glob(os.path.join(local_path,path))

    numpy_info = get_info('numpy',notfound_action=2)
    lapack_opt = get_info('lapack_opt',notfound_action=2)

    atlas_version = ([v[3:-3] for k,v in lapack_opt.get('define_macros',[]) \
                      if k=='ATLAS_INFO']+[None])[0]
    if atlas_version:
        print 'ATLAS version',atlas_version

    target_dir = ''
    skip_names = {'clapack':[],'flapack':[]}
    if skip_single_routines:
        target_dir = 'dbl'
        skip_names['clapack'].extend(\
            'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\
            ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\
            ' slauum clauum strtri ctrtri'.split())
        skip_names['flapack'].extend(skip_names['clapack'])
        skip_names['flapack'].extend(\
            'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\
            ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees'
            ' sggev cggev'.split())

    if atlas_version=='3.2.1_pre3.3.6':
        target_dir = join(target_dir,'atlas321')
        skip_names['clapack'].extend(\
            'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\
            ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split())
    elif atlas_version>'3.4.0' and atlas_version<='3.5.12':
        skip_names['clapack'].extend('cpotrf zpotrf'.split())

    # flapack:
    ext_args = {}
    dict_append(ext_args,
                name = dot_join(parent_package,package,'flapack'),
                sources = [local_join('flapack.pyf.src')],
                depends = [__file__]+local_glob('flapack_*.pyf.src'),
                f2py_options = ['skip:']+skip_names['flapack']+[':'])
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    # clapack:
    def get_clapack_source(ext, build_dir):
        name = ext.name.split('.')[-1]
        assert name=='clapack',`name`
        if atlas_version is None:
            target = join(build_dir,target_dir,'clapack.pyf')
            from distutils.dep_util import newer
            if newer(__file__,target):
                f = open(source,'w')
                f.write(tmpl_empty_clapack_pyf)
                f.close()
        else:
            target = ext.depends[0]
            assert os.path.basename(target)=='clapack.pyf.src'
        return target

    ext_args = {}
    dict_append(ext_args,
                name = dot_join(parent_package,package,'clapack'),
                sources = [get_clapack_source],
                depends =  [local_join('clapack.pyf.src')] \
                + local_glob('clapack_*.pyf.src'),
                f2py_options = ['skip:']+skip_names['clapack']+[':'])
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    # calc_lwork:
    ext_args = {'name':dot_join(parent_package,package,'calc_lwork'),
                'sources':[local_join('calc_lwork.f')],
                }
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    config['ext_modules'].append(Extension(**ext_args))

    # atlas_version:
    ext_args = {'name':dot_join(parent_package,package,'atlas_version'),
                'sources':[os.path.join(local_path,'atlas_version.c')]}
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    return config

if __name__ == '__main__':
    from scipy_distutils.core import setup

    setup(**configuration(parent_path=''))
<commit_msg>Fixed typos.<commit_after>#!/usr/bin/env python

import os
from glob import glob

#-------------------
# To skip wrapping single precision atlas/lapack routines, set
# the following flag to True:

skip_single_routines = 0

#--------------------

tmpl_empty_clapack_pyf = '''
python module clapack
  usercode void empty_module(void) {}
  interface
    subroutine empty_module()
      intent(c) empty_module
    end subroutine empty_module
  end interface
end python module clapack
'''

def configuration(parent_package='',parent_path=None):
    from scipy_distutils.core import Extension
    from scipy_distutils.misc_util import dot_join, get_path, default_config_dict
    from scipy_distutils.system_info import get_info, dict_append

    package = 'lapack'
    config = default_config_dict(package,parent_package)
    local_path = get_path(__name__,parent_path)
    def local_join(*paths):
        return os.path.join(*((local_path,)+paths))
    def local_glob(path):
        return glob(os.path.join(local_path,path))

    numpy_info = get_info('numpy',notfound_action=2)
    lapack_opt = get_info('lapack_opt',notfound_action=2)

    atlas_version = ([v[3:-3] for k,v in lapack_opt.get('define_macros',[]) \
                      if k=='ATLAS_INFO']+[None])[0]
    if atlas_version:
        print 'ATLAS version',atlas_version

    target_dir = ''
    skip_names = {'clapack':[],'flapack':[]}
    if skip_single_routines:
        target_dir = 'dbl'
        skip_names['clapack'].extend(\
            'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\
            ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\
            ' slauum clauum strtri ctrtri'.split())
        skip_names['flapack'].extend(skip_names['clapack'])
        skip_names['flapack'].extend(\
            'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\
            ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees'
            ' sggev cggev'.split())

    if atlas_version=='3.2.1_pre3.3.6':
        target_dir = os.path.join(target_dir,'atlas321')
        skip_names['clapack'].extend(\
            'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\
            ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split())
    elif atlas_version>'3.4.0' and atlas_version<='3.5.12':
        skip_names['clapack'].extend('cpotrf zpotrf'.split())

    # flapack:
    ext_args = {}
    dict_append(ext_args,
                name = dot_join(parent_package,package,'flapack'),
                sources = [local_join('flapack.pyf.src')],
                depends = [__file__]+local_glob('flapack_*.pyf.src'),
                f2py_options = ['skip:']+skip_names['flapack']+[':'])
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    # clapack:
    def get_clapack_source(ext, build_dir):
        name = ext.name.split('.')[-1]
        assert name=='clapack',`name`
        if atlas_version is None:
            target = os.path.join(build_dir,target_dir,'clapack.pyf')
            from distutils.dep_util import newer
            if newer(__file__,target):
                f = open(source,'w')
                f.write(tmpl_empty_clapack_pyf)
                f.close()
        else:
            target = ext.depends[0]
            assert os.path.basename(target)=='clapack.pyf.src'
        return target

    ext_args = {}
    dict_append(ext_args,
                name = dot_join(parent_package,package,'clapack'),
                sources = [get_clapack_source],
                depends =  [local_join('clapack.pyf.src')] \
                + local_glob('clapack_*.pyf.src'),
                f2py_options = ['skip:']+skip_names['clapack']+[':'])
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    # calc_lwork:
    ext_args = {'name':dot_join(parent_package,package,'calc_lwork'),
                'sources':[local_join('calc_lwork.f')],
                }
    dict_append(ext_args,**numpy_info)
    dict_append(ext_args,**lapack_opt)
    config['ext_modules'].append(Extension(**ext_args))

    # atlas_version:
    ext_args = {'name':dot_join(parent_package,package,'atlas_version'),
                'sources':[os.path.join(local_path,'atlas_version.c')]}
    dict_append(ext_args,**lapack_opt)
    ext = Extension(**ext_args)
    config['ext_modules'].append(ext)

    return config

if __name__ == '__main__':
    from scipy_distutils.core import setup

    setup(**configuration(parent_path=''))
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import re

class Automake(AutotoolsPackage, GNUMirrorPackage):
    """Automake -- make file builder part of autotools"""

    homepage = 'https://www.gnu.org/software/automake/'
    gnu_mirror_path = 'automake/automake-1.15.tar.gz'

    version('1.16.3', sha256='ce010788b51f64511a1e9bb2a1ec626037c6d0e7ede32c1c103611b9d3cba65f')
    version('1.16.2', sha256='b2f361094b410b4acbf4efba7337bdb786335ca09eb2518635a09fb7319ca5c1')
    version('1.16.1', sha256='608a97523f97db32f1f5d5615c98ca69326ced2054c9f82e65bade7fc4c9dea8')
    version('1.15.1', sha256='988e32527abe052307d21c8ca000aa238b914df363a617e38f4fb89f5abf6260')
    version('1.15',   sha256='7946e945a96e28152ba5a6beb0625ca715c6e32ac55f2e353ef54def0c8ed924')
    version('1.14.1', sha256='814c2333f350ce00034a1fe718e0e4239998ceea7b0aff67e9fd273ed6dfc23b')
    version('1.13.4', sha256='4c93abc0bff54b296f41f92dd3aa1e73e554265a6f719df465574983ef6f878c')
    version('1.11.6', sha256='53dbf1945401c43f4ce19c1971baecdbf8bc32e0f37fa3f49fe7b6992d0d2030')

    depends_on('autoconf', type='build')
    depends_on('perl', type=('build', 'run'))

    build_directory = 'spack-build'

    tags = ['build-tools']

    executables = ['^automake$']

    @classmethod
    def determine_version(cls, exe):
        output = Executable(exe)('--version', output=str, error=str)
        match = re.search(r'GNU automake\)\s+(\S+)', output)
        return match.group(1) if match else None

    def patch(self):
        # The full perl shebang might be too long
        files_to_be_patched_fmt = 'bin/{0}.in'
        if '@:1.15.1' in self.spec:
            files_to_be_patched_fmt = 't/wrap/{0}.in'

        if '@1.16.3:' in self.spec:
            shebang_string = '^#!@PERL@'
        else:
            shebang_string = '^#!@PERL@ -w'

        for file in ('aclocal', 'automake'):
            filter_file(shebang_string,
                        '#!/usr/bin/env perl',
                        files_to_be_patched_fmt.format(file))

    def _make_executable(self, name):
        return Executable(join_path(self.prefix.bin, name))

    def setup_dependent_package(self, module, dependent_spec):
        # Automake is very likely to be a build dependency,
        # so we add the tools it provides to the dependent module
        executables = ['aclocal', 'automake']
        for name in executables:
            setattr(module, name, self._make_executable(name))
<commit_msg>automake: New version 1.16.5 (#28299)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import re

class Automake(AutotoolsPackage, GNUMirrorPackage):
    """Automake -- make file builder part of autotools"""

    homepage = 'https://www.gnu.org/software/automake/'
    gnu_mirror_path = 'automake/automake-1.15.tar.gz'

    version('1.16.5', sha256='07bd24ad08a64bc17250ce09ec56e921d6343903943e99ccf63bbf0705e34605')
    version('1.16.3', sha256='ce010788b51f64511a1e9bb2a1ec626037c6d0e7ede32c1c103611b9d3cba65f')
    version('1.16.2', sha256='b2f361094b410b4acbf4efba7337bdb786335ca09eb2518635a09fb7319ca5c1')
    version('1.16.1', sha256='608a97523f97db32f1f5d5615c98ca69326ced2054c9f82e65bade7fc4c9dea8')
    version('1.15.1', sha256='988e32527abe052307d21c8ca000aa238b914df363a617e38f4fb89f5abf6260')
    version('1.15',   sha256='7946e945a96e28152ba5a6beb0625ca715c6e32ac55f2e353ef54def0c8ed924')
    version('1.14.1', sha256='814c2333f350ce00034a1fe718e0e4239998ceea7b0aff67e9fd273ed6dfc23b')
    version('1.13.4', sha256='4c93abc0bff54b296f41f92dd3aa1e73e554265a6f719df465574983ef6f878c')
    version('1.11.6', sha256='53dbf1945401c43f4ce19c1971baecdbf8bc32e0f37fa3f49fe7b6992d0d2030')

    depends_on('autoconf', type='build')
    depends_on('perl', type=('build', 'run'))

    build_directory = 'spack-build'

    tags = ['build-tools']

    executables = ['^automake$']

    @classmethod
    def determine_version(cls, exe):
        output = Executable(exe)('--version', output=str, error=str)
        match = re.search(r'GNU automake\)\s+(\S+)', output)
        return match.group(1) if match else None

    def patch(self):
        # The full perl shebang might be too long
        files_to_be_patched_fmt = 'bin/{0}.in'
        if '@:1.15.1' in self.spec:
            files_to_be_patched_fmt = 't/wrap/{0}.in'

        if '@1.16.3:' in self.spec:
            shebang_string = '^#!@PERL@'
        else:
            shebang_string = '^#!@PERL@ -w'

        for file in ('aclocal', 'automake'):
            filter_file(shebang_string,
                        '#!/usr/bin/env perl',
                        files_to_be_patched_fmt.format(file))

    def _make_executable(self, name):
        return Executable(join_path(self.prefix.bin, name))

    def setup_dependent_package(self, module, dependent_spec):
        # Automake is very likely to be a build dependency,
        # so we add the tools it provides to the dependent module
        executables = ['aclocal', 'automake']
        for name in executables:
            setattr(module, name, self._make_executable(name))
<|endoftext|>


<commit_before>import csv
import unittest
from infrastructure import models
from scorecard.models import Geography
from django.db import transaction
import xlrd
import logging

logger = logging.Logger(__name__)

headers = [
    x.strip()
    for x in """
    Function, Project Description, Project Number,
    Type, MTSF Service Outcome, IUDF,
    Own Strategic Objectives, Asset Class, Asset Sub-Class,
    Ward Location, GPS Longitude, GPS Latitude""".strip().split(",")
]
#Audited Outcome 2017/18,
#Full Year Forecast 2018/19,
#Budget year 2019/20,
#Budget year 2020/21,
#Budget year 2021/22

def float_or_none(val):
    try:
        return float(val)
    except ValueError:
        return None

def check_file(fp):
    reader = csv.DictReader(fp)
    return check_headers(reader.fieldnames)

def check_headers(fields):
    missing_headers = [h for h in headers if h not in fields]
    if len(missing_headers) > 0:
        raise ValueError(
            "The following fields are missing from the data source: %s" % missing_headers
        )

@transaction.atomic
def load_excel(filename):
    def clean(s):
        if type(s) == str:
            return s.strip()
        else:
            return s

    def fix_broken_headers(header_row):
        header_row = [r.replace("\n", " ") for r in header_row]
        header_row = [r.replace("Project Decription", "Project Description") for r in header_row]
        return header_row

    def sheet_parser(sheet):
        skip = True
        header_row = []
        for idx in range(0, sheet.nrows):
            row = [clean(sheet.cell(idx, col).value) for col in range(0, sheet.ncols)]

            val = sheet.cell(idx, 0).value.strip()
            if val != "Function" and skip:
                continue
            elif val == "Function":
                header_row = fix_broken_headers(row)
                check_headers(header_row)
                skip = False
                continue
            elif val == "":
                return

            yield dict(zip(header_row, row))

    workbook = xlrd.open_workbook(filename)
    print(workbook.sheets)
    for sheet in workbook.sheets():
        geo_code = sheet.name
        logger.info("Processing sheet: %s" % sheet.name)
        if Geography.objects.filter(geo_code=geo_code).count() == 0:
            raise CommandError("%s is an unknown Geography. Please ensure that this Geography exists in the database" % geo_code)
        geography = Geography.objects.get(geo_code=geo_code)
        load_file(geography, sheet_parser(sheet))

def load_csv(geography, fp):
    check_file(fp)
    fp.seek(0)
    reader = csv.DictReader(fp)
    return load_file(geography, reader)

@transaction.atomic
def load_file(geography, reader):
    print(geography.geo_code)

    for idx, row in enumerate(reader):
        try:
            p = models.Project.objects.create(
                geography=geography,
                function=row["Function"],
                project_description=row["Project Description"],
                project_number=row["Project Number"],
                project_type=row["Type"],
                mtsf_service_outcome=row["MTSF Service Outcome"],
                iudf=row["IUDF"],
                own_strategic_objectives=row["Own Strategic Objectives"],
                asset_class=row["Asset Class"],
                asset_subclass=row["Asset Sub-Class"],
                ward_location=row["Ward Location"],
                longitude=float_or_none(row["GPS Longitude"]),
                latitude=float_or_none(row["GPS Latitude"]),
            )

            additional_fields = [k for k in row.keys() if k not in headers]
            for field in additional_fields:
                amount = row[field]
                create_expenditure(p, field, amount)
        except Exception as e:
            raise ValueError("Error loading data in row: %d - %s" % (idx + 2, row))
    return idx + 1

def create_expenditure(project, finance_phase, amount):
    phase, year = create_finance_phase(finance_phase)
    try:
        expenditure = models.Expenditure.objects.create(
            project=project,
            budget_phase=phase,
            financial_year=year,
            amount=float(amount),
        )
        return True
    except ValueError:
        return False

def create_finance_phase(s):
    phase, year = parse_finance_phase(s)
    fy, _ = models.FinancialYear.objects.get_or_create(budget_year=year)
    phase, _ = models.BudgetPhase.objects.get_or_create(name=phase)

    return phase, fy

def parse_finance_phase(s):
    parts = s.split()
    year = parts[-1]

    y1, y2 = year.split("/")
    if len(y2) == 2:
        y2 = str(int(y1) + 1)

    year = "%s/%s" % (y1, y2)

    return " ".join(parts[0:-1]), year
<commit_msg>prepare quarterly data for chart plotting<commit_after>import csv
import unittest
from infrastructure import models
from scorecard.models import Geography
from django.db import transaction
import xlrd
import logging
import json

logger = logging.Logger(__name__)

headers = [
    x.strip()
    for x in """
    Function, Project Description, Project Number,
    Type, MTSF Service Outcome, IUDF,
    Own Strategic Objectives, Asset Class, Asset Sub-Class,
    Ward Location, GPS Longitude, GPS Latitude""".strip().split(
        ","
    )
]
# Audited Outcome 2017/18,
# Full Year Forecast 2018/19,
# Budget year 2019/20,
# Budget year 2020/21,
# Budget year 2021/22

def float_or_none(val):
    try:
        return float(val)
    except ValueError:
        return None

def check_file(fp):
    reader = csv.DictReader(fp)
    return check_headers(reader.fieldnames)

def check_headers(fields):
    missing_headers = [h for h in headers if h not in fields]
    if len(missing_headers) > 0:
        raise ValueError(
            "The following fields are missing from the data source: %s"
            % missing_headers
        )

@transaction.atomic
def load_excel(filename, financial_year=None):
    def clean(s):
        if type(s) == str:
            return s.strip()
        else:
            return s

    def fix_broken_headers(header_row):
        header_row = [r.replace("\n", " ") for r in header_row]
        header_row = [
            r.replace("Project Decription", "Project Description") for r in header_row
        ]
        return header_row

    def sheet_parser(sheet):
        skip = True
        header_row = []
        for idx in range(0, sheet.nrows):
            row = [clean(sheet.cell(idx, col).value) for col in range(0, sheet.ncols)]

            val = sheet.cell(idx, 0).value.strip()
            if val != "Function" and skip:
                continue
            elif val == "Function":
                header_row = fix_broken_headers(row)
                check_headers(header_row)
                skip = False
                continue
            elif val == "":
                return

            yield dict(zip(header_row, row))

    workbook = xlrd.open_workbook(filename)
    print(workbook.sheets)
    for sheet in workbook.sheets():
        geo_code = sheet.name
        logger.info("Processing sheet: %s" % sheet.name)
        if Geography.objects.filter(geo_code=geo_code).count() == 0:
            raise CommandError(
                "%s is an unknown Geography. Please ensure that this Geography exists in the database"
                % geo_code
            )
        geography = Geography.objects.get(geo_code=geo_code)
        load_file(geography, sheet_parser(sheet), financial_year)

def load_csv(geography, fp):
    check_file(fp)
    fp.seek(0)
    reader = csv.DictReader(fp)
    return load_file(geography, reader)

@transaction.atomic
def load_file(geography, reader, financial_year):
    print(geography.geo_code)

    for idx, row in enumerate(reader):
        try:
            p, _ = models.Project.objects.update_or_create(
                geography=geography,
                function=row["Function"],
                project_description=row["Project Description"],
                project_number=row["Project Number"],
                defaults={
                    "project_type": row["Type"],
                    "mtsf_service_outcome": row["MTSF Service Outcome"],
                    "iudf": row["IUDF"],
                    "own_strategic_objectives": row["Own Strategic Objectives"],
                    "asset_class": row["Asset Class"],
                    "asset_subclass": row["Asset Sub-Class"],
                    "ward_location": row["Ward Location"],
                    "longitude": float_or_none(row["GPS Longitude"]),
                    "latitude": float_or_none(row["GPS Latitude"]),
                },
            )
            additional_fields = [k for k in row.keys() if k not in headers]
            budget_phase_fields = find_phase(additional_fields)
            quarterly_fields = find_quarter(additional_fields)
            for field in budget_phase_fields:
                amount = row[field]
                create_expenditure(p, field, amount)
            for field in quarterly_fields:
                amount = row[field]
                create_quarter(p, field, amount, financial_year)
        except Exception as e:
            raise ValueError("Error loading data in row: %d - %s" % (idx + 2, row))
    return idx + 1

def create_expenditure(project, finance_phase, amount):
    phase, year = create_finance_phase(finance_phase)
    try:
        expenditure = models.Expenditure.objects.create(
            project=project,
            budget_phase=phase,
            financial_year=year,
            amount=float(amount),
        )
        return True
    except ValueError:
        return False

def create_finance_phase(s):
    phase, year = parse_finance_phase(s)
    fy, _ = models.FinancialYear.objects.get_or_create(budget_year=year)
    phase, _ = models.BudgetPhase.objects.get_or_create(name=phase)

    return phase, fy

def create_quarter(project, header, amount, financial_year):
    """
    create the nessesary quarter
    """
    quarter = None
    if "Q1" in header:
        quarter = "q1"
    elif "Q2" in header:
        quarter = "q2"
    elif "Q3" in header:
        quarter = "q3"
    elif "Q4" in header:
        quarter = "q4"
    else:
        raise ValueError("Unknown Quarter")

    if amount:
        models.ProjectQuarterlySpend.objects.update_or_create(
            project=project,
            financial_year=financial_year,
            defaults={quarter: float(amount)},
        )

def parse_finance_phase(s):
    parts = s.split()
    year = parts[-1]

    y1, y2 = year.split("/")
    if len(y2) == 2:
        y2 = str(int(y1) + 1)

    year = "%s/%s" % (y1, y2)

    return " ".join(parts[0:-1]), year

def find_phase(fields):
    """Find fields with the project budgets"""
    phase = []
    for field in fields:
        if (
            field.startswith("Audited")
            or field.startswith("Adjusted")
            or field.startswith("Original")
            or field.startswith("Budgeted")
        ):
            phase.append(field)

    return phase

def find_quarter(fields):
    """Find the fields with project quarters"""
    return [field for field in fields if field.startswith("Q")]

def chart_quarters(quarter_queryset, phase_queryset, years):
    """
    prepare data for charting.
    """
    quarter_chart_data = {"labels": [], "data": []}
    original_chart_data = {"labels": [], "data": []}
    adjusted_chart_data = {"labels": [], "data": []}

    total_audit_expenditure = 0
    total_spending = {"Q1": 0, "Q2": 0, "Q3": 0, "Q4": 0}

    audited_years = []
    if phase_queryset:
        for phase in phase_queryset:
            if phase.budget_phase.name == "Original Budget":
                original_chart_data["labels"].append(
                    f"End Q1
{phase.financial_year.budget_year}"
                )
                original_chart_data["labels"].append(
                    f"End Q2
{phase.financial_year.budget_year}"
                )
                original_chart_data["labels"].append(
                    f"End Q3
{phase.financial_year.budget_year}"
                )
                original_chart_data["data"].append(float(phase.amount))
                original_chart_data["data"].append(float(phase.amount))
                original_chart_data["data"].append(float(phase.amount))
            if phase.budget_phase.name == "Adjusted Budget":
                adjusted_chart_data["labels"].append(
                    f"End Q3
{phase.financial_year.budget_year}"
                )
                adjusted_chart_data["labels"].append(
                    f"End Q4
{phase.financial_year.budget_year}"
                )
                adjusted_chart_data["data"].append(float(phase.amount))
                adjusted_chart_data["data"].append(float(phase.amount))
            if phase.budget_phase.name == "Audited Outcome":
                # audited_years.append(phase.financial_year)
                total_audit_expenditure += float(phase.amount)

    if quarter_queryset:
        for spend in quarter_queryset:
            if spend.q1:
                quarter_chart_data["labels"].append(
                    f"End Q1
{spend.financial_year.budget_year}"
                )
                total_spending["Q1"] = float(spend.q1) + total_audit_expenditure
                quarter_chart_data["data"].append(
                    [float(spend.q1), total_spending["Q1"]]
                )

            if spend.q2:
                quarter_chart_data["labels"].append(
                    f"End Q2
{spend.financial_year.budget_year}"
                )

                total_spending["Q2"] = float(spend.q2) + total_spending["Q1"]
                quarter_chart_data["data"].append(
                    [float(spend.q2), total_spending["Q2"]]
                )

            if spend.q3:
                quarter_chart_data["labels"].append(
                    f"End Q3
{spend.financial_year.budget_year}"
                )

                total_spending["Q3"] = float(spend.q3) + total_spending["Q2"]
                quarter_chart_data["data"].append(
                    [float(spend.q3), total_spending["Q3"]]
                )

            if spend.q4:
                quarter_chart_data["labels"].append(
                    f"End Q4
{spend.financial_year.budget_year}"
                )

                total_spending["Q4"] = float(spend.q4) + total_spending["Q4"]
                quarter_chart_data["data"].append(
                    [float(spend.q4), total_spending["Q4"]]
                )
    return original_chart_data, adjusted_chart_data, quarter_chart_data
<|endoftext|>


<commit_before>#!/usr/bin/python
"""mini-guild

A simplified version of guild without the full set of capabilities.
Has actor_methods and late bound methods.

"""

class Actor:
    Behaviour = None # Override with your behaviour, doesn't have to be a special class
    def __init__(self, *args, **argd):
        super(Actor, self).__init__()
        if self.Behaviour is None:
            raise Exception("You do not call Actor directly. Inherit and override Behaviour")
        self.greenthread = None
        self.inputqueue = []
        self._behaviour = (self.Behaviour)(*args, **argd)
        self.active = False
        self.sleeping = False

    def start(self):
        self.greenthread = self.main()
        self.active = True
        return self

    def tick(self):
        try:
            live = next(self.greenthread)
            return live
        except StopIteration:
            return False

    def handle_inqueue(self):
        call = self.inputqueue.pop(0)
        func_name, args = call[0], call[1:]
        #print(func_name, args)
        func = getattr(self._behaviour, func_name)
        func(*args)

    def main(self):
        if not hasattr(self._behaviour, "tick"):
            self._behaviour.tick = lambda *args: None
        while self.active:
            yield 1
            while (self.inputqueue  and self.active):
                self.handle_inqueue()
            if self.active and not self.sleeping:
                self._behaviour.tick()

    def link(self, methodname, target):
        setattr(self._behaviour, methodname, target)

    def isactive(self):
        return self.active

    def issleeping(self):
        return self.sleeping

    def input(self, data):
        self.inputqueue.append(("input", data))

    def stop(self):
        if hasattr(self._behaviour, "stop"):
            self.inputqueue.append(("stop", ))
        self.active = False
        self.sleeping = False

class API:
    """"Not technically needed in this version (remnants of "`Activity` actor"""
    def input(self, data):
        pass
    def output(self, data):
        raise Exception("base class `output` called directly - you should link over this")

class Producer(Actor):
    class Behaviour:
        def __init__(self, message):
            super(Producer.Behaviour, self).__init__()
            self.message = message
            self.greenthread = self.main()  # This could be pushed into API
            self.tick = self.greenthread.__next__

        def main(self):
            while True:
                yield 1
                self.output(self.message)

class Consumer(Actor):
    class Behaviour:
        def __init__(self):
            super(Consumer.Behaviour, self).__init__()
            self.count = 0
        def input(self, data):
            self.count += 1
            print("Consumed:", data, self.count)
            self.sleeping = True

if __name__ == "__main__":

    p = Producer("Hello").start()
    c = Consumer().start()

    p.link("output", c.input)

    x = 0

    # Manual scheduler

    p.tick()
    c.tick()
    while p.isactive() and c.isactive():
        p.tick()
        c.tick()
        x +=1
        if x > 10:
            p.stop()
            c.stop()
<commit_msg>Update mini-guild to support multiple behaviors for an actor<commit_after>#!/usr/bin/python
"""mini-guild

A simplified version of guild without the full set of capabilities.
Has actor_methods and late bound methods.

"""
def mkActorMethod(self, func_name):
    def actor_method(*args):
        self.inputqueue.append((func_name, *args))
    return actor_method

class Actor:
    Behaviour = None # Override with your behaviour, doesn't have to be a special class
    Behaviours = []
    default_actor_methods = ["input"]
    actor_methods = []

    def __init__(self, *args, **argd):
        super(Actor, self).__init__()
        if self.Behaviour is None:
            if self.Behaviours != []:
                self.Behaviour = self.Behaviours[0]
            else:
                raise Exception("You do not call Actor directly. Inherit and override Behaviour")
        self.args = args
        self.argd = argd
        self.greenthread = None
        self.inputqueue = []
        self.become(self.Behaviour)
        self.active = False
        self.sleeping = False

    def initialiseBehaviour(self, *args, **argd):
        self._behaviour = (self.Behaviour)(*args, **argd)
        for name in self.default_actor_methods + self.actor_methods:
            if name in self.Behaviour.__dict__:
                setattr(self, name, mkActorMethod(self, name))
        self._behaviour.become = self.become

    def become(self, behaviour_class):
        self.Behaviour = behaviour_class
        self.initialiseBehaviour(*self.args, **self.argd)
        if not hasattr(self._behaviour, "tick"):
            self._behaviour.tick = lambda *args: None

    def start(self):
        self.greenthread = self.main()
        self.active = True
        return self

    def tick(self):
        try:
            live = next(self.greenthread)
            return live
        except StopIteration:
            return False

    def handle_inqueue(self):
        call = self.inputqueue.pop(0)
        func_name, args = call[0], call[1:]
        #print(func_name, args)
        func = getattr(self._behaviour, func_name)
        func(*args)

    def main(self):
        while self.active:
            yield 1
            while (self.inputqueue  and self.active):
                self.handle_inqueue()
            if self.active and not self.sleeping:
                self._behaviour.tick()

    def link(self, methodname, target):
        setattr(self._behaviour, methodname, target)

    def isactive(self):
        return self.active

    def issleeping(self):
        return self.sleeping

    def stop(self):
        if hasattr(self._behaviour, "stop"):
            self.inputqueue.append(("stop", ))
        self.active = False
        self.sleeping = False

class API:
    """"Not technically needed in this version (remnants of "`Activity` actor"""
    def input(self, data):
        pass
    def output(self, data):
        raise Exception("base class `output` called directly - you should link over this")

class Producer(Actor):
    class Behaviour:
        def __init__(self, message):
            super(Producer.Behaviour, self).__init__()
            self.message = message
            self.greenthread = self.main()  # This could be pushed into API
            self.tick = self.greenthread.__next__

        def main(self):
            while True:
                yield 1
                self.output(self.message)

class Consumer(Actor):
    class Behaviour:
        def __init__(self):
            super(Consumer.Behaviour, self).__init__()
            self.count = 0
        def input(self, data):
            self.count += 1
            print("Consumed:", data, self.count)
            self.sleeping = True

        def munch(self, data):
            self.count += 1
            print("Munched:", data, self.count)
            self.sleeping = True

    actor_methods = ["munch"]

class Door(Actor):
    class OpenBehaviour:
        def open(self):
            print("OPEN:open.  The Door is already open!")
        def close(self):
            print("OPEN:close. The door is now closed!")
            self.become(Door.ClosedBehaviour)

    class ClosedBehaviour:
        def open(self):
            print("CLOSE:open.  The door is now open!")
            self.become(Door.OpenBehaviour)
        def close(self):
            print("CLOSE:close. The Door is already closed!")

    actor_methods = ["open","close"]
    Behaviours = ClosedBehaviour, OpenBehaviour

if __name__ == "__main__":

    p = Producer("Hello").start()
    c = Consumer().start()
    d = Door().start()

    d.open()
    d.open()
    d.close()
    d.close()
    d.open()
    d.open()
    d.tick()
    d.tick()
    d.tick()
    d.tick()
    d.tick()
    d.tick()

    p.link("output", c.munch)

    x = 0

    # Manual scheduler

    p.tick()
    c.tick()
    while p.isactive() and c.isactive():
        p.tick()
        c.tick()
        x +=1
        if x > 10:
            p.stop()
            c.stop()
<|endoftext|>


<commit_before># Copyright (c) 2019 brain-tec AG (http://www.braintec-group.com)
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError, AccessError, RedirectWarning

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    @api.model
    def _default_operating_unit_ids(self):
        if self.categ_id and self.categ_id.operating_unit_ids:
            return [(6, 0, self.categ_id.operating_unit_ids.ids)]
<<<<<<< HEAD
        if self.env.user.default_operating_unit_id:
            return [(6, 0,
                     [self.env['res.users'].operating_unit_default_get(
                         self.env.uid).id])]
=======
        return [(6, 0,
                 [self.env['res.users'].operating_unit_default_get(
                     self.env.uid).id])]
>>>>>>> [ADD] Added a product_operating_unit v12

    operating_unit_ids = fields.Many2many(
        'operating.unit',
        'product_operating_unit_rel',
        string='Operating Units',
        default=_default_operating_unit_ids)

    @api.multi
    @api.constrains('operating_unit_ids', 'categ_id')
    def _check_operating_unit(self):
        for record in self:
            if record.categ_id.operating_unit_ids and \
                    not all(ou in record.operating_unit_ids.ids for
                            ou in record.categ_id.operating_unit_ids.ids):
                raise ValidationError(_(
                    "The operating units of the product must include the "
                    "ones from the category."))

    @api.multi
    @api.onchange('categ_id')
    def onchange_operating_unit_ids(self):
        for record in self:
<<<<<<< HEAD
            if record.categ_id.operating_unit_ids:
                record.operating_unit_ids = \
                    [(6, 0, record.categ_id.operating_unit_ids.ids)]

    def _get_default_category_id(self):
        for ou_id in self.env.user.operating_unit_ids:
            category = self.env['product.category'].\
                search([], limit=1)
            if category:
                return category.id
            else:
                try:
                    self.env.ref('product.product_category_all',
                                 raise_if_not_found=False).name
                except AccessError:
                    err_msg = _('You must define at least one product \
                        category within your Operating Unit in order to be \
                        able to create products.')
                    redir_msg = _('Go to Product Categories')
                    raise RedirectWarning(
                        err_msg,
                        self.env.ref(
                            'product.product_category_action_form').id,
                        redir_msg)
                return super()._get_default_category_id()

    categ_id = fields.Many2one(
        'product.category', 'Product Category',
        change_default=True, default=_get_default_category_id,
        required=True, help="Select category for the current product")
=======
            record.operating_unit_ids = \
                [(6, 0, record.categ_id.operating_unit_ids.ids)]
>>>>>>> [ADD] Added a product_operating_unit v12
<commit_msg>[FIX] Default Get + Show OU on Small Form<commit_after># Copyright (c) 2019 brain-tec AG (http://www.braintec-group.com)
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError, AccessError, RedirectWarning

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    @api.model
    def _default_operating_unit_ids(self):
        if self.categ_id and self.categ_id.operating_unit_ids:
            return [(6, 0, self.categ_id.operating_unit_ids.ids)]
        if self.env.user.default_operating_unit_id:
            return [(6, 0,
                     [self.env['res.users'].operating_unit_default_get(
                         self.env.uid).id])]

    operating_unit_ids = fields.Many2many(
        'operating.unit',
        'product_operating_unit_rel',
        string='Operating Units',
        default=_default_operating_unit_ids)

    @api.multi
    @api.constrains('operating_unit_ids', 'categ_id')
    def _check_operating_unit(self):
        for record in self:
            if record.categ_id.operating_unit_ids and \
                    not all(ou in record.operating_unit_ids.ids for
                            ou in record.categ_id.operating_unit_ids.ids):
                raise ValidationError(_(
                    "The operating units of the product must include the "
                    "ones from the category."))

    @api.multi
    @api.onchange('categ_id')
    def onchange_operating_unit_ids(self):
        for record in self:
            if record.categ_id.operating_unit_ids:
                record.operating_unit_ids = \
                    [(6, 0, record.categ_id.operating_unit_ids.ids)]

    def _get_default_category_id(self):
        for ou_id in self.env.user.operating_unit_ids:
            category = self.env['product.category'].\
                search([], limit=1)
            if category:
                return category.id
            else:
                try:
                    self.env.ref('product.product_category_all',
                                 raise_if_not_found=False).name
                except AccessError:
                    err_msg = _('You must define at least one product \
                        category within your Operating Unit in order to be \
                        able to create products.')
                    redir_msg = _('Go to Product Categories')
                    raise RedirectWarning(
                        err_msg,
                        self.env.ref(
                            'product.product_category_action_form').id,
                        redir_msg)
                return super()._get_default_category_id()

    categ_id = fields.Many2one(
        'product.category', 'Product Category',
        change_default=True, default=_get_default_category_id,
        required=True, help="Select category for the current product")<|endoftext|>