<commit_before># -*- coding: utf8 -*-
#
# Copyright (C) 2014 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
#    This program 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.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#

from datetime import datetime
from dateutil.relativedelta import relativedelta
from psycopg2 import OperationalError
import logging

import openerp
import openerp.addons.decimal_precision as dp
from openerp.tools import float_compare, float_round, DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.sql import drop_view_if_exists
from openerp import fields, models, api, exceptions, _

_logger = logging.getLogger(__name__)

class procurement_order_qty(models.Model):
    _inherit = 'procurement.order'

    qty = fields.Float(string="Quantity", digits_compute=dp.get_precision('Product Unit of Measure'),
                       help='Quantity in the default UoM of the product', compute="_compute_qty", store=True)

    @api.multi
    @api.depends('product_qty','product_uom')
    def _compute_qty(self):
        uom_obj = self.env['product.uom']
        for m in self:
            qty = uom_obj._compute_qty_obj(m.product_uom, m.product_qty, m.product_id.uom_id)
            m.qty = qty

    @api.model
    def _get_orderpoint_date_planned(self, orderpoint, start_date):
        """Returns the date to be set on the procurement made from orderpoint.
        Overridden here to set the date to the needed date."""
        date = datetime.strptime(orderpoint.get_next_need().date, DEFAULT_SERVER_DATETIME_FORMAT)
        return date + relativedelta(seconds=-1)

    @api.model
    def _procure_orderpoint_confirm(self, use_new_cursor=False, company_id=False):
        '''
        Create procurement based on Orderpoint

        :param bool use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement.
            This is appropriate for batch jobs only.
        '''
        if use_new_cursor:
            cr = openerp.registry(self.env.cr.dbname).cursor()
            new_env = api.Environment(cr, self.env.user.id, self.env.context)
        else:
            new_env = self.env
        this = self.with_env(new_env)

        orderpoint_env = this.env['stock.warehouse.orderpoint']
        proc_env = this.env['procurement.order']
        dom = company_id and [('company_id', '=', company_id)] or []
        orderpoint_ids = orderpoint_env.search(dom)
        prev_ids = []
        while orderpoint_ids:
            orderpoints = orderpoint_ids[:100]
            orderpoint_ids = orderpoint_ids - orderpoints
            for op in orderpoints:
                try:
                    _logger.debug("Computing orderpoint %s (%s, %s)" % (op.id, op.product_id.name, op.location_id.name))
                    need = op.get_next_need()
                    processed_needs = [need]
                    while need:
                        # We go the the next need (i.e. stock level forecast < minimum qty)
                        next_proc = need.get_next_proc()
                        # We check if there is already a procurement in the future
                        if next_proc:
                            # If there is a future procurement, we reschedule it (required date) to fit our need
                            next_proc.date_planned = this._get_orderpoint_date_planned(op, datetime.today())
                            next_proc.action_reschedule()
                            _logger.debug("Rescheduled proc: %s, (%s, %s)" % (next_proc, next_proc.date_planned,
                                                                                next_proc.product_qty))
                        else:
                            # Else, we create a new procurement
                            qty = max(op.product_min_qty, op.product_max_qty) - need.qty
                            reste = op.qty_multiple > 0 and qty % op.qty_multiple or 0.0
                            if float_compare(reste, 0.0, precision_rounding=op.product_uom.rounding) > 0:
                                qty += op.qty_multiple - reste
                            qty = float_round(qty, precision_rounding=op.product_uom.rounding)
                            proc_vals = this._prepare_orderpoint_procurement(op, qty)
                            proc = proc_env.create(proc_vals)
                            proc.check()
                            proc.run()
                            _logger.debug("Created proc: %s, (%s, %s)" % (proc, proc.date_planned, proc.product_qty))
                        need = op.get_next_need()
                        if need in processed_needs:
                            break
                        else:
                            processed_needs.append(need)
                except OperationalError:
                    if use_new_cursor:
                        orderpoint_ids = orderpoint_ids | op
                        new_env.cr.rollback()
                        continue
                    else:
                        raise
            if use_new_cursor:
                new_env.cr.commit()
            if prev_ids == orderpoints:
                break
            else:
                prev_ids = orderpoints
        if use_new_cursor:
            new_env.cr.commit()
            new_env.cr.close()
        return {}

class stock_warehouse_order_point_jit(models.Model):
    _inherit = 'stock.warehouse.orderpoint'

    @api.one
    @api.returns('stock.levels.requirements')
    def get_next_need(self):
        """Returns the next stock.level.requirements where the stock level is below minimumqty for the product and
        the location of the orderpoint."""
        need = self.env['stock.levels.requirements'].search([('product_id','=',self.product_id.id),
                                                             ('qty','<',self.product_min_qty),
                                                             ('location_id','=',self.location_id.id),
                                                             ('move_type','=','out')], order='date', limit=1)
        return need

class stock_levels_report(models.Model):
    _name = "stock.levels.report"
    _description = "Stock Levels Report"
    _order = "date"
    _auto = False

    id = fields.Integer("ID", readonly=True)
    product_id = fields.Many2one("product.product", string="Product", index=True)
    product_categ_id = fields.Many2one("product.category", string="Product Category")
    location_id = fields.Many2one("stock.location", string="Location", index=True)
    other_location_id = fields.Many2one("stock.location", string="Origin/Destination")
    move_type = fields.Selection([('existing','Existing'),('in','Incoming'),('out','Outcoming'),
                                  ('planned',"Planned (In)")],
                                 string="Move type", index=True)
    date = fields.Datetime("Date", index=True)
    qty = fields.Float("Stock quantity", group_operator="last")
    move_qty = fields.Float("Moved quantity")

    def init(self, cr):
        drop_view_if_exists(cr, "stock_levels_report")
        cr.execute("""
        create or replace view stock_levels_report as (
            select
                row_number() over () as id,
                foo.product_id,
                pt.categ_id as product_categ_id,
                foo.location_id,
                foo.other_location_id,
                foo.move_type,
                sum(foo.qty) over (partition by foo.location_id, foo.product_id order by date) as qty,
                foo.date as date,
                foo.qty as move_qty
            from
                (
                    select
                        sq.product_id as product_id,
                        sq.location_id as location_id,
                        NULL as other_location_id,
                        'existing'::text as move_type,
                        max(sq.in_date) as date,
                        sum(sq.qty) as qty
                    from
                        stock_quant sq
                        left join stock_location sl on sq.location_id = sl.id
                    where
                        sl.usage = 'internal'::text or sl.usage = 'transit'::text
                    group by sq.product_id, sq.location_id
                union
                    select
                        sm.product_id as product_id,
                        sm.location_dest_id as location_id,
                        sm.location_id as other_location_id,
                        'in'::text as move_type,
                        sm.date_expected as date,
                        sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_dest_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        sm.product_id as product_id,
                        sm.location_id as location_id,
                        sm.location_dest_id as other_location_id,
                        'out'::text as move_type,
                        sm.date_expected as date,
                        -sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        po.product_id as product_id,
                        po.location_id as location_id,
                        NULL as other_location_id,
                        'planned'::text as move_type,
                        po.date_planned as date,
                        po.qty as qty
                    from
                        procurement_order po
                        left join stock_location sl on po.location_id = sl.id
                        left join stock_move sm on sm.procurement_id = po.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and po.state::text <> 'cancel'::text
                        and po.state::text <> 'done'::text
                        and (sm.id is NULL or sm.state::text = 'draft'::text)
                ) foo
                left join product_product pp on foo.product_id = pp.id
                left join product_template pt on pp.product_tmpl_id = pt.id
        )
        """)

class stock_levels_requirements(models.Model):
    _name = "stock.levels.requirements"
    _description = "Stock Levels Requirements"
    _order = "date"
    _auto = False

    id = fields.Integer("ID", readonly=True)
    proc_id = fields.Many2one("procurement.order", string="Procurement")
    product_id = fields.Many2one("product.product", string="Product", index=True)
    product_categ_id = fields.Many2one("product.category", string="Product Category")
    location_id = fields.Many2one("stock.location", string="Location", index=True)
    other_location_id = fields.Many2one("stock.location", string="Origin/Destination")
    move_type = fields.Selection([('existing','Existing'),('in','Incoming'),('out','Outcoming'),
                                  ('planned',"Planned (In)")],
                                 string="Move type", index=True)
    date = fields.Datetime("Date", index=True)
    qty = fields.Float("Stock quantity", group_operator="last")
    move_qty = fields.Float("Moved quantity")

    def init(self, cr):
        drop_view_if_exists(cr, "stock_levels_requirements")
        cr.execute("""
        create or replace view stock_levels_requirements as (
            select
                row_number() over () as id,
                foo.proc_id,
                foo.product_id,
                pt.categ_id as product_categ_id,
                foo.location_id,
                foo.other_location_id,
                foo.move_type,
                sum(foo.qty) over (partition by foo.location_id, foo.product_id order by date) as qty,
                foo.date as date,
                foo.qty as move_qty
            from
                (
                    select
                        NULL as proc_id,
                        sq.product_id as product_id,
                        sq.location_id as location_id,
                        NULL as other_location_id,
                        'existing'::text as move_type,
                        max(sq.in_date) as date,
                        sum(sq.qty) as qty
                    from
                        stock_quant sq
                        left join stock_location sl on sq.location_id = sl.id
                    where
                        sl.usage = 'internal'::text or sl.usage = 'transit'::text
                    group by sq.product_id, sq.location_id
                union
                    select
                        sm.procurement_id as proc_id,
                        sm.product_id as product_id,
                        sm.location_dest_id as location_id,
                        sm.location_id as other_location_id,
                        'in'::text as move_type,
                        sm.date as date,
                        sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_dest_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        NULL as proc_id,
                        sm.product_id as product_id,
                        sm.location_id as location_id,
                        sm.location_dest_id as other_location_id,
                        'out'::text as move_type,
                        sm.date as date,
                        -sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        po.id as proc_id,
                        po.product_id as product_id,
                        po.location_id as location_id,
                        NULL as other_location_id,
                        'planned'::text as move_type,
                        po.date_planned as date,
                        po.qty as qty
                    from
                        procurement_order po
                        left join stock_location sl on po.location_id = sl.id
                        left join stock_move sm on sm.procurement_id = po.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and po.state::text <> 'cancel'::text
                        and po.state::text <> 'done'::text
                        and (sm.id is NULL or sm.state::text = 'draft'::text)
                ) foo
                left join product_product pp on foo.product_id = pp.id
                left join product_template pt on pp.product_tmpl_id = pt.id
        )
        """)

    @api.one
    @api.returns('procurement.order')
    def get_next_proc(self):
        """Returns the next procurement.order after this line which date is not the line's date."""
        next_line = self.search([('product_id','=',self.product_id.id),('location_id','=',self.location_id.id),
                                 ('date','>',self.date),('proc_id','!=',False)], limit=1)
        return next_line.proc_id
<commit_msg>[FIX] stock procurement jit: changed to calculate need in child_of location<commit_after># -*- coding: utf8 -*-
#
# Copyright (C) 2014 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
#    This program 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.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#

from datetime import datetime
from dateutil.relativedelta import relativedelta
from psycopg2 import OperationalError
import logging

import openerp
import openerp.addons.decimal_precision as dp
from openerp.tools import float_compare, float_round, DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.sql import drop_view_if_exists
from openerp import fields, models, api, exceptions, _

_logger = logging.getLogger(__name__)

class procurement_order_qty(models.Model):
    _inherit = 'procurement.order'

    qty = fields.Float(string="Quantity", digits_compute=dp.get_precision('Product Unit of Measure'),
                       help='Quantity in the default UoM of the product', compute="_compute_qty", store=True)

    @api.multi
    @api.depends('product_qty','product_uom')
    def _compute_qty(self):
        uom_obj = self.env['product.uom']
        for m in self:
            qty = uom_obj._compute_qty_obj(m.product_uom, m.product_qty, m.product_id.uom_id)
            m.qty = qty

    @api.model
    def _get_orderpoint_date_planned(self, orderpoint, start_date):
        """Returns the date to be set on the procurement made from orderpoint.
        Overridden here to set the date to the needed date."""
        date = datetime.strptime(orderpoint.get_next_need().date, DEFAULT_SERVER_DATETIME_FORMAT)
        return date + relativedelta(seconds=-1)

    @api.model
    def _procure_orderpoint_confirm(self, use_new_cursor=False, company_id=False):
        '''
        Create procurement based on Orderpoint

        :param bool use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement.
            This is appropriate for batch jobs only.
        '''
        if use_new_cursor:
            cr = openerp.registry(self.env.cr.dbname).cursor()
            new_env = api.Environment(cr, self.env.user.id, self.env.context)
        else:
            new_env = self.env
        this = self.with_env(new_env)

        orderpoint_env = this.env['stock.warehouse.orderpoint']
        proc_env = this.env['procurement.order']
        dom = company_id and [('company_id', '=', company_id)] or []
        orderpoint_ids = orderpoint_env.search(dom)
        prev_ids = []
        while orderpoint_ids:
            orderpoints = orderpoint_ids[:100]
            orderpoint_ids = orderpoint_ids - orderpoints
            for op in orderpoints:
                try:
                    _logger.debug("Computing orderpoint %s (%s, %s)" % (op.id, op.product_id.name, op.location_id.name))
                    need = op.get_next_need()
                    processed_needs = [need]
                    while need:
                        # We go the the next need (i.e. stock level forecast < minimum qty)
                        next_proc = need.get_next_proc()
                        # We check if there is already a procurement in the future
                        if next_proc:
                            # If there is a future procurement, we reschedule it (required date) to fit our need
                            next_proc.date_planned = this._get_orderpoint_date_planned(op, datetime.today())
                            next_proc.action_reschedule()
                            _logger.debug("Rescheduled proc: %s, (%s, %s)" % (next_proc, next_proc.date_planned,
                                                                                next_proc.product_qty))
                        else:
                            # Else, we create a new procurement
                            qty = max(op.product_min_qty, op.product_max_qty) - need.qty
                            reste = op.qty_multiple > 0 and qty % op.qty_multiple or 0.0
                            if float_compare(reste, 0.0, precision_rounding=op.product_uom.rounding) > 0:
                                qty += op.qty_multiple - reste
                            qty = float_round(qty, precision_rounding=op.product_uom.rounding)
                            proc_vals = this._prepare_orderpoint_procurement(op, qty)
                            proc = proc_env.create(proc_vals)
                            proc.check()
                            proc.run()
                            _logger.debug("Created proc: %s, (%s, %s)" % (proc, proc.date_planned, proc.product_qty))
                        need = op.get_next_need()
                        if need in processed_needs:
                            break
                        else:
                            processed_needs.append(need)
                except OperationalError:
                    if use_new_cursor:
                        orderpoint_ids = orderpoint_ids | op
                        new_env.cr.rollback()
                        continue
                    else:
                        raise
            if use_new_cursor:
                new_env.cr.commit()
            if prev_ids == orderpoints:
                break
            else:
                prev_ids = orderpoints
        if use_new_cursor:
            new_env.cr.commit()
            new_env.cr.close()
        return {}

class stock_warehouse_order_point_jit(models.Model):
    _inherit = 'stock.warehouse.orderpoint'

    @api.one
    @api.returns('stock.levels.requirements')
    def get_next_need(self):
        """Returns the next stock.level.requirements where the stock level is below minimumqty for the product and
        the location of the orderpoint."""
        need = self.env['stock.levels.requirements'].search([('product_id','=',self.product_id.id),
                                                             ('qty','<',self.product_min_qty),
                                                             ('location_id','child_of',self.location_id.id),
                                                             ('move_type','=','out')], order='date', limit=1)
        return need

class stock_levels_report(models.Model):
    _name = "stock.levels.report"
    _description = "Stock Levels Report"
    _order = "date"
    _auto = False

    id = fields.Integer("ID", readonly=True)
    product_id = fields.Many2one("product.product", string="Product", index=True)
    product_categ_id = fields.Many2one("product.category", string="Product Category")
    location_id = fields.Many2one("stock.location", string="Location", index=True)
    other_location_id = fields.Many2one("stock.location", string="Origin/Destination")
    move_type = fields.Selection([('existing','Existing'),('in','Incoming'),('out','Outcoming'),
                                  ('planned',"Planned (In)")],
                                 string="Move type", index=True)
    date = fields.Datetime("Date", index=True)
    qty = fields.Float("Stock quantity", group_operator="last")
    move_qty = fields.Float("Moved quantity")

    def init(self, cr):
        drop_view_if_exists(cr, "stock_levels_report")
        cr.execute("""
        create or replace view stock_levels_report as (
            select
                row_number() over () as id,
                foo.product_id,
                pt.categ_id as product_categ_id,
                foo.location_id,
                foo.other_location_id,
                foo.move_type,
                sum(foo.qty) over (partition by foo.location_id, foo.product_id order by date) as qty,
                foo.date as date,
                foo.qty as move_qty
            from
                (
                    select
                        sq.product_id as product_id,
                        sq.location_id as location_id,
                        NULL as other_location_id,
                        'existing'::text as move_type,
                        max(sq.in_date) as date,
                        sum(sq.qty) as qty
                    from
                        stock_quant sq
                        left join stock_location sl on sq.location_id = sl.id
                    where
                        sl.usage = 'internal'::text or sl.usage = 'transit'::text
                    group by sq.product_id, sq.location_id
                union
                    select
                        sm.product_id as product_id,
                        sm.location_dest_id as location_id,
                        sm.location_id as other_location_id,
                        'in'::text as move_type,
                        sm.date_expected as date,
                        sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_dest_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        sm.product_id as product_id,
                        sm.location_id as location_id,
                        sm.location_dest_id as other_location_id,
                        'out'::text as move_type,
                        sm.date_expected as date,
                        -sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        po.product_id as product_id,
                        po.location_id as location_id,
                        NULL as other_location_id,
                        'planned'::text as move_type,
                        po.date_planned as date,
                        po.qty as qty
                    from
                        procurement_order po
                        left join stock_location sl on po.location_id = sl.id
                        left join stock_move sm on sm.procurement_id = po.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and po.state::text <> 'cancel'::text
                        and po.state::text <> 'done'::text
                        and (sm.id is NULL or sm.state::text = 'draft'::text)
                ) foo
                left join product_product pp on foo.product_id = pp.id
                left join product_template pt on pp.product_tmpl_id = pt.id
        )
        """)

class stock_levels_requirements(models.Model):
    _name = "stock.levels.requirements"
    _description = "Stock Levels Requirements"
    _order = "date"
    _auto = False

    id = fields.Integer("ID", readonly=True)
    proc_id = fields.Many2one("procurement.order", string="Procurement")
    product_id = fields.Many2one("product.product", string="Product", index=True)
    product_categ_id = fields.Many2one("product.category", string="Product Category")
    location_id = fields.Many2one("stock.location", string="Location", index=True)
    other_location_id = fields.Many2one("stock.location", string="Origin/Destination")
    move_type = fields.Selection([('existing','Existing'),('in','Incoming'),('out','Outcoming'),
                                  ('planned',"Planned (In)")],
                                 string="Move type", index=True)
    date = fields.Datetime("Date", index=True)
    qty = fields.Float("Stock quantity", group_operator="last")
    move_qty = fields.Float("Moved quantity")

    def init(self, cr):
        drop_view_if_exists(cr, "stock_levels_requirements")
        cr.execute("""
        create or replace view stock_levels_requirements as (
            select
                row_number() over () as id,
                foo.proc_id,
                foo.product_id,
                pt.categ_id as product_categ_id,
                foo.location_id,
                foo.other_location_id,
                foo.move_type,
                sum(foo.qty) over (partition by foo.location_id, foo.product_id order by date) as qty,
                foo.date as date,
                foo.qty as move_qty
            from
                (
                    select
                        NULL as proc_id,
                        sq.product_id as product_id,
                        sq.location_id as location_id,
                        NULL as other_location_id,
                        'existing'::text as move_type,
                        max(sq.in_date) as date,
                        sum(sq.qty) as qty
                    from
                        stock_quant sq
                        left join stock_location sl on sq.location_id = sl.id
                    where
                        sl.usage = 'internal'::text or sl.usage = 'transit'::text
                    group by sq.product_id, sq.location_id
                union
                    select
                        sm.procurement_id as proc_id,
                        sm.product_id as product_id,
                        sm.location_dest_id as location_id,
                        sm.location_id as other_location_id,
                        'in'::text as move_type,
                        sm.date as date,
                        sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_dest_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        NULL as proc_id,
                        sm.product_id as product_id,
                        sm.location_id as location_id,
                        sm.location_dest_id as other_location_id,
                        'out'::text as move_type,
                        sm.date as date,
                        -sm.product_qty as qty
                    from
                        stock_move sm
                        left join stock_location sl on sm.location_id = sl.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and sm.state::text <> 'cancel'::text
                        and sm.state::text <> 'done'::text
                        and sm.state::text <> 'draft'::text
                union
                    select
                        po.id as proc_id,
                        po.product_id as product_id,
                        po.location_id as location_id,
                        NULL as other_location_id,
                        'planned'::text as move_type,
                        po.date_planned as date,
                        po.qty as qty
                    from
                        procurement_order po
                        left join stock_location sl on po.location_id = sl.id
                        left join stock_move sm on sm.procurement_id = po.id
                    where
                        (sl.usage = 'internal'::text or sl.usage = 'transit'::text)
                        and po.state::text <> 'cancel'::text
                        and po.state::text <> 'done'::text
                        and (sm.id is NULL or sm.state::text = 'draft'::text)
                ) foo
                left join product_product pp on foo.product_id = pp.id
                left join product_template pt on pp.product_tmpl_id = pt.id
        )
        """)

    @api.one
    @api.returns('procurement.order')
    def get_next_proc(self):
        """Returns the next procurement.order after this line which date is not the line's date."""
        next_line = self.search([('product_id','=',self.product_id.id),('location_id','=',self.location_id.id),
                                 ('date','>',self.date),('proc_id','!=',False)], limit=1)
        return next_line.proc_id
<|endoftext|>


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

import rospy

from monitored_navigation.ui_helper import UIHelper

import actionlib
from strands_tweets.msg import GrabImageThenTweetAction, GrabImageThenTweetGoal

class HelpTweet(UIHelper):

    def __init__(self, bumper_fails_to_tweet=20, nav_fails_to_tweet=20):

        self.twitter=actionlib.SimpleActionClient('strands_image_tweets', GrabImageThenTweetAction)
        self.got_server=self.twitter.wait_for_server(rospy.Duration(1))
        countdown=10
        while not self.got_server and countdown>0:
            rospy.loginfo("Help via twitter is waiting for grab image then tweet action..." + str(countdown))
            self.got_server=self.twitter.wait_for_server(rospy.Duration(1))
            countdown=countdown-1
            if rospy.is_shutdown():
                return
        if self.got_server:
            rospy.loginfo("Help via twitter got grab image then tweet action action")
        else:
            rospy.logwarn("Timeout waiting for grab image then tweet action, no tweeting for help")

        rospy.set_param('bumper_fails_to_tweet',20)
        rospy.set_param('nav_fails_to_tweet',20)
        self.bumper_post="I've been crashed into something for quite some time now. Someone should come by and get me out of here."
        self.nav_post="I've been having some issue going around for quite some time now. I'm sure I'm pretty stuck somewhere. What does it look like?"
        self.magnetic_post="I'm very close to a flight of stairs! I'm frozen in terror! I need one of my handlers to come and help me!"
        self.tweet=GrabImageThenTweetGoal(topic='head_xtion/rgb/image_color')

        self.was_helped=False

        UIHelper.__init__(self)

        rospy.loginfo("Help via twitter initialized")

    def ask_help(self, failed_component, interaction_service, n_fails):
        if self.got_server:
            if failed_component=='navigation' and n_fails == rospy.get_param('nav_fails_to_tweet',20):
                self.tweet.text=self.nav_post
                self.twitter.send_goal_and_wait(self.tweet)
            elif failed_component=='bumper' and n_fails == rospy.get_param('bumper_fails_to_tweet',20):
                self.tweet.text=self.bumper_post
                self.twitter.send_goal_and_wait(self.tweet)
            elif failed_component=='magnetic_strip':
                self.tweet.text=self.magnetic_post
                self.twitter.send_goal_and_wait(self.tweet)

    def being_helped(self, failed_component, interaction_service, n_fails):
        return

    def help_finished(self, failed_component, interaction_service, n_fails):
        return

    def help_failed(self, failed_component, interaction_service, n_fails):
        return

<commit_msg>shortening twitter posts<commit_after>#! /usr/bin/env python

import rospy

from monitored_navigation.ui_helper import UIHelper

import actionlib
from strands_tweets.msg import GrabImageThenTweetAction, GrabImageThenTweetGoal

class HelpTweet(UIHelper):

    def __init__(self, bumper_fails_to_tweet=20, nav_fails_to_tweet=20):

        self.twitter=actionlib.SimpleActionClient('strands_image_tweets', GrabImageThenTweetAction)
        self.got_server=self.twitter.wait_for_server(rospy.Duration(1))
        countdown=10
        while not self.got_server and countdown>0:
            rospy.loginfo("Help via twitter is waiting for grab image then tweet action..." + str(countdown))
            self.got_server=self.twitter.wait_for_server(rospy.Duration(1))
            countdown=countdown-1
            if rospy.is_shutdown():
                return
        if self.got_server:
            rospy.loginfo("Help via twitter got grab image then tweet action action")
        else:
            rospy.logwarn("Timeout waiting for grab image then tweet action, no tweeting for help")

        rospy.set_param('bumper_fails_to_tweet',20)
        rospy.set_param('nav_fails_to_tweet',20)
        self.bumper_post="I've been crashed into something for some time now. Someone should come by and get me out of here."
        self.nav_post="I've been struggling to go around for a while now. I'm pretty sure I got stuck. What does it look like?"
        self.magnetic_post="I'm very close to a flight of stairs! I'm frozen in terror! I need one of my handlers to come and help me!"
        self.tweet=GrabImageThenTweetGoal(topic='head_xtion/rgb/image_color')

        self.was_helped=False

        UIHelper.__init__(self)

        rospy.loginfo("Help via twitter initialized")

    def ask_help(self, failed_component, interaction_service, n_fails):
        if self.got_server:
            if failed_component=='navigation' and n_fails == rospy.get_param('nav_fails_to_tweet',20):
                self.tweet.text=self.nav_post
                self.twitter.send_goal_and_wait(self.tweet)
            elif failed_component=='bumper' and n_fails == rospy.get_param('bumper_fails_to_tweet',20):
                self.tweet.text=self.bumper_post
                self.twitter.send_goal_and_wait(self.tweet)
            elif failed_component=='magnetic_strip':
                self.tweet.text=self.magnetic_post
                self.twitter.send_goal_and_wait(self.tweet)

    def being_helped(self, failed_component, interaction_service, n_fails):
        return

    def help_finished(self, failed_component, interaction_service, n_fails):
        return

    def help_failed(self, failed_component, interaction_service, n_fails):
        return

<|endoftext|>


<commit_before># Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from telemetry import decorators
from telemetry.util import trace_runner
from telemetry.internal.browser import browser_finder
from telemetry.testing import options_for_unittests
from telemetry.testing import tab_test_case
from telemetry.timeline import model as model_module
from telemetry.timeline import tracing_config

def ReadMarkerEvents(trace_data):
  # Parse the trace and extract all test markers & trace-flushing markers
  return trace_runner.ExecuteMappingCodeOnTraceData(
      trace_data, """
function processTrace(results, model) {
    var markers = [];
    for (const thread of model.getAllThreads()) {
        for (const event of thread.asyncSliceGroup.slices) {
            if (event.title.startsWith('test-marker-') ||
                event.title === 'flush-tracing') {
                markers.push({'title': event.title, 'start': event.start});
           }
       }
   }
   results.addPair('markers', markers);
};
       """)['markers']

class TracingControllerTest(tab_test_case.TabTestCase):
  """Tests that start tracing when a browser tab is already active."""

  @decorators.Isolated
  def testExceptionRaisedInStopTracing(self):
    tracing_controller = self._tab.browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)

    self.Navigate('blank.html')

    def _FakeStopChromeTracing(*args):
      del args  # Unused
      raise Exception('Intentional Tracing Exception')

    self._tab._inspector_backend._devtools_client.StopChromeTracing = (
        _FakeStopChromeTracing)
    with self.assertRaisesRegexp(Exception, 'Intentional Tracing Exception'):
      tracing_controller.StopTracing()

    # Tracing is stopped even if there is exception.
    self.assertFalse(tracing_controller.is_tracing_running)

  @decorators.Isolated
  def testGotTrace(self):
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)

    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    # Test that trace data is parsable
    model = model_module.TimelineModel(trace_data)
    assert len(model.processes) > 0

  @decorators.Isolated
  def testStartAndStopTraceMultipleTimes(self):
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)
    self.assertFalse(tracing_controller.StartTracing(config))

    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    # Test that trace data is parsable
    model_module.TimelineModel(trace_data)
    self.assertFalse(tracing_controller.is_tracing_running)
    # Calling stop again will raise exception
    self.assertRaises(Exception, tracing_controller.StopTracing)

  @decorators.Isolated
  @decorators.Disabled('win')  # crbug.com/829976
  def testFlushTracing(self):
    subtrace_count = 5

    tab = self._browser.tabs[0]

    # Set up the tracing config.
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True

    # Start tracing and inject a unique marker into the sub-trace.
    tracing_controller.StartTracing(config)
    self.assertTrue(tracing_controller.is_tracing_running)
    tab.AddTimelineMarker('test-marker-0')

    # Flush tracing |subtrace_count - 1| times and inject a unique marker into
    # the sub-trace each time.
    for i in xrange(1, subtrace_count):
      tracing_controller.FlushTracing()
      self.assertTrue(tracing_controller.is_tracing_running)
      tab.AddTimelineMarker('test-marker-%d' % i)

    # Stop tracing.
    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    self.assertFalse(tracing_controller.is_tracing_running)

    # Check that the markers 'test-marker-0', 'flush-tracing',
    # 'test-marker-1', ..., 'flush-tracing',
    # 'test-marker-|subtrace_count - 1|' are monotonic.
    markers = ReadMarkerEvents(trace_data)
    self.assertEquals(2 * subtrace_count - 1, len(markers))
    for i in xrange(0, len(markers) - 2):
      if i % 2 == 0:
        expected_title = 'test-marker-%d' % (i/2)
      else:
        expected_title = 'flush-tracing'
      self.assertEquals(expected_title, markers[i]['title'])
      self.assertLess(markers[i]['start'], markers[i + 1]['start'])

class StartupTracingTest(unittest.TestCase):
  """Tests that start tracing before the browser is created."""

  def setUp(self):
    finder_options = options_for_unittests.GetCopy()
    self.possible_browser = browser_finder.FindBrowser(finder_options)
    if not self.possible_browser:
      raise Exception('No browser found, cannot continue test.')
    self.browser_options = finder_options.browser_options
    self.config = tracing_config.TracingConfig()
    self.config.enable_chrome_trace = True

  def tearDown(self):
    if self.possible_browser and self.tracing_controller.is_tracing_running:
      self.tracing_controller.StopTracing()

  @property
  def tracing_controller(self):
    return self.possible_browser.platform.tracing_controller

  def StopTracingAndGetTestMarkers(self, marker_prefix):
    self.assertTrue(self.tracing_controller.is_tracing_running)
    trace_data, errors = self.tracing_controller.StopTracing()
    self.assertFalse(self.tracing_controller.is_tracing_running)
    self.assertEqual(errors, [])
    return [
        e['title']
        for e in ReadMarkerEvents(trace_data)
        if e['title'].startswith(marker_prefix)]

  @decorators.Isolated
  def testStopTracingWhileBrowserIsRunning(self):
    self.tracing_controller.StartTracing(self.config)
    with self.possible_browser.BrowserSession(self.browser_options) as browser:
      browser.tabs[0].Navigate('about:blank')
      browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
      browser.tabs[0].AddTimelineMarker('test-marker-foo')
      markers = self.StopTracingAndGetTestMarkers('test-marker-')
    self.assertEquals(markers, ['test-marker-foo'])

  @decorators.Isolated
  def testCloseBrowserBeforeTracingIsStopped(self):
    self.tracing_controller.StartTracing(self.config)
    with self.possible_browser.BrowserSession(self.browser_options) as browser:
      browser.tabs[0].Navigate('about:blank')
      browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
      browser.tabs[0].AddTimelineMarker('test-marker-bar')
      # TODO(crbug.com/854212): This should happen implicitly on browser.Close()
      self.tracing_controller.FlushTracing()
    markers = self.StopTracingAndGetTestMarkers('test-marker-')
    self.assertEquals(markers, ['test-marker-bar'])
<commit_msg>[Telemetry] Add testRestartBrowserWhileTracing<commit_after># Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from telemetry import decorators
from telemetry.util import trace_runner
from telemetry.internal.browser import browser_finder
from telemetry.testing import options_for_unittests
from telemetry.testing import tab_test_case
from telemetry.timeline import model as model_module
from telemetry.timeline import tracing_config

def ReadMarkerEvents(trace_data):
  # Parse the trace and extract all test markers & trace-flushing markers
  return trace_runner.ExecuteMappingCodeOnTraceData(
      trace_data, """
function processTrace(results, model) {
    var markers = [];
    for (const thread of model.getAllThreads()) {
        for (const event of thread.asyncSliceGroup.slices) {
            if (event.title.startsWith('test-marker-') ||
                event.title === 'flush-tracing') {
                markers.push({'title': event.title, 'start': event.start});
           }
       }
   }
   results.addPair('markers', markers);
};
       """)['markers']

class TracingControllerTest(tab_test_case.TabTestCase):
  """Tests that start tracing when a browser tab is already active."""

  @decorators.Isolated
  def testExceptionRaisedInStopTracing(self):
    tracing_controller = self._tab.browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)

    self.Navigate('blank.html')

    def _FakeStopChromeTracing(*args):
      del args  # Unused
      raise Exception('Intentional Tracing Exception')

    self._tab._inspector_backend._devtools_client.StopChromeTracing = (
        _FakeStopChromeTracing)
    with self.assertRaisesRegexp(Exception, 'Intentional Tracing Exception'):
      tracing_controller.StopTracing()

    # Tracing is stopped even if there is exception.
    self.assertFalse(tracing_controller.is_tracing_running)

  @decorators.Isolated
  def testGotTrace(self):
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)

    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    # Test that trace data is parsable
    model = model_module.TimelineModel(trace_data)
    assert len(model.processes) > 0

  @decorators.Isolated
  def testStartAndStopTraceMultipleTimes(self):
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True
    tracing_controller.StartTracing(config)
    self.assertFalse(tracing_controller.StartTracing(config))

    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    # Test that trace data is parsable
    model_module.TimelineModel(trace_data)
    self.assertFalse(tracing_controller.is_tracing_running)
    # Calling stop again will raise exception
    self.assertRaises(Exception, tracing_controller.StopTracing)

  @decorators.Isolated
  @decorators.Disabled('win')  # crbug.com/829976
  def testFlushTracing(self):
    subtrace_count = 5

    tab = self._browser.tabs[0]

    # Set up the tracing config.
    tracing_controller = self._browser.platform.tracing_controller
    config = tracing_config.TracingConfig()
    config.enable_chrome_trace = True

    # Start tracing and inject a unique marker into the sub-trace.
    tracing_controller.StartTracing(config)
    self.assertTrue(tracing_controller.is_tracing_running)
    tab.AddTimelineMarker('test-marker-0')

    # Flush tracing |subtrace_count - 1| times and inject a unique marker into
    # the sub-trace each time.
    for i in xrange(1, subtrace_count):
      tracing_controller.FlushTracing()
      self.assertTrue(tracing_controller.is_tracing_running)
      tab.AddTimelineMarker('test-marker-%d' % i)

    # Stop tracing.
    trace_data, errors = tracing_controller.StopTracing()
    self.assertEqual(errors, [])
    self.assertFalse(tracing_controller.is_tracing_running)

    # Check that the markers 'test-marker-0', 'flush-tracing',
    # 'test-marker-1', ..., 'flush-tracing',
    # 'test-marker-|subtrace_count - 1|' are monotonic.
    markers = ReadMarkerEvents(trace_data)
    self.assertEquals(2 * subtrace_count - 1, len(markers))
    for i in xrange(0, len(markers) - 2):
      if i % 2 == 0:
        expected_title = 'test-marker-%d' % (i/2)
      else:
        expected_title = 'flush-tracing'
      self.assertEquals(expected_title, markers[i]['title'])
      self.assertLess(markers[i]['start'], markers[i + 1]['start'])

class StartupTracingTest(unittest.TestCase):
  """Tests that start tracing before the browser is created."""

  def setUp(self):
    finder_options = options_for_unittests.GetCopy()
    self.possible_browser = browser_finder.FindBrowser(finder_options)
    if not self.possible_browser:
      raise Exception('No browser found, cannot continue test.')
    self.browser_options = finder_options.browser_options
    self.config = tracing_config.TracingConfig()
    self.config.enable_chrome_trace = True

  def tearDown(self):
    if self.possible_browser and self.tracing_controller.is_tracing_running:
      self.tracing_controller.StopTracing()

  @property
  def tracing_controller(self):
    return self.possible_browser.platform.tracing_controller

  def StopTracingAndGetTestMarkers(self):
    self.assertTrue(self.tracing_controller.is_tracing_running)
    trace_data, errors = self.tracing_controller.StopTracing()
    self.assertFalse(self.tracing_controller.is_tracing_running)
    self.assertEqual(errors, [])
    return [
        e['title']
        for e in ReadMarkerEvents(trace_data)
        if e['title'].startswith('test-marker-')]

  @decorators.Isolated
  def testStopTracingWhileBrowserIsRunning(self):
    self.tracing_controller.StartTracing(self.config)
    with self.possible_browser.BrowserSession(self.browser_options) as browser:
      browser.tabs[0].Navigate('about:blank')
      browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
      browser.tabs[0].AddTimelineMarker('test-marker-foo')
      markers = self.StopTracingAndGetTestMarkers()
    self.assertEquals(markers, ['test-marker-foo'])

  @decorators.Isolated
  def testCloseBrowserBeforeTracingIsStopped(self):
    self.tracing_controller.StartTracing(self.config)
    with self.possible_browser.BrowserSession(self.browser_options) as browser:
      browser.tabs[0].Navigate('about:blank')
      browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
      browser.tabs[0].AddTimelineMarker('test-marker-bar')
      # TODO(crbug.com/854212): This should happen implicitly on browser.Close()
      self.tracing_controller.FlushTracing()
    markers = self.StopTracingAndGetTestMarkers()
    self.assertEquals(markers, ['test-marker-bar'])

  @decorators.Isolated
  def testRestartBrowserWhileTracing(self):
    expected_markers = ['test-marker-%i' % i for i in xrange(4)]
    self.tracing_controller.StartTracing(self.config)
    try:
      self.possible_browser.SetUpEnvironment(self.browser_options)
      for marker in expected_markers:
        with self.possible_browser.Create() as browser:
          browser.tabs[0].Navigate('about:blank')
          browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
          browser.tabs[0].AddTimelineMarker(marker)
          # TODO(crbug.com/854212): This should happen implicitly.
          self.tracing_controller.FlushTracing()
    finally:
      self.possible_browser.CleanUpEnvironment()
    markers = self.StopTracingAndGetTestMarkers()
    # Markers may be out of order.
    self.assertItemsEqual(markers, expected_markers)
<|endoftext|>


<commit_before>"""
TASKS:
    init:
        maintain SSH tunnel to conductor
        listen to Web API
        open DB connection
    runtime:
        maintain DB of inventory histories?
        generate HTML reports
        serve reports on request

API for conductor:
    receive_inventory_and_map

Dashboard:
    web interface
    websocket push
    status of all camera_units
        connected
        current status ( color coded )
        inventory
        exceptions

"""

import importlib
import json
import os
import settings
import sys
import threading
import time

import crystal_helpers as c

from thirtybirds_2_0.Network.manager import init as network_init
from thirtybirds_2_0.Network.email_simple import init as email_init

BASE_PATH = os.path.dirname(os.path.realpath(__file__))
UPPER_PATH = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
DEVICES_PATH = "%s/Hosts/" % (BASE_PATH )
THIRTYBIRDS_PATH = "%s/thirtybirds" % (UPPER_PATH )

sys.path.append(BASE_PATH)
sys.path.append(UPPER_PATH)

global last_f1
global last_f2
global last_f3

"""
class Main(threading.Thread):
    def __init__(self, hostname):
        threading.Thread.__init__(self)
        self.hostname = hostname
        ### NETWORK ###

        ### SET UP SUBSCRIPTIONS AND LISTENERS ###

        ### SET UP ATTAR ### so any exceptions can be reported

    def run(self):
        while True:
            time.sleep(60)

        ###  ###
"""

class FPGA():
    def __init__(
        self,
        spi_chipeselect,
        spi_masterslave
    ):
        self.spi_chipeselect = spi_chipeselect
        self.spi_masterslave = spi_masterslave
        self.spi_connection = None # to do
        # create SPI connection
    def send(self, filter_a, filter_b):
        #self.spi_connection.send
        print "FPGA: ", filter_a, filter_b

class TONE():
    def __init__(
        self,
        spi_chipeselect_for_dac,
        spi_masterslave_for_dac
    ):
        self.spi_chipeselect_for_dac = spi_chipeselect_for_dac
        self.spi_masterslave_for_dac = spi_masterslave_for_dac
        self.spi_connection = None # to do

    def send(self, freq, vol):
        #self.spi_connection.send
        print "TONE: ", freq, vol

# class TONES():
#     def __init__(
#         self,
#         spi_chipeselect_for_dac_1,
#         spi_masterslave_for_dac_1,
#         spi_chipeselect_for_dac_2,
#         spi_masterslave_for_dac_2,
#         spi_chipeselect_for_dac_3,
#         spi_masterslave_for_dac_3,
#         spi_chipeselect_for_fpga,
#         spi_masterslave_for_fpga
#     ):
#         self.tone_1 = TONE(spi_chipeselect_for_dac_1, spi_masterslave_for_dac_1)
#         self.tone_2 = TONE(spi_chipeselect_for_dac_2 , spi_masterslave_for_dac_2)
#         self.tone_3 = TONE(spi_chipeselect_for_dac_3, spi_masterslave_for_dac_3)
#         self.fpga = FPGA(spi_chipeselect_for_fpga,spi_masterslave_for_fpga)

#     def send(self, multi_msg):
#         self.tone_1.send(multi_msg[0],multi_msg[1])
#         self.tone_2.send(multi_msg[2],multi_msg[3])
#         self.tone_3.send(multi_msg[4],multi_msg[5])
#         self.fpga.send(multi_msg[6],multi_msg[7])

# tones = TONES(
#         , #spi_chipeselect_for_dac_1,
#         0, #spi_masterslave_for_dac_1,
#         , #spi_chipeselect_for_dac_2,
#         0, #spi_masterslave_for_dac_2,
#         , #spi_chipeselect_for_dac_3,
#         0, #spi_masterslave_for_dac_3,
#         , #spi_chipeselect_for_fpga,
#          #spi_masterslave_for_fpga
# )

def network_status_handler(msg):
    print "network_status_handler", msg

def network_message_handler(msg):
    print "network_message_handler", msg
    topic = msg[0]
    #host, sensor, data = yaml.safe_load(msg[1])
    if topic == "__heartbeat__":
        print "heartbeat received", msg

    if topic == "voice_3":
        # tones.send(eval(msg[1]))

        # quick hack -- will make this better later!
        payload = eval(msg[1])
        offset = 167500
        print offset-int(payload[0])

        if (payload[1] > 0):
            c.send_freq(0, offset-int(payload[0]))
            c.send_freq(1, offset-int(payload[2]))
            c.send_freq(2, offset-int(payload[4]))
        else:
            c.send_freq(0, 0)
            c.send_freq(1, 0)
            c.send_freq(2, 0)

        c.set_levels(0, 255 if payload[1] < 0.05 else 220)
        c.set_levels(1, 255 if payload[3] < 0.05 else 220)
        c.set_levels(2, 255 if payload[5] < 0.05 else 220)
        #c.set_levels(0, int(254 - (payload[1] * 10)))
        #c.set_levels(1, int(254 - (payload[3] * 10)))
        #c.set_levels(2, int(254 - (payload[5] * 10)))

network = None # makin' it global

def init(HOSTNAME):
    c.init()

    c.send_freq(0, 0)
    c.send_freq(1, 0)
    c.send_freq(2, 0)

    c.set_levels(0, 0)
    c.set_levels(1, 0)
    c.set_levels(2, 0)

    global network
    network = network_init(
        hostname=HOSTNAME,
        role="client",
        discovery_multicastGroup=settings.discovery_multicastGroup,
        discovery_multicastPort=settings.discovery_multicastPort,
        discovery_responsePort=settings.discovery_responsePort,
        pubsub_pubPort=settings.pubsub_pubPort,
        message_callback=network_message_handler,
        status_callback=network_status_handler
    )

    network.subscribe_to_topic("system")  # subscribe to all system messages
    network.subscribe_to_topic("voice_3")
    #main = Main(HOSTNAME)
    #main.start()

<commit_msg>fixing gain distortion- bool hack<commit_after>"""
TASKS:
    init:
        maintain SSH tunnel to conductor
        listen to Web API
        open DB connection
    runtime:
        maintain DB of inventory histories?
        generate HTML reports
        serve reports on request

API for conductor:
    receive_inventory_and_map

Dashboard:
    web interface
    websocket push
    status of all camera_units
        connected
        current status ( color coded )
        inventory
        exceptions

"""

import importlib
import json
import os
import settings
import sys
import threading
import time

import crystal_helpers as c

from thirtybirds_2_0.Network.manager import init as network_init
from thirtybirds_2_0.Network.email_simple import init as email_init

BASE_PATH = os.path.dirname(os.path.realpath(__file__))
UPPER_PATH = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
DEVICES_PATH = "%s/Hosts/" % (BASE_PATH )
THIRTYBIRDS_PATH = "%s/thirtybirds" % (UPPER_PATH )

sys.path.append(BASE_PATH)
sys.path.append(UPPER_PATH)

global last_f1
global last_f2
global last_f3

"""
class Main(threading.Thread):
    def __init__(self, hostname):
        threading.Thread.__init__(self)
        self.hostname = hostname
        ### NETWORK ###

        ### SET UP SUBSCRIPTIONS AND LISTENERS ###

        ### SET UP ATTAR ### so any exceptions can be reported

    def run(self):
        while True:
            time.sleep(60)

        ###  ###
"""

class FPGA():
    def __init__(
        self,
        spi_chipeselect,
        spi_masterslave
    ):
        self.spi_chipeselect = spi_chipeselect
        self.spi_masterslave = spi_masterslave
        self.spi_connection = None # to do
        # create SPI connection
    def send(self, filter_a, filter_b):
        #self.spi_connection.send
        print "FPGA: ", filter_a, filter_b

class TONE():
    def __init__(
        self,
        spi_chipeselect_for_dac,
        spi_masterslave_for_dac
    ):
        self.spi_chipeselect_for_dac = spi_chipeselect_for_dac
        self.spi_masterslave_for_dac = spi_masterslave_for_dac
        self.spi_connection = None # to do

    def send(self, freq, vol):
        #self.spi_connection.send
        print "TONE: ", freq, vol

# class TONES():
#     def __init__(
#         self,
#         spi_chipeselect_for_dac_1,
#         spi_masterslave_for_dac_1,
#         spi_chipeselect_for_dac_2,
#         spi_masterslave_for_dac_2,
#         spi_chipeselect_for_dac_3,
#         spi_masterslave_for_dac_3,
#         spi_chipeselect_for_fpga,
#         spi_masterslave_for_fpga
#     ):
#         self.tone_1 = TONE(spi_chipeselect_for_dac_1, spi_masterslave_for_dac_1)
#         self.tone_2 = TONE(spi_chipeselect_for_dac_2 , spi_masterslave_for_dac_2)
#         self.tone_3 = TONE(spi_chipeselect_for_dac_3, spi_masterslave_for_dac_3)
#         self.fpga = FPGA(spi_chipeselect_for_fpga,spi_masterslave_for_fpga)

#     def send(self, multi_msg):
#         self.tone_1.send(multi_msg[0],multi_msg[1])
#         self.tone_2.send(multi_msg[2],multi_msg[3])
#         self.tone_3.send(multi_msg[4],multi_msg[5])
#         self.fpga.send(multi_msg[6],multi_msg[7])

# tones = TONES(
#         , #spi_chipeselect_for_dac_1,
#         0, #spi_masterslave_for_dac_1,
#         , #spi_chipeselect_for_dac_2,
#         0, #spi_masterslave_for_dac_2,
#         , #spi_chipeselect_for_dac_3,
#         0, #spi_masterslave_for_dac_3,
#         , #spi_chipeselect_for_fpga,
#          #spi_masterslave_for_fpga
# )

def network_status_handler(msg):
    print "network_status_handler", msg

def network_message_handler(msg):
    print "network_message_handler", msg
    topic = msg[0]
    #host, sensor, data = yaml.safe_load(msg[1])
    if topic == "__heartbeat__":
        print "heartbeat received", msg

    if topic == "voice_3":
        # tones.send(eval(msg[1]))

        # quick hack -- will make this better later!
        payload = eval(msg[1])
        offset = 167500
        print offset-int(payload[0])

        if (payload[1] > 0):
            c.send_freq(0, offset-int(payload[0]))
            c.send_freq(1, offset-int(payload[2]))
            c.send_freq(2, offset-int(payload[4]))
        else:
            c.send_freq(0, 0)
            c.send_freq(1, 0)
            c.send_freq(2, 0)

        c.set_levels(0, 255 if payload[1] < 0.05 else 180)
        c.set_levels(1, 255 if payload[3] < 0.05 else 180)
        c.set_levels(2, 255 if payload[5] < 0.05 else 180)
        #c.set_levels(0, int(254 - (payload[1] * 10)))
        #c.set_levels(1, int(254 - (payload[3] * 10)))
        #c.set_levels(2, int(254 - (payload[5] * 10)))

network = None # makin' it global

def init(HOSTNAME):
    c.init()

    c.send_freq(0, 0)
    c.send_freq(1, 0)
    c.send_freq(2, 0)

    c.set_levels(0, 0)
    c.set_levels(1, 0)
    c.set_levels(2, 0)

    global network
    network = network_init(
        hostname=HOSTNAME,
        role="client",
        discovery_multicastGroup=settings.discovery_multicastGroup,
        discovery_multicastPort=settings.discovery_multicastPort,
        discovery_responsePort=settings.discovery_responsePort,
        pubsub_pubPort=settings.pubsub_pubPort,
        message_callback=network_message_handler,
        status_callback=network_status_handler
    )

    network.subscribe_to_topic("system")  # subscribe to all system messages
    network.subscribe_to_topic("voice_3")
    #main = Main(HOSTNAME)
    #main.start()

<|endoftext|>


<commit_before>""" A context manager for a docker container. """
from __future__ import division, print_function

import socket
from contextlib import contextmanager
import uuid
import logging
import time
import typing
import docker

__version__ = '2017.8.1'
__all__ = ['new_container']
logger = logging.getLogger('dockerctx')

@contextmanager
def new_container(
        image_name,
        new_container_name=lambda: uuid.uuid4().hex,
        ports=None,
        tmpfs=None,
        ready_test=None,
        privileged=None,
        docker_api_version='auto',
        **kwargs):
    """Start a docker container, and kill+remove when done.

    :param new_container_name: The container name. By default, a UUID will be used.
        If a callable, the result must be a str.
    :type new_container_name: str | callable
    :param ports: The list of port mappings to configure on the docker
        container. The format is the same as that used in the `docker`
        package, e.g. `ports={'5432/tcp': 60011}`
    :type ports: typing.Dict[str, int]
    :param tmpfs: When creating a container you can specify paths to be mounted
        with tmpfs. It can be a list or a dictionary to configure on the docker
        container. If it's a list, each item is a string specifying the path and
        (optionally) any configuration for the mount, e.g. `tmpfs={'/mnt/vol2': '',
        '/mnt/vol1': 'size=3G,uid=1000'}`
    :type tmpfs: typing.Dict[str, str]
    :param ready_test: A function to run to verify whether the container is "ready"
        (in some sense) before yielding the container back to the caller. An example
        of such a test is the `accepting_connections` function in the this module,
        which will try repeatedly to connect to a socket, until either successfuly,
        or a max timeout is reached. Use functools.partial to wrap up the args.
    :type ready_test: typing.Callable[[], bool]
    :param privileged: a privileged container is given access to all devices on
        the host as well as set some configuration in AppArmor or SELinux to allow
        the container nearly all the same access to the host as processes running
        outside containers on the host.
    :type ports: bool
    :param kwargs: These extra keyword arguments will be passed through to the
        `client.containers.run()` call.  One of the more commons ones is to pass
        a custom command through.

    """
    _ = new_container_name
    name = str(_() if callable(_) else _)
    client = docker.from_env(version=docker_api_version)

    logger.info('New postgres container: %s', name)
    container = client.containers.run(image_name, name=name, tmpfs=tmpfs, privileged=False, detach=True, ports=ports,
                                      **kwargs)
    try:
        logger.info('Waiting for postgres to be ready')
        if ready_test and not ready_test():
            raise ConnectionError(
                'Container {} not ready fast enough.'.format(name)
            )
        yield container
    finally:
        logger.info('Stopping container %s', name)
        # TODO: container.stop() does not seem to work here (e.g. for postgres)
        container.kill()
        logger.info('Removing container %s', name)
        container.remove()

def accepting_connections(host, port, timeout=20):
    """Try to make a socket connection to `(host, port)`

    I'll try every 200 ms, and eventually give up after `timeout`.

    :type host: str
    :type port: int
    :type timeout: int
    :return: True for successful connection, False otherwise
    :rtype: bool
    """
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s = socket.create_connection((host, port))
            logger.debug('Connected!')
            s.close()
            return True
        except socket.error as ex:
            logger.debug("Connection failed with errno %s: %s",
                         ex.errno, ex.strerror)
        time.sleep(0.2)
    return False

def pg_ready(host, port, dbuser='postgres', dbname='postgres',
             timeout=20, poll_freq=0.2):
    """Wait until a postgres instance is ready to receive connections.

    .. note::

        This requires psycopg2 to be installed.

    :type host: str
    :type port: int
    :type timeout: float
    :type poll_freq: float
    """
    import psycopg2
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            conn = psycopg2.connect(
                "host={host} port={port} user={dbuser} "
                "dbname={dbname}".format(**vars())
            )
            logger.debug('Connected successfully.')
            conn.close()
            return True
        except psycopg2.OperationalError as ex:
            logger.debug("Connection failed: {0}".format(ex));
        time.sleep(poll_freq)

    logger.error('Postgres readiness check timed out.')
    return False

@contextmanager
def session_scope(session_cls):
    """Provide a transactional scope around a series of operations.

    .. note::

        This requires SQLAlchemy to be installed.

    :type: sqlalchemy.orm.Session
    """
    session = session_cls()
    try:
        logger.debug('Yielding session')
        yield session
        logger.debug('Committing session')
        session.commit()
    except:
        logger.exception('Error detected, rolling back session')
        session.rollback()
        raise
    finally:
        logger.debug('Closing session')
        session.close()

def get_open_port():
    """Return a currently-unused local network TCP port number

    This is extremely handy when running unit tests because you may
    not always be able to get the port of your choice, especially
    in a continuous-integration context.

    :return: TCP port number
    :rtype: int
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 0))  # Using zero means the OS assigns one
    address_info = s.getsockname()
    port = int(address_info[1])
    s.close()
    return port
<commit_msg>Explicit "privileged" argument is not required<commit_after>""" A context manager for a docker container. """
from __future__ import division, print_function

import socket
from contextlib import contextmanager
import uuid
import logging
import time
import typing
import docker

__version__ = '2017.8.1'
__all__ = ['new_container']
logger = logging.getLogger('dockerctx')

@contextmanager
def new_container(
        image_name,
        new_container_name=lambda: uuid.uuid4().hex,
        ports=None,
        tmpfs=None,
        ready_test=None,
        docker_api_version='auto',
        **kwargs):
    """Start a docker container, and kill+remove when done.

    :param new_container_name: The container name. By default, a UUID will be used.
        If a callable, the result must be a str.
    :type new_container_name: str | callable
    :param ports: The list of port mappings to configure on the docker
        container. The format is the same as that used in the `docker`
        package, e.g. `ports={'5432/tcp': 60011}`
    :type ports: typing.Dict[str, int]
    :param tmpfs: When creating a container you can specify paths to be mounted
        with tmpfs. It can be a list or a dictionary to configure on the docker
        container. If it's a list, each item is a string specifying the path and
        (optionally) any configuration for the mount, e.g. `tmpfs={'/mnt/vol2': '',
        '/mnt/vol1': 'size=3G,uid=1000'}`
    :type tmpfs: typing.Dict[str, str]
    :param ready_test: A function to run to verify whether the container is "ready"
        (in some sense) before yielding the container back to the caller. An example
        of such a test is the `accepting_connections` function in the this module,
        which will try repeatedly to connect to a socket, until either successfuly,
        or a max timeout is reached. Use functools.partial to wrap up the args.
    :type ready_test: typing.Callable[[], bool]
    :param privileged: a privileged container is given access to all devices on
        the host as well as set some configuration in AppArmor or SELinux to allow
        the container nearly all the same access to the host as processes running
        outside containers on the host.
    :type ports: bool
    :param kwargs: These extra keyword arguments will be passed through to the
        `client.containers.run()` call.  One of the more commons ones is to pass
        a custom command through.

    """
    _ = new_container_name
    name = str(_() if callable(_) else _)
    client = docker.from_env(version=docker_api_version)

    logger.info('New postgres container: %s', name)
    container = client.containers.run(
        image_name, name=name, tmpfs=tmpfs, detach=True, ports=ports,
        **kwargs
    )
    try:
        logger.info('Waiting for postgres to be ready')
        if ready_test and not ready_test():
            raise ConnectionError(
                'Container {} not ready fast enough.'.format(name)
            )
        yield container
    finally:
        logger.info('Stopping container %s', name)
        # TODO: container.stop() does not seem to work here (e.g. for postgres)
        container.kill()
        logger.info('Removing container %s', name)
        container.remove()

def accepting_connections(host, port, timeout=20):
    """Try to make a socket connection to `(host, port)`

    I'll try every 200 ms, and eventually give up after `timeout`.

    :type host: str
    :type port: int
    :type timeout: int
    :return: True for successful connection, False otherwise
    :rtype: bool
    """
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s = socket.create_connection((host, port))
            logger.debug('Connected!')
            s.close()
            return True
        except socket.error as ex:
            logger.debug("Connection failed with errno %s: %s",
                         ex.errno, ex.strerror)
        time.sleep(0.2)
    return False

def pg_ready(host, port, dbuser='postgres', dbname='postgres',
             timeout=20, poll_freq=0.2):
    """Wait until a postgres instance is ready to receive connections.

    .. note::

        This requires psycopg2 to be installed.

    :type host: str
    :type port: int
    :type timeout: float
    :type poll_freq: float
    """
    import psycopg2
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            conn = psycopg2.connect(
                "host={host} port={port} user={dbuser} "
                "dbname={dbname}".format(**vars())
            )
            logger.debug('Connected successfully.')
            conn.close()
            return True
        except psycopg2.OperationalError as ex:
            logger.debug("Connection failed: {0}".format(ex));
        time.sleep(poll_freq)

    logger.error('Postgres readiness check timed out.')
    return False

@contextmanager
def session_scope(session_cls):
    """Provide a transactional scope around a series of operations.

    .. note::

        This requires SQLAlchemy to be installed.

    :type: sqlalchemy.orm.Session
    """
    session = session_cls()
    try:
        logger.debug('Yielding session')
        yield session
        logger.debug('Committing session')
        session.commit()
    except:
        logger.exception('Error detected, rolling back session')
        session.rollback()
        raise
    finally:
        logger.debug('Closing session')
        session.close()

def get_open_port():
    """Return a currently-unused local network TCP port number

    This is extremely handy when running unit tests because you may
    not always be able to get the port of your choice, especially
    in a continuous-integration context.

    :return: TCP port number
    :rtype: int
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 0))  # Using zero means the OS assigns one
    address_info = s.getsockname()
    port = int(address_info[1])
    s.close()
    return port
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob, imp, sys, threading, time, urllib
from flask import Flask,request
import core

name = "Mainframe"

app = Flask(__name__)

threads = []

class flask_thread (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.name = "Flask_Thread"
    def run(self):
        global app
        print "Starting " + self.name
        app.run(host="0.0.0.0")
        print "Exiting " + self.name
    def stop(self):
        urllib.urlopen("http://127.0.0.1:5000/shutdown")

def import_plugins():
    """
    Function to import plugins from the /plugins folder. Valid plugins are marked by <name>.is_sam_plugin == 1.
    """
    plugins = []
    #list files in /plugin folder
    filenames = glob.glob("plugins/*_plugin.py")
    core.log(name, "Importing Plugins: \n {filenames}".format(filenames = filenames))

    #try importing each plugin
    for i in range(0,len(filenames)):
        core.log(name, "Found {}".format(filenames[i]))
        try:
            new_plugin = imp.load_source("samplugin{}".format(i), filenames[i])
            core.log(name, "{} imported successfully.".format(filenames[i]))
            #Test if the imported file is a valid Plugin
            try:
                if new_plugin.is_sam_plugin:
                    plugins.append(new_plugin)
                    core.log(name, "  Name:\t{}\n  Keywords:\t{}".format(new_plugin.name, new_plugin.keywords))
                    new_plugin.initialize()
            except AttributeError:
                core.log(name, "{} is not a valid Plugin.".format(filenames[i]))
        except ImportError:
            core.log(name, "{} wasn't imported successfully.".format(filenames[i]))
    return plugins

@app.route("/")
def process():
    return "Running"

@app.route('/shutdown')
def shutdown():
    func = request.environ.get("werkzeug.server.shutdown")
    if func is None:
        raise RuntimeError("Not running with the Werkzeug Server")
    func()
    return 'Server shutting down...'
'''
@app.route('/restart')
def restart():
    shutdown_server()
    main()
    return 'Server restarting...'
'''
def main():
    global threadID
    core.log(name, "Starting up!")
    t = flask_thread()
    t.start()
    threads.append(t)
    #plugins = import_plugins()
    core.log(name, "Startup finished.")

if __name__ == "__main__":
    main()
    time.sleep(30)
    for t in threads:
        t.stop()
    print("Shutdown completed.")

<commit_msg>added importing plugins again<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob, imp, sys, threading, time, urllib
from flask import Flask,request
import core

name = "Mainframe"

app = Flask(__name__)

threads = []

class flask_thread (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.name = "Flask_Thread"
    def run(self):
        global app
        print "Starting " + self.name
        app.run(host="0.0.0.0")
        print "Exiting " + self.name
    def stop(self):
        urllib.urlopen("http://127.0.0.1:5000/shutdown")

def import_plugins():
    """
    Function to import plugins from the /plugins folder. Valid plugins are marked by <name>.is_sam_plugin == 1.
    """
    plugins = []
    #list files in /plugin folder
    filenames = glob.glob("plugins/*_plugin.py")
    core.log(name, "Importing Plugins: \n {filenames}".format(filenames = filenames))

    #try importing each plugin
    for i in range(0,len(filenames)):
        core.log(name, "Found {}".format(filenames[i]))
        try:
            new_plugin = imp.load_source("samplugin{}".format(i), filenames[i])
            core.log(name, "{} imported successfully.".format(filenames[i]))
            #Test if the imported file is a valid Plugin
            try:
                if new_plugin.is_sam_plugin:
                    plugins.append(new_plugin)
                    core.log(name, "  Name:\t{}\n  Keywords:\t{}".format(new_plugin.name, new_plugin.keywords))
                    new_plugin.initialize()
            except AttributeError:
                core.log(name, "{} is not a valid Plugin.".format(filenames[i]))
        except ImportError:
            core.log(name, "{} wasn't imported successfully.".format(filenames[i]))
    return plugins

@app.route("/")
def process():
    return "Running"

@app.route('/shutdown')
def shutdown():
    func = request.environ.get("werkzeug.server.shutdown")
    if func is None:
        raise RuntimeError("Not running with the Werkzeug Server")
    func()
    return 'Server shutting down...'
'''
@app.route('/restart')
def restart():
    shutdown_server()
    main()
    return 'Server restarting...'
'''
def main():
    global threadID
    core.log(name, "Starting up!")
    t = flask_thread()
    t.start()
    threads.append(t)
    plugins = import_plugins()
    core.log(name, "Startup finished.")

if __name__ == "__main__":
    main()
    time.sleep(30)
    for t in threads:
        t.stop()
    print("Shutdown completed.")

<|endoftext|>


<commit_before>import Ogre
import OgreRTShader

class SGResolver(Ogre.MaterialManager_Listener):
    def __init__(self, shadergen):
        Ogre.MaterialManager_Listener.__init__(self)
        self.shadergen = shadergen

    def handleSchemeNotFound(self, idx, name, mat, lod_idx, rend):
        if name != OgreRTShader.cvar.ShaderGenerator_DEFAULT_SCHEME_NAME:
            return None

        def_name = Ogre.cvar.MaterialManager_DEFAULT_SCHEME_NAME
        succ = self.shadergen.createShaderBasedTechnique(mat, def_name, name)

        if not succ:
            return None

        self.shadergen.validateMaterial(name, mat.getName(), mat.getGroup())

        return mat.getTechnique(1)

def main():
    root = Ogre.Root("plugins.cfg", "ogre.cfg", "")

    cfg = Ogre.ConfigFile()
    cfg.loadDirect("resources.cfg")

    rgm = Ogre.ResourceGroupManager.getSingleton()

    for sec, settings in cfg.getSettingsBySection().items():
        for kind, loc in settings.items():
            rgm.addResourceLocation(loc, kind, sec)

    arch = cfg.getSettings("General").values()[0]
    rgm.addResourceLocation(arch + "/materials/programs/GLSL", "FileSystem", "General")
    arch += "/RTShaderLib"
    rgm.addResourceLocation(arch + "/materials", "FileSystem", "General")
    rgm.addResourceLocation(arch + "/GLSL", "FileSystem", "General")

    if not root.restoreConfig():
        root.showConfigDialog(Ogre.ConfigDialog())

    win = root.initialise(True)

    OgreRTShader.ShaderGenerator.initialize()
    shadergen = OgreRTShader.ShaderGenerator.getSingleton()

    sgres = SGResolver(shadergen)
    Ogre.MaterialManager.getSingleton().addListener(sgres)

    rgm.initialiseAllResourceGroups()

    rs = shadergen.getRenderState(OgreRTShader.cvar.ShaderGenerator_DEFAULT_SCHEME_NAME)
    rs.addTemplateSubRenderState(shadergen.createSubRenderState(OgreRTShader.cvar.PerPixelLighting_Type));

    scn_mgr = root.createSceneManager(Ogre.ST_GENERIC)
    shadergen.addSceneManager(scn_mgr)

    scn_mgr.setAmbientLight(Ogre.ColourValue(.1, .1, .1))

    light = scn_mgr.createLight("MainLight")
    lightnode = scn_mgr.getRootSceneNode().createChildSceneNode()
    lightnode.setPosition(0, 10, 15)
    lightnode.attachObject(light)

    cam = scn_mgr.createCamera("myCam")
    cam.setPosition(0, 0, 15)
    cam.setNearClipDistance(5)
    cam.lookAt(0, 0, -1)
    vp = win.addViewport(cam)
    vp.setBackgroundColour(Ogre.ColourValue(.3, .3, .3))

    ent = scn_mgr.createEntity("Sinbad.mesh")
    node = scn_mgr.getRootSceneNode().createChildSceneNode()
    node.attachObject(ent)

    root.startRendering()

if __name__ == "__main__":
    main()
<commit_msg>Samples: python - update raw sample to deprecation-less API<commit_after>import Ogre
import OgreRTShader

class SGResolver(Ogre.MaterialManager_Listener):
    def __init__(self, shadergen):
        Ogre.MaterialManager_Listener.__init__(self)
        self.shadergen = shadergen

    def handleSchemeNotFound(self, idx, name, mat, lod_idx, rend):
        if name != OgreRTShader.cvar.ShaderGenerator_DEFAULT_SCHEME_NAME:
            return None

        def_name = Ogre.cvar.MaterialManager_DEFAULT_SCHEME_NAME
        succ = self.shadergen.createShaderBasedTechnique(mat, def_name, name)

        if not succ:
            return None

        self.shadergen.validateMaterial(name, mat.getName(), mat.getGroup())

        return mat.getTechnique(1)

def main():
    root = Ogre.Root("plugins.cfg", "ogre.cfg", "")

    cfg = Ogre.ConfigFile()
    cfg.loadDirect("resources.cfg")

    rgm = Ogre.ResourceGroupManager.getSingleton()

    for sec, settings in cfg.getSettingsBySection().items():
        for kind, loc in settings.items():
            rgm.addResourceLocation(loc, kind, sec)

    arch = cfg.getSettings("General").values()[0]
    rgm.addResourceLocation(arch + "/materials/programs/GLSL120", "FileSystem", "General")
    arch += "/RTShaderLib"
    rgm.addResourceLocation(arch + "/materials", "FileSystem", "General")
    rgm.addResourceLocation(arch + "/GLSL", "FileSystem", "General")

    if not root.restoreConfig():
        root.showConfigDialog(Ogre.ConfigDialog())

    win = root.initialise(True)

    OgreRTShader.ShaderGenerator.initialize()
    shadergen = OgreRTShader.ShaderGenerator.getSingleton()

    sgres = SGResolver(shadergen)
    Ogre.MaterialManager.getSingleton().addListener(sgres)

    rgm.initialiseAllResourceGroups()

    rs = shadergen.getRenderState(OgreRTShader.cvar.ShaderGenerator_DEFAULT_SCHEME_NAME)
    rs.addTemplateSubRenderState(shadergen.createSubRenderState(OgreRTShader.cvar.PerPixelLighting_Type));

    scn_mgr = root.createSceneManager()
    shadergen.addSceneManager(scn_mgr)

    scn_mgr.setAmbientLight(Ogre.ColourValue(.1, .1, .1))

    light = scn_mgr.createLight("MainLight")
    lightnode = scn_mgr.getRootSceneNode().createChildSceneNode()
    lightnode.setPosition(0, 10, 15)
    lightnode.attachObject(light)

    cam = scn_mgr.createCamera("myCam")
    cam.setNearClipDistance(5)

    camnode = scn_mgr.getRootSceneNode().createChildSceneNode()
    camnode.attachObject(cam)
    camnode.lookAt(Ogre.Vector3(0, 0, -1), Ogre.Node.TS_WORLD)
    camnode.setPosition(0, 0, 15)

    vp = win.addViewport(cam)
    vp.setBackgroundColour(Ogre.ColourValue(.3, .3, .3))

    ent = scn_mgr.createEntity("Sinbad.mesh")
    node = scn_mgr.getRootSceneNode().createChildSceneNode()
    node.attachObject(ent)

    root.startRendering()

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


<commit_before>from testix import scenario
from testix import testixexception
from testix import expectations
from testix import argumentexpectations
from testix import saveargument
from testix import fakeobject
from testix.startertests import startertestcollection
from testix.startertests.asserts import *

class StarterTestArgumentExpectations( startertestcollection.StarterTestCollection ):
	def starter_test_ArgumentEquals( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first' ) <<\
			expectations.Call( 'some object', [ 11 ], 'second' )
		STS_ASSERT_EQUALS( fakeObject( 10 ), 'first' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 10 )
		aScenario.end()

	def starter_test_ArgumentIsFakeObjectWithPath( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		anotherFakeObject = fakeobject.FakeObject( 'another fake object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 	'some object', [ argumentexpectations.ArgumentIsFakeObjectWithPath( 'another fake object' ) ],
								'the result' ) <<\
			expectations.Call( 	'some object', [ argumentexpectations.ArgumentIsFakeObjectWithPath( 'yet another' ) ],
								'another result' )

		STS_ASSERT_EQUALS( fakeObject( anotherFakeObject ), 'the result' )
		STS_ASSERT_EQUALS( fakeObject( fakeobject.FakeObject( 'yet another' ) ), 'another result' )
		aScenario.end()

	def starter_test_IgnoreArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first' ) <<\
			expectations.Call( 'some object', [ argumentexpectations.IgnoreArgument() ], 'second' )
		STS_ASSERT_EQUALS( fakeObject( 10 ), 'first' )
		STS_ASSERT_EQUALS( fakeObject( "this doens't matter" ), 'second' )
		aScenario.end()

	def starter_test_KeywordArguments( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first', kwargExpectations = { 'name': 'Lancelot' } ) <<\
			expectations.Call( 'some object', [ 11 ], 'second', kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_EQUALS( fakeObject( 10, name = 'Lancelot' ), 'first' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11, name = 'not Galahad'  )
		aScenario.end()

	def starter_test_KeywordArgumentsExpected_NoneGiven( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 11 ], 'result', kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11 )
		aScenario.end()

	def starter_test_KeywordArgumentsForThrowingCall( self ):
		class MyException( Exception ): pass

		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.ThrowingCall( 'some object', [ 'no kwargs will violate expectation' ], MyException, kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 'no kwargs will violate expectation' )
		aScenario.end()

		aScenario = scenario.Scenario() <<\
			expectations.ThrowingCall( 'some object', [ 11 ], MyException, kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( MyException, fakeObject, 11, name = 'Galahad' )
		aScenario.end()

	def starter_test_Bugfix_NumberOfArguments_can_be_different_FromExpectedNumberOfArguments( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ argumentexpectations.IgnoreArgument(), argumentexpectations.IgnoreArgument() ], 'result' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 1, 2, 3 )
		aScenario.end()

	def starter_test_SaveArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 'first', saveargument.SaveArgument( 'second' ) ], None )
		fakeObject( 'first', 'value of second argument' )
		aScenario.end()
		STS_ASSERT_EQUALS( saveargument.saved()[ 'second' ], 'value of second argument' )

	def starter_test_SaveArgument_With_KeyworkArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 'first'  ], None, kwargExpectations = { 'god': saveargument.SaveArgument( 'god' ) } )
		fakeObject( 'first', god = 'Zeus' )
		aScenario.end()
		STS_ASSERT_EQUALS( saveargument.saved()[ 'god' ], 'Zeus' )

	def starter_test_Bugfix_UnexpectedKeywordArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 11 ], 'some result', kwargExpectations = { 'name': 'Lancelot' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11, name = 'Lancelot', maidenName = 'Sarah' )
		aScenario.end()
StarterTestArgumentExpectations()
<commit_msg>FakeObject can be used as expectation directly<commit_after>from testix import scenario
from testix import testixexception
from testix import expectations
from testix import argumentexpectations
from testix import saveargument
from testix import fakeobject
from testix.startertests import startertestcollection
from testix.startertests.asserts import *

class StarterTestArgumentExpectations( startertestcollection.StarterTestCollection ):
	def starter_test_ArgumentEquals( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first' ) <<\
			expectations.Call( 'some object', [ 11 ], 'second' )
		STS_ASSERT_EQUALS( fakeObject( 10 ), 'first' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 10 )
		aScenario.end()

	def starter_test_ArgumentIsFakeObjectWithPath( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		anotherFakeObject = fakeobject.FakeObject( 'another fake object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 	'some object', [ argumentexpectations.ArgumentIsFakeObjectWithPath( 'another fake object' ) ],
								'the result' ) <<\
			expectations.Call( 	'some object', [ argumentexpectations.ArgumentIsFakeObjectWithPath( 'yet another' ) ],
								'another result' )

		STS_ASSERT_EQUALS( fakeObject( anotherFakeObject ), 'the result' )
		STS_ASSERT_EQUALS( fakeObject( fakeobject.FakeObject( 'yet another' ) ), 'another result' )
		aScenario.end()

	def starter_test_FakeObjectExpectation( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		fakeArgument = fakeobject.FakeObject( 'fake argument' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ fakeobject.FakeObject( 'fake argument' ) ], None )
		fakeObject( fakeArgument )
		aScenario.end()

	def starter_test_IgnoreArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first' ) <<\
			expectations.Call( 'some object', [ argumentexpectations.IgnoreArgument() ], 'second' )
		STS_ASSERT_EQUALS( fakeObject( 10 ), 'first' )
		STS_ASSERT_EQUALS( fakeObject( "this doens't matter" ), 'second' )
		aScenario.end()

	def starter_test_KeywordArguments( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 10 ], 'first', kwargExpectations = { 'name': 'Lancelot' } ) <<\
			expectations.Call( 'some object', [ 11 ], 'second', kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_EQUALS( fakeObject( 10, name = 'Lancelot' ), 'first' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11, name = 'not Galahad'  )
		aScenario.end()

	def starter_test_KeywordArgumentsExpected_NoneGiven( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 11 ], 'result', kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11 )
		aScenario.end()

	def starter_test_KeywordArgumentsForThrowingCall( self ):
		class MyException( Exception ): pass

		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.ThrowingCall( 'some object', [ 'no kwargs will violate expectation' ], MyException, kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 'no kwargs will violate expectation' )
		aScenario.end()

		aScenario = scenario.Scenario() <<\
			expectations.ThrowingCall( 'some object', [ 11 ], MyException, kwargExpectations = { 'name': 'Galahad' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( MyException, fakeObject, 11, name = 'Galahad' )
		aScenario.end()

	def starter_test_Bugfix_NumberOfArguments_can_be_different_FromExpectedNumberOfArguments( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ argumentexpectations.IgnoreArgument(), argumentexpectations.IgnoreArgument() ], 'result' )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 1, 2, 3 )
		aScenario.end()

	def starter_test_SaveArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 'first', saveargument.SaveArgument( 'second' ) ], None )
		fakeObject( 'first', 'value of second argument' )
		aScenario.end()
		STS_ASSERT_EQUALS( saveargument.saved()[ 'second' ], 'value of second argument' )

	def starter_test_SaveArgument_With_KeyworkArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 'first'  ], None, kwargExpectations = { 'god': saveargument.SaveArgument( 'god' ) } )
		fakeObject( 'first', god = 'Zeus' )
		aScenario.end()
		STS_ASSERT_EQUALS( saveargument.saved()[ 'god' ], 'Zeus' )

	def starter_test_Bugfix_UnexpectedKeywordArgument( self ):
		fakeObject = fakeobject.FakeObject( 'some object' )
		aScenario = scenario.Scenario() <<\
			expectations.Call( 'some object', [ 11 ], 'some result', kwargExpectations = { 'name': 'Lancelot' } )
		STS_ASSERT_THROWS_SPECIFIC_EXCEPTION( testixexception.ExpectationException, fakeObject, 11, name = 'Lancelot', maidenName = 'Sarah' )
		aScenario.end()
StarterTestArgumentExpectations()
<|endoftext|>