Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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)
Exemplo n.º 4
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
Exemplo n.º 5
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)
Exemplo n.º 6
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='已经删除')
Exemplo n.º 7
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))
Exemplo n.º 8
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='访问量')
Exemplo n.º 9
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='')
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
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__()
Exemplo n.º 13
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.",
    )
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
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='已经删除')
Exemplo n.º 17
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
Exemplo n.º 18
0
class Observation(models.Model):

    flight = ForeignKey(Flight,
                        null=True,
                        blank=True,
                        default=None,
                        related_name='observations')
    adsbInfo = OneToOneField(ADSBInfo, related_name="observation", null=True)

    # 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)

    simulated = BooleanField(default=False)

    def __unicode__(self):
        return "Observation of flight " + str(self.flight.code)

    @staticmethod
    def generateFromADSBInfo(info):
        # If the flight no exists, will be created

        collector = None
        try:
            collector = Collector.objects.get(key=info.collectorKey)
        except Exception as err:
            print err
            print info.collectorKey
            return None

        callsign = info.callsign
        airlineICAO = callsign[:3]
        airline = None
        flight = None
        try:
            airline = Airline.objects.get(icao=airlineICAO)
        except:
            pass

        try:
            flight = Flight.objects.get(code=callsign)
        except Flight.DoesNotExist:
            flight = Flight(code=callsign, airline=airline)
            flight.save()

        delay = info.timestampSent - info.timestamp
        timestamp = int(time() * 1000) - delay

        # Set a correct longitude
        if info.longitude > 180:
            info.longitude -= 360
        info.save()

        collector.timestampData = timestamp
        collector.save()

        obs = Observation(flight=flight,
                          adsbInfo=info,
                          timestamp=timestamp,
                          latitude=info.latitude,
                          longitude=info.longitude,
                          altitude=info.altitude,
                          verticalVelocity=info.verticalVelocity,
                          horizontalVelocity=info.horizontalVelocity,
                          groundTrackHeading=info.groundTrackHeading)
        obs.save()
        return obs
Exemplo n.º 19
0
 def test_BigIntegerField(self):
     self.assertIsInstance(
         BigIntegerField().get_prep_value(long(9999999999999999999)), long)
Exemplo n.º 20
0
 def test_BigIntegerField(self):
     lazy_func = lazy(lambda: long(9999999999999999999), long)
     self.assertIsInstance(BigIntegerField().get_prep_value(lazy_func()),
                           long)
Exemplo n.º 21
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外键
Exemplo n.º 22
0
class FlightInfo(models.Model):
    # Flight identification
    flight = OneToOneField(Flight, null=True)
    airline = ForeignKey(Airline, null=True)

    # 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)

    @staticmethod
    def generateFromFlight(flight, obs):
        info = None
        try:
            info = FlightInfo.objects.get(flight=flight)
            info.latitude = obs.latitude
            info.longitude = obs.longitude
            info.altitude = obs.altitude
            info.verticalVelocity = obs.verticalVelocity
            info.horizontalVelocity = obs.horizontalVelocity
            info.groundTrackHeading = obs.groundTrackHeading
            info.timestamp = obs.timestamp
        except FlightInfo.DoesNotExist:
            info = FlightInfo(flight=flight,
                              airline=flight.airline,
                              latitude=obs.latitude,
                              longitude=obs.longitude,
                              altitude=obs.altitude,
                              verticalVelocity=obs.verticalVelocity,
                              horizontalVelocity=obs.horizontalVelocity,
                              groundTrackHeading=obs.groundTrackHeading,
                              timestamp=obs.timestamp)

        info.save()

    def generatePropagatedTrajectory(self, propCount, propInterval):

        observations = Observation.objects.filter(flight=self.flight).filter(
            simulated=True)
        for o in observations:
            o.delete()

        observations = Observation.objects.filter(
            flight=self.flight).order_by("-timestamp")[0:2]
        obs = []
        for o in observations:
            obs.append(o)
        obs.reverse()
        propInterval /= 1000.0

        for i in range(0, int(propCount)):
            infoA = obs[len(obs) - 2]
            infoB = obs[len(obs) - 1]

            turnRateInterval = (float(infoB.timestamp) -
                                float(infoA.timestamp)) / 1000.0
            turnRate = 0 if turnRateInterval == 0 \
                else propInterval * (float(infoB.groundTrackHeading) - float(infoA.groundTrackHeading))/turnRateInterval
            groundTrackHeading = float(infoB.groundTrackHeading) + turnRate
            distance = Math.knotsToMetres(float(
                infoB.horizontalVelocity)) * propInterval
            R = 6371000.0
            lat1 = Math.degreesToRadians(float(infoB.latitude))
            lng1 = Math.degreesToRadians(float(infoB.longitude))
            bearing = Math.degreesToRadians(float(infoB.groundTrackHeading))

            lat2 = Math.radiansToDegrees(
                math.asin(
                    math.sin(lat1) * math.cos(distance / R) + math.cos(lat1) *
                    math.sin(distance / R) * math.cos(bearing)))

            lng2 = Math.radiansToDegrees(lng1 + math.atan2(
                math.sin(bearing) * math.sin(distance / R) * math.cos(lat1),
                math.cos(distance / R) - math.sin(lat1) * math.sin(lat2)))

            alt = float(infoB.altitude) + (float(infoB.verticalVelocity) *
                                           propInterval)

            newObs = Observation()

            newObs.flight = self.flight
            newObs.latitude = lat2
            newObs.longitude = lng2
            newObs.altitude = alt
            newObs.groundTrackHeading = groundTrackHeading
            newObs.verticalVelocity = infoB.verticalVelocity
            newObs.horizontalVelocity = infoB.horizontalVelocity
            newObs.timestamp = float(infoB.timestamp) + int(
                propInterval * 1000)
            newObs.simulated = True
            obs.append(newObs)
            newObs.save()

        return obs[2:]
Exemplo n.º 23
0
class APIHits(models.Model):
    count = BigIntegerField()