コード例 #1
0
    def __init__(cls, *args, **kwargs):
        if cls.__dataclass__['eq'] and cls.__dataclass__['order']:
            from functools import total_ordering
            total_ordering(cls)

        # determine a static expression for an instance's fields as a tuple, then evaluate this to create a property
        # allowing efficient representation for internal methods
        tuple_expr = ', '.join((*(f'self.{f}' for f in fields(cls)), ''))  # '' ensures closing comma
        cls.__tuple__ = property(eval(f'lambda self: ({tuple_expr})'))
コード例 #2
0
ファイル: __init__.py プロジェクト: jlubcke/tri.declarative
def creation_ordered(class_to_decorate):
    """
        Class decorator that ensures that instances will be ordered after creation order when sorted.

        @type class_to_decorate: class
        @return class
    """

    next_index = functools.partial(next, itertools.count())

    __init__orig = class_to_decorate.__init__

    def __init__(self, *args, **kwargs):
        object.__setattr__(self, '_index', next_index())
        __init__orig(self, *args, **kwargs)

    setattr(class_to_decorate, '__init__', __init__)

    # noinspection PyProtectedMember
    def __lt__(self, other):
        return self._index < other._index

    setattr(class_to_decorate, '__lt__', __lt__)

    class_to_decorate = total_ordering(class_to_decorate)

    return class_to_decorate
コード例 #3
0
ファイル: __init__.py プロジェクト: jayvdb/tri.declarative
def creation_ordered(class_to_decorate):
    """
        Class decorator that ensures that instances will be ordered after creation order when sorted.

        :type class_to_decorate: class
        :rtype: class
    """

    next_index = functools.partial(next, itertools.count())

    __init__orig = class_to_decorate.__init__

    @functools.wraps(__init__orig, assigned=['__doc__'])
    def __init__(self, *args, **kwargs):
        object.__setattr__(self, '_index', next_index())
        __init__orig(self, *args, **kwargs)

    setattr(class_to_decorate, '__init__', __init__)

    # noinspection PyProtectedMember
    def __lt__(self, other):
        return self._index < other._index  # pragma: no mutate

    setattr(class_to_decorate, '__lt__', __lt__)

    class_to_decorate = functools.total_ordering(class_to_decorate)

    return class_to_decorate
コード例 #4
0
    def __new__(cls, *args, **kwargs):
        generated_cls = type.__new__(cls, *args, **kwargs)

        def _init(self, value):
            value_type = getattr(generated_cls, 'value_type', None)
            if value_type is None or isinstance(value, value_type):
                self.value = value
            else:
                raise RuntimeError("MethodsInjector: wrong init type.")

        def _repr(self):
            return repr(self.value)

        def _eq(self, other):
            return type(self) == type(other) and self.value == other.value

        def _gt(self, other):
            return self.value > other.value

        def _hash(self):
            return hash(self.value)

        def inject_method(generated_cls, text, func):
            if text not in generated_cls.__dict__:
                setattr(generated_cls, text, func)

        inject_method(generated_cls, '__init__', _init)
        inject_method(generated_cls, '__repr__', _repr)
        inject_method(generated_cls, '__eq__', _eq)
        inject_method(generated_cls, '__gt__', _gt)
        inject_method(generated_cls, '__hash__', _hash)

        return functools.total_ordering(generated_cls)
コード例 #5
0
ファイル: utils.py プロジェクト: fraca7/ptk
 def __new__(metacls, name, bases, attrs):
     # pylint: disable=C0103
     cls = type.__new__(metacls, name, bases, attrs)
     cls.__eq__ = lambda self, other: other is self
     cls.__lt__ = lambda self, other: not other is self
     cls.__copy__ = lambda self: self
     cls.__deepcopy__ = lambda self, memo: self
     cls.__repr__ = lambda self: self.__reprval__
     cls.__len__ = lambda self: len(self.__reprval__)
     cls.__hash__ = lambda self: hash(id(self))
     return functools.total_ordering(cls)()
コード例 #6
0
ファイル: Utils.py プロジェクト: zjunweihit/Tensile
def state_key_ordering(cls):
    def tup(obj):
        return tuple([getattr(obj, k) for k in cls.StateKeys])

    def lt(a, b):
        return tup(a) < tup(b)
    def eq(a, b):
        return tup(a) == tup(b)

    cls.__lt__ = lt
    cls.__eq__ = eq

    return functools.total_ordering(cls)
コード例 #7
0
    def decorate(cls):
        def eq(self, other):
            return all(getattr(self, a) == getattr(other, a) for a in attrs)

        def lt(self, other):

            for a in attrs:
                ours = getattr(self, a)
                theirs = getattr(other, a)
                if ours < theirs: return True
                elif theirs > ours: return False

            return False

        setattr(cls, '__lt__', lt)
        setattr(cls, '__eq__', eq)

        return total_ordering(cls)
コード例 #8
0
    def decorator(cls):
        def lt(self, other):
            if not isinstance(other, cls):
                raise TypeError("Comparison with unrelated classes is "
                                "unsupported.")

            for member in members:
                if getattr(self, member) == getattr(other, member):
                    continue

                if (getattr(self, member) is None
                        or getattr(other, member) is None):
                    return getattr(self, member) is None

                return getattr(self, member) < getattr(other, member)

            return False

        cls.__lt__ = lt
        return total_ordering(generate_eq(*members)(cls))
コード例 #9
0
ファイル: Decorators.py プロジェクト: BigDproject/coala
    def decorator(cls):
        def lt(self, other):
            if not isinstance(other, cls):
                raise TypeError("Comparison with unrelated classes is "
                                "unsupported.")

            for member in members:
                if getattr(self, member) == getattr(other, member):
                    continue

                if (
                        getattr(self, member) is None or
                        getattr(other, member) is None):
                    return getattr(self, member) is None

                return getattr(self, member) < getattr(other, member)

            return False

        cls.__lt__ = lt
        return total_ordering(generate_eq(*members)(cls))
コード例 #10
0
ファイル: int_mod.py プロジェクト: squarooticus/alta
def IntMod(mod):
    def __init__(self, value):
        self._value = int(value % mod)

    def __add__(self, other):
        self._typecheck(other)
        return type(self)(self._value + int(other))

    def __sub__(self, other):
        self._typecheck(other)
        return type(self)(self._value - int(other))

    def __lt__(self, other):
        self._typecheck(other)
        if (self.__int__() - int(other)) % mod >= 3 * mod / 4:
            return True
        elif (self.__int__() - int(other)) % mod <= mod / 4:
            return False
        else:
            raise OverflowError()

    def __eq__(self, other):
        self._typecheck(other)
        return self.__int__() == (int(other) % mod)

    def __int__(self):
        return self._value % mod

    def __getattr__(self, name):
        return getattr(self._value, name)

    def __str__(self):
        return (self._value % mod).__str__()

    def _typecheck(self, other):
        if not isinstance(other, int) and not isinstance(other, type(self)):
            raise TypeError()

    return total_ordering(type('IntMod%d' % mod, (), dict( __init__=__init__, __add__=__add__, __sub__=__sub__, __lt__=__lt__, __eq__=__eq__, __int__=__int__, __getattr__=__getattr__, __str__=__str__, _typecheck=_typecheck)))
コード例 #11
0
            def addClassFunctions(cls) -> None:
                def __init__(self):
                    raise TypeError(_ErrorMsg.IllegalOperation)

                def __str__(self):
                    return self.Name

                def __int__(self):
                    return self.Value

                def __eq__(self, other):
                    if not builtins.isinstance(other, self.__class__):
                        return NotImplemented
                    return self.Value == other.Value

                def __hash__(self):
                    return builtins.hash(self.Value)

                def __lt__(self, other):
                    if not builtins.isinstance(other, self.__class__):
                        return NotImplemented
                    return self.Value < other.Value

                def __setattr__(self, name, value):
                    raise TypeError(_ErrorMsg.IllegalOperation)

                def __delattr__(self, name):
                    raise TypeError(_ErrorMsg.IllegalOperation)

                cls.__init__ = __init__
                cls.__str__ = __str__
                cls.__int__ = __int__
                cls.__eq__ = __eq__
                cls.__hash__ = __hash__
                cls.__lt__ = __lt__
                cls.__setattr__ = __setattr__
                cls.__delattr__ = __delattr__

                cls = functools.total_ordering(cls)
コード例 #12
0
ファイル: _cmp.py プロジェクト: Jane-Panaiotova/OOP
def cmp_using(
    eq=None,
    lt=None,
    le=None,
    gt=None,
    ge=None,
    require_same_type=True,
    class_name="Comparable",
):
    """
    Create a class that can be passed into `attr.ib`'s ``eq``, ``order``, and
    ``cmp`` arguments to customize field comparison.

    The resulting class will have a full set of ordering methods if
    at least one of ``{lt, le, gt, ge}`` and ``eq``  are provided.

    :param Optional[callable] eq: `callable` used to evaluate equality
        of two objects.
    :param Optional[callable] lt: `callable` used to evaluate whether
        one object is less than another object.
    :param Optional[callable] le: `callable` used to evaluate whether
        one object is less than or equal to another object.
    :param Optional[callable] gt: `callable` used to evaluate whether
        one object is greater than another object.
    :param Optional[callable] ge: `callable` used to evaluate whether
        one object is greater than or equal to another object.

    :param bool require_same_type: When `True`, equality and ordering methods
        will return `NotImplemented` if objects are not of the same type.

    :param Optional[str] class_name: Name of class. Defaults to 'Comparable'.

    See `comparison` for more details.

    .. versionadded:: 21.1.0
    """

    body = {
        "__slots__": ["value"],
        "__init__": _make_init(),
        "_requirements": [],
        "_is_comparable_to": _is_comparable_to,
    }

    # Add operations.
    num_order_functions = 0
    has_eq_function = False

    if eq is not None:
        has_eq_function = True
        body["__eq__"] = _make_operator("eq", eq)
        body["__ne__"] = _make_ne()

    if lt is not None:
        num_order_functions += 1
        body["__lt__"] = _make_operator("lt", lt)

    if le is not None:
        num_order_functions += 1
        body["__le__"] = _make_operator("le", le)

    if gt is not None:
        num_order_functions += 1
        body["__gt__"] = _make_operator("gt", gt)

    if ge is not None:
        num_order_functions += 1
        body["__ge__"] = _make_operator("ge", ge)

    type_ = new_class(class_name, (object, ), {}, lambda ns: ns.update(body))

    # Add same type requirement.
    if require_same_type:
        type_._requirements.append(_check_same_type)

    # Add total ordering if at least one operation was defined.
    if 0 < num_order_functions < 4:
        if not has_eq_function:
            # functools.total_ordering requires __eq__ to be defined,
            # so raise early error here to keep a nice stack.
            raise ValueError(
                "eq must be define is order to complete ordering from "
                "lt, le, gt, ge.")
        type_ = functools.total_ordering(type_)

    return type_
コード例 #13
0
ファイル: model.py プロジェクト: michel-slm/0install
	last_checked = property(lambda self: None)
	implementations = property(lambda self: {})
	feeds = property(lambda self: [])
	summary = property(lambda self: '-')
	description = property(lambda self: '')
	def get_name(self): return self.name
	def get_feed(self, url): return None
	def get_metadata(self, uri, name): return []
_dummy_feed = DummyFeed()

if sys.version_info[0] > 2:
	# Python 3

	from functools import total_ordering
	# (note: delete these two lines when generating epydoc)
	Stability = total_ordering(Stability)
	Implementation = total_ordering(Implementation)

	# These could be replaced by urllib.parse.quote, except that
	# it uses upper-case escapes and we use lower-case ones...
	def unescape(uri):
		"""Convert each %20 to a space, etc.
		@rtype: str"""
		uri = uri.replace('#', '/')
		if '%' not in uri: return uri
		return re.sub(b'%[0-9a-fA-F][0-9a-fA-F]',
			lambda match: bytes([int(match.group(0)[1:], 16)]),
			uri.encode('ascii')).decode('utf-8')

	def escape(uri):
		"""Convert each space to %20, etc
コード例 #14
0
ファイル: functools模块.py プロジェクト: Fover21/notebook

 functools.reduce
 functools.reduce(function, iterable[, initializer])


 functools.cmp_to_key
 functools.cmp_to_key(func)

 将老式鼻尖函数转换成key函数,用在接受key函数的方法中(such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby())
 一个比较函数,接收两个参数,小于,返回负数,等于,返回0,大于返回整数
 key函数,接收一个参数,返回一个表明该参数在期望序列中的位置


 functools.total_ordering
 functools.total_ordering(cls)
 from functools import total_ordering


 @total_ordering
 class Student:
     def __eq__(self, other):
         return ((self.lastname.lower(), self.firstname.lower()) ==
                 (other.lastname.lower(), other.firstname.lower()))

     def __lt__(self, other):
         return ((self.lastname.lower(), self.firstname.lower()) <
                 (other.lastname.lower(), other.firstname.lower()))


 print(dir(Student))
コード例 #15
0
ファイル: dncp_tlv.py プロジェクト: fingon/pysyma
    def decode(cls, x, *a, **kwa):
        o = cls()
        o.decode_buffer(x, *a, **kwa)
        return o
    def encode(self):
        raise NotImplementedError
    def decode_buffer(self, x):
        raise NotImplementedError
    def __eq__(self, o):
        return type(self) == type(o) and self.encode() == o.encode()
    def __lt__(self, o):
        return self.encode() < o.encode()
    def __hash__(self):
        return 0

functools.total_ordering(Blob)

try:
    buffer('foo')
except:
    def buffer(x): return x

class CStruct(Blob):
    format = None # subclass responsibility
    keys = [] # subclass responsibility
    arkeys = None # additional repr-keys
    def __init__(self, **kw):
        Blob.__init__(self, **kw)
    def __hash__(self):
        h = 0
        for key in self.keys:
コード例 #16
0
CLUBS = Suit(id='♣', color='black')
SPADES = Suit(id='♠', color='black')
SUITS = (HEARTS, DIAMONDS, CLUBS, SPADES)
NAME_BY_SUIT = {HEARTS: 'HEARTS', DIAMONDS: 'DIAMONDS', CLUBS: 'CLUBS', SPADES: 'SPADES'}

Rank = namedtuple('Rank', 'id')
RANKIDS_ACE_HI = list(range(2, 11)) + ['J', 'Q', 'K', 'A'] # [2, 3, ..., 10, 'J', 'Q', 'K', 'A']
RANKIDS_ACE_LO = [RANKIDS_ACE_HI[-1]] + RANKIDS_ACE_HI[:-1] # ['A', 2, 3, ..., 10, 'J', 'Q', 'K']
INDEX_BY_RANKID_ACE_HI = dict(zip(RANKIDS_ACE_HI, range(2, 15))) # {2: 2, 3: 3, ..., J: 11, Q: 12, K: 13, A: 14}
INDEX_BY_RANKID_ACE_LO = dict(INDEX_BY_RANKID_ACE_HI, A=1) # {A: 1, 2: 2, 3: 3, ..., J: 11, Q: 12, K: 13}
# rank comparison functions, for determining whether e.g. Rank(id='A') < Rank(id='K')
Rank.__eq__ = lambda self, other: self.id == other.id
rank_lt_ace_hi = lambda self, other: INDEX_BY_RANKID_ACE_HI[self.id] < INDEX_BY_RANKID_ACE_HI[other.id]
rank_lt_ace_lo = lambda self, other: INDEX_BY_RANKID_ACE_LO[self.id] < INDEX_BY_RANKID_ACE_LO[other.id]
Rank.__lt__ = rank_lt_ace_hi # choose ace hi by default, easily swapped out though
Rank = total_ordering(Rank)
RANKS = tuple(Rank(id=i) for i in RANKIDS_ACE_HI)
NAME_BY_RANKID = dict(zip(RANKIDS_ACE_HI, ('TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'JACK', 'QUEEN', 'KING', 'ACE')))
# export names for each rank to this module's namespace, so e.g. "TWO" refers to the Rank(id=2) object
locals().update({NAME_BY_RANKID[rank.id]: rank for rank in RANKS})

Card = namedtuple('Card', 'rank suit')
# print cards out like 3♡ instead of Card(Rank(id=3), suit=Suit(id='♡'...
Card.__str__ = lambda self: str(self.rank.id) + str(self.suit.id)
Card.__repr__ = Card.__str__
# give Cards a default ordering, expecting overriding as desired
Card.__eq__ = lambda self, other: self.rank == other.rank and self.suit == other.suit
Card.__lt__ = lambda self, other: self.rank < other.rank if self.suit == other.suit else SUITS.index(self.suit) < SUITS.index(other.suit)
Card = total_ordering(Card)
CARDS = tuple(Card(rank=rank, suit=suit) for suit in SUITS for rank in RANKS)
# export names for each card to this module's namespace, so you can refer to the two of hearts with "TWO_HEARTS"
コード例 #17
0
ファイル: managers.py プロジェクト: huyx/django-taggit
        extra_col = self.through._meta.get_field('content_type').column
        content_type_ids = [
            ContentType.objects.get_for_model(subclass).pk
            for subclass in _get_subclasses(self.model)
        ]
        return ExtraJoinRestriction(related_alias, extra_col, content_type_ids)

    def get_reverse_joining_columns(self):
        return self.get_joining_columns(reverse_join=True)

    @property
    def related_fields(self):
        return [(self.through._meta.get_field('object_id'),
                 self.model._meta.pk)]

    @property
    def foreign_related_fields(self):
        return [self.related_fields[0][1]]


def _get_subclasses(model):
    subclasses = [model]
    for field in model._meta.get_fields():
        if isinstance(field, OneToOneRel) and getattr(
                _remote_field(field.field), "parent_link", None):
            subclasses.extend(_get_subclasses(field.related_model))
    return subclasses


TaggableManager = total_ordering(TaggableManager)
コード例 #18
0
ファイル: slightly.py プロジェクト: afeller08/hackkit
def inferred(name, bases, dict, type=type):
    if '__add__' in dict and not '__radd__' in dict:
        def __radd__(self, other):
            return self + other
        dict['__radd__'] = __radd__
    if '__mul__' in dict and not '__rmul__' in dict:
        def __rmul__(self, other):
            return self * other
        dict['__rmul__'] = __rmul__
    if '__and__' in dict and not '__rand__' in dict:
        def __rand__(self, other):
            return self & other
        dict['__rand__'] = __rmul__
    if '__or__' in dict and not '__ror__' in dict:
        def __ror__(self, other):
            return self | other
        dict['__ror__'] = __ror__
    if '__xor__' in dict and not '__rxor__' in dict:
        def __rxor__(self, other):
            return self ^ other
        dict['__rxor__'] = __rxor__
    if '__mul__' in dict and not '__neg__' in dict:
        def __neg__(self):
            return self * -1
        dict['__neg__'] = __neg__
    if '__add__' in dict and '__neg__' in dict and not '__sub__' in dict:
        def __sub__(self, other):
            try:
                return self + -other
            except:
                return -(-self + other)
        dict['__sub__'] = __sub__
    if '__add__' in dict and '__neg__' in dict and not '__rsub__' in dict:
        def __rsub__(self, other):
            return -self + other
        dict['__rsub__'] = __rsub__
    if '__pow__' in dict and not '__rdiv__' in dict:
        def __rdiv__(self, other):
            return other * self ** -1
        dict['__rdiv__'] = __rdiv__
    if '__rdiv__' in dict and not '__div__' in dict:
        def __div__(self, other):
            return 1 / (other/self)
        dict['__div__'] = __div__
    if '__div__' in dict and not '__truediv__' in dict:
        dict['__truediv__'] = dict['__div__']
    if '__rdiv__' in dict and not '__rtruediv__' in dict:
        dict['___rtruediv__'] = dict['_rdiv__']
    if '__truediv__' in dict and not '__div__' in dict:
        dict['__div__'] = dict['__truediv__']
    if '__rtruediv__' in dict and not '__rdiv__' in dict:
        dict['__rdiv__'] = dict['__rtruediv__']
    if '__floordiv__' in dict and '__sub__' in dict and not '__mod__' in dict:
        def __mod__(self, other):
            return self - ((self // other) * other)
        dict['__mod__'] = __mod__
    if '__setslice__' in dict and not '__setitem__' in dict:
        def __setitem__(self, i, v):
            self[i:i] = [v]
        dict['__setitem__'] = __setitem__
    if '__getslice__' in dict and not '__getitem__' in dict:
        def __getitem__(self, i):
            return self[i:i][0]
        dict['__getitem__'] = __getitem__
    if '__delslice__' in dict and not '__delitem__' in dict:
        def __delitem__(self, i):
            del self[i:i]
        dict['__delitem__'] = __delitem__
    if '__rshift__' in dict and not '__lshift__' in dict:
        def __lshift__(self, other):
            return self >> -other
        dict['__lshift__'] = __lshift__
    if '__lshift__' in dict and not '__rshift__' in dict:
        def __rshift__(self, other):
            return self << -other
        dict['__rshift__'] = __rshift__
    eqops = set(ops.full(ops.comparison))
    if '__eq__' in dict and len(set(dict.keys()).intersection(eqops)) > 1:
        return functools.total_ordering(type(name, bases, dict))
    else:
        return type(name, bases, dict)
コード例 #19
0
    def __new__(cls, name, bases, attrs):
        super_new = super().__new__
        parents = [b for b in bases if isinstance(b, ModelBuilder)]
        if not parents:
            return super_new(cls, name, bases, attrs)

        #不存在多个model继承
        if len(parents) > 1:
            raise BuildingModelError(
                "[%s] are Model, Model can't extend Model, user minix style to resove it"
                % ",".join([p.__name__ for p in parents]))

        # new_class
        _meta_dict = {}
        _meta = attrs.pop("Meta", None)
        if _meta:
            for key, value in yield_options_from_meta(_meta):
                _meta_dict[key] = value

        if "default_table_name" not in _meta_dict:
            _meta_dict["default_table_name"] = name.lower()

        super_fields = {}
        for base in bases[::-1]:
            for (attr_name, attr) in yield_fields_from_cls(base):
                new_attr = copy.deepcopy(attr)
                super_fields[attr_name] = new_attr

        local_fields = {}
        _meta_dict.update(super_fields=super_fields.values())
        other_model_relateds = []

        for key in list(attrs.keys()):
            if key == "_meta":
                raise BuildingModelError(
                    "`_meta` is keyword, use other instead ")
            if isinstance(attrs[key], Field):
                if "__" in key:
                    raise FieldNammingError("%s:%s" % (name, key))
                elif key.lower() == "pk":
                    raise FieldNammingError("%s:%s" % (name, key))
                local_fields[key] = attrs.pop(key)
            elif isinstance(attrs[key], ModelRelatedEntity):
                other_model_relateds.append((key, attrs[key]))
                attrs.pop(key)

        super_fields.update(local_fields)
        if len(super_fields) == 0:
            raise BuildingModelError(
                "Model was not allowed that has no field. nameed %s" % name)
        _meta_dict.update(fields=super_fields.values())

        options = Options(**_meta_dict)
        if "__repr__" not in attrs:
            attrs["__repr__"] = make_model_repr()
        if "__str__" not in attrs:
            attrs["__str__"] = attrs["__repr__"]

        #cmp
        attrs["__eq__"] = make_model_eq()
        attrs["__lt__"] = make_model_lt()

        new_cls = super_new(cls, name, bases, attrs)
        new_cls = total_ordering(new_cls)
        new_cls.register(ModelBuilder.meta_mgr)

        new_cls.add_to_model("_meta", options)
        for name, field in super_fields.items():
            new_cls.add_to_model(name, field)

        #其他model related
        for name, item in other_model_relateds:
            new_cls.add_to_model(name, item)

        #判断是否有pk
        if not hasattr(new_cls, "pk"):
            raise BuildingModelError("Model %s was not allows has no pk ." %
                                     name)
        return new_cls
コード例 #20
0
ファイル: colors.py プロジェクト: pavgup/ubertool_cts
    def _lookupName(self,D={}):
        if not D:
            for n,v in getAllNamedColors().items():
                if not isinstance(v,CMYKColor):
                    t = v.red,v.green,v.blue
                    if t in D:
                        n = n+'/'+D[t]
                    D[t] = n
        t = self.red,self.green,self.blue
        return t in D and D[t] or None

    @property
    def normalizedAlpha(self):
        return self.alpha
if isPy3: Color = functools.total_ordering(Color)

class CMYKColor(Color):
    """This represents colors using the CMYK (cyan, magenta, yellow, black)
    model commonly used in professional printing.  This is implemented
    as a derived class so that renderers which only know about RGB "see it"
    as an RGB color through its 'red','green' and 'blue' attributes, according
    to an approximate function.

    The RGB approximation is worked out when the object in constructed, so
    the color attributes should not be changed afterwards.

    Extra attributes may be attached to the class to support specific ink models,
    and renderers may look for these."""

    _scale = 1.0
コード例 #21
0
        if self.revision:
            s += "-" + self.revision
        return s

    def __hash__(self):
        return hash(str(self))

    def __cmp__(self, other):
        if isinstance(other, DebianVersion):
            return cmp(self._comparable_parts, other._comparable_parts)
        else:
            return NotImplemented

    def __eq__(self, other):
        if isinstance(other, DebianVersion):
            return self._comparable_parts == other._comparable_parts
        else:
            return NotImplemented

    def __lt__(self, other):
        if isinstance(other, DebianVersion):
            return self._comparable_parts < other._comparable_parts
        else:
            return NotImplemented


if six.PY3:
    import functools
    ComparablePart = functools.total_ordering(ComparablePart)
    DebianVersion = functools.total_ordering(DebianVersion)
コード例 #22
0
ファイル: debian_version.py プロジェクト: awwad/depsolver
            s = self.epoch + ":" + s
        if self.revision:
            s += "-" + self.revision
        return s

    def __hash__(self):
        return hash(str(self))

    def __cmp__(self, other):
        if isinstance(other, DebianVersion):
            return cmp(self._comparable_parts, other._comparable_parts)
        else:
            return NotImplemented

    def __eq__(self, other):
        if isinstance(other, DebianVersion):
            return self._comparable_parts == other._comparable_parts
        else:
            return NotImplemented

    def __lt__(self, other):
        if isinstance(other, DebianVersion):
            return self._comparable_parts < other._comparable_parts
        else:
            return NotImplemented

if six.PY3:
    import functools
    ComparablePart = functools.total_ordering(ComparablePart)
    DebianVersion = functools.total_ordering(DebianVersion)
コード例 #23
0
    def _backward():
        self.grad += 1 / self.data * out.grad

    out._backward = _backward

    return out


def exp(self, *args, **kwargs):
    return math.e**self


def __ge__(self, other):
    return self.data >= (other.data if isinstance(other, Value) else other)


def __eq__(self, other):
    return self.data == (other.data if isinstance(other, Value) else other)


Value.__rpow__ = __rpow__
Value.__pow__ = __pow__
Value.log = log
Value.exp = exp
Value.sigmoid = sigmoid
Value.__ge__ = __ge__
Value.__eq__ = __eq__

total_ordering(Value)
コード例 #24
0
ファイル: family.py プロジェクト: alexji/pynbody
        # Provided so a single family can be treated as a list of families
        yield self

    def __str__(self):
        return self.name

    def __cmp__(self, other):
        # for python 2.x
        return cmp(str(self), str(other))

    def __eq__(self, other):
        return str(self) == str(other)

    def __lt__(self, other):
        return str(self) < str(other)

    def __hash__(self):
        return hash(str(self))

if sys.version_info[0] >= 3:
    Family = functools.total_ordering(Family)


# Instantiate the default families as specified
# by the configuration file

g = globals()
for f in config_parser.options('families'):
    aliases = config_parser.get('families', f)
    g[f] = Family(f, map(str.strip, aliases.split(",")))
コード例 #25
0
        if not D:
            for n, v in getAllNamedColors().items():
                if not isinstance(v, CMYKColor):
                    t = v.red, v.green, v.blue
                    if t in D:
                        n = n + '/' + D[t]
                    D[t] = n
        t = self.red, self.green, self.blue
        return t in D and D[t] or None

    @property
    def normalizedAlpha(self):
        return self.alpha


if isPy3: Color = functools.total_ordering(Color)


def opaqueColor(c):
    '''utility to check we have a color that's not fully transparent'''
    return isinstance(c, Color) and c.alpha > 0


class CMYKColor(Color):
    """This represents colors using the CMYK (cyan, magenta, yellow, black)
    model commonly used in professional printing.  This is implemented
    as a derived class so that renderers which only know about RGB "see it"
    as an RGB color through its 'red','green' and 'blue' attributes, according
    to an approximate function.

    The RGB approximation is worked out when the object in constructed, so
コード例 #26
0
 def update_event(self, inp=-1):
     self.set_output_val(0, functools.total_ordering(self.input(0)))
コード例 #27
0
ファイル: family.py プロジェクト: lluciesmith/pynbody
        # Provided so a single family can be treated as a list of families
        yield self

    def __str__(self):
        return self.name

    def __cmp__(self, other):
        # for python 2.x
        return cmp(str(self), str(other))

    def __eq__(self, other):
        return str(self) == str(other)

    def __lt__(self, other):
        return str(self) < str(other)

    def __hash__(self):
        return hash(str(self))


if sys.version_info[0] >= 3:
    Family = functools.total_ordering(Family)

# Instantiate the default families as specified
# by the configuration file

g = globals()
for f in config_parser.options('families'):
    aliases = config_parser.get('families', f)
    g[f] = Family(f, list(map(str.strip, aliases.split(","))))
コード例 #28
0
ファイル: managers.py プロジェクト: jdufresne/django-taggit
    @property
    def related_fields(self):
        return [(_get_field(self.through, 'object_id'), self.model._meta.pk)]

    @property
    def foreign_related_fields(self):
        return [self.related_fields[0][1]]


def _get_subclasses(model):
    subclasses = [model]
    if VERSION < (1, 8):
        all_fields = (_get_field(model, f) for f in model._meta.get_all_field_names())
    else:
        all_fields = model._meta.get_fields()
    for field in all_fields:
        # Django 1.8 +
        if (not RelatedObject and isinstance(field, OneToOneRel) and
                getattr(_remote_field(field.field), "parent_link", None)):
            subclasses.extend(_get_subclasses(field.related_model))

        # < Django 1.8
        if (RelatedObject and isinstance(field, RelatedObject) and
                getattr(field.field.rel, "parent_link", None)):
            subclasses.extend(_get_subclasses(field.model))
    return subclasses


TaggableManager = total_ordering(TaggableManager)
コード例 #29
0
ファイル: adt.py プロジェクト: JelleZijlstra/taxonomy
    def __new__(mcs, name: str, bases: Any, ns: Any) -> Type[Any]:
        if "_is_member" in ns and ns["_is_member"]:
            return super().__new__(mcs, name, bases, ns)
        members = {}
        for key, value in list(ns.items()):
            if isinstance(value, _ADTMember):
                members[key] = value
                del ns[key]
        new_cls = super().__new__(
            mcs, name, bases, dict(ns.items(), _members=tuple(members.keys()))
        )
        new_cls._tag_to_member = {}  # type: ignore
        if name in members and not members[name].called:
            del members[name]
            has_self_cls = True
        else:
            has_self_cls = False
        for member in members.values():
            if not member.called:
                raise TypeError(f"incomplete member {member}")
            has_args = bool(member.kwargs)
            attrs: Dict[str, Type[Any]] = {}
            member_ns = {
                "_attributes": attrs,
                "_tag": member.tag,
                "_has_args": has_args,
                "_is_member": True,
                "_adt_cls": new_cls,
                "__eq__": _adt_member_eq,
                "__lt__": _adt_member_lt,
                "__hash__": _adt_member_hash,
            }
            if has_args:
                for key, value in member.kwargs.items():
                    if value in BASIC_TYPES:
                        attrs[key] = value
                    elif isinstance(value, type) and issubclass(value, enum.IntEnum):
                        attrs[key] = value
                    elif (
                        isinstance(value, type)
                        and hasattr(value, "serialize")
                        and hasattr(value, "unserialize")
                    ):
                        attrs[key] = value
                    elif (
                        has_self_cls
                        and isinstance(value, _ADTMember)
                        and value.name == name
                    ):
                        attrs[key] = new_cls
                    else:
                        raise TypeError(f"unsupported type {value}")
                lines = "".join(
                    f"    self.{attr} = {attr}\n" for attr in member.kwargs.keys()
                )
                code = (
                    f'def __init__(self, {", ".join(member.kwargs.keys())}):\n{lines}'
                )
                new_ns: Dict[str, Any] = {}
                exec(code, {}, new_ns)
                member_ns["__init__"] = new_ns["__init__"]
            member_cls = functools.total_ordering(
                type(member.name, (new_cls,), member_ns)
            )
            if not has_args:
                cls_obj = member_cls
                member_cls = cls_obj()

                def make_init(member_cls: object) -> Callable[[object], None]:
                    def __init__(self: object) -> None:
                        raise TypeError(f"cannot instantiate {member_cls}")

                    return __init__

                cls_obj.__init__ = make_init(member_cls)  # type: ignore
            new_cls._tag_to_member[member.tag] = member_cls  # type: ignore
            setattr(new_cls, member.name, member_cls)
        return new_cls