<commit_before>#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#__END_LICENSE__
import datetime
import pytz

from django.conf import settings
from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from geocamUtil.loader import getModelByName
from xgds_sample.models import SampleType, Region, Label
from geocamUtil.loader import LazyGetModelByName
from geocamTrack.utils import getClosestPosition

LOCATION_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_PAST_POSITION_MODEL)

class SampleForm(ModelForm):
    latitude = forms.FloatField(required=False, label="Latitude:")
    longitude = forms.FloatField(required=False, label="Longitude:")
    altitude = forms.FloatField(required=False, label="Altitude:")
    date_formats = list(forms.DateTimeField.input_formats) + [
        '%Y/%m/%d %H:%M:%S',
        '%Y-%m-%d %H:%M:%S',
        '%m/%d/%Y %H:%M'
    ]
    collection_time = forms.DateTimeField(required=False, input_formats=date_formats)
    collection_timezone = forms.CharField(widget=forms.HiddenInput(), initial=settings.TIME_ZONE)
    
    # populate the event time with NOW if it is blank.
    def clean_collection_time(self): 
        ctime = self.cleaned_data['collection_time']
        if not ctime:
            return None
        else:
            ctimezone = self.cleaned_data['collection_timezone']
            tz = pytz.timezone(ctimezone)
            naiveTime = ctime.replace(tzinfo = None)
            localizedTime = tz.localize(naiveTime)
            utcTime = localizedTime.astimezone(pytz.utc)
            return utcTime
    
    
    def clean(self):
        """
        Checks that both lat and lon are entered (or both are empty)
        Checks that collection time is entered if user is entering position for the first time.
        """
        cleaned_data = super(SampleForm, self).clean()
        latitude = cleaned_data.get("latitude")
        longitude = cleaned_data.get("longitude")
        if (latitude and not longitude) or (not latitude and longitude):  # if only one of them is filled in
            msg = "Must enter both latitude and longitude or leave both blank."
            self.add_error('latitude', msg)
            self.add_error('longitude', msg)
        if latitude and longitude:
            instance = super(SampleForm, self).save(commit=False)
            if instance.user_position is None:
                if not self.cleaned_data['collection_time']:
                    msg = "Must enter collection time to record position"
                    self.add_error('collection_time', msg)
                
    
    def save(self, commit=True):
        instance = super(SampleForm, self).save(commit=False)
        instance.collection_time = self.cleaned_data['collection_time']
        if instance.resource and instance.collection_time:
            instance.track_position = getClosestPosition(timestamp=instance.collection_time, resource=instance.resource)
        if (('latitude' in self.changed_data) and ('longitude' in self.changed_data)) or ('altitude' in self.changed_data):
            if instance.user_position is None:
                instance.user_position = LOCATION_MODEL.get().objects.create(serverTimestamp = datetime.datetime.now(pytz.utc),
                                                                             timestamp = instance.collection_time,
                                                                             latitude = self.cleaned_data['latitude'],
                                                                             longitude = self.cleaned_data['longitude'], 
                                                                             altitude = self.cleaned_data['altitude'])
            else:
                instance.user_position.latitude = self.cleaned_data['latitude']
                instance.user_position.longitude = self.cleaned_data['longitude']
                instance.user_position.longitude = self.cleaned_data['altitude']
        if instance.name is None:
            try:
                instance.name = instance.buildName()
            except:
                instance.name = None
        if commit:
            instance.save()
        return instance

    class Meta: 
        model = getModelByName(settings.XGDS_SAMPLE_SAMPLE_MODEL)
        exclude = ['track_position', 
                   'user_position', 
                   'name', 
                   'creation_time', 
                   'modification_time', 
                   'creator', 
                   'modifier', 
                   'label']

    <commit_msg>rest of sample save bug fixed<commit_after>#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#__END_LICENSE__
import datetime
import pytz

from django.conf import settings
from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from geocamUtil.loader import getModelByName
from xgds_sample.models import SampleType, Region, Label
from geocamUtil.loader import LazyGetModelByName
from geocamTrack.utils import getClosestPosition

LOCATION_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_PAST_POSITION_MODEL)

class SampleForm(ModelForm):
    latitude = forms.FloatField(required=False, label="Latitude:")
    longitude = forms.FloatField(required=False, label="Longitude:")
    altitude = forms.FloatField(required=False, label="Altitude:")
    date_formats = list(forms.DateTimeField.input_formats) + [
        '%Y/%m/%d %H:%M:%S',
        '%Y-%m-%d %H:%M:%S',
        '%m/%d/%Y %H:%M'
    ]
    collection_time = forms.DateTimeField(required=False, input_formats=date_formats)
    collection_timezone = forms.CharField(widget=forms.HiddenInput(), initial=settings.TIME_ZONE)
    
    # populate the event time with NOW if it is blank.
    def clean_collection_time(self): 
        ctime = self.cleaned_data['collection_time']
        if not ctime:
            return None
        else:
            ctimezone = self.cleaned_data['collection_timezone']
            tz = pytz.timezone(ctimezone)
            naiveTime = ctime.replace(tzinfo = None)
            localizedTime = tz.localize(naiveTime)
            utcTime = localizedTime.astimezone(pytz.utc)
            return utcTime
    
    
    def clean(self):
        """
        Checks that both lat and lon are entered (or both are empty)
        Checks that collection time is entered if user is entering position for the first time.
        """
        cleaned_data = super(SampleForm, self).clean()
        latitude = cleaned_data.get("latitude")
        longitude = cleaned_data.get("longitude")
        if (latitude and not longitude) or (not latitude and longitude):  # if only one of them is filled in
            msg = "Must enter both latitude and longitude or leave both blank."
            self.add_error('latitude', msg)
            self.add_error('longitude', msg)
        if latitude and longitude:
            instance = super(SampleForm, self).save(commit=False)
            if instance.user_position is None:
                if not self.cleaned_data['collection_time']:
                    msg = "Must enter collection time to record position"
                    self.add_error('collection_time', msg)
                
    
    def save(self, commit=True):
        instance = super(SampleForm, self).save(commit=False)
        instance.collection_time = self.cleaned_data['collection_time']
        if instance.resource and instance.collection_time:
            instance.track_position = getClosestPosition(timestamp=instance.collection_time, resource=instance.resource)
        if (('latitude' in self.changed_data) and ('longitude' in self.changed_data)) or ('altitude' in self.changed_data):
            if instance.user_position is None:
                instance.user_position = LOCATION_MODEL.get().objects.create(serverTimestamp = datetime.datetime.now(pytz.utc),
                                                                             timestamp = instance.collection_time,
                                                                             latitude = self.cleaned_data['latitude'],
                                                                             longitude = self.cleaned_data['longitude'], 
                                                                             altitude = self.cleaned_data['altitude'])
            else:
                instance.user_position.latitude = self.cleaned_data['latitude']
                instance.user_position.longitude = self.cleaned_data['longitude']
                instance.user_position.altitude = self.cleaned_data['altitude']
        if instance.name is None:
            try:
                instance.name = instance.buildName()
            except:
                instance.name = None
        if commit:
            instance.save()
        return instance

    class Meta: 
        model = getModelByName(settings.XGDS_SAMPLE_SAMPLE_MODEL)
        exclude = ['track_position', 
                   'user_position', 
                   'name', 
                   'creation_time', 
                   'modification_time', 
                   'creator', 
                   'modifier', 
                   'label']
{'fraction_non_alphanumeric': 0.08213242912310445, 'fraction_numerical': 0.001507017048130357, 'mean_word_length': 2.2550582464745554, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1836377', 'n_tokens_mistral': 2753, 'n_tokens_neox': 2661, 'n_words': 751}