<commit_before># SPDX-FileCopyrightText: 2013 SAP SE Srdjan Boskovic <srdjan.boskovic@sap.com>
#
# SPDX-License-Identifier: Apache-2.0

# -*- coding: utf-8 -*
import platform
import datetime
from configparser import ConfigParser
from pyrfc import set_ini_file_directory

COPA = ConfigParser()
fc = open("tests/pyrfc.cfg", "r")
COPA.read_file(fc)

# Numeric types
#
# ABAP:       https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-US/index.htm?file=abenddic_builtin_types_intro.htm
# JavaScript: https://www.ecma-international.org/ecma-262/10.0/index.html#Title
#

RFC_MATH = {
    "RFC_INT1": {"MIN": 0, "MAX": 255},
    "RFC_INT2": {"NEG": -32768, "POS": 32767},
    "RFC_INT4": {"NEG": -2147483648, "POS": 2147483647},
    "RFC_INT8": {"NEG": -9223372036854775808, "POS": 9223372036854775807},
    "FLOAT": {
        "NEG": {"MIN": "-2.2250738585072014E-308", "MAX": "-1.7976931348623157E+308"},
        "POS": {"MIN": "2.2250738585072014E-308", "MAX": "1.7976931348623157E+308"},
    },
    "DECF16": {
        "NEG": {"MIN": "-1E-383", "MAX": "-9.999999999999999E+384"},
        "POS": {"MIN": "1E-383", "MAX": "9.999999999999999E+384"},
    },
    "DECF34": {
        "NEG": {"MIN": "-1E-6143", "MAX": "-9.999999999999999999999999999999999E+6144"},
        "POS": {"MIN": "1E-6143", "MAX": "9.999999999999999999999999999999999E+6144"},
    },
    "DATE": {"MIN": "00010101", "MAX": "99991231"},
    "TIME": {"MIN": "000000", "MAX": "235959"},
    "UTCLONG": {
        "MIN": "0001-01-01T00:00:00.0000000",
        "MAX": "9999-12-31T23:59:59.9999999",
        "INITIAL": "0000-00-00T00:00:00.0000000",
    },
}

def get_error(ex):
    error = {}
    ex_type_full = str(type(ex))
    error["type"] = ex_type_full[ex_type_full.rfind(".") + 1 : ex_type_full.rfind("'")]
    error["code"] = ex.code if hasattr(ex, "code") else "<None>"
    error["key"] = ex.key if hasattr(ex, "key") else "<None>"
    error["message"] = ex.message.split("\n")
    error["msg_class"] = ex.msg_class if hasattr(ex, "msg_class") else "<None>"
    error["msg_type"] = ex.msg_type if hasattr(ex, "msg_type") else "<None>"
    error["msg_number"] = ex.msg_number if hasattr(ex, "msg_number") else "<None>"
    error["msg_v1"] = ex.msg_v1 if hasattr(ex, "msg_v1") else "<None>"
    return error

def ABAP_to_python_date(abap_date):
    return datetime.datetime.strptime(abap_date, "%Y%m%d").date()

def ABAP_to_python_time(abap_time):
    return datetime.datetime.strptime(abap_time, "%H%M%S").time()

def python_to_ABAP_date(py_date):
    return "{:04d}{:02d}{:02d}".format(py_date.year, py_date.month, py_date.day)

def python_to_ABAP_time(py_time):
    return "{:02d}{:02d}{:02d}".format(py_time.hour, py_time.minute, py_time.second)

CONFIG_SECTIONS = COPA._sections
CONNECTION_INFO = CONFIG_SECTIONS["coevi51"]
UNICODETEST = u"ทดสอบสร้างลูกค้าจากภายนอกครั้งที่" * 7
UNICODE1 = u"四周远处都"
BYTEARRAY_TEST = bytearray.fromhex("01414243444549500051fdfeff")
BYTES_TEST = bytes(BYTEARRAY_TEST)
PARAMS = CONNECTION_INFO
PARAMSDEST = {"dest": "MME"}

set_ini_file_directory("tests")

PLATFORM = platform.system().lower()
CryptoLibPath = {
    "darwin": "/Applications/Secure Login Client.app/Contents/MacOS/lib/libsapcrypto.dylib",
    "linux": "/usr/local/sap/cryptolib/libsapcrypto.so",
    "win32": "C:\\Tools\\cryptolib\\sapcrypto.dll"
    # "C:\\Program Files\\SAP\\FrontEnd\\SecureLogin\\libsapcrypto.dll"
}[PLATFORM]

ClientPSEPath = {
    "darwin": "/Users/d037732/dotfiles/sec/rfctest.pse",
    "linux": "/home/www-admin/sec/rfctest.pse",
    "win32": "C:\\Tools\\sec\\rfctest.pse",
}[PLATFORM]
<commit_msg>Windows tests fix<commit_after># SPDX-FileCopyrightText: 2013 SAP SE Srdjan Boskovic <srdjan.boskovic@sap.com>
#
# SPDX-License-Identifier: Apache-2.0

# -*- coding: utf-8 -*
import platform
import datetime
from configparser import ConfigParser
from pyrfc import set_ini_file_directory

COPA = ConfigParser()
fc = open("tests/pyrfc.cfg", "r")
COPA.read_file(fc)

# Numeric types
#
# ABAP:       https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-US/index.htm?file=abenddic_builtin_types_intro.htm
# JavaScript: https://www.ecma-international.org/ecma-262/10.0/index.html#Title
#

RFC_MATH = {
    "RFC_INT1": {"MIN": 0, "MAX": 255},
    "RFC_INT2": {"NEG": -32768, "POS": 32767},
    "RFC_INT4": {"NEG": -2147483648, "POS": 2147483647},
    "RFC_INT8": {"NEG": -9223372036854775808, "POS": 9223372036854775807},
    "FLOAT": {
        "NEG": {"MIN": "-2.2250738585072014E-308", "MAX": "-1.7976931348623157E+308"},
        "POS": {"MIN": "2.2250738585072014E-308", "MAX": "1.7976931348623157E+308"},
    },
    "DECF16": {
        "NEG": {"MIN": "-1E-383", "MAX": "-9.999999999999999E+384"},
        "POS": {"MIN": "1E-383", "MAX": "9.999999999999999E+384"},
    },
    "DECF34": {
        "NEG": {"MIN": "-1E-6143", "MAX": "-9.999999999999999999999999999999999E+6144"},
        "POS": {"MIN": "1E-6143", "MAX": "9.999999999999999999999999999999999E+6144"},
    },
    "DATE": {"MIN": "00010101", "MAX": "99991231"},
    "TIME": {"MIN": "000000", "MAX": "235959"},
    "UTCLONG": {
        "MIN": "0001-01-01T00:00:00.0000000",
        "MAX": "9999-12-31T23:59:59.9999999",
        "INITIAL": "0000-00-00T00:00:00.0000000",
    },
}

def get_error(ex):
    error = {}
    ex_type_full = str(type(ex))
    error["type"] = ex_type_full[ex_type_full.rfind(".") + 1 : ex_type_full.rfind("'")]
    error["code"] = ex.code if hasattr(ex, "code") else "<None>"
    error["key"] = ex.key if hasattr(ex, "key") else "<None>"
    error["message"] = ex.message.split("\n")
    error["msg_class"] = ex.msg_class if hasattr(ex, "msg_class") else "<None>"
    error["msg_type"] = ex.msg_type if hasattr(ex, "msg_type") else "<None>"
    error["msg_number"] = ex.msg_number if hasattr(ex, "msg_number") else "<None>"
    error["msg_v1"] = ex.msg_v1 if hasattr(ex, "msg_v1") else "<None>"
    return error

def ABAP_to_python_date(abap_date):
    return datetime.datetime.strptime(abap_date, "%Y%m%d").date()

def ABAP_to_python_time(abap_time):
    return datetime.datetime.strptime(abap_time, "%H%M%S").time()

def python_to_ABAP_date(py_date):
    return "{:04d}{:02d}{:02d}".format(py_date.year, py_date.month, py_date.day)

def python_to_ABAP_time(py_time):
    return "{:02d}{:02d}{:02d}".format(py_time.hour, py_time.minute, py_time.second)

CONFIG_SECTIONS = COPA._sections
CONNECTION_INFO = CONFIG_SECTIONS["coevi51"]
UNICODETEST = u"ทดสอบสร้างลูกค้าจากภายนอกครั้งที่" * 7
UNICODE1 = u"四周远处都"
BYTEARRAY_TEST = bytearray.fromhex("01414243444549500051fdfeff")
BYTES_TEST = bytes(BYTEARRAY_TEST)
PARAMS = CONNECTION_INFO
PARAMSDEST = {"dest": "MME"}

set_ini_file_directory("tests")

PLATFORM = platform.system().lower()
CryptoLibPath = {
    "darwin": "/Applications/Secure Login Client.app/Contents/MacOS/lib/libsapcrypto.dylib",
    "linux": "/usr/local/sap/cryptolib/libsapcrypto.so",
    "win32": "C:\\Tools\\cryptolib\\sapcrypto.dll",
    "windows": "C:\\Tools\\cryptolib\\sapcrypto.dll"
    # "C:\\Program Files\\SAP\\FrontEnd\\SecureLogin\\libsapcrypto.dll"
}[PLATFORM]

ClientPSEPath = {
    "darwin": "/Users/d037732/dotfiles/sec/rfctest.pse",
    "linux": "/home/www-admin/sec/rfctest.pse",
    "win32": "C:\\Tools\\sec\\rfctest.pse",
    "windows": "C:\\Tools\\sec\\rfctest.pse",
}[PLATFORM]
<|endoftext|>


<commit_before>import os
import sys

from spec import Spec, skip, eq_, raises

from invoke.loader import FilesystemLoader as Loader # TODO: expand
from invoke.collection import Collection
from invoke.exceptions import CollectionNotFound

from _utils import support

class Loader_(Spec):
    def exposes_discovery_start_point(self):
        start = '/tmp/'
        eq_(Loader(start=start).start, start)

    def has_a_default_discovery_start_point(self):
        eq_(Loader().start, os.getcwd())

    class load:
        def setup(self):
            self.l = Loader(start=support)

        def returns_collection_object_if_name_found(self):
            result = self.l.load('foo')
            eq_(type(result), Collection)

        @raises(CollectionNotFound)
        def raises_CollectionNotFound_if_not_found(self):
            self.l.load('nope')

        @raises(ImportError)
        def raises_ImportError_if_found_collection_cannot_be_imported(self):
            # Instead of masking with a CollectionNotFound
            self.l.load('oops')

        def searches_towards_root_of_filesystem(self):
            # Loaded while root is in same dir as .py
            directly = self.l.load('foo')
            # Loaded while root is multiple dirs deeper than the .py
            deep = os.path.join(support, 'ignoreme', 'ignoremetoo')
            indirectly = Loader(start=deep).load('foo')
            eq_(directly, indirectly)

        def defaults_to_tasks_collection(self):
            "defaults to 'tasks' collection"
            result = Loader(start=support + '/implicit/').load()
            eq_(type(result), Collection)

    class find:
        @raises(CollectionNotFound)
        def raises_CollectionNotFound_for_missing_collections(self):
            result = Loader(start=support).find('nope')

#class SysPathLoader_(Spec):
#    # TODO: factor out anything that applies, from FilesystemLoader tests
#
#    class update_path:
#        def setup(self):
#            self.l = Loader(start=support)
#
#        def does_not_modify_argument(self):
#            path = []
#            new_path = self.l.update_path(path)
#            eq_(path, [])
#            assert len(new_path) > 0
#
#        def inserts_self_start_parent_at_front_of_path(self):
#            "Inserts self.start at front of path"
#            eq_(self.l.update_path([])[0], self.l.start)
#
#        def adds_to_front_if_exists(self):
#            "Inserts self.start at front of path even if it's already elsewhere"
#            new_path = self.l.update_path([self.l.start])
#            eq_(len(new_path), 2) # lol ?
#            eq_(new_path[0], self.l.start)
<commit_msg>Tweak names in test<commit_after>import os
import sys

from spec import Spec, skip, eq_, raises

from invoke.loader import FilesystemLoader as FSLoader
from invoke.collection import Collection
from invoke.exceptions import CollectionNotFound

from _utils import support

class FilesystemLoader_(Spec):
    def exposes_discovery_start_point(self):
        start = '/tmp/'
        eq_(FSLoader(start=start).start, start)

    def has_a_default_discovery_start_point(self):
        eq_(FSLoader().start, os.getcwd())

    class load:
        def setup(self):
            self.l = FSLoader(start=support)

        def returns_collection_object_if_name_found(self):
            result = self.l.load('foo')
            eq_(type(result), Collection)

        @raises(CollectionNotFound)
        def raises_CollectionNotFound_if_not_found(self):
            self.l.load('nope')

        @raises(ImportError)
        def raises_ImportError_if_found_collection_cannot_be_imported(self):
            # Instead of masking with a CollectionNotFound
            self.l.load('oops')

        def searches_towards_root_of_filesystem(self):
            # Loaded while root is in same dir as .py
            directly = self.l.load('foo')
            # Loaded while root is multiple dirs deeper than the .py
            deep = os.path.join(support, 'ignoreme', 'ignoremetoo')
            indirectly = FSLoader(start=deep).load('foo')
            eq_(directly, indirectly)

        def defaults_to_tasks_collection(self):
            "defaults to 'tasks' collection"
            result = FSLoader(start=support + '/implicit/').load()
            eq_(type(result), Collection)

    class find:
        @raises(CollectionNotFound)
        def raises_CollectionNotFound_for_missing_collections(self):
            result = FSLoader(start=support).find('nope')

#class SysPathLoader_(Spec):
#    # TODO: factor out anything that applies, from FilesystemLoader tests
#
#    class update_path:
#        def setup(self):
#            self.l = Loader(start=support)
#
#        def does_not_modify_argument(self):
#            path = []
#            new_path = self.l.update_path(path)
#            eq_(path, [])
#            assert len(new_path) > 0
#
#        def inserts_self_start_parent_at_front_of_path(self):
#            "Inserts self.start at front of path"
#            eq_(self.l.update_path([])[0], self.l.start)
#
#        def adds_to_front_if_exists(self):
#            "Inserts self.start at front of path even if it's already elsewhere"
#            new_path = self.l.update_path([self.l.start])
#            eq_(len(new_path), 2) # lol ?
#            eq_(new_path[0], self.l.start)
<|endoftext|>


<commit_before>import os
import uuid
from datetime import date, datetime, time

from django.db import models
from django.db.models.query import QuerySet
from django.db.models import sql, manager
from django.contrib.auth.models import User

### For basic tests and bench

class Category(models.Model):
    title = models.CharField(max_length=128)

    def __unicode__(self):
        return self.title

class Post(models.Model):
    title = models.CharField(max_length=128)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts')
    visible = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

class Extra(models.Model):
    post = models.OneToOneField(Post, on_delete=models.CASCADE)
    tag = models.IntegerField(db_column='custom_column_name', unique=True)
    to_tag = models.ForeignKey('self', on_delete=models.CASCADE, to_field='tag', null=True)

    def __unicode__(self):
        return 'Extra(post_id=%s, tag=%s)' % (self.post_id, self.tag)

### Specific and custom fields

class CustomValue(object):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def __eq__(self, other):
        return isinstance(other, CustomValue) and self.value == other.value

class CustomField(models.Field):
    def db_type(self, connection):
        return 'text'

    def to_python(self, value):
        if isinstance(value, CustomValue):
            return value
        return CustomValue(value)

    def from_db_value(self, value, expession, conn):
        return self.to_python(value)

    def get_prep_value(self, value):
        return value.value

class CustomWhere(sql.where.WhereNode):
    pass

class CustomQuery(sql.Query):
    pass

class CustomManager(models.Manager):
    def get_query_set(self):
        q = CustomQuery(self.model, CustomWhere)
        return QuerySet(self.model, q)
    get_queryset = get_query_set

class IntegerArrayField(models.Field):
    def db_type(self, connection):
        return 'text'

    def to_python(self, value):
        if value in (None, ''):
            return None
        if isinstance(value, list):
            return value
        return [int(v) for v in value.split(',')]

    def from_db_value(self, value, expession, conn):
        return self.to_python(value)

    def get_prep_value(self, value):
        return ','.join(map(str, value))

def custom_value_default():
    return CustomValue('default')

class Weird(models.Model):
    date_field = models.DateField(default=date(2000, 1, 1))
    datetime_field = models.DateTimeField(default=datetime(2000, 1, 1, 10, 10))
    time_field = models.TimeField(default=time(10, 10))
    list_field = IntegerArrayField(default=list, blank=True)
    custom_field = CustomField(default=custom_value_default)
    binary_field = models.BinaryField()

    objects = models.Manager()
    customs = CustomManager()

# TODO: check other new fields:
#       - PostgreSQL ones: ArrayField, HStoreField, RangeFields, unaccent
#       - Other: DurationField
if os.environ.get('CACHEOPS_DB') in {'postgresql', 'postgis'}:
    from django.contrib.postgres.fields import ArrayField
    try:
        from django.contrib.postgres.fields import JSONField
    except ImportError:
        JSONField = None

    class TaggedPost(models.Model):
        name = models.CharField(max_length=200)
        tags = ArrayField(models.IntegerField())
        if JSONField:
            meta = JSONField()

# 16
class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    tag = models.IntegerField()

# Proxy model
class Video(models.Model):
    title = models.CharField(max_length=128)

class VideoProxy(Video):
    class Meta:
        proxy = True

class NonCachedVideoProxy(Video):
    class Meta:
        proxy = True

class NonCachedMedia(models.Model):
    title = models.CharField(max_length=128)

class MediaProxy(NonCachedMedia):
    class Meta:
        proxy = True

# Multi-table inheritance
class Media(models.Model):
    name = models.CharField(max_length=128)

class Movie(Media):
    year = models.IntegerField()

# M2M models
class Label(models.Model):
    text = models.CharField(max_length=127, blank=True, default='')

class Brand(models.Model):
    labels = models.ManyToManyField(Label, related_name='brands')

# M2M with explicit through models
class LabelT(models.Model):
    text = models.CharField(max_length=127, blank=True, default='')

class BrandT(models.Model):
    labels = models.ManyToManyField(LabelT, related_name='brands', through='Labeling')

class Labeling(models.Model):
    label = models.ForeignKey(LabelT, on_delete=models.CASCADE)
    brand = models.ForeignKey(BrandT, on_delete=models.CASCADE)
    tag = models.IntegerField()

class PremiumBrand(Brand):
    extra = models.CharField(max_length=127, blank=True, default='')

# local_get
class Local(models.Model):
    tag = models.IntegerField(null=True)

# 45
class CacheOnSaveModel(models.Model):
    title = models.CharField(max_length=32)

# 47
class DbAgnostic(models.Model):
    pass

class DbBinded(models.Model):
    pass

# contrib.postgis
if os.environ.get('CACHEOPS_DB') == 'postgis':
    from django.contrib.gis.db import models as gis_models

    class Geometry(gis_models.Model):
        point = gis_models.PointField(geography=True, dim=3, blank=True, null=True, default=None)

# 145
class One(models.Model):
    boolean = models.BooleanField(default=False)

def set_boolean_true(sender, instance, created, **kwargs):
    if created:
        return

    dialog = One.objects.cache().get(id=instance.id)
    assert dialog.boolean is True

from django.db.models.signals import post_save
post_save.connect(set_boolean_true, sender=One)

# 312
class Device(models.Model):
    uid = models.UUIDField(default=uuid.uuid4)
    model = models.CharField(max_length=64)

# 333
class CustomQuerySet(QuerySet):
    pass

class CustomFromQSManager(manager.BaseManager.from_queryset(CustomQuerySet)):
    use_for_related_fields = True

class CustomFromQSModel(models.Model):
    boolean = models.BooleanField(default=False)
    objects = CustomFromQSManager()

# 352
class CombinedField(models.CharField):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.another_field = models.CharField(*args, **kwargs)

    def contribute_to_class(self, cls, name, **kwargs):
        super().contribute_to_class(cls, name, private_only=True)

        self.another_field.contribute_to_class(cls, name, **kwargs)

class CombinedFieldModel(models.Model):
    text = CombinedField(max_length=8, default='example')
<commit_msg>Remove empty lines<commit_after>import os
import uuid
from datetime import date, datetime, time

from django.db import models
from django.db.models.query import QuerySet
from django.db.models import sql, manager
from django.contrib.auth.models import User

### For basic tests and bench

class Category(models.Model):
    title = models.CharField(max_length=128)

    def __unicode__(self):
        return self.title

class Post(models.Model):
    title = models.CharField(max_length=128)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts')
    visible = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

class Extra(models.Model):
    post = models.OneToOneField(Post, on_delete=models.CASCADE)
    tag = models.IntegerField(db_column='custom_column_name', unique=True)
    to_tag = models.ForeignKey('self', on_delete=models.CASCADE, to_field='tag', null=True)

    def __unicode__(self):
        return 'Extra(post_id=%s, tag=%s)' % (self.post_id, self.tag)

### Specific and custom fields

class CustomValue(object):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def __eq__(self, other):
        return isinstance(other, CustomValue) and self.value == other.value

class CustomField(models.Field):
    def db_type(self, connection):
        return 'text'

    def to_python(self, value):
        if isinstance(value, CustomValue):
            return value
        return CustomValue(value)

    def from_db_value(self, value, expession, conn):
        return self.to_python(value)

    def get_prep_value(self, value):
        return value.value

class CustomWhere(sql.where.WhereNode):
    pass

class CustomQuery(sql.Query):
    pass

class CustomManager(models.Manager):
    def get_query_set(self):
        q = CustomQuery(self.model, CustomWhere)
        return QuerySet(self.model, q)
    get_queryset = get_query_set

class IntegerArrayField(models.Field):
    def db_type(self, connection):
        return 'text'

    def to_python(self, value):
        if value in (None, ''):
            return None
        if isinstance(value, list):
            return value
        return [int(v) for v in value.split(',')]

    def from_db_value(self, value, expession, conn):
        return self.to_python(value)

    def get_prep_value(self, value):
        return ','.join(map(str, value))

def custom_value_default():
    return CustomValue('default')

class Weird(models.Model):
    date_field = models.DateField(default=date(2000, 1, 1))
    datetime_field = models.DateTimeField(default=datetime(2000, 1, 1, 10, 10))
    time_field = models.TimeField(default=time(10, 10))
    list_field = IntegerArrayField(default=list, blank=True)
    custom_field = CustomField(default=custom_value_default)
    binary_field = models.BinaryField()

    objects = models.Manager()
    customs = CustomManager()

# TODO: check other new fields:
#       - PostgreSQL ones: ArrayField, HStoreField, RangeFields, unaccent
#       - Other: DurationField
if os.environ.get('CACHEOPS_DB') in {'postgresql', 'postgis'}:
    from django.contrib.postgres.fields import ArrayField
    try:
        from django.contrib.postgres.fields import JSONField
    except ImportError:
        JSONField = None

    class TaggedPost(models.Model):
        name = models.CharField(max_length=200)
        tags = ArrayField(models.IntegerField())
        if JSONField:
            meta = JSONField()

# 16
class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    tag = models.IntegerField()

# Proxy model
class Video(models.Model):
    title = models.CharField(max_length=128)

class VideoProxy(Video):
    class Meta:
        proxy = True

class NonCachedVideoProxy(Video):
    class Meta:
        proxy = True

class NonCachedMedia(models.Model):
    title = models.CharField(max_length=128)

class MediaProxy(NonCachedMedia):
    class Meta:
        proxy = True

# Multi-table inheritance
class Media(models.Model):
    name = models.CharField(max_length=128)

class Movie(Media):
    year = models.IntegerField()

# M2M models
class Label(models.Model):
    text = models.CharField(max_length=127, blank=True, default='')

class Brand(models.Model):
    labels = models.ManyToManyField(Label, related_name='brands')

# M2M with explicit through models
class LabelT(models.Model):
    text = models.CharField(max_length=127, blank=True, default='')

class BrandT(models.Model):
    labels = models.ManyToManyField(LabelT, related_name='brands', through='Labeling')

class Labeling(models.Model):
    label = models.ForeignKey(LabelT, on_delete=models.CASCADE)
    brand = models.ForeignKey(BrandT, on_delete=models.CASCADE)
    tag = models.IntegerField()

class PremiumBrand(Brand):
    extra = models.CharField(max_length=127, blank=True, default='')

# local_get
class Local(models.Model):
    tag = models.IntegerField(null=True)

# 45
class CacheOnSaveModel(models.Model):
    title = models.CharField(max_length=32)

# 47
class DbAgnostic(models.Model):
    pass

class DbBinded(models.Model):
    pass

# contrib.postgis
if os.environ.get('CACHEOPS_DB') == 'postgis':
    from django.contrib.gis.db import models as gis_models

    class Geometry(gis_models.Model):
        point = gis_models.PointField(geography=True, dim=3, blank=True, null=True, default=None)

# 145
class One(models.Model):
    boolean = models.BooleanField(default=False)

def set_boolean_true(sender, instance, created, **kwargs):
    if created:
        return

    dialog = One.objects.cache().get(id=instance.id)
    assert dialog.boolean is True

from django.db.models.signals import post_save
post_save.connect(set_boolean_true, sender=One)

# 312
class Device(models.Model):
    uid = models.UUIDField(default=uuid.uuid4)
    model = models.CharField(max_length=64)

# 333
class CustomQuerySet(QuerySet):
    pass

class CustomFromQSManager(manager.BaseManager.from_queryset(CustomQuerySet)):
    use_for_related_fields = True

class CustomFromQSModel(models.Model):
    boolean = models.BooleanField(default=False)
    objects = CustomFromQSManager()

# 352
class CombinedField(models.CharField):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.another_field = models.CharField(*args, **kwargs)

    def contribute_to_class(self, cls, name, **kwargs):
        super().contribute_to_class(cls, name, private_only=True)
        self.another_field.contribute_to_class(cls, name, **kwargs)

class CombinedFieldModel(models.Model):
    text = CombinedField(max_length=8, default='example')
<|endoftext|>


<commit_before>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim import optim

os.chdir('..')
from data import Data

LEARNING_RATE = 1e-3
EPOCH = 10000
NUM_CLASSES = 5
NUM_HIDDEN = 128 # commonly chosen hyperparam
DROPOUT_RATE = 0.5
EMBEDDING_SIZE = 5

class Net(nn.Module):
    def __init__(self, maxSentenceLength, embedDim, inputSize, weights = None):

        super(Net, self).__init__()

        self.inputSize = inputSize
        self.embedDim = embedDim
        self.maxSentenceLength = maxSentenceLength

        self.input = [Variable(torch.tensor(1, self.embedDim)) for _ in range(self.maxSentenceLength)]
        self.hiddenParam = Variable(torch.randn(1, 1, self.NUM_HIDDEN)) #fix the dimensions

        if not weights:
           self.setBLSTM()

        else:
            weights = weights

    def setBLSTM(self):
        self.lstm = nn.LSTM(input_size=self.inputSize,hidden_size=NUM_HIDDEN,bidirectional=True,
                        dropout=DROPOUT_RATE, bias=True)

    def forward(self):
        pass<commit_msg>added the layers, except for fully connected. started implementing forward<commit_after>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim import optim

os.chdir('..')
from data import Data

LEARNING_RATE = 1e-3
EPOCH = 10000
NUM_CLASSES = 5
NUM_HIDDEN = 300
DROPOUT_RATE = 0.5
EMBEDDING_SIZE = 5
BATCH_SIZE = 1

class Net(nn.Module):
    def __init__(self, maxSentenceLength, embedDim, inputSize, weights = None):

        super(Net, self).__init__()
        self.inputSize = inputSize
        self.embedDim = embedDim
        self.maxSentenceLength = maxSentenceLength

        self.input = [Variable(torch.tensor(1, self.embedDim)) for _ in range(self.maxSentenceLength)]
        self.hiddenParam = Variable(torch.randn(1, 1, self.NUM_HIDDEN)) #fix the dimensions

        if not weights:
           self.weights = None
           self.setLayers()
           self.train = True
        else:
            self.weights = weights

    def setLayers(self):
        self.LSTM = nn.LSTM(input_size=self.inputSize,hidden_size=NUM_HIDDEN,bidirectional=True,
                        num_layers=1, dropout=DROPOUT_RATE, bias=True)

        self.conv = nn.Conv2d(in_channels=1, out_channels=100, kernel_size=3, bias=True)

        self.maxpool = nn.MaxPool2d(kernel_size=2)

        self.softmax = nn.LogSoftmax()

    def forward(self):
        # (sequence_length, batch_size, input_size)
        self.in1 = Variable(torch.randn(self.embedDim, BATCH_SIZE, self.inputSize))
        # (num_layers*2, batch, hidden_size)
        self.hiddenVariable = Variable(torch.randn(2, BATCH_SIZE, NUM_HIDDEN))
        # (num_layers*2, batch, hidden_size)
        self.cellVariable = Variable(torch.randn(2, BATCH_SIZE, NUM_HIDDEN))

        #states is a tuple with (hidden_states, cell_states)
        self.output, self.states = self.LSTM(self.in1, (self.hiddenVariable, self.cellVariable))

        # self.output = <|endoftext|>


<commit_before>import base64
import redis
import unittest
from redisco import models
from redisco.connection import _get_client

class Person(models.Model):
    first_name = models.Attribute()
    last_name = models.Attribute()

    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name,)

    class Meta:
        indices = ['full_name']

class ModelTestCase(unittest.TestCase):
    def setUp(self):
        self.client = _get_client()
        self.client.flushdb()

    def tearDown(self):
        self.client.flushdb()

    def test_key(self):
        self.assertEqual('Person', Person._key)

    def test_is_new(self):
        p = Person(first_name="Darken", last_name="Rahl")
        self.assertTrue(p.is_new())

    def test_attributes(self):
        person = Person(first_name="Granny", last_name="Goose")
        self.assertEqual("Granny", person.first_name)
        self.assertEqual("Goose", person.last_name)

    def test_save(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        self.assertEqual('1', person1.id)
        self.assertEqual('2', person2.id)

    def test_getitem(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        p1 = Person.objects.get_by_id(1)
        p2 = Person.objects.get_by_id(2)

        self.assertEqual('Jejomar', p2.first_name)
        self.assertEqual('Binay', p2.last_name)

        self.assertEqual('Granny', p1.first_name)
        self.assertEqual('Goose', p1.last_name)

    def test_manager_create(self):
        person = Person.objects.create(first_name="Granny", last_name="Goose")

        p1 = Person.objects.get_by_id(1)
        self.assertEqual('Granny', p1.first_name)
        self.assertEqual('Goose', p1.last_name)

    def test_indices(self):
        person = Person.objects.create(first_name="Granny", last_name="Goose")
        db = person.db
        key = person.key()
        ckey = Person._key

        index = 'Person:first_name:%s' % base64.b64encode("Granny").replace("\n", "")
        self.assertTrue(index in db.smembers(key['_indices']))
        self.assertTrue("1" in db.smembers(index))

    def test_find(self):
        Person.objects.create(first_name="Granny", last_name="Goose")
        Person.objects.create(first_name="Clark", last_name="Kent")
        Person.objects.create(first_name="Granny", last_name="Mommy")
        Person.objects.create(first_name="Granny", last_name="Kent")
        persons = Person.objects.filter(first_name="Granny")

        self.assertEqual('1', persons[0].id)
        self.assertEqual(3, len(persons))

        persons = Person.objects.filter(first_name="Clark")
        self.assertEqual(1, len(persons))

        # by index
        persons = Person.objects.filter(full_name="Granny Mommy")
        self.assertEqual(1, len(persons))
        self.assertEqual("Granny Mommy", persons[0].full_name())

    def test_iter(self):
        Person.objects.create(first_name="Granny", last_name="Goose")
        Person.objects.create(first_name="Clark", last_name="Kent")
        Person.objects.create(first_name="Granny", last_name="Mommy")
        Person.objects.create(first_name="Granny", last_name="Kent")

        for person in Person.objects.all():
            self.assertTrue(person.full_name() in ("Granny Goose",
                "Clark Kent", "Granny Mommy", "Granny Kent",))

    def test_sort(self):
        Person.objects.create(first_name="Zeddicus", last_name="Zorander")
        Person.objects.create(first_name="Richard", last_name="Cypher")
        Person.objects.create(first_name="Richard", last_name="Rahl")
        Person.objects.create(first_name="Kahlan", last_name="Amnell")

        res = Person.objects.order('first_name').all()
        self.assertEqual("Kahlan", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Richard", res[2].first_name)
        self.assertEqual("Zeddicus Zorander", res[3].full_name())

        res = Person.objects.order('-full_name').all()
        self.assertEqual("Zeddicus Zorander", res[0].full_name())
        self.assertEqual("Richard Rahl", res[1].full_name())
        self.assertEqual("Richard Cypher", res[2].full_name())
        self.assertEqual("Kahlan Amnell", res[3].full_name())

    def test_all(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        all = Person.objects.all()
        self.assertEqual(list([person1, person2]), list(all))

    def test_limit(self):
        Person.objects.create(first_name="Zeddicus", last_name="Zorander")
        Person.objects.create(first_name="Richard", last_name="Cypher")
        Person.objects.create(first_name="Richard", last_name="Rahl")
        Person.objects.create(first_name="Kahlan", last_name="Amnell")

        res = Person.objects.order('first_name').all().limit(3)
        self.assertEqual(3, len(res))
        self.assertEqual("Kahlan", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Richard", res[2].first_name)

        res = Person.objects.order('first_name').limit(3, offset=1)
        self.assertEqual(3, len(res))
        self.assertEqual("Richard", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Zeddicus", res[2].first_name)

    def test_integer_field(self):
        class Character(models.Model):
            n = models.IntegerField()
            m = models.Attribute()

        Character.objects.create(n=1998, m="A")
        Character.objects.create(n=3100, m="b")
        Character.objects.create(n=1, m="C")

        chars = Character.objects.all()
        self.assertEqual(3, len(chars))
        self.assertEqual(1998, chars[0].n)
        self.assertEqual("A", chars[0].m)

    def test_list_field(self):
        class Cake(models.Model):
            name = models.Attribute()
            ingredients = models.ListField(str)
            sizes = models.ListField(int)

        Cake.objects.create(name="StrCake",
                            ingredients=['strawberry', 'sugar', 'dough'],
                            sizes=[1, 2, 5])
        Cake.objects.create(name="Normal Cake",
                            ingredients=['sugar', 'dough'],
                            sizes=[1, 3, 5])
        Cake.objects.create(name="No Sugar Cake",
                            ingredients=['dough'],
                            sizes=[])
        cake = Cake.objects.all()[0]
        self.assertEqual(['strawberry', 'sugar', 'dough'],
                cake.ingredients)
        with_sugar = Cake.objects.filter(ingredients='sugar')
        self.assertTrue(2, len(with_sugar))
        self.assertEqual([1, 2, 5], with_sugar[0].sizes)
        self.assertEqual([1, 3, 5], with_sugar[1].sizes)

        size1 = Cake.objects.filter(sizes=str(2))
        self.assertEqual(1, len(size1))

    def test_reference_field(self):
        class Word(models.Model):
            placeholder = models.Attribute()

        class Character(models.Model):
            n = models.IntegerField()
            m = models.Attribute()
            word = models.ReferenceField(Word)

        Word.objects.create()
        word = Word.objects.all()[0]
        Character.objects.create(n=32, m='a', word=word)
        Character.objects.create(n=33, m='b', word=word)
        Character.objects.create(n=34, m='c', word=word)
        Character.objects.create(n=34, m='d')
        for char in Character.objects.all():
            self.assertEqual(word, char.word)
        a, b, c, d = list(Character.objects.all())
        self.assertTrue(a in word.character_set)
        self.assertTrue(b in word.character_set)
        self.assertTrue(c in word.character_set)
        self.assertTrue(d not in word.character_set)
        self.assertEqual(3, len(word.character_set))

    def test_datetime_field(self):
        from datetime import datetime
        n = datetime(2009, 12, 31)
        class Post(models.Model):
            title = models.Attribute()
            date_posted = models.DateTimeField()
            created_at = models.DateTimeField(auto_now_add=True)
        post = Post(title="First!", date_posted=n)
        post.save()
        post = Post.objects.get_by_id(post.id)
        self.assertEqual(n, post.date_posted)
        assert post.created_at

    def test_sort_by_int(self):
        class Exam(models.Model):
            score = models.IntegerField()
            total_score = models.IntegerField()

            def percent(self):
                return int((float(self.score) / self.total_score) * 100)

            class Meta:
                indices = ('percent',)

        Exam.objects.create(score=9, total_score=100)
        Exam.objects.create(score=99, total_score=100)
        Exam.objects.create(score=75, total_score=100)
        Exam.objects.create(score=33, total_score=100)
        Exam.objects.create(score=95, total_score=100)

        exams = Exam.objects.order('score')
        self.assertEqual([9, 33, 75, 95, 99,], [exam.score for exam in exams])
        filtered = Exam.objects.zfilter(score__in=(10, 96))
        self.assertEqual(3, len(filtered))

    def test_filter_date(self):
        from datetime import datetime

        class Post(models.Model):
            name = models.Attribute()
            date = models.DateTimeField()

        dates = (
            datetime(2010, 1, 20, 1, 40, 0),
            datetime(2010, 2, 20, 1, 40, 0),
            datetime(2010, 1, 26, 1, 40, 0),
            datetime(2009, 12, 21, 1, 40, 0),
            datetime(2010, 1, 10, 1, 40, 0),
            datetime(2010, 5, 20, 1, 40, 0),
        )

        i = 0
        for date in dates:
            Post.objects.create(name="Post#%d" % i, date=date)
            i += 1

        self.assertEqual([Post.objects.get_by_id(4)],
                list(Post.objects.filter(date=
                    datetime(2009, 12, 21, 1, 40, 0))))

        lt = (0, 2, 3, 4)
        res = [Post.objects.get_by_id(l + 1) for l in lt]
        self.assertEqual(set(res),
                set(Post.objects.zfilter(
                    date__lt=datetime(2010, 1, 30))))

    def test_validation(self):
        class Person(models.Model):
            name = models.Attribute(required=True)
        p = Person(name="Kokoy")
        self.assertTrue(p.is_valid())

        p = Person()
        self.assertFalse(p.is_valid())
        self.assertTrue(('name', 'required') in p.errors)

        # custom validator

        class Ninja(models.Model):
            def validator(age):
                if not age or age >= 10:
                    return (('age', 'must be below 10'),)
            age = models.IntegerField(required=True, validator=validator)

        nin1 = Ninja(age=9)
        self.assertTrue(nin1.is_valid())

        nin2 = Ninja(age=10)
        self.assertFalse(nin2.is_valid())
        self.assertTrue(('age', 'must be below 10') in nin2.errors)
<commit_msg>Move to a new test func.<commit_after>import base64
import redis
import unittest
from redisco import models
from redisco.connection import _get_client

class Person(models.Model):
    first_name = models.Attribute()
    last_name = models.Attribute()

    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name,)

    class Meta:
        indices = ['full_name']

class ModelTestCase(unittest.TestCase):
    def setUp(self):
        self.client = _get_client()
        self.client.flushdb()

    def tearDown(self):
        self.client.flushdb()

    def test_key(self):
        self.assertEqual('Person', Person._key)

    def test_is_new(self):
        p = Person(first_name="Darken", last_name="Rahl")
        self.assertTrue(p.is_new())

    def test_attributes(self):
        person = Person(first_name="Granny", last_name="Goose")
        self.assertEqual("Granny", person.first_name)
        self.assertEqual("Goose", person.last_name)

    def test_save(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        self.assertEqual('1', person1.id)
        self.assertEqual('2', person2.id)

    def test_getitem(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        p1 = Person.objects.get_by_id(1)
        p2 = Person.objects.get_by_id(2)

        self.assertEqual('Jejomar', p2.first_name)
        self.assertEqual('Binay', p2.last_name)

        self.assertEqual('Granny', p1.first_name)
        self.assertEqual('Goose', p1.last_name)

    def test_manager_create(self):
        person = Person.objects.create(first_name="Granny", last_name="Goose")

        p1 = Person.objects.get_by_id(1)
        self.assertEqual('Granny', p1.first_name)
        self.assertEqual('Goose', p1.last_name)

    def test_indices(self):
        person = Person.objects.create(first_name="Granny", last_name="Goose")
        db = person.db
        key = person.key()
        ckey = Person._key

        index = 'Person:first_name:%s' % base64.b64encode("Granny").replace("\n", "")
        self.assertTrue(index in db.smembers(key['_indices']))
        self.assertTrue("1" in db.smembers(index))

    def test_find(self):
        Person.objects.create(first_name="Granny", last_name="Goose")
        Person.objects.create(first_name="Clark", last_name="Kent")
        Person.objects.create(first_name="Granny", last_name="Mommy")
        Person.objects.create(first_name="Granny", last_name="Kent")
        persons = Person.objects.filter(first_name="Granny")

        self.assertEqual('1', persons[0].id)
        self.assertEqual(3, len(persons))

        persons = Person.objects.filter(first_name="Clark")
        self.assertEqual(1, len(persons))

        # by index
        persons = Person.objects.filter(full_name="Granny Mommy")
        self.assertEqual(1, len(persons))
        self.assertEqual("Granny Mommy", persons[0].full_name())

    def test_iter(self):
        Person.objects.create(first_name="Granny", last_name="Goose")
        Person.objects.create(first_name="Clark", last_name="Kent")
        Person.objects.create(first_name="Granny", last_name="Mommy")
        Person.objects.create(first_name="Granny", last_name="Kent")

        for person in Person.objects.all():
            self.assertTrue(person.full_name() in ("Granny Goose",
                "Clark Kent", "Granny Mommy", "Granny Kent",))

    def test_sort(self):
        Person.objects.create(first_name="Zeddicus", last_name="Zorander")
        Person.objects.create(first_name="Richard", last_name="Cypher")
        Person.objects.create(first_name="Richard", last_name="Rahl")
        Person.objects.create(first_name="Kahlan", last_name="Amnell")

        res = Person.objects.order('first_name').all()
        self.assertEqual("Kahlan", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Richard", res[2].first_name)
        self.assertEqual("Zeddicus Zorander", res[3].full_name())

        res = Person.objects.order('-full_name').all()
        self.assertEqual("Zeddicus Zorander", res[0].full_name())
        self.assertEqual("Richard Rahl", res[1].full_name())
        self.assertEqual("Richard Cypher", res[2].full_name())
        self.assertEqual("Kahlan Amnell", res[3].full_name())

    def test_all(self):
        person1 = Person(first_name="Granny", last_name="Goose")
        person1.save()
        person2 = Person(first_name="Jejomar", last_name="Binay")
        person2.save()

        all = Person.objects.all()
        self.assertEqual(list([person1, person2]), list(all))

    def test_limit(self):
        Person.objects.create(first_name="Zeddicus", last_name="Zorander")
        Person.objects.create(first_name="Richard", last_name="Cypher")
        Person.objects.create(first_name="Richard", last_name="Rahl")
        Person.objects.create(first_name="Kahlan", last_name="Amnell")

        res = Person.objects.order('first_name').all().limit(3)
        self.assertEqual(3, len(res))
        self.assertEqual("Kahlan", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Richard", res[2].first_name)

        res = Person.objects.order('first_name').limit(3, offset=1)
        self.assertEqual(3, len(res))
        self.assertEqual("Richard", res[0].first_name)
        self.assertEqual("Richard", res[1].first_name)
        self.assertEqual("Zeddicus", res[2].first_name)

    def test_integer_field(self):
        class Character(models.Model):
            n = models.IntegerField()
            m = models.Attribute()

        Character.objects.create(n=1998, m="A")
        Character.objects.create(n=3100, m="b")
        Character.objects.create(n=1, m="C")

        chars = Character.objects.all()
        self.assertEqual(3, len(chars))
        self.assertEqual(1998, chars[0].n)
        self.assertEqual("A", chars[0].m)

    def test_list_field(self):
        class Cake(models.Model):
            name = models.Attribute()
            ingredients = models.ListField(str)
            sizes = models.ListField(int)

        Cake.objects.create(name="StrCake",
                            ingredients=['strawberry', 'sugar', 'dough'],
                            sizes=[1, 2, 5])
        Cake.objects.create(name="Normal Cake",
                            ingredients=['sugar', 'dough'],
                            sizes=[1, 3, 5])
        Cake.objects.create(name="No Sugar Cake",
                            ingredients=['dough'],
                            sizes=[])
        cake = Cake.objects.all()[0]
        self.assertEqual(['strawberry', 'sugar', 'dough'],
                cake.ingredients)
        with_sugar = Cake.objects.filter(ingredients='sugar')
        self.assertTrue(2, len(with_sugar))
        self.assertEqual([1, 2, 5], with_sugar[0].sizes)
        self.assertEqual([1, 3, 5], with_sugar[1].sizes)

        size1 = Cake.objects.filter(sizes=str(2))
        self.assertEqual(1, len(size1))

    def test_reference_field(self):
        class Word(models.Model):
            placeholder = models.Attribute()

        class Character(models.Model):
            n = models.IntegerField()
            m = models.Attribute()
            word = models.ReferenceField(Word)

        Word.objects.create()
        word = Word.objects.all()[0]
        Character.objects.create(n=32, m='a', word=word)
        Character.objects.create(n=33, m='b', word=word)
        Character.objects.create(n=34, m='c', word=word)
        Character.objects.create(n=34, m='d')
        for char in Character.objects.all():
            self.assertEqual(word, char.word)
        a, b, c, d = list(Character.objects.all())
        self.assertTrue(a in word.character_set)
        self.assertTrue(b in word.character_set)
        self.assertTrue(c in word.character_set)
        self.assertTrue(d not in word.character_set)
        self.assertEqual(3, len(word.character_set))

    def test_datetime_field(self):
        from datetime import datetime
        n = datetime(2009, 12, 31)
        class Post(models.Model):
            title = models.Attribute()
            date_posted = models.DateTimeField()
            created_at = models.DateTimeField(auto_now_add=True)
        post = Post(title="First!", date_posted=n)
        post.save()
        post = Post.objects.get_by_id(post.id)
        self.assertEqual(n, post.date_posted)
        assert post.created_at

    def test_sort_by_int(self):
        class Exam(models.Model):
            score = models.IntegerField()
            total_score = models.IntegerField()

            def percent(self):
                return int((float(self.score) / self.total_score) * 100)

            class Meta:
                indices = ('percent',)

        Exam.objects.create(score=9, total_score=100)
        Exam.objects.create(score=99, total_score=100)
        Exam.objects.create(score=75, total_score=100)
        Exam.objects.create(score=33, total_score=100)
        Exam.objects.create(score=95, total_score=100)

        exams = Exam.objects.order('score')
        self.assertEqual([9, 33, 75, 95, 99,], [exam.score for exam in exams])
        filtered = Exam.objects.zfilter(score__in=(10, 96))
        self.assertEqual(3, len(filtered))

    def test_filter_date(self):
        from datetime import datetime

        class Post(models.Model):
            name = models.Attribute()
            date = models.DateTimeField()

        dates = (
            datetime(2010, 1, 20, 1, 40, 0),
            datetime(2010, 2, 20, 1, 40, 0),
            datetime(2010, 1, 26, 1, 40, 0),
            datetime(2009, 12, 21, 1, 40, 0),
            datetime(2010, 1, 10, 1, 40, 0),
            datetime(2010, 5, 20, 1, 40, 0),
        )

        i = 0
        for date in dates:
            Post.objects.create(name="Post#%d" % i, date=date)
            i += 1

        self.assertEqual([Post.objects.get_by_id(4)],
                list(Post.objects.filter(date=
                    datetime(2009, 12, 21, 1, 40, 0))))

        lt = (0, 2, 3, 4)
        res = [Post.objects.get_by_id(l + 1) for l in lt]
        self.assertEqual(set(res),
                set(Post.objects.zfilter(
                    date__lt=datetime(2010, 1, 30))))

    def test_validation(self):
        class Person(models.Model):
            name = models.Attribute(required=True)
        p = Person(name="Kokoy")
        self.assertTrue(p.is_valid())

        p = Person()
        self.assertFalse(p.is_valid())
        self.assertTrue(('name', 'required') in p.errors)

    def test_custom_validation(self):
        class Ninja(models.Model):
            def validator(age):
                if not age or age >= 10:
                    return (('age', 'must be below 10'),)
            age = models.IntegerField(required=True, validator=validator)

        nin1 = Ninja(age=9)
        self.assertTrue(nin1.is_valid())

        nin2 = Ninja(age=10)
        self.assertFalse(nin2.is_valid())
        self.assertTrue(('age', 'must be below 10') in nin2.errors)
<|endoftext|>


<commit_before>import pytest
from hoomd.filter.type_ import Type
from hoomd.filter.tags import Tags
from hoomd.filter.set_ import SetDifference, Union, Intersection
from copy import deepcopy
from itertools import combinations

def set_types(s, inds, particle_types, particle_type):
    for i in inds:
        s.particles.typeid[i] = particle_types.index(particle_type)

_type_indices = [([0, 3, 4, 8], [1, 2, 5, 6, 7, 9]),
                 ([2, 3, 5, 6, 7, 8, 9], [0, 1, 4]),
                 ([3, 7], [0, 1, 2, 4, 5, 6, 8, 9])]

@pytest.fixture(scope="function", params=_type_indices)
def type_indices(request):
    return deepcopy(request.param)

def test_type_filter(dummy_simulation_factory, type_indices):
    particle_types = ['A', 'B']
    N = 10
    sim = dummy_simulation_factory(particle_types=particle_types, n=N)

    A_filter = Type(["A"])
    B_filter = Type(["B"])
    AB_filter = Type(["A", "B"])
    assert A_filter(sim.state) == list(range(N))
    assert B_filter(sim.state) == []

    s = sim.state.snapshot
    if s.exists:
        set_types(s, range(N), particle_types, "B")
    sim.state.snapshot = s
    assert A_filter(sim.state) == []
    assert B_filter(sim.state) == list(range(N))

    A_inds, B_inds = type_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
    sim.state.snapshot = s
    assert A_filter(sim.state) == A_inds
    assert B_filter(sim.state) == B_inds
    assert AB_filter(sim.state) == list(range(N))

_tag_indices = [[0, 3, 4, 8],
                [1, 2, 5, 6, 7, 9],
                [2, 3, 5, 6, 7, 8, 9],
                [0, 1, 4],
                [3, 7],
                [0, 1, 2, 4, 5, 6, 8, 9]]

@pytest.fixture(scope="function", params=_tag_indices)
def tag_indices(request):
    return deepcopy(request.param)

def test_tags_filter(dummy_simulation_factory, tag_indices):
    particle_types = ['A']
    N = 10
    sim = dummy_simulation_factory(particle_types=particle_types, n=N)
    inds = tag_indices
    tag_filter = Tags(inds)
    assert tag_filter(sim.state) == inds

_set_indices = [([0, 3, 8], [1, 6, 7, 9], [2, 4, 5]),
                ([2, 3, 5, 7, 8], [0, 1, 4], [6, 9]),
                ([3], [0, 7, 8], [1, 2, 4, 5, 6, 9])]

@pytest.fixture(scope="function", params=_set_indices)
def set_indices(request):
    return deepcopy(request.param)

def type_not_in_combo(combo, particle_types):
    for particle_type in particle_types:
        if particle_type not in combo:
            return particle_type

def test_intersection(dummy_simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    sim = dummy_simulation_factory(particle_types=particle_types, n=N)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        combo_filter = Type(type_combo)
        for particle_type in type_combo:
            type_filter = Type([particle_type])
            intersection_filter = Intersection(combo_filter, type_filter)
            assert intersection_filter(sim.state) == type_filter(sim.state)
        remaining_type = type_not_in_combo(type_combo, particle_types)
        remaining_filter = Type([remaining_type])
        intersection_filter = Intersection(combo_filter, remaining_filter)
        assert intersection_filter(sim.state) == []

def test_union(dummy_simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    sim = dummy_simulation_factory(particle_types=particle_types, n=N)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        filter1 = Type([type_combo[0]])
        filter2 = Type([type_combo[1]])
        combo_filter = Type(type_combo)
        union_filter = Union(filter1, filter2)
        assert union_filter(sim.state) == combo_filter(sim.state)

def test_difference(dummy_simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    sim = dummy_simulation_factory(particle_types=particle_types, n=N)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        print(type_combo)
        print(str((A_inds, B_inds, C_inds)))
        filter1 = Type([type_combo[0]])
        filter2 = Type([type_combo[1]])
        remaining_type = type_not_in_combo(type_combo, particle_types)
        remaining_filter = Type([remaining_type])
        combo_filter = Type(type_combo)
        difference_filter = SetDifference(filter1, filter2)
        assert difference_filter(sim.state) == remaining_filter(sim.state)

        difference_filter = SetDifference(combo_filter, remaining_filter)
        assert difference_filter(sim.state) == []
<commit_msg>Changed tests to newer simulation factory<commit_after>import pytest
from hoomd.filter.type_ import Type
from hoomd.filter.tags import Tags
from hoomd.filter.set_ import SetDifference, Union, Intersection
from hoomd.snapshot import Snapshot
from copy import deepcopy
from itertools import combinations
import numpy

@pytest.fixture(scope="function")
def make_filter_snapshot(device):
    def filter_snapshot(n=10, particle_types=['A']):
        s = Snapshot(device.comm)
        if s.exists:
            s.configuration.box = [20, 20, 20, 0, 0, 0]
            s.particles.N = n
            s.particles.position[:] = numpy.random.uniform(-10, 10, size=(n, 3))
            s.particles.types = particle_types
        return s
    return filter_snapshot

def set_types(s, inds, particle_types, particle_type):
    for i in inds:
        s.particles.typeid[i] = particle_types.index(particle_type)

_type_indices = [([0, 3, 4, 8], [1, 2, 5, 6, 7, 9]),
                 ([2, 3, 5, 6, 7, 8, 9], [0, 1, 4]),
                 ([3, 7], [0, 1, 2, 4, 5, 6, 8, 9])]

@pytest.fixture(scope="function", params=_type_indices)
def type_indices(request):
    return deepcopy(request.param)

def test_type_filter(make_filter_snapshot, simulation_factory, type_indices):
    particle_types = ['A', 'B']
    N = 10
    filter_snapshot = make_filter_snapshot(n=N, particle_types=particle_types)
    sim = simulation_factory(filter_snapshot)

    A_filter = Type(["A"])
    B_filter = Type(["B"])
    AB_filter = Type(["A", "B"])
    assert A_filter(sim.state) == list(range(N))
    assert B_filter(sim.state) == []

    s = sim.state.snapshot
    if s.exists:
        set_types(s, range(N), particle_types, "B")
    sim.state.snapshot = s
    assert A_filter(sim.state) == []
    assert B_filter(sim.state) == list(range(N))

    A_inds, B_inds = type_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
    sim.state.snapshot = s
    assert A_filter(sim.state) == A_inds
    assert B_filter(sim.state) == B_inds
    assert AB_filter(sim.state) == list(range(N))

_tag_indices = [[0, 3, 4, 8],
                [1, 2, 5, 6, 7, 9],
                [2, 3, 5, 6, 7, 8, 9],
                [0, 1, 4],
                [3, 7],
                [0, 1, 2, 4, 5, 6, 8, 9]]

@pytest.fixture(scope="function", params=_tag_indices)
def tag_indices(request):
    return deepcopy(request.param)

def test_tags_filter(make_filter_snapshot, simulation_factory, tag_indices):
    particle_types = ['A']
    N = 10
    filter_snapshot = make_filter_snapshot(n=N, particle_types=particle_types)
    sim = simulation_factory(filter_snapshot)
    inds = tag_indices
    tag_filter = Tags(inds)
    assert tag_filter(sim.state) == inds

_set_indices = [([0, 3, 8], [1, 6, 7, 9], [2, 4, 5]),
                ([2, 3, 5, 7, 8], [0, 1, 4], [6, 9]),
                ([3], [0, 7, 8], [1, 2, 4, 5, 6, 9])]

@pytest.fixture(scope="function", params=_set_indices)
def set_indices(request):
    return deepcopy(request.param)

def type_not_in_combo(combo, particle_types):
    for particle_type in particle_types:
        if particle_type not in combo:
            return particle_type

def test_intersection(make_filter_snapshot, simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    filter_snapshot = make_filter_snapshot(n=N, particle_types=particle_types)
    sim = simulation_factory(filter_snapshot)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        combo_filter = Type(type_combo)
        for particle_type in type_combo:
            type_filter = Type([particle_type])
            intersection_filter = Intersection(combo_filter, type_filter)
            assert intersection_filter(sim.state) == type_filter(sim.state)
        remaining_type = type_not_in_combo(type_combo, particle_types)
        remaining_filter = Type([remaining_type])
        intersection_filter = Intersection(combo_filter, remaining_filter)
        assert intersection_filter(sim.state) == []

def test_union(make_filter_snapshot, simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    filter_snapshot = make_filter_snapshot(n=N, particle_types=particle_types)
    sim = simulation_factory(filter_snapshot)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        filter1 = Type([type_combo[0]])
        filter2 = Type([type_combo[1]])
        combo_filter = Type(type_combo)
        union_filter = Union(filter1, filter2)
        assert union_filter(sim.state) == combo_filter(sim.state)

def test_difference(make_filter_snapshot, simulation_factory, set_indices):
    particle_types = ['A', 'B', 'C']
    N = 10
    filter_snapshot = make_filter_snapshot(n=N, particle_types=particle_types)
    sim = simulation_factory(filter_snapshot)
    A_inds, B_inds, C_inds = set_indices
    s = sim.state.snapshot
    if s.exists:
        set_types(s, A_inds, particle_types, "A")
        set_types(s, B_inds, particle_types, "B")
        set_types(s, C_inds, particle_types, "C")
    sim.state.snapshot = s

    for type_combo in combinations(particle_types, 2):
        print(type_combo)
        print(str((A_inds, B_inds, C_inds)))
        filter1 = Type([type_combo[0]])
        filter2 = Type([type_combo[1]])
        remaining_type = type_not_in_combo(type_combo, particle_types)
        remaining_filter = Type([remaining_type])
        combo_filter = Type(type_combo)
        difference_filter = SetDifference(filter1, filter2)
        assert difference_filter(sim.state) == remaining_filter(sim.state)

        difference_filter = SetDifference(combo_filter, remaining_filter)
        assert difference_filter(sim.state) == []
<|endoftext|>


<commit_before>from auth import auth
import model.ordergroup

def protected(**pars):
    """
    .protected()
    Decorator to only allowed login users. We use the auth.protect method. Note
    that this method can only be used on the 'top' level function (GET) as it re-
    directs directly and thus fails on nested functions.

        @protected([perm][, captcha_on][, test])

        Decorator for limiting the access to pages.

        'perm' can be either a single permission (string) or a sequence of them.

        'captcha_on' is a Boole value('True' or 'False') to turn on or off the
        captcha validation.

        'test' must be a function that takes a user object and returns
        True or False.
    """
    return auth.protected(**pars)

def get_users():
    """
    .get_users()
        Returns a list of all users and their permissions/info
    """
    return auth.get_all_users()

def get_permissions():
    """
    .get_permissions()
        Returns a list of all permissions and their description
    """
    return auth.get_all_permissions()

def get_username():
    """
    .get_username()
        Returns a the name (str) of the logged in user
    """
    return auth.get_user().user_login

def get_permission():
    """
    .get_permission()
        Returns a list of all permissions of the logged in user
    """
    permissions = auth.get_permissions()
    if isinstance(permissions, str):
        return [permissions]
    return permissions

def check_permission(perm):
    """
    .check_permissions(perm)
        input: perm as string or list of strings
        output: True/False
        Checks if current user has (all) permissions: True, otherwise
        returns False
    """
    return auth.has_perm(perm)

def check_ordergroup(og_file, og_name):
    """
    .check_ordegroup(og_file, og_name)
        input: og_file as string, og_name as string
        output: True/False
        Checks if user has access to ordegroup 'og_name' in ordegroupfile 'og_file'
        returns True if both match, otherwise False
    """
    ordergroups_allowed = model.users.ordergroups_allowed()
    for ordergroup_file_allowed, ordergroup_allowed in ordergroups_allowed:
        ordergroup = model.ordergroup.load(ordergroup_file_allowed).find(ordergroup_allowed)
        for subordergroup in ordergroup.list_groups():
            if subordergroup.name == og_name and ordergroup_file_allowed == og_file:
                return True

    return False

def ordergroups_allowed():
    """
    .orders_allowed()
        input: none
        output: List of ordersgroups and the file that user has permission for:
                [ (ordergroup-file, ordergroup), (.. , ..)]
    """
    ordergroups_allowed = []
    permissions = get_permission()
    for permission in permissions:
        if permission[:10] == 'ordergroup':
            ordergroup, group = __parse_ordergroup_permission(permission)
            ordergroups_allowed.append((ordergroup, group))

    return ordergroups_allowed

def orders_allowed():
    """
    .orders_allowed()
        input: none
        output: List of orders (int) that user has access too based
        on the ordergroups he has permission for.
    """
    orders = []
    for ordergroup, group in ordergroups_allowed():
        ordergroup = model.ordergroup.load(ordergroup).find(group)
        orders.extend(ordergroup.list_orders_recursive().keys())

    return orders

def __parse_ordergroup_permission(permission):
    """
    .__parse_ordergroup_permission(permission)
        input: permission as str
        output: ordgergroup as str, group in ordergroup as str
    """
    permission_as_list = permission.split('-')
    ordergroup = permission_as_list[1]
    group = '-'.join(permission_as_list[2:])

    return ordergroup, group
<commit_msg>adds dummy code<commit_after>from auth import auth
import model.ordergroup

def protected(**pars):
    """
    .protected()
    Decorator to only allowed login users. We use the auth.protect method. Note
    that this method can only be used on the 'top' level function (GET) as it re-
    directs directly and thus fails on nested functions.

        @protected([perm][, captcha_on][, test])

        Decorator for limiting the access to pages.

        'perm' can be either a single permission (string) or a sequence of them.

        'captcha_on' is a Boole value('True' or 'False') to turn on or off the
        captcha validation.

        'test' must be a function that takes a user object and returns
        True or False.
    """
    return auth.protected(**pars)

def get_users():
    """
    .get_users()
        Returns a list of all users and their permissions/info
    """
    return auth.get_all_users()

def get_permissions():
    """
    .get_permissions()
        Returns a list of all permissions and their description
    """
    return auth.get_all_permissions()

def get_username():
    """
    .get_username()
        Returns a the name (str) of the logged in user
    """
    return auth.get_user().user_login

def get_permission():
    """
    .get_permission()
        Returns a list of all permissions of the logged in user
    """
    permissions = auth.get_permissions()
    if isinstance(permissions, str):
        return [permissions]
    return permissions

def check_permission(perm):
    """
    .check_permissions(perm)
        input: perm as string or list of strings
        output: True/False
        Checks if current user has (all) permissions: True, otherwise
        returns False
    """
    return auth.has_perm(perm)

def check_ordergroup(og_file, og_name):
    """
    .check_ordegroup(og_file, og_name)
        input: og_file as string, og_name as string
        output: True/False
        Checks if user has access to ordegroup 'og_name' in ordegroupfile 'og_file'
        returns True if both match, otherwise False
    """
    ordergroups_allowed = model.users.ordergroups_allowed()
    for ordergroup_file_allowed, ordergroup_allowed in ordergroups_allowed:
        ordergroup = model.ordergroup.load(ordergroup_file_allowed).find(ordergroup_allowed)
        for subordergroup in ordergroup.list_groups():
            if subordergroup.name == og_name and ordergroup_file_allowed == og_file:
                return True

    return False

def ordergroups_allowed():
    """
    .orders_allowed()
        input: none
        output: List of ordersgroups and the file that user has permission for:
                [ (ordergroup-file, ordergroup), (.. , ..)]
    """
    ordergroups_allowed = []
    permissions = get_permission()
    for permission in permissions:
        if permission[:10] == 'ordergroup':
            ordergroup, group = __parse_ordergroup_permission(permission)
            ordergroups_allowed.append((ordergroup, group))

    return ordergroups_allowed

def orders_allowed():
    """
    .orders_allowed()
        input: none
        output: List of orders (int) that user has access too based
        on the ordergroups he has permission for.
    """
    orders = []

    for ordergroup, group in ordergroups_allowed():
        ordergroup = model.ordergroup.load(ordergroup).find(group)
        orders.extend(ordergroup.list_orders_recursive().keys())

    #TODO DEBUG BUILDING NEW FEATURE TO ADD PI BASED ACCESS
    permissions = get_permission()
    for permission in permissions:
        if permission[:3] == 'BH-':
            budgetHolder = permission[3:]
            print 'you are authorzed to view'
            print budgetHolder
            #orders.extend(model.orders.load('BH'=budgetHolder))
            orders.extend([9999999999])

    print orders
    orders = []

    return orders

def __parse_ordergroup_permission(permission):
    """
    .__parse_ordergroup_permission(permission)
        input: permission as str
        output: ordgergroup as str, group in ordergroup as str
    """
    permission_as_list = permission.split('-')
    ordergroup = permission_as_list[1]
    group = '-'.join(permission_as_list[2:])

    return ordergroup, group
<|endoftext|>


<commit_before>#
# ------------------------------------------------------------
# Copyright (c) All rights reserved
# SiLab, Institute of Physics, University of Bonn
# ------------------------------------------------------------
#
from basil.HL.RegisterHardwareLayer import HardwareLayer

class weissSB22(HardwareLayer):

    '''Driver for the Weiss SB 22 climate chamber.
    A simple protocoll via RS 232 serial port is used with 9600/19200 baud rate and 256 modulo complement check sum.
    Between the different command a delay of 5 seconds should be set according to the manual, but it works also faster.
    '''

    _ERROR_CODES = {
        1: "Power cut",
        2: "Communication error",
        3: "Ventilator failure",
        4: "Temperature sensor short",
        5: "Humidity sensor short",
        6: "Sensor short",
        7: "Sensor short",
        8: "Sensor short",
        9: "Chiller prestage failure",
        10: "Chiller final stage failure",
        11: "Water level at minimum",
        12: "Water elvel below minimum",
        13: "Temperature too high",
        14: "Temperature too low",
        15: "Humidity too high",
        16: "Humidity too low",
        17: "Humidity water heater",
        18: "Test room heater",
        19: "No program memory"
    }

    def __init__(self, intf, conf):
        super(weissSB22, self).__init__(intf, conf)

    def init(self):
        self.slave_address = self._init['address']  # set the device address
        self.min_temp = self._init['min_temp']  # define the minimum temperature one can set, for safety
        self.max_temp = self._init['max_temp']  # define the maximum temperature one can set, for safety
        self.min_humidity = self._init['min_humidity']  # define the minimum humidity one can set, for safety
        self.max_humidity = self._init['max_humidity']  # define the maximum humidity one can set, for safety
        self._temperature = self.get_temperature()  # tmp variable to store last value set, needed since always temp and humidity has to be set
        self._humidity = self.get_humidity()  # tmp variable to store last value set, needed since always temp and humidity has to be set
        self._digital_ch = self.get_digital_ch()  # the digital channels define the functions (humiditiy control, dew protection, ..., in binary coding, 1000000000000000 is temperature control only)

    def get_temperature(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return float(answer[3:8])

    def get_temperature_target(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return float(answer[23:28])

    def get_humidity(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[9:11])

    def get_humidity_target(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[29:31])

    def get_digital_ch(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[32:49])

    def set_temperature(self, temperature):
        if temperature < self.min_temp:
            raise RuntimeWarning('Set temperature %f is lower than minimum allowed temperature %f', temperature, self.min_temp)
        if temperature > self.max_temp:
            raise RuntimeWarning('Set temperature %f is higher than maximum allowed temperature %f', temperature, self.max_temp)
        self._temperature = temperature
        msg = '%dT%05.1fF%02dR%16d' % (self.slave_address, self._temperature, self._humidity, self._digital_ch)
        self.write(msg)
        self.check_for_errors(self.read())

    def set_humidity(self, humidity):
        if humidity < self.min_humidity:
            raise RuntimeWarning('Set humidity %f is lower than minimum allowed humidity %f', humidity, self.min_humidity)
        if humidity > self.max_humidity:
            raise RuntimeWarning('Set humidity %f is higher than maximum allowed humidity %f', humidity, self.max_humidity)
        self._humidity = humidity
        msg = '%dT%05.1fF%02dR%16d' % (self.slave_address, self._temperature, self._humidity, self._digital_ch)
        self.write(msg)
        self.check_for_errors(self.read())

    def write(self, value):
        msg = '\x02' + value  # msg has STX at the beginning
        msg += self._calc_crc(msg)  # CRC for all characters including STX
        msg += '\x03'  # msg has ETX at the end
        self._intf.write(str(msg))

    def read(self):
        answer = self._intf._readline()  # the read termination string has to be set to \x03
        return answer

    def check_for_errors(self, answer):
        if len(answer) > 6:  # error codes are not in the ackowledge strings
            error_code = int(answer[20:22]) if answer[20:22] != '--' else 0
            if error_code > 0:
                raise RuntimeError('Climate chamber error %d: %s', error_code, self._ERROR_CODES[error_code])
        else:  # ack answer
            if answer[2] != '\x06':
                raise RuntimeError('Data transmission not ackowledged')
        if int(answer[1]) != self.slave_address:
            raise RuntimeError('Climate chamber address %s instead of %d', answer[1], self.slave_address)

    def _calc_crc(self, msg):
        ASCII = "0123456789ABCDEF"
        mod_256 = (-(sum(ord(i) for i in msg) % 256) & 0xFF)
        lword = (mod_256 & 0xF0) >> 4
        hword = mod_256 & 0x0F
        return ASCII[lword] + ASCII[hword]
<commit_msg>MAINT: typo<commit_after>#
# ------------------------------------------------------------
# Copyright (c) All rights reserved
# SiLab, Institute of Physics, University of Bonn
# ------------------------------------------------------------
#
from basil.HL.RegisterHardwareLayer import HardwareLayer

class weissSB22(HardwareLayer):

    '''Driver for the Weiss SB 22 climate chamber.
    A simple protocoll via RS 232 serial port is used with 9600/19200 baud rate and 256 modulo complement check sum.
    Between the different command a delay of 5 seconds should be set according to the manual, but it works at faster rates.
    '''

    _ERROR_CODES = {
        1: "Power cut",
        2: "Communication error",
        3: "Ventilator failure",
        4: "Temperature sensor short",
        5: "Humidity sensor short",
        6: "Sensor short",
        7: "Sensor short",
        8: "Sensor short",
        9: "Chiller prestage failure",
        10: "Chiller final stage failure",
        11: "Water level at minimum",
        12: "Water level below minimum",
        13: "Temperature too high",
        14: "Temperature too low",
        15: "Humidity too high",
        16: "Humidity too low",
        17: "Humidity water heater",
        18: "Test room heater",
        19: "No program memory"
    }

    def __init__(self, intf, conf):
        super(weissSB22, self).__init__(intf, conf)

    def init(self):
        self.slave_address = self._init['address']  # set the device address
        self.min_temp = self._init['min_temp']  # define the minimum temperature one can set, for safety
        self.max_temp = self._init['max_temp']  # define the maximum temperature one can set, for safety
        self.min_humidity = self._init['min_humidity']  # define the minimum humidity one can set, for safety
        self.max_humidity = self._init['max_humidity']  # define the maximum humidity one can set, for safety
        self._temperature = self.get_temperature()  # tmp variable to store last value set, needed since always temp and humidity has to be set
        self._humidity = self.get_humidity()  # tmp variable to store last value set, needed since always temp and humidity has to be set
        self._digital_ch = self.get_digital_ch()  # the digital channels define the functions (humiditiy control, dew protection, ..., in binary coding, 1000000000000000 is temperature control only)

    def get_temperature(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return float(answer[3:8])

    def get_temperature_target(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return float(answer[23:28])

    def get_humidity(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[9:11])

    def get_humidity_target(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[29:31])

    def get_digital_ch(self):
        self.write('%d?' % self.slave_address)
        answer = self.read()
        return int(answer[32:49])

    def set_temperature(self, temperature):
        if temperature < self.min_temp:
            raise RuntimeWarning('Set temperature %f is lower than minimum allowed temperature %f', temperature, self.min_temp)
        if temperature > self.max_temp:
            raise RuntimeWarning('Set temperature %f is higher than maximum allowed temperature %f', temperature, self.max_temp)
        self._temperature = temperature
        msg = '%dT%05.1fF%02dR%16d' % (self.slave_address, self._temperature, self._humidity, self._digital_ch)
        self.write(msg)
        self.check_for_errors(self.read())

    def set_humidity(self, humidity):
        if humidity < self.min_humidity:
            raise RuntimeWarning('Set humidity %f is lower than minimum allowed humidity %f', humidity, self.min_humidity)
        if humidity > self.max_humidity:
            raise RuntimeWarning('Set humidity %f is higher than maximum allowed humidity %f', humidity, self.max_humidity)
        self._humidity = humidity
        msg = '%dT%05.1fF%02dR%16d' % (self.slave_address, self._temperature, self._humidity, self._digital_ch)
        self.write(msg)
        self.check_for_errors(self.read())

    def write(self, value):
        msg = '\x02' + value  # msg has STX at the beginning
        msg += self._calc_crc(msg)  # CRC for all characters including STX
        msg += '\x03'  # msg has ETX at the end
        self._intf.write(str(msg))

    def read(self):
        answer = self._intf._readline()  # the read termination string has to be set to \x03
        return answer

    def check_for_errors(self, answer):
        if len(answer) > 6:  # error codes are not in the ackowledge strings
            error_code = int(answer[20:22]) if answer[20:22] != '--' else 0
            if error_code > 0:
                raise RuntimeError('Climate chamber error %d: %s', error_code, self._ERROR_CODES[error_code])
        else:  # ack answer
            if answer[2] != '\x06':
                raise RuntimeError('Data transmission not ackowledged')
        if int(answer[1]) != self.slave_address:
            raise RuntimeError('Climate chamber address %s instead of %d', answer[1], self.slave_address)

    def _calc_crc(self, msg):
        ASCII = "0123456789ABCDEF"
        mod_256 = (-(sum(ord(i) for i in msg) % 256) & 0xFF)
        lword = (mod_256 & 0xF0) >> 4
        hword = mod_256 & 0x0F
        return ASCII[lword] + ASCII[hword]
<|endoftext|>


<commit_before>""" Travis Ci Tests """

ActualData = [
              {'Name': 'ByeByeBaePls',
              'Rank': {'wasStaff': False, 'rank': 'MVP+'},
              'Level': 13.7633,
              'GuildID': '54b9e7060cf2141da4fb3449',
              'Session': None},

              {'Name': 'kevinkool',
               'Rank': {'wasStaff': True, 'rank': 'MVP+'},
               'Level': 43.25043478260869,
               'GuildID': None,
               'Session': None},

              {'Name': 'canihasban',
               'Rank': {'wasStaff': False, 'rank': 'Non'},
               'Level': 1.053,
               'GuildID': None,
               'Session': None},

              {'Name': 'Kqwqii',
               'Rank': {'wasStaff': False, 'rank': 'MVP+'},
               'Level': 5.1,
               'GuildID': None,
               'Session': None}
              ]

import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import hypixel
import time

print("Test \"{}\" is now running...\n".format(os.path.basename(__file__)))

API_KEY = os.environ['apikey']

hypixel.setKeys([API_KEY])

TestFailed = False

for player in ActualData:
    TestPlayer = hypixel.Player(player['Name'])
    for test in player:
        method_to_call = getattr(TestPlayer, 'get' + test)
        testdata = method_to_call()
        if testdata == player[test]:
            print("\U00002714 {}".format(testdata))
        else:
            print("\U0000274C {}, Expected: {} [FAILED]".format(testdata, player[test]))
            TestFailed = True
    print("UUID: {}\n".format(TestPlayer.UUID))

if TestFailed is True:
    raise ValueError

print("\nDone! All tests finished.")
<commit_msg>[skip ci] Update testdata<commit_after>""" Travis Ci Tests """

ActualData = [
              {'Name': 'ByeByeBaePls',
              'Rank': {'wasStaff': False, 'rank': 'MVP PLUS'},
              'Level': 16.184484210526314,
              'GuildID': None,
              'Session': None},

              {'Name': 'kevinkool',
               'Rank': {'wasStaff': True, 'rank': 'MVP+'},
               'Level': 43.25043478260869,
               'GuildID': None,
               'Session': None},

              {'Name': 'canihasban',
               'Rank': {'wasStaff': False, 'rank': 'Non'},
               'Level': 1.053,
               'GuildID': None,
               'Session': None},

              {'Name': 'Kqwqii',
               'Rank': {'wasStaff': False, 'rank': 'MVP PLUS'},
               'Level': 5.85,
               'GuildID': None,
               'Session': None}
              ]

import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import hypixel
import time

print("Test \"{}\" is now running...\n".format(os.path.basename(__file__)))

API_KEY = os.environ['apikey']

hypixel.setKeys([API_KEY])

TestFailed = False

for player in ActualData:
    TestPlayer = hypixel.Player(player['Name'])
    for test in player:
        method_to_call = getattr(TestPlayer, 'get' + test)
        testdata = method_to_call()
        if testdata == player[test]:
            print("\U00002714 {}".format(testdata))
        else:
            print("\U0000274C {}, Expected: {} [FAILED]".format(testdata, player[test]))
            TestFailed = True
    print("UUID: {}\n".format(TestPlayer.UUID))

if TestFailed is True:
    raise ValueError

print("\nDone! All tests finished.")
<|endoftext|>


<commit_before>'''
Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
Distributed under the MIT License.
See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
'''

# Set up modules and packages
# I/O
import csv
from pprint import pprint

# Numerical
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
import math

# System
import sys
import time
from tqdm import tqdm

# Get plotting packages
import matplotlib
import matplotlib.colors as colors
import matplotlib.axes
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib import rcParams
from matplotlib import cm
from matplotlib import gridspec
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.basemap import Basemap
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.tri as tri

print ""
print "---------------------------------------------------------------------------------"
print "                                 NAOS                                            "
print "                                                                                "
print "         Copyright (c) 2016, A. Agrawal (abhishek.agrawal@protonmail.com)        "
print "---------------------------------------------------------------------------------"
print ""

# Start timer.
start_time = time.time( )

## Operations
# Read data in csv file. data returned as a panda series.
data = pd.read_csv( '../data/eomOrbiterURESolution.csv' )
x = data[ 'x' ].values
y = data[ 'y' ].values
z = data[ 'z' ].values
vx = data[ 'vx' ].values
vy = data[ 'vy' ].values
vz = data[ 'vz' ].values
t = data[ 't' ].values
jacobian = data[ 'jacobian' ].values
semiMajor = data['semiMajor'].values
eccentricity = data['eccentricity'].values
inclination = data['inclination'].values
raan = data['RAAN'].values
aop = data['AOP'].values
ta = data['TA'].values

## Set up the figure
fig = plt.figure( )
ax1 = fig.add_subplot( 321 )
ax2 = fig.add_subplot( 322 )
ax3 = fig.add_subplot( 323 )
ax4 = fig.add_subplot( 324 )
ax5 = fig.add_subplot( 325 )
ax6 = fig.add_subplot( 326 )

## plot the orbital elements
ax1.plot( t, semiMajor, color=colors.cnames['purple'] )
ax1.set_xlabel('time [s]')
ax1.set_ylabel('semi-major axis [m]')
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useOffset=False)
ax1.grid( )

ax2.plot( t, eccentricity, color=colors.cnames['purple'] )
ax2.set_xlabel('time [s]')
ax2.set_ylabel('eccentricity')
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useOffset=False)
ax2.grid( )

ax3.plot( t, inclination, color=colors.cnames['purple'] )
ax3.set_xlabel('time [s]')
ax3.set_ylabel('inclination [deg]')
ax3.ticklabel_format(style='plain', axis='y')
ax3.grid( )

ax4.plot( t, raan, color=colors.cnames['purple'] )
ax4.set_xlabel('time [s]')
ax4.set_ylabel('RAAN [deg]')
ax3.ticklabel_format(style='plain', axis='y')
ax4.grid( )

ax5.plot( t, aop, color=colors.cnames['purple'] )
ax5.set_xlabel('time [s]')
ax5.set_ylabel('AOP [deg]')
ax3.ticklabel_format(style='plain', axis='y')
ax5.grid( )

## plot meta data
endIndex = np.size( x )
ax6.axis( 'off' )
metadata_table = []
metadata_table.append( [ "Initial X coordinate", x[0], "[m]" ] )
metadata_table.append( [ "Initial Y coordinate", y[0], "[m]" ] )
metadata_table.append( [ "Initial Z coordinate", z[0], "[m]" ] )
metadata_table.append( [ "Initial X velocity", vx[0], "[m/s]" ] )
metadata_table.append( [ "Initial Y velocity", vy[0], "[m/s]" ] )
metadata_table.append( [ "Initial Z velocity", vz[0], "[m/s]" ] )
metadata_table.append( [ "Simulation time", t[endIndex-1], "[s]" ] )
table = ax6.table( cellText = metadata_table, colLabels = None, cellLoc = 'center', loc = 'center' )
table_properties = table.properties( )
table_cells = table_properties[ 'child_artists' ]
for cell in table_cells: cell.set_height( 0.15 )
cell_dict = table.get_celld( )
for row in xrange( 0, 7 ): cell_dict[ ( row, 2 ) ].set_width( 0.1 )

## show plot
plt.tight_layout( )
plt.grid( )
plt.show( )

# Stop timer
end_time = time.time( )

# Print elapsed time
print "Script time: " + str("{:,g}".format(end_time - start_time)) + "s"

print ""
print "------------------------------------------------------------------"
print "                         Exited successfully!                     "
print "------------------------------------------------------------------"
print ""
<commit_msg>minor correction<commit_after>'''
Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
Distributed under the MIT License.
See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
'''

# Set up modules and packages
# I/O
import csv
from pprint import pprint

# Numerical
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
import math

# System
import sys
import time
from tqdm import tqdm

# Get plotting packages
import matplotlib
import matplotlib.colors as colors
import matplotlib.axes
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib import rcParams
from matplotlib import cm
from matplotlib import gridspec
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.basemap import Basemap
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.tri as tri

print ""
print "---------------------------------------------------------------------------------"
print "                                 NAOS                                            "
print "                                                                                "
print "         Copyright (c) 2016, A. Agrawal (abhishek.agrawal@protonmail.com)        "
print "---------------------------------------------------------------------------------"
print ""

# Start timer.
start_time = time.time( )

## Operations
# Read data in csv file. data returned as a panda series.
data = pd.read_csv( '../data/eomOrbiterURESolution.csv' )
x = data[ 'x' ].values
y = data[ 'y' ].values
z = data[ 'z' ].values
vx = data[ 'vx' ].values
vy = data[ 'vy' ].values
vz = data[ 'vz' ].values
t = data[ 't' ].values
jacobian = data[ 'jacobian' ].values
semiMajor = data['semiMajor'].values
eccentricity = data['eccentricity'].values
inclination = data['inclination'].values
raan = data['RAAN'].values
aop = data['AOP'].values
ta = data['TA'].values

## Set up the figure
fig = plt.figure( )
ax1 = fig.add_subplot( 321 )
ax2 = fig.add_subplot( 322 )
ax3 = fig.add_subplot( 323 )
ax4 = fig.add_subplot( 324 )
ax5 = fig.add_subplot( 325 )
ax6 = fig.add_subplot( 326 )

## plot the orbital elements
ax1.plot( t, semiMajor, color=colors.cnames['purple'] )
ax1.set_xlabel('time [s]')
ax1.set_ylabel('semi-major axis [m]')
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useOffset=False)
ax1.grid( )

ax2.plot( t, eccentricity, color=colors.cnames['purple'] )
ax2.set_xlabel('time [s]')
ax2.set_ylabel('eccentricity')
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useOffset=False)
ax2.grid( )

ax3.plot( t, inclination, color=colors.cnames['purple'] )
ax3.set_xlabel('time [s]')
ax3.set_ylabel('inclination [deg]')
ax3.ticklabel_format(style='plain', useOffset=False)
ax3.grid( )

ax4.plot( t, raan, color=colors.cnames['purple'] )
ax4.set_xlabel('time [s]')
ax4.set_ylabel('RAAN [deg]')
ax4.ticklabel_format(style='plain', useOffset=False)
ax4.grid( )

ax5.plot( t, aop, color=colors.cnames['purple'] )
ax5.set_xlabel('time [s]')
ax5.set_ylabel('AOP [deg]')
ax5.ticklabel_format(style='plain', useOffset=False)
ax5.grid( )

## plot meta data
endIndex = np.size( x )
ax6.axis( 'off' )
metadata_table = []
metadata_table.append( [ "Initial X coordinate", x[0], "[m]" ] )
metadata_table.append( [ "Initial Y coordinate", y[0], "[m]" ] )
metadata_table.append( [ "Initial Z coordinate", z[0], "[m]" ] )
metadata_table.append( [ "Initial X velocity", vx[0], "[m/s]" ] )
metadata_table.append( [ "Initial Y velocity", vy[0], "[m/s]" ] )
metadata_table.append( [ "Initial Z velocity", vz[0], "[m/s]" ] )
metadata_table.append( [ "Simulation time", t[endIndex-1], "[s]" ] )
table = ax6.table( cellText = metadata_table, colLabels = None, cellLoc = 'center', loc = 'center' )
table_properties = table.properties( )
table_cells = table_properties[ 'child_artists' ]
for cell in table_cells: cell.set_height( 0.15 )
cell_dict = table.get_celld( )
for row in xrange( 0, 7 ): cell_dict[ ( row, 2 ) ].set_width( 0.1 )

## show plot
plt.tight_layout( )
plt.grid( )
plt.show( )

# Stop timer
end_time = time.time( )

# Print elapsed time
print "Script time: " + str("{:,g}".format(end_time - start_time)) + "s"

print ""
print "------------------------------------------------------------------"
print "                         Exited successfully!                     "
print "------------------------------------------------------------------"
print ""
<|endoftext|>