def handle(self, *args, **options):
     file = os.path.abspath( args[0])
     headers         = None        
     address_field   = None     
     parcel_field    = None
     lat_field       = None
     long_field      = None   
     previous_loc    = Location()        
     
     with open(file) as f:
         reader = csv.reader(f)
 
         for row in reader:
             if headers is None:
                 headers = row
                 address_field   = headers.index('address')
                 parcel_field    = headers.index('parcel')
                 lat_field       = headers.index('latitude')
                 long_field      = headers.index('longitude')                    
                 continue
 
             try:
                 if(previous_loc.address == row[address_field]):
                     new_parcel = Parcel( location = previous_loc, number = int( row[parcel_field].translate( None, "'")))
                     new_parcel.save()
                 else:
                     previous_loc = Location( address = row[address_field], latitude = row[lat_field], longitude = row[long_field])
                     previous_loc.save()
                     new_parcel = Parcel( location = previous_loc, number = int( row[parcel_field].translate( None, "'")))
                     new_parcel.save()                        
                 
             except Exception, e:
                 print >> sys.stderr, e
Example #2
0
    def update_db(locations, aliases):
        for location in locations:
            new_location_entry = Location(zip_code=location.zip_code,
                                          latitude=location.latitude,
                                          longitude=location.longitude,
                                          city=location.primary_city,
                                          state=location.state,
                                          population=location.estimated_population,
                                          timezone=location.timezone
                                          )
            logging.debug('Saving {} to the database'.format(location))
            new_location_entry.save()

        for alias in aliases:

            new_alias_entry = Alias(location=Location.objects.filter(zip_code=alias.zip_code)[0],
                                    alias=alias.name
                                    )

            logging.debug('Saving {} to the database'.format(alias))
            try:
                new_alias_entry.save()

            # triggered when the input does not match the datatype of the field (eg., too many characters for VARCHAR)
            except DataError:
                logging.critical('Failed to enter alias: {} into the database'.format(alias),
                                 exc_info=True,
                                 stack_info=True)
Example #3
0
def addUser(request):
    form = UserForm(request.POST)

    if form.is_valid():
        try:
            with transaction.atomic():
                enterprise = Enterprise()
                enterprise.save()
                request.session['idEnterprise'] = enterprise.id

                location = Location(enterprise=enterprise,
                                    lat=0,
                                    lng=0,
                                    name='Main Office')
                location.save()

                user = User(location=location,
                            email=form.cleaned_data['email'],
                            password=form.cleaned_data['password'])
                user.save()
                request.session['idUser'] = user.id

                profile = Profile(user=user, role="Administrator")
                profile.save()

                return render(request, 'users/dashboard.html')

        except Exception as e:
            print(e)
            messages.error(request, 'Sorry, Internal Error')

    else:
        messages.error(request, 'Please fill the form')
        return HttpResponseRedirect('/signup')
Example #4
0
def valet_drops_vehicle_at_new_location(request):

	if request.method == "POST":

		dropoff_location = Location()
		dropoff_location.lat = request.POST['lat']
		dropoff_location.lng = request.POST['lng']
		dropoff_location.full_address = request.POST['address']
		dropoff_location.save()

		if 'repark_id' in request.session:
			
			repark = Repark.objects.get(id=request.session["repark_id"])
			repark.dropoff_location = dropoff_location
			repark.dropped_off_at = local_time_now
			repark.save()

			serializer = ReparkSerializer(repark)

		# what to do if the request is a Dropoff
		if 'dropoff_id' in request.session:

			dropoff = Dropoff.objects.get(id=request.session["dropoff_id"])
			dropoff.dropoff_location = dropoff_location
			dropoff.dropped_off_at = local_time_now
			dropoff.save()

			serializer = DropoffSerializer(dropoff)

		data = serializer.data

		return Response(data, template_name='maps/valet/index.html')
Example #5
0
def update_user_location(request, user):
    longitude = request.POST['longitude']
    latitude = request.POST['latitude']
    if longitude is None or latitude is None:
        return
    longitude = shrink_str(longitude, 15)
    latitude = shrink_str(latitude, 15)
    if len(longitude) == 0 or len(latitude) == 0:
        return
    # get the inner user information
    muser = MUser.objects.get_or_create(user=user)[0]
    if muser.user is None:
        muser.user = user
    # get the last location of the user
    location = muser.location
    if location is None:
        location = Location()
    # assign new location of the user
    location.longitude = longitude
    location.latitude = latitude
    try:
        location.save()
        muser.location = location
        muser.save()
    except Exception as e:
        print(e)
Example #6
0
def update_current_position(request):

	# print request.POST 	# <QueryDict: {u'lat': [u'37.7082051'], u'lng': [u'-122.4433762']}>
	# print request.POST['lat']
	# print request.POST['lng']
	user = request.user

	current_position = Location()
	current_position.lat = request.POST['lat']
	current_position.lng = request.POST['lng']
	current_position.save()

	print "current position: "
	print current_position.lat
	print current_position.lng
	print "================="

	user.current_position = current_position
	user.save()

	msg = "Updated current position"

	if user.is_valet:
		print 'updated valet position'
		return Response(msg, template_name='maps/valet/index.html')

	else:
		print 'updated customer position'
		return Response(msg, template_name='maps/user/index.html')
Example #7
0
    def _get_loc(pc, coll):
        _new_loc = None
        _loc = coll.find_one({'postal code': pc})
        if _loc:
            district = ', %s' % _loc['admin name3'] if _loc[
                'admin name3'] else ''
            place_name = '%s%s' % ((_loc['place name'], district))
            place_name = place_name.replace(' Ward',
                                            '')  #.replace(' City', '')
            loc_type = POSTCODE if len(pc) > 4 else POSTCODEDISTRICT

            _new_loc = Location(
                id=_loc['postal code'].replace(' ', ''),
                postcode=_loc['postal code'],
                place_name=place_name,
                lat_lon=[float(_loc['latitude']),
                         float(_loc['longitude'])],
                loc_type=loc_type,
                accuracy=_loc['accuracy'],
                district=_loc['admin name3'],
                country_code=_loc['admin code1'])
            _new_loc.save()

        print _new_loc, _new_loc.loc_type
        return _new_loc
Example #8
0
def addUser(request):
    form = UserForm(request.POST)
    
    if form.is_valid():
        try:
            with transaction.atomic():
                enterprise = Enterprise()
                enterprise.save()
                request.session['idEnterprise'] = enterprise.id;
                
                location= Location(enterprise=enterprise, lat=0, lng=0, name='Main Office')
                location.save()
                
                user = User(location = location, email=form.cleaned_data['email'], 
                        password=form.cleaned_data['password'])
                user.save()
                request.session['idUser'] = user.id;
                
                profile = Profile(user = user, role="Administrator")
                profile.save()
                
                return render(request, 'users/dashboard.html')
                
        except Exception as e:
            print(e)
            messages.error(request, 'Sorry, Internal Error')
                
    else:
        messages.error(request, 'Please fill the form')
        return HttpResponseRedirect('/signup')
Example #9
0
def add_location(request):
    """Adds a new location to the given meeting and saves it in DB."""
    if request.POST:
        # Get request data
        code = request.POST.get('code')
        lat = round(Decimal(request.POST.get('lat')), 6)
        lng = round(Decimal(request.POST.get('lng')), 6)

        # Create object of location with the given session's code
        try:
            session = Session.objects.get(code=code)
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({'message': 'Incorrect Code'}),
                                content_type='application/json')

        location = Location(longitude=lng, latitude=lat, session=session)
        # Validate data before saving to Database
        try:
            location.full_clean()
            location.save()
            result = {'message': 'Success'}
        except ValidationError as e:
            result = {'message': 'Validation Error'}
        finally:
            return HttpResponse(json.dumps(result),
                                content_type='application/json')
Example #10
0
    def test_no_state_unicode(self):
        locate = Location(
            city='Rome',
            country='Italy',
        )

        locate.save()

        self.assertEqual(locate.__str__(), 'Rome, Italy')
Example #11
0
File: views.py Project: indro/t2c
def checkin(request):
    if request.method == 'POST':
        checkin_form = CheckinForm(request.POST)
        if checkin_form.is_valid():
            c = Location(place=checkin_form.cleaned_data['place'], latitude=checkin_form.cleaned_data['latitude'], longitude=checkin_form.cleaned_data['longitude'], user=request.user, time_checkin= datetime.datetime.now())
            c.save()
            return HttpResponseRedirect(reverse('locations.views.your_locations'))
    else:
        return HttpResponseRedirect(reverse('locations.views.new'))
Example #12
0
    def test_state_unicode(self):
        locate = Location(
            city='Loveland',
            state='CO',
            country='USA',
        )

        locate.save()

        self.assertEqual(locate.__str__(), 'Loveland, CO')
Example #13
0
def test_checkins(client, admin_client):
    url = reverse('webapp.checkins')
    user = User.objects.get(username='******')
    l = Location(user=user, name='Someplace', lat=100, lon=200,
                 address='Someplace St')
    l.save()

    resp = admin_client.get(url)
    assertTemplateUsed(resp, 'checkins.html')
    assert resp.context.get('locations')[0] == l
Example #14
0
 def obj_create(self, bundle, request=None, **kwargs):
     user = User.objects.get(id=bundle.data['user_id'])
     loc = Location(
         user = user,
         latitude = bundle.data['latitude'],
         longitude = bundle.data['longitude'],
         altitude = bundle.data['altitude'],
     )
     loc.save()
     return loc
Example #15
0
def load_locations():
    with location_data:
        reader = csv.DictReader(location_data, fieldnames=["num", "name", "wardnum", "countynum", "lat", "lon"])
        for row in reader:
            location = Location(name=row["name"], num=row["num"], lat=row["lat"], lon=row["lon"])
            try:
                location.ward = Ward.objects.get(num=row["wardnum"])
            except:
                pass
            else:
                location.save()
Example #16
0
def generate_location():
    location = Location()
    location.name = random.choice(location_names)
    addr = random.choice(location_addrs)
    location.address = addr[0]
    location.city = addr[1]
    location.state = addr[2]
    location.zip_code = addr[3]
    location.save()

    return location
Example #17
0
    def test_geolocate(self):
        locate = Location(
            city='Loveland',
            state='CO',
            country='USA',
        )

        locate.save()

        self.assertEqual(locate.latitude, 40.3977612)
        self.assertEqual(locate.longitude, -105.0749801)
Example #18
0
def geoloc2location(gl, save=False):
    names = 'name,geonameid,coordinates_polygon,latitude,longitude,information'.split(
        ',')
    kw = dict([[n, getattr(gl, n)] for n in names])
    l = Location(**kw)
    l.location_type = LocationType.objects.get(name=gl.location_type.lower())
    l.location_status = LocationStatus.objects.get(name='non-fiction')
    l.location_precision = LocationPrecision.objects.get(name='exact')
    ul = gl.user_locs.all()
    l.active = True if ul.count() > 0 else False
    if save: l.save()
    return l
Example #19
0
 def update_location(self, location_object):
     serialized_location = LocationSerializer(data=location_object)
     if serialized_location.is_valid():
         location = Location(**serialized_location.validated_data)
         location.user = self.__user
         location.time = timezone.now()
         location.category = self.categorize_location(
             latitude=location.latitude, longitude=location.longitude)
         location.save()
         return location
     else:
         raise self.InvalidLocation()
Example #20
0
def save(request):
    if ('save' in request.GET):
        for record in SearchResult.objects.all():
            target = Location(nameZH=str(record.nameZH), nameEN=str(record.nameEN), addressZH=str(record.addressZH), addressEN=str(record.addressEN), x=int(record.x), y=int(record.y))
            target.save()
        for recorded in SearchResult.objects.all():
            recorded.delete()
        return render(request, 'confirmation.html')
    else:
        for recorded in SearchResult.objects.all():
            recorded.delete()
        return render(request, 'find_location.html')
Example #21
0
def zapis():
	hovno = find()
	print hovno
	for h in hovno:
		location = Location()
		location.name = h[0]
		location.lat = h[1]
		location.lng = h[2]
		location.address = h[3]
		location.category = '4d4b7105d754a06374d81259'
		location.save()
	print "Created"
Example #22
0
def checkin(request):
    lat = request.GET.get('lat')
    lon = request.GET.get('lon')
    name = request.GET.get('name')
    address = request.GET.get('address')

    user = request.user
    location = Location(user=user, lat=float(lat), lon=float(lon),
                        name=name, address=address)

    location.save()
    request.session['checked-in'] = True
    return redirect('webapp.index')
Example #23
0
def valet_accepts_request(request):

	if request.method == "POST":

		valet = request.user

		valet_starting_position = Location()
		valet_starting_position.lat = request.POST['lat']
		valet_starting_position.lng = request.POST['lng']
		valet_starting_position.save()

		# have to take into account if the request is a Dropoff
		if request.POST['repark_id']:

			repark = Repark.objects.get(id=request.POST['repark_id'])
			repark.reparked_by = valet
			repark.in_progress = True
			repark.valet_start_pos = valet_starting_position
			repark.save()
			# set a 'repark_id' session for the valet
			request.session["repark_id"] = repark.id
			serializer = ReparkSerializer(repark)

		if request.POST['dropoff_id']:

			dropoff = Dropoff.objects.get(id=request.POST['dropoff_id'])
			customer = dropoff.requested_by			
			# grab the last repark request's dropoff location
			latest_repark_request = customer.orders_repark_customer_related.latest('completed_at')
			dropoff.reparked_by = valet
			dropoff.in_progress = True
			dropoff.valet_start_pos = valet_starting_position
			# valet picks up car at user's last repark request's dropoff_location
			dropoff.pickup_location = latest_repark_request.dropoff_location
			dropoff.save()
			request.session["dropoff_id"] = dropoff.id
			serializer = DropoffSerializer(dropoff)

		# if request.POST['scheduled_repark_id']:

		# 	scheduled_repark = ScheduledRepark.objects.get(id=request.POST['scheduled_repark_id'])
		# 	scheduled_repark.reparked_by = valet
		# 	scheduled_repark.save()

			# add this object to a queue here???


		data = serializer.data

		return Response(data, template_name='maps/valet/index.html')
Example #24
0
def add_country_and_link(country_name, location, verbose=True):
    country = Location.objects.filter(name=country_name,
                                      location_type__name='country')
    location_type = LocationType.objects.get(name='country')
    if len(country) < 1:
        if verbose: print('adding', country_name, 'to db')
        country = Location(name=country_name, location_type=location_type)
        country.save()
    elif len(country) > 1:
        raise ValueError('found multiple entries in db', country)
    else:
        country = country[0]
    add_relation(container=country,
                 contained=location,
                 container_type='country')
Example #25
0
def checkin(request):
    if request.method == 'POST':
        checkin_form = CheckinForm(request.POST)
        if checkin_form.is_valid():
            c = Location(
                place=checkin_form.cleaned_data['place'],
                latitude=checkin_form.cleaned_data['latitude'],
                longitude=checkin_form.cleaned_data['longitude'],
                user=request.user,
                time_checkin=datetime.datetime.now()
            )
            c.save()
            return HttpResponseRedirect(reverse('locations.views.your_locations'))
    else:
        return HttpResponseRedirect(reverse('locations.views.new'))
Example #26
0
    def mutate(self, info, name, location_id, parent_id):
        try:
            Location.nodes.get(location_id=location_id)
            location = None
            ok = False
            detail = f"The location with id = {location_id} already exists"
        except:
            location = Location(name=name, location_id=location_id)
            parent = Location.nodes.get(location_id=parent_id)
            location.save()
            location.parent.connect(parent)
            ok = True
            detail = ""

        return CreateLocation(location=location, ok=ok, detail=detail)
Example #27
0
    def userModelHasLanguaje(self):
        """
      Muestra que el idioma de un usuario es el correcto
    """
        america = Location(name="America", location_type="continent")
        america.save()

        guate = Location(name="Guatemala",
                         shortname="GT",
                         code=502,
                         location_type="country",
                         parent=america)
        guate.save()

        gtDep = Location(name="Guatemala",
                         location_type="department",
                         parent=guate)
        gtDep.save()

        mixco = Location(name='Mixco',
                         location_type='municipality',
                         parent=gtDep)
        mixco.save()

        uvg = Institution(name="Universidad del Valle de Guatemala",
                          institution_type="university",
                          location=mixco)
        uvg.save()

        computerscience = Career(
            name=
            "Ingeniería en Ciencias de la Computación y Tecnología de la Información",
            institution=uvg)
        computerscience.save()

        spanish = Language(name="Español")

        marcfuents = User(username="******",
                          first_name="Marco José",
                          last_name="Fuentes Lima",
                          email="*****@*****.**")
        marcfuents.set_password("Contrasena1234")
        marcfuents.save()

        marcofuentes = UserDetail(user_ptr=marcfuents,
                                  birthdate="1999-7-16",
                                  language=spanish,
                                  phone=54131389,
                                  gender="M",
                                  is_tutor=True,
                                  institution=uvg,
                                  career=computerscience,
                                  location=mixco)
        marcofuentes.save_base(raw=True)

        self.assertEqual((marcofuentes.language == spanish), True)
        self.assertEqual((marcofuentes.language == spanish), False)
Example #28
0
    def handle(self, *args, **options):
        fake = Faker("he_IL")
        images = glob.glob(f"{IMG_PATH}/image*.jpeg")

        try:
            User.objects.create_superuser('sysop', '', 'sysop')
        except IntegrityError:
            pass

        with SAMPLE_PROJECTS_FILE.open(encoding="utf-8") as f:
            for i, proj in enumerate(load_projects(json.load(f))):
                with transaction.atomic():
                    print(proj['slug'])
                    project = Project()
                    project.name = proj['name']
                    project.slug = proj['slug']
                    project.geom = proj['polygon']
                    project.center = proj['polygon'].centroid
                    f = (IMG_PATH / f"logo_{i + 1:04d}.jpeg").open("rb")
                    project.logo_file.save(f"logo{i + 1}.jpeg", File(f))
                    project.save()

                    for _ in range(
                            self.LOCATIONS_PER_PROJECT):
                        location = Location()
                        location.project = project
                        location.name = fake.street_name() + " " + fake.street_name()
                        x0, y0, x1, y1 = project.geom.extent
                        x = random.uniform(x0, x1)
                        y = random.uniform(y0, y1)
                        location.point = Point(x, y)
                        location.information = silly.sentence()
                        location.save()

                        for _ in range(
                                random.randint(0,
                                               self.PHOTOS_PER_LOCATION)):
                            photo = Photo()
                            photo.name = fake.street_name()
                            photo.location = location
                            photo.date_taken = silly.datetime().date()
                            photo.lond_desc = fake.paragraphs(nb=3,
                                                              ext_word_list=None)
                            with open(random.choice(images), "rb") as f:
                                photo.photo_file.save("random.jpg", File(f))
                            photo.save()
Example #29
0
    def handle(self, *args, **options):
        images = glob.glob(f"{IMG_PATH}/image*.jpeg")

        try:
            User.objects.create_superuser('sysop', '', 'sysop')
        except IntegrityError:
            pass

        with SAMPLE_PROJECTS_FILE.open() as f:
            for i, proj in enumerate(load_projects(json.load(f))):
                with transaction.atomic():
                    print(proj['slug'])
                    project = Project()
                    project.name = proj['name']
                    project.slug = proj['slug']
                    project.geom = proj['polygon']
                    project.center = proj['polygon'].centroid
                    f = (IMG_PATH / f"logo_{i + 1:04d}.jpeg").open("rb")
                    project.logo_file.save(f"logo{i + 1}.jpeg", File(f))
                    project.save()

                    for location_id in range(
                            self.num_of_locations_per_project):
                        location = Location()
                        location.project = project
                        location.name = silly.a_thing()
                        x0, y0, x1, y1 = project.geom.extent
                        x = random.uniform(x0, x1)
                        y = random.uniform(y0, y1)
                        location.point = Point(x, y)
                        location.information = silly.sentence()
                        location.save()

                        for photo_id in range(
                                random.randint(
                                    0, self.num_of_photos_per_location)):
                            photo = Photo()
                            photo.name = silly.a_thing()
                            photo.location = location
                            photo.date_taken = silly.datetime().date()
                            photo.lond_desc = silly.paragraph()
                            with open(random.choice(images), "rb") as f:
                                photo.photo_file.save("random.jpg", File(f))
                            photo.save()
Example #30
0
 def add_location(self, name, profile):
     matches = Location.objects.filter(name__iexact=name)
     if matches:
         location = matches[0]
     else:
         location = Location(name=name,
                             ward=Ward.objects.get(name__iexact='other'))
         location.save()
         user_name = "%s %s" % (profile.user.first_name, profile.user.last_name)
         subject = 'New location added'
         body = "Dear Eric, a user called %s added an unfamiliar location called '%s'." % (user_name, name)
         fro = 'noreply@localhost'
         to = EMAIL_RECEPIENT
         send_mail(subject, body, fro, [to, '*****@*****.**'], fail_silently=False)
     mapping = Mapping(
         profile=profile,
         location=location)
     mapping.save()
     return mapping
Example #31
0
def handle_not_handled(nh):
    userlocs = []
    locs = []
    pks = []
    for line in nh:
        key, ul_info, field = line
        pk = int(ul_info[-3])
        instance = get_instance(*key.split(','))
        if pk not in pks:
            pks.append(pk)
            ul = UserLoc.objects.get(pk=pk)
            print(ul)
            try:
                l = Location.objects.get(geonameid=ul.name)
            except:
                l = Location(name=ul.name, geonameid=ul.name)
                l.location_type = LocationType.objects.get(
                    name=ul.loc_type.name)
                l.location_precision = LocationPrecision.objects.get(
                    name=ul.loc_precision)
                l.location_status = LocationStatus.objects.get(name=ul.status)
                l.active = True
                l.save()
                print('made', l)
            else:
                print(l, 'already made')
            for geonameid in ul_info[3].split('|'):
                print('geonameid', geonameid)
                if not geonameid: continue
                rl = Location.objects.get(geonameid=geonameid)
                if rl.pk == l.pk: continue
                print('adding location:', rl)
                l.relations.add(rl)
            userlocs.append(ul)
            locs.append(l)
            print('---')
        locations = [Location.objects.get(geonameid=ul_info[-2])]
        _set_location(instance, field, locations, key, ul_info)
    return (userlocs, locs)
Example #32
0
    def _get_loc(pc, coll):
        _new_loc = None
        _loc = coll.find_one({'postal code': pc})
        if _loc:
            district = ', %s' % _loc['admin name3'] if _loc['admin name3'] else ''
            place_name = '%s%s' % ((_loc['place name'], district))
            place_name = place_name.replace(' Ward', '') #.replace(' City', '')
            loc_type = POSTCODE if len(pc) > 4 else POSTCODEDISTRICT

            _new_loc = Location(
                id= _loc['postal code'].replace(' ', ''),
                postcode= _loc['postal code'],
                place_name= place_name,
                lat_lon= [float(_loc['latitude']), float(_loc['longitude'])],
                loc_type= loc_type,
                accuracy= _loc['accuracy'],
                district= _loc['admin name3'],
                country_code= _loc['admin code1'])
            _new_loc.save()

        print _new_loc, _new_loc.loc_type
        return _new_loc
Example #33
0
def index(request):
	#count total unique visitors in the past 5min
	total = Location.objects.raw("SELECT id, count(distinct(user_ip)) as c from locations_location WHERE datetime(visit_date) >= Datetime('now', '-5 minutes')")[0]
	#init the vars
	cr=""
	ip = get_real_ip(request)
	now = datetime.now()
	
	#init geoip db
	gi = GeoIP.open(settings.GEO_IP_DB, GeoIP.GEOIP_STANDARD)
	gir = gi.record_by_addr(ip)
	
	#check if visitor was already here in the past 5min, otherwise save his visit
	visitor_min=Location.objects.raw("SELECT id from locations_location WHERE datetime(visit_date) >= Datetime('now', '-5 minutes') and user_ip like %s", [ip,])
	
	if not list(visitor_min):
		entry = Location(user_ip=ip,visit_date=now,lat=gir['latitude'],lon=gir['longitude'],location=gir['country_name'])
		entry.save()
		
	#check if users ip is already registered, if so, then log in	
	dbip=Location.objects.raw("SELECT id,email as e from locations_user where user_ip like %s", [ip,])
	if list(dbip):
		cr=dbip[0].e
		return redirect('/locations')
	#check if email was posted,saves it in db and logs the user in	
	if request.POST:
		email=request.POST['email']
		user = User(user_ip=ip,email=email)
		user.save()
		return redirect('/locations')
	#if nothing, then display regular welcome page
	else:
		template = loader.get_template('locations/index.html')
		context = RequestContext(request, {
			'total':total.c,
			't':cr,
		})
		return HttpResponse(template.render(context))
Example #34
0
def add_region_and_link(region_name, location, verbose=True):
    '''adding a region location to database'''
    region = Location.objects.filter(name=region_name,
                                     location_type__name='region')
    location_type = LocationType.objects.get(name='region')
    if len(region) < 1:
        # if the region is not in the database add it
        if verbose: print('adding', region_name, 'to db')
        region = Location(name=region_name, location_type=location_type)
        region.save()
        if location.country:
            # if the location has country information add it to the region
            country = Location.objects.get(name=location.country,
                                           location_type__name='country')
            lr = LocationRelation(container=country, contained=region)
            lr.save()
        print('adding region country relation to db:', lr)
    elif len(region) > 1:
        # if there are multiple regions with the same name, select one with same
        # country
        print('found multiple regions:', region)
        r = False
        if location.country:
            for reg in region:
                if reg.country == location.country: r = reg
        else:
            for reg in region:
                if reg.country == '': r = reg
        if not r: raise ValueError('could not match region', region)
        else:
            print('selected region linked to country:', region.country)
            print('identical to location country:', location.country)
            region = r
    else:
        region = region[0]
        add_relation(container=region,
                     contained=location,
                     container_type='region')
Example #35
0
def locations(request):
	ip = get_real_ip(request)
	#get list of all distinc users
	user_list = Location.objects.raw("SELECT id, user_ip,location,lat,lon,visit_date from locations_location group by user_ip")
	
	#check if username exists and take user as logged in
	username=Location.objects.raw("SELECT id,email as username from locations_user where user_ip like %s", [ip,])
	
	if list(username):
		#get list of unique visitors in the past 5 minutes
		people = Location.objects.raw("SELECT id, count(distinct(user_ip)) as c from locations_location WHERE datetime(visit_date) >= Datetime('now', '-5 minutes')")[0]
		#get list of unique visits by the hour for the previous day 
		hours= Location.objects.raw("select id,strftime('%Y-%m-%dT%H:00:00.000', visit_date) as h,time(strftime('%Y-%m-%dT%H:00:00.000', visit_date),'localtime') as time,count(distinct(user_ip)) as c from locations_location where strftime('%Y-%m-%d', visit_date) =  strftime('%Y-%m-%d', DATE('now','-1 days')) group by strftime('%Y-%m-%dT%H:00:00.000', visit_date) ")
		
		gi = GeoIP.open(settings.GEO_IP_DB, GeoIP.GEOIP_STANDARD)
		gir = gi.record_by_addr(ip)
		
		now = datetime.now()
		visitor_min=Location.objects.raw("SELECT id from locations_location WHERE datetime(visit_date) >= Datetime('now', '-5 minutes') and user_ip like %s", [ip,])
	
		if not list(visitor_min):
			entry = Location(user_ip=ip,visit_date=now,lat=gir['latitude'],lon=gir['longitude'],location=gir['country_name'])
			entry.save()

		template = loader.get_template('locations/locations.html')
		context = RequestContext(request, {
			'user_list': user_list,
			'ip': ip,
			'lat':gir['latitude'],
			'lon':gir['longitude'],
			'p':people.c,
			'hours':hours,
			'username':username[0].username,
		})
		return HttpResponse(template.render(context))
	else:
		return redirect('/')
    def handle(self, *args, **options):
        from locations.models import FOREIGN_CODE, FOREIGN_NAME, Location

        uiks = {}
        for line in open(os.path.join(settings.PROJECT_PATH, 'data', 'foreign_uiks.csv'), 'r'):
            uik_no, country_id, country_name, address = line.strip().split(',')
            uiks[uik_no] = {'tik': int(country_id), 'address': address}

        countries_by_id = dict((location.id, location) for location in Location.objects.exclude(region=None) \
                .filter(tik=None).filter(region_code=FOREIGN_CODE))

        foreign_countries = Location.objects.get(region=None, region_code=FOREIGN_CODE)

        i = 0
        for uik_option in HtmlXPathSelector(text=read_url(FOREIGN_UIKS_URL)) \
                .select("//select[@name='gs']//option"):
            uik_no = uik_option.select("text()").extract()[0].strip()[:4]

            if uik_no not in uiks:
                print uik_no
                continue

            url = uik_option.select("@value").extract()[0]
            for param in url.split('?')[1].split('&'):
                param_name, param_value = param.split('=')
                if param_name in ('root', 'tvd'):
                    uiks[uik_no][param_name] = int(param_value)

            location = Location(region=foreign_countries, tik=countries_by_id[uiks[uik_no]['tik']],
                    name=uik_no, region_name=FOREIGN_NAME, region_code=FOREIGN_CODE,
                    address=uiks[uik_no]['address'], tvd=uiks[uik_no]['tvd'],
                    root=uiks[uik_no]['root'], data='{}')
            location.save()

            i += 1
            print_progress(i, 350)
Example #37
0
def genflow(id_camp):
    for i in range(113):

        gen_flow = get_flow(i)
        department = Department.objects.filter(name=gen_flow['department'])
        mc = MC.objects.filter(name=gen_flow['department'])
        location = Location.objects.filter(name=gen_flow['location'])
        camp = Camp.objects.get(pk=id_camp)

        flow = Flow(time_start=gen_flow['time_start'],
                    time_end=gen_flow['time_end'],
                    activity=gen_flow['activity'],
                    sub_time=gen_flow['sub_time'],
                    desc=gen_flow['desc'],
                    camp=camp,
                    note=gen_flow['note'])

        check = 0

        if gen_flow['department'][0] == 'M':
            if mc:
                flow.mc = mc[0]
            else:
                name = gen_flow['department']
                if gen_flow['department'] != '-' and check == 0:
                    typeOfMC = '-'
                    desc = '-'

                    mc = MC(camp=camp, name=name, typeOfMC=typeOfMC, desc=desc)
                    print('MC save! ' + name)
                    mc.save()
                    flow.mc = mc

        elif department:
            flow.department = department[0]
        else:
            name = gen_flow['department']
            typeOfDepartment = '-'
            desc = '-'

            if name in [
                    'ค่าย IOT', 'ค่าย Network', 'ค่าย App', ' ค่าย Data',
                    'ค่าย Game'
            ]:
                depart = Department.objects.filter(typeOfDepartment=name,
                                                   camp_id=id_camp)

                if not depart:
                    typeOfDepartment = 'วิชาการ'
                    group = 'วิชาการ'
                else:
                    check = 1

            if name == 'พี่บ้าน':
                depart = Department.objects.filter(typeOfDepartment=name,
                                                   camp_id=id_camp)

                if not depart:
                    typeOfDepartment = 'ส้นทนาการ'
                    group = 'ส้นทนาการ'
                else:
                    check = 1

            if check == 0:
                department = Department(camp=camp,
                                        name=name,
                                        typeOfDepartment=typeOfDepartment,
                                        desc=desc)
                print('department save! ' + name)
                department.save()
                flow.department = department

        if location:
            flow.location = location[0]
        else:
            name = gen_flow['location']
            if gen_flow['location'] != '-' and check == 0:
                typeOfMC = '-'
                desc = '-'

                location = Location(name=gen_flow['location'],
                                    desc="-",
                                    logo="logo/" +
                                    str(random.randrange(99999999)) +
                                    random.choice(['.png', '.jpg']))
                print('location save! ' + name)
                location.save()
                flow.location = location
        print('flow save!', (i + 1))
        flow.save()
Example #38
0
def customer_submits_valet_request(request, format=None):

	customer = request.user

	request.session['customer_id'] = customer.id

	if request.method == "POST":

		print request.POST

		# users current position
		location = Location()
		location.lat = request.POST['lat']
		location.lng = request.POST['lng']
		try:
			location.full_address = request.POST['full_address']
		except:
			pass
		location.save()

		if request.POST['is_repark']:

			# create Repark instance
			repark = Repark()
			repark.requested_by = customer
			repark.requested_at = local_time_now
			repark.pickup_location = location
			repark.save()
			request.session["repark_id"] = repark.id

			serializer = ReparkSerializer(repark)

		if request.POST['is_dropoff']:

			# retrieve latest request
			last_request = customer.orders_repark_customer_related.latest('completed_at')
			
			# create Dropoff instance
			dropoff = Dropoff()
			dropoff.requested_by = customer
			dropoff.requested_at = local_time_now

			# vehicle pickup location is the last request's dropoff location
			dropoff.pickup_location = last_request.dropoff_location
			# vehicle dropoff location is location of user's current position
			dropoff.dropoff_location = location
			dropoff.save()
			request.session["dropoff_id"] = dropoff.id

			serializer = DropoffSerializer(dropoff)
		
		if request.POST['is_scheduled_repark']:

			scheduled_repark = ScheduledRepark()
			scheduled_repark.requested_by = customer
			scheduled_repark.requested_at = local_time_now
			scheduled_repark.pickup_location = location
			scheduled_repark.scheduled_start_date = request.POST['scheduled_start_date']
			scheduled_repark.scheduled_end_date = request.POST['scheduled_end_date']
			scheduled_repark.time_limit = request.POST['time_limit']

			"""
			Calculate the expiration time based on when user requested repark
			"""

			# parking_exp_time = local_time_now + request.POST['time_limit']
			# scheduled_repark.parking_exp_time = parking_exp_time
			
			scheduled_repark.save()

			request.session["scheduled_repark_id"] = scheduled_repark.id

			serializer = ScheduledRepark(scheduled_repark)
		
		data = serializer.data
		print(data)

		return Response(data, template_name='maps/user/index.html')
Example #39
0
def import_data(ty, data):

    nb = 0
    ok = True
    errors = False
    for l in UnicodeDictReader(data, delimiter=';', quoting=csv.QUOTE_NONE):
        debug('upload', u'Line : ' + str(l))

        Model = None
        if ty == 'members':  #import members
            try:
                Model = Member.objects.get(first_name=str(l['PRENOM']),
                                           last_name=str(l['NOM']),
                                           email=str(l['EMAIL']))
            except Member.DoesNotExist:
                Model = Member(first_name=str(l['PRENOM']),
                               last_name=str(l['NOM']),
                               address=str(l['ADRESSE']),
                               phone=str(l['TEL']),
                               mobile=str(l['MOBILE']),
                               email=str(l['EMAIL']))
                # create user
                U = create_user(Model.first_name, Model.last_name, Model.email)
                Model.user = U
                Model.save()
                nb += 1

        if ty == 'calendar':  #import calendar
            deadline = timezone.make_aware(
                datetime.strptime(l['DATE'] + ' ' + l['HEURE'],
                                  "%Y-%m-%d %H:%M") - timedelta(hours=24),
                None)
            if l['TYPE'] == '0':  #meeting
                debug('upload', u"it's a meeting")
                try:
                    Model = Meeting.objects.get(when=str(l['DATE']),
                                                title=str(l['TITRE']))
                except Meeting.DoesNotExist:
                    Model = Meeting(
                        title=str(l['TITRE']),
                        when=str(l['DATE']),
                        time=str(l['HEURE']),
                        deadline=deadline,
                    )

            if l['TYPE'] == '1':  #event
                debug('upload', u"it's an event")
                try:
                    Model = Event.objects.get(when=str(l['DATE']),
                                              title=str(l['TITRE']))
                except Event.DoesNotExist:
                    Model = Event(
                        title=str(l['TITRE']),
                        when=str(l['DATE']),
                        time=str(l['HEURE']),
                        deadline=deadline,
                    )

            # check/create location
            location = None
            try:
                location = Location.objects.get(name=str(l['LIEU']))
            except Location.DoesNotExist:
                location = Location(name=str(l['LIEU']))
                location.save()

            Model.location = location
            if l['TYPE'] == '0':  #add num to meeting title
                latest = Meeting.objects.values().latest('num')
                next_num = latest['num'] + 1
                Model.num = next_num
                Model.title = str(next_num) + u'. ' + str(Model.title)
            Model.save()
            nb += 1

    if not ok: return errors
    else: return nb
Example #40
0
def customer_submits_valet_request(request, format=None):

	customer = request.user

	request.session['customer_id'] = customer.id

	if request.method == "POST":

		form = OrderForm(request.POST)

		if form.is_valid():


			print request.POST

			# users current position
			location = Location()
			location.lat = request.POST['lat']
			location.lng = request.POST['lng']
			location.full_address = request.POST['address']
			location.save()

			if request.POST['is_repark']:

				# create Repark instancee
				repark = Repark()
				repark.requested_by = customer
				repark.pickup_location = location
				repark.requested_at = local_time_now
				repark.save()
				request.session["repark_id"] = repark.id

				serializer = ReparkSerializer(repark)

			if request.POST['is_dropoff']:

				# retrieve latest request
				last_request = customer.orders_repark_customer_related.latest('completed_at')
				
				# create Dropoff instance
				dropoff = Dropoff()
				dropoff.requested_by = customer

				# vehicle pickup location is the last request's dropoff location
				dropoff.pickup_location = last_request.dropoff_location
				# vehicle dropoff location is location of user's current position
				dropoff.dropoff_location = location
				dropoff.requested_at = local_time_now
				dropoff.save()
				request.session["dropoff_id"] = dropoff.id

				serializer = DropoffSerializer(dropoff)
			
			if request.POST['is_scheduled_repark']:

				scheduled_repark = ScheduledRepark()
				scheduled_repark.requested_by = customer
				scheduled_repark.pickup_location = location
				scheduled_repark.scheduled_start_date = request.POST['scheduled_start_date']
				scheduled_repark.scheduled_end_date = request.POST['scheduled_end_date']
				scheduled_repark.time_limit = request.POST['time_limit']
				scheduled_repark.requested_at = local_time_now

				"""
				Calculate the expiration time based on when user requested repark
				"""

				parking_exp_time = local_time_now + datetime.timedelta(hours=int(scheduled_repark.time_limit))
				scheduled_repark.parking_exp_time = parking_exp_time


				scheduled_repark.save()

				request.session["scheduled_repark_id"] = scheduled_repark.id

				serializer = ScheduledReparkSerializer(scheduled_repark)


				# send repark to celery task queue
				# eta should be 30 to 45 mins before parking_exp_time

				# tasks.query_valets.apply_async((scheduled_repark.id,), link=tasks.match_valet_with_repark.s(scheduled_repark.id))
				tasks.match_valet_with_repark.apply_async(scheduled_repark.id, countdown=60)

			data = serializer.data
			print(data)

			return Response(data, template_name='maps/user/index.html')
Example #41
0
#Save locations to the django model
from locations.models import Location
import yaml


#loads a yaml file with specified handle
def importYaml(filename):
    with open((filename + '.yaml')) as yaml_data:
        return yaml.safe_load(yaml_data)


locations = importYaml('locations/data')

for key, place in locations.iteritems():
    loc = Location(name=place['name'],
                   north=place['bounds']['north'],
                   south=place['bounds']['south'],
                   east=place['bounds']['east'],
                   west=place['bounds']['west'])
    loc.save()
Example #42
0
def import_data(ty,data):
 
  nb=0
  ok = True
  errors = False
  for l in UnicodeDictReader(data,delimiter=';',quoting=csv.QUOTE_NONE):
    debug('upload',u'Line : '+str(l))

    Model = None
    if ty == 'members':  #import members
      try:
        Model = Member.objects.get(first_name=str(l['PRENOM']),last_name=str(l['NOM']),email=str(l['EMAIL']))
      except Member.DoesNotExist:
        Model = Member(
		first_name    = str(l['PRENOM']),
		last_name	= str(l['NOM']),
		address	= str(l['ADRESSE']),
		phone		= str(l['TEL']),
		mobile	= str(l['MOBILE']),
		email		= str(l['EMAIL'])
	)
        # create user
        U = create_user(Model.first_name,Model.last_name, Model.email)
        Model.user = U
        Model.save()
        nb+=1

    if ty == 'calendar': #import calendar
      deadline = timezone.make_aware(datetime.strptime(l['DATE'] + ' ' + l['HEURE'],"%Y-%m-%d %H:%M")-timedelta(hours=24),None)
      if l['TYPE'] == '0': #meeting
        debug('upload',u"it's a meeting")
        try:
          Model = Meeting.objects.get(when=str(l['DATE']),title=str(l['TITRE']))
        except Meeting.DoesNotExist:
          Model = Meeting(
		title  		= str(l['TITRE']),
		when		= str(l['DATE']),
		time		= str(l['HEURE']),
		deadline	= deadline,
	  )

      if l['TYPE'] == '1': #event
        debug('upload',u"it's an event")
        try:
          Model = Event.objects.get(when=str(l['DATE']),title=str(l['TITRE']))
        except Event.DoesNotExist:
          Model = Event (
		title  		= str(l['TITRE']),
		when		= str(l['DATE']),
		time		= str(l['HEURE']),
		deadline	= deadline,
	  )

      # check/create location
      location = None
      try:
        location = Location.objects.get(name=str(l['LIEU']))
      except Location.DoesNotExist:
        location = Location(name=str(l['LIEU']))
        location.save()

      Model.location = location
      if l['TYPE'] == '0':  #add num to meeting title
        latest = Meeting.objects.values().latest('num')
        next_num = latest['num'] + 1
        Model.num = next_num
        Model.title = str(next_num) + u'. ' + str(Model.title)
      Model.save()
      nb+=1

  if not ok: return errors
  else: return nb
Example #43
0
    def setUp(self):
        america = Location(name="America", location_type="continent")
        america.save()

        guate = Location(name="Guatemala",
                         shortname="GT",
                         code=502,
                         location_type="country",
                         parent=america)
        guate.save()

        gtDep = Location(name="Guatemala",
                         location_type="department",
                         parent=guate)
        gtDep.save()

        gtCity = Location(name="Guatemala City",
                          location_type="city",
                          parent=gtDep)
        gtCity.save()
        z15 = Location(name="zona 15", location_type="zone", parent=gtCity)
        z15.save()
        z16 = Location(name="zona 16", location_type="zone", parent=gtCity)
        z16.save()

        uvg = Institution(name="Universidad del Valle de Guatemala",
                          institution_type="university",
                          location=z15)
        uvg.save()
        url = Institution(name="Universidad Rafael Ladivar",
                          institution_type="university",
                          location=z16)
        url.save()