Beispiel #1
0
def hydrate(engine=Engine, session=Session):

    accounts = [
        m.Account(name='Burger Kwik'),
        m.Account(name='Chikin Likin'),
        m.Account(name='Pizza Face')]

    locations = [
        m.Location(
            name='BK1',
            address='314 Circle Ct',
            account=accounts[0]),
        m.Location(
            name='BK2',
            address='1350 American Way',
            account=accounts[0]),
        m.Location(
            name='CL1',
            address='2718 Euler Blvd',
            account=accounts[1])]

    users = [
        m.User(
            name='Peter',
            account=accounts[0]),
        m.User(
            name='Paul',
            account=accounts[0]),
        m.User(
            name='Mary',
            account=accounts[0]),
        m.User(
            name='Karen',
            account=accounts[2]),
        m.User(
            name='Richard',
            account=accounts[2])]

    features = _features(
        locations[0], 'low',
        datetime.date(2016, 12, 1), datetime.date(2016, 12, 7))
    features += _features(
        locations[0], 'high',
        datetime.date(2016, 12, 1), datetime.date(2016, 12, 7))

    session.add_all(accounts)
    session.add_all(locations)
    session.add_all(users)
    session.commit()
Beispiel #2
0
def create_edge(start_loc, end_loc, weight=0):
    print("Trying to create {} -> {}".format(start_loc, end_loc))
    start = models.Location()
    start.custom_load("name = ? COLLATE NOCASE", (start_loc, ))
    end = models.Location()
    end.custom_load("name = ? COLLATE NOCASE", (end_loc, ))

    edge = models.LocationEdge()
    edge.start_location_id = start.location_id
    edge.end_location_id = end.location_id
    edge.weight = weight
    edge.insert()

    print("Added {} to {}, Weight: {}".format(start.name, end.name,
                                              edge.weight))
Beispiel #3
0
def get_locations():
    if request.method == 'GET':
        locations = models.Location.query.all()
        lat, long = request.args.get('latitude'), request.args.get('longitude')

        def distance(p1, p2):
            x1, y1 = p1
            x2, y2 = p2
            import math
            return math.sqrt(((x1 - x2)**2) + ((y1 - y2)**2))

        if lat and long:
            filt_point = float(lat), float(long)
            locations.sort(
                key=lambda l: distance((l.latitude, l.longitude), filt_point))
        return jsonify(locations=[v.to_json() for v in locations])

    location = models.Location()
    location.name = request.form.get('name')
    location.type = request.form.get('type')
    location.zipcode = request.form.get('zipcode')
    lat = request.form.get('latitude')
    location.latitude = float(lat) if lat else None
    long = request.form.get('longitude')
    location.longitude = float(long) if long else None
    location.address = request.form.get('address')
    location.notes = request.form.get('notes')
    location.put()
    return jsonify(location=location.to_json())
Beispiel #4
0
def addNote(payload):
    id_location = None
    author =  M.User.objects.get(pk=payload["id_author"])
    #do we need to insert a location ? 
    if "id_location" in payload: 
        location = M.Location.objects.get(pk=payload["id_location"])
    else:
        location = M.Location()
        location.source = M.Source.objects.get(pk=payload["id_source"])
        location.ensemble = M.Ensemble.objects.get(pk=payload["id_ensemble"])        
        location.y = payload["top"]
        location.x = payload["left"]
        location.w = payload["w"]
        location.h = payload["h"]
        location.page = payload["page"]
        location.section = M.Membership.objects.get(user=author, ensemble=location.ensemble, deleted=False).section
        location.save()        
    comment = M.Comment()
    if "id_parent" in payload:
        comment.parent = M.Comment.objects.get(pk=payload["id_parent"])
    comment.location = location
    comment.author = author
    comment.body = payload["body"]
    comment.type = payload["type"]
    comment.signed = payload["signed"] == 1
    comment.save()
    return comment
Beispiel #5
0
async def pay(ctx, target_location, amount):
    if not config['game_ongoing']: return

    amount = int(amount)  # dumb.
    member = ctx.message.author
    p = models.Player()
    try:
        p.custom_load("discord_id = ?", (member.id, ))
    except Exception:
        await ctx.send("I don't have you listed as a player, {}\n\
            If you believe this is an error, please talk to a Lord or the King"
                       .format(member.mention))
        return
    # Make sure player has enough coins!!!
    if amount < 1:
        await ctx.send("You can't pay 0 or negative coins, {}".format(
            member.mention))
        return
    elif amount > p.coins:
        await ctx.send("{}, you don't have enough coins!".format(
            member.mention))
        return
    # Get team, current location id, available locations
    t = models.Team()
    t.load(p.team_id)
    current_loc = t.current_location_id
    avail_locs = graphanalyzer.get_next_location_list(t.team_id)
    # Make sure it's a valid target location.
    if target_location.lower() not in (name.lower()
                                       for name in avail_locs.keys()):
        await ctx.send(
            "I don't think {} is a valid location. Maybe you mistyped it?".
            format(target_location))
        return
    # Get the ID for the target location...
    target_loc = models.Location()
    target_loc.custom_load("name = ? COLLATE NOCASE", (target_location, ))

    edge = models.LocationEdge()
    edge.custom_load("start_location_id = ? AND end_location_id = ?", (
        current_loc,
        target_loc.location_id,
    ))
    # Store the payment in the db
    payment = models.Payment()
    payment.player_id = p.player_id
    payment.team_id = p.team_id
    payment.amount = amount
    payment.location_edge = edge.edge_id
    payment.time = helpers.get_game_day()
    payment.insert()

    # Remove coins from player's account.
    p.coins -= amount
    p.last_active_day = helpers.get_game_day()
    p.update()
    models.save()
    # Send confirmation message.
    await ctx.send("{} has paid **{}** coins toward **{}**".format(
        member.mention, amount, target_loc.name))
Beispiel #6
0
def create_location(db: Session,key:str,latitude:float,longitude:float,place_name:str,admin_name1:str):
	db_location = models.Location(key=key,latitude=latitude,longitude=longitude,place_name=place_name,admin_name1=admin_name1)
	db.add(db_location)
	db.commit()
	db.refresh(db_location)

	return db_location
Beispiel #7
0
 def mutate(self, args, context, info):
     new = m.Location(account_id=args.get('account_id'),
                      name=args.get('name'),
                      address=args.get('address'))
     db.Session.add(new)
     db.Session.commit()
     return AddLocation(location=new)
Beispiel #8
0
async def team(ctx):
    if not config['game_ongoing']: return
    member = ctx.message.author
    try:
        p = models.Player()
        p.custom_load("discord_id = ?", (member.id, ))
        if p.last_active_day != helpers.get_game_day():
            p.last_active_day = helpers.get_game_day()
            p.update()
            models.save()
    except Exception:
        await ctx.send("I don't think you're playing, {}\n\
            (If you think this is a mistake, please talk to a Lord or the King)"
                       .format(member.mention))
        return
    t = models.Team()
    t.load(p.team_id)
    l = models.Location()
    l.load(t.current_location_id)
    funding_table = paymentreducer.get_funding_table(p.team_id,
                                                     helpers.get_game_day())
    await ctx.send(
        "Your team is in **{}**, with at least **{}km** to go!\nHere is how today's funding is going:\n{}"
        .format(
            l.name,
            graphanalyzer.dijkstra(graphanalyzer.graph, t.current_location_id,
                                   0), "```" + funding_table + "```"))
Beispiel #9
0
 def post(self):
     name = self.get_argument("name")
     lng = self.get_argument("lng")
     lat = self.get_argument("lat")
     location = models.Location(name=name, lng=lng, lat=lat)
     self.db.add(location)
     self.db.commit()
     print name, lng, lat
     self.write('success')
def location_update(db: Session, loc: schemas.Location):
    db_loc = models.Location(latitude=loc.latitude,
                             longitude=loc.longitude,
                             vehicle=loc.vehicle)
    # db.query(models.Location).filter(models.Location.vehicle == vehicle).update({models.Location.latitude:loc.latitude, models.Location.longitude:loc.longitude},synchronize_session = False)
    db.add(db_loc)
    db.commit()
    db.refresh(db_loc)
    return db_loc
Beispiel #11
0
def add_or_return_location(place: str):
    location_row = get_location_by_place(place)
    if location_row is None:
        location = dict(place=place)
        location['latitude'], location['longitude'] = geo.get_lat_lon_for_place(location['place'])
        location_row = models.Location(**location)
        models.db.session.add(location_row)

    return location_row
def hydrate(engine=Engine, session=Session):

    accounts = {
        'bk': m.Account(name='Burger Kwik'),
        'cl': m.Account(name='Chikin Likin'),
        'pf': m.Account(name='Pizza Face')}

    locations = [
        m.Location(
            name='BK1',
            address='314 Circle Ct',
            account=accounts['bk']),
        m.Location(
            name='BK2',
            address='1350 American Way',
            account=accounts['bk']),
        m.Location(
            name='CL1',
            address='2718 Euler Blvd',
            account=accounts['cl'])]

    users = [
        m.User(
            name='Peter',
            account=accounts['bk']),
        m.User(
            name='Paul',
            account=accounts['bk']),
        m.User(
            name='Mary',
            account=accounts['bk']),
        m.User(
            name='Karen',
            account=accounts['pf']),
        m.User(
            name='Richard',
            account=accounts['pf'])]

    session.add_all(accounts.values())
    session.add_all(locations)
    session.add_all(users)
    session.commit()
Beispiel #13
0
def next_location_table(team_id):
    t = graphanalyzer.get_next_location_list(team_id)
    tab = []
    tab.append("```\n")
    for k, v in t.items():
        l = models.Location()
        l.custom_load("name = ?", (k, ))
        tab.append("{}: {} coins, at least {}km from the goal\n".format(
            k, v, graphanalyzer.dijkstra(graphanalyzer.graph, l.location_id,
                                         0)))
    tab.append("```")
    return ''.join(tab)
Beispiel #14
0
def addLocation():
    content = request.get_json()
    print(content)

    location = models.Location(content.get('name'))
    db.session.add(location)
    db.session.commit()
    response = {
        'status': 200,
        'message': "Location added to database",
    }
    return json.dumps(response,
                      sort_keys=True,
                      indent=4,
                      separators=(',', ': '))
Beispiel #15
0
def team_attempt_move(team_id):
    process_log = ""
    # Load team.
    t = models.Team()
    t.load(team_id)
    flns = paymentreducer.get_funding_list(team_id,
                                           helpers.get_game_day() - 1, False)
    fl = paymentreducer.get_funding_list(team_id,
                                         helpers.get_game_day() - 1, True)

    # Check for best-funded succesful path
    new_loc = t.current_location_id
    biggest_funding = -1
    was_sabotaged = False
    for k, v in flns.items():
        le = models.LocationEdge()
        le.load(k)
        if v >= le.weight and v > biggest_funding:
            new_loc = le.end_location_id
            biggest_funding = v
            if fl[k] < le.weight:
                was_sabotaged = True
            else:
                was_sabotaged = False

    if biggest_funding == -1:
        process_log = "The {} didn't raise enough to book passage anywhere...".format(
            t.name)
    else:
        l = models.Location()
        l.load(new_loc)
        if was_sabotaged:
            process_log = "The {} tried to travel to {}, but someone sabotaged them and they were stopped by the Black Cats!".format(
                t.name, l.name)
        else:
            t.current_location_id = new_loc
            t.update()
            process_log = "The {} have successfully reached {}!".format(
                t.name, l.name)

    models.save()
    return process_log + "\n"
Beispiel #16
0
def get_funding_table(team_id, day=-1):
    #f = get_funding_list(team_id, day=helpers.get_game_day(), show_sabotage=False)
    f = get_funding_list(team_id, day, show_sabotage=False)
    if len(f.keys()) == 0:
        return "No payments have been made yet today!"

    t = models.Team()
    t.load(team_id)
    tab = []
    row_format = "{:<18}{:<8}{:<8}\n"
    tab.append(row_format.format('Location', 'Toll', 'Paid'))
    tab.append("-" * (34) + "\n")
    # FIXME toooo many queries
    for k, v in f.items():
        le = models.LocationEdge()
        le.load(k)
        l = models.Location()
        l.load(le.end_location_id)
        tab.append(row_format.format(l.name, le.weight, v))

    return "".join(tab)
Beispiel #17
0
def add_location(request):
    # Current time in milliseconds
    post_time = int(time.time() * 1000)

    name = request.get('PlaceName')
    logging.info("Place name is %s" % name)
    address = request.get('Street_number') + " " + request.get('Street_name')
    city = request.get('City')
    state = request.get('State')
    latitude = request.get('Latitude')
    longitude = request.get('Longitude')

    location = models.Location()
    if len(name) <= 80:
        location.name = name
    if len(address) <= 48:
        location.address = address
    if len(city) <= 32:
        location.city = city
    if len(state) == 2 and state.isalpha():
        location.state = state
    location.time_created = post_time
    location.key = ndb.Key(models.Location, request.get("PlaceID"))
    try:
        location.latitude = float(latitude)
    except ValueError:
        pass
    try:
        location.longitude = float(longitude)
    except ValueError:
        pass
    if (location.name is not None and location.address is not None
            and location.city is not None and location.state is not None
            and location.latitude is not None
            and location.longitude is not None):
        location.put()
        return str(location.key.id())
    else:
        return None
Beispiel #18
0
def geocode_location(location, api_key=None):
    """Use Google to geocode a location string.

    For high-volume traffic, you will need to specify an API-key.
    """
    GEOCODE_URL = "http://maps.google.com/maps/geo"
    params = [('q', location), ('sensor', 'false'), ('output', 'json')]

    if api_key:
        params += [('key', api_key)]

    resp = utils.open_url(GEOCODE_URL, params)
    data = json.loads(resp.read())

    if data['Status']['code'] != 200:
        raise exceptions.GeocodeException('Unable to geocode this location')

    best_match = data['Placemark'][0]
    address = best_match['address']
    lon, lat, _ = best_match['Point']['coordinates']

    location = models.Location(lat, lon, address)
    return location
Beispiel #19
0
 def insert_program_location(self):
     pro_loc_list = []
     for row in self.content:
         locations = self.get_locations(row)
         for location in locations:
             loc_name = location[0]
             loc_post = location[1]
             loc_lat = location[2]
             loc_lon = location[3]
             address = location[4]
             # Check that the location is not empty
             if loc_name != 'None' and loc_name != '' and loc_post != 'None' and loc_post != '' and loc_lat != 'None' and loc_lat != '' and loc_lon != 'None' and loc_lon != '':
                 # Check that location does not already exist
                 check = models.Location.objects.filter(
                     program_andar_number=row[
                         self.postal_index['Program Andar #']],
                     program_name=row[self.postal_index['Program Name']],
                     location=loc_name,
                     postal_code=loc_post,
                     latitude=loc_lat,
                     longitude=loc_lon).exists()
                 # Insert data into database
                 if not check:
                     loc = models.Location(
                         program_andar_number=row[
                             self.postal_index['Program Andar #']],
                         program_name=row[
                             self.postal_index['Program Name']],
                         location=loc_name,
                         postal_code=loc_post,
                         latitude=loc_lat,
                         longitude=loc_lon,
                         address=address,
                         website=row[self.postal_index['Website']])
                     if loc not in pro_loc_list:
                         pro_loc_list.append(loc)
     models.Location.objects.bulk_create(pro_loc_list)
Beispiel #20
0
import models
'''
Every Location has:
    name - str
    visited (has the user come here before?) - bool
    view (text that shows up when a user enters the view command) - str
    ooi (objects of interest on the location) - list of ObjectOfInterest objects
    chain (locations to the north/west/east/south) - Chain object

Every object has:
    name - str
    descrip (the text that shows up when user enters the examine command) - str
    used_with (like key can have lock as its used_with) - a list of ObjectOfInterest objects
'''

forest = models.Location
cave = models.Location

beach = models.Location(
    name="Beach",
    visited=False,
    view="A beach with bright sunlight and waves crashing on the"
    "shore. Straight ahead is a forest, while to the right"
    "is a cave. The cave gives off an eerie vibe.",
    ooi=['rock', 'broken boat'],
    chain=models.Chain(north=forest, west=cave))
Beispiel #21
0
    def createDatabase(self):
        """Create the Required Database Objects"""
        session = models.meta.Session()
        arSession = self.Session()
        #log.setLevel(logging.WARNING)
        deploymentName = "archRock"
        houseName = self.houseAddress

        theDep = session.query(models.Deployment).filter_by(name=deploymentName).first()
        log.debug("Checking for existing deployment {0}".format(theDep))
        if theDep is None:
            #Create a new deployment
            theDep = models.Deployment(name=deploymentName)
            session.add(theDep)
            session.flush()
            log.debug("Adding Deployment to database {0}".format(theDep))


        #And check for Houses
        theHouse = session.query(models.House).filter_by(address=houseName).first()
        log.debug("Checking for house {0}".format(theHouse))
        if theHouse is None:
            theHouse = models.House(address=houseName,
                                    deploymentId = theDep.id)
            session.add(theHouse)
            session.flush()
            log.debug("Adding New House {0}".format(theHouse))


        self.theHouse = theHouse

        emptyRoom = session.query(models.RoomType).filter_by(name="Unocupied").first()

        nodeMap = {}
        #Temp storage for <ADDDR> <Node>
        addrMap = {}

        #We want to setup nodes / Rooms / Locations based on the node_dimension table
        log.info("Setting Up Nodes")
        nodeQry = arSession.query(Ar_Node)
        for item in nodeQry:
            #Dont bother with the router
            if item.name == "archrock-router":
                continue

            #Check / Create a node if required
            nodeId = int(item.addr[8:],16)
            log.debug("{0} {1} {2}".format(item,item.addr,nodeId))
            
            #nodeId = BASE_NODE_ID + item.short_addr
            
            theNode = session.query(models.Node).filter_by(id = nodeId).first()
            if theNode is None:
                theNode = models.Node(id=nodeId)
                session.add(theNode)
                session.flush()
                log.debug("Creating New Node {0}".format(theNode))
            
            #Next we create a room / Location
            roomName = item.name
            if not roomName == "":
                log.debug("Room Name is {0}".format(roomName))

                theRoom = session.query(models.Room).filter_by(name=roomName).first()
                if theRoom is None:
                    theRoom = models.Room(name=roomName,
                                          roomTypeId=emptyRoom.id)
                    log.debug("Creating Room {0}".format(theRoom))
                    session.add(theRoom)
                    session.flush()

                #And now we can turn this room into a Location
                theLocation = session.query(models.Location).filter_by(houseId=theHouse.id,
                                                                       roomId = theRoom.id).first()
                if theLocation is None:
                    theLocation = models.Location(houseId = theHouse.id,
                                                  roomId = theRoom.id)
                    session.add(theLocation)
                    log.debug("Creating Location {0}".format(theLocation))
                    session.flush()
            #Last thing we create a mapping between the node and the Location
            nodeMap[item.node_key] = [theNode,theLocation]
            addrMap[item.addr] = theNode

        #log.debug(nodeMap)
        self.nodeMap = nodeMap
        #We also need to do mapping for sensor types etc
        #theQry = arSession.query(Source)

        #Map the Types we are expecting to types from the database
        sensorTypeMap = {}
        log.info("Mapping Sensor Types")
        for sType in ALLOWED_TYPES:
            theType = session.query(models.SensorType).filter_by(name=sType[1]).first()
            
            log.debug("AR: {0}  Local {1}".format(sType,theType))
            sensorTypeMap[sType[0]] = theType
            
        #log.debug(sensorTypeMap)

        sensorMap = {}
        
        sQry = arSession.query(Source)
        for item in sQry:
            thisItem = sensorTypeMap.get(item.source,None)
            if thisItem:
                sensorMap[item.datasource_key] = sensorTypeMap[item.source]

        self.sensorMap = sensorMap
        log.setLevel(logging.DEBUG)
        
        log.info("Commtitting Changes")
        session.flush()
        session.commit()
Beispiel #22
0
  def post(self):
    """
    This script fetches the information for a track. It is meant to be called via TaskQueue.
    """
     
    logging.info("Working the taskqueue. Fetching a new track.")
    
    try:                  
      # check, if track is not already overdue (which may happen, if memcache fails, which happens from time to time)
      if (self.request.get('time_track_added_to_queue') == '' or \
         time.time() > (int(self.request.get('time_track_added_to_queue')) + settings.TRACK_BACKEND_UPDATE_LIFETIME * 60)):
        # track is overdue
        logging.info("Track with Track ID %s is overdue with time %s." % ((self.request.get('track_id') or ''), (self.request.get('time_track_added_to_queue') or ''))) 
        self.response.out.write("done") # finished processing script          
        return # return 200. task gets deleted from task queue           
        
      # fetch track info from memcache
      track_id = self.request.get('track_id')
      track = memcache.get(track_id, namespace="backend_update_track")
      if track is None:
        logging.warning("Fetching memcache item %s failed in backend track update" % track_id)  
        self.response.set_status(500)
        return
          
      logging.info("Received the track \"%s\" by \"%s\" (id: %s, created at: %s)." % \
                  (track['title'], track['user']['username'], track['id'], track['created_at']))
                  
      # check if track meets our needs
      if not track['streamable'] or track['sharing'] != 'public':
        logging.info("The track does not match our needs. Will not be used.")
        if not memcache.delete(track_id, namespace="backend_update_track"):
          logging.error("Deletion from Memcache was not successfull.")
          self.response.set_status(500)
        logging.info("End of track update, because track didn't fit our needs.")          
        self.response.out.write("done") # finished processing script          
        return # return 200. task gets deleted from task queue

      # check if track is already in the datastore
      if models.Track.all().filter('track_id', int(track['id'])).get(): 
        logging.info("The track already is in the datastore.")
        logging.info("End of track update, because the track is already in the datastore.")       
        self.response.out.write("done") # finished processing script                  
        return # return 200. task gets deleted from task queue
      
      # check if user is already in the datastore     
      user = models.User.all().filter('user_id', int(track['user_id'])).get()
      if user:
        logging.info("User is already in datastore as permalink: %s user_id: %i" % (user.permalink, user.user_id))
        location = user.location                                                        
        backend_utils.update_location_data(track, location)                                                   
      else:
        # fetch complete user data
        logging.info("User is not in the datastore yet. Fetching user data.")
        track['user'] = backend_utils.open_remote_api("/users/%s.json?consumer_key=%s" % (track['user_id'], settings.SOUNDCLOUD_CONSUMER_KEY), 'soundcloud') 
        logging.info("User data fetched.")              
        
        # determining location
        try:
          if track['user']['city'] == 'None' or track['user']['country'] == 'None' or \
            track['user']['city'] == None or track['user']['country'] == None:
            raise RuntimeError
          location = models.Location.all().filter('city', unicode(track['user']['city'])).filter('country', unicode(track['user']['country'])).get()
          if location:
            logging.info("Location is already in datastore: city: %s country: %s lat / lon: %s / %s" % \
                        (track['user']['city'], track['user']['country'], location.location.lat, location.location.lon)) 
            backend_utils.update_location_data(track, location)           
          else:
            logging.info("Looks as if location is not in the datastore yet. Fetching it ...")
            geocached_location = backend_utils.get_location(track['user']['city'], track['user']['country']) 
            if geocached_location['city'] == 'None' or geocached_location['country'] == 'None' or \
               geocached_location['city'] == None or geocached_location['country'] == None:             
              raise RuntimeError
            # check again, if location not in datastore already
            location = models.Location.all().filter('location', geocached_location['location']).get()              
            if location:    
              logging.info("Location has yet already been in datastore. Updating it.") 
              backend_utils.update_location_data(track, location)                                                                                                                                           
            else:
              location = models.Location( \
                          location = geocached_location['location'],
                          city = unicode(geocached_location['city']),
                          country = unicode(geocached_location['country']),   
                          track_counter = 1,
                          last_time_updated=datetime.datetime.now())
              logging.info("Saving new location for user \"%s\" lat/lon %s/%s in city/country %s/%s to datastore ..." % \
                          (track['user']['username'], location.location.lat, location.location.lon, location.city, location.country))
              location.put()
              backend_utils.update_location_genre_data(track, location)
              logging.info("New location saved to datastore.") 
                                                                   
        except RuntimeError:
          logging.info("No Location for User \"%s\" with City/Country: \"%s / %s\"." % \
                      (track['user']['username'], track['user']['city'], track['user']['country']))
          if not memcache.delete(track_id, namespace="backend_update_track"):
            logging.error("Deletion from Memcache was not successful.") 
            self.response.set_status(500)
            logging.info("End of track update because could not be geolocated.")              
          self.response.out.write("done") # finished processing script          
          return # return 200. task gets deleted from task queue         
        
        logging.info("Saving user data (id: %s, permalink: %s) to datastore ..." % (track['user']['id'], track['user']['permalink']))
        user = models.User( \
                  user_id = track['user']['id'],
                  permalink = track['user']['permalink'],
                  permalink_url = track['user']['permalink_url'],
                  username = track['user']['username'],
                  fullname = track['user']['full_name'],
                  avatar_url = track['user']['avatar_url'],
                  location = location.key())           
        user.put()
        logging.info("User saved to datastore.")     

      backend_utils.write_track_to_datastore(track, user, location)
        
      if not memcache.delete(track_id, namespace="backend_update_track"):
        logging.error("Deletion from Memcache was not successful.")
        self.response.set_status(500)
        self.response.out.write("done")
        return

      logging.info("End of track update.")      
      self.response.set_status(200)
      self.response.out.write("done") # finished processing script
      return # return 200. task gets deleted from task queue 
  
    except DeadlineExceededError:
      logging.warning("Backend Update for track id: %s has been canceled due to Deadline Exceeded" % track_id)
      for name in os.environ.keys():
        logging.info("%s = %s" % (name, os.environ[name]))
      self.response.set_status(500)
      return       
Beispiel #23
0
import models
from neomodel import db

db.cypher_query("match(n) detach delete n;")

location = models.Location(name="thing")
location.save()

person = models.Patient(uuid="1", name="dave")
person.save()

person.address.connect(location)
Beispiel #24
0
def update_data():
    models.db.drop_all()
    models.db.create_all()
    import os, csv
    FILE_PATH = os.path.abspath(os.path.dirname(__file__))
    vehicles = models.Vehicle.query.all()

    locations = models.Location.query.all()
    for l in locations:
        models.db.session.delete(l)
    models.db.session.commit()

    all_locations = []

    with open(os.path.join(FILE_PATH, "../sample_locations.csv")) as csvfile:
        csvreader = csv.reader(csvfile)
        first = True
        for row in csvreader:
            if first:
                first = False
                continue

            l = models.Location()
            l.name = row[0]
            l.type = row[1]
            l.zipcode = row[2]
            try:
                l.latitude = float(row[3])
                l.longitude = float(row[4])
            except ValueError:
                pass
            l.address = row[5]
            l.notes = row[6]
            models.db.session.add(l)
            all_locations.append(l)
    models.db.session.commit()

    users = models.User.query.all()
    for u in users:
        models.db.session.delete(u)
    models.db.session.commit()

    with open(os.path.join(FILE_PATH, "../sample_users.csv")) as csvfile:
        csvreader = csv.reader(csvfile)
        first = True
        for row in csvreader:
            if first:
                first = False
                continue

            l = models.User()
            l.name = row[0]
            l.image_url = row[1]
            try:
                l.latitude = float(row[2])
                l.longitude = float(row[3])
            except ValueError:
                pass
            l.email = row[4]
            l.set_password(row[5])
            l.notes = row[6]
            for i in [int(s) for s in row[7].split()]:
                all_locations[i - 1].users.append(l)
            models.db.session.add(l)
    for l in all_locations:
        models.db.session.add(l)
    models.db.session.commit()

    csvfile = open(os.path.join(FILE_PATH, "../sample_data.csv"))
    csvreader = csv.reader(csvfile)

    for v in vehicles:
        models.db.session.delete(v)
    first = True
    for row in csvreader:
        if first:
            first = False
            continue
        v = models.Vehicle()
        v.year = row[0]
        v.vin = row[1]
        v.make = row[2]
        v.model = row[3]
        v.color = row[4]
        v.status = row[5]
        img_url = "http://cdn.lhmws.com"
        img_path = "/photos/large/" + v.vin + "_1.jpg"
        # if url_exists(img_url, img_path):
        v.image = img_url + img_path
        models.db.session.add(v)
    models.db.session.commit()
    return "All sample data up to date!"
Beispiel #25
0
eggs = models.Object(name='eggs')

sleep = models.Action(name='sleep', transitive=False)
get_eggs = models.Action(name='get eggs', transitive=True, obj=eggs)

henry = models.Character(name=models.Name(name='Henry', proper=True),
                         gender='male',
                         age=25,
                         transit_modes=['walk', 'bike', 'drive', 'bus'],
                         posture='standing',
                         desires=[get_eggs])

home = models.Location(
    name=models.Name(name='home', proper=True),
    size='building',
    satisfies=[],
)
bedroom = models.Location(
    name=models.Name(name='bedroom', proper=False),
    size='room',
    satisfies=[sleep],
    objects_present=[
        models.Object(name=models.Name(name='bed', proper=False)),
        models.Object(name=models.Name(name='desk', proper=False)),
        models.Object(name=models.Name(name='chair', proper=False)),
    ])
bedroom.sublocation(home)

store = models.Location(name=models.Name(name='store', proper=False),
                        size='building',
Beispiel #26
0
async def sabotage(ctx, target_team, target_location, amount):
    if not config['game_ongoing']: return
    # just pay() but with negative coins and another team
    amount = int(amount)  # still dumb
    member = ctx.message.author
    p = models.Player()
    try:
        p.custom_load("discord_id = ?", (member.id, ))
    except Exception:
        await ctx.send(
            "Gonna be hard to sabotage when I don't have you listed as a player, {}\n\
            If you believe this is a mistake, please talk to a Lord or the King"
            .format(member.mention))
        return
    # Mke sure player has enough coins
    if amount < 1:
        await ctx.send("You can't pay 0 or negative coins, {}".format(
            member.mention))
        return
    elif amount > p.coins:
        await ctx.send("{}, you don't have enough coins!".format(
            member.mention))
        return

    t = models.Team()
    try:
        t.custom_load("name = ? COLLATE NOCASE",
                      (target_team, ))  # TODO make this more user-friendly
    except Exception:
        await ctx.send(
            "I don't think {} is a real team, {}. Make sure you type the full name!"
            .format(target_team, member.mention))
        return

    if t.team_id == p.team_id:
        await ctx.send(
            "You can't sabotage your own team, {}!!! They won't like you for that!"
            .format(member.mention))
        return

    current_loc = t.current_location_id
    avail_locs = graphanalyzer.get_next_location_list(t.team_id)
    # Validate target location...
    if target_location.lower() not in (name.lower()
                                       for name in avail_locs.keys()):
        await ctx.send(
            "I don't think {} is a valid location. Maybe a typo?".format(
                target_location))
        return
    # Get id for the target location...
    location = models.Location()
    location.custom_load("name = ? COLLATE NOCASE", (target_location, ))

    edge = models.LocationEdge()
    edge.custom_load("start_location_id = ? AND end_location_id = ?",
                     (current_loc, location.location_id))

    # Store the payment!
    payment = models.Payment()
    payment.player_id = p.player_id
    payment.team_id = t.team_id
    payment.amount = -amount  # VERY IMPORTANT DIFFERENCE
    payment.location_edge = edge.edge_id
    payment.time = helpers.get_game_day()
    payment.insert()

    # Remove coins from the player's account
    p.coins -= amount
    p.last_active_day = helpers.get_game_day()
    p.update()
    models.save()
    # Send confirmation message.
    await ctx.send(
        "{} has paid **{}** coins to sabotage the **{}'** trip to **{}**".
        format(member.mention, amount, t.name, location.name))
Beispiel #27
0
        if args.all:
            vehicles = api1.get_json('vehicles/')
        else:
            vehicles = api1.get_json('routes/{}/vehicles/'.format(args.route))
        if not vehicles == "":
            for vehicle in vehicles:
                timenow = datetime.now()
                true_time = timenow - \
                    timedelta(seconds=int(vehicle['secsSinceReport']))
                # Save the data to the database
                total_secs = (true_time - true_time.replace(
                    hour=0, minute=0, second=0, microsecond=0)).seconds

                models.Location(datetime=timenow,
                                rid=vehicle['routeId'],
                                vid=vehicle['id'],
                                secs=int(vehicle['secsSinceReport']),
                                kph=int(vehicle['kph']),
                                head=int(vehicle['heading']),
                                dir=vehicle['directionId'],
                                lat=float(vehicle['lat']),
                                lon=float(vehicle['lon']),
                                timeInSec=total_secs,
                                timeInMin=int(total_secs / 60),
                                timeInHour=int(total_secs / 3600),
                                year=timenow.timetuple().tm_year,
                                dow=timenow.weekday() + 1,
                                doy=timenow.timetuple().tm_yday)

        time.sleep(INTERVAL)
Beispiel #28
0
def start():
    for i in range(8):
        innergrid = []
        for j in range(8):
            innergrid.append(None)
        grid.append(innergrid)

    for j in range(8):
        grid[1][j] = models.Location("pop", "white")
        grid[6][j] = models.Location("pop", "black")

    grid[0][0] = models.Location("rook", "white")
    grid[0][7] = models.Location("rook", "white")
    grid[7][0] = models.Location("rook", "black")
    grid[7][7] = models.Location("rook", "black")

    grid[0][1] = models.Location("knight", "white")
    grid[0][6] = models.Location("knight", "white")
    grid[7][1] = models.Location("knight", "black")
    grid[7][6] = models.Location("knight", "black")

    grid[0][2] = models.Location("bishop", "white")
    grid[0][5] = models.Location("bishop", "white")
    grid[7][2] = models.Location("bishop", "black")
    grid[7][5] = models.Location("bishop", "black")

    grid[0][3] = models.Location("queen", "white")
    grid[0][4] = models.Location("king", "white")
    grid[7][4] = models.Location("queen", "black")
    grid[7][3] = models.Location("king", "black")

    text = '['
    for row in grid:
        text += '['
        for loc in row:
            if loc is not None:
                text += str(loc.color) + str(loc.piece) + ' '
            else:
                text += 'None' + ' '
        text += ']'
    text += ']'
    print('grid is ' + text)
Beispiel #29
0
def addNote(payload):
    id_location = None
    author =  M.User.objects.get(pk=payload["id_author"])
    location = None
    h5l = None
    parent =  M.Comment.objects.get(pk=payload["id_parent"]) if "id_parent" in payload else None

    #putting this in factor for duplicate detection: 
    similar_comments = M.Comment.objects.filter(parent=parent, ctime__gt=datetime.datetime.now()-datetime.timedelta(0,10,0), author=author, body=payload["body"]);
    
    #do we need to insert a location ? 
    if "id_location" in payload: 
        location = M.Location.objects.get(pk=payload["id_location"])
        #refuse if similar comment
        similar_comments = similar_comments.filter(location=location)
        if similar_comments.count(): 
            return None
    else:
        location = M.Location()
        location.source = M.Source.objects.get(pk=payload["id_source"])
        location.ensemble = M.Ensemble.objects.get(pk=payload["id_ensemble"])        
        location.y = payload["top"]
        location.x = payload["left"]
        location.w = payload["w"]
        location.h = payload["h"]
        location.page = payload["page"]
        location.section = M.Membership.objects.get(user=author, ensemble=location.ensemble, deleted=False).section

        #refuse if similar comment
        similar_comments = similar_comments.filter(location__in=M.Location.objects.filter(source=location.source, ensemble=location.ensemble, y=location.y, x=location.x, w=location.w, h=location.h, page=location.page));
        if similar_comments.count():
            return None

        location.save()
        #do we need to add an html5 location ?    
        if "html5range" in payload: 
                h5range = payload["html5range"]
                h5l = M.HTML5Location()
                h5l.path1 =   h5range["path1"]
                h5l.path2 =   str(h5range["path2"])
                h5l.offset1 = h5range["offset1"]
                h5l.offset2 = h5range["offset2"]
                h5l.location = location  
                h5l.save()

    # Should we import this comment from somewhere?
    body = payload["body"]
    matchObj = re.match( r'@import\((\d+), *(.*)\)', body)

    if (matchObj):
        from_loc_id = int(matchObj.group(1))
        import_type = matchObj.group(2)

        # Am I allowed to do this? Am I an admin in the source?
        src_membership = M.Location.objects.get(pk=from_loc_id).ensemble.membership_set.filter(user=author,admin=True)
        if src_membership.count() > 0:
            return importAnnotation(import_type, from_loc_id, location)
        else:
            return None
    else:
        comment = M.Comment()
        comment.parent = parent
        comment.location = location
        comment.author = author
        comment.body = payload["body"]
        comment.type = payload["type"]
        comment.signed = payload["signed"] == 1
        comment.save()
        return comment
Beispiel #30
0
    def createDeployment(self):
        """
        Create a new deployment and house etc on the Transfer Database
        """

        deploymentName = "archRock"
        houseName = self.houseName
        
        session = models.meta.Session()
        #Check for deployment

        theDep = session.query(models.Deployment).filter_by(name=deploymentName).first()
        log.debug("Checking for existing deployment {0}".format(theDep))
        if theDep is None:
            #Create a new deployment
            theDep = models.Deployment(name=deploymentName)
            session.add(theDep)
            session.flush()
            log.debug("Adding Deployment to database {0}".format(theDep))


        #And check for Houses
        theHouse = session.query(models.House).filter_by(address=houseName).first()
        log.debug("Checking for house {0}".format(theHouse))
        if theHouse is None:
            theHouse = models.House(address=houseName,
                                    deploymentId = theDep.id)
            session.add(theHouse)
            session.flush()
            log.debug("Adding New House {0}".format(theHouse))


        self.theHouse = theHouse
        #Create a location for this particular node
        
        theRoom = session.query(models.Room).filter_by(name="External").first()
        if theRoom is None:
            theRoom = models.Room(name="External",roomTypeId=1)
            session.add(theRoom)
            session.flush()

        log.debug("External Room is {0}".format(theRoom))

        #theLocation = models.Location(houseId = theHouse.id,roomId = theRoom.id)
        theLocation = session.query(models.Location).filter_by(houseId=theHouse.id,
                                                               roomId = theRoom.id).first()
        log.debug("Checking for existing location {0}".format(theLocation))
        if theLocation is None:
            theLocation = models.Location(houseId = theHouse.id,
                                          roomId = theRoom.id)
            session.add(theLocation)
            session.flush()

        self.theLocation = theLocation

        #Node / Node Type
        theNode = session.query(models.Node).filter_by(id=118118).first()
        if theNode is None:
            theNode = models.Node(id=118118)
            session.add(theNode)
            session.flush()
        log.debug("Node is {0}".format(theNode))
        self.theNode = theNode

        sensorType = session.query(models.SensorType).filter_by(name="Power").first()
        self.avgType = sensorType
        log.debug("Sensor is {0}".format(sensorType))
        
        sensorType = session.query(models.SensorType).filter_by(name="Power Min").first()
        self.minType = sensorType

        sensorType = session.query(models.SensorType).filter_by(name="Power Max").first()
        self.maxType = sensorType

        session.commit()