예제 #1
0
def location(request):
    if request.method == 'POST':
        lon = request.POST['lon']
        lat = request.POST['lat']
        err = request.POST['err']
        key = request.POST['key']

        query = Location.objects.get(Key=key)
        if query:
            query.lon = lon
            query.lat = lat
            query.err = err
            query.save()
        else:
            new_row = Location(pk=key, lon=lon, lat=lat, err=err)
            new_row.save()

        return HttpResponse()

    if request.method == 'GET':
        key = request.GET.get('key', '')
        query = Location.objects.filter(pk=key).values('lon', 'lat',
                                                       'err').first()
        if query:
            return HttpResponse(json.dumps({
                'lon': query['lon'],
                'lat': query['lat'],
                'err': query['err']
            }),
                                content_type="application/json")
        else:
            print "no match"
            return HttpResponse()
예제 #2
0
def add_address(request):
    if request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            location = Location(house_number=form.cleaned_data['house_number'],
                                street=form.cleaned_data['street'],
                                city_name=form.cleaned_data['city_name'],
                                zip_code=form.cleaned_data['zip_code'])
            location.save()
            coord = find_coordinates(location.house_number, location.street,
                                     location.zip_code, location.city_name)
            location.latitude = float(coord.split(",")[2])
            location.longitude = float(coord.split(",")[3])
            location.save()
            address = Address(user=request.user, location=location)
            address.save()
            request.user.message_set.create(message="Adresse ajoutée.")
            return HttpResponseRedirect('/users/address/edit/%s' % address.id)
        else:
            return render_to_response('users/add_address.html', {'form': form},
                                      RequestContext(request))
    else:
        form = AddressForm()
        return render_to_response('users/add_address.html', {'form': form},
                                  RequestContext(request))
예제 #3
0
 def save(self,user):
     user.profile.about = self.cleaned_data['about']
     user.profile.gender = self.cleaned_data['gender']
     user.profile.birth_date = self.cleaned_data['birth_date']
     city_value = self.cleaned_data['city']
     location_value = self.cleaned_data['location']
     if self.cleaned_data['lat'] and self.cleaned_data['lon'] and city_value:
         lat_value = float(self.cleaned_data['lat'])
         lon_value = float(self.cleaned_data['lon'])
         hh = City.objects.get(value=city_value)
         if user.profile.location:
             if lat_value!=user.profile.location.lat or lon_value != user.profile.location.lon:
                 user.profile.location.lon = lon_value
                 user.profile.location.lat = lat_value
                 user.profile.location.city = hh
                 user.profile.location.address = location_value
                 user.profile.location.save()
         else:
             l = Location(city=hh, lon=lon_value,
                     lat=lat_value, address=location_value)
             l.save()
             user.profile.location = l
     elif not city_value:
         user.profile.location = None
     return user
예제 #4
0
    def handle(self, *args, **options):

        possibilities = list(
            itertools.product([
                'Anne', 'Robert', 'Marie', 'Tove', 'Jens', 'Ines', 'Lars',
                'Karl'
            ], [
                'Larson', 'Nilson', 'Weier', 'Mueller', 'Chu-Xi', 'Wa',
                'Halakkai', 'Czetec'
            ]))
        random.shuffle(possibilities)

        tags = [
            'banana', 'apple', 'fruit', 'ice', 'green', 'red', 'Anne',
            'Robert', 'Marie', 'Tove', 'Jens', 'Ines', 'Lars', 'Karl',
            'Larson', 'Nilson', 'Weier', 'Mueller', 'Chu-Xi', 'Wa', 'Halakkai',
            'Czetec'
        ]
        tags_obj = []
        for t in tags:
            tg = SlugPhrase.objects.get_or_create(value=t)[0]
            tags_obj.append(tg)

        usernames = [e[0] + " " + e[1] for e in possibilities[0:25]]

        users = []
        for name in usernames:
            u = User.objects.create_user(
                name, '{}@heleska.de'.format(name.replace(' ', '_')),
                'aqwsderf')

            iby = None

            if len(users) > 0 and random.random() > 0.3:
                iby = random.choice(users)

            p = UserProfile(user=u, invited_by=iby)
            p.about_me_text = "Some about me"
            p.save()

            long = str(random.randint(-900, 900) / 10.0)
            lang = str(random.randint(-1800, 1800) / 10.0)

            l = Location(user=u,
                         longitude=long,
                         latitude=lang,
                         position_updated=datetime.datetime.today())
            l.save()

            num = random.randint(0, len(tags))
            for e in random.sample(tags_obj, num):
                UserSlugs(user=u, slug=e).save()

            users.append(u)

        self.stdout.write(
            self.style.SUCCESS('Successfully create a bunch of users!'))
 def to_imis_obj(cls, fhir_location, audit_user_id):
     errors = []
     imis_location = Location()
     cls.build_imis_location_identiftier(imis_location, fhir_location,
                                         errors)
     cls.build_imis_location_name(imis_location, fhir_location, errors)
     cls.build_imis_location_type(imis_location, fhir_location, errors)
     cls.build_imis_parent_location_id(imis_location, fhir_location, errors)
     cls.check_errors(errors)
     return imis_location
예제 #6
0
def clear_location(request):
    """ This method allows to clear the location """
    try:
        location = Location.objects.get(user=request.user)
        location.clear_location()
        return JsonResponse({'success': True})
    except Location.DoesNotExist:
        location = Location(user=request.user)
        location.save()
        return JsonResponse({'success': True})
    except Exception:
        return JsonResponse({
            'success': False,
            'error': 'Could not find location object'
        })
예제 #7
0
    def setUp(self):
        api_key, key = APIKey.objects.create_key(name="bO4_UffT6FcimKuhY_qL-j")
        self.key = key

        location = Location(name="Orchid Country Club", lock_id="IGP1053e20f2")
        location.save()

        self.booking = Booking(slotKey="-wowweareteating",
                               bookingKey="-wowweareteating",
                               date="2020-07-20T00:00:00+05:00",
                               duration=1,
                               end="11pm",
                               location="Orchid Country Club",
                               name="Fozan Ali",
                               pitch=2,
                               rate=95,
                               start="10pm",
                               status="Paid",
                               sumittedDate="2020-02-27T13:17:09+08:00",
                               email="*****@*****.**")
        self.booking.save()
예제 #8
0
 def post(self, request, *args, **kwargs):
     """
     Update status and current location of user. Authentication required.
     """
     if not request.user.is_authenticated:
         return Response("You have to log yourself in", status=403)
     serialized = SimpleUserSerializer(data=request.data)
     if serialized.is_valid():
         user = request.user
         location_dict = serialized.data['current_location']
         matchable = serialized.data['matchable']
         user.matchable = matchable
         if not user.matchable:
             user.other_user.other_user = None
             user.other_user.save()
             user.other_user = None
             user.save()
             serialized = UpdateUserSerializer(user)
             return Response(serialized.data, status=200)
         location = Location(longtitude=location_dict['longtitude'], latitude=location_dict['latitude'])
         location.save()
         user.current_location = location
         user.save()
         if user.current_location is not None and distance(CENTER,
                                                           user.current_location) < RADIUS and user.matchable:
             if len(available_users) > 0:
                 candidate = available_users.pop()
                 user.other_user = candidate
                 candidate.other_user = user
                 user.matchable = False
                 candidate.matchable = False
                 candidate.save()
                 user.save()
             elif user.matchable:
                 available_users.append(user)
         serialized = UpdateUserSerializer(user)
         return Response(serialized.data, status=200)
     return Response("Invalid request", status=400)
예제 #9
0
    def handle(self, *args, **options):

        # check for necessary parameters
        if 'filename' not in options:
            raise ValueError("no filename given")
        if 'scenario_id' not in options:
            raise ValueError("no scenario_id given")

        filename = options['filename']
        logger.info('starting to import file {}'.format(filename))

        # get scenario and root tile
        try:
            scenario_id = options['scenario_id']
            scenario = Scenario.objects.get(pk=scenario_id)
        except ObjectDoesNotExist:
            logger.error('invalid scenario id: {}'.format(scenario_id))
            raise ValueError(
                'Scenario with id {} does not exist'.format(scenario_id))

        order = 0
        with fiona.open(filename) as shapefile:
            for feature in shapefile:
                coordinates = feature['geometry']['coordinates']
                geometry = Point(coordinates)
                name = feature['properties'][NAME_FIELD]

                location = Location()
                location.scenario = scenario
                location.name = name
                location.direction = 0  # TODO: currently looking north all the time
                location.location = geometry
                location.order = order
                location.save()

                order += 1  # currently there is no order field in the shapefile

        logger.info("finished import to scenario_id {}".format(scenario_id))
예제 #10
0
def update_location(request):
    """ This method updates the location of the user """
    latitude = request.POST.get('latitude')
    longitude = request.POST.get('longitude')

    if not longitude or not latitude:
        return JsonResponse({
            'success': False,
            'error': 'Longitude or Latitude not defined'
        })

    try:
        location = Location.objects.get(user=request.user)
    except Location.DoesNotExist:
        location = Location(user=request.user)
    except Exception:
        return JsonResponse({
            'success': False,
            'error': 'Longitude or Latitude not defined'
        })

    location.update_location(longitude, latitude)
    return JsonResponse({'success': True})
예제 #11
0
def change_precision(request):
    """ This method allows change the precision of the location based on the user's preference"""
    precision = request.POST.get('precision')

    if not precision:
        return JsonResponse({'success': False, 'error': 'Precision not set'})

    if not re.match(r'[0-9]+', precision):
        return JsonResponse({
            'success': False,
            'error': 'Precision in wrong format'
        })

    precision = int(precision)

    if precision not in [LocationPrecision.PRECISE, LocationPrecision.ROUGH]:
        return JsonResponse({
            'success': False,
            'error': 'Precision in wrong format'
        })

    try:
        location = Location.objects.get(user=request.user)
    except Location.DoesNotExist:
        location = Location(user=request.user)
        location.save()
    except Exception:
        return JsonResponse({
            'success': False,
            'error': 'Could not find location object'
        })

    location.location_precision = precision
    location.save()

    return JsonResponse({'success': True})
예제 #12
0
def register_location(request, name, meter_x, meter_y, scenario_id):
    """Called when a new location (a.k.a. point of interest) is created at the given x, y.
    Returns a JsonResponse with 'creation_success' (bool) and, if true, the
    'location_id' of the new point of interest."""

    ret = {"creation_success": False, "location_id": None}

    if not Scenario.objects.filter(id=scenario_id):
        logger.warn(
            "Non-existent scenario with ID {} requested!".format(scenario_id))
        return JsonResponse(ret)

    scenario = Scenario.objects.get(id=scenario_id)

    location_point = geos.Point(float(meter_x), float(meter_y))

    lst = Scenario.objects.all()

    highest_order = 0
    for entry in lst:
        for location in entry.locations.all():
            if highest_order < location.order:
                highest_order = location.order

    new_location = Location(name=name,
                            location=location_point,
                            direction=0.0,
                            scenario=scenario,
                            order=highest_order + 10)

    new_location.save()

    ret["creation_success"] = True
    ret["location_id"] = new_location.id

    return JsonResponse(ret)
예제 #13
0
from location.models import Location
from school.models import School

import csv

with open('dataframe_v1.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for row in spamreader:
        row[2] = row[2].split(row[3])[0][0:-2]
        try:
            int(row[1].split(' ')[0])
            row[1] = ' '.join(row[1].split(' ')[1:])

        except ValueError:
            pass
        loc = Location(endereco=row[2],
                       bairro=row[3],
                       latitude=row[4],
                       longitude=row[5])
        loc.save()
        scho = School(nro_entidade=row[0], name=row[1], location=loc)
        scho.save()
        print(row)
예제 #14
0
    def setUp(self):
        api_key, key = APIKey.objects.create_key(name="bO4_UffT6FcimKuhY_qL-j")
        self.key = key

        location = Location(name="Orchid Country Club", lock_id="IGP1053e20f2")
        location.save()