Exemplo n.º 1
0
def loadAllBarData(fileName):
	with open('locationfixtures.json') as datafile:
		jdata = json.load(datafile)
		for bar in jdata:
			print bar
			l = Location(country = "USA",city = "College Station",place_name = bar['name'],twitter_handle = bar['twtter_handle'],twitter_id = bar['twitter_id'],fb_id = bar['fb_id'],lattitude_1 = bar['lattitude_1'],longitude_1 = bar['longitude_1'],lattitude_2 = bar['lattitude_2'],longitude_2 = bar['longitude_2'],lattitude_3 = bar['lattitude_3'],longitude_3 = bar['longitude_3'],lattitude_4 = bar['lattitude_4'],longitude_4 = bar['longitude_4'],lattitude_center = bar['lattitude_center'],longitude_center = bar['longitude_center'])
			l.save()
Exemplo n.º 2
0
class LocationLocationTest(TestCase):
    def setUp(self):
        # create the objects needed
        self.client = Client()
        self.location = Location()

        self.user = User(username='******')
        self.user.set_password('google')
        self.user.is_active = True
        self.user.save()
        
    
    def tearDown(self):
        self.client = None
        self.location = None
        self.user = None
        
    def test_save(self):
        self.location.location_name = 'Unit Testing'
        self.location.description = 'Unit Testing'
        
        # required fields
        self.location.creator = self.user
        self.location.creator_username = self.user.username
        self.location.owner = self.user
        self.location.owner_username = self.user.username
        self.location.status = True
        self.location.status_detail = 'active'
        self.location.enclosure_length = 0   
        self.location.timezone = 'America/Chicago'
        
        self.location.save()
        
        self.assertEquals(type(self.location.id), long)
Exemplo n.º 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
Exemplo n.º 4
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()
Exemplo n.º 5
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!'))
Exemplo n.º 6
0
def blog_save_location(country, city):
    try:
        location = Location.objects.get(country=ucwords(country), city=ucwords(city))
    except Location.DoesNotExist:
        location = Location(country=country, city=city)
        location.save()
    # For unittest maybe create duplicate location
    except Location.MultipleObjectsReturned:
        location = Location.objects.filter(country=ucwords(country), city=ucwords(city)).order_by('-id')[0]
        
    return location
Exemplo n.º 7
0
    def get_location(self, location_name):
        if location_name in [u'台灣', u'臺灣']:
            country = Location.TAIWAN
            location_name = u'臺灣'
        else:
            country = Location.CHINA

        try:
            location = Location.objects.get(name=location_name)
        except:
            location = Location(name=location_name, country=country)
            location.save()

        return location
Exemplo n.º 8
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))
Exemplo n.º 9
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'
        })
Exemplo n.º 10
0
    def setUp(self):
        # create the objects needed
        self.client = Client()
        self.location = Location()

        self.user = User(username='******')
        self.user.set_password('google')
        self.user.is_active = True
        self.user.save()
 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
Exemplo n.º 12
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()
Exemplo n.º 13
0
def locate_photo(request):
    data = json.loads(request.body.decode('utf-8') or "{}")
    photo = get_object_or_404(Photo,
                              id=data.get('photo_id'),
                              user=request.user)
    if 'place_id' in data:
        photo.location = Location.from_place_id(data['place_id'])
    elif 'location_id' in data:
        photo.location = Location.objects.get(id=data['location_id'])
    else:
        raise NotImplementedError('Must specify place_id or location_id')
    photo.save()
    return JsonResponse({})
Exemplo n.º 14
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)
Exemplo n.º 15
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})
Exemplo n.º 16
0
    def test_validate_invalid_product_location(self):
        location_r1 = Location.filter_queryset().get(code="R1")
        location_r2 = Location.filter_queryset().get(code="R2")
        officer = create_test_officer(custom_props={"code": "TSTSIMP1"})
        insuree = create_test_insuree(custom_props={"chf_id": "paysimp"},
                                      family_custom_props={"location": location_r1})  # Family in R1 !
        product = create_test_product("ELI1", custom_props={"location": location_r2})  # Product in R2 !
        (policy, insuree_policy) = create_test_policy2(
            product, insuree,
            custom_props={"value": 1000, "status": Policy.STATUS_IDLE})
        service = create_test_service("A")
        svc_pl_detail = add_service_to_hf_pricelist(service)
        product_service = create_test_product_service(product, service, custom_props={"limit_no_adult": 20})
        premium = create_test_premium(policy_id=policy.id, with_payer=False)
        payment, payment_detail = create_test_payment2(
            insuree_code=insuree.chf_id,
            product_code=product.code,
            officer_code=officer.code,
        )

        errors = validate_payment_detail(payment_detail)

        self.assertGreater(len(errors), 0)
        self.assertEqual(errors[0]["code"], PAYMENT_DETAIL_REJECTION_PRODUCT_NOT_ALLOWED)

        payment_detail.delete()
        payment.delete()
        premium.delete()
        product_service.delete()
        svc_pl_detail.delete()
        service.delete()
        policy.insuree_policies.all().delete()
        policy.delete()
        product.delete()
        insuree.delete()
        officer.delete()
Exemplo n.º 17
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)
Exemplo n.º 18
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))
Exemplo n.º 19
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))
Exemplo n.º 20
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})
Exemplo n.º 21
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()
Exemplo n.º 22
0
def new(request, form_class=SharedForm, success_url=None, 
        extra_context=None, template_name="sharing/new.html"):
    """
    Creates a new shared object.
    
    **Optional arguments:**
    
    ``extra_context``
        A dictionary of variables to add to the template context.
    
    """
    if success_url is None:
        pass
        #success_url = reverse('shares_list_yours', kwargs={ 'username': request.user.username })
        
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
                              
    if request.method == "POST" and request.POST["action"] == "create":
        geometry = None
        is_video = False
        is_photo = False
        
        data = request.POST.copy()
                
        comment = data.get("comment")
        station = data.get("station")
        location = data.get("location")
        media = data.get("media").strip('\'"')
        
        if comment:
            pass
        else:
            comment = ''
            #log.debug('comment is %s.', comment)
            
        if station:
            #pass
            log.debug('station is %s.', station)
            
        if media:
            parsed = urlparse(media)
            provider = parsed.netloc.split('.')

            if 'flickr' in provider:
                is_photo = True
                elements = parsed.path.split('/')
                flickr_id = elements[2]
                photo_id = elements[3]

            elif 'youtube' in provider:
                is_video = True
                video_id = parsed.query[2:]

        if media and is_photo:
            if geometry:
                latest = fetch_single_flickr_photo_with_geo(photo_id, flickr_id, geometry, request)
                return HttpResponseRedirect(reverse("shares_list_yours"))
            else:
                latest = fetch_single_flickr_photo(photo_id, flickr_id, request)
                return HttpResponseRedirect(reverse("shares_list_yours"))
                
        if media and is_video:
            if geometry:
                latest = fetch_single_youtube_video_with_geo(video_id, geometry, request)
                return HttpResponseRedirect(reverse("shares_list_yours"))
            else:
                latest = fetch_single_youtube_video(video_id, request)
                return HttpResponseRedirect(reverse("shares_list_yours"))
                
        if location:
            try:
                result = geocode(location)
            except UnboundLocalError:
                return SharePostBadRequest(
                    "Geocoding error for %s ." % escape(result))
            if result:
                geometry = Point(result[1][1], result[1][0])
                loc = Location(author=request.user, address=location, title=result[0], geometry=geometry, description=comment) 
                share = loc.save_as_shared()
                share.save()
                return HttpResponseRedirect(reverse("shares_list_yours"))
            else:
                pass
                #log.debug('we seemed to have failed')
                
        if request.POST["action"] == "create":
            share_form = form_class(request.user, request.POST)
    else:
        if request.method == 'GET':
            share_form = SharedFormGET()

    return render_to_response(template_name, {
        "form": share_form
    }, context_instance=RequestContext(request))
Exemplo n.º 23
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)
Exemplo n.º 24
0
def change_location(request):
    try:
        location = Location.objects.get(user=request.user)
    except Location.DoesNotExist:
        location = Location(user=request.user)
        location.save()

    if request.method == 'POST':
        form = LocationDetailsForm(request.POST)

        if form.is_valid():

            if form.has_location:
                long, lat = form.longlat_value
                location.longitude = long
                location.latitude = lat
                location.location_precision = form.cleaned_data['location_precision']
                location.location_trace = form.cleaned_data['location_trace']
                location.country = form.cleaned_data['country']
                location.position_updated = timezone.datetime.now(tz=timezone.get_current_timezone())
                location.save()
            else:
                location.longitude = None
                location.latitude = None
                location.location_trace = ''
                location.country = '-'
                location.position_updated = None
                location.save()

            return HttpResponseRedirect(reverse('profile', kwargs={'user_id': request.user.id}))

    else:
        form = LocationDetailsForm(initial={
            'longitude': location.longitude,
            'latitude': location.latitude,
            'location_precision': location.location_precision,
            'location_trace': location.location_trace,
            'country': location.country
        })

    return render(request, 'location_update.html', {'form': form})
Exemplo n.º 25
0
def location_from_place_id(request):
    data = json.loads(request.body.decode('utf-8') or "{}")
    location = Location.from_place_id(data['place_id'])
    return JsonResponse({'location': location.to_json(['id', 'name'])})
    def handle(self, *args, **options):
        User.objects.all().delete()

        usernames = list(itertools.product(['Anne', 'Robert', 'Marie', 'Tove', 'Jens', 'Ines'], ['Larson', 'Nilson', 'Weier', 'Wa', 'Halakkai', 'Czetec']))
        usernames = ["{}.{}".format(e[0], e[1]) for e in usernames]
        usernames.append('sheepy')

        skill_sample_list = ['running', 'flying', 'diving', 'programming', 'dancing', 'cutting video', 'jumping', 'sking', 'eating', 'washing', 'brooming', 'walking']
        sample_languages = dict(LANGUAGES).keys()

        for name in usernames:
            # Create the user
            user = create_user(name, '{}@heleska.de'.format(name), 'aqwsderf')

            # Add a location in some cases
            if random.random() > 0.2:
                long = str(random.randint(-900, 900) / 10.0)
                lang = str(random.randint(-1800, 1800) / 10.0)

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

            # Add some skills
            num_skills = random.randint(0, len(skill_sample_list))
            for value in random.sample(skill_sample_list, num_skills):
                slug, created = SlugPhrase.objects.get_or_create(value=value)
                UserSkill(user=user, slug=slug, level=random.randint(1, 5)).save()

            # Add some languages
            num_languages = random.randint(0, len(sample_languages))
            for value in random.sample(sample_languages, num_languages):
                LanguageSpoken(user=user, language=value).save()

        # Make my user superuser to access admin and so on
        u = User.objects.get(username='******')
        u.is_superuser = True
        u.is_staff = True
        u.status = True
        u.save()

        # Add some messages
        all_profiles = User.objects.all()

        num_messages = 50
        bodies = ["Soem body", "Another body", "1 2 3 4", "Giraffen sind cool"]

        for idx in range(num_messages):
            u1, u2 = random.sample(all_profiles, 2)

            m = Message.create_message(u1, u2, random.choice(bodies), silent=True)
            m.sent_time = datetime.datetime.now() - datetime.timedelta(days=random.randint(0, 30),
                                                                       minutes=random.randint(0, 60))
            m.save()

            if random.random() > 0.9:
                m.status = MessageStatus.READ

            if random.random() > 0.9:
                m.status = MessageStatus.DELETED

            m.save()

        organization_names = [
            ('The Auravana Project(TAP)', 'http://www.auravana.com', ['community', 'systems', 'scientific',
                                                                        'critical', 'no_money', 'open_source']),
            ('Buckminster Fuller Institute', 'http://www.bfi.org', ['systems', 'scientific'])
        ]

        for element in organization_names:
            ozt = [OrganizationTag.objects.get_or_create(value=e)[0] for e in element[2]]

            org = create_organization(name=element[0], website_url=element[1])
            org.enabled = True
            for e in ozt:
                org.tags.add(e)

            org.save()

        self.stdout.write(self.style.SUCCESS('Successfully create a bunch of users!'))