示例#1
0
    def __init__(self, flags, default=None, *args, **kwargs):
        if isinstance(flags, dict):
            # Get only integer keys in correct range
            valid_keys = (k for k in flags.keys()
                          if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
            if not valid_keys:
                raise ValueError('Wrong keys or empty dictionary')
            # Fill list with values from dict or with empty values
            flags = [flags.get(i, '') for i in range(max(valid_keys) + 1)]

        if len(flags) > MAX_FLAG_COUNT:
            raise ValueError('Too many flags')

        self._arg_flags = flags
        flags = list(flags)
        labels = []
        for num, flag in enumerate(flags):
            if isinstance(flag, (tuple, list)):
                flags[num] = flag[0]
                labels.append(flag[1])
            else:
                labels.append(flag)

        if isinstance(default, (list, tuple, set, frozenset)):
            new_value = 0
            for flag in default:
                new_value |= Bit(flags.index(flag))
            default = new_value

        BigIntegerField.__init__(self, default=default, *args, **kwargs)
        self.flags = flags
        self.labels = labels
示例#2
0
class Collector(models.Model):

    key = models.UUIDField(default=uuid.uuid4, unique=True)
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             related_name="collectors",
                             null=True)

    latitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)
    longitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)
    timestamp = BigIntegerField(default=0)
    timestampData = BigIntegerField(default=0)

    def getDate(self):
        return datetime.datetime.fromtimestamp(int(
            self.timestamp / 1000)).strftime('%d/%m/%Y %H:%M:%S')

    def getStrLatitude(self):
        return "%.8f" % self.latitude

    def getStrLongitude(self):
        return "%.8f" % self.longitude

    def __unicode__(self):
        return "Active collector from " + self.user.username
示例#3
0
    def __init__(self, flags, default=None, *args, **kwargs):
        if isinstance(flags, dict):
            # Get only integer keys in correct range
            valid_keys = (k for k in flags.keys() if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
            if not valid_keys:
                raise ValueError('Wrong keys or empty dictionary')
            # Fill list with values from dict or with empty values
            flags = [flags.get(i, '') for i in range(max(valid_keys) + 1)]

        if len(flags) > MAX_FLAG_COUNT:
            raise ValueError('Too many flags')

        flags = list(flags)
        labels = []
        for num, flag in enumerate(flags):
            if isinstance(flag, (tuple, list)):
                flags[num] = flag[0]
                labels.append(flag[1])
            else:
                labels.append(flag)

        if isinstance(default, (list, tuple, set, frozenset)):
            new_value = 0
            for flag in default:
                new_value |= Bit(flags.index(flag))
            default = new_value

        BigIntegerField.__init__(self, default=default, *args, **kwargs)
        self.flags = flags
        self.labels = labels
示例#4
0
 def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
     if isinstance(value, SQLEvaluator) and isinstance(value.expression, Bit):
         value = value.expression
     if isinstance(value, (BitHandler, Bit)):
         return BitQueryLookupWrapper(self.model._meta.db_table, self.name, value)
     if connection is None:
         return BigIntegerField.get_db_prep_lookup(self, lookup_type=lookup_type, value=value)
     return BigIntegerField.get_db_prep_lookup(self, lookup_type=lookup_type, value=value,
                                                     connection=connection, prepared=prepared)
示例#5
0
    def __init__(self, flags, *args, **kwargs):
        if isinstance(flags, dict):
            # Get only integer keys in correct range
            valid_keys = (k for k in flags.keys() if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
            if not valid_keys:
                raise ValueError('Wrong keys or empty dictionary')
            # Fill list with values from dict or with empty values
            flags = [flags.get(i, '') for i in range(max(valid_keys) + 1)]

        if len(flags) > MAX_FLAG_COUNT:
            raise ValueError('Too many flags')

        BigIntegerField.__init__(self, *args, **kwargs)
        self.flags = flags
示例#6
0
    def __init__(self, flags, *args, **kwargs):
        if isinstance(flags, dict):
            # Get only integer keys in correct range
            valid_keys = (k for k in flags.keys()
                          if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
            if not valid_keys:
                raise ValueError('Wrong keys or empty dictionary')
            # Fill list with values from dict or with empty values
            flags = [flags.get(i, '') for i in range(max(valid_keys) + 1)]

        if len(flags) > MAX_FLAG_COUNT:
            raise ValueError('Too many flags')

        BigIntegerField.__init__(self, *args, **kwargs)
        self.flags = flags
示例#7
0
class GreetData(BaseModel):
    """あいさつ情報.
    """
    class Meta:
        app_label = settings_sub.APP_NAME
        abstract = False
    
    FIXED_COLUMNS = (
        'fromid','toid'
    )
    
    id = BigIntegerField(primary_key=True, verbose_name=u'ID((ユーザID<<32)+相手のID)')
    fromid = models.PositiveIntegerField(db_index=True, verbose_name=u'あいさつしたユーザID')
    toid = models.PositiveIntegerField(db_index=True, verbose_name=u'あいさつされたユーザID')
    ltime = AppDateTimeField(default=OSAUtil.get_now, verbose_name=u'最後にあいさつした時間')
    
    @classmethod
    def makeID(cls, uid, oid):
        return (uid << 32) + oid
    
    @classmethod
    def makeInstance(cls, key):
        ins = cls()
        ins.id = key
        ins.fromid = (key >> 32)
        ins.toid = (key & 0xffffffff)
        return ins
示例#8
0
class ColourTheme(Model):
    """The storage for the colouring theme stored for a company."""

    company = OneToOneField(Company, CASCADE, related_name="theme")

    primary = BigIntegerField(validators=[
        MinValueValidator(0x000000),
        MaxValueValidator(0xFFFFFFFF)
    ])

    accent = BigIntegerField(validators=[
        MinValueValidator(0x000000),
        MaxValueValidator(0xFFFFFFFF)
    ])

    logo = ForeignKey(Image, SET_NULL, null=True)
示例#9
0
 def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
     if isinstance(value, SQLEvaluator) and isinstance(value.expression, Bit):
         value = value.expression
     if isinstance(value, (BitHandler, Bit)):
         return [value.mask]
     return BigIntegerField.get_db_prep_lookup(self, lookup_type=lookup_type, value=value,
                                               connection=connection, prepared=prepared)
示例#10
0
 def get_prep_lookup(self, lookup_type, value):
     if isinstance(getattr(value, "expression", None), Bit):
         value = value.expression
     if isinstance(value, Bit):
         raise TypeError("Lookup type %r not supported with `Bit` type." %
                         lookup_type)
     return BigIntegerField.get_prep_lookup(self, lookup_type, value)
示例#11
0
class TelegramUser(Model):
    full_name = CharField(max_length=50)
    position = CharField(max_length=40)
    invite_code = CharField(max_length=40, default=generate_invite_code)
    telegram_id = BigIntegerField(blank=True, null=True, unique=True)

    class Meta:
        abstract = True
示例#12
0
 def get_prep_lookup(self, lookup_type, value):
     if isinstance(value, SQLEvaluator) and isinstance(value.expression, Bit):
         value = value.expression
     if isinstance(value, Bit):
         if lookup_type in ('exact',):
             return value
         raise TypeError('Lookup type %r not supported with `Bit` type.' % lookup_type)
     return BigIntegerField.get_prep_lookup(self, lookup_type, value)
示例#13
0
 def get_prep_lookup(self, lookup_type, value):
     if isinstance(getattr(value, 'expression', None), Bit):
         value = value.expression
     if isinstance(value, Bit):
         if lookup_type in ('exact',):
             return value
         raise TypeError('Lookup type %r not supported with `Bit` type.' % lookup_type)
     return BigIntegerField.get_prep_lookup(self, lookup_type, value)
示例#14
0
 def db_type(self, connection):
     rel_field = self.rel.get_related_field()
     # print "db_type: %s [%s]" % (rel_field.db_type(connection=connection),
     # rel_field)
     if (isinstance(rel_field, (models.AutoField, BigAutoField))) and \
             connection.settings_dict['ENGINE'] in psql_engines:
         return BigIntegerField().db_type(connection=connection)
     elif isinstance(rel_field, models.AutoField):  # Not postgreSQL
         return IntegerField().db_type(connection=connection)
     return rel_field.db_type(connection=connection)
示例#15
0
class Like(Model):
    id = BigAutoField(verbose_name='ID', primary_key=True)
    blog = ForeignKey(
        to=Blog,
        db_column='blog_id',
        db_constraint=False,
        on_delete=DO_NOTHING,
        related_name='like',
    )
    user = BigIntegerField(null=False, verbose_name='点赞者ID')  # user外键
    deleted = BooleanField(null=False, default=False, verbose_name='已经删除')
示例#16
0
    def __init__(self, flags, default=None, *args, **kwargs):
        if isinstance(flags, dict):
            # Get only integer keys in correct range
            valid_keys = (k for k in flags.keys() if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
            if not valid_keys:
                raise ValueError("Wrong keys or empty dictionary")
            # Fill list with values from dict or with empty values
            flags = [flags.get(i, "") for i in range(max(valid_keys) + 1)]

        if len(flags) > MAX_FLAG_COUNT:
            raise ValueError("Too many flags")

        if isinstance(default, (list, tuple, set, frozenset)):
            new_value = 0
            for flag in default:
                new_value |= Bit(flags.index(flag))
            default = new_value

        BigIntegerField.__init__(self, default=default, *args, **kwargs)
        self.flags = flags
示例#17
0
 def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
     if isinstance(getattr(value, 'expression', None), Bit):
         value = value.expression
     if isinstance(value, (BitHandler, Bit)):
         if hasattr(self, 'class_lookups'):
             # Django 1.7+
             return [value.mask]
         else:
             return BitQueryLookupWrapper(self.model._meta.db_table, self.db_column or self.name, value)
     return BigIntegerField.get_db_prep_lookup(self, lookup_type=lookup_type, value=value,
                                               connection=connection, prepared=prepared)
示例#18
0
 def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
     if isinstance(getattr(value, 'expression', None), Bit):
         value = value.expression
     if isinstance(value, (BitHandler, Bit)):
         if hasattr(self, 'class_lookups'):
             # Django 1.7+
             return [value.mask]
         else:
             return BitQueryLookupWrapper(self.model._meta.db_table, self.db_column or self.name, value)
     return BigIntegerField.get_db_prep_lookup(self, lookup_type=lookup_type, value=value,
                                               connection=connection, prepared=prepared)
示例#19
0
    def get_db_prep_lookup(self,
                           lookup_type,
                           value,
                           connection,
                           prepared=False):
        if isinstance(value, (BitHandler, Bit)):
            raise NotImplementedError(
                "get_db_prep_lookup not supported with types Bit, BitHandler")

        return BigIntegerField.get_db_prep_lookup(self,
                                                  lookup_type=lookup_type,
                                                  value=value,
                                                  connection=connection,
                                                  prepared=prepared)
示例#20
0
class BlogInfo(Model):
    id = OneToOneField(
        to=Blog,
        on_delete=CASCADE,  # 级联删除
        db_constraint=False,  # False表示逻辑外键
        db_column='id',
        primary_key=True,
        related_name='info',  # 默认类名全小写
        verbose_name='ID',
    )
    views = BigIntegerField(null=False,
                            default=0,
                            blank=True,
                            verbose_name='访问量')
示例#21
0
class HOTPDevice(Device):
    """
    HOTP Device implementation.

    Uses the HOTP algorithm to generate a one time password with a
    counter as variable factor.
    """

    secret = EncryptedField(max_length=255,
                            editable=False,
                            default=_generate_secret)

    counter = BigIntegerField(default=0)

    @property
    def authenticator_url(self):
        """
        Generate a URL for google authenticator.

        This URL could be shared by a QR-code.

        NOTE: According to the wiki are some fields ignored by the current
        version (5.00) of authenticator:

            - digits (on android and blackberry)
            - algorithm

        see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format

        :return: A URI that can be synchronised with google authenticator
        :rtype: str
        """
        label = urllib.parse.quote(self.user.get_username())

        digits = multi_factor_settings.HOTP_DIGITS
        issuer = multi_factor_settings.HOTP_ISSUER
        digest = multi_factor_settings.HOTP_ALGORITHM()

        issuer = urllib.parse.quote(issuer)

        params = urllib.parse.urlencode({
            "issuer": issuer,
            "digits": digits,
            "secret": base64.b32encode(self.secret),
            "counter": self.counter,
            "algorithm": digest.name.upper(),
        })

        return urllib.parse.urlunparse(
            ("otpauth", "hotp", label, None, params, None))
示例#22
0
class ADSBInfo(models.Model):

    collectorKey = models.CharField(max_length=64,
                                    blank=True,
                                    null=True,
                                    default="")

    modeSCode = CharField(max_length=16, blank=True, null=True, default="")
    callsign = CharField(max_length=16, blank=True, null=True, default="")

    # Airplane position
    latitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)
    longitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)
    altitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)

    # Airplane velocity
    verticalVelocity = DecimalField(max_digits=20,
                                    decimal_places=10,
                                    default=0.0)
    horizontalVelocity = DecimalField(max_digits=20,
                                      decimal_places=10,
                                      default=0.0)

    # Airplane angle
    groundTrackHeading = DecimalField(max_digits=20,
                                      decimal_places=10,
                                      default=0.0)

    # Observation date time generated by server
    timestamp = BigIntegerField(default=0)
    timestampSent = BigIntegerField(default=0)

    # Originals ADS-B messages
    messageDataId = CharField(max_length=100, blank=True, default='')
    messageDataPositionEven = CharField(max_length=100, blank=True, default='')
    messageDataPositionOdd = CharField(max_length=100, blank=True, default='')
    messageDataVelocity = CharField(max_length=100, blank=True, default='')
示例#23
0
 def get_db_prep_lookup(self,
                        lookup_type,
                        value,
                        connection,
                        prepared=False):
     if isinstance(value, SQLEvaluator) and isinstance(
             value.expression, Bit):
         value = value.expression
     if isinstance(value, Bit):
         return BitQueryLookupWrapper(self.model._meta.db_table, self.name,
                                      value)
     return BigIntegerField.get_db_prep_lookup(self,
                                               lookup_type=lookup_type,
                                               value=value,
                                               connection=connection,
                                               prepared=prepared)
示例#24
0
class Img(Model):
    id = BigAutoField(verbose_name='ID', primary_key=True)
    md5 = CharField(verbose_name='MD5', max_length=32, null=False)
    src = CharField(
        verbose_name='路径',
        max_length=255,
        null=False,
    )
    is_deleted = BooleanField(verbose_name='已经删除',
                              null=False,
                              default=False,
                              blank=True)
    size = IntegerField(verbose_name='体积(Byte)', null=False)
    updater = BigIntegerField(null=False, verbose_name='作者账号')  # user外键
    create_time = DateTimeField(null=False,
                                verbose_name='创建时间',
                                auto_now_add=True)
示例#25
0
class Admin(Model):
    user = OneToOneField(User, on_delete=PROTECT)
    telegram_id = BigIntegerField(blank=True, null=True)

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None):
        if not self.user.is_superuser:
            raise Exception("None superuser cannot be admin")
        super().save(force_insert, force_update, using, update_fields)

    def __repr__(self):
        return self.user.get_full_name()

    def __str__(self):
        return self.__repr__()
示例#26
0
class DNSPublication(Model):
    """A row in this table denotes a DNS publication request.

    Typically this will be populated by a trigger within the database. A
    listeners in regiond will be notified and consult the most recent record
    in this table. This way we can consistently publish zones with the same
    serial in an HA environment, and newly starting regiond processes can
    immediately be consistent with their peers.
    """

    class Meta(DefaultMeta):
        """Needed for South to recognize this model."""

    objects = DNSPublicationManager()

    # The serial number with which to publish the zone. We don't use the
    # primary key for this because zone serials are allowed to cycle.
    serial = BigIntegerField(
        editable=False,
        null=False,
        default=next_serial,
        unique=False,
        validators=(
            MinValueValidator(zone_serial.minvalue),
            MaxValueValidator(zone_serial.maxvalue),
        ),
    )

    # This field is informational.
    created = DateTimeField(
        editable=False, null=False, auto_now=False, auto_now_add=True
    )

    # This field is informational.
    source = CharField(
        editable=False,
        max_length=255,
        null=False,
        blank=True,
        help_text="A brief explanation why DNS was published.",
    )
示例#27
0
class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('phone_number', 'affiliations')
    # apparently, for regular forms (i.e. not ModelForms), you have to use
    # 'required' as an option and not 'blank'
    affiliations = forms.CharField(max_length=100, required=False)
    # TODO: figure out how the F**K to make phone_number, or more specifically,
    # IntegerField() to be null
    
    phone_number = BigIntegerField(null=True, blank=True)

    def save(self, commit=True):
        profile = super().save(commit=False)

        profile.affiliations = self.cleaned_data['affiliations']
        profile.phone_number = self.cleaned_data['phone_number']

        if commit:
            profile.save()
        return profile
示例#28
0
class Usuario(models.Model):
    nombre = CharField(max_length=255, null=True, blank=True)
    mac = CharField(max_length=17,
                    unique=True,
                    validators=[
                        validate_MAC,
                    ],
                    null=True,
                    blank=True)
    fecha_registro = DateTimeField(null=True, blank=True)
    responsable = models.ForeignKey(Responsable, null=True, blank=True)
    telefono = CharField(max_length=255, null=True, blank=True)
    zona = models.ForeignKey(Zona, null=True, blank=True)
    tipo = models.ForeignKey(TipoDeEquipo, null=True, blank=True)
    ip = GenericIPAddressField(unique=True)
    ip_int = BigIntegerField(default=0)

    def __str__(self):
        if self.nombre:
            return self.nombre + '(' + self.ip + ')'
        else:
            return self.ip
示例#29
0
class Comment(Model):
    id = BigAutoField(verbose_name='ID', primary_key=True)
    article = ForeignKey(
        to=Blog,
        db_column='article',
        db_constraint=False,
        on_delete=DO_NOTHING,
        related_name='comment',
    )
    text = CharField(max_length=255,
                     null=False,
                     blank=False,
                     verbose_name='内容')
    status = CharField(max_length=1,
                       choices=(('p', '通过'), ('u', '等待审核'), ('b', '审核未通过')),
                       null=False,
                       blank=False,
                       verbose_name='审核状态',
                       default='u')
    author = BigIntegerField(null=False, verbose_name='作者账号')  # user外键
    create_time = DateTimeField(null=False,
                                verbose_name='创建时间',
                                auto_now_add=True)
    deleted = BooleanField(null=False, default=False, verbose_name='已经删除')
示例#30
0
class APIHits(models.Model):
    count = BigIntegerField()
示例#31
0
 def contribute_to_class(self, cls, name):
     BigIntegerField.contribute_to_class(self, cls, name)
     setattr(cls, self.name, BitFieldCreator(self))
示例#32
0
 def __init__(self, flags,  *args, **kwargs):
     kwargs['choices']= enumerate(x for x in flags)
     
     BigIntegerField.__init__(self, *args, **kwargs)
     self.flags = flags
示例#33
0
 def __init__(self, flags, *args, **kwargs):
     BigIntegerField.__init__(self, *args, **kwargs)
     self.flags = flags
示例#34
0
 def test_BigIntegerField(self):
     # NOQA: long undefined on PY3
     lazy_func = lazy(lambda: long(9999999999999999999), long)  # NOQA
     self.assertIsInstance(BigIntegerField().get_prep_value(lazy_func()),
                           long)  # NOQA
示例#35
0
 def contribute_to_class(self, cls, name):
     BigIntegerField.contribute_to_class(self, cls, name)
     setattr(cls, self.name, BitFieldCreator(self))
示例#36
0
def auto_to_integer(field):
    _field = BigIntegerField()
    _field.name = field.attname
    _field.db_index = field.db_index
    _field.verbose_name = field.verbose_name
    _field.db_column = field.db_column
    _field.db_tablespace = field.db_tablespace
    _field.primary_key = field.primary_key
    _field.serialize = field.serialize
    _field.null = field.null
    _field._unique = field._unique
    _field.unique_for_date = field.unique_for_date
    _field.unique_for_month = field.unique_for_month
    _field.unique_for_year = field.unique_for_year

    return _field
示例#37
0
 def __init__(self, flags, *args, **kwargs):
     BigIntegerField.__init__(self, *args, **kwargs)
     self.flags = flags
示例#38
0
 def test_BigIntegerField(self):
     self.assertIsInstance(
         BigIntegerField().get_prep_value(long(9999999999999999999)), long)
示例#39
0
 def test_BigIntegerField(self):
     lazy_func = lazy(lambda: long(9999999999999999999), long)
     self.assertIsInstance(BigIntegerField().get_prep_value(lazy_func()),
                           long)
示例#40
0
class Favorite(Model):
    id = BigAutoField(verbose_name='ID', primary_key=True)
    user_id = BigIntegerField(null=False, verbose_name='被粉ID')  # user外键
    fan_id = BigIntegerField(null=False, verbose_name='粉丝ID')  # user外键