Giter VIP home page Giter VIP logo

calif-earthquakes's People

Contributors

bricker avatar chrislkeller avatar ewr avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

calif-earthquakes's Issues

Gamification component

  • Autotweet of quakes above certain threshold (id you feel it? Possible Tweet language: 5.0 quake strikes Northridge. Did you feel it? Let @kpcc and @usgs know and learn more about fire safety here: kp.cc/djaflksd
  • Lightbox pop up for "Did you feel it?" query on individual quake pages. To contain:
    • your location (with "why we're collecting this")
    • rank how deeply it was felt (on scale of 1-10)
    • ability to add comment (ie. "books fell off shelf").
  • Protocol or special template for breaking news alert. Including "Did you feel it?" with fields:
    • your location (with "why we're collecting this")
    • rank how deeply it was felt (on scale of 1-10)
    • ability to add comment (ie. "books fell off shelf").
  • Ability to plot USGS and KPCC reactions to "did you feel it?" query
    • by location
    • by how deeply it was felt (designated by color gradient?)
    • clickable to read comments
  • "Thank you/ next step" page to load after submission of "did you feel it query" to include:
    • thank you note
    • Clickable preparation checklist (ie. Do you have a go bag? Have you secured your books? Do you have these items handy in case of evacuation, etc.)

Bulletproof database queries

Maximize the database queries, and make sure they are as efficient as possible.

Index view has at least two queries. Can you handle one and filter based on logic or on the template?

Detail view has at least three queries. Same question applies.

Remote fabric tasks that will need to be moved to Rundeck

There are still some remote fabric tasks that will need to be moved to Rundeck if you still need them. The easiest way to do this would be to move the tasks into a manager, and then add the Rundeck jobs to trigger those manager tasks. I'll help you with this if you need it.

Alert/notification to web producers

  • Notification email sent to KPCC web producers for alert of quakes with magnitude of over 3.5.
  • Pre-fill 2-line base story
  • Pre-fill breaking news alert
  • Protocol for covering earthquakes to include how to embed vital card, authorities to call in quake situations, how to follow up on Social networks to gather on-the-ground information and audio.

Finalize map application

  • Data loading and how best to represent to the user that the map is ready to be interacted with
  • Link to full-screen map view
  • Add the border around the map display per the comp.
  • Implement range sliders to filter information by date, magnitude…
  • Implement different layers. Such this perhaps?…
  • Add shakemap HTML map, or link, on detail view?
  • Marker to show the difference between nearby cities and an earthquake…
  • Add map legend
  • Change clusters to mirror the color of the individual markers.
  • Test marker cluster layer...
  • Determine how best to render geojson/shapefiles
  • Add a full-screen map view
  • Zoom issues...
  • Layer tiles are still uploading to my server, but things seem to be working...
  • Touch events for map markers...
  • Configure hover on map markers
  • Detail view map to plot epicenter and nearby cities
  • Does the index page map have limited features and the larger view add features as the space is more applicable to exploring?
  • Address search with a radius dropdown and an action (submit) button
  • Remove user layers from map on new search

Craft filter logic for exploring the map

  • Layer toggle
  • Magnitude
  • Intensity
  • Address search

UI elements

  • Checkbox
  • Slider
  • Text input
  • Action button

Additional Layers

  • Critical infrastructure layer
  • liquefaction zones

Develop resources post and links

Enhance Engagement

  • Ability for users to supply feedback to KPCC and USGS on whether they felt the earthquake, how much, and where they were.
  • Also give them an option to send in PIN-like survey with more narrative information and contact if they like).
  • What information is available from the Did You Feel it API?
  • What information is available from social media?

On the map, I can only open each pin's "balloon" once.

So, here's a weird bug: On the interactive map, I can only instantiate each pin's tip-balloon once, then — after it's been closed (loses focus, whatever) — I can't re-open it. See attached screenshots for context. (The story here is that I've clicked the first pin; then clicked the second pin; then unsuccessfully tried re-clicking either of them, to no avail.)

map-bug-1
map-bug-2
map-bug-3

Detail views are loading un-necessary stylesheets and scripts...

css loaded on detail page with those stylesheets that don't need to be crossed out.

  • jquery-ui.css
  • leaflet.min.css
  • MarkerCluster.css
  • MarkerCluster.Default.css
  • leaflet.usermarker.css
  • style.css
  • map-application.css

javascript loaded on detail page with those scripts that don't need to be crossed out.

  • dkj3oci.js
  • jquery.min.js
  • jquery-ui.min.js
  • modernizr.min.js
  • underscore-min.js
  • backbone-min.js
  • moment.min.js
  • leaflet.min.js
  • leaflet.markercluster.min.js
  • app.js
  • router.js
  • earthquake.js
  • map.js
  • marker.js
  • earthquakes.js
  • la-habra-earthquakes.js
  • markers.js
  • la-habra-map.js
  • clustered-marker.js
  • leaflet.usermarker.min.js
  • tile.stamen.js?v1.2.4
  • webtrends.v2.js
  • js?key=AIzaSyAtS1OYyuRY0inb23BK0nuGId3FiOC6Rb8&sensor=false&libraries=places
  • jquery.geocomplete.min.js
  • dc.js
  • beacon.js
  • chartbeat.js

Solve API manager fail if no nearby cities available on first pass

Log is...

  ?[1;36mINFO:?[0;37m Starting new HTTP connection (1): earthquake.usgs.gov
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/summary/all_hour.geojson HTTP/1.1" 200 1111
  ?[1;36mDEBUG:?[0;37m Details: M 1.9 - 2km SE of La Habra, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/ci15481705
  ?[1;36mDEBUG:?[0;37m Details: M 2.0 - 1km N of Brea, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/ci15481697
  ?[1;36mDEBUG:?[0;37m Details: M 3.4 - 2km ESE of La Habra, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/ci15481681
  ?[1;36mDEBUG:?[0;37m Details: M 5.1 - 2km E of La Habra, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/ci15481673
  ?[1;36mDEBUG:?[0;37m Details: M 1.8 - 11km NE of San Antonio Heights, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/ci15481665
  ?[1;36mDEBUG:?[0;37m Details: M 1.1 - 18km SSE of Ridgemark, California. URL: http://earthquake.usgs.gov/earthquakes/eventpage/nc72190405
  ?[1;36mINFO:?[0;37m Starting new HTTP connection (1): earthquake.usgs.gov
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/ci15481705.geojson HTTP/1.1" 200 None
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/ci15481697.geojson HTTP/1.1" 200 None
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/ci15481681.geojson HTTP/1.1" 200 None
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/ci15481673.geojson HTTP/1.1" 200 None
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/ci15481665.geojson HTTP/1.1" 200 None
  ?[1;36mDEBUG:?[0;37m "GET /earthquakes/feed/v1.0/detail/nc72190405.geojson HTTP/1.1" 200 None
  ?[1;36mINFO:?[0;37m Starting new HTTP connection (1): earthquake.usgs.gov
  ?[1;36mDEBUG:?[0;37m "GET /product/nearby-cities/ci15481697/us/1396066640330/nearby-cities.json HTTP/1.1" 200 265
  ?[1;36mDEBUG:?[0;37m "GET /product/nearby-cities/ci15481681/us/1396066445130/nearby-cities.json HTTP/1.1" 200 264
  ?[1;36mDEBUG:?[0;37m "GET /product/nearby-cities/ci15481673/us/1396066600289/nearby-cities.json HTTP/1.1" 200 264
  ?[1;36mDEBUG:?[0;37m "GET /product/nearby-cities/ci15481665/us/1396066269942/nearby-cities.json HTTP/1.1" 200 270
  ?[1;36mDEBUG:?[0;37m "GET /product/nearby-cities/nc72190405/us/1396063343507/nearby-cities.json HTTP/1.1" 200 245
  ?[1;36mDEBUG:?[0;37m Creating new record for M1.9  - Greater Los Angeles area, California
  Traceback (most recent call last):
    File "manage.py", line 434, in <module>
      manager.run()
    File "/web/archive/apps/earthquakes/virtualenvs/earthquakes/lib/python2.7/site-packages/flask_script/__init__.py", line 405, in run
      result = self.handle(sys.argv[0], sys.argv[1:])
    File "/web/archive/apps/earthquakes/virtualenvs/earthquakes/lib/python2.7/site-packages/flask_script/__init__.py", line 384, in handle
      return handle(app, *positional_args, **kwargs)
    File "/web/archive/apps/earthquakes/virtualenvs/earthquakes/lib/python2.7/site-packages/flask_script/commands.py", line 145, in handle
      return self.run(*args, **kwargs)
    File "manage.py", line 58, in run
      self.retrieve_details_from(list_of_urls)
    File "manage.py", line 74, in retrieve_details_from
      self.retrieve_nearby_cities_from(list_of_instances)
    File "manage.py", line 108, in retrieve_nearby_cities_from
      self.write(list_of_instances)
    File "manage.py", line 157, in write
      nearest_cities_url=item["nearest_cities_url"],
  KeyError: 'nearest_cities_url'

What role can significance play in the story of an earthquake?

Significance is based on magnitude, PAGER estimated impact alert level, and DYFI? maximum reported MMI and number of responses:

mag_sig = magnitude * 100 * (magnitude / 6.5)
    pager_sig = {
    red => 2000,
    orange => 1000,
    yellow => 500,
    green => 0
    }
dyfi_sig = min(responses, 1000) * (mmi / 10)
significance = max(mag_sig, pager_sig) + dyfi_sig

We consider an event significant when significance is 650 or higher. This roughly means magnitude 6.5, destructive, or widely felt. The maximum significance is 3000.

These pages have more information about PAGER and DYFI

Add New Relic monitoring

So reading through this, I should

  • pip install locally
  • Commit, push and deploy
  • Go into the the server to create the config file newrelic-admin generate-config LICENSE-KEY newrelic.ini

Refactor api manager...

  • Make the read -> create/update logic more efficient…

  • Determine if a record exists earlier in the process of populate the database…

    "performs request on earthquake api url and returns the data"
    def run(self):
    usgs_query_api = requests.get(app.config['GT_2_5_PAST_DAY'], headers=app.config['API_MANAGER_HEADERS'])
    usgs_api_data = usgs_query_api.json()
    list_of_details_urls = []
    for item in usgs_api_data['features']:
    if 'California' in item['properties']['place']:
    url_to_save = self.test_if_in_db(item)
    list_of_details_urls.append(url_to_save)
    else:
    logging.debug('passing this one by')
    pass
    self.retrieve_details_from(list_of_details_urls)

    def test_if_in_db(self, item):

    # set comparison variables
    comparison_place = '%s' % (item['properties']['place'])
    comparison_time = '%s' % (item['properties']['time'])
    comparison_updated_raw = item['properties']['updated']
    
    # query the database
    instance = Earthquake.query.filter_by(place=comparison_place, date_time_raw=comparison_time).first()
    
    # if it doesn't exist the db
    if instance is None:
        logging.debug('I am creating a new record')
    
        # return a link to the details
        usgs_details_link = str(item['properties']['detail'])
        return usgs_details_link
    
    # if it exists
    else:
    
        # and if no new information
        if instance.updated_raw == comparison_updated_raw:
            logging.debug('I compared and found this record exists and doesnt need to be updated')
    
            # move along
            pass
    
        # otherwise return it to update
        else:
            logging.debug('I compared and found this record should be updated')
            usgs_details_link = str(item['properties']['detail'])
            return usgs_details_link
    

    '

Refactored code that I should revisit

!/usr/bin/env python

import os, logging, requests, time, datetime, calendar
import pytz
from requests_futures.sessions import FuturesSession
from pytz import timezone
from datetime import tzinfo, date
from flask.ext.script import Manager, Command
from flask.ext.migrate import Migrate, MigrateCommand
from concurrent import futures
from earthquakes import app, db
from earthquakes.models import Earthquake, NearestCity

logging.basicConfig(format='\033[1;36m%(levelname)s:\033[0;37m %(message)s', level=logging.DEBUG)

migrate = Migrate(app, db)
manager = Manager(app)

class UsgsApiQuery(Command):

"mimics django's get or create function"
def get_or_create(self, session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        session.add(instance)
        session.commit()
        return instance

"performs request on earthquake api url and returns the data"
def run(self):
    usgs_query_api = requests.get(app.config['ALL_PAST_DAY'], headers=app.config['API_MANAGER_HEADERS'])
    usgs_api_data = usgs_query_api.json()
    list_of_details_urls = []
    for item in usgs_api_data['features']:
        if 'California' in item['properties']['place']:
            usgs_details_link = str(item['properties']['detail'])
            list_of_details_urls.append(usgs_details_link)
        else:
            logging.debug('passing this one by')
            pass
    self.retrieve_details_from(list_of_details_urls)

"performs request on local earthquake details url and returns the data"
def retrieve_details_from(self, list_of_details_urls):
    logging.debug('Beginning to process %s records' % (len(list_of_details_urls)))
    session = FuturesSession(max_workers=1)
    for detail_instance in list_of_details_urls:
        usgs_query_details = session.get(detail_instance, headers=app.config['API_MANAGER_HEADERS'])
        usgs_api_details = usgs_query_details.result()
        usgs_api_details = usgs_api_details.json()
        nearest_cities_url = usgs_api_details['properties']['products']['nearby-cities'][0]['contents']['nearby-cities.json']['url']
        nearest_cities_list = self.retrieve_nearby_cities_from(nearest_cities_url)
        usgs_api_details['nearest_cities_url'] = nearest_cities_url
        usgs_api_details['nearest_cities'] = nearest_cities_list
        self.write_to_db(usgs_api_details)
    logging.debug('Finished processing %s records' % (len(list_of_details_urls)))

"performs request on local earthquake nearby cities url and returns the data"
def retrieve_nearby_cities_from(self, nearest_cities_url):
    session = FuturesSession(max_workers=1)
    list_of_nearby_cities = []
    if nearest_cities_url:
        nearest_cities_query_details = session.get(nearest_cities_url, headers=app.config['API_MANAGER_HEADERS'])
        nearest_cities_api_details = nearest_cities_query_details.result()
        nearest_cities_api_details = nearest_cities_api_details.json()
        for nearby_city in nearest_cities_api_details:
            city = NearestCity(
                id = None,
                distance = nearby_city['distance'],
                direction = nearby_city['direction'],
                name = nearby_city['name'],
                latitude = nearby_city['latitude'],
                longitude = nearby_city['longitude'],
                population = nearby_city['population'],
                earthquake_id = None
            )
            list_of_nearby_cities.append(city)
    else:
        pass
    return list_of_nearby_cities

"write class instances to the database"
def write_to_db(self, item):
    comparison_slug = '%s-%s' % (item['properties']['title'].lower(), item['properties']['time'])
    comparison_updated_raw = item['properties']['updated']
    instance = Earthquake.query.filter_by(primary_slug=comparison_slug).first()
    if instance is None:
        logging.debug('creating new record')
        quake = Earthquake(
            id = None,
            primary_slug = '%s-%s' % (item['properties']['title'].lower(), item['properties']['time']),
            mag = item['properties']['mag'],
            place = item['properties']['place'],
            title = item['properties']['title'],
            date_time = datetime.datetime.utcfromtimestamp(item['properties']['time']/1e3),
            date_time_raw = item['properties']['time'],
            updated = datetime.datetime.utcfromtimestamp(item['properties']['updated']/1e3),
            updated_raw = item['properties']['updated'],
            tz = item['properties']['tz'],
            url = item['properties']['url'],
            felt = item['properties']['felt'],
            cdi = item['properties']['cdi'],
            mmi = item['properties']['mmi'],
            alert = item['properties']['alert'],
            status = item['properties']['status'],
            tsunami = item['properties']['tsunami'],
            sig = item['properties']['sig'],
            resource_type = item['properties']['type'],
            latitude = item['geometry']['coordinates'][1],
            longitude = item['geometry']['coordinates'][0],
            depth = item['geometry']['coordinates'][2],
            net = item['properties']['net'],
            code = item['properties']['code'],
            ids = item['properties']['ids'],
            sources = item['properties']['sources'],
            nst = item['properties']['nst'],
            dmin = item['properties']['dmin'],
            rms = item['properties']['rms'],
            gap = item['properties']['gap'],
            magType = item['properties']['magType'],
            nearest_cities_url = item['nearest_cities_url'],
            nearest_cities=item['nearest_cities']
        )
        db.session.add(quake)
        for city in item['nearest_cities']:
            db.session.add(city)
    else:
        if instance.updated_raw == comparison_updated_raw:
            logging.debug('compared and found record exists and doesnt need to be updated')
            pass
        else:
            logging.debug('compared and have updated this record')
            instance.primary_slug = '%s-%s' % (item['properties']['title'].lower(), item['properties']['time'])
            instance.mag = item['properties']['mag']
            instance.place = item['properties']['place']
            instance.title = item['properties']['title']
            instance.date_time = datetime.datetime.utcfromtimestamp(item['properties']['time']/1e3)
            instance.date_time_raw = item['properties']['time']
            instance.updated = datetime.datetime.utcfromtimestamp(item['properties']['updated']/1e3)
            instance.updated_raw = item['properties']['updated']
            instance.tz = item['properties']['tz']
            instance.url = item['properties']['url']
            instance.felt = item['properties']['felt']
            instance.cdi = item['properties']['cdi']
            instance.mmi = item['properties']['mmi']
            instance.alert = item['properties']['alert']
            instance.status = item['properties']['status']
            instance.tsunami = item['properties']['tsunami']
            instance.sig = item['properties']['sig']
            instance.resource_type = item['properties']['type']
            instance.latitude = item['geometry']['coordinates'][1]
            instance.longitude = item['geometry']['coordinates'][0]
            instance.depth = item['geometry']['coordinates'][2]
            instance.net = item['properties']['net']
            instance.code = item['properties']['code']
            instance.ids = item['properties']['ids']
            instance.sources = item['properties']['sources']
            instance.nst = item['properties']['nst']
            instance.dmin = item['properties']['dmin']
            instance.rms = item['properties']['rms']
            instance.gap = item['properties']['gap']
            instance.magType = item['properties']['magType']
            instance.nearest_cities_url = item['nearest_cities_url']
    db.session.commit()

class InitDb(Command):
"sets up the database based on models"
def run(self):
db.create_all()

manager.add_command('query', UsgsApiQuery())
manager.add_command('initdb', InitDb())
manager.add_command('db', MigrateCommand)

if name == "main":
manager.run()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.