<commit_before>import getpass
import os
import time
import traceback
from threading import Thread

import praw
from bitcoinrpc.authproxy import AuthServiceProxy
from praw.models import Message, Comment

import bot_command
import bot_logger
import crypto
import lang
import user_function
import utils
import config
from config import rpc_config, bot_config, DATA_PATH

class SoDogeTip():
    def __init__(self):
        self.reddit = praw.Reddit(config.bot_name)

        self.rpc_main = AuthServiceProxy("http://%s:%s@%s:%s" % (
            rpc_config['doge_rpc_username'], rpc_config['doge_rpc_password'], rpc_config['doge_rpc_host'],
            rpc_config['doge_rpc_port']), timeout=120)

        self.rpc_antispam = AuthServiceProxy("http://%s:%s@%s:%s" % (
            rpc_config['doge_rpc_username'], rpc_config['doge_rpc_password'], rpc_config['doge_rpc_host'],
            rpc_config['doge_rpc_port']), timeout=120)

    def main(self):
        bot_logger.logger.info('Main Bot loop !')
        while True:
            try:
                if not os.path.exists(DATA_PATH + bot_config['user_history_path']):
                    os.makedirs(DATA_PATH + bot_config['user_history_path'])

                # create file if not exist (user storage)
                utils.create_user_storage()

                # create file if not exist (tip unregistered user )
                utils.create_unregistered_tip_storage()

                for msg in self.reddit.inbox.unread(limit=None):

                    if (type(msg) is not Message) and (type(msg) is not Comment):
                        bot_logger.logger.info('Not a good message !')
                        msg.reply(lang.message_not_supported)
                        self.mark_msg_read(msg)
                    else:
                        bot_logger.logger.info("%s - %s sub : %s" % (str(msg), msg.author.name, msg.subject))
                        msg_body = msg.body.strip()
                        msg_subject = msg.subject.strip()
                        split_message = msg_body.lower().split()

                        if msg_body == '+register' and msg_subject == '+register':
                            bot_command.register_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+info' and msg_subject == '+info':
                            bot_command.info_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+help' and msg_subject == '+help':
                            bot_command.help_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+balance' and msg_subject == '+balance':
                            bot_command.balance_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+history' and msg_subject == '+history':
                            bot_command.history_user(msg)
                            self.mark_msg_read(msg)

                        elif split_message.count('+withdraw') and msg_subject == '+withdraw':
                            bot_command.withdraw_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif split_message.count('+/u/sodogetiptest'):
                            bot_command.tip_user(self.rpc_main, self.reddit, msg)
                            self.mark_msg_read(msg)

                        else:
                            self.mark_msg_read(msg)
                            # msg.reply('Currently not supported')
                            bot_logger.logger.info('Currently not supported')
                            self.mark_msg_read(msg)

                # to not explode rate limit :)
                bot_logger.logger.info('Make an pause !')
                time.sleep(3)
            except:
                traceback.print_exc()
                bot_logger.logger.error('Main Bot loop crashed...')
                time.sleep(10)

    def mark_msg_read(self, msg):
        unread_messages = [msg]
        self.reddit.inbox.mark_read(unread_messages)

    def process_pending_tip(self):
        while True:
            bot_logger.logger.info('Make clean of unregistered tips')
            bot_command.replay_remove_pending_tip(self.rpc_main, self.reddit)
            time.sleep(60)

    def anti_spamming_tx(self):
        # protect against spam attacks of an address having UTXOs.
        while True:
            bot_logger.logger.info('Make clean of tx')
            # get list of account
            list_account = user_function.get_users()
            for account, address in list_account.items():
                time.sleep(1)  # don't flood daemon
                list_tx = self.rpc_antispam.listunspent(1, 99999999999, [address])
                unspent_amounts = []
                for i in range(0, len(list_tx), 1):
                    unspent_amounts.append(list_tx[i]['amount'])
                    if i > 200:
                        break

                if len(list_tx) > int(bot_config['spam_limit']):
                    bot_logger.logger.info('Consolidate %s account !' % account)
                    #amount = crypto.get_user_confirmed_balance(self.rpc_antispam, account)
                    crypto.send_to(self.rpc_antispam, address, address, sum(unspent_amounts), True)
            time.sleep(240)

if __name__ == "__main__":
    bot_logger.logger.info("Bot Started !!")

    config.init_passphrase()

    while True:
        try:
            Bot = SoDogeTip()

            thread_master = Thread(target=Bot.main)
            thread_pending_tip = Thread(target=Bot.process_pending_tip)
            thread_anti_spamming_tx = Thread(target=Bot.anti_spamming_tx)

            thread_master.start()
            thread_pending_tip.start()
            thread_anti_spamming_tx.start()

            thread_master.join()
            thread_pending_tip.join()
            thread_anti_spamming_tx.join()

            bot_logger.logger.error('All bot task finished ...')
        except:
            traceback.print_exc()
            bot_logger.logger.error('Resuming in 30sec...')
            time.sleep(30)
<commit_msg>Update dogetipper.py<commit_after>import getpass
import os
import time
import traceback
from threading import Thread

import praw
from bitcoinrpc.authproxy import AuthServiceProxy
from praw.models import Message, Comment

import bot_command
import bot_logger
import crypto
import lang
import user_function
import utils
import config
from config import rpc_config, bot_config, DATA_PATH

class SoDogeTip():
    def __init__(self):
        self.reddit = praw.Reddit(config.bot_name)

        self.rpc_main = AuthServiceProxy("http://%s:%s@%s:%s" % (
            rpc_config['doge_rpc_username'], rpc_config['doge_rpc_password'], rpc_config['doge_rpc_host'],
            rpc_config['doge_rpc_port']), timeout=120)

        self.rpc_antispam = AuthServiceProxy("http://%s:%s@%s:%s" % (
            rpc_config['doge_rpc_username'], rpc_config['doge_rpc_password'], rpc_config['doge_rpc_host'],
            rpc_config['doge_rpc_port']), timeout=120)

    def main(self):
        bot_logger.logger.info('Main Bot loop !')
        while True:
            try:
                if not os.path.exists(DATA_PATH + bot_config['user_history_path']):
                    os.makedirs(DATA_PATH + bot_config['user_history_path'])

                # create file if not exist (user storage)
                utils.create_user_storage()

                # create file if not exist (tip unregistered user )
                utils.create_unregistered_tip_storage()

                for msg in self.reddit.inbox.unread(limit=None):

                    if (type(msg) is not Message) and (type(msg) is not Comment):
                        bot_logger.logger.info('Not a good message !')
                        msg.reply(lang.message_not_supported)
                        self.mark_msg_read(msg)
                    else:
                        bot_logger.logger.info("%s - %s sub : %s" % (str(msg), msg.author.name, msg.subject))
                        msg_body = msg.body.strip()
                        msg_subject = msg.subject.strip()
                        split_message = msg_body.lower().split()

                        if msg_body == '+register' and msg_subject == '+register':
                            bot_command.register_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+info' and msg_subject == '+info':
                            bot_command.info_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+help' and msg_subject == '+help':
                            bot_command.help_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+balance' and msg_subject == '+balance':
                            bot_command.balance_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif msg_body == '+history' and msg_subject == '+history':
                            bot_command.history_user(msg)
                            self.mark_msg_read(msg)

                        elif split_message.count('+withdraw') and msg_subject == '+withdraw':
                            bot_command.withdraw_user(self.rpc_main, msg)
                            self.mark_msg_read(msg)

                        elif split_message.count('+/u/' + config.bot_name):
                            bot_command.tip_user(self.rpc_main, self.reddit, msg)
                            self.mark_msg_read(msg)

                        else:
                            self.mark_msg_read(msg)
                            # msg.reply('Currently not supported')
                            bot_logger.logger.info('Currently not supported')
                            self.mark_msg_read(msg)

                # to not explode rate limit :)
                bot_logger.logger.info('Make an pause !')
                time.sleep(3)
            except:
                traceback.print_exc()
                bot_logger.logger.error('Main Bot loop crashed...')
                time.sleep(10)

    def mark_msg_read(self, msg):
        unread_messages = [msg]
        self.reddit.inbox.mark_read(unread_messages)

    def process_pending_tip(self):
        while True:
            bot_logger.logger.info('Make clean of unregistered tips')
            bot_command.replay_remove_pending_tip(self.rpc_main, self.reddit)
            time.sleep(60)

    def anti_spamming_tx(self):
        # protect against spam attacks of an address having UTXOs.
        while True:
            bot_logger.logger.info('Make clean of tx')
            # get list of account
            list_account = user_function.get_users()
            for account, address in list_account.items():
                time.sleep(1)  # don't flood daemon
                list_tx = self.rpc_antispam.listunspent(1, 99999999999, [address])
                unspent_amounts = []
                for i in range(0, len(list_tx), 1):
                    unspent_amounts.append(list_tx[i]['amount'])
                    if i > 200:
                        break

                if len(list_tx) > int(bot_config['spam_limit']):
                    bot_logger.logger.info('Consolidate %s account !' % account)
                    #amount = crypto.get_user_confirmed_balance(self.rpc_antispam, account)
                    crypto.send_to(self.rpc_antispam, address, address, sum(unspent_amounts), True)
            time.sleep(240)

if __name__ == "__main__":
    bot_logger.logger.info("Bot Started !!")

    config.init_passphrase()

    while True:
        try:
            Bot = SoDogeTip()

            thread_master = Thread(target=Bot.main)
            thread_pending_tip = Thread(target=Bot.process_pending_tip)
            thread_anti_spamming_tx = Thread(target=Bot.anti_spamming_tx)

            thread_master.start()
            thread_pending_tip.start()
            thread_anti_spamming_tx.start()

            thread_master.join()
            thread_pending_tip.join()
            thread_anti_spamming_tx.join()

            bot_logger.logger.error('All bot task finished ...')
        except:
            traceback.print_exc()
            bot_logger.logger.error('Resuming in 30sec...')
            time.sleep(30)
<|endoftext|>


<commit_before>from sympy import sympify, Dummy, Matrix, Basic, Expr, solve, diff

# TODO order the imports and make them explicit
# TODO issue 2070: all the stuff about .args and rebuilding
# TODO better dosctrings and more distributed doctests
# TODO maybe a common class Field makes sense

class Manifold(Basic):
    """Object representing a mathematical manifold.

    The only role that it plays is to keep a list of all patches defined on the
    manifold.
    """
    def __init__(self, name, dim):
        super(Manifold, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.dim = dim
        self.patches = []
        # The patches list is necessary if a Patch instance needs to enumerate
        # other Patch instance on the same manifold.

class Patch(Basic):
    """Object representing a patch on a manifold.

    It serves as a container/parent for all coordinate system charts that can
    be defined on this patch.

    Examples:
    =========

    Define a Manifold and a Patch on that Manifold:
    >>> from sympy.differential_geometry import Manifold, Patch
    >>> m = Manifold('M', 3)
    >>> p = Patch('P', m)
    >>> p in m.patches
    True

    """
    # Contains a reference to the parent manifold in order to be able to access
    # other patches.
    def __init__(self, name, manifold):
        super(Patch, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.manifold = manifold
        self.manifold.patches.append(self)
        self.coord_systems = []
        # The list of coordinate systems is necessary for an instance of
        # CoordSystem to enumerate other coord systems on the patch.

class CoordSystem(Basic):
    """Contains all coordinate transformation logic.

    Examples:
    =========

    Define a Manifold and a Patch, and then define two coord systems on that
    patch:
    >>> from sympy import symbols, sin, cos, pi
    >>> from sympy.differential_geometry import Manifold, Patch, CoordSystem
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> rect in p.coord_systems
    True

    Connect the coordinate systems. An inverse transformation is automatically
    found by `solve`:
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])
    >>> polar.coord_transform_to(rect, [0, 2])
    [0]
    [0]
    >>> polar.coord_transform_to(rect, [2, pi/2])
    [0]
    [2]
    >>> rect.coord_transform_to(polar, [1, 1])
    [sqrt(2)]
    [   pi/4]

    Define a point using coordinates in one of the coordinate systems:
    >>> p = polar.point([1, 3*pi/4])
    >>> rect.point_to_coords(p)
    [-sqrt(2)/2]
    [ sqrt(2)/2]

    >>> rect.coord_function(0)(p)
    -sqrt(2)/2
    >>> rect.coord_function(1)(p)
    sqrt(2)/2

    """
    #  Contains a reference to the parent patch in order to be able to access
    # other coordinate system charts.
    def __init__(self, name, patch):
        super(CoordSystem, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.patch = patch
        self.patch.coord_systems.append(self)
        self.transforms = {}
        # All the coordinate transformation logic is in this dictionary in the
        # form of:
        #  key = other coordinate system
        #  value = tuple of  # TODO make these Lambda instances
        #          - list of `Dummy` coordinates in this coordinate system
        #          - list of expressions as a function of the Dummies giving
        #          the coordinates in another coordinate system

    def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=True):
        """Register the transformation used to switch to another coordinate system.

        Arguments:
        ==========
        - to_sys - another instance of `CoordSystem`
        - from_coords - list of symbols in terms of which `to_exprs` is given
        - to_exprs - list of the expressions of the new coordinate tuple
        - inverse - try to deduce and register the inverse transformation
        - fill_in_gaps - try to deduce other transformation that are made
        possible by composing the present transformation with other already
        registered transformation
        """
        from_coords, to_exprs = dummyfy(from_coords, to_exprs)
        self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)

        if inverse:
            to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)

        if fill_in_gaps:
            self._fill_gaps_in_transformations()

    @staticmethod
    def _inv_transf(from_coords, to_exprs):
        # TODO, check for results, get solve to return results in definite
        # format instead of wondering dict/tuple/whatever.
        # As it is at the moment this is an ugly hack for changing the format
        inv_from = [i.as_dummy() for i in from_coords]
        inv_to = solve([t[0]-t[1] for t in zip(inv_from, to_exprs)], list(from_coords))
        if isinstance(inv_to, dict):
            inv_to = [inv_to[fc] for fc in from_coords]
        else:
            inv_to = inv_to[0]
        return Matrix(inv_from), Matrix(inv_to)

    @staticmethod
    def _fill_gaps_in_transformations():
        # TODO
        pass

    def coord_transform_to(self, to_sys, coords):
        """Transform `coords` to coord system `to_sys`."""
        coords = Matrix(coords)
        if self != to_sys:
            transf = self.transforms[to_sys]
            coords = transf[1].subs(zip(transf[0], coords))
        return coords

    def coord_function(self, coord_index):
        """Return a ScalarField that takes a point and returns one of the coords."""
        args = [Dummy() for i in range(self.patch.manifold.dim)]
        result = args[coord_index]
        return ScalarField(self, args, result)

    def base_vector(self, coord_index):
        """Return a basis VectorField."""
        args = [Dummy() for i in range(self.patch.manifold.dim)]
        result = [0,] * self.patch.manifold.dim
        result[coord_index] = 1
        return VectorField(self, args, result)

    def point(self, coords):
        """Create a `Point` with coordinates given in this coord system."""
        return Point(self, coords)

    def point_to_coords(self, point):
        """Calculate the coordinates of a point in this coord system."""
        return point.coords(self)

class Point(Basic):
    """Point in a Manifold object.

    To define a point you must supply coordinates and a coordinate system.

    Examples:
    =========

    Define the boilerplate Manifold, Patch and coordinate systems:
    >>> from sympy import symbols, sin, cos, pi
    >>> from sympy.differential_geometry import (
    ...        Manifold, Patch, CoordSystem, Point)
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])

    Define a point using coordinates from one of the coordinate systems:
    >>> p = Point(polar, [r, 3*pi/4])
    >>> p.coords()
    [     r]
    [3*pi/4]
    >>> p.coords(rect)
    [-sqrt(2)*r/2]
    [ sqrt(2)*r/2]

    """
    def __init__(self, coord_sys, coords):
        super(Point, self).__init__()
        self.coord_sys = coord_sys
        self._coords = Matrix(coords)

    def coords(self, to_sys=None):
        """Coordinates of the point in a given coordinate system.

        If `to_sys` is None it returns the coordinates in the system in
        which the point was defined."""
        if to_sys:
            return self.coord_sys.coord_transform_to(to_sys, self._coords)
        else:
            return self._coords

class ScalarField(Expr):
    """Scalar Field over a Manifold.

    A scalar field takes a point as an argument and returns a scalar.

    To define a scalar field you need to choose a coordinate system and define
    the scalar field in terms of that coordinate system.

    Examples:
    =========

    Define boilerplate Manifold, Patch and coordinate systems:
    >>> from sympy import symbols, sin, cos, pi, Function
    >>> from sympy.differential_geometry import (
    ...        Manifold, Patch, CoordSystem, Point, ScalarField)
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])

    Points to be used as arguments for the filed:
    >>> pointA = polar.point([r, 0])

    Examples of fields:
    >>> field1 = ScalarField(rect, [x, y], x**2+y**2)
    >>> field1(pointA)
    r**2
    >>> (1+5*field1)(pointA)
    5*r**2 + 1

    >>> g = Function('g')
    >>> field2 = ScalarField(polar, [r, theta], g(theta-pi))
    >>> field2(pointA)
    g(-pi)

    """
    def __init__(self, coord_sys, coords, expr):
        super(ScalarField, self).__init__()
        self.coord_sys = coord_sys
        coords, (expr, ) = dummyfy(coords, (expr, ))
        self.coords = coords
        self.expr = expr
        self._args = self.coord_sys, self.coords, self.expr

    def __call__(self, point):
        coords = point.coords(self.coord_sys)
        return self.expr.subs(zip(self.coords, coords))

class VectorField(Expr):
    """Vector Field over a Manifold.

    A vector field is an operator taking a scalar field and returning a
    directional derivative (which is also a scalar field).

    To define a vector field you need to choose a coordinate system and define
    the vector field in terms of that coordinate system.

    Examples:
    =========

    Use the predefined R2 manifold
    >>> from sympy import symbols, sin, cos, pi, Function
    >>> from sympy.differential_geometry.Rn import R2, R2_p, R2_r
    >>> from sympy.differential_geometry import ScalarField, VectorField
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0')

    Points to be used as arguments for the filed:
    >>> point_p = R2_p.point([r0, theta0])
    >>> point_r = R2_r.point([x0, y0])

    Scalar field to operate on:
    >>> g = Function('g')
    >>> s_field = g(R2.x, R2.y)
    >>> s_field(point_r)
    g(x0, y0)
    >>> s_field(point_p)
    g(r0*cos(theta0), r0*sin(theta0))

    Vector field:
    >>> v = VectorField(R2_r, [x, y], [1, 1])
    >>> v(s_field)(point_r)
    Derivative(g(x0, y0), x0) + Derivative(g(x0, y0), y0)
    >>> v(s_field)(point_p) # TODO this is correct but unusable
    Subs(Derivative(g(_x, r0*sin(theta0)), _x), (_x,), (r0*cos(theta0),)) + Subs(Derivative(g(r0*cos(theta0), _y), _y), (_y,), (r0*sin(theta0),))

    """
    def __init__(self, coord_sys, coords, components):
        super(VectorField, self).__init__()
        self.coord_sys = coord_sys
        coords, components = dummyfy(coords, components)
        self.coords = coords
        self.components = components
        self._args = self.coord_sys, self.coords, self.components

    def __call__(self, scalar_field):
        scalar_expr = scalar_field(Point(self.coord_sys, self.coords))
        diff_scalar_expr = (diff(scalar_expr, c) for c in self.coords)
        projected = sum(e[0]*e[1] for e in zip(diff_scalar_expr, self.components))
        # TODO This is the simplest to write, however is it the smartest
        # routine for applying vector field on a scalar field?
        return ScalarField(self.coord_sys, self.coords, projected)

def dummyfy(args, exprs):
    # TODO Is this a good idea?
    d_args = Matrix([s.as_dummy() for s in args])
    d_exprs = Matrix([sympify(expr).subs(zip(args, d_args)) for expr in exprs])
    return d_args, d_exprs
<commit_msg>Mark coordinate-dependent attributes in differential_geometry as private.<commit_after>from sympy import sympify, Dummy, Matrix, Basic, Expr, solve, diff

# TODO order the imports and make them explicit
# TODO issue 2070: all the stuff about .args and rebuilding
# TODO better dosctrings and more distributed doctests
# TODO maybe a common class Field makes sense

class Manifold(Basic):
    """Object representing a mathematical manifold.

    The only role that it plays is to keep a list of all patches defined on the
    manifold.
    """
    def __init__(self, name, dim):
        super(Manifold, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.dim = dim
        self.patches = []
        # The patches list is necessary if a Patch instance needs to enumerate
        # other Patch instance on the same manifold.

class Patch(Basic):
    """Object representing a patch on a manifold.

    It serves as a container/parent for all coordinate system charts that can
    be defined on this patch.

    Examples:
    =========

    Define a Manifold and a Patch on that Manifold:
    >>> from sympy.differential_geometry import Manifold, Patch
    >>> m = Manifold('M', 3)
    >>> p = Patch('P', m)
    >>> p in m.patches
    True

    """
    # Contains a reference to the parent manifold in order to be able to access
    # other patches.
    def __init__(self, name, manifold):
        super(Patch, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.manifold = manifold
        self.manifold.patches.append(self)
        self.coord_systems = []
        # The list of coordinate systems is necessary for an instance of
        # CoordSystem to enumerate other coord systems on the patch.

class CoordSystem(Basic):
    """Contains all coordinate transformation logic.

    Examples:
    =========

    Define a Manifold and a Patch, and then define two coord systems on that
    patch:
    >>> from sympy import symbols, sin, cos, pi
    >>> from sympy.differential_geometry import Manifold, Patch, CoordSystem
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> rect in p.coord_systems
    True

    Connect the coordinate systems. An inverse transformation is automatically
    found by `solve`:
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])
    >>> polar.coord_transform_to(rect, [0, 2])
    [0]
    [0]
    >>> polar.coord_transform_to(rect, [2, pi/2])
    [0]
    [2]
    >>> rect.coord_transform_to(polar, [1, 1])
    [sqrt(2)]
    [   pi/4]

    Define a point using coordinates in one of the coordinate systems:
    >>> p = polar.point([1, 3*pi/4])
    >>> rect.point_to_coords(p)
    [-sqrt(2)/2]
    [ sqrt(2)/2]

    >>> rect.coord_function(0)(p)
    -sqrt(2)/2
    >>> rect.coord_function(1)(p)
    sqrt(2)/2

    """
    #  Contains a reference to the parent patch in order to be able to access
    # other coordinate system charts.
    def __init__(self, name, patch):
        super(CoordSystem, self).__init__()
        self.name = name
        # TODO What is the purpose of this name, besides printing?
        self.patch = patch
        self.patch.coord_systems.append(self)
        self.transforms = {}
        # All the coordinate transformation logic is in this dictionary in the
        # form of:
        #  key = other coordinate system
        #  value = tuple of  # TODO make these Lambda instances
        #          - list of `Dummy` coordinates in this coordinate system
        #          - list of expressions as a function of the Dummies giving
        #          the coordinates in another coordinate system

    def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=True):
        """Register the transformation used to switch to another coordinate system.

        Arguments:
        ==========
        - to_sys - another instance of `CoordSystem`
        - from_coords - list of symbols in terms of which `to_exprs` is given
        - to_exprs - list of the expressions of the new coordinate tuple
        - inverse - try to deduce and register the inverse transformation
        - fill_in_gaps - try to deduce other transformation that are made
        possible by composing the present transformation with other already
        registered transformation
        """
        from_coords, to_exprs = dummyfy(from_coords, to_exprs)
        self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)

        if inverse:
            to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)

        if fill_in_gaps:
            self._fill_gaps_in_transformations()

    @staticmethod
    def _inv_transf(from_coords, to_exprs):
        # TODO, check for results, get solve to return results in definite
        # format instead of wondering dict/tuple/whatever.
        # As it is at the moment this is an ugly hack for changing the format
        inv_from = [i.as_dummy() for i in from_coords]
        inv_to = solve([t[0]-t[1] for t in zip(inv_from, to_exprs)], list(from_coords))
        if isinstance(inv_to, dict):
            inv_to = [inv_to[fc] for fc in from_coords]
        else:
            inv_to = inv_to[0]
        return Matrix(inv_from), Matrix(inv_to)

    @staticmethod
    def _fill_gaps_in_transformations():
        # TODO
        pass

    def coord_transform_to(self, to_sys, coords):
        """Transform `coords` to coord system `to_sys`."""
        coords = Matrix(coords)
        if self != to_sys:
            transf = self.transforms[to_sys]
            coords = transf[1].subs(zip(transf[0], coords))
        return coords

    def coord_function(self, coord_index):
        """Return a ScalarField that takes a point and returns one of the coords."""
        args = [Dummy() for i in range(self.patch.manifold.dim)]
        result = args[coord_index]
        return ScalarField(self, args, result)

    def base_vector(self, coord_index):
        """Return a basis VectorField."""
        args = [Dummy() for i in range(self.patch.manifold.dim)]
        result = [0,] * self.patch.manifold.dim
        result[coord_index] = 1
        return VectorField(self, args, result)

    def point(self, coords):
        """Create a `Point` with coordinates given in this coord system."""
        return Point(self, coords)

    def point_to_coords(self, point):
        """Calculate the coordinates of a point in this coord system."""
        return point.coords(self)

class Point(Basic):
    """Point in a Manifold object.

    To define a point you must supply coordinates and a coordinate system.

    Examples:
    =========

    Define the boilerplate Manifold, Patch and coordinate systems:
    >>> from sympy import symbols, sin, cos, pi
    >>> from sympy.differential_geometry import (
    ...        Manifold, Patch, CoordSystem, Point)
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])

    Define a point using coordinates from one of the coordinate systems:
    >>> p = Point(polar, [r, 3*pi/4])
    >>> p.coords()
    [     r]
    [3*pi/4]
    >>> p.coords(rect)
    [-sqrt(2)*r/2]
    [ sqrt(2)*r/2]

    """
    def __init__(self, coord_sys, coords):
        super(Point, self).__init__()
        self._coord_sys = coord_sys
        self._coords = Matrix(coords)

    def coords(self, to_sys=None):
        """Coordinates of the point in a given coordinate system.

        If `to_sys` is None it returns the coordinates in the system in
        which the point was defined."""
        if to_sys:
            return self._coord_sys.coord_transform_to(to_sys, self._coords)
        else:
            return self._coords

class ScalarField(Expr):
    """Scalar Field over a Manifold.

    A scalar field takes a point as an argument and returns a scalar.

    To define a scalar field you need to choose a coordinate system and define
    the scalar field in terms of that coordinate system.

    Examples:
    =========

    Define boilerplate Manifold, Patch and coordinate systems:
    >>> from sympy import symbols, sin, cos, pi, Function
    >>> from sympy.differential_geometry import (
    ...        Manifold, Patch, CoordSystem, Point, ScalarField)
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> m = Manifold('M', 2)
    >>> p = Patch('P', m)
    >>> rect = CoordSystem('rect', p)
    >>> polar = CoordSystem('polar', p)
    >>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])

    Points to be used as arguments for the filed:
    >>> pointA = polar.point([r, 0])

    Examples of fields:
    >>> field1 = ScalarField(rect, [x, y], x**2+y**2)
    >>> field1(pointA)
    r**2
    >>> (1+5*field1)(pointA)
    5*r**2 + 1

    >>> g = Function('g')
    >>> field2 = ScalarField(polar, [r, theta], g(theta-pi))
    >>> field2(pointA)
    g(-pi)

    """
    def __init__(self, coord_sys, coords, expr):
        super(ScalarField, self).__init__()
        self._coord_sys = coord_sys
        coords, (expr, ) = dummyfy(coords, (expr, ))
        self._coords = coords
        self._expr = expr
        self._args = self._coord_sys, self._coords, self._expr

    def __call__(self, point):
        coords = point.coords(self._coord_sys)
        return self._expr.subs(zip(self._coords, coords))

class VectorField(Expr):
    """Vector Field over a Manifold.

    A vector field is an operator taking a scalar field and returning a
    directional derivative (which is also a scalar field).

    To define a vector field you need to choose a coordinate system and define
    the vector field in terms of that coordinate system.

    Examples:
    =========

    Use the predefined R2 manifold
    >>> from sympy import symbols, sin, cos, pi, Function
    >>> from sympy.differential_geometry.Rn import R2, R2_p, R2_r
    >>> from sympy.differential_geometry import ScalarField, VectorField
    >>> x, y, r, theta = symbols('x, y, r, theta')
    >>> x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0')

    Points to be used as arguments for the filed:
    >>> point_p = R2_p.point([r0, theta0])
    >>> point_r = R2_r.point([x0, y0])

    Scalar field to operate on:
    >>> g = Function('g')
    >>> s_field = g(R2.x, R2.y)
    >>> s_field(point_r)
    g(x0, y0)
    >>> s_field(point_p)
    g(r0*cos(theta0), r0*sin(theta0))

    Vector field:
    >>> v = VectorField(R2_r, [x, y], [1, 1])
    >>> v(s_field)(point_r)
    Derivative(g(x0, y0), x0) + Derivative(g(x0, y0), y0)
    >>> v(s_field)(point_p) # TODO this is correct but unusable
    Subs(Derivative(g(_x, r0*sin(theta0)), _x), (_x,), (r0*cos(theta0),)) + Subs(Derivative(g(r0*cos(theta0), _y), _y), (_y,), (r0*sin(theta0),))

    """
    def __init__(self, coord_sys, coords, components):
        super(VectorField, self).__init__()
        self._coord_sys = coord_sys
        coords, components = dummyfy(coords, components)
        self._coords = coords
        self._components = components
        self._args = self._coord_sys, self._coords, self._components

    def __call__(self, scalar_field):
        scalar_expr = scalar_field(Point(self._coord_sys, self._coords))
        diff_scalar_expr = (diff(scalar_expr, c) for c in self._coords)
        projected = sum(e[0]*e[1] for e in zip(diff_scalar_expr, self._components))
        # TODO This is the simplest to write, however is it the smartest
        # routine for applying vector field on a scalar field?
        return ScalarField(self._coord_sys, self._coords, projected)

def dummyfy(args, exprs):
    # TODO Is this a good idea?
    d_args = Matrix([s.as_dummy() for s in args])
    d_exprs = Matrix([sympify(expr).subs(zip(args, d_args)) for expr in exprs])
    return d_args, d_exprs
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_almost_equal
from megamix.online import Kmeans, GaussianMixture
from megamix.online import dist_matrix
from megamix.utils_testing import checking
from scipy.linalg import linalg

import pytest
import h5py

def test_dist_matrix():
    n_points,n_components,dim = 10,5,2
    points = np.random.randn(n_points,dim)
    means = np.random.randn(n_components,dim)

    expected_dist_matrix = np.zeros((n_points,n_components))
    for i in range(n_points):
        for j in range(n_components):
            expected_dist_matrix[i,j] = np.linalg.norm(points[i] - means[j])

    predected_dist_matrix = dist_matrix(points,means)

    assert_almost_equal(expected_dist_matrix,predected_dist_matrix)

class TestKmeans:

    def setup(self):
        self.n_components = 5
        self.dim = 2
        self.n_points = 10

        self.file_name = 'test.h5'

    def teardown(self):
        checking.remove(self.file_name)

    def test_initialize(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)

        checking.verify_means(KM.get('means'),self.n_components,self.dim)
        checking.verify_log_pi(np.log(KM.get('N')),self.n_components)
        assert KM.get('_is_initialized')

    def test_step_E(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)

        expected_assignements = np.zeros((self.n_points,self.n_components))
        M = dist_matrix(points,KM.get('means'))
        for i in range(self.n_points):
            index_min = np.argmin(M[i]) #the cluster number of the ith point is index_min
            if (isinstance(index_min,np.int64)):
                expected_assignements[i][index_min] = 1
            else: #Happens when two points are equally distant from a cluster mean
                expected_assignements[i][index_min[0]] = 1

        predected_assignements = KM._step_E(points)

        assert_almost_equal(expected_assignements,predected_assignements)

    def test_step_M(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)
        points_window = points[:window:]
        assignements = KM._step_E(points_window)

        N = assignements.sum(axis=0) / window
        X = np.dot(assignements.T,points_window) / window

        gamma = 1/((KM.get('iter') + window//2)**KM.get('kappa'))

        expected_N = (1-gamma)*KM.get('N') + gamma*N
        expected_X = (1-gamma)*KM.get('X') + gamma*X
        expected_means = expected_X / expected_N[:,np.newaxis]

        KM._step_M(points_window,assignements)

        assert_almost_equal(expected_N,KM.get('N'))
        assert_almost_equal(expected_X,KM.get('X'))
        assert_almost_equal(expected_means,KM.get('means'))

    def test_score(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)

        with pytest.raises(Exception):
            KM.score(points)
        KM.initialize(points)
        KM.fit(points)
        score1 = KM.score(points)
        score2 = KM.score(points+2)
        assert score1 < score2

    def test_predict_assignements(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)

        with pytest.raises(Exception):
            KM.score(points)
        KM.initialize(points)

        expected_assignements = KM._step_E(points)

        predected_assignements = KM.predict_assignements(points)

        assert_almost_equal(expected_assignements,predected_assignements)

    def test_write_and_read(self):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM.initialize(points)

        f = h5py.File(self.file_name,'w')
        grp = f.create_group('init')
        KM.write(grp)
        f.close()

        KM2 = Kmeans(self.n_components)

        f = h5py.File(self.file_name,'r')
        grp = f['init']
        KM2.read_and_init(grp,points)
        f.close()

        checking.verify_online_models(KM,KM2)

        KM.fit(points)
        KM2.fit(points)

        checking.verify_online_models(KM,KM2)

    def test_write_and_read_GM(self,update):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM.initialize(points)

        f = h5py.File(self.file_name,'w')
        grp = f.create_group('init')
        KM.write(grp)
        f.close()

        predected_GM = GaussianMixture(self.n_components,update=update)

        f = h5py.File(self.file_name,'r')
        grp = f['init']
        with pytest.warns(UserWarning):
            predected_GM.read_and_init(grp,points)
        f.close()

        expected_GM = GaussianMixture(self.n_components,update=update)

        expected_GM.set('means',KM.get('means'))
        expected_GM._initialize_cov(points)

        # Computation of self.cov_chol
        expected_GM.set('cov_chol',np.empty(expected_GM.cov.shape))
        for i in range(self.n_components):
            expected_GM.cov_chol[i] = linalg.cholesky(expected_GM.cov[i],lower=True)

        expected_GM._initialize_weights(points)
        expected_GM.set('iter',KM.get('iter'))

        weights = np.exp(expected_GM.log_weights)
        expected_GM.N = weights
        expected_GM.X = expected_GM.means * expected_GM.N[:,np.newaxis]
        expected_GM.S = expected_GM.cov * expected_GM.N[:,np.newaxis,np.newaxis]

        # Computation of S_chol if update=True
        if expected_GM.update:
            if expected_GM.covariance_type == 'full':
                expected_GM.S_chol = np.empty(expected_GM.S.shape)
                for i in range(expected_GM.n_components):
                    expected_GM.S_chol[i] = linalg.cholesky(expected_GM.S[i],lower=True)
            elif expected_GM.covariance_type == 'spherical':
                expected_GM.S_chol = np.sqrt(expected_GM.S)

        checking.verify_online_models(predected_GM,expected_GM)

    def test_fit_save(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)

        checking.remove(self.file_name + '.h5')
        KM.initialize(points)
        KM.fit(points,saving='linear',saving_iter=2,
               file_name=self.file_name)
        f = h5py.File(self.file_name + '.h5','r')
        cpt = 0
        for name in f:
            cpt += 1

        assert cpt == self.n_points//(2*window)

        checking.remove(self.file_name + '.h5')
        KM.fit(points,saving='log',saving_iter=2,
               file_name=self.file_name)
        f = h5py.File(self.file_name + '.h5','r')
        cpt = 0
        for name in f:
            cpt += 1

        assert cpt == 1 + int(np.log(self.n_points/window)/np.log(2))<commit_msg>changed import in test<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_almost_equal
from megamix.online import Kmeans, GaussianMixture
from megamix.online import dist_matrix
from megamix.utils_testing import checking
from scipy import linalg

import pytest
import h5py

def test_dist_matrix():
    n_points,n_components,dim = 10,5,2
    points = np.random.randn(n_points,dim)
    means = np.random.randn(n_components,dim)

    expected_dist_matrix = np.zeros((n_points,n_components))
    for i in range(n_points):
        for j in range(n_components):
            expected_dist_matrix[i,j] = np.linalg.norm(points[i] - means[j])

    predected_dist_matrix = dist_matrix(points,means)

    assert_almost_equal(expected_dist_matrix,predected_dist_matrix)

class TestKmeans:

    def setup(self):
        self.n_components = 5
        self.dim = 2
        self.n_points = 10

        self.file_name = 'test.h5'

    def teardown(self):
        checking.remove(self.file_name)

    def test_initialize(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)

        checking.verify_means(KM.get('means'),self.n_components,self.dim)
        checking.verify_log_pi(np.log(KM.get('N')),self.n_components)
        assert KM.get('_is_initialized')

    def test_step_E(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)

        expected_assignements = np.zeros((self.n_points,self.n_components))
        M = dist_matrix(points,KM.get('means'))
        for i in range(self.n_points):
            index_min = np.argmin(M[i]) #the cluster number of the ith point is index_min
            if (isinstance(index_min,np.int64)):
                expected_assignements[i][index_min] = 1
            else: #Happens when two points are equally distant from a cluster mean
                expected_assignements[i][index_min[0]] = 1

        predected_assignements = KM._step_E(points)

        assert_almost_equal(expected_assignements,predected_assignements)

    def test_step_M(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)
        KM.initialize(points)
        points_window = points[:window:]
        assignements = KM._step_E(points_window)

        N = assignements.sum(axis=0) / window
        X = np.dot(assignements.T,points_window) / window

        gamma = 1/((KM.get('iter') + window//2)**KM.get('kappa'))

        expected_N = (1-gamma)*KM.get('N') + gamma*N
        expected_X = (1-gamma)*KM.get('X') + gamma*X
        expected_means = expected_X / expected_N[:,np.newaxis]

        KM._step_M(points_window,assignements)

        assert_almost_equal(expected_N,KM.get('N'))
        assert_almost_equal(expected_X,KM.get('X'))
        assert_almost_equal(expected_means,KM.get('means'))

    def test_score(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)

        with pytest.raises(Exception):
            KM.score(points)
        KM.initialize(points)
        KM.fit(points)
        score1 = KM.score(points)
        score2 = KM.score(points+2)
        assert score1 < score2

    def test_predict_assignements(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)

        with pytest.raises(Exception):
            KM.score(points)
        KM.initialize(points)

        expected_assignements = KM._step_E(points)

        predected_assignements = KM.predict_assignements(points)

        assert_almost_equal(expected_assignements,predected_assignements)

    def test_write_and_read(self):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM.initialize(points)

        f = h5py.File(self.file_name,'w')
        grp = f.create_group('init')
        KM.write(grp)
        f.close()

        KM2 = Kmeans(self.n_components)

        f = h5py.File(self.file_name,'r')
        grp = f['init']
        KM2.read_and_init(grp,points)
        f.close()

        checking.verify_online_models(KM,KM2)

        KM.fit(points)
        KM2.fit(points)

        checking.verify_online_models(KM,KM2)

    def test_write_and_read_GM(self,update):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM.initialize(points)

        f = h5py.File(self.file_name,'w')
        grp = f.create_group('init')
        KM.write(grp)
        f.close()

        predected_GM = GaussianMixture(self.n_components,update=update)

        f = h5py.File(self.file_name,'r')
        grp = f['init']
        with pytest.warns(UserWarning):
            predected_GM.read_and_init(grp,points)
        f.close()

        expected_GM = GaussianMixture(self.n_components,update=update)

        expected_GM.set('means',KM.get('means'))
        expected_GM._initialize_cov(points)

        # Computation of self.cov_chol
        expected_GM.set('cov_chol',np.empty(expected_GM.cov.shape))
        for i in range(self.n_components):
            expected_GM.cov_chol[i] = linalg.cholesky(expected_GM.cov[i],lower=True)

        expected_GM._initialize_weights(points)
        expected_GM.set('iter',KM.get('iter'))

        weights = np.exp(expected_GM.log_weights)
        expected_GM.N = weights
        expected_GM.X = expected_GM.means * expected_GM.N[:,np.newaxis]
        expected_GM.S = expected_GM.cov * expected_GM.N[:,np.newaxis,np.newaxis]

        # Computation of S_chol if update=True
        if expected_GM.update:
            if expected_GM.covariance_type == 'full':
                expected_GM.S_chol = np.empty(expected_GM.S.shape)
                for i in range(expected_GM.n_components):
                    expected_GM.S_chol[i] = linalg.cholesky(expected_GM.S[i],lower=True)
            elif expected_GM.covariance_type == 'spherical':
                expected_GM.S_chol = np.sqrt(expected_GM.S)

        checking.verify_online_models(predected_GM,expected_GM)

    def test_fit_save(self,window):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components,window=window)

        checking.remove(self.file_name + '.h5')
        KM.initialize(points)
        KM.fit(points,saving='linear',saving_iter=2,
               file_name=self.file_name)
        f = h5py.File(self.file_name + '.h5','r')
        cpt = 0
        for name in f:
            cpt += 1

        assert cpt == self.n_points//(2*window)

        checking.remove(self.file_name + '.h5')
        KM.fit(points,saving='log',saving_iter=2,
               file_name=self.file_name)
        f = h5py.File(self.file_name + '.h5','r')
        cpt = 0
        for name in f:
            cpt += 1

        assert cpt == 1 + int(np.log(self.n_points/window)/np.log(2))<|endoftext|>


<commit_before>import pytest
import capnp
import os
import platform
import test_regression
import tempfile
import pickle

this_dir = os.path.dirname(__file__)

@pytest.fixture
def all_types():
    return capnp.load(os.path.join(this_dir, 'all_types.capnp'))

def test_roundtrip_file(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)

    f.seek(0)
    msg = all_types.TestAllTypes.read(f)
    test_regression.check_all_types(msg)

def test_roundtrip_file_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)

    f.seek(0)
    msg = all_types.TestAllTypes.read_packed(f)
    test_regression.check_all_types(msg)

def test_roundtrip_bytes(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    message_bytes = msg.to_bytes()

    msg = all_types.TestAllTypes.from_bytes(message_bytes)
    test_regression.check_all_types(msg)

def test_roundtrip_bytes_packed(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    message_bytes = msg.to_bytes_packed()

    msg = all_types.TestAllTypes.from_bytes_packed(message_bytes)
    test_regression.check_all_types(msg)

def test_roundtrip_file_multiple(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)
    msg.write(f)
    msg.write(f)

    f.seek(0)
    i = 0
    for msg in all_types.TestAllTypes.read_multiple(f):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_bytes_multiple(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)

    msgs = msg.to_bytes()
    msgs += msg.to_bytes()
    msgs += msg.to_bytes()

    i = 0
    for msg in all_types.TestAllTypes.read_multiple_bytes(msgs):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_file_multiple_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)
    msg.write_packed(f)
    msg.write_packed(f)

    f.seek(0)
    i = 0
    for msg in all_types.TestAllTypes.read_multiple_packed(f):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_bytes_multiple_packed(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)

    msgs = msg.to_bytes_packed()
    msgs += msg.to_bytes_packed()
    msgs += msg.to_bytes_packed()

    i = 0
    for msg in all_types.TestAllTypes.read_multiple_bytes_packed(msgs):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_dict(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    d = msg.to_dict()

    msg = all_types.TestAllTypes.from_dict(d)
    test_regression.check_all_types(msg)

def test_file_and_bytes(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)

    f.seek(0)

    assert f.read() == msg.to_bytes()

def test_file_and_bytes_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)

    f.seek(0)

    assert f.read() == msg.to_bytes_packed()

def test_pickle(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    data = pickle.dumps(msg)
    msg2 = pickle.loads(data)

    test_regression.check_all_types(msg2)
<commit_msg>Skip broken test in PyPy<commit_after>import pytest
import capnp
import os
import platform
import test_regression
import tempfile
import pickle

this_dir = os.path.dirname(__file__)

@pytest.fixture
def all_types():
    return capnp.load(os.path.join(this_dir, 'all_types.capnp'))

def test_roundtrip_file(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)

    f.seek(0)
    msg = all_types.TestAllTypes.read(f)
    test_regression.check_all_types(msg)

def test_roundtrip_file_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)

    f.seek(0)
    msg = all_types.TestAllTypes.read_packed(f)
    test_regression.check_all_types(msg)

def test_roundtrip_bytes(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    message_bytes = msg.to_bytes()

    msg = all_types.TestAllTypes.from_bytes(message_bytes)
    test_regression.check_all_types(msg)

def test_roundtrip_bytes_packed(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    message_bytes = msg.to_bytes_packed()

    msg = all_types.TestAllTypes.from_bytes_packed(message_bytes)
    test_regression.check_all_types(msg)

def test_roundtrip_file_multiple(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)
    msg.write(f)
    msg.write(f)

    f.seek(0)
    i = 0
    for msg in all_types.TestAllTypes.read_multiple(f):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_bytes_multiple(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)

    msgs = msg.to_bytes()
    msgs += msg.to_bytes()
    msgs += msg.to_bytes()

    i = 0
    for msg in all_types.TestAllTypes.read_multiple_bytes(msgs):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_file_multiple_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)
    msg.write_packed(f)
    msg.write_packed(f)

    f.seek(0)
    i = 0
    for msg in all_types.TestAllTypes.read_multiple_packed(f):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

def test_roundtrip_bytes_multiple_packed(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)

    msgs = msg.to_bytes_packed()
    msgs += msg.to_bytes_packed()
    msgs += msg.to_bytes_packed()

    i = 0
    for msg in all_types.TestAllTypes.read_multiple_bytes_packed(msgs):
        test_regression.check_all_types(msg)
        i += 1
    assert i == 3

@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason="This works on my local PyPy v2.5.0, but is for some reason broken on TravisCI. Skip for now.")
def test_roundtrip_dict(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    d = msg.to_dict()

    msg = all_types.TestAllTypes.from_dict(d)
    test_regression.check_all_types(msg)

def test_file_and_bytes(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write(f)

    f.seek(0)

    assert f.read() == msg.to_bytes()

def test_file_and_bytes_packed(all_types):
    f = tempfile.TemporaryFile()
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    msg.write_packed(f)

    f.seek(0)

    assert f.read() == msg.to_bytes_packed()

def test_pickle(all_types):
    msg = all_types.TestAllTypes.new_message()
    test_regression.init_all_types(msg)
    data = pickle.dumps(msg)
    msg2 = pickle.loads(data)

    test_regression.check_all_types(msg2)
<|endoftext|>


<commit_before># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import, division

import itertools

import pingparsing
import pytest
import typepy
from subprocrunner import SubprocessRunner
from tcconfig._const import Tc

from .common import DEADLINE_TIME, execute_tcdel

@pytest.fixture
def device_option(request):
    return request.config.getoption("--device")

@pytest.fixture
def dst_host_option(request):
    return request.config.getoption("--dst-host")

@pytest.fixture
def transmitter():
    transmitter = pingparsing.PingTransmitter()
    transmitter.ping_option = "-f -q"
    transmitter.deadline = DEADLINE_TIME

    return transmitter

@pytest.fixture
def pingparser():
    return pingparsing.PingParsing()

class Test_tcset_one_network(object):
    """
    Tests in this class are not executable on CI services.
    Execute the following command at the local environment to running tests:

        python setup.py test --addopts \
            "--device=<test device> --dst-host=<IP address>"

    These tests expected to execute in the following environment:
       - Linux w/ iputils-ping package
       - English locale (for parsing ping output)
    """

    @pytest.mark.parametrize(["shaping_algo", "delay"], [
        [params[0], params[1]]
        for params in itertools.product(["htb"], [100])
    ])
    def test_dst_net_uniform_latency(
            self, device_option, dst_host_option, transmitter, pingparser, shaping_algo, delay):
        if device_option is None:
            pytest.skip("device option is null")
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o latency tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_rtt_avg = pingparser.rtt_avg

        # w/ latency tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {}ms".format(delay),
            "--shaping-algo {:s}".format(shaping_algo),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["delay", "delay_distro"], [
        [100, 50],
    ])
    def test_dst_net_latency_distro(
            self, device_option, dst_host_option, transmitter, pingparser, delay, delay_distro):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o latency tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_rtt_avg = pingparser.rtt_avg
        without_tc_rtt_mdev = pingparser.rtt_mdev

        # w/ latency tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {:d}ms".format(delay),
            "--delay-distro {:d}ms".format(delay_distro),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg
        with_tc_rtt_mdev = pingparser.rtt_mdev

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        rtt_diff = with_tc_rtt_mdev - without_tc_rtt_mdev
        assert rtt_diff > (delay_distro / 2.0)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["option", "value"], [
        ["--loss", 10],
        ["--corrupt", 10],
    ])
    def test_dst_net_packet_loss(
            self, device_option, dst_host_option, transmitter, pingparser, option, value):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o packet loss tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_loss_rate = pingparser.packet_loss_rate

        # w/ packet loss tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "{:s} {:f}".format(option, value),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_loss_rate = pingparser.packet_loss_rate

        # assertion ---
        loss_diff = with_tc_loss_rate - without_tc_loss_rate
        assert loss_diff > (value / 2)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["option", "value"], [
        ["--duplicate", 50],
    ])
    def test_dst_net_packet_duplicate(
            self, device_option, dst_host_option, transmitter, pingparser, option, value):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o packet duplicate tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_duplicate_rate = pingparser.packet_duplicate_rate

        # w/ packet duplicate tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "{:s} {:f}".format(option, value),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_duplicate_rate = pingparser.packet_duplicate_rate

        # assertion ---
        duplicate_rate_diff = (
            with_tc_duplicate_rate - without_tc_duplicate_rate)
        assert duplicate_rate_diff > (value / 2)

        # finalize ---
        execute_tcdel(device_option)

    def test_dst_net_exclude_dst_network(
            self, device_option, dst_host_option, transmitter, pingparser):
        if device_option is None:
            pytest.skip("device option is null")
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        delay = 100

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/ latency tc ---
        command_list = [
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {:d}ms".format(delay),
        ]
        assert SubprocessRunner(" ".join(command_list)).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg

        # exclude certain network ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--exclude-dst-network {:s}/24".format(
                ".".join(dst_host_option.split(".")[:3] + ["0"])),
            "--delay {:d}ms".format(delay),
            "--overwrite",
        ]).run() == 0

        pingparser.parse(transmitter.ping())
        without_tc_rtt_avg = pingparser.rtt_avg

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        # finalize ---
        execute_tcdel(device_option)
<commit_msg>Update comments<commit_after># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import, division

import itertools

import pingparsing
import pytest
import typepy
from subprocrunner import SubprocessRunner
from tcconfig._const import Tc

from .common import DEADLINE_TIME, execute_tcdel

@pytest.fixture
def device_option(request):
    return request.config.getoption("--device")

@pytest.fixture
def dst_host_option(request):
    return request.config.getoption("--dst-host")

@pytest.fixture
def transmitter():
    transmitter = pingparsing.PingTransmitter()
    transmitter.ping_option = "-f -q"
    transmitter.deadline = DEADLINE_TIME

    return transmitter

@pytest.fixture
def pingparser():
    return pingparsing.PingParsing()

class Test_tcset_one_network(object):
    """
    Tests in this class are not executable on CI services.
    Execute the following command at the local environment to running tests:

        python setup.py test --addopts \
            "--device=<test device> --dst-host=<IP address>"

    These tests expected to execute in the following environment:
       - Linux w/ iputils-ping package
       - English locale (for parsing ping output)
    """

    @pytest.mark.parametrize(["shaping_algo", "delay"], [
        [params[0], params[1]]
        for params in itertools.product(["htb"], [100])
    ])
    def test_dst_net_uniform_latency(
            self, device_option, dst_host_option, transmitter, pingparser, shaping_algo, delay):
        if device_option is None:
            pytest.skip("device option is null")
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o latency tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_rtt_avg = pingparser.rtt_avg

        # w/ latency tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {}ms".format(delay),
            "--shaping-algo {:s}".format(shaping_algo),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["delay", "delay_distro"], [
        [100, 50],
    ])
    def test_dst_net_latency_distro(
            self, device_option, dst_host_option, transmitter, pingparser, delay, delay_distro):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o latency tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_rtt_avg = pingparser.rtt_avg
        without_tc_rtt_mdev = pingparser.rtt_mdev

        # w/ latency tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {:d}ms".format(delay),
            "--delay-distro {:d}ms".format(delay_distro),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg
        with_tc_rtt_mdev = pingparser.rtt_mdev

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        rtt_diff = with_tc_rtt_mdev - without_tc_rtt_mdev
        assert rtt_diff > (delay_distro / 2.0)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["option", "value"], [
        ["--loss", 10],
        ["--corrupt", 10],
    ])
    def test_dst_net_packet_loss(
            self, device_option, dst_host_option, transmitter, pingparser, option, value):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o traffic shaping ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_loss_rate = pingparser.packet_loss_rate

        # w/ traffic shaping ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "{:s} {:f}".format(option, value),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_loss_rate = pingparser.packet_loss_rate

        # check packet loss rate ---
        loss_diff = with_tc_loss_rate - without_tc_loss_rate
        assert loss_diff > (value / 2)

        # finalize ---
        execute_tcdel(device_option)

    @pytest.mark.parametrize(["option", "value"], [
        ["--duplicate", 50],
    ])
    def test_dst_net_packet_duplicate(
            self, device_option, dst_host_option, transmitter, pingparser, option, value):
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/o packet duplicate tc ---
        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        without_tc_duplicate_rate = pingparser.packet_duplicate_rate

        # w/ packet duplicate tc ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "{:s} {:f}".format(option, value),
        ]).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_duplicate_rate = pingparser.packet_duplicate_rate

        # assertion ---
        duplicate_rate_diff = (
            with_tc_duplicate_rate - without_tc_duplicate_rate)
        assert duplicate_rate_diff > (value / 2)

        # finalize ---
        execute_tcdel(device_option)

    def test_dst_net_exclude_dst_network(
            self, device_option, dst_host_option, transmitter, pingparser):
        if device_option is None:
            pytest.skip("device option is null")
        if typepy.is_null_string(dst_host_option):
            pytest.skip("destination host is null")

        delay = 100

        execute_tcdel(device_option)
        transmitter.destination_host = dst_host_option

        # w/ latency tc ---
        command_list = [
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--delay {:d}ms".format(delay),
        ]
        assert SubprocessRunner(" ".join(command_list)).run() == 0

        ping_result = transmitter.ping()
        assert ping_result.returncode == 0
        pingparser.parse(ping_result)
        with_tc_rtt_avg = pingparser.rtt_avg

        # exclude certain network ---
        assert SubprocessRunner([
            Tc.Command.TCSET,
            "--device {:s}".format(device_option),
            "--exclude-dst-network {:s}/24".format(
                ".".join(dst_host_option.split(".")[:3] + ["0"])),
            "--delay {:d}ms".format(delay),
            "--overwrite",
        ]).run() == 0

        pingparser.parse(transmitter.ping())
        without_tc_rtt_avg = pingparser.rtt_avg

        # assertion ---
        rtt_diff = with_tc_rtt_avg - without_tc_rtt_avg
        assert rtt_diff > (delay / 2.0)

        # finalize ---
        execute_tcdel(device_option)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    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/>.
#
##############################################################################

import time
from osv import fields,osv

#
# Sale/Purchase Canal, Media
#
class res_partner_canal(osv.osv):
    _name = "res.partner.canal"
    _description = "Channels"
    _order = 'name'
    _columns = {
        'name': fields.char('Channel Name',size=64, required=True),
        'active': fields.boolean('Active'),
    }
    _defaults = {
        'active': lambda *a: 1,
    }
res_partner_canal()

def _links_get(self, cr, uid, context={}):
    obj = self.pool.get('res.request.link')
    ids = obj.search(cr, uid, [])
    res = obj.read(cr, uid, ids, ['object', 'name'], context)
    return [(r['object'], r['name']) for r in res]

class res_partner_event(osv.osv):
    _name = "res.partner.event"
    _columns = {
        'name': fields.char('Events',size=64, required=True),
        'description': fields.text('Description'),
        'partner_id': fields.many2one('res.partner', 'Partner', select=True),
        'date': fields.datetime('Date', size=16),
        'user_id': fields.many2one('res.users', 'User'),
    }
    _order = 'date desc'
    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
        'user_id': lambda self, cr, uid, context: uid,
    }
res_partner_event()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[MERGE] res/partner/crm: removed unused code.<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    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/>.
#
##############################################################################

import time
from osv import osv
from osv import fields

#
# Sale/Purchase Canal, Media
#
class res_partner_canal(osv.osv):
    _name = "res.partner.canal"
    _description = "Channels"
    _order = 'name'
    _columns = {
        'name': fields.char('Channel Name', size=64, required=True),
        'active': fields.boolean('Active'),
    }
    _defaults = {
        'active': lambda *a: 1,
    }
res_partner_canal()

class res_partner_event(osv.osv):
    _name = "res.partner.event"
    _columns = {
        'name': fields.char('Events', size=64, required=True),
        'description': fields.text('Description'),
        'partner_id': fields.many2one('res.partner', 'Partner', select=True),
        'date': fields.datetime('Date', size=16),
        'user_id': fields.many2one('res.users', 'User'),
    }
    _order = 'date desc'
    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
        'user_id': lambda self, cr, uid, context: uid,
    }
res_partner_event()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>