Esempio n. 1
0
class StopTime(models.Model):
    trip = models.ForeignKey(Trip, models.CASCADE)
    stop_code = models.CharField(max_length=255)
    arrival = models.DurationField()
    departure = models.DurationField()
    sequence = models.PositiveSmallIntegerField()
    timing_status = models.CharField(max_length=3, blank=True)
    activity = models.CharField(max_length=16, blank=True)

    class Meta:
        ordering = ('sequence', )
        index_together = (('stop_code', 'departure'), )
Esempio n. 2
0
class Trip(models.Model):
    route = models.ForeignKey(Route, models.CASCADE)
    inbound = models.BooleanField(default=False)
    journey_pattern = models.CharField(max_length=255, blank=True)
    destination = models.ForeignKey('busstops.StopPoint',
                                    models.SET_NULL,
                                    null=True,
                                    blank=True)
    calendar = models.ForeignKey(Calendar, models.CASCADE)
    sequence = models.PositiveSmallIntegerField(null=True, blank=True)
    notes = models.ManyToManyField(Note, blank=True)
    start = models.DurationField()
    end = models.DurationField()

    def __str__(self):
        return f'{self.start}'

    class Meta:
        index_together = (('route', 'start', 'end'), )

    def __cmp__(a, b):
        """Compare two journeys"""
        if a.sequence is not None and a.sequence is not None:
            a_time = a.sequence
            b_time = b.sequence
        else:
            a_time = a.start
            b_time = b.start
            a_times = a.stoptime_set.all()
            b_times = b.stoptime_set.all()
            if a_times[0].get_key() != b_times[0].get_key():
                if a.destination_id == b.destination_id:
                    a_time = a.end
                    b_time = b.end
                else:
                    times = {
                        time.get_key(): time.arrival or time.departure
                        for time in a_times
                    }
                    for time in b_times:
                        key = time.get_key()
                        if key in times:
                            a_time = times[key]
                            b_time = time.arrival or time.departure
                            break
        if a_time > b_time:
            return 1
        if a_time < b_time:
            return -1
        return 0

    def __repr__(self):
        return str(self.start)
Esempio n. 3
0
class Session(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    created_at = models.DateTimeField(editable=False, auto_now_add=True)

    started_at = models.DateTimeField(blank=True, null=True)
    submit_before = models.DateTimeField(blank=True, null=True)
    duration = models.DurationField(default=timedelta(
        seconds=SESSION_DURATION))

    questionnaire = models.ForeignKey('Questionnaire',
                                      on_delete=models.CASCADE,
                                      related_name='+')
    frozen = models.BooleanField(default=False)
    _signal = models.ForeignKey('signals.Signal',
                                on_delete=models.CASCADE,
                                null=True)

    objects = SessionManager()

    @property
    def is_expired(self):
        return ((self.submit_before and self.submit_before < timezone.now())
                or (self.started_at
                    and self.started_at + self.duration < timezone.now()))

    @property
    def too_late(self):
        return not self.frozen or self.is_expired
Esempio n. 4
0
class Weapon(models.Model):
    country = models.ForeignKey('world.WorldBorder', on_delete=models.CASCADE, default=DEFAULT_COUNTRY_ID)
    wave = models.ForeignKey(Wave, on_delete=models.CASCADE, default=DEFAULT_WAVE_ID)
    page_display_name = models.CharField(max_length=200)
    true_launch_location = models.PointField(default=DEFAULT_POINT)
    observed_launch_location = models.PointField(null=True, blank=True)
    observed_launch_country = models.ForeignKey('world.WorldBorder', null=True, blank=True, on_delete=models.CASCADE, related_name='+')
    launch_delta = models.DurationField(default=DEFAULT_DURATION)

    def __str__(self):
        return f'{self.page_display_name} - {self.pk}'

    def launch_location(self):
        if self.observed_launch_location is None:
            return self.true_launch_location
        else:
            return self.observed_launch_location

    def launch_datetime(self):
        return self.wave.start_datetime() + self.launch_delta

    def launch_country(self):
        if self.observed_launch_country is None:
            return self.country
        else:
            return self.observed_launch_country
Esempio n. 5
0
class ManagementAction(models.Model):
    FULL_DESTRUCTION_NO_DEBRIS = 'FD'
    PARTIAL_DESTRUCTION_DEBRIS_LEFT = 'PD'
    EMPTY_NEST_NOTHING_DONE = 'ND'

    OUTCOME_CHOICE = (
        (FULL_DESTRUCTION_NO_DEBRIS, _('Full destruction, no debris')),
        (PARTIAL_DESTRUCTION_DEBRIS_LEFT,
         _('Partial destruction/debris left')),
        (EMPTY_NEST_NOTHING_DONE, _('Empty nest, nothing done')),
    )

    nest = models.ForeignKey(Nest, on_delete=models.CASCADE)
    outcome = models.CharField(max_length=2, choices=OUTCOME_CHOICE)
    action_time = models.DateTimeField()
    person_name = models.CharField(max_length=255, blank=True)
    duration = models.DurationField(null=True, blank=True)

    @property
    def duration_in_seconds(self):
        try:
            return self.duration.total_seconds()  # Positive val, but also 0!
        except AttributeError:
            return ''  # NULL

    @property
    def finished(self):
        return self.outcome in (self.FULL_DESTRUCTION_NO_DEBRIS,
                                self.EMPTY_NEST_NOTHING_DONE)

    def __str__(self):
        return f'{self.action_time.strftime("%Y-%m-%d")} {self.get_outcome_display()}'
Esempio n. 6
0
class OrderType(models.Model):
    TYPE0 = 0
    TYPE1 = 1
    TYPE2 = 2
    TYPE3 = 3
    TYPE4 = 4
    ORDER_TYPES = (
        (TYPE0, 'None'),
        (TYPE1, 'Subscription'),
        (TYPE2, 'Overnight'),
        (TYPE3, 'Day Delivery'),
        (TYPE4, 'Hotshot'),
    )
    name = models.IntegerField(choices=ORDER_TYPES, default=TYPE0)
    duration = models.DurationField(null=True, blank=True)
    delivery_datetime = models.DateTimeField(auto_created=False,
                                             auto_now=False,
                                             auto_now_add=False,
                                             null=True,
                                             blank=True)
    price = models.DecimalField(max_digits=10,
                                decimal_places=2,
                                default=0.00,
                                null=True,
                                blank=True)  # TODO: use MoneyField if needed
    tags = TaggableManager(blank=True)

    def __str__(self):
        return "{0}: ${1}".format(self.ORDER_TYPES[self.name][1], self.price)

    def get_name_display(self):
        return self.ORDER_TYPES[self.name[1]]
Esempio n. 7
0
class Scenario(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)
    exercise_start = models.DateTimeField(default=datetime.datetime.now)
    scenario_start = models.DurationField(default=0)

    def __str__(self):
        return self.name
Esempio n. 8
0
class GanttTask(models.Model):
    name = models.CharField(max_length=32)
    start_date = models.DateField()
    duration = models.DurationField()
    progress = models.IntegerField()

    def __str__(self):
        return self.name
Esempio n. 9
0
class Event(models.Model):
    """
    Meeting or hearing associated with a proposal.
    """
    title = models.CharField(max_length=256, db_index=True)
    date = models.DateTimeField(db_index=True)
    duration = models.DurationField(null=True)
    description = models.TextField()
    proposals = models.ManyToManyField(Proposal, related_name="proposals")
Esempio n. 10
0
class Event(models.Model):
    """
    Meeting or hearing associated with a proposal.
    """
    title = models.CharField(max_length=256)
    date = models.DateTimeField()
    duration = models.DurationField(null=True)
    description = models.TextField()
    proposal = models.ForeignKey(Proposal)
Esempio n. 11
0
class Wave(models.Model):
    scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    start_delta = models.DurationField(default=DEFAULT_DURATION)

    def __str__(self):
        return f'{self.name} for {self.scenario.name}'

    def start_datetime(self):
        return self.scenario.exercise_start + self.start_delta
Esempio n. 12
0
class StopTime(models.Model):
    id = models.BigAutoField(primary_key=True)
    trip = models.ForeignKey(Trip, models.CASCADE)
    stop_code = models.CharField(max_length=255, blank=True)
    stop = models.ForeignKey('busstops.StopPoint',
                             models.SET_NULL,
                             null=True,
                             blank=True)
    arrival = models.DurationField()
    departure = models.DurationField()
    sequence = models.PositiveSmallIntegerField()
    timing_status = models.CharField(max_length=3, blank=True)
    activity = models.CharField(max_length=16, blank=True)

    def get_key(self):
        return self.stop_id or self.stop_code

    class Meta:
        ordering = ('sequence', )
        index_together = (('stop', 'departure'), )
Esempio n. 13
0
class Importer(models.Model):
    """Importers are created through the administrator interface. Cornerwise
    will place a GET request to the importer's URL once a day with a `when`
    query parameter. The endpoint should return a result conforming to the
    format documented in `docs/scraper-schema.json`.
    """
    name = models.CharField(max_length=128,
                            unique=True,
                            help_text="""Readable name that will be used
                            to identify the origin of the proposals. """)
    region_name = models.CharField(max_length=128,
                                   blank=True,
                                   help_text="""Default region name, used when
                                   a proposal in the response JSON does not
                                   have one set.""")
    timezone = models.CharField(default="US/Eastern", max_length=25,
                                help_text="""Ambiguous date fields will be
                                interpreted as having this timezone""")
    url = models.URLField(help_text="""A URL endpoint that should accept a
    `when` parameter of the format YYYYmmdd and should respond with a JSON
    document conforming to the scraper-schema spec.""")
    run_frequency = models.DurationField(
        help_text="""Specifies how often the scraper should run. Effectively
    rounds up to the next day, so values of '3 days' and '2 days, 3 hours' are
    the same.""",
        default=timedelta(days=1),
        validators=[MinValueValidator(timedelta(days=1))])
    last_run = models.DateTimeField(help_text="Last time the scraper ran",
                                    null=True)

    @staticmethod
    def validate(data, schema=None):
        """Validates data against the JSON schema for Cornerwise importers.
        """
        return jsonschema.validate(data, schema or get_importer_schema())

    def __str__(self):
        return self.name

    @property
    def tz(self):
        return pytz.timezone(self.timezone)

    def url_for(self, since=None):
        params = since and {"since": since.strftime("%Y%m%d")}
        return utils.add_params(self.url, params)

    def updated_since(self, when=None):
        with request.urlopen(self.url_for(when)) as u:
            return json.load(u)

    def cases_since(self, when):
        return self.updated_since(when).get("cases", [])
Esempio n. 14
0
class Process(models.Model):
    name = models.CharField(max_length=256, unique=True)
    function = models.ForeignKey(Function,
                                 on_delete=models.PROTECT,
                                 null=True,
                                 blank=True)
    mtd = models.DurationField(
        help_text="Maximum Tolerable Downtime (days hh:mm:ss)",
        default=timedelta(days=14))
    rto = models.DurationField(
        help_text="Recovery Time Objective (days hh:mm:ss)",
        default=timedelta(days=7))
    rpo = models.DurationField(
        help_text="Recovery Point Objective/Data Loss Interval (days hh:mm:ss)",
        default=timedelta(hours=24))
    users = models.PositiveSmallIntegerField(default=1)

    #TODO: Add validation for durationfields

    def __str__(self):
        return self.name
Esempio n. 15
0
class MonitoringRun(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('Monitoring run'))
    start = models.DateTimeField(null=True, blank=True)
    end = models.DateTimeField(null=True, blank=True)
    duration = models.DurationField(null=True, blank=True)
    metadatas = models.ManyToManyField('service.Metadata', related_name='monitoring_runs', verbose_name=_('Checked resources'))

    class Meta:
        ordering = ["-end"]
        verbose_name = _('Monitoring run')
        verbose_name_plural = _('Monitoring runs')

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

    @property
    def icon(self):
        return Tag(tag='i', attrs={"class": [IconEnum.MONITORING_RUN.value]}).render()

    @classmethod
    def get_add_action(cls):
        return LinkButton(content=Tag(tag='i', attrs={"class": [IconEnum.ADD.value]}) + _(' New run').__str__(),
                          color=ButtonColorEnum.SUCCESS,
                          url=reverse('monitoring:run_new'),
                          needs_perm=PermissionEnum.CAN_RUN_MONITORING.value)

    def get_absolute_url(self):
        return f"{reverse('monitoring:run_overview')}?uuid={self.uuid}"

    @property
    def result_view_uri(self):
        results = self.monitoring_results.all()
        if results:
            querystring = ""
            for is_last_element, result in signal_last(results):
                if is_last_element:
                    querystring += f"monitoring_run_uuid={result.pk}"
                else:
                    querystring += f"monitoring_run_uuid={result.pk}&"
            return f"{reverse('monitoring:result_overview')}?{querystring}"
        else:
            return None

    @property
    def add_view_uri(self):
        return reverse('monitoring:run_new')

    @transaction.atomic
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        super().save(force_insert, force_update, using, update_fields)
        from monitoring.tasks import run_manual_monitoring
        run_manual_monitoring.delay(monitoring_run=self.pk)
Esempio n. 16
0
class Trip(models.Model):
    route = models.ForeignKey(Route, models.CASCADE)
    inbound = models.BooleanField(default=False)
    journey_pattern = models.CharField(max_length=255, blank=True)
    destination = models.ForeignKey('busstops.StopPoint', models.CASCADE)
    calendar = models.ForeignKey(Calendar, models.CASCADE)
    sequence = models.PositiveSmallIntegerField(null=True, blank=True)
    notes = models.ManyToManyField(Note, blank=True)
    start = models.DurationField()
    end = models.DurationField()

    class Meta:
        index_together = (('route', 'start', 'end'), )

    def cmp(a, b):
        """Compare two journeys"""
        # if x.sequencenumber is not None and y.sequencenumber is not None:
        #     if x.sequencenumber > y.sequencenumber:
        #         return 1
        #     if x.sequencenumber < y.sequencenumber:
        #         return -1
        #     return 0
        a_times = a.stoptime_set.all()
        b_times = b.stoptime_set.all()
        a_time = a_times[0].arrival
        b_time = b_times[0].arrival
        if a_times[0].stop_code != b_times[0].stop_code:
            times = {time.stop_code: time.arrival for time in a_times}
            for time in b_times:
                if time.stop_code in times:
                    if time.arrival >= b_time:
                        if times[time.stop_code] >= a_time:
                            a_time = times[time.stop_code]
                            b_time = time.arrival
        #             break
        if a_time > b_time:
            return 1
        if b_time < a_time:
            return -1
        return 0
Esempio n. 17
0
class MonitoringRun(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('Monitoring run'))
    start = models.DateTimeField(null=True, blank=True)
    end = models.DateTimeField(null=True, blank=True)
    duration = models.DurationField(null=True, blank=True)
    metadatas = models.ManyToManyField('service.Metadata', related_name='monitoring_runs', verbose_name=_('Checked resources'))

    class Meta:
        ordering = ["-end"]
        verbose_name = _('Monitoring run')
        verbose_name_plural = _('Monitoring runs')

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

    @property
    def icon(self):
        return Tag(tag='i', attrs={"class": [IconEnum.MONITORING_RUN.value]}).render()

    @classmethod
    def get_add_action(cls):
        return LinkButton(content=Tag(tag='i', attrs={"class": [IconEnum.ADD.value]}) + _(' New run').__str__(),
                          color=ButtonColorEnum.SUCCESS,
                          url=reverse('monitoring:run_new'),
                          needs_perm=PermissionEnum.CAN_RUN_MONITORING.value)

    def get_absolute_url(self):
        return f"{reverse('monitoring:run_overview')}?uuid={self.uuid}"

    @property
    def result_view_uri(self):
        results = self.monitoring_results.all()
        if results:
            querystring = ""
            for is_last_element, result in signal_last(results):
                if is_last_element:
                    querystring += f"monitoring_run_uuid={result.pk}"
                else:
                    querystring += f"monitoring_run_uuid={result.pk}&"
            return f"{reverse('monitoring:result_overview')}?{querystring}"
        else:
            return None

    @property
    def add_view_uri(self):
        return reverse('monitoring:run_new')

    def save(self, *args, **kwargs):
        if self._state.adding:
            from monitoring.tasks import run_manual_service_monitoring
            transaction.on_commit(lambda: run_manual_service_monitoring.apply_async(args=(self.pk, ), countdown=settings.CELERY_DEFAULT_COUNTDOWN))
        super().save(*args, **kwargs)
Esempio n. 18
0
class JourneyPatternTimingLink(models.Model):
    id = models.CharField(max_length=255, primary_key=True, db_index=True)
    stop_from = models.ForeignKey(Stop,
                                  related_name='departure_journeys',
                                  on_delete=models.CASCADE)
    stop_from_timing_status = models.CharField(max_length=3)
    stop_from_sequence_number = models.IntegerField()
    stop_to = models.ForeignKey(Stop,
                                related_name='arrival_journeys',
                                on_delete=models.CASCADE)
    stop_to_timing_status = models.CharField(max_length=3)
    stop_to_sequence_number = models.IntegerField()
    run_time = models.DurationField()
    wait_time = models.DurationField(null=True, blank=True)
    journey_pattern_section = models.ForeignKey(JourneyPatternSection,
                                                related_name='timing_links',
                                                on_delete=models.CASCADE)
    last_modified = models.DateTimeField(auto_now=True)

    @python_2_unicode_compatible
    def __str__(self):
        return "%s - %s (%s)" % (self.stop_from, self.stop_to, self.run_time)
Esempio n. 19
0
class Session(models.Model):
    """
    Sessions keep track of incoming answers and store them after questionnaire
    is finished.
    """
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    created_at = models.DateTimeField(editable=False, auto_now_add=True)

    started_at = models.DateTimeField(blank=True, null=True)
    submit_before = models.DateTimeField(blank=True, null=True)
    duration = models.DurationField(
        default=timedelta(seconds=SESSION_DURATION), blank=True, null=True)

    questionnaire = models.ForeignKey('Questionnaire',
                                      on_delete=models.CASCADE,
                                      related_name='+')
    frozen = models.BooleanField(default=False)
    _signal = models.ForeignKey('signals.Signal',
                                on_delete=models.CASCADE,
                                blank=True,
                                null=True)

    objects = SessionManager()

    @property
    def is_expired(self):
        """
        Check overall deadline and maximum duration for filling out for expiry.

        Both overall deadline, called `submit_before`, and maximum duration that
        can be taken to fill out a questionnaire are considered (either or both)
        can take a None value. The submission deadline is not extended with
        the value of duration. So if you are allowed two hours to fill out the
        questionnaire, but start it 5 minutes before the submission deadline
        you will effectively only have 5 minutes to fill it out and submit it.

        If you want no deadline, set `submit_before` to None and set `duration`
        to None. If you only want to enforce the time taken to fill out the
        questionnaire set `submit_before` to None and `duration` to the
        desired duration.
        """
        return bool(
            (self.submit_before and self.submit_before < timezone.now())
            or (self.started_at and self.duration
                and self.started_at + self.duration < timezone.now()))

    @property
    def too_late(self):
        return not self.frozen and self.is_expired
Esempio n. 20
0
class Person(models.Model):
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    #  Jards Macalé is an amazing brazilian musician! =]
    enjoy_jards_macale = models.BooleanField(default=True)
    like_metal_music = models.BooleanField(default=False)
    name = models.CharField(max_length=30)
    nickname = models.SlugField(max_length=36)
    age = models.IntegerField()
    bio = models.TextField()
    birthday = models.DateField()
    birth_time = models.TimeField()
    appointment = models.DateTimeField()
    blog = models.URLField()
    occupation = models.CharField(max_length=10, choices=OCCUPATION_CHOICES)
    uuid = models.UUIDField(primary_key=False)
    name_hash = models.BinaryField(max_length=16)
    days_since_last_login = models.BigIntegerField()
    duration_of_sleep = models.DurationField()
    email = models.EmailField()
    id_document = models.CharField(unique=True, max_length=10)

    try:
        from django.contrib.postgres.fields import ArrayField, HStoreField, JSONField
        from django.contrib.postgres.fields.citext import (
            CICharField,
            CIEmailField,
            CITextField,
        )

        acquaintances = ArrayField(models.IntegerField())
        data = JSONField()
        hstore_data = HStoreField()
        ci_char = CICharField(max_length=30)
        ci_email = CIEmailField()
        ci_text = CITextField()
    except ImportError:
        # Skip PostgreSQL-related fields
        pass

    if BAKER_GIS:
        geom = models.GeometryField()
        point = models.PointField()
        line_string = models.LineStringField()
        polygon = models.PolygonField()
        multi_point = models.MultiPointField()
        multi_line_string = models.MultiLineStringField()
        multi_polygon = models.MultiPolygonField()
        geom_collection = models.GeometryCollectionField()
Esempio n. 21
0
class ManagementAction(models.Model):
    PERMAS_D_PROF = 'PP'
    PERMAS_D_CLASSIC = 'PC'
    REMOVAL_COMPLETE = 'FD'  # previously "full destruction": possible cleanup: create a data migration so FD -> RC?
    REMOVAL_PARTIAL = 'PD'  # previously "partial destruction": possible cleanup: create a data migration so PD -> RP?
    NOT_TREATED = 'ND'  # previously "nothing done": : possible cleanup: create a data migration so ND -> NT?
    UNKNOWN = 'UK'

    OUTCOME_CHOICE = (
        (PERMAS_D_PROF, _('Professional permas-D treatment')),
        (PERMAS_D_CLASSIC, _('Classic permas-D treatment')),
        (REMOVAL_COMPLETE, _('Complete manual removal')),
        (REMOVAL_PARTIAL, _('Partial manual removal')),
        (NOT_TREATED, _('Not treated')),
        (UNKNOWN, _('Unknown')),
    )

    nest = models.OneToOneField(Nest,
                                on_delete=models.CASCADE,
                                primary_key=True)
    user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    outcome = models.CharField(verbose_name=_("Outcome"),
                               max_length=2,
                               choices=OUTCOME_CHOICE)
    action_time = models.DateTimeField(verbose_name=_("Date and time"))
    person_name = models.CharField(verbose_name=_("Reported by"),
                                   max_length=255,
                                   blank=True)
    duration = models.DurationField(verbose_name=_("Duration (in minutes)"),
                                    null=True,
                                    blank=True)
    number_of_persons = models.IntegerField(
        verbose_name=_("Number of persons"), null=True)
    comments = models.TextField(verbose_name=_("Comments"), blank=True)

    @property
    def duration_in_seconds(self):
        try:
            return self.duration.total_seconds()  # Positive val, but also 0!
        except AttributeError:
            return ''  # NULL

    def __str__(self):
        return f'{self.action_time.strftime("%Y-%m-%d")} {self.get_outcome_display()}'
Esempio n. 22
0
class Person(models.Model):
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    happy = models.BooleanField(default=True)
    unhappy = models.BooleanField(default=False)
    bipolar = models.BooleanField(default=False)
    name = models.CharField(max_length=30)
    nickname = models.SlugField(max_length=36)
    age = models.IntegerField()
    bio = models.TextField()
    birthday = models.DateField()
    birth_time = models.TimeField()
    appointment = models.DateTimeField()
    blog = models.URLField()
    occupation = models.CharField(max_length=10, choices=OCCUPATION_CHOICES)
    uuid = models.UUIDField(primary_key=False)
    name_hash = models.BinaryField(max_length=16)
    wanted_games_qtd = models.BigIntegerField()
    duration_of_sleep = models.DurationField()
    email = models.EmailField()

    try:
        from django.contrib.postgres.fields import ArrayField, HStoreField, JSONField
        from django.contrib.postgres.fields.citext import CICharField, CIEmailField, CITextField
        acquaintances = ArrayField(models.IntegerField())
        data = JSONField()
        hstore_data = HStoreField()
        ci_char = CICharField(max_length=30)
        ci_email = CIEmailField()
        ci_text = CITextField()
    except ImportError:
        # Skip PostgreSQL-related fields
        pass

    if MOMMY_GIS:
        geom = models.GeometryField()
        point = models.PointField()
        line_string = models.LineStringField()
        polygon = models.PolygonField()
        multi_point = models.MultiPointField()
        multi_line_string = models.MultiLineStringField()
        multi_polygon = models.MultiPolygonField()
        geom_collection = models.GeometryCollectionField()
Esempio n. 23
0
class Warhead(models.Model):
    weapon = models.ForeignKey(Weapon, on_delete=models.CASCADE, related_name='warheads')
    warhead_yield = models.FloatField()
    true_impact_location = models.PointField(default=DEFAULT_POINT)
    observed_impact_location = models.PointField(null=True, blank=True)
    observed_impact_country = models.ForeignKey('world.WorldBorder', null=True, blank=True, on_delete=models.CASCADE)
    impact_delta = models.DurationField(default=DEFAULT_DURATION)
    target_display_name = models.CharField(max_length=200, default=DEFAULT_TARGET_NAME)

    def __str__(self):
        return f'{self.warhead_yield} kt warhead - {self.pk}'

    def impact_datetime(self):
        return self.weapon.launch_datetime() + self.impact_delta

    def impact_location(self):
        if self.observed_impact_location is None:
            return self.true_impact_location
        else:
            return self.observed_impact_location
Esempio n. 24
0
class ManagementAction(models.Model):
    FULL_DESTRUCTION_NO_DEBRIS = 'FD'
    PARTIAL_DESTRUCTION_DEBRIS_LEFT = 'PD'
    EMPTY_NEST_NOTHING_DONE = 'ND'
    UNKNOWN = 'UK'

    OUTCOME_CHOICE = (
        (FULL_DESTRUCTION_NO_DEBRIS, _('Full destruction, no debris')),
        (PARTIAL_DESTRUCTION_DEBRIS_LEFT,
         _('Partial destruction/debris left')),
        (EMPTY_NEST_NOTHING_DONE, _('Empty nest, nothing done')),
        (UNKNOWN, _('Unknown')),
    )

    nest = models.OneToOneField(Nest,
                                on_delete=models.CASCADE,
                                primary_key=True)
    user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    outcome = models.CharField(verbose_name=_("Outcome"),
                               max_length=2,
                               choices=OUTCOME_CHOICE)
    action_time = models.DateTimeField(verbose_name=_("Date and time"))
    person_name = models.CharField(verbose_name=_("Reported by"),
                                   max_length=255,
                                   blank=True)
    duration = models.DurationField(verbose_name=_("Duration (in minutes)"),
                                    null=True,
                                    blank=True)
    number_of_persons = models.IntegerField(
        verbose_name=_("Number of persons"), null=True)
    comments = models.TextField(verbose_name=_("Comments"), blank=True)

    @property
    def duration_in_seconds(self):
        try:
            return self.duration.total_seconds()  # Positive val, but also 0!
        except AttributeError:
            return ''  # NULL

    def __str__(self):
        return f'{self.action_time.strftime("%Y-%m-%d")} {self.get_outcome_display()}'
Esempio n. 25
0
class ReminderTime(models.Model):
    """
    Set of time types for reminder.
    Super admin can change list of defaults time types.
    """
    class Meta:
        db_table = 'reminder_time_types'

    before = models.DurationField(blank=True)
    duration = models.PositiveIntegerField()
    time_type = models.CharField(max_length=10,
                                 choices=ReminderTimeType.choices(),
                                 default=ReminderTimeType.Minutes.value)
    is_default = models.BooleanField(default=False)

    def save(self, **kwargs):
        self.before = timedelta(**{self.time_type: self.duration})
        super(ReminderTime, self).save(**kwargs)

    def __str__(self):
        return "{} {}".format(self.duration, self.time_type)
Esempio n. 26
0
class MonitoringResult(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('Result'))
    metadata = models.ForeignKey('service.Metadata', on_delete=models.CASCADE, verbose_name=_('Resource'))
    timestamp = models.DateTimeField(auto_now_add=True)
    duration = models.DurationField(null=True, blank=True)
    status_code = models.IntegerField(null=True, blank=True)
    error_msg = models.TextField(null=True, blank=True)
    available = models.BooleanField(null=True)
    monitored_uri = models.CharField(max_length=2000)
    monitoring_run = models.ForeignKey(MonitoringRun, on_delete=models.CASCADE, related_name='monitoring_results')

    class Meta:
        ordering = ["-timestamp"]
        verbose_name = _('Monitoring result')
        verbose_name_plural = _('Monitoring results')

    @property
    def icon(self):
        return Tag(tag='i', attrs={"class": [IconEnum.MONITORING_RESULTS.value]}).render()

    def get_absolute_url(self):
        return reverse('monitoring:result_details', args=[self.uuid, ])
Esempio n. 27
0
class DataImport(BaseModel):
    start = models.DateTimeField()
    task = models.CharField(max_length=128)
    description = models.TextField(blank=True)
    optional_data = JSONField(blank=True, null=True)

    stop = models.DateTimeField(blank=True, null=True)
    duration = models.DurationField(blank=True, null=True)
    callsigns = models.PositiveIntegerField(default=0)
    new_callsigns = models.PositiveIntegerField(default=0)
    duplicated_callsigns = models.PositiveIntegerField(default=0)
    updated_callsigns = models.PositiveIntegerField(default=0)
    deleted_callsigns = models.PositiveIntegerField(default=0)
    invalid_callsigns = models.PositiveIntegerField(default=0)
    blacklisted_callsigns = models.PositiveIntegerField(default=0)
    errors = models.PositiveIntegerField(default=0)
    finished = models.BooleanField(default=False)
    failed = models.BooleanField(default=False)
    error_message = models.TextField(blank=True)

    def __str__(self) -> str:
        return f"{self.task}-{self.start}"
Esempio n. 28
0
class RecurringNotice(models.Model):

    title = models.CharField(max_length=80)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    description = models.TextField(blank=True, null=True)
    location = models.GeometryField()
    duration = models.DurationField()
    recurrences = RecurrenceField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    tags = HStoreField(blank=True, null=True)
    timezone = models.CharField(max_length=40,
                                choices=_get_timezones_as_tuple(),
                                blank=False)

    objects = models.GeoManager()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('recurring-notice-detail', args=[str(self.id)])
class DisturbanceStops(models.Model):
    opd_date = models.DateField(blank=True, null=True)
    service_key = models.TextField(blank=True, null=True)
    year = models.IntegerField(blank=True, null=True)
    month = models.IntegerField(blank=True, null=True)
    day = models.IntegerField(blank=True, null=True)
    day_of_week = models.IntegerField(blank=True, null=True)
    act_arr_time = models.DateTimeField(blank=True, null=True)
    act_dep_time = models.DateTimeField(blank=True, null=True)
    start_quarter_hour = models.FloatField(blank=True, null=True)
    end_quarter_hour = models.FloatField(blank=True, null=True)
    duration = models.DurationField(blank=True, null=True)
    line_id = models.IntegerField(blank=True, null=True)
    pattern_direction = models.TextField(blank=True, null=True)
    longitude = models.FloatField(blank=True, null=True)
    latitude = models.FloatField(blank=True, null=True)
    geom_point_4326 = models.PointField(blank=True, null=True)
    id = models.BigIntegerField(primary_key=True)

    class Meta:
        managed = False
        db_table = "disturbance_stops"
        unique_together = (("opd_date", "id"), )
Esempio n. 30
0
class Checklist(models.Model):
    id = models.IntegerField(
        primary_key=True)  # Strip the leading S off the checklist ID
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    location = models.ForeignKey('Location')
    complete_checklist = models.BooleanField()
    start_date_time = models.DateTimeField()
    checklist_comments = models.TextField(blank=True)
    number_of_observers = models.PositiveIntegerField(null=True)
    protocol = models.TextField()  # Later, choices?
    duration = models.DurationField(null=True, help_text='Duration in minutes')
    distance = models.DecimalField(decimal_places=6,
                                   max_digits=16,
                                   null=True,
                                   help_text='Distance in km')
    area = models.DecimalField(decimal_places=6,
                               max_digits=16,
                               null=True,
                               help_text='Area covered in ha')

    def __str__(self):
        return 'Checklist at {s.location.locality} {s.start_date_time}'.format(
            s=self)