<commit_before>import inspect, re

__all__ = [
  'Object',
  'const',
  'static',
  'public',
  'private',
]

class _Attribute(object):
  """
  A base extreme attribute.
  """
  def __init__(self):
    self.__name__ = None

  def _get_caller(self):
    """
    Returns the calling frame.
    """
    def is_object(obj):
      def find_base(cls, bases):
        if cls in bases:
          return True
        else:
          for base in bases:
            if find_base(cls, base.__bases__):
              return True
        return False
      try:
        return find_base(Object, obj.__class__.__bases__)
      except AttributeError:
        return False

    i, selftext = 0, 'self.%s' % (self.__name__,)
    stacks = iter(inspect.stack())
    callingframe = None
    while i < 20 and callingframe is None:
      try:
        stack = next(stacks)
      except StopIteration:
        break

      # The xpy Object class uses either __getattribute__ or __setattr__ to access
      # internall class/instance attributes, so check find that call. The frame
      # immediately after __getattribute__ or __setattr__ should be the calling frame.
      code = stack[0].f_code
      if code.co_name == '__getattribute__' or code.co_name == '__setattr__' and code.co_varnames[0] == 'self':
        # If this appears to be a call from within the Object class, get the calling
        # frame and extract the calling instance (first argument).
        instance = stack[0].f_locals['self']
        if is_object(instance):
          callingframe = next(stacks)
          try:
            firstarg = callingframe[0].f_code.co_varnames[0]
          except IndexError:
            return None
          else:
            for i in range(len(callingframe[4])):
              if '%s.%s' % (firstarg, self.__name__) in callingframe[4][i]:
                return callingframe[0].f_locals[firstarg]
      i += 1
    return None

class Constant(_Attribute):
  """
  A constant attribute.
  """
  def __init__(self, value):
    self.__value__ = value

  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    return self.__value__

  def __set__(self, instance, value):
    """
    Raises an AttributeError to make the constant value read-only.
    """
    raise AttributeError("%s object attribute %s is read-only." % (instance.__class__.__name__, self.__name__))

class _Method(_Attribute):
  """
  A callable attribute.
  """
  def __init__(self, callback):
    if not callable(callback):
      raise AttributeError("%s is not callable." % (callback,))
    self.__callback__ = callback

  def __get__(self, instance, owner):
    return self.__callback__

class _Variable(_Attribute):
  """
  A typeable attribute.
  """
  def __init__(self, *args, **kwargs):
    try:
      args[0]
    except IndexError:
      try:
        kwargs['default']
      except KeyError:
        self.__hasdefault__ = False
        self.__default__ = None
      else:
        self.__hasdefault__ = True
        self.__default__ = kwargs['default']
    else:
      self.__hasdefault__ = True
      self.__default__ = args[0]

    for kwarg in ('type', 'validate'):
      try:
        kwargs[kwarg]
      except KeyError:
        setattr(self, '__%s__'%(kwarg,), None)
      else:
        setattr(self, '__%s__'%(kwarg,), kwargs[kwarg])
    super(_Variable, self).__init__()

  def _validate(self, value):
    """
    Validates a variable value.
    """
    if self.__type__ is not None:
      if not isinstance(value, self.__type__):
        raise AttributeError("Invalid attribute value %s." % (value,))
    if self.__validate__ is not None:
      if not self.__validate__(value):
        raise AttributeError("Invalid attribute value %s." % (value,))
    return value

class StaticMethod(_Method):
  """
  A static method.
  """

class StaticMember(_Variable):
  """
  A static member.
  """

class PublicMethod(_Method):
  """
  A public method.
  """

class PublicMember(_Variable):
  """
  A public member.
  """
  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    try:
      instance.__properties__
    except AttributeError:
      instance.__properties__ = {}
    try:
      return instance.__properties__[self.__name__]
    except KeyError:
      if self.__hasdefault__:
        return self.__default__
      raise AttributeError("%s object %s not found." % (instance.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    try:
      instance.__properties__
    except AttributeError:
      instance.__properties__ = {}
    instance.__properties__[self.__name__] = self._validate(value)

  def __del__(self, instance):
    """
    Deletes the attribute value.
    """
    try:
      del instance.__properties__[self.__name__]
    except AttributeError:
      pass
    except KeyError:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

class StaticPublicMethod(_Method):
  """
  A static public method.
  """
  def __get__(self, instance, owner=None):
    if owner is None:
      owner = instance.__class__
    def wrap(*args, **kwargs):
      return self.__callback__(owner, *args, **kwargs)
    return wrap

class StaticPublicMember(_Variable):
  """
  A static public member.
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    try:
      owner.__properties__
    except AttributeError:
      owner.__properties__ = {}
    try:
      return owner.__properties__[self.__name__]
    except KeyError:
      if self.__hasdefault__:
        return self.__default__
      raise AttributeError("%s object %s not found." % (owner.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    owner = instance.__class__
    try:
      owner.__properties__
    except AttributeError:
      owner.__properties__ = {}
    owner.__properties__[self.__name__] = self._validate(value)

  def __del__(self, instance):
    """
    Deletes the attribute value.
    """
    owner = instance.__class__
    try:
      del owner.__properties__[self.__name__]
    except AttributeError:
      pass
    except KeyError:
      raise AttributeError("%s object attribute %s not found." % (owner.__class__.__name__, self.__name__))

class PrivateMethod(_Method):
  """
  A private method.
  """
  def __get__(self, instance, owner=None):
    if owner is None:
      owner = instance.__class__
    caller = self._get_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name:
      def wrap(*args, **kwargs):
        return self.__callback__(owner, *args, **kwargs)
      return wrap
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

class PrivateMember(_Variable):
  """
  A private member.
  """
  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    caller = self._get_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name__:
      try:
        instance.__properties__
      except AttributeError:
        instance.__properties__ = {}
      try:
        return instance.__properties__[self.__name__]
      except KeyError:
        if self.__hasdefault__:
          return self.__default__
        raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    caller = self._get_caller()
    if caller.__class__.__name__ == instance.__class__.__name__:
      try:
        instance.__properties__
      except AttributeError:
        instance.__properties__ = {}
      instance.__properties__[self.__name__] = self._validate(value)
    else:
      raise AttributeError("%s attribute %s not found." % (instance.__class__.__name__, self.__name__,))

class StaticPrivateMethod(_Method):
  """
  A static private method.
  """

class StaticPrivateMember(_Variable):
  """
  A static private member
  """

class _ObjectType(type):
  """
  An extreme object metaclass.
  """
  def __init__(cls, name, bases, d):
    super(_ObjectType, cls).__init__(name, bases, d)
    attributes = {}
    for key in d.keys():
      if isinstance(d[key], _Attribute):
        attributes[key] = d[key]
        attributes[key].__name__ = key
        delattr(cls, key)
    setattr(cls, '__attributes__', attributes)

class Object(object):
  """
  A base object.
  """
  __metaclass__ = _ObjectType

  def __getattribute__(self, name):
    _attributes_ = object.__getattribute__(self, '__class__').__dict__['__attributes__']
    try:
      _attribute_ = _attributes_[name]
    except KeyError:
      return object.__getattribute__(self, name)
    else:
      return _attribute_.__get__(self, self.__class__)

  def __setattr__(self, name, value):
    _attributes_ = object.__getattribute__(self, '__class__').__dict__['__attributes__']
    try:
      _attribute_ = _attributes_[name]
    except KeyError:
      return object.__setattr__(self, name, value)
    else:
      return _attribute_.__set__(self, value)

def const(value):
  if callable(value):
    raise AttributeError("Constant values may not be callable.")
  return Constant(value)

def static(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return StaticMethod(args[0])
    else:
      if isinstance(args[0], PublicMethod):
        return StaticPublicMethod(args[0].__callback__)
      elif isinstance(args[0], PrivateMethod):
        return StaticPrivateMethod(args[0].__callback__)
      elif isinstance(args[0], PublicMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        return StaticPublicMember(**kwargs)
      elif isinstance(args[0], PrivateMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        return StaticPrivateMember(**kwargs)
      else:
        return StaticMember(args[0])
  else:
    return StaticMember(*args, **kwargs)

def public(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return PublicMethod(args[0])
    else:
      if isinstance(args[0], StaticMethod):
        return StaticPublicMethod(args[0].__callback__)
      elif isinstance(args[0], StaticMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        return StaticPublicMember(**kwargs)
      else:
        return PublicMember(args[0])
  else:
    return PublicMember(*args, **kwargs)

def private(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return PrivateMethod(args[0])
    else:
      if isinstance(args[0], StaticMethod):
        return StaticPrivateMethod(args[0].__callback__)
      elif isinstance(args[0], StaticMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        return StaticPrivateMember(**kwargs)
      else:
        return PrivateMember(args[0])
  else:
    return PrivateMember(*args, **kwargs)
<commit_msg>Add various basic classes.<commit_after>import inspect, gc

__all__ = [
  'Object',
  'const',
  'static',
  'public',
  'protected',
  'private',
]

class _Attribute(object):
  """
  A base extreme attribute.
  """
  def __init__(self):
    self.__name__ = None
    self.__parent__ = None

  def _get_local_caller(self):
    """
    Returns the calling frame.
    """
    i, selftext = 0, 'self.%s' % (self.__name__,)
    stacks = iter(inspect.stack())
    callingframe = None
    while i < 5 and callingframe is None:
      try:
        stack = next(stacks)
      except StopIteration:
        break

      # The xpy Object class uses either __getattribute__ or __setattr__ to access
      # internall class/instance attributes, so check find that call. The frame
      # immediately after __getattribute__ or __setattr__ should be the calling frame.
      code = stack[0].f_code
      if code.co_name == '__getattribute__' or code.co_name == '__setattr__' and code.co_varnames[0] == 'self':
        # If this appears to be a call from within the Object class, get the calling
        # frame and extract the calling instance (first argument).
        instance = stack[0].f_locals['self']
        if isinstance(instance, Object):
          callingframe = next(stacks)
          try:
            firstarg = callingframe[0].f_code.co_varnames[0]
          except IndexError:
            return None
          else:
            if firstarg == 'self':
              firstinst = callingframe[0].f_locals[firstarg]
              if isinstance(firstinst, Object):
                for i in range(len(callingframe[4])):
                  if 'self.%s' % (self.__name__,) in callingframe[4][i] or '%s.%s' % (self.__parent__, self.__name__) in callingframe[4][i]:
                    return firstinst
            return None
      i += 1
    return None

class Constant(_Attribute):
  """
  A constant attribute.
  """
  def __init__(self, value):
    self.__value__ = value

  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    return self.__value__

  def __set__(self, instance, value):
    """
    Raises an AttributeError to make the constant value read-only.
    """
    raise AttributeError("%s object attribute %s is read-only." % (instance.__class__.__name__, self.__name__))

class _Method(_Attribute):
  """
  A callable attribute.
  """
  def __init__(self, callback):
    if not callable(callback):
      raise AttributeError("%s is not callable." % (callback,))
    self.__callback__ = callback

  def __get__(self, instance, owner):
    return self.__callback__

class _Variable(_Attribute):
  """
  A typeable attribute.
  """
  def __init__(self, *args, **kwargs):
    try:
      args[0]
    except IndexError:
      try:
        kwargs['default']
      except KeyError:
        self.__hasdefault__ = False
        self.__default__ = None
      else:
        self.__hasdefault__ = True
        self.__default__ = kwargs['default']
    else:
      self.__hasdefault__ = True
      self.__default__ = args[0]

    for kwarg in ('type', 'validate'):
      try:
        kwargs[kwarg]
      except KeyError:
        setattr(self, '__%s__'%(kwarg,), None)
      else:
        setattr(self, '__%s__'%(kwarg,), kwargs[kwarg])
    super(_Variable, self).__init__()

  def _validate(self, value):
    """
    Validates a variable value.
    """
    if self.__type__ is not None:
      if not isinstance(value, self.__type__):
        raise AttributeError("Invalid attribute value %s." % (value,))
    if self.__validate__ is not None:
      if not self.__validate__(value):
        raise AttributeError("Invalid attribute value %s." % (value,))
    return value

class StaticMethod(_Method):
  """
  A static method.
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    def wrap(*args, **kwargs):
      return self.__callback__(owner, *args, **kwargs)
    return wrap

class StaticMember(_Variable):
  """
  A static member.
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    try:
      owner.__properties__
    except AttributeError:
      owner.__properties__ = {}
    try:
      return owner.__properties__[self.__name__]
    except KeyError:
      if self.__hasdefault__:
        return self.__default__
      raise AttributeError("%s object %s not found." % (owner.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    owner = instance.__class__
    try:
      owner.__properties__
    except AttributeError:
      owner.__properties__ = {}
    owner.__properties__[self.__name__] = self._validate(value)

  def __del__(self, instance=None):
    """
    Deletes the attribute value.
    """
    if instance is None:
      return
    owner = instance.__class__
    try:
      del owner.__properties__[self.__name__]
    except AttributeError:
      pass
    except KeyError:
      raise AttributeError("%s object attribute %s not found." % (owner.__class__.__name__, self.__name__))

class PublicMethod(_Method):
  """
  A public method.
  """

class PublicMember(_Variable):
  """
  A public member.
  """
  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    try:
      instance.__properties__
    except AttributeError:
      instance.__properties__ = {}
    try:
      return instance.__properties__[self.__name__]
    except KeyError:
      if self.__hasdefault__:
        return self.__default__
      raise AttributeError("%s object %s not found." % (instance.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    try:
      instance.__properties__
    except AttributeError:
      instance.__properties__ = {}
    instance.__properties__[self.__name__] = self._validate(value)

  def __del__(self, instance=None):
    """
    Deletes the attribute value.
    """
    if instance is None:
      return
    try:
      del instance.__properties__[self.__name__]
    except AttributeError:
      pass
    except KeyError:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

class StaticPublicMethod(StaticMethod):
  """
  A static public method.
  """

class StaticPublicMember(StaticMember):
  """
  A static public member.
  """

class PrivateMethod(_Method):
  """
  A protected method.
  """
  def __get__(self, instance, owner=None):
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name__:
      def wrap(*args, **kwargs):
        return self.__callback__(owner, *args, **kwargs)
      return wrap
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

class ProtectedMember(_Variable):
  """
  A protected member.
  """
  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    for cls in inspect.getmro(caller.__class__):
      if cls.__name__ == self.__parent__:
        try:
          instance.__properties__
        except AttributeError:
          instance.__properties__ = {}
        try:
          return instance.__properties__[self.__name__]
        except KeyError:
          if self.__hasdefault__:
            return self.__default__
          raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    for cls in inspect.getmro(caller.__class__):
      if cls.__name__ == self.__parent__:
        try:
          instance.__properties__
        except AttributeError:
          instance.__properties__ = {}
        instance.__properties__[self.__name__] = self._validate(value)
        return
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__,))

class StaticProtectedMethod(_Method):
  """
  A static protected method.
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    for cls in inspect.getmro(caller.__class__):
      if cls.__name__ == self.__parent__:
        def wrap(*args, **kwargs):
          return self.__callback__(owner, *args, **kwargs)
        return wrap
    raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__))

class StaticProtectedMember(_Variable):
  """
  A static protected member
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    for cls in inspect.getmro(caller.__class__):
      if cls.__name__ == self.__parent__:
        try:
          owner.__properties__
        except AttributeError:
          owner.__properties__ = {}
        try:
          return owner.__properties__[self.__name__]
        except KeyError:
          if self.__hasdefault__:
            return self.__default__
    raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    for cls in inspect.getmro(caller.__class__):
      if cls.__name__ == self.__parent__:
        try:
          owner.__properties__
        except AttributeError:
          owner.__properties__ = {}
        owner.__properties__[self.__name__] = self._validate(value)
        return
    raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__,))

class PrivateMethod(_Method):
  """
  A private method.
  """
  def __get__(self, instance, owner=None):
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name:
      def wrap(*args, **kwargs):
        return self.__callback__(owner, *args, **kwargs)
      return wrap
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

class PrivateMember(_Variable):
  """
  A private member.
  """
  def __get__(self, instance, owner):
    """
    Gets the attribute value.
    """
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name__:
      try:
        instance.__properties__
      except AttributeError:
        instance.__properties__ = {}
      try:
        return instance.__properties__[self.__name__]
      except KeyError:
        if self.__hasdefault__:
          return self.__default__
        raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__))
    if caller.__class__.__name__ == instance.__class__.__name__:
      try:
        instance.__properties__
      except AttributeError:
        instance.__properties__ = {}
      instance.__properties__[self.__name__] = self._validate(value)
    else:
      raise AttributeError("%s object attribute %s not found." % (instance.__class__.__name__, self.__name__,))

class StaticPrivateMethod(_Method):
  """
  A static private method.
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    if caller.__class__.__name__ == owner.__name__:
      def wrap(*args, **kwargs):
        return self.__callback__(owner, *args, **kwargs)
      return wrap
    raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__))

class StaticPrivateMember(_Variable):
  """
  A static private member
  """
  def __get__(self, instance, owner=None):
    """
    Gets the attribute value.
    """
    if owner is None:
      owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    if caller.__class__.__name__ == owner.__name__:
      try:
        owner.__properties__
      except AttributeError:
        owner.__properties__ = {}
      try:
        return owner.__properties__[self.__name__]
      except KeyError:
        if self.__hasdefault__:
          return self.__default__
    raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__))

  def __set__(self, instance, value):
    """
    Sets the attribute value.
    """
    owner = instance.__class__
    caller = self._get_local_caller()
    if caller is None:
      raise AttributeError("%s object attribute %s not found." % (owner.__name__, self.__name__))
    if caller.__class__.__name__ == owner.__name__:
      try:
        owner.__properties__
      except AttributeError:
        owner.__properties__ = {}
      owner.__properties__[self.__name__] = self._validate(value)
    else:
      raise AttributeError("%s attribute %s not found." % (owner.__name__, self.__name__,))

class _ObjectType(type):
  """
  An extreme object metaclass.
  """
  def __init__(cls, name, bases, d):
    super(_ObjectType, cls).__init__(name, bases, d)
    attributes = {}
    for key in d.keys():
      if not (key.startswith('__') and key.endswith('__')):
        if not isinstance(d[key], _Attribute):
          if callable(d[key]):
            d[key] = public(d[key])
          else:
            d[key] = public(default=d[key])
        attributes[key] = d[key]
        attributes[key].__name__ = key
        attributes[key].__parent__ = cls
        delattr(cls, key)
    setattr(cls, '__attributes__', attributes)

class Object(object):
  """
  A base object.
  """
  __metaclass__ = _ObjectType

  def __getattribute__(self, name):
    _attributes_ = object.__getattribute__(self, '__class__').__dict__['__attributes__']
    try:
      _attribute_ = _attributes_[name]
    except KeyError:
      return object.__getattribute__(self, name)
    else:
      return _attribute_.__get__(self, self.__class__)

  def __setattr__(self, name, value):
    _attributes_ = object.__getattribute__(self, '__class__').__dict__['__attributes__']
    try:
      _attribute_ = _attributes_[name]
    except KeyError:
      return object.__setattr__(self, name, value)
    else:
      return _attribute_.__set__(self, value)

def const(value):
  if callable(value):
    raise AttributeError("Constant values may not be callable.")
  return Constant(value)

def static(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return StaticMethod(args[0])
    else:
      if isinstance(args[0], PublicMethod):
        return StaticPublicMethod(args[0].__callback__)
      elif isinstance(args[0], ProtectedMethod):
        return StaticProtectedMethod(args[0].__callback__)
      elif isinstance(args[0], PrivateMethod):
        return StaticPrivateMethod(args[0].__callback__)
      elif isinstance(args[0], PublicMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticPublicMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      elif isinstance(args[0], ProtectedMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticProtectedMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      elif isinstance(args[0], PrivateMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticPrivateMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      else:
        return StaticMember(args[0])
  else:
    return StaticMember(*args, **kwargs)

def public(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return PublicMethod(args[0])
    else:
      if isinstance(args[0], StaticMethod):
        return StaticPublicMethod(args[0].__callback__)
      elif isinstance(args[0], StaticMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticPublicMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      else:
        return PublicMember(args[0])
  else:
    return PublicMember(*args, **kwargs)

def protected(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return ProtectedMethod(args[0])
    else:
      if isinstance(args[0], StaticMethod):
        return StaticProtectedMethod(args[0].__callback__)
      elif isinstance(args[0], StaticMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticProtectedMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      else:
        return ProtectedMember(args[0])
  else:
    return ProtectedMember(*args, **kwargs)

def private(*args, **kwargs):
  if len(args) == 1 and len(kwargs) == 0:
    if inspect.ismethod(args[0]):
      return PrivateMethod(args[0])
    else:
      if isinstance(args[0], StaticMethod):
        return StaticPrivateMethod(args[0].__callback__)
      elif isinstance(args[0], StaticMember):
        kwargs = dict(type=args[0].__type__, validate=args[0].__validate__)
        if args[0].__hasdefault__:
          kwargs['default'] = args[0].__default__
        member = StaticPrivateMember(**kwargs)
        member.__name__ = args[0].__name__
        member.__parent__ = args[0].__parent__
        return member
      else:
        return PrivateMember(args[0])
  else:
    return PrivateMember(*args, **kwargs)
<|endoftext|>


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

from django.conf import settings as st
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.views.generic import TemplateView, RedirectView
from django.views.generic.detail import DetailView

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^investigacion/$', RedirectView.as_view(
        url=st.BASE_URL), name='index'),
    url(r'^investigacion/admin/', include(admin.site.urls)),
    url(r'^investigacion/accounts/login/$',
        'django_cas.views.login', name='login'),
    url(r'^investigacion/accounts/logout/$',
        'django_cas.views.logout', name='logout'),
    url(r'^investigacion/tinymce/', include('tinymce.urls')),
)

urlpatterns += i18n_patterns(
    '',
    url(r'^investigacion/cvn/', include('cvn.urls')),
    url(r'^investigacion/faq/$', TemplateView.as_view(
        template_name='core/faq.html'), name='faq'),
    url(r'^investigacion/faq/(?P<pk>\d+)/$', DetailView.as_view(
        template_name='core/question_faq.html', model=FlatPage),
        name='question_faq'),
)

if st.DEVEL:
    urlpatterns += static(st.MEDIA_URL, document_root=st.MEDIA_ROOT)
    if 'rosetta' in st.INSTALLED_APPS:
        urlpatterns += patterns(
            '',
            url(r'^rosetta/', include('rosetta.urls')),
        )
<commit_msg>Changed URL Rosetta<commit_after># -*- encoding: utf-8 -*-

from django.conf import settings as st
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.views.generic import TemplateView, RedirectView
from django.views.generic.detail import DetailView

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^investigacion/$', RedirectView.as_view(
        url=st.BASE_URL), name='index'),
    url(r'^investigacion/admin/', include(admin.site.urls)),
    url(r'^investigacion/accounts/login/$',
        'django_cas.views.login', name='login'),
    url(r'^investigacion/accounts/logout/$',
        'django_cas.views.logout', name='logout'),
    url(r'^investigacion/tinymce/', include('tinymce.urls')),
)

urlpatterns += i18n_patterns(
    '',
    url(r'^investigacion/cvn/', include('cvn.urls')),
    url(r'^investigacion/faq/$', TemplateView.as_view(
        template_name='core/faq.html'), name='faq'),
    url(r'^investigacion/faq/(?P<pk>\d+)/$', DetailView.as_view(
        template_name='core/question_faq.html', model=FlatPage),
        name='question_faq'),
)

if st.DEVEL:
    urlpatterns += static(st.MEDIA_URL, document_root=st.MEDIA_ROOT)

if st.DEBUG:
    if 'rosetta' in st.INSTALLED_APPS:
        urlpatterns += patterns(
            '',
            url(r'^investigacion/rosetta/', include('rosetta.urls')),
        )
<|endoftext|>


<commit_before>import logging
import time

logger = logging.getLogger(__name__)

class Monitor(object):
    """This class is used to track algorithms and environments."""

    def __init__(self, verbose=0):
        self.verbose = verbose

        # rollout
        self._rollout_cnt = {}

        # optimize
        self._optimize_start = {}
        self.optimize_times = {}
        self.optimize_policy = {}

        # step
        self.parameters = {}
        self.traces = {}
        self.rewards = {}
        self.step_cnts = {}
        self.rollout_cnts = {}

    def before_update(self, env):
        pass

    def after_update(self, env):
        pass

    def before_rollout(self, env):
        if env not in self._rollout_cnt:
            self._rollout_cnt[env] = 0

    def after_rollout(self, env):
        self._rollout_cnt[env] += 1

    def before_reset(self, env):
        pass

    def after_reset(self, env):
        pass

    def before_optimize(self, alg, policy):
        """Setup montitor for optimization run."""
        if self.verbose > 0:
            logger.info('Starting optimization of %s...', str(alg))

        # register algorithm
        # init policy
        self.optimize_policy[alg] = policy

        # init tracking information
        self.step_cnts[alg] = 0
        self.parameters[alg] = []
        self.traces[alg] = []
        self.rewards[alg] = []

        # init optimization time control
        self.optimize_times[alg] = []
        self._optimize_start[alg] = time.time()

    def after_optimize(self, alg):
        """Catch data after optimization run."""
        # retrieve time of optimization
        optimize_end = time.time()
        optimize_time = optimize_end - self._optimize_start[alg]

        if self._optimize_start[alg] == 0:
            logger.warning('Time measure for optimize corrupted')

        self._optimize_start[alg] = 0

        self.optimize_times[alg].append(optimize_time)

        # independently compute traces after optimization is finished
        if self.verbose > 0:
            logger.info('Computing traces for %s run...', str(alg))

        policy = self.optimize_policy[alg]

        for parameter in self.parameters[alg]:

            policy.setParameter(parameter)

            # compute trace
            trace = alg.environment._rollout(policy)
            self.traces[alg].append(trace)

            # compute total reward
            reward = sum([t[2] for t in trace])
            self.rewards[alg].append(reward)

    def before_step(self, alg):
        # count the number of rollouts for each step
        self._rollout_cnt[alg.environment] = 0

        if self.verbose > 1:
            logger.info('Computing step %d for %s...', self.step_cnts[alg],
                        str(alg))

        # place holding code to make sure we see something at this stage
        n = self.step_cnts[alg]
        parameter = self.optimize_policy[alg].parameter
        if n == 0:
            self.t = time.time()
        elif n % 100 == 0:
            print("Run: " + str(n) + "  \tParameter: \t" + str(parameter)
                  + "\n\t\tGradient: \t" + str(alg.grad))
            now = time.time()
            print("\t\tAverage Time: "
                  + "\t{:.2f}".format((now - self.t) / 100)
                  + "s/step")
            self.t = now

    def after_step(self, alg):

        self.step_cnts[alg] += 1

        # store the number of rollouts since before step
        self.rollout_cnts[alg].append(self.rollout_cnt[alg.environment])

        # retrieve information
        policy = self.optimize_policy[alg]
        parameter = policy.parameter

        # store information
        self.parameters[alg].append(parameter)
<commit_msg>Added alternative implementation for monitor...<commit_after>import logging
import time

logger = logging.getLogger(__name__)

class Monitor(object):
    """This class is used to track algorithms and environments."""

    def __init__(self, verbose=0):
        self.verbose = verbose

        self.monitors = {}

        # setup default algorithm monitor
        self.alg_monitor = {
            # init tracking information
            'step_cnt': 0,
            'rollout_cnts': [],

            'parameters': [],
            'traces': [],
            'rewards': [],
        }

        # setup default environment monitor
        self.env_monitor = {
            '_rollout_cnt': 0
        }
        # rollout
        self._rollout_cnt = {}

        # optimize
        self._optimize_start = {}
        self.optimize_times = {}
        self.optimize_policy = {}

        # step
        self.parameters = {}
        self.traces = {}
        self.rewards = {}
        self.step_cnts = {}
        self.rollout_cnts = {}

    def before_update(self, env):
        pass

    def after_update(self, env):
        pass

    def before_rollout(self, env):
        if env not in self.monitors:
            self.monitors[env] = {'_rollout_cnt': 0}

    def after_rollout(self, env):
        self.monitors[env]['_rollout_cnt'] += 1

    def before_reset(self, env):
        pass

    def after_reset(self, env):
        pass

    def before_optimize(self, alg, policy):
        """Setup montitor for optimization run."""
        if self.verbose > 0:
            logger.info('Starting optimization of %s...', str(alg))

        # init monitor dict for algorithm
        monitor = self.alg_monitor.copy()
        monitor['policy'] = policy

        self.monitors[alg] = monitor

        if alg.environment not in self.monitors:
            self.monitors[alg.environment] = self.env_monitor.copy()

        # init optimization time control
        monitor['_optimize_start'] = time.time()

    def after_optimize(self, alg):
        """Catch data after optimization run."""
        monitor = self.monitors[alg]
        # retrieve time of optimization
        optimize_end = time.time()
        optimize_time = optimize_end - monitor['_optimize_start']

        if monitor['_optimize_start'] == 0:
            logger.warning('Time measure for optimize corrupted')

        monitor['_optimize_start'] = 0

        monitor['optimize_time'] = optimize_time

        # independently compute traces after optimization is finished
        if self.verbose > 0:
            logger.info('Computing traces for %s run...', str(alg))

        policy = monitor['policy']

        for parameter in monitor['parameters']:

            policy.setParameter(parameter)

            # compute trace
            trace = alg.environment._rollout(policy)
            monitor['traces'].append(trace)

            # compute total reward
            reward = sum([t[2] for t in trace])
            monitor['rewards'].append(reward)

    def before_step(self, alg):
        # count the number of rollouts for each step
        self.monitors[alg.environment]['rollout_cnt'] = 0

        if self.verbose > 1:
            logger.info('Computing step %d for %s...', self.step_cnts[alg],
                        str(alg))

        # place holding code to make sure we see something at this stage
        monitor = self.monitors[alg]
        n = monitor['step_cnt']
        parameter = monitor['policy'].parameter

        if n == 0:
            self.t = time.time()
        elif n % 100 == 0:
            print("Run: " + str(n) + "  \tParameter: \t" + str(parameter)
                  + "\n\t\tGradient: \t" + str(alg.grad))
            now = time.time()
            print("\t\tAverage Time: "
                  + "\t{:.2f}".format((now - self.t) / 100)
                  + "s/step")
            self.t = now

    def after_step(self, alg):
        monitor = self.monitor[alg]
        emonitor = self.monitor[alg.environment]

        monitor['step_cnt'] += 1

        # store the number of rollouts since before step
        monitor['rollout_cnts'].append(emonitor['_rollout_cnt'])

        # retrieve information
        policy = monitor['policy']
        parameter = policy.parameter

        # store information
        monitor['parameter'].append(parameter)
<|endoftext|>


<commit_before>"""Properties

:class:`Property` objects can be defined on subclasses of
:class:`~pydispatch.Dispatcher` to create instance attributes that act as events
when their values change::

    from pydispatch import Dispatcher, Property

    class Foo(Dispatcher):
        name = Property()
        value = Property()
    def __str__(self):
        return self.__class__.__name__

    class Listener(object):
        def on_foo_name(self, instance, value, **kwargs):
            print("{}'s name is {}".format(instance, value))
        def on_foo_value(self, instance, value, **kwargs):
            print('{} = {}'.format(instance, value))

    foo_obj = Foo()
    listener_obj = Listener()

    foo_obj.bind(name=listener_obj.on_foo_name, value=listener_obj.on_foo_value)

    foo_obj.name = 'bar'
    # Foo's name is bar

    foo_obj.value = 42
    # Foo = 42

Type checking is not enforced, so values can be any valid python type.
Values are however checked for equality to avoid dispatching events for no
reason. If custom objects are used as values, they must be able to support
equality checking. In most cases, this will be handled automatically.
"""

import sys
import weakref

from pydispatch.utils import InformativeWVDict

PY2 = sys.version_info < (3,)

class Property(object):
    """Defined on the class level to create an observable attribute

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise ``None``

    Attributes:
        name (str): The name of the Property as defined in the class definition.
            This will match the attribute name for the :class:`Dispatcher` instance.

    """
    def __init__(self, default=None):
        self._name = ''
        self.default = default
        self.__storage = {}
        self.__weakrefs = InformativeWVDict(del_callback=self._on_weakref_fin)
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, value):
        if self._name != '':
            return
        self._name = value
    def _add_instance(self, obj, default=None):
        if default is None:
            default = self.default
        self.__storage[id(obj)] = self.default
        self.__weakrefs[id(obj)] = obj
    def _del_instance(self, obj):
        del self.__storage[id(obj)]
    def _on_weakref_fin(self, obj_id):
        del self.__storage[obj_id]
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        return self.__storage[obj_id]
    def __set__(self, obj, value):
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        current = self.__storage[obj_id]
        if current == value:
            return
        self.__storage[obj_id] = value
        self._on_change(obj, current, value)
    def _on_change(self, obj, old, value, **kwargs):
        """Called internally to emit changes from the instance object

        The keyword arguments here will be passed to callbacks through the
        instance object's :meth:`~Dispatcher.emit` method.

        Keyword Args:
            property: The :class:`Property` instance. This is useful if multiple
                properties are bound to the same callback. The attribute name
            keys (optional): If the :class:`Property` is a container type
                (:class:`ListProperty` or :class:`DictProperty`), the changes
                may be found here.
                This is not implemented for nested containers and will only be
                available for operations that do not alter the size of the
                container.

        """
        kwargs['property'] = self
        obj.emit(self.name, obj, value, old=old, **kwargs)
    def __repr__(self):
        return '<{}: {}>'.format(self.__class__, self)
    def __str__(self):
        return self.name

class ListProperty(Property):
    """Property with a ``list`` type value

    Changes to the contents of the list are able to be observed through
    :class:`ObservableList`.
    """
    def __init__(self, default=None):
        if default is None:
            default = []
        super(ListProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default[:]
        default = ObservableList(default, obj=obj, property=self)
        super(ListProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableList(value, obj=obj, property=self)
        super(ListProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(ListProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableList):
            value = ObservableList(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class DictProperty(Property):
    """Property with a ``dict`` type value

    Changes to the contents of the dict are able to be observed through
    :class:`ObservableDict`.
    """
    def __init__(self, default=None):
        if default is None:
            default = {}
        super(DictProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default.copy()
        default = ObservableDict(default, obj=obj, property=self)
        super(DictProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableDict(value, obj=obj, property=self)
        super(DictProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(DictProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableDict):
            value = ObservableDict(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class Observable(object):
    """Used by container subclasses to emit changes and build other observables

    When an item is added to an observable container (a subclass of Observable)
    it is type-checked and, if possible replaced by an observable version of it.

    In other words, if a ``dict`` is added to a :class:`ObservableDict`, it is
    copied and replaced by another :class:`ObservableDict`. This allows nested
    containers to be observed and their changes to be tracked.
    """
    def _build_observable(self, item):
        if isinstance(item, list):
            item = ObservableList(item, parent=self)
        elif isinstance(item, dict):
            item = ObservableDict(item, parent=self)
        return item
    def _emit_change(self, **kwargs):
        if not self._init_complete:
            return
        p = self.parent_observable
        if p is not None:
            p._emit_change()
            return
        self.property._on_change(self.obj, None, self, **kwargs)

class ObservableList(list, Observable):
    """A ``list`` object that tracks changes to its contents
    """
    def __init__(self, initlist=None, **kwargs):
        self._init_complete = False
        super(ObservableList, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if initlist is not None:
            self.extend(initlist)
        self._init_complete = True
    def __setitem__(self, key, item):
        item = self._build_observable(item)
        super(ObservableList, self).__setitem__(key, item)
        self._emit_change(keys=[key])
    def __delitem__(self, key):
        super(ObservableList, self).__delitem__(key)
        self._emit_change()
    if PY2:
        def __setslice__(self, *args):
            super(ObservableList, self).__setslice__(*args)
            self._emit_change()
        def __delslice__(self, *args):
            super(ObservableList, self).__delslice__(*args)
            self._emit_change()
    if hasattr(list, 'clear'):
        def clear(self):
            super(ObservableList, self).clear()
            self._emit_change()
    def __iadd__(self, other):
        other = self._build_observable(other)
        self.extend(other)
        return self
    def append(self, item):
        item = self._build_observable(item)
        super(ObservableList, self).append(item)
        self._emit_change()
    def extend(self, other):
        init = self._init_complete
        self._init_complete = False
        for item in other:
            self.append(item)
        if init:
            self._init_complete = True
        self._emit_change()
    def remove(self, *args):
        super(ObservableList, self).remove(*args)
        self._emit_change()

class ObservableDict(dict, Observable):
    """A ``dict`` object that tracks changes to its contents
    """
    def __init__(self, initdict=None, **kwargs):
        self._init_complete = False
        super(ObservableDict, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if initdict is not None:
            self.update(initdict)
        self._init_complete = True
    def __setitem__(self, key, item):
        item = self._build_observable(item)
        super(ObservableDict, self).__setitem__(key, item)
        self._emit_change(keys=[key])
    def __delitem__(self, key):
        super(ObservableDict, self).__delitem__(key)
        self._emit_change()
    def update(self, other):
        init = self._init_complete
        self._init_complete = False
        keys = set(other.keys()) - set(self.keys())
        for key, val in other.items():
            if key not in keys and self[key] == val:
                continue
            self[key] = val
            keys.add(key)
        if init:
            self._init_complete = True
        self._emit_change(keys=list(keys))
    def clear(self):
        super(ObservableDict, self).clear()
        self._emit_change()
    def pop(self, *args):
        super(ObservableDict, self).pop(*args)
        self._emit_change()
    def setdefault(self, *args):
        super(ObservableDict, self).setdefault(*args)
        self._emit_change()
<commit_msg>Add optional copy_on_change parameter for container properties<commit_after>"""Properties

:class:`Property` objects can be defined on subclasses of
:class:`~pydispatch.Dispatcher` to create instance attributes that act as events
when their values change::

    from pydispatch import Dispatcher, Property

    class Foo(Dispatcher):
        name = Property()
        value = Property()
    def __str__(self):
        return self.__class__.__name__

    class Listener(object):
        def on_foo_name(self, instance, value, **kwargs):
            print("{}'s name is {}".format(instance, value))
        def on_foo_value(self, instance, value, **kwargs):
            print('{} = {}'.format(instance, value))

    foo_obj = Foo()
    listener_obj = Listener()

    foo_obj.bind(name=listener_obj.on_foo_name, value=listener_obj.on_foo_value)

    foo_obj.name = 'bar'
    # Foo's name is bar

    foo_obj.value = 42
    # Foo = 42

Type checking is not enforced, so values can be any valid python type.
Values are however checked for equality to avoid dispatching events for no
reason. If custom objects are used as values, they must be able to support
equality checking. In most cases, this will be handled automatically.
"""

import sys
import weakref

from pydispatch.utils import InformativeWVDict

PY2 = sys.version_info < (3,)

class Property(object):
    """Defined on the class level to create an observable attribute

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise ``None``

    Attributes:
        name (str): The name of the Property as defined in the class definition.
            This will match the attribute name for the :class:`Dispatcher` instance.

    """
    def __init__(self, default=None):
        self._name = ''
        self.default = default
        self.__storage = {}
        self.__weakrefs = InformativeWVDict(del_callback=self._on_weakref_fin)
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, value):
        if self._name != '':
            return
        self._name = value
    def _add_instance(self, obj, default=None):
        if default is None:
            default = self.default
        self.__storage[id(obj)] = self.default
        self.__weakrefs[id(obj)] = obj
    def _del_instance(self, obj):
        del self.__storage[id(obj)]
    def _on_weakref_fin(self, obj_id):
        del self.__storage[obj_id]
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        return self.__storage[obj_id]
    def __set__(self, obj, value):
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        current = self.__storage[obj_id]
        if current == value:
            return
        self.__storage[obj_id] = value
        self._on_change(obj, current, value)
    def _on_change(self, obj, old, value, **kwargs):
        """Called internally to emit changes from the instance object

        The keyword arguments here will be passed to callbacks through the
        instance object's :meth:`~Dispatcher.emit` method.

        Keyword Args:
            property: The :class:`Property` instance. This is useful if multiple
                properties are bound to the same callback. The attribute name
            keys (optional): If the :class:`Property` is a container type
                (:class:`ListProperty` or :class:`DictProperty`), the changes
                may be found here.
                This is not implemented for nested containers and will only be
                available for operations that do not alter the size of the
                container.

        """
        kwargs['property'] = self
        obj.emit(self.name, obj, value, old=old, **kwargs)
    def __repr__(self):
        return '<{}: {}>'.format(self.__class__, self)
    def __str__(self):
        return self.name

class ListProperty(Property):
    """Property with a ``list`` type value

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise ``None``
        copy_on_change (bool, optional): If ``True``, the ``list`` will be copied
            when contents are modified. This can be useful for observing the
            original state of the ``list`` from within callbacks. The copied
            (original) state will be available from the keyword argument 'old'.
            The default if ``False`` (for performance and memory reasons).

    Changes to the contents of the list are able to be observed through
    :class:`ObservableList`.
    """
    def __init__(self, default=None, copy_on_change=False):
        if default is None:
            default = []
        self.copy_on_change = copy_on_change
        super(ListProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default[:]
        default = ObservableList(default, obj=obj, property=self)
        super(ListProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableList(value, obj=obj, property=self)
        super(ListProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(ListProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableList):
            value = ObservableList(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class DictProperty(Property):
    """Property with a ``dict`` type value

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise ``None``
        copy_on_change (bool, optional): If ``True``, the ``dict`` will be copied
            when contents are modified. This can be useful for observing the
            original state of the ``dict`` from within callbacks. The copied
            (original) state will be available from the keyword argument 'old'.
            The default if ``False`` (for performance and memory reasons).

    Changes to the contents of the dict are able to be observed through
    :class:`ObservableDict`.
    """
    def __init__(self, default=None, copy_on_change=False):
        if default is None:
            default = {}
        self.copy_on_change = copy_on_change
        super(DictProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default.copy()
        default = ObservableDict(default, obj=obj, property=self)
        super(DictProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableDict(value, obj=obj, property=self)
        super(DictProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(DictProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableDict):
            value = ObservableDict(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class Observable(object):
    """Used by container subclasses to emit changes and build other observables

    When an item is added to an observable container (a subclass of Observable)
    it is type-checked and, if possible replaced by an observable version of it.

    In other words, if a ``dict`` is added to a :class:`ObservableDict`, it is
    copied and replaced by another :class:`ObservableDict`. This allows nested
    containers to be observed and their changes to be tracked.
    """
    def _build_observable(self, item):
        if isinstance(item, list):
            item = ObservableList(item, parent=self)
        elif isinstance(item, dict):
            item = ObservableDict(item, parent=self)
        return item
    def _get_copy_or_none(self):
        p = self.parent_observable
        if p is not None:
            return p._get_copy_or_none()
        if not self.copy_on_change:
            return None
        return self._deepcopy()
    def _deepcopy(self):
        o = self.copy()
        if isinstance(self, list):
            item_iter = enumerate(self)
        elif isinstance(self, dict):
            item_iter = self.items()
        for key, item in item_iter:
            if isinstance(item, Observable):
                o[key] = item._deepcopy()
        return o
    def _emit_change(self, **kwargs):
        if not self._init_complete:
            return
        old = kwargs.pop('old')
        p = self.parent_observable
        if p is not None:
            p._emit_change(old=old)
            return
        self.property._on_change(self.obj, old, self, **kwargs)

class ObservableList(list, Observable):
    """A ``list`` object that tracks changes to its contents
    """
    def __init__(self, initlist=None, **kwargs):
        self._init_complete = False
        super(ObservableList, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if self.property is not None:
            self.copy_on_change = self.property.copy_on_change
        else:
            self.copy_on_change = False
        if initlist is not None:
            self.extend(initlist)
        self._init_complete = True
    def __setitem__(self, key, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableList, self).__setitem__(key, item)
        self._emit_change(keys=[key], old=old)
    def __delitem__(self, key):
        old = self._get_copy_or_none()
        super(ObservableList, self).__delitem__(key)
        self._emit_change(old=old)
    if PY2:
        def __setslice__(self, *args):
            old = self._get_copy_or_none()
            super(ObservableList, self).__setslice__(*args)
            self._emit_change(old=old)
        def __delslice__(self, *args):
            old = self._get_copy_or_none()
            super(ObservableList, self).__delslice__(*args)
            self._emit_change(old=old)
    if hasattr(list, 'clear'):
        def clear(self):
            old = self._get_copy_or_none()
            super(ObservableList, self).clear()
            self._emit_change(old=old)
    if not hasattr(list, 'copy'):
        def copy(self):
            return self[:]
    def __iadd__(self, other):
        other = self._build_observable(other)
        self.extend(other)
        return self
    def append(self, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableList, self).append(item)
        self._emit_change(old=old)
    def extend(self, other):
        old = self._get_copy_or_none()
        init = self._init_complete
        self._init_complete = False
        for item in other:
            self.append(item)
        if init:
            self._init_complete = True
        self._emit_change(old=old)
    def remove(self, *args):
        old = self._get_copy_or_none()
        super(ObservableList, self).remove(*args)
        self._emit_change(old=old)

class ObservableDict(dict, Observable):
    """A ``dict`` object that tracks changes to its contents
    """
    def __init__(self, initdict=None, **kwargs):
        self._init_complete = False
        super(ObservableDict, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if self.property is not None:
            self.copy_on_change = self.property.copy_on_change
        else:
            self.copy_on_change = False
        if initdict is not None:
            self.update(initdict)
        self._init_complete = True
    def __setitem__(self, key, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableDict, self).__setitem__(key, item)
        self._emit_change(keys=[key], old=old)
    def __delitem__(self, key):
        old = self._get_copy_or_none()
        super(ObservableDict, self).__delitem__(key)
        self._emit_change(old=old)
    def update(self, other):
        old = self._get_copy_or_none()
        init = self._init_complete
        self._init_complete = False
        keys = set(other.keys()) - set(self.keys())
        for key, val in other.items():
            if key not in keys and self[key] == val:
                continue
            self[key] = val
            keys.add(key)
        if init:
            self._init_complete = True
        self._emit_change(keys=list(keys), old=old)
    def clear(self):
        old = self._get_copy_or_none()
        super(ObservableDict, self).clear()
        self._emit_change(old=old)
    def pop(self, *args):
        old = self._get_copy_or_none()
        super(ObservableDict, self).pop(*args)
        self._emit_change(old=old)
    def setdefault(self, *args):
        old = self._get_copy_or_none()
        super(ObservableDict, self).setdefault(*args)
        self._emit_change(old=old)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ************************************************************************
#   Copyright (C) 2011, Paul Lutus
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the
#   Free Software Foundation, Inc.,
#   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# ************************************************************************

import re
import sys

PVERSION = '1.0'

class BeautifyBash:

    def __init__(self):
        self.tab_str = ' '
        self.tab_size = 2

    def read_file(self, fp):
        with open(fp) as f:
            return f.read()

    def write_file(self, fp, data):
        with open(fp, 'w') as f:
            f.write(data)

    def beautify_string(self, data, path=''):
        tab = 0
        case_stack = []
        in_here_doc = False
        defer_ext_quote = False
        in_ext_quote = False
        ext_quote_string = ''
        here_string = ''
        output = []
        line = 1
        for record in re.split('\n', data):
            record = record.rstrip()
            stripped_record = record.strip()

            # collapse multiple quotes between ' ... '
            test_record = re.sub(r'\'.*?\'', '', stripped_record)
            # collapse multiple quotes between " ... "
            test_record = re.sub(r'".*?"', '', test_record)
            # collapse multiple quotes between ` ... `
            test_record = re.sub(r'`.*?`', '', test_record)
            # collapse multiple quotes between \` ... ' (weird case)
            test_record = re.sub(r'\\`.*?\'', '', test_record)
            # strip out any escaped single characters
            test_record = re.sub(r'\\.', '', test_record)
            # remove '#' comments
            test_record = re.sub(r'(\A|\s)(#.*)', '', test_record, 1)
            if(not in_here_doc):
                if(re.search('<<-?', test_record)):
                    here_string = re.sub('.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', '\\1', stripped_record, 1)
                    in_here_doc = (len(here_string) > 0)
            if(in_here_doc):  # pass on with no changes
                output.append(record)
                # now test for here-doc termination string
                if(re.search(here_string, test_record) and not re.search('<<', test_record)):
                    in_here_doc = False
            else:  # not in here doc
                if(in_ext_quote):
                    if(re.search(ext_quote_string, test_record)):
                        # provide line after quotes
                        test_record = re.sub('.*%s(.*)' % ext_quote_string, '\\1', test_record, 1)
                        in_ext_quote = False
                else:  # not in ext quote
                    if(re.search(r'(\A|\s)(\'|")', test_record)):
                        # apply only after this line has been processed
                        defer_ext_quote = True
                        ext_quote_string = re.sub('.*([\'"]).*', '\\1', test_record, 1)
                        # provide line before quote
                        test_record = re.sub('(.*)%s.*' % ext_quote_string, '\\1', test_record, 1)
                if(in_ext_quote):
                    # pass on unchanged
                    output.append(record)
                else:  # not in ext quote
                    inc = len(re.findall('(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
                    inc += len(re.findall('(\{|\(|\[)', test_record))
                    outc = len(re.findall('(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)', test_record))
                    outc += len(re.findall('(\}|\)|\])', test_record))
                    if(re.search(r'\besac\b', test_record)):
                        if(len(case_stack) == 0):
                            sys.stderr.write(
                                'File %s: error: "esac" before "case" in line %d.\n' % (path, line)
                            )
                        else:
                            outc += case_stack.pop()
                    # sepcial handling for bad syntax within case ... esac
                    if(len(case_stack) > 0):
                        if(re.search('\A[^(]*\)', test_record)):
                            # avoid overcount
                            outc -= 2
                            case_stack[-1] += 1
                        if(re.search(';;', test_record)):
                            outc += 1
                            case_stack[-1] -= 1
                    # an ad-hoc solution for the "else" keyword
                    else_case = (0, -1)[re.search('^(else)', test_record) != None]
                    net = inc - outc
                    tab += min(net, 0)
                    extab = tab + else_case
                    extab = max(0, extab)
                    output.append((self.tab_str * self.tab_size * extab) + stripped_record)
                    tab += max(net, 0)
                if(defer_ext_quote):
                    in_ext_quote = True
                    defer_ext_quote = False
                if(re.search(r'\bcase\b', test_record)):
                    case_stack.append(0)
            line += 1
        error = (tab != 0)
        if(error):
            sys.stderr.write('File %s: error: indent/outdent mismatch: %d.\n' % (path, tab))
        return '\n'.join(output), error

    def beautify_file(self, path):
        error = False
        if(path == '-'):
            data = sys.stdin.read()
            result, error = self.beautify_string(data, '(stdin)')
            sys.stdout.write(result)
        else:  # named file
            data = self.read_file(path)
            result, error = self.beautify_string(data, path)
            if(data != result):
                # make a backup copy
                self.write_file(path + '~', data)
                self.write_file(path, result)
        return error

    def main(self):
        error = False
        sys.argv.pop(0)
        if(len(sys.argv) < 1):
            sys.stderr.write('usage: shell script filenames or \"-\" for stdin.\n')
        else:
            for path in sys.argv:
                error |= self.beautify_file(path)
        sys.exit((0, 1)[error])

# if not called as a module
if(__name__ == '__main__'):
    BeautifyBash().main()
<commit_msg>format py script<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ************************************************************************
#   Copyright (C) 2011, Paul Lutus
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the
#   Free Software Foundation, Inc.,
#   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# ************************************************************************

import re
import sys

PVERSION = '1.0'

class BeautifyBash:

    def __init__(self):
        self.tab_str = ' '
        self.tab_size = 2

    def read_file(self, fp):
        with open(fp) as f:
            return f.read()

    def write_file(self, fp, data):
        with open(fp, 'w') as f:
            f.write(data)

    def beautify_string(self, data, path=''):
        tab = 0
        case_stack = []
        in_here_doc = False
        defer_ext_quote = False
        in_ext_quote = False
        ext_quote_string = ''
        here_string = ''
        output = []
        line = 1
        for record in re.split('\n', data):
            record = record.rstrip()
            stripped_record = record.strip()

            # collapse multiple quotes between ' ... '
            test_record = re.sub(r'\'.*?\'', '', stripped_record)
            # collapse multiple quotes between " ... "
            test_record = re.sub(r'".*?"', '', test_record)
            # collapse multiple quotes between ` ... `
            test_record = re.sub(r'`.*?`', '', test_record)
            # collapse multiple quotes between \` ... ' (weird case)
            test_record = re.sub(r'\\`.*?\'', '', test_record)
            # strip out any escaped single characters
            test_record = re.sub(r'\\.', '', test_record)
            # remove '#' comments
            test_record = re.sub(r'(\A|\s)(#.*)', '', test_record, 1)
            if(not in_here_doc):
                if(re.search('<<-?', test_record)):
                    here_string = re.sub(
                        '.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', '\\1', stripped_record, 1)
                    in_here_doc = (len(here_string) > 0)
            if(in_here_doc):  # pass on with no changes
                output.append(record)
                # now test for here-doc termination string
                if(re.search(here_string, test_record) and not re.search('<<', test_record)):
                    in_here_doc = False
            else:  # not in here doc
                if(in_ext_quote):
                    if(re.search(ext_quote_string, test_record)):
                        # provide line after quotes
                        test_record = re.sub(
                            '.*%s(.*)' % ext_quote_string, '\\1', test_record, 1)
                        in_ext_quote = False
                else:  # not in ext quote
                    if(re.search(r'(\A|\s)(\'|")', test_record)):
                        # apply only after this line has been processed
                        defer_ext_quote = True
                        ext_quote_string = re.sub(
                            '.*([\'"]).*', '\\1', test_record, 1)
                        # provide line before quote
                        test_record = re.sub(
                            '(.*)%s.*' % ext_quote_string, '\\1', test_record, 1)
                if(in_ext_quote):
                    # pass on unchanged
                    output.append(record)
                else:  # not in ext quote
                    inc = len(re.findall(
                        '(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
                    inc += len(re.findall('(\{|\(|\[)', test_record))
                    outc = len(re.findall(
                        '(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)', test_record))
                    outc += len(re.findall('(\}|\)|\])', test_record))
                    if(re.search(r'\besac\b', test_record)):
                        if(len(case_stack) == 0):
                            sys.stderr.write(
                                'File %s: error: "esac" before "case" in line %d.\n' % (
                                    path, line)
                            )
                        else:
                            outc += case_stack.pop()
                    # sepcial handling for bad syntax within case ... esac
                    if(len(case_stack) > 0):
                        if(re.search('\A[^(]*\)', test_record)):
                            # avoid overcount
                            outc -= 2
                            case_stack[-1] += 1
                        if(re.search(';;', test_record)):
                            outc += 1
                            case_stack[-1] -= 1
                    # an ad-hoc solution for the "else" keyword
                    else_case = (
                        0, -1)[re.search('^(else)', test_record) != None]
                    net = inc - outc
                    tab += min(net, 0)
                    extab = tab + else_case
                    extab = max(0, extab)
                    output.append(
                        (self.tab_str * self.tab_size * extab) + stripped_record)
                    tab += max(net, 0)
                if(defer_ext_quote):
                    in_ext_quote = True
                    defer_ext_quote = False
                if(re.search(r'\bcase\b', test_record)):
                    case_stack.append(0)
            line += 1
        error = (tab != 0)
        if(error):
            sys.stderr.write(
                'File %s: error: indent/outdent mismatch: %d.\n' % (path, tab))
        return '\n'.join(output), error

    def beautify_file(self, path):
        error = False
        if(path == '-'):
            data = sys.stdin.read()
            result, error = self.beautify_string(data, '(stdin)')
            sys.stdout.write(result)
        else:  # named file
            data = self.read_file(path)
            result, error = self.beautify_string(data, path)
            if(data != result):
                # make a backup copy
                self.write_file(path + '~', data)
                self.write_file(path, result)
        return error

    def main(self):
        error = False
        sys.argv.pop(0)
        if(len(sys.argv) < 1):
            sys.stderr.write(
                'usage: shell script filenames or \"-\" for stdin.\n')
        else:
            for path in sys.argv:
                error |= self.beautify_file(path)
        sys.exit((0, 1)[error])

# if not called as a module
if(__name__ == '__main__'):
    BeautifyBash().main()
<|endoftext|>


<commit_before># Copyright (c) 2008-2014 LG Electronics, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This implementation introduces next generation build environment for
# Open webOS. The change introduces a mechanism to add additional layers to the
# base ones: oe-core, meta-oe, and meta-webos, and to specify the commits to be
# used for each. mcf now expects the layers to be defined in this file
# (weboslayers.py in the same directory as mcf) as a list of Python data tuples:
#
# webos_layers = [
# ('layer-name', priority, 'URL', 'submission', 'working-dir'),
# ...
# ]
#
# where:
#
# layer-name  = Unique identifier; it represents the layer directory containing
#               conf/layer.conf.
#
# priority    = Integer layer priority as defined by OpenEmbedded. It also
#               specifies the order in which layers are searched for files.
#               Larger values have higher priority. A value of -1 indicates
#               that the entry is not a layer; for example, bitbake.
#
# URL         = The Git repository address for the layer from which to clone.
#               A value of '' skips the cloning.
#
# submission  = The information used by Git to checkout and identify the precise
#               content. Submission values could be "branch=<name>" and
#               "commit=<id>" or "tag=<tag>". Omitted branch information means
#               only that "master" will be used as the name of the local
#               branch. Omitted commit or tag means origin/HEAD will be checked
#               out (which might NOT be origin/master, although
#               it usually is).
#
# working-dir = Alternative directory for the layer.
#
# The name of the distribution is also defined in this file
# along with a list of the valid MACHINE-s
#

Distribution = "webos"

# Supported MACHINE-s
Machines = ['qemux86', 'qemuarm']

# github.com/openembedded repositories are read-only mirrors of the authoritative
# repositories on git.openembedded.org
webos_layers = [
('bitbake',               -1, 'git://github.com/openembedded/bitbake.git',              'branch=1.18,commit=0f7b6a0', ''),
('meta',                   5, 'git://github.com/openembedded/oe-core.git',              'branch=dylan,commit=bf2d538', ''),
('meta-oe',                6, 'git://github.com/openembedded/meta-oe.git',              'branch=dylan,commit=70ebe86', ''),
('meta-networking',        6, 'git://github.com/openembedded/meta-oe.git',              '', ''),

('meta-webos-backports',   9, 'git://github.com/openwebos/meta-webos-backports.git',    'commit=907a089', ''),
('meta-webos',            10, 'git://github.com/openwebos/meta-webos.git',              'commit=d6d34e2', ''),
]
<commit_msg>webos-image: Update layer pins for 2014-08-13<commit_after># Copyright (c) 2008-2014 LG Electronics, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This implementation introduces next generation build environment for
# Open webOS. The change introduces a mechanism to add additional layers to the
# base ones: oe-core, meta-oe, and meta-webos, and to specify the commits to be
# used for each. mcf now expects the layers to be defined in this file
# (weboslayers.py in the same directory as mcf) as a list of Python data tuples:
#
# webos_layers = [
# ('layer-name', priority, 'URL', 'submission', 'working-dir'),
# ...
# ]
#
# where:
#
# layer-name  = Unique identifier; it represents the layer directory containing
#               conf/layer.conf.
#
# priority    = Integer layer priority as defined by OpenEmbedded. It also
#               specifies the order in which layers are searched for files.
#               Larger values have higher priority. A value of -1 indicates
#               that the entry is not a layer; for example, bitbake.
#
# URL         = The Git repository address for the layer from which to clone.
#               A value of '' skips the cloning.
#
# submission  = The information used by Git to checkout and identify the precise
#               content. Submission values could be "branch=<name>" and
#               "commit=<id>" or "tag=<tag>". Omitted branch information means
#               only that "master" will be used as the name of the local
#               branch. Omitted commit or tag means origin/HEAD will be checked
#               out (which might NOT be origin/master, although
#               it usually is).
#
# working-dir = Alternative directory for the layer.
#
# The name of the distribution is also defined in this file
# along with a list of the valid MACHINE-s
#

Distribution = "webos"

# Supported MACHINE-s
Machines = ['qemux86', 'qemuarm']

# github.com/openembedded repositories are read-only mirrors of the authoritative
# repositories on git.openembedded.org
webos_layers = [
('bitbake',               -1, 'git://github.com/openembedded/bitbake.git',              'branch=1.18,commit=0f7b6a0', ''),
('meta',                   5, 'git://github.com/openembedded/oe-core.git',              'branch=dylan,commit=bf2d538', ''),
('meta-oe',                6, 'git://github.com/openembedded/meta-oe.git',              'branch=dylan,commit=70ebe86', ''),
('meta-networking',        6, 'git://github.com/openembedded/meta-oe.git',              '', ''),

('meta-webos-backports',   9, 'git://github.com/openwebos/meta-webos-backports.git',    'commit=907a089', ''),
('meta-webos',            10, 'git://github.com/openwebos/meta-webos.git',              'commit=f4c36e8', ''),
]
<|endoftext|>


<commit_before># encoding: utf-8
"""Module contains some specialiced versions of some functions from mparray.
They are tuned for speed with special applications in mind
"""
from __future__ import absolute_import, division, print_function

from math import ceil

import numpy as np

from . import mparray as mp

def inner_prod_mps(mpa1, mpa2):
    """Same as :func:`mparray.inner`, but assumes that `mpa1` is a product MPS

    :param mpa1: MPArray with one physical leg per site and bond dimension 1
    :param mpa2: MPArray with same physical shape as mpa1
    :returns: <mpa1|mpa2>

    """
    assert all(bdim == 1 for bdim in mpa1.bdims)
    assert all(pleg == 1 for pleg in mpa1.plegs)
    assert all(pleg == 1 for pleg in mpa2.plegs)

    # asssume mpa1 is product
    ltens1 = iter(mpa1.lt)
    ltens2 = iter(mpa2.lt)

    res = np.dot(next(ltens1)[0, :, 0].conj(), next(ltens2))
    for l1, l2 in zip(ltens1, ltens2):
        res = np.dot(res, np.dot(l1[0, :, 0].conj(), l2))
    return res[0, 0]

def sumup(mpas, weights=None, target_bdim=None, max_bdim=None,
          compargs={'method': 'svd'}):
    """Same as :func:`mparray.sumup`, but with extended weighting & compression
    options. Supports intermediate compression.

    Make sure that max_bdim >> target_bdim. Also, this function really flies
    only with python optimizations enabled.

    :param mpas: Iterator over MPArrays
    :param weights: Iterator of same length as mpas containing weights for
        computing weighted sum.
    :param target_bdim: Bond dimension the result should have (default: `None`)
    :param max_bdim: Maximum bond dimension the intermediate steps may assume
        (default: `None`)
    :param compargs: Arguments for compression function
        (default: `{'method': 'svd'}`)
    :returns: Sum of `mpas` with max. bond dimension `target_bdim`

    """
    mpas = list(mpas)
    length = len(mpas[0])
    weights = weights if weights is not None else np.ones(len(mpas))

    assert all(len(mpa) == length for mpa in mpas)
    assert len(weights) == len(mpas)
    assert 'bdim' not in compargs

    if length == 1:
        # The code below assumes at least two sites.
        return mp.MPArray((sum(w * mpa.lt[0] for w, mpa in zip(weights, mpas)),))

    assert all(mpa.bdim == 1 for mpa in mpas)
    return _sum_n_compress(mpas, weights, 1, target_bdim, max_bdim, compargs)

def _sum_n_compress(mpas, weights, current_bdim, target_bdim, max_bdim, compargs):
    """Recursively sum and compress the MPArrays' in `mpas`. The end result
    will have bond dimension smaller than `target_bdim` and during the process,
    the intermediate results always have bond dimension smaller than
    `max_bdim`.

    :param mpas: List of MPArrays to sum
    :param weights: Optional weights to compute weighted sum. If `None` is
        passed, they are all assumed to be 1.
    :param current_bdim: The maximal bond dimension of any MPArray in `mpas`
    :param target_bdim: Bond dimension the end result should have at most.
    :param max_bdim: Max bond dimension any intermediate result should have
    :param compargs: Compression args to be used.

    """
    length = len(mpas[0])
    # no subpartition ne
    if (max_bdim is None) or (len(mpas) * current_bdim <= max_bdim):
        ltensiter = [iter(mpa.lt) for mpa in mpas]
        if weights is None:
            ltens = [np.concatenate([next(lt) for lt in ltensiter], axis=-1)]
        else:
            ltens = [np.concatenate([w * next(lt) for w, lt in zip(weights, ltensiter)], axis=-1)]
        ltens += [mp._local_add([next(lt) for lt in ltensiter])
                for _ in range(length - 2)]
        ltens += [np.concatenate([next(lt) for lt in ltensiter], axis=0)]

        summed = mp.MPArray(ltens)
        summed.compress(bdim=target_bdim, **compargs)
        return summed

    else:
        nodes = max(max_bdim // target_bdim, 1)
        stride = ceil(len(mpas) / nodes)
        partition = [slice(n * stride, (n + 1) * stride) for n in range(nodes)
                     if n * stride < len(mpas)]
        mpas = [_sum_n_compress(mpas[sel], weights[sel], 1, target_bdim,
                                max_bdim, compargs)
                for sel in partition]
        return _sum_n_compress(mpas, None, target_bdim, target_bdim, max_bdim,
                               compargs)
<commit_msg>Fix Python 2<commit_after># encoding: utf-8
"""Module contains some specialiced versions of some functions from mparray.
They are tuned for speed with special applications in mind
"""
from __future__ import absolute_import, division, print_function

from math import ceil

import numpy as np

from . import mparray as mp

def inner_prod_mps(mpa1, mpa2):
    """Same as :func:`mparray.inner`, but assumes that `mpa1` is a product MPS

    :param mpa1: MPArray with one physical leg per site and bond dimension 1
    :param mpa2: MPArray with same physical shape as mpa1
    :returns: <mpa1|mpa2>

    """
    assert all(bdim == 1 for bdim in mpa1.bdims)
    assert all(pleg == 1 for pleg in mpa1.plegs)
    assert all(pleg == 1 for pleg in mpa2.plegs)

    # asssume mpa1 is product
    ltens1 = iter(mpa1.lt)
    ltens2 = iter(mpa2.lt)

    res = np.dot(next(ltens1)[0, :, 0].conj(), next(ltens2))
    for l1, l2 in zip(ltens1, ltens2):
        res = np.dot(res, np.dot(l1[0, :, 0].conj(), l2))
    return res[0, 0]

def sumup(mpas, weights=None, target_bdim=None, max_bdim=None,
          compargs={'method': 'svd'}):
    """Same as :func:`mparray.sumup`, but with extended weighting & compression
    options. Supports intermediate compression.

    Make sure that max_bdim >> target_bdim. Also, this function really flies
    only with python optimizations enabled.

    :param mpas: Iterator over MPArrays
    :param weights: Iterator of same length as mpas containing weights for
        computing weighted sum.
    :param target_bdim: Bond dimension the result should have (default: `None`)
    :param max_bdim: Maximum bond dimension the intermediate steps may assume
        (default: `None`)
    :param compargs: Arguments for compression function
        (default: `{'method': 'svd'}`)
    :returns: Sum of `mpas` with max. bond dimension `target_bdim`

    """
    mpas = list(mpas)
    length = len(mpas[0])
    weights = weights if weights is not None else np.ones(len(mpas))

    assert all(len(mpa) == length for mpa in mpas)
    assert len(weights) == len(mpas)
    assert 'bdim' not in compargs

    if length == 1:
        # The code below assumes at least two sites.
        return mp.MPArray((sum(w * mpa.lt[0] for w, mpa in zip(weights, mpas)),))

    assert all(mpa.bdim == 1 for mpa in mpas)
    return _sum_n_compress(mpas, weights, 1, target_bdim, max_bdim, compargs)

def _sum_n_compress(mpas, weights, current_bdim, target_bdim, max_bdim, compargs):
    """Recursively sum and compress the MPArrays' in `mpas`. The end result
    will have bond dimension smaller than `target_bdim` and during the process,
    the intermediate results always have bond dimension smaller than
    `max_bdim`.

    :param mpas: List of MPArrays to sum
    :param weights: Optional weights to compute weighted sum. If `None` is
        passed, they are all assumed to be 1.
    :param current_bdim: The maximal bond dimension of any MPArray in `mpas`
    :param target_bdim: Bond dimension the end result should have at most.
    :param max_bdim: Max bond dimension any intermediate result should have
    :param compargs: Compression args to be used.

    """
    length = len(mpas[0])
    # no subpartition ne
    if (max_bdim is None) or (len(mpas) * current_bdim <= max_bdim):
        ltensiter = [iter(mpa.lt) for mpa in mpas]
        if weights is None:
            ltens = [np.concatenate([next(lt) for lt in ltensiter], axis=-1)]
        else:
            ltens = [np.concatenate([w * next(lt) for w, lt in zip(weights, ltensiter)], axis=-1)]
        ltens += [mp._local_add([next(lt) for lt in ltensiter])
                for _ in range(length - 2)]
        ltens += [np.concatenate([next(lt) for lt in ltensiter], axis=0)]

        summed = mp.MPArray(ltens)
        summed.compress(bdim=target_bdim, **compargs)
        return summed

    else:
        nodes = max(max_bdim // target_bdim, 1)
        stride = int(ceil(len(mpas) / nodes))
        partition = [slice(n * stride, (n + 1) * stride) for n in range(nodes)
                     if n * stride < len(mpas)]
        mpas = [_sum_n_compress(mpas[sel], weights[sel], 1, target_bdim,
                                max_bdim, compargs)
                for sel in partition]
        return _sum_n_compress(mpas, None, target_bdim, target_bdim, max_bdim,
                               compargs)
<|endoftext|>