Beispiel #1
0
def update_ex_gyms(geofence):
    # Parse geofence file.
    log.info('Finding border points from geofence.')
    geofence = Geofences.parse_geofences_file(geofence, '')
    fence = geofence[0]['polygon']

    # Figure out borders for bounding box.
    south = min(fence, key=lambda ev: ev['lat'])['lat']
    west = min(fence, key=lambda ev: ev['lon'])['lon']
    north = max(fence, key=lambda ev: ev['lat'])['lat']
    east = max(fence, key=lambda ev: ev['lon'])['lon']

    log.info('Finding parks within zone.')
    ex_gyms = ex_query(south, west, north, east)
    gyms = Gym.get_gyms(south, west, north, east)

    if not gyms:
        log.error('No gyms detected within geofence, exiting.')
        exit(1)

    log.info('Checking {} gyms against {} parks.'.format(
        len(gyms), len(ex_gyms.ways)))
    # Retrieve list of confirmed EX gyms to update the DB.
    confirmed_ex_gyms = filter(lambda gym: __gym_is_ex_gym(gym, ex_gyms),
                               gyms.values())

    if not confirmed_ex_gyms:
        log.info('No EX-eligible gyms found.')
        exit(1)
    Gym.set_gyms_in_park(confirmed_ex_gyms, True)
Beispiel #2
0
def create_gym(handler, name):
    user = service_util.get_or_create_user(users.get_current_user())
    gym = Gym(name=name)
    gym.put()

    membership = GymMembership(parent=gym, gym=gym, user=user, owner=True)
    membership.put()
    return dict(group=group)
Beispiel #3
0
def create_gym(handler, name):
    user = service_util.get_or_create_user(users.get_current_user())
    gym = Gym(name=name)
    gym.put()

    membership = GymMembership(parent=gym, gym=gym, user=user, owner=True)
    membership.put()
    return dict(group=group)
Beispiel #4
0
 def get(self):
   user = users.get_current_user()
   if user:
     context = {
         'user': user,
         'logout': users.create_logout_url(self.request.uri)}
   else:
     context = {
         'login': users.create_login_url('/login')}
   context['gyms'] = [Gym.all().fetch(20)]
   tmpl = path.join(path.dirname(__file__), 'static/html/gyms.html')
   self.response.out.write(render(tmpl, context))
Beispiel #5
0
def insert_gym(session, gym, time):
    gym_obj = Gym(gym_id=str(gym['gym_id']),
                  gym_points=int(gym['gym_points']),
                  enabled=bool(gym['enabled']),
                  guard_pokemon_id=int(gym['guard_pokemon_id']),
                  team_id=int(gym['team_id']),
                  last_modified=dt_from_epoch(int(gym['last_modified'])),
                  time=time,
                  geom='SRID=4326;POINT(%s %s)' %
                  (float(gym['longitude']), float(gym['latitude'])))

    session.merge(gym_obj)
Beispiel #6
0
  def post(self):
    user = users.get_current_user()
    if user:
      climber = Climber.from_appengine_user(user)
      gym = Gym()
      gym.name = self.request.get('name')
      gym.put()

      membership = GymMembership()
      membership.climber = climber
      membership.user = user
      membership.gym = gym
      membership.owner = True
      membership.put()

      context = {
          'gym_name': gym.name,
          'error': False}
    else:
      context = {'error': 'log in to create a gym!'}

    tmpl = path.join(path.dirname(__file__), 'static/html/addgymresult.html')
    self.response.out.write(render(tmpl, context))
Beispiel #7
0
def raw_data():
    """ Gets raw data for pokemons/gyms/pokestops via REST """
    pokemons, gyms, pokestops = [], [], []
    for pokemon in Pokemon.select():
        pokemons.append(model_to_dict(pokemon))
    for gym in Gym.select():
        gyms.append(model_to_dict(gym))
    for pokestop in Pokestop.select():
        pokestops.append(model_to_dict(pokestop))
    return flask.jsonify(
        pokemons=pokemons,
        gyms=gyms,
        pokestops=pokestops
    )
Beispiel #8
0
def exgyms(geofence):
    # Parse geofence file
    log.info('Finding border points from geofence')
    f = json.loads(json.dumps(Geofences.parse_geofences_file(geofence, '')))
    fence = f[0]['polygon']
    # Figure out borders for bounding box
    south = min(fence, key=lambda ev: ev['lat'])['lat']
    west = min(fence, key=lambda ev: ev['lon'])['lon']
    north = max(fence, key=lambda ev: ev['lat'])['lat']
    east = max(fence, key=lambda ev: ev['lon'])['lon']
    log.info('Finding parks within zone')
    ex_gyms = ex_query(south, west, north, east)

    gyms = Gym.get_gyms(south, west, north, east)
    log.info('Checking {} gyms against {} parks'.format(len(gyms),
                                                        len(ex_gyms.ways)))
    for way in ex_gyms.ways:
        data = []
        for node in way.nodes:
            data.append({'lat': float(node.lat),
                         'lon': float(node.lon)})

        for gym in gyms.items():

            gympoint = {'lat': float(gym[1]['latitude']),
                        'lon': float(gym[1]['longitude'])}
            # Check if gyms falls within a designated park and update if park
            if Geofences.is_point_in_polygon_custom(gympoint, data):

                # Try to get Gym name, but default to id if missing
                try:
                    gymname = Gym.get_gym(gym[0])['name'].encode('utf8')
                except AttributeError:
                    gymname = gym[0]
                log.info('{} is eligible for legendary raid'.format(gymname))
                Gym.is_gym_park(gym[0], True)
Beispiel #9
0
 def post(self):
   gym = Gym()
   gym.name = self.request.get('name')
   gym.put()
   self.redirect('/')
Beispiel #10
0
 def get(self):
   gyms = Gym.all().getch(20)
   context = {
     'gyms': gyms}
   tmpl = path.join(path.dirname(__file__), 'static/html/admin.html')
   self.response.out.write(render(tmpl, context))
Beispiel #11
0
def get_pokemarkers():
    pokeMarkers = [{
        'icon': icons.dots.red,
        'lat': origin_lat,
        'lng': origin_lon,
        'infobox': "Start position",
        'type': 'custom',
        'key': 'start-position',
        'disappear_time': -1
    }]

    for pokemon in Pokemon.select():
        label_mapping = {}
        label_mapping['disappear_time_formatted'] = datetime.fromtimestamp(pokemon.disappear_time).strftime("%H:%M:%S")
        label_mapping['id'] = pokemon.pokedex_num
        label_mapping['disappear_time'] = pokemon.disappear_time
        label_mapping['name'] = pokemon.name
        label_mapping['lat'] = pokemon.lat
        label_mapping['lon'] = pokemon.lon

        LABEL_TMPL = u'''
<div><b>{name}</b><span> - </span><small><a href='http://www.pokemon.com/us/pokedex/{id}' target='_blank' title='View in Pokedex'>#{id}</a></small></div>
<div>Disappears at - {disappear_time_formatted} <span class='label-countdown' disappears-at='{disappear_time}'></span></div>
<div><a href='https://www.google.com/maps/dir/Current+Location/{lat},{lon}' target='_blank' title='View in Maps'>Get Directions</a></div>
'''
        label = LABEL_TMPL.format(**label_mapping)
        #  NOTE: `infobox` field doesn't render multiple line string in frontend
        label = label.replace('\n', '')

        pokeMarkers.append({
            'type': 'pokemon',
            'icon': 'static/icons/%d.png' % pokemon.pokedex_num,
            'lat': pokemon.lat,
            'lng': pokemon.lon,
            'key': pokemon.spawnpoint_id,
            'disappear_time': pokemon.disappear_time,
            'infobox': label
        })

    if args.display_gym:
        for gym in Gym.select():
            if gym.team_id == 0:
                color = "rgba(0,0,0,.4)"
            if gym.team_id == 1:
                color = "rgba(0, 0, 256, .4)"
            if gym.team_id == 2:
                color = "rgba(255, 0, 0, .4)"
            if gym.team_id == 3:
                color = "rgba(255, 255, 0, .4)"

        icon = 'static/forts/'+gym.team_name+'_large.png'
        pokeMarkers.append({
            'icon': 'static/forts/' + gym.team_name + '.png',
            'type': 'gym',
            'key': gym.gym_id,
            'disappear_time': -1,
            'lat': gym.lat,
            'lng': gym.lon,
            'infobox': "<div><center><small>Gym owned by:</small><br><b style='color:" + color + "'>Team " +
                       gym.team_name + "</b><br><img id='" + gym.team_name + "' height='100px' src='" + icon + "'></center>"

        })

    if args.display_pokestop:
        for pokestop in Pokestop.select():
            pokeMarkers.append({
                'type': 'stop',
                'key': pokestop.pokestop_id,
                'disappear_time': -1,
                'icon': 'static/forts/Pstop.png',
                'infobox': 'Pokestop',
                'lng': pokestop.lon,
                'lat': pokestop.lat,
            })
    return pokeMarkers
Beispiel #12
0
def process_step(args, api_endpoint, access_token, profile_response,
                 pokemonsJSON, ignore, only):
    print('[+] Searching pokemons for location {} {}'.format(FLOAT_LAT, FLOAT_LONG))
    origin = LatLng.from_degrees(FLOAT_LAT, FLOAT_LONG)
    step_lat = FLOAT_LAT
    step_long = FLOAT_LONG
    parent = CellId.from_lat_lng(LatLng.from_degrees(FLOAT_LAT,
                                                     FLOAT_LONG)).parent(15)
    h = get_heartbeat(args.auth_service, api_endpoint, access_token,
                      profile_response)
    hs = [h]
    seen = set([])

    for child in parent.children():
        latlng = LatLng.from_point(Cell(child).get_center())
        set_location_coords(latlng.lat().degrees, latlng.lng().degrees, 0)
        hs.append(
            get_heartbeat(args.auth_service, api_endpoint, access_token,
                          profile_response))
    set_location_coords(step_lat, step_long, 0)
    visible = []

    for hh in hs:
        try:
            for cell in hh.cells:
                for wild in cell.WildPokemon:
                    hash = wild.SpawnPointId + ':' \
                        + str(wild.pokemon.PokemonId)
                    if hash not in seen:
                        visible.append(wild)
                        seen.add(hash)
                if cell.Fort:
                    for Fort in cell.Fort:
                        if Fort.Enabled == True:
                            if args.china:
                                (Fort.Latitude, Fort.Longitude) = \
transform_from_wgs_to_gcj(Location(Fort.Latitude, Fort.Longitude))
                            if Fort.GymPoints:
                                Gym.create_or_get(
                                    gym_id=Fort.FortId,
                                    team_id=Fort.Team,
                                    team_name=numbertoteam[Fort.Team],
                                    lat=Fort.Latitude,
                                    lon=Fort.Longitude
                                )

                            elif Fort.FortType :
                                Pokestop.create_or_get(
                                    pokestop_id=Fort.FortId,
                                    lat=Fort.Latitude,
                                    lon=Fort.Longitude
                                )
        except AttributeError:
            break

    for poke in visible:
        pokename = pokemonsJSON[str(poke.pokemon.PokemonId)]
        if args.ignore:
            if pokename.lower() in ignore:
                continue
        elif args.only:
            if pokename.lower() not in only:
                continue

        disappear_timestamp = time.time() + poke.TimeTillHiddenMs \
            / 1000

        if args.china:
            (poke.Latitude, poke.Longitude) = \
                transform_from_wgs_to_gcj(Location(poke.Latitude,
                    poke.Longitude))

        Pokemon.create_or_get(
            spawnpoint_id=poke.SpawnPointId,
            lat=poke.Latitude,
            lon=poke.Longitude,
            pokedex_num=poke.pokemon.PokemonId,
            name=pokename,
            disappear_time=disappear_timestamp
        )
Beispiel #13
0
                'type': 'stop',
                'key': pokestop.pokestop_id,
                'disappear_time': -1,
                'icon': 'static/forts/Pstop.png',
                'infobox': 'Pokestop',
                'lng': pokestop.lon,
                'lat': pokestop.lat,
            })
    return pokeMarkers


def get_map():
    fullmap = Map(
        identifier="fullmap2",
        style='height:100%;width:100%;top:0;left:0;position:absolute;z-index:200;',
        lat=origin_lat,
        lng=origin_lon,
        markers=get_pokemarkers(),
        zoom='15', )
    return fullmap


if __name__ == '__main__':
    args = get_args()
    register_background_thread(initial_registration=True)
    db.connect()
    Pokemon.create_table(fail_silently=True)
    Pokestop.create_table(fail_silently=True)
    Gym.create_table(fail_silently=True)
    app.run(debug=True, threaded=True, host=args.host, port=args.port)
Beispiel #14
0
from random import choice, sample
from typing import *
from enum import auto, Enum

import matplotlib.pyplot as plt

from kaggle_environments.envs.hungry_geese.hungry_geese import Observation, Configuration, row_col
from kaggle_environments import make

from agents import Goose_mk1 as GooseLee
from models import LibaAgy_lite as brain
from models import GooseGym as Gym

from coaches.kagglegreedy import GreedyAgent as Greedy
from coaches.diffusion_agent import Agent as Diffusion
from coaches.crazy_goose import Crazy
from coaches.risk_averse_greedy import RAGreedy
from coaches.straightforward_bfs import BFS
from coaches.RLbot import RLbot

rbots = [Greedy,Diffusion,Crazy,RAGreedy,BFS,RLbot]

RoboGoose = GooseLee(0.001,brain,epsilon=1.0,name='test')
Dojo = Gym(RoboGoose,ncheck=25,n_smart=1,rule_bots=rbots,ndisplay=1000000,switch_epoch=10000)#,load_weights='models/GooseLee_lite2.0.h5')
Dojo.train(50)

F = plt.figure()
ax = F.add_subplot(111)
ax.hist(RoboGoose.M.mem_TD_loss,bins=100)
plt.show()