Ejemplo n.º 1
0
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    incidents_with_age = Incident.select().where(Incident.age > 0).order_by(
        Incident.age.asc())
    incidents_without_age = Incident.select().where(
        Incident.age >> None).order_by(Incident.age.asc())
    incidents = list(incidents_with_age) + list(incidents_without_age)
    states = [
        i.state for i in Incident.select(Incident.state).distinct().order_by(
            Incident.state)
    ]

    def slug(incident):
        uniq = incident.name or 'unknown'

        if (incident.postofficename):
            uniq += '-' + incident.postofficename

        uniq += '-' + incident.state

        return uniq.lower().replace(' ', '-').replace('.',
                                                      '').replace('--', '-')

    return render_template('index.html',
                           incidents=incidents,
                           states=states,
                           slug=slug,
                           **make_context())
Ejemplo n.º 2
0
def create_incident_instance(row):
    i = Incident(
        incident_datetime=row['Incident Datetime'],
        incident_date=row['Incident Date'],
        incident_time=row['Incident Time'],
        incident_year=row['Incident Year'],
        incident_day_of_the_week=row['Incident Day of Week'],
        report_datetime=row['Report Datetime'],
        row_id=row['Row ID'],
        incident_id=row['Incident ID'],
        incident_number=row['Incident Number'],
        cad_number=row['CAD Number'],
        report_type_code=row['Report Type Code'],
        report_type_description=row['Report Type Description'],
        filed_online=row['Filed Online'],
        incident_code=row['Incident Code'],
        incident_category=row['Incident Category'],
        incident_subcategory=row['Incident Subcategory'],
        incident_description=row['Incident Description'],
        resolution=row['Resolution'],
        intersection=row['Intersection'],
        cnn=row['CNN'],
        police_district=row['Police District'],
        analysis_neighborhood=row['Analysis Neighborhood'],
        supervisor_district=row['Supervisor District'],
        latitude=row['Latitude'],
        longitude=row['Longitude'],
        point=row['point'],
    )
    print("...adding Incident #%s, Row ID: %s" % (i.incident_id, i.row_id))
    db.session.add(i)
    print("...adding Incident #%s, Row ID: %s" % (i.incident_id, i.row_id))
Ejemplo n.º 3
0
def alert():

    alerts = iris_db.query(Alert)
    #alerts = []

    if request.method == 'POST':
        if request.form['btn'] == 'New':
            return redirect(url_for('new_alert'))
        elif request.form['btn'] == 'Update':
            selected = request.form.getlist('selected')
            return redirect(url_for('update_alert', selected=selected))
        elif request.form['btn'] == 'Promote':
            selected = request.form.getlist('selected')
            for s in selected:
                query = iris_db.query(Alert).filter(Alert.title == s)
                for q in query:
                    alerts.append(q.to_ref())
                    #iris_db.remove(q)

            iris_db.insert(
                Incident(title=q.title,
                         entered=q.entered,
                         comments=q.comments,
                         status="Promoted",
                         itype=q.itype,
                         alerts=alerts))

    return render_template('alert/alert.html', title='Alert', alerts=alerts)
Ejemplo n.º 4
0
def handle_incident():
    firststep=request.get_json()
    print(firststep)
    print(firststep["email"])
    secondstep=User.query.filter(User.email==firststep["email"]).first()
    thridstep=Service.query.filter(Service.servicetype_name==firststep["servicetype_name"]).first()
    fourthstep=Incident(user_id=secondstep.user_id,servicetype_id=thridstep.servicetype_id,latitude=firststep["latitude"],longitude=firststep["longitude"])
    db.session.add(fourthstep)
    db.session.commit()
# getting a User's zipcode by using latitude & longitude
    responsepostal = requests.get("https://maps.googleapis.com/maps/api/geocode/json",params={'latlng':firststep["latitude"]+','+firststep["longitude"],'key':'AIzaSyDnPdnUPzUc0NaVzp4hS6Y_dhPSE8rvK1s'})
    response1=responsepostal.json()
    list1=response1["results"][0]["address_components"]
    postal_code = None
    for obj in list1:
        if obj["types"][0]=="postal_code":
            postal_code = obj["long_name"]
    print(postal_code)
    if postal_code is not None:
        # its time to send the sms to everyone at this postal code
        heros_nearby = Hero.query.filter(Hero.zip_code==postal_code).all()
        for _hero in heros_nearby:
            print(_hero)
            send_sms("Hello "+_hero.first_name+", someone needs your help! please reply with "+str(fourthstep.incident_id)+" if you are willing to help", _hero.phone)   
        return "success"   
Ejemplo n.º 5
0
def incident(request):
    if request.method == 'POST':
        form = Incident_Report_Form(request.POST, request.FILES)
        if form.is_valid():
            print "form was valid"

            cd = form.cleaned_data
            print "cd: ", cd
            i = Incident(description=cd['description'], incident_image=cd['incident_image'], x_gps_coordinate=cd['x_gps_coordinate'],
                         y_gps_coordinate=cd['y_gps_coordinate'], pub_date=timezone.now())
            i.save()
            return HttpResponse("Thank You!")
    else:
        print "Generating form:"
        form = Incident_Report_Form()
    return render(request, 'incident_report/incident.html', {'form':form})
Ejemplo n.º 6
0
def run_test(endpoint_model, metrics_groups, alert_groups, endpoint_expected,
             endpoint_threshold):
    attempt = 0
    keep_trying = True
    incident_timestamp = datetime.now(timezone.utc).astimezone().isoformat()
    original_endpoint_url = endpoint_model.url
    while keep_trying:

        if "##CUPCAKE_ATTEMPT##" in original_endpoint_url:
            endpoint_model.url = original_endpoint_url.replace(
                "##CUPCAKE_ATTEMPT##", str(attempt + 1))

        result = test_endpoint(endpoint=endpoint_model,
                               expected=endpoint_expected,
                               threshold=endpoint_threshold,
                               metrics_groups=metrics_groups)
        if not result["result"] and result["message"] == "TIMEOUT":
            attempt = attempt + 1
            if attempt <= 3:
                logger.info(
                    "re-testing timed out endpoint ({}) (attempt {} failed)".
                    format(endpoint_model.url, attempt))
                keep_trying = True
                continue
        break

    incident = Incident(timestamp=incident_timestamp,
                        endpoint=endpoint_model,
                        result=result,
                        expected=endpoint_expected)

    handle_result(incident=incident, alert_groups=alert_groups)
Ejemplo n.º 7
0
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    incidents_with_age = Incident.select().where(Incident.age > 0).order_by(Incident.age.asc())
    incidents_without_age = Incident.select().where(Incident.age >> None).order_by(Incident.age.asc())
    incidents = list(incidents_with_age) + list(incidents_without_age)
    states = [i.state for i in Incident.select(Incident.state).distinct().order_by(Incident.state)]

    def slug(incident):
        uniq = incident.name or 'unknown'

        if (incident.postofficename):
            uniq += '-' + incident.postofficename

        uniq += '-' +  incident.state

        return uniq.lower().replace(' ', '-').replace('.', '').replace('--', '-')

    return render_template('index.html', incidents=incidents, states=states, slug=slug, **make_context())
Ejemplo n.º 8
0
def receive_incident(request):
    #print "LOL"
    print "Request: ", request
    try:
        #print "Data: ", data

        latitude = request.POST['LATITUDE']
        print "got latitude"
        longitude = request.POST['LONGITUDE']
        print "got longitude"
        description = request.POST['DESCRIPTION']
        print "got description"
        image = request.FILES['PHOTOGRAPH']
        today = now()
        print "\n\n\nDescription: ", description
        i = Incident(description=description, incident_image=image, x_gps_coordinate=latitude, y_gps_coordinate=longitude,
                    pub_date=today)
        i.save()
    except:
        print "Could not parse json"



    return HttpResponse("")
Ejemplo n.º 9
0
def emit_summary():
    """
    Show a summary via a subset of notification types
    """
    logger.info("emit summary")

    global endpoint_definitions
    global alert_definitions
    global db

    number_of_endpoints = 0

    for group in endpoint_definitions["groups"]:
        for environment in group["environments"]:
            for endpoint_group in environment["endpoint-groups"]:
                if endpoint_group["enabled"] == "true":
                    for _ in endpoint_group["endpoints"]:
                        number_of_endpoints = number_of_endpoints + 1

    endpoint_plural = "s"

    if number_of_endpoints == 1:
        endpoint_plural = ""

    message = "Cupcake is alive and currently monitoring {} endpoint{}.".format(
        number_of_endpoints, endpoint_plural)

    actives = db.get_all_actives()
    actives_message = ""

    for active in actives:
        actives_message = actives_message + "{} since {}\n".format(
            active["message"],
            datetime.utcfromtimestamp(
                active["timestamp"]).strftime('%Y-%m-%d %H:%M:%S'))

    if len(actives) == 0:
        message = message + "\n\nCupcake is not currently aware of any alerts."
    else:
        message = message + "\n\nCupcake is aware of the following alerts:\n%s" % actives_message

    deliver_alert_to_group(incident=Incident(timestamp=time.time(),
                                             message=message),
                           alert_group_id="summary",
                           alert_definitions=alert_definitions)
Ejemplo n.º 10
0
    def store_data(self, incident_data):
        incident_type, created = IncidentType.objects.get_or_create(
            type_name=incident_data['type'])
        incident = None
        try:
            incident = Incident.objects.get(
                incident_id=incident_data['incident_id'])
        except Incident.DoesNotExist:
            if incident_data['status'] == 'active':
                incident_args = {'incident_id': incident_data['incident_id'],
                                 'type': incident_type,
                                 'location_text': incident_data['location'],
                                 'level': incident_data['level']
                                 }
                incident = Incident()
                incident.create_incident(**incident_args)

                self.incident_logger.info("start, id: %s, type_id:"
                                          "\"%s\", loc_str: %s, lvl: %s"
                                          % (incident.incident_id,
                                             incident.type.type_name,
                                             incident.location_text,
                                             incident.level))

        if incident is not None and incident_data['status'] == 'closed' and \
                incident.end is None:
            incident.end = timezone.now()
            incident.save()
            self.incident_logger.info("end, id: %s" % incident.incident_id)

        for vehic_data in incident_data['units']:
            p = re.compile("([A-Za-z]+)")
            match = p.search(vehic_data)
            type_string = match.group()
            vehic_type, created = VehicleType.objects.get_or_create(
                name=type_string)

            vehicle, created = \
                Vehicle.objects.get_or_create(name=vehic_data,
                                              defaults={'type': vehic_type})
            if incident is not None:
                try:
                    Dispatch.objects.get(vehicle_id=vehicle,
                                         incident_id=incident)
                except ObjectDoesNotExist:
                    dispatch = Dispatch()
                    dispatch.dispatch(vehicle_id=vehicle,
                                      incident_id=incident)
                    self.dispatch_logger.info("vehic: %s, incident: %s" %
                                              (vehicle.name,
                                               incident.incident_id))
                    pass
Ejemplo n.º 11
0
def new_incident_action ():
    if 'gcs_user' in session and session ['gcs_logged_in']:
        incident_title = request.form.get ('title')
        incident_title = incident_title.strip ()

        description = request.form.get ('description').strip()
        description = description.strip ()
        username_val = session ['gcs_user']
        drone_sel_id = int(request.form.get ('drone_select'))
        username_id = GCSUser.query.filter_by (username = username_val).first().id
        drone_sel_name = Drone.query.filter_by (id = drone_sel_id).first ().drone_name

        priority_sel = request.form.get ('priority_sel')
        incident = Incident (incident_title,description,username_id,username_val,
                drone_sel_id,drone_sel_name,priority_sel)
        db.session.add (incident)
        db.session.commit ()
        return redirect ('/incidents',code = 302)
    else:
        return redirect ('/gcslogin',code = 302)
Ejemplo n.º 12
0
def new_incident():
    form = NewIncidentForm()
    if form.validate_on_submit():
        title = form.title.data
        itype = form.itype.data
        entered = datetime.utcnow()
        comments = [form.comments.data]
        alerts = []

        iris_db.insert(
            Incident(title=title,
                     status="Manual",
                     itype=itype,
                     comments=comments,
                     entered=entered,
                     alerts=alerts))
        return redirect(url_for('incident'))

    return render_template("incident/new_incident.html",
                           title='New Incident',
                           form=form)
Ejemplo n.º 13
0
def create(request):
    """Create Incident with IncidentLocation"""
    try:
        json_obj = commonHttp.get_json(request.body)

        # Check request json
        req_attrs = [
            expectedAttr["DESC"],
            expectedAttr["TYPE"],
            expectedAttr["LOC"],
        ]

        commonHttp.check_keys(json_obj, req_attrs)

        new_location = None

        if json_obj.get(expectedAttr["LOC"]):
            new_location = create_location(json_obj.get(expectedAttr["LOC"]))

        activation_time = json_obj.get(expectedAttr["ACT_TIME"])
        deactivation_time = json_obj.get(expectedAttr["DEACT_TIME"])

        new_incident = Incident(activation_time=activation_time,
                                deactivation_time=deactivation_time,
                                description=json_obj[expectedAttr["DESC"]],
                                incident_type=json_obj[expectedAttr["TYPE"]],
                                location=new_location)

        commonHttp.save_model_obj(new_incident)

        response = JsonResponse({"id": new_incident.id, "success": True})

        return response

    except commonHttp.HttpBadRequestException as e:
        return HttpResponseBadRequest(e.reason_phrase)
Ejemplo n.º 14
0
def photo_menu(photo):
    previous_incidents = (session.query(Incident).order_by(
        Incident.time.desc()))
    choices = [{
        'name': 'Create new Incident',
        'value': 'new_incident',
    }]
    if previous_incidents.first():
        choices.append({
            'name': 'Add to previous Incident',
            'value': 'previous_incident',
        })

    choices += [{
        'name': 'Ignore',
        'value': 'ignore',
    }, {
        'name': 'Main Menu',
        'value': 'main_menu',
    }, {
        'name': 'Quit',
        'value': 'quit',
    }]

    choice = prompt({
        'type':
        'list',
        'name':
        'item',
        'message':
        'Photo {}; {}'.format(photo.filename,
                              photo.timestamp.astimezone(timezone)),
        'choices':
        choices,
    })['item']
    if choice == 'new_incident':
        incident = Incident(time=photo.timestamp)
        incident.photos.append(photo)
        session.add(incident)
        session.commit()
        incident_menu(incident)
    elif choice == 'previous_incident':
        incident = prompt({
            'type':
            'list',
            'name':
            'incident',
            'message':
            'Previous Incidents',
            'choices': [{
                'name':
                '{} {} {}'.format(i.time and i.time.astimezone(timezone),
                                  i.location and i.location.name, i.car
                                  and i.car.license_plate),
                'value':
                i,
            } for i in previous_incidents]
        })['incident']
        incident.photos.append(photo)
        session.commit()
    elif choice == 'ignore':
        photo.ignore = True
        session.commit()
    elif choice == 'main_menu':
        main_menu()
    elif choice == 'quit':
        sys.exit(0)
Ejemplo n.º 15
0
#!/usr/bin/env python

from bs4 import BeautifulSoup
import requests

from models import Incident

url_base = 'http://www.osha.gov/pls/imis/establishment.inspection_detail?id='

for incident in Incident.select():
    if incident.narrative:
        pass
    else:
        try:
            url = url_base + '%s' % incident.inspection_no
            print url
            r = requests.get(url)
            soup = BeautifulSoup(r.content)

            tables = soup.find(id="maincontain").find_all('table',
                                                          bgcolor='white')
            num_matches = len(tables)
            narrative = tables[num_matches - 3].find('td').text.strip()

            print narrative
            query = Incident.update(narrative=narrative).where(
                Incident.inspection_no == incident.inspection_no)
            print query
            query.execute()
        except Exception as error:
            print 'Failed: %s, error is: %s' % (incident.inspection_no, error)
Ejemplo n.º 16
0
#!/usr/bin/env python

from bs4 import BeautifulSoup
import requests

from models import Incident

url_base = 'http://www.osha.gov/pls/imis/establishment.inspection_detail?id='

for incident in Incident.select():
    if incident.narrative:
        pass
    else:
        try:
            url = url_base + '%s' % incident.inspection_no
            print url
            r = requests.get(url)
            soup = BeautifulSoup(r.content)

            tables = soup.find(id="maincontain").find_all('table', bgcolor='white')
            num_matches = len(tables)
            narrative = tables[num_matches-3].find('td').text.strip()

            print narrative
            query = Incident.update(narrative=narrative).where(Incident.inspection_no == incident.inspection_no)
            print query
            query.execute()
        except Exception as error:
            print 'Failed: %s, error is: %s' % (incident.inspection_no, error)