Best Python code snippet using avocado_python
models.py
Source:models.py  
1from __future__ import unicode_literals2import logging3from django.db import models4from django.contrib.gis.db import models5from django.contrib.postgres.fields.jsonb import JSONField6from django.db.models import Max7from django.utils.encoding import python_2_unicode_compatible8from ledger.accounts.models import EmailUser, RevisionedMixin9from ledger.licence.models import LicenceType10from wildlifecompliance.components.organisations.models import Organisation11from wildlifecompliance.components.call_email.models import CallEmail, Location12#from wildlifecompliance.components.artifact.utils import build_legal_case_hierarchy13#from wildlifecompliance.components.artifact.utils import BriefOfEvidenceRecordOfInterview14from wildlifecompliance.components.main.models import (15        CommunicationsLogEntry,16        UserAction, 17        Document,18        )19from wildlifecompliance.components.main.related_item import can_close_legal_case20#from wildlifecompliance.components.users.models import CompliancePermissionGroup21from wildlifecompliance.components.users.models import Region, District22from django.core.exceptions import ValidationError23from treebeard.mp_tree import MP_Node24from datetime import datetime, timedelta, date25from django.utils import timezone26logger = logging.getLogger(__name__)27class LegalCasePriority(models.Model):28    case_priority = models.CharField(max_length=50)29    #schema = JSONField(null=True)30    #version = models.SmallIntegerField(default=1, blank=False, null=False)31    #description = models.CharField(max_length=255, blank=True, null=True)32    #replaced_by = models.ForeignKey(33     #   'self', on_delete=models.PROTECT, blank=True, null=True)34    #date_created = models.DateTimeField(auto_now_add=True, null=True)35    class Meta:36        app_label = 'wildlifecompliance'37        verbose_name = 'CM_CasePriority'38        verbose_name_plural = 'CM_CasePriorities'39        #unique_together = ('case_priority', 'version')40    def __str__(self):41        #return '{0}, v.{1}'.format(self.case_priority, self.version)42        return self.case_priority43class CourtProceedings(models.Model):44    legal_case = models.OneToOneField(45        'LegalCase',46        null=True,47        blank=True,48        related_name="court_proceedings",49    )50    court_outcome_details = models.TextField(blank=True)51    court_outcome_type = models.ForeignKey('CourtOutcomeType', null=True, blank=True)52    court_outcome_fines = models.DecimalField(53        verbose_name="Fines",54        decimal_places=2,55        max_digits=12,56        blank=True,57        null=True)58    court_outcome_costs = models.DecimalField(59        verbose_name="Costs",60        decimal_places=2,61        max_digits=12,62        blank=True,63        null=True)64    class Meta:65        app_label = 'wildlifecompliance'66class LegalCase(RevisionedMixin):67    STATUS_OPEN = 'open'68    STATUS_WITH_MANAGER = 'with_manager'69    STATUS_WITH_PROSECUTION_COORDINATOR = 'with_prosecution_coordinator'70    STATUS_WITH_PROSECUTION_COUNCIL = 'with_prosecution_council'71    STATUS_WITH_PROSECUTION_MANAGER = 'with_prosecution_manager'72    STATUS_AWAIT_ENDORSEMENT = 'await_endorsement'73    STATUS_BRIEF_OF_EVIDENCE = 'brief_of_evidence'74    STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF = 'with_prosecution_coordinator_prosecution_brief'75    STATUS_WITH_PROSECUTION_COORDINATOR_COURT = 'with_prosecution_coordinator_court'76    STATUS_DISCARDED = 'discarded'77    STATUS_CLOSED = 'closed'78    STATUS_PENDING_CLOSURE = 'pending_closure'79    STATUS_CHOICES = (80            (STATUS_OPEN, 'Open'),81            (STATUS_WITH_MANAGER, 'With Manager'),82            (STATUS_WITH_PROSECUTION_COORDINATOR, 'With Prosecution Coordinator'),83            (STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF, 'With Prosecution Coordinator (Prosecution Brief)'),84            (STATUS_WITH_PROSECUTION_COORDINATOR_COURT, 'With Prosecution Coordinator (Court)'),85            (STATUS_WITH_PROSECUTION_COUNCIL, 'With Prosecution Council'),86            (STATUS_WITH_PROSECUTION_MANAGER, 'With Prosecution Manager'),87            (STATUS_AWAIT_ENDORSEMENT, 'Awaiting Endorsement'),88            (STATUS_DISCARDED, 'Discarded'),89            (STATUS_BRIEF_OF_EVIDENCE, 'Brief of Evidence'),90            (STATUS_CLOSED, 'Closed'),91            (STATUS_PENDING_CLOSURE, 'Pending Closure')92            )93    title = models.CharField(max_length=200, blank=True, null=True)94    status = models.CharField(95            max_length=100,96            choices=STATUS_CHOICES,97            default='open'98            )99    details = models.TextField(blank=True, null=True)100    number = models.CharField(max_length=50, blank=True, null=True)101    case_created_date = models.DateField(auto_now_add=True, blank=True, null=True)102    case_created_time = models.TimeField(auto_now_add=True, blank=True, null=True)103    call_email = models.ForeignKey(104        CallEmail, 105        related_name='legal_case_call_email',106        null=True107        )108    assigned_to = models.ForeignKey(109        EmailUser, 110        related_name='legal_case_assigned_to',111        null=True112        )113    #allocated_group = models.ForeignKey(114    #    CompliancePermissionGroup,115    #    related_name='legal_case_allocated_group', 116    #    null=True117    #    )118    #region = models.ForeignKey(119    #    Region, 120    #    related_name='legal_case_region', 121    #    null=True122    #)123    #district = models.ForeignKey(124    #    District, 125    #    related_name='legal_case_district', 126    #    null=True127    #)128    legal_case_priority = models.ForeignKey(129            LegalCasePriority,130            null=True131            )132    associated_persons = models.ManyToManyField(133            EmailUser,134            related_name='legal_case_associated_persons',135            )136    class Meta:137        app_label = 'wildlifecompliance'138        verbose_name = 'CM_LegalCase'139        verbose_name_plural = 'CM_LegalCases'140    def __str__(self):141        return 'ID: {}, Title: {}'.format(self.number, self.title)142    # Prefix "CS" char to LegalCase number.143    def save(self, *args, **kwargs):144        super(LegalCase, self).save(*args,**kwargs)145        if self.number is None:146            new_number_id = 'CS{0:06d}'.format(self.pk)147            self.number = new_number_id148            self.save()149        if not hasattr(self, 'court_proceedings'):150            cp = CourtProceedings.objects.create(legal_case=self)151            cp.save()152    def log_user_action(self, action, request):153        # return LegalCaseUserAction.log_action(self, action, request.user)154        if request:155            return LegalCaseUserAction.log_action(self, action, request.user)156        else:157            return LegalCaseUserAction.log_action(self, action)158    @property159    def get_related_items_identifier(self):160        return self.number161    @property162    def get_related_items_descriptor(self):163        #return '{0}, {1}'.format(self.title, self.details)164        return self.title165    def close(self, request=None):166        close_record, parents = can_close_legal_case(self, request)167        if close_record:168            self.status = self.STATUS_CLOSED169            self.log_user_action(170                    LegalCaseUserAction.ACTION_CLOSE.format(self.number),171                    request)172        else:173            self.status = self.STATUS_PENDING_CLOSURE174            self.log_user_action(175                    LegalCaseUserAction.ACTION_PENDING_CLOSURE.format(self.number), 176                    request)177        self.save()178        # Call close() on any parent with pending_closure status179        if parents and self.status == 'closed':180            for parent in parents:181                if parent.status == 'pending_closure':182                    parent.close(request)183    def set_status_brief_of_evidence(self, request):184        self.assigned_to = None185        self.status = self.STATUS_BRIEF_OF_EVIDENCE186        self.log_user_action(187            LegalCaseUserAction.ACTION_STATUS_BRIEF_OF_EVIDENCE.format(self.number), 188            request)189        self.save()190    def set_status_generate_prosecution_brief(self, request):191        self.assigned_to = None192        self.status = self.STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF193        self.log_user_action(194            LegalCaseUserAction.ACTION_GENERATE_PROSECUTION_BRIEF.format(self.number), 195            request)196        self.save()197    def send_to_prosecution_coordinator(self, request):198        self.assigned_to = None199        self.status = self.STATUS_WITH_PROSECUTION_COORDINATOR200        self.log_user_action(201            LegalCaseUserAction.ACTION_STATUS_WITH_PROSECUTION_COORDINATOR.format(self.number), 202            request)203        # set allocated group to 204        self.allocated_group = CompliancePermissionGroup.objects.get(permissions__codename="prosecution_coordinator")205        self.save()206    def back_to_prosecution_coordinator(self, request):207        self.assigned_to = None208        self.status = self.STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF209        self.log_user_action(210            LegalCaseUserAction.ACTION_STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF.format(self.number), 211            request)212        # set allocated group to 213        self.allocated_group = CompliancePermissionGroup.objects.get(permissions__codename="prosecution_coordinator")214        self.save()215    def send_to_prosecution_council(self, request):216        self.assigned_to = None217        self.status = self.STATUS_WITH_PROSECUTION_COUNCIL218        self.log_user_action(219            LegalCaseUserAction.ACTION_STATUS_WITH_PROSECUTION_COUNCIL.format(self.number), 220            request)221        # set allocated group to 222        self.allocated_group = CompliancePermissionGroup.objects.get(permissions__codename="prosecution_council")223        self.save()224    def approve_for_court(self, request):225        self.assigned_to = None226        self.status = self.STATUS_WITH_PROSECUTION_COORDINATOR_COURT227        self.log_user_action(228            LegalCaseUserAction.ACTION_APPROVE_FOR_COURT.format(self.number), 229            request)230        # set allocated group to 231        self.allocated_group = CompliancePermissionGroup.objects.get(permissions__codename="prosecution_council")232        self.save()233    def send_to_prosecution_manager(self, request):234        self.assigned_to = None235        self.status = self.STATUS_WITH_PROSECUTION_MANAGER236        self.log_user_action(237            LegalCaseUserAction.ACTION_STATUS_WITH_PROSECUTION_MANAGER.format(self.number), 238            request)239        # set allocated group to 240        self.allocated_group = CompliancePermissionGroup.objects.get(permissions__codename="prosecution_manager")241        self.save()242    def send_to_manager(self, request):243        self.assigned_to = None244        self.status = self.STATUS_WITH_MANAGER245        self.log_user_action(246            LegalCaseUserAction.ACTION_SEND_TO_MANAGER.format(self.number), 247            request)248        # set allocated group to 249        #region_district_id = self.district_id if self.district_id else self.region_id250        #region_district = Region.objects.get(id=region_district_id)251        region_district = self.allocated_group.region_district252        if type(region_district) is District:253            self.allocated_group = CompliancePermissionGroup.district_groups.get(district=region_district, permissions__codename="manager")254        elif type(region_district) is Region:255            self.allocated_group = CompliancePermissionGroup.district_groups.get(region=region_district, permissions__codename="manager")256        #self.allocated_group = CompliancePermissionGroup.objects.get(region_district=region_district, permissions__codename="manager")257        self.save()258    def back_to_case(self, request):259        self.assigned_to = None260        self.status = self.STATUS_OPEN261        self.log_user_action(262            LegalCaseUserAction.ACTION_BACK_TO_CASE.format(self.number), 263            request)264        self.save()265    def back_to_officer(self, request):266        self.assigned_to = None267        self.status = self.STATUS_BRIEF_OF_EVIDENCE268        self.log_user_action(269            LegalCaseUserAction.ACTION_BACK_TO_OFFICER.format(self.number), 270            request)271        # set allocated group to 272        #region_district_id = self.district_id if self.district_id else self.region_id273        #region_district = RegionDistrict.objects.get(id=region_district_id)274        #self.allocated_group = CompliancePermissionGroup.objects.get(region_district=region_district, permissions__codename="officer")275        region_district = self.allocated_group.region_district276        if type(region_district) is District:277            self.allocated_group = CompliancePermissionGroup.district_groups.get(district=region_district, permissions__codename="officer")278        elif type(region_district) is Region:279            self.allocated_group = CompliancePermissionGroup.district_groups.get(region=region_district, permissions__codename="officer")280        self.save()281class BriefOfEvidence(models.Model):282    legal_case = models.OneToOneField(283            LegalCase,284            null=True,285            blank=True,286            related_name="brief_of_evidence",287            )288    statement_of_facts = models.TextField(blank=True, null=True)289    victim_impact_statement_taken = models.BooleanField(default=False)290    statements_pending = models.BooleanField(default=False)291    vulnerable_hostile_witnesses = models.BooleanField(default=False)292    witness_refusing_statement = models.BooleanField(default=False)293    problems_needs_prosecution_witnesses = models.BooleanField(default=False)294    accused_bad_character = models.BooleanField(default=False)295    further_persons_interviews_pending = models.BooleanField(default=False)296    other_interviews = models.BooleanField(default=False)297    relevant_persons_pending_charges = models.BooleanField(default=False)298    other_persons_receiving_sanction_outcome = models.BooleanField(default=False)299    local_public_interest = models.BooleanField(default=False)300    applications_orders_requests = models.BooleanField(default=False)301    applications_orders_required = models.BooleanField(default=False)302    other_legal_matters = models.BooleanField(default=False)303    victim_impact_statement_taken_details = models.TextField(blank=True, null=True)304    statements_pending_details = models.TextField(blank=True, null=True)305    vulnerable_hostile_witnesses_details = models.TextField(blank=True, null=True)306    witness_refusing_statement_details = models.TextField(blank=True, null=True)307    problems_needs_prosecution_witnesses_details = models.TextField(blank=True, null=True)308    accused_bad_character_details = models.TextField(blank=True, null=True)309    further_persons_interviews_pending_details = models.TextField(blank=True, null=True)310    other_interviews_details = models.TextField(blank=True, null=True)311    relevant_persons_pending_charges_details = models.TextField(blank=True, null=True)312    other_persons_receiving_sanction_outcome_details = models.TextField(blank=True, null=True)313    local_public_interest_details = models.TextField(blank=True, null=True)314    applications_orders_requests_details = models.TextField(blank=True, null=True)315    applications_orders_required_details = models.TextField(blank=True, null=True)316    other_legal_matters_details = models.TextField(blank=True, null=True)317    class Meta:318        app_label = 'wildlifecompliance'319class ProsecutionBrief(models.Model):320    legal_case = models.OneToOneField(321            LegalCase,322            null=True,323            blank=True,324            related_name="prosecution_brief",325            )326    statement_of_facts = models.TextField(blank=True, null=True)327    victim_impact_statement_taken = models.BooleanField(default=False)328    statements_pending = models.BooleanField(default=False)329    vulnerable_hostile_witnesses = models.BooleanField(default=False)330    witness_refusing_statement = models.BooleanField(default=False)331    problems_needs_prosecution_witnesses = models.BooleanField(default=False)332    accused_bad_character = models.BooleanField(default=False)333    further_persons_interviews_pending = models.BooleanField(default=False)334    other_interviews = models.BooleanField(default=False)335    relevant_persons_pending_charges = models.BooleanField(default=False)336    other_persons_receiving_sanction_outcome = models.BooleanField(default=False)337    local_public_interest = models.BooleanField(default=False)338    applications_orders_requests = models.BooleanField(default=False)339    applications_orders_required = models.BooleanField(default=False)340    other_legal_matters = models.BooleanField(default=False)341    victim_impact_statement_taken_details = models.TextField(blank=True, null=True)342    statements_pending_details = models.TextField(blank=True, null=True)343    vulnerable_hostile_witnesses_details = models.TextField(blank=True, null=True)344    witness_refusing_statement_details = models.TextField(blank=True, null=True)345    problems_needs_prosecution_witnesses_details = models.TextField(blank=True, null=True)346    accused_bad_character_details = models.TextField(blank=True, null=True)347    further_persons_interviews_pending_details = models.TextField(blank=True, null=True)348    other_interviews_details = models.TextField(blank=True, null=True)349    relevant_persons_pending_charges_details = models.TextField(blank=True, null=True)350    other_persons_receiving_sanction_outcome_details = models.TextField(blank=True, null=True)351    local_public_interest_details = models.TextField(blank=True, null=True)352    applications_orders_requests_details = models.TextField(blank=True, null=True)353    applications_orders_required_details = models.TextField(blank=True, null=True)354    other_legal_matters_details = models.TextField(blank=True, null=True)355    class Meta:356        app_label = 'wildlifecompliance'357class CourtProceedingsJournalEntryManager(models.Manager):358    def create_journal_entry(self, court_proceedings_id, user_id):359        max_row_num_dict = CourtProceedingsJournalEntry.objects.filter(court_proceedings_id=court_proceedings_id).aggregate(Max('row_num'))360        # initial value for new LegalCase361        row_num = 1362        # increment initial value if other entries exist for LegalCase363        if max_row_num_dict.get('row_num__max'):364            max_row_num = int(max_row_num_dict.get('row_num__max'))365            row_num = max_row_num + 1366        journal_entry = self.create(row_num=row_num, court_proceedings_id=court_proceedings_id, user_id=user_id)367        return journal_entry368class CourtProceedingsJournalEntry(RevisionedMixin):369    court_proceedings = models.ForeignKey(CourtProceedings, related_name='journal_entries')370    #person = models.ManyToManyField(LegalCasePerson, related_name='journal_entry_person')371    date_modified = models.DateTimeField(auto_now=True)372    user = models.ForeignKey(EmailUser, related_name='journal_entry_user')373    description = models.TextField(blank=True)374    row_num = models.SmallIntegerField(blank=False, null=False)375    deleted = models.BooleanField(default=False)376    objects = CourtProceedingsJournalEntryManager()377    class Meta:378        app_label = 'wildlifecompliance'379        unique_together = ('court_proceedings', 'row_num')380    def number(self):381        #return self.court_proceedings.number + '-' + str(self.row_num)382        number = ''383        if self.court_proceedings.legal_case:384            number = self.court_proceedings.legal_case.number + '-' + str(self.row_num)385        return number386    def delete_entry(self):387        is_deleted = False388        if not self.deleted:389            self.deleted = True390            is_deleted = True391        return is_deleted392    def reinstate_entry(self):393        is_reinstated = False394        if self.deleted:395            self.deleted = False396            is_reinstated = True397        return is_reinstated398class LegalCasePerson(EmailUser):399    legal_case = models.ForeignKey(LegalCase, related_name='legal_case_person')400    class Meta:401        app_label = 'wildlifecompliance'402    def __str__(self):403        return "id:{}, legal_case_id:{}".format(404                self.id,405                self.legal_case_id,406                )407class LegalCaseRunningSheetEntryManager(models.Manager):408    def create_running_sheet_entry(self, legal_case_id, user_id):409        max_row_num_dict = LegalCaseRunningSheetEntry.objects.filter(legal_case_id=legal_case_id).aggregate(Max('row_num'))410        # initial value for new LegalCase411        row_num = 1412        # increment initial value if other entries exist for LegalCase413        if max_row_num_dict.get('row_num__max'):414            max_row_num = int(max_row_num_dict.get('row_num__max'))415            row_num = max_row_num + 1416        running_sheet_entry = self.create(row_num=row_num, legal_case_id=legal_case_id, user_id=user_id)417        return running_sheet_entry418class LegalCaseRunningSheetEntry(RevisionedMixin):419    legal_case = models.ForeignKey(LegalCase, related_name='running_sheet_entries')420    # TODO: person fk req?  Url links in description instead421    person = models.ManyToManyField(LegalCasePerson, related_name='running_sheet_entry_person')422    #number = models.CharField(max_length=50, blank=True)423    #date_created = models.DateTimeField(auto_now_add=True)424    date_modified = models.DateTimeField(auto_now=True)425    user = models.ForeignKey(EmailUser, related_name='running_sheet_entry_user')426    #description = models.CharField(max_length=255, blank=True)427    description = models.TextField(blank=True)428    row_num = models.SmallIntegerField(blank=False, null=False)429    deleted = models.BooleanField(default=False)430    objects = LegalCaseRunningSheetEntryManager()431    class Meta:432        app_label = 'wildlifecompliance'433        unique_together = ('legal_case', 'row_num')434    def __str__(self):435        return "Number:{}, User:{}, Description:{}".format(436                self.number(),437                self.user,438                self.description)439    def legal_case_persons(self):440        persons = self.legal_case.legal_case_person.all()441        return persons442    def number(self):443        return self.legal_case.number + '-' + str(self.row_num)444    def delete_entry(self):445        is_deleted = False446        if not self.deleted:447            self.deleted = True448            is_deleted = True449        return is_deleted450    def reinstate_entry(self):451        is_reinstated = False452        if self.deleted:453            self.deleted = False454            is_reinstated = True455        return is_reinstated456class LegalCaseCommsLogEntry(CommunicationsLogEntry):457    legal_case = models.ForeignKey(LegalCase, related_name='comms_logs')458    class Meta:459        app_label = 'wildlifecompliance'460class LegalCaseCommsLogDocument(Document):461    log_entry = models.ForeignKey(462        LegalCaseCommsLogEntry,463        related_name='documents')464    _file = models.FileField(max_length=255)465    class Meta:466        app_label = 'wildlifecompliance'467# class LegalCaseUserAction(UserAction):468class LegalCaseUserAction(models.Model):469    ACTION_CREATE_LEGAL_CASE = "Create Case {}"470    ACTION_SAVE_LEGAL_CASE = "Save Case {}"471    ACTION_STATUS_BRIEF_OF_EVIDENCE = "Generate 'Brief of Evidence' for Case {}"472    ACTION_GENERATE_PROSECUTION_BRIEF = "Generate 'Prosecution Brief' for Case {}"473    ACTION_GENERATE_DOCUMENT = "Generate {} for Case {} with sections: {}"474    ACTION_STATUS_WITH_PROSECUTION_COORDINATOR = "Send Case {} to Prosecution Coordinator"475    ACTION_STATUS_WITH_PROSECUTION_COORDINATOR_PROSECUTION_BRIEF = "Change status of Case {} to Prosecution Coordinator (Prosecution Brief)"476    ACTION_STATUS_WITH_PROSECUTION_COUNCIL = "Send Case {} to Prosecution Council"477    ACTION_STATUS_WITH_PROSECUTION_MANAGER = "Send Case {} to Prosecution Manager"478    ACTION_APPROVE_FOR_COURT = "Approve Case {} for Court"479    ACTION_SEND_TO_MANAGER = "Send Case {} to Manager"480    ACTION_BACK_TO_CASE = "Return Case {} to Open status"481    ACTION_BACK_TO_OFFICER = "Return Case {} to Officer"482    ACTION_CLOSE = "Close Legal Case {}"483    ACTION_PENDING_CLOSURE = "Mark Inspection {} as pending closure"484    ACTION_ADD_WEAK_LINK = "Create manual link between {}: {} and {}: {}"485    ACTION_REMOVE_WEAK_LINK = "Remove manual link between {}: {} and {}: {}"486    class Meta:487        app_label = 'wildlifecompliance'488        ordering = ('-when',)489    @classmethod490    def log_action(cls, legal_case, action, user=None):491        return cls.objects.create(492            legal_case=legal_case,493            who=user,494            what=str(action)495        )496    who = models.ForeignKey(EmailUser, null=True, blank=True)497    when = models.DateTimeField(null=False, blank=False, auto_now_add=True)498    what = models.TextField(blank=False)499    legal_case = models.ForeignKey(LegalCase, related_name='action_logs')500class LegalCaseDocument(Document):501    legal_case = models.ForeignKey(LegalCase, related_name='documents')502    _file = models.FileField(max_length=255)503    input_name = models.CharField(max_length=255, blank=True, null=True)504    # after initial submit prevent document from being deleted505    can_delete = models.BooleanField(default=True)506    version_comment = models.CharField(max_length=255, blank=True, null=True)507    def delete(self):508        if self.can_delete:509            return super(LegalCaseDocument, self).delete()510    class Meta:511        app_label = 'wildlifecompliance'512class ProsecutionNoticeDocument(Document):513    legal_case = models.ForeignKey(LegalCase, related_name='prosecution_notices')514    _file = models.FileField(max_length=255,)515    class Meta:516        app_label = 'wildlifecompliance'517        verbose_name = 'CM_ProsecutionNoticeDocument'518        verbose_name_plural = 'CM_ProsecutionNoticeDocuments'519class CourtHearingNoticeDocument(Document):520    legal_case = models.ForeignKey(LegalCase, related_name='court_hearing_notices')521    _file = models.FileField(max_length=255,)522    class Meta:523        app_label = 'wildlifecompliance'524        verbose_name = 'CM_CourtHearingNoticeDocument'525        verbose_name_plural = 'CM_CourtHearingNoticeDocuments'526class BriefOfEvidenceDocument(Document):527    brief_of_evidence = models.ForeignKey(BriefOfEvidence, related_name='documents')528    _file = models.FileField(max_length=255)529    input_name = models.CharField(max_length=255, blank=True, null=True)530    # after initial submit prevent document from being deleted531    can_delete = models.BooleanField(default=True)532    version_comment = models.CharField(max_length=255, blank=True, null=True)533    def delete(self):534        if self.can_delete:535            return super(BriefOfEvidenceDocument, self).delete()536    class Meta:537        app_label = 'wildlifecompliance'538class ProsecutionBriefDocument(Document):539    prosecution_brief = models.ForeignKey(ProsecutionBrief, related_name='documents')540    _file = models.FileField(max_length=255)541    input_name = models.CharField(max_length=255, blank=True, null=True)542    # after initial submit prevent document from being deleted543    can_delete = models.BooleanField(default=True)544    version_comment = models.CharField(max_length=255, blank=True, null=True)545    def delete(self):546        if self.can_delete:547            return super(ProsecutionBriefDocument, self).delete()548    class Meta:549        app_label = 'wildlifecompliance'550class LegalCaseGeneratedDocument(Document):551    legal_case = models.ForeignKey(LegalCase, related_name='generated_documents')552    _file = models.FileField(max_length=255)553    class Meta:554        app_label = 'wildlifecompliance'555        verbose_name = 'CM_LegalCaseGeneratedDocument'556        verbose_name_plural = 'CM_LegalCaseGeneratedDocuments'557def update_court_outcome_doc_filename(instance, filename):558    return 'wildlifecompliance/legal_case/{}/court_outcome_documents/{}'.format(instance.legal_case.id, filename)559class CourtOutcomeDocument(Document):560    court_proceedings = models.ForeignKey(CourtProceedings, related_name='court_outcome_documents')561    _file = models.FileField(max_length=255, upload_to=update_court_outcome_doc_filename)562    class Meta:563        app_label = 'wildlifecompliance'564        verbose_name = 'CM_CourtOutcomeDocument'565        verbose_name_plural = 'CM_CourtOutcomeDocuments'566class Court(models.Model):567    identifier = models.CharField(max_length=255, blank=True, null=True)568    location = models.CharField(max_length=255, blank=True, null=True)569    description = models.TextField(blank=True, null=True)570    class Meta:571        app_label = 'wildlifecompliance'572        verbose_name = 'CM_Court'573        verbose_name_plural = 'CM_Courts'574    def __str__(self):575        return self.identifier + ' ({})'.format(self.location)576class CourtOutcomeType(models.Model):577    identifier = models.CharField(max_length=255, blank=True, null=True)578    description = models.TextField(blank=True, null=True)579    class Meta:580        app_label = 'wildlifecompliance'581        verbose_name = 'CM_CourtOutcomeType'582        verbose_name_plural = 'CM_CourtOutcomeTypes'583    def __str__(self):584        return self.identifier585class CourtDate(models.Model):586    court_proceedings = models.ForeignKey(CourtProceedings, related_name='court_dates')587    court_datetime = models.DateTimeField(blank=True, null=True,)588    comments = models.TextField(blank=True)589    court = models.ForeignKey(Court, blank=True, null=True)590    class Meta:591        app_label = 'wildlifecompliance'592        verbose_name = 'CM_CourtDate'593        verbose_name_plural = 'CM_CourtDates'594import reversion595#reversion.register(LegalCaseRunningSheetEntry, follow=['user'])596#reversion.register(CourtProceedingsJournalEntry, follow=['user'])597#reversion.register(LegalCase)598reversion.register(EmailUser)599reversion.register(LegalCasePriority, follow=['legalcase_set'])600reversion.register(CourtProceedings, follow=['journal_entries', 'court_outcome_documents', 'court_dates'])601#reversion.register(LegalCase_associated_persons, follow=[])602reversion.register(LegalCase, follow=['court_proceedings', 'brief_of_evidence', 'prosecution_brief', 'legal_case_person', 'running_sheet_entries', 'comms_logs', 'action_logs', 'documents', 'prosecution_notices', 'court_hearing_notices', 'generated_documents', 'inspection_legal_case', 'offence_legal_case', 'legal_case_document_artifacts', 'documentartifactlegalcases_set', 'briefofevidencedocumentartifacts_set', 'prosecutionbriefdocumentartifacts_set', 'legal_case_physical_artifacts', 'physicalartifactlegalcases_set', 'briefofevidencephysicalartifacts_set', 'prosecutionbriefphysicalartifacts_set', 'legal_case_boe_other_statements', 'legal_case_boe_roi', 'legal_case_pb_other_statements', 'legal_case_pb_roi'])603reversion.register(BriefOfEvidence, follow=['documents'])604reversion.register(ProsecutionBrief, follow=['documents'])605reversion.register(CourtProceedingsJournalEntry, follow=[])606reversion.register(LegalCasePerson, follow=['logentry_set', 'social_auth', 'revision_set', 'userrecord_set', 'userproductview_set', 'usersearch_set', 'addresses', 'reviews', 'review_votes', 'partners', 'baskets', 'bankcards', 'rangeproductfileupload_set', 'orders', 'ordernote_set', 'emails', 'notifications', 'notification_set', 'alerts', 'voucherapplication_set', 'wishlists', 'profile_addresses', 'emailidentity_set', 'emailuseraction_set', 'action_logs', 'comms_logs', 'profiles', 'holder', 'issuer', 'trackrefund_set', 'stored_cards', 'wildlifecompliance_organisations', 'organisationcontactaction_set', 'organisationcontactdeclineddetails_set', 'userdelegation_set', 'organisationaction_set', 'organisationrequest_set', 'org_request_assignee', 'organisationrequestuseraction_set', 'organisationrequestdeclineddetails_set', 'compliancemanagementuserpreferences_set', 'intelligence_documents', 'callemail_assigned_to', 'callemail_volunteer', 'callemail_set', 'callemailuseraction_set', 'legal_case_assigned_to', 'legal_case_associated_persons', 'journal_entry_user', 'running_sheet_entry_user', 'legalcaseuseraction_set', 'individual_inspected', 'inspection_assigned_to', 'inspection_team_lead', 'inspection_set', 'inspectionuseraction_set', 'licenceuseraction_set', 'wildlifecompliance_proxy', 'wildlifecompliance_applications', 'wildlifecompliance_assessor', 'applicationselectedactivity_set', 'wildlifecompliance_officer_finalisation', 'wildlifecompliance_officer', 'applicationuseraction_set', 'returns_curator', 'returns_submitter', 'returnuseraction_set', 'offence_assigned_to', 'alleged_offence_removed_by', 'offender_removed_by', 'offender_person', 'offenceuseraction_set', 'sanctionoutcomeduedate_set', 'created_by_infringement_penalty', 'sanction_outcome_assigned_to', 'sanction_outcome_responsible_officer', 'sanction_outcome_registration_holder', 'sanction_outcome_driver', 'sanctionoutcomedocumentaccesslog_set', 'sanctionoutcomeuseraction_set', 'document_artifact_person_providing_statement', 'document_artifact_officer_interviewer', 'document_artifact_people_attending', 'physical_artifact_officer', 'physical_artifact_custodian', 'artifactuseraction_set', 'email_user_boe_other_statements', 'email_user_pb_other_statements', 'running_sheet_entry_person'])607#reversion.register(LegalCaseRunningSheetEntry_person, follow=[])608reversion.register(LegalCaseRunningSheetEntry, follow=[])609reversion.register(LegalCaseCommsLogEntry, follow=['documents'])610reversion.register(LegalCaseCommsLogDocument, follow=[])611reversion.register(LegalCaseUserAction, follow=[])612reversion.register(LegalCaseDocument, follow=[])613reversion.register(ProsecutionNoticeDocument, follow=[])614reversion.register(CourtHearingNoticeDocument, follow=[])615reversion.register(BriefOfEvidenceDocument, follow=[])616reversion.register(ProsecutionBriefDocument, follow=[])617reversion.register(LegalCaseGeneratedDocument, follow=[])618reversion.register(CourtOutcomeDocument, follow=[])619reversion.register(Court, follow=['courtdate_set'])620reversion.register(CourtOutcomeType, follow=['courtproceedings_set'])...multipath.py
Source:multipath.py  
...149    reinstating the individual paths150    :param disk_path: disk path. Example: sda, sdb.151    :return: True or False152    """153    def is_reinstated():154        path_stat = get_path_status(path)155        if path_stat[0] == 'active' and path_stat[2] == 'ready':156            return True157        return False158    cmd = 'multipathd -k"reinstate path %s"' % path159    if process.system(cmd) == 0:160        return wait.wait_for(is_reinstated, timeout=10) or False161def get_policy(wwid):162    """163    Gets path_checker policy, given a multipath wwid.164    :return: path checker policy.165    """166    if device_exists(wwid):167        cmd = "multipath -ll %s" % wwid...Policy.py
Source:Policy.py  
1# -*- coding: utf-8 -*-2"""3Created on Mon Nov 13 22:09:44 20174@author: Archit5"""6from Entities.SimilarityCalculator import SimilarityCalculator7class Policy(SimilarityCalculator):8    def __init__(self):9        self.number = None10        self.issue_date = None11        self.premium_method = None12        self.medical_exam = None13        self.decision = None14        self.channel_code = None15        self.is_lapsed = None16        self.lapsed_date = None17        self.is_reinstated = None18        self.reinstate_date = None19        self.is_autopaid = None20        self.autopaid_date = None21        self.inforce_year = None22        self.premium_frequency = None23        self.face_amount = None24        self.total_premium = None25        26    def similarity(self, other):27        if not isinstance(other, Policy):28            return 029        d = self.issue_date.month - other.issue_date.month30        s1 = self.distance_score(d)31        s2 = self.equality_score(self.premium_method, other.premium_method)32        s3 = self.equality_score(self.medical_exam, other.medical_exam)33        s4 = self.equality_score(self.decision, other.decision)34        s5 = self.equality_score(self.channel_code, other.channel_code)35        s6 = self.equality_score(self.is_lapsed, other.is_lapsed)36        s7 = self.equality_score(self.is_reinstated, other.is_reinstated)37        s8 = self.equality_score(self.is_autopaid, other.is_autopaid)38        s9 = self.equality_score(self.inforce_year, other.inforce_year)39        s10 = self.equality_score(self.premium_frequency, other.premium_frequency)40        s11 = self.manhattan_score(self.face_amount/10000, other.face_amount/10000)41        s12 = self.manhattan_score(self.total_premium, other.total_premium)42        43        scores = [s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12]44        weights = [1/12] * 1245        46        return self.weighted_score(weights, scores)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
