def _create_or_update_facility(self,submission,distance_threshold=1):
		"""
		Gets nearby submissions to determine duplicate by comparing name and submitter
		If the submitted facility already exists, it is updated; if not, it is created
		"""
		# # get facility/submissions within the set distance (in km)
		# distance_filter = (submission.location,D(km=distance_threshold))
		# for facility in Facility.objects.filter(location__dwithin=distance_filter):
			# if not facility.name or facility.name == submission.name: # TODO: use proper string comparison function
				# for field in 'name address type'.split():
					# new_value = getattr(submission,field,None)
					# existing_value = getattr(facility,field,None)
					# if new_value and not existing_value:
						# # currently keeps existing value
						# # TODO: if a value already exists, select the value with the highest submitter rating
						# setattr(facility,field,getattr(submission,field,None))
				# nearby_submissions = Submission.objects.filter(location__dwithin=distance_filter)
				# facility.location = nearby_submissions.collect().centroid()
				# facility.save()
				# return facility

		logging.info('The submission is new')
		facility_args = {}
		for field in 'name address type location'.split():
			facility_args[field] = getattr(submission,field)
		facility = Facility(**facility_args)
		facility.save()
		return facility
Exemple #2
0
 def delete(id):
     entity = Facility.get(id)
     if (entity is None):
         raise ValueError("Facility does not exists")
     else:
         entity.active = False
         Facility.save(entity)
def get_connections():
    connections = {}
    for facility in Facility.select(): 
        for transfer in facility.transfers_from:
            if facility.get_id() not in connections:
                connections[facility.get_id()] = {}
            if transfer.to_facility is not None:
                connections[facility.get_id()][transfer.to_facility.get_id()] = True

    return connections
Exemple #4
0
def add_facility():
    form = AddFacilityForm()
    if form.validate_on_submit():
        facility = Facility(acct_id=current_user.acct_id, name=form.name.data)
        db.session.add(facility)
        db.session.commit()
        log_message(
            f'user_id: {current_user.id} added facility: {facility.id}')
        flash('Facility created', 'success')
        return jsonify('OK'), 201
    else:
        return jsonify(form.errors)
Exemple #5
0
 def save(entity):
     if entity.key is None:
         entity = Facility.save(entity)
     else:
         current = Facility.get(entity.key.urlsafe())
         if current is not None:
             current.facility_name = entity.facility_name
             current.facility_address = entity.facility_address
             current.facility_zipcode = entity.facility_zipcode
             current.facility_state = entity.facility_state
             current.facility_city = entity.facility_city
             current.contact_name = entity.contact_name
             current.contact_email = entity.contact_email
             current.contact_phone = entity.contact_phone
             current.hours_of_operation = entity.hours_of_operation
             current.active = entity.active
             current.latitude = entity.latitude
             current.longitude = entity.longitude
             entity = Facility.save(entity)
         else:
             raise ValueError("Facility does not exists")
     return entity
Exemple #6
0
    def register_provider (self, message, role, password, last, first, alias, mobile):
        ''' Adds people into the system 
            JOIN CHW PASSWORD LAST FIRST ALIAS'''
        
        # If error in role, assume CHW
        role    = role.upper()
        if role == 'PHA':
            role    = Provider.PHA_ROLE
        else:
            role    = Provider.CHW_ROLE

        # retrieve clinic
        clinic      = Facility.by_alias(password)
        
        # PHA _must_ be affiliated to a Clinic
        if role == Provider.PHA_ROLE and clinic == None:
            message.respond(_(u"Registration Failed. PHA needs correct clinic ID. '%(input)s' is not.") % {'input': password})
            return True

        # Verify alias availability
        dumb    = Provider.by_alias(alias)
        if not dumb == None:
            message.respond(_(u"Registration Failed. Alias already in use by %(prov)s") % {'prov': dumb.display_full()})
            return True

        # Verify mobile slot
        dumb    = Provider.by_mobile(mobile)
        if not dumb == None:
            message.respond(_(u"Registration Failed. mobile number already in use by %(prov)s") % {'prov': dumb.display_full()})
            return True
        
        # Create provier
        provider    = Provider(alias=alias, first_name=first, last_name=last, role=role, active=True, clinic=clinic, mobile=mobile)
        provider.save()

        # send notifications
        message.respond(_(u"SUCCESS. %(prov)s has been registered with alias %(al)s.") % {'prov': provider.display_full(), 'al': provider.alias})
        
        if not provider.mobile == None:
            message.forward(provider.mobile, _(u"Welcome %(prov)s. You have been registered with alias %(al)s.") % {'prov': provider.display_full(), 'al': provider.alias})
    
        return True
Exemple #7
0
def facility_create_data_controller():
    # this is the facility data create handler
    toilet_id = request.values.get('toilet_id')
    shower = request.values.get('shower')
    soap = request.values.get('soap')
    hand_drier = request.values.get('hand_drier')
    toilet_paper = request.values.get('toilet_paper')
    wash_basin = request.values.get('wash_basin')

    new_facility = Facility(toilet_id=toilet_id,
                            shower=shower,
                            soap=soap,
                            hand_drier=hand_drier,
                            toilet_paper=toilet_paper,
                            wash_basin=wash_basin)

    db.session.add(new_facility)
    db.session.commit()

    return 'data input successful <a href="/facility/">back to Entries</a>'
def main(argv):
    db.connect()
    try:
        Detention.drop_table()
    except sqlite3.OperationalError:
        pass
    Detention.create_table()

    with open(argv[1]) as f:
        date_format = '%d-%b-%y'
        csv_file = DictReader(f)
        for line in csv_file:
            person = Person.select().where(Person.trac_id == line['TRAC Assigned Identifier for Individual'].strip()).get()
            facility = Facility.select().where(Facility.name == line['Detention Facility'].strip()).get()
            attrs = {
                'person': person,
                'facility': facility,
                'book_in_date': datetime.strptime(line['Book-In Date'].strip(), date_format).date(),
                'book_out_date': datetime.strptime(line['Book-Out Date'].strip(), date_format).date(),
                'book_out_reason': line['Reason for Book-Out'].strip(),
            }
            Detention.create(**attrs)
def main(argv):
    db.connect()
    try:
        Facility.drop_table()
    except sqlite3.OperationalError:
        pass
    Facility.create_table()

    with open(argv[1]) as f:
        csv_file = DictReader(f)
        for line in csv_file:
            attrs = {
                'name': line['name'].strip(),
                'official_name': line['official_name'].strip(),
                'url': line['url'].strip(),
            }
            if len(line['geo_latitude']):
                attrs['latitude'] = float(line['geo_latitude'].strip())
            if len(line['geo_longitude']):
                attrs['longitude'] = float(line['geo_longitude'].strip())
            Facility.create(**attrs)
Exemple #10
0
 def get_all(page, page_size, filters):
     return Facility.get_all(page, page_size, filters)
Exemple #11
0
 def get(id):
     return Facility.get(id)
             street_number = numbers[0]
         else:
             street_number = ""
         # cleaned address
         cleaned_street = cleaned_street.split(',')[0].split('-')[0]
         # generate address
         address = Address(province=row['Province'],
                           city=row['City'],
                           street=cleaned_street,
                           number=str(street_number),
                           cap=int(row['CAP']),
                           location=location)
         # generate price
         price = Price(row['Price'])
         # generate contact
         contact = Contact(phone=row['Phone'],
                           email=row['Email'],
                           website=row['Website'])
         #generate facility
         facility = Facility(type=row['Type'],
                             price=price,
                             contact=contact,
                             ranking=1,
                             address=address,
                             calendar=None)
         data.append(facility.toJSON())
 #print(data)
 print("2. Exporting assured json data")
 ds_out_path = '../../dataset/Formal Modeling/data/accomodations_assured.json'
 with open(ds_out_path, 'w') as ds_out_file:
     json.dump(data, ds_out_file)
Exemple #13
0
        geolocator = Nominatim(user_agent="me")
        tempLoc = ''
        tempLoc += str(i.geometry.y) + ',' + str(i.geometry.x)
        rawData = geolocator.reverse(tempLoc)
        location = Location(rawData.latitude, rawData.longitude, None)
        address = Address(
            rawData.raw['address']['state'], rawData.raw['address']['city']
            if 'city' in rawData.raw['address'] else None,
            rawData.raw['address']['road'] if 'road' in rawData.raw['address']
            else '' + ',' + rawData.raw['address']['suburb']
            if 'suburb' in rawData.raw['address'] else '',
            rawData.raw['address']['house_number']
            if 'house_number' in rawData.raw['address'] else None,
            rawData.raw['address']['postcode']
            if 'postcode' in rawData.raw['address'] else None, location)
        contact = Contact(phone=None, email=None, website=None)
        facility = Facility('CarSharingPark', None, contact, None, address,
                            None)
        data.append(facility.toJSON())
        num += 1
        if num % 10 == 0:
            print(str(num) + ' of items done:)')
    print('finished Iterating Dataset.')
    #%%
    # print(os.getcwd())

    ds_out_path = '../../dataset/Formal Modeling/data/CarSharing.json'
    with open(ds_out_path, 'w') as ds_out_file:
        json.dump(data, ds_out_file)
    print('finished dumping json and saved file.')
Exemple #14
0
 def add_facility(acct_id, name):
     facility = Facility(acct_id, name)
     db.session.add(facility)
     db.session.commit()
     return facility
Exemple #15
0
  -h, --help                      Show this screen and exit
  -a, --accomodation=<Y|N>        Wants accomodation [default: N]
  -oa, --output-allocations FILE  Specify output file [default: ./allocations.txt]
  -ou, --output-unallocated FILE  Specify output file [default: ./unallocated.txt]
  --version                       Show version.

"""
from __future__ import print_function

from docopt import docopt

from models import Facility


__version__ = '0.1.0'
# Create Facility instance representing the Amity Facility
amity = Facility('Amity')

if __name__ == '__main__':
    args = docopt(__doc__, version=__version__)
    print(args)

    if (args['create_office']):
        amity.create_rooms('office', args['<room_name>'])
    elif args['create_living_space']:
        amity.create_rooms('living_space', args['<room_name>'])
    elif args['add_fellows']:
        amity.add_fellows(args['<fellow_name>'], args['--accomodation'])
    elif args['add_staff']:
        amity.add_staff(args['<staff_name>'])
Exemple #16
0
     dataset = json.load(ds_file)
     # iterating each row
     for row in dataset:
         # creating location
         location = Location(float(row['Latitude']),
                             float(row['Longitude']), None)
         # generate address
         address = Address(province=None,
                           city=row['City'],
                           street=None,
                           number=None,
                           cap=None,
                           location=location)
         # generate price
         price = None
         # generate contact
         contact = Contact(phone=None, email=None, website=None)
         #generate facility
         facility = Facility(type="PARKINGAREA - {}".format(
             row['Name'] if row['Name'] != None else ''),
                             price=price,
                             contact=contact,
                             ranking=1,
                             address=address,
                             calendar=None)
         data.append(facility.toJSON())
 #print(data)
 print("2. Exporting assured json data")
 ds_out_path = '../../dataset/Formal Modeling/data/parking_areas_assured.json'
 with open(ds_out_path, 'w') as ds_out_file:
     json.dump(data, ds_out_file)
def export_facilities(filename):
    with open(filename, 'w') as f:
        data = []
        for facility in Facility.select().dicts():
            data.append(facility)
        json.dump(data, f)
Exemple #18
0
    #%% Loop
    print('Start iterating dataset ...')
    data = []
    for i in stazioni.itertuples():
        geolocator = Nominatim(user_agent="me")
        tempLoc = ''
        tempLoc += str(i.geometry.y) + ',' + str(i.geometry.x)
        rawData = geolocator.reverse(tempLoc)
        location = Location(rawData.latitude, rawData.longitude, None)
        address = Address(
            rawData.raw['address']['state'], rawData.raw['address']['city'],
            rawData.raw['address']['road'] + ',' +
            rawData.raw['address']['suburb']
            if 'suburb' in rawData.raw['address'] else '',
            rawData.raw['address']['house_number']
            if 'house_number' in rawData.raw['address'] else None,
            rawData.raw['address']['postcode']
            if 'postcode' in rawData.raw['address'] else None, location)
        contact = Contact(phone=None, email=None, website=None)
        facility = Facility('RailwayStation', None, contact, None, address,
                            None)
        data.append(facility.toJSON())
    print('finished Iterating Dataset.')
    #%%
    # print(os.getcwd())

    ds_out_path = '../../dataset/Formal Modeling/data/stazioni.json'
    with open(ds_out_path, 'w') as ds_out_file:
        json.dump(data, ds_out_file)
    print('finished dumping json and saved file.')
Exemple #19
0
from models import db, Facility

facility1 = Facility('リバーサイト', 1, '01', 'test')
facility2 = Facility('リバーサイト1', 2, '01', 'test')
facility3 = Facility('リバーサイト2', 3, '01', 'test')

# db.drop_all()
# db.create_all()

db.session.add_all([facility1, facility2])
db.session.add(facility3)

db.session.commit()
Exemple #20
0
        geolocator = Nominatim(user_agent="me")
        tempLoc = ''
        tempLoc += str(i.geometry.y) + ',' + str(i.geometry.x)
        rawData = geolocator.reverse(tempLoc)
        location = Location(rawData.latitude, rawData.longitude, None)
        address = Address(
            rawData.raw['address']['state'], rawData.raw['address']['city']
            if 'city' in rawData.raw['address'] else None,
            rawData.raw['address']['road'] if 'road' in rawData.raw['address']
            else '' + ',' + rawData.raw['address']['suburb']
            if 'suburb' in rawData.raw['address'] else '',
            rawData.raw['address']['house_number']
            if 'house_number' in rawData.raw['address'] else None,
            rawData.raw['address']['postcode']
            if 'postcode' in rawData.raw['address'] else None, location)
        contact = Contact(phone=None, email=None, website=None)
        facility = Facility('cycling_points', None, contact, None, address,
                            None)
        data.append(facility.toJSON())
        num += 1
        if num % 10 == 0:
            print(str(num) + ' of items done:)')
    print('finished Iterating Dataset.')
    #%%
    # print(os.getcwd())

    ds_out_path = '../../dataset/Formal Modeling/data/cycling_points.json'
    with open(ds_out_path, 'w') as ds_out_file:
        json.dump(data, ds_out_file)
    print('finished dumping json and saved file.')