<commit_before>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
	iconUrl: '/static/icons/place_marker.png',
	iconSize: [40, 40],
	iconAnchor: [20, 40],
	popupAnchor: [0,-40]
});

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var currentPatients;
var newPatientIndex;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    $('#start_dispatch_button').hide();

    // Update current location
    updateCurrentLocation(mymap.getCenter());

    // Update current address
    updateCurrentAddress(currentLocation);

    // Clear current currentPatients
    currentPatients = {};
    newPatientIndex = 0;

    // Initialize patient form
    $('#patients').empty();

    // add new patient form entry
    addPatientForm(newPatientIndex);

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();

    $('#start_dispatch_button').show();

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        bsalert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = ambulance;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

var updateCurrentLocation = function(location) {

    console.log('Setting current location to: ' + location.lat + ', ' + location.lng);

    // set currentLocation
    currentLocation = location;

    // update coordinates on form
    $('#curr-lat').html(currentLocation.lat);
    $('#curr-lng').html(currentLocation.lng);

    // remove existing marker
    markersGroup.clearLayers();

    // laydown marker
    var marker = L.marker(location,
        {
            icon: placeIcon,
            draggable: true
        })
        .addTo(markersGroup);
    markersGroup.addTo(mymap);

    // pan to location
    mymap.panTo(location);

    // events
    marker.on('dragend', function(e) {

        // update current location
        updateCurrentLocation(marker.getLatLng());

        // update address?
        if ($('#update-address').prop('checked'))
            updateCurrentAddress(currentLocation);

    })

}

var updateCurrentAddress = function(location) {

    var options = {
        types: 'address',
        limit: 1
    };
    geocoder.reverse(location, options,
        function (results, status) {

        if (status != "success") {
            bsalert("Could not geocode:\nError " + status + ", " + results['error']);
            return;
        }

        // quick return if found nothing
        if (results.length == 0) {
            console.log('Got nothing from geocode');
            return;
        }

        // parse features into current address
        currentAddress = geocoder.parse_feature(results[0]);

        console.log(
            'Setting currentAddress to:'
            + '\nnumber: ' + currentAddress['number']
            + '\nstreet: ' + currentAddress['street']
            + '\nunit: ' + currentAddress['unit']
            + '\nlocation: ' + currentAddress['location']['latitude']
            + ',' + currentAddress['location']['longitude']
            + '\nneighborhood: ' + currentAddress['neighborhood']
            + '\nzipcode: ' + currentAddress['zipcode']
            + '\ncity: ' + currentAddress['city']
            + '\nstate: ' + currentAddress['state']
            + '\ncountry: ' + currentAddress['country']
        );

        // set input text
        $('#street').val(currentAddress['street_address']);

    });

}

var updateCoordinates = function() {

    // when the user changes the street address
    var address =$('#street').val();

    // quick return if no address
    if (!address)
        return;

    // otherwise geocode and update
    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocoder.geocode(address, options,
        function (results, status) {

            if (status != "success") {
                bsalert("Could not geocode:\nError " + status + ", " + results['error']);
                return;
            }

            // quick return if found nothing
            if (results.length == 0) {
                console.log('Got nothing from geocode');
                return;
            }

            // parse features into address
            var address = geocoder.parse_feature(results[0]);

            console.log(
                'Setting currentLocation to:'
                + '\nnumber: ' + address['number']
                + '\nstreet: ' + address['street']
                + '\nunit: ' + address['unit']
                + '\nlocation: ' + address['location']['latitude']
                + ',' + address['location']['longitude']
                + '\nneighborhood: ' + address['neighborhood']
                + '\nzipcode: ' + address['zipcode']
                + '\ncity: ' + address['city']
                + '\nstate: ' + address['state']
                + '\ncountry: ' + address['country']
            );

            // set current location
            updateCurrentLocation({
                lat: address['location']['latitude'],
                lng: address['location']['longitude']
            });

        });
}

function dispatchCall() {

    var form = {};

    // call information
    var street_address = $('#street').val().trim();
    form['details'] = $('#comment').val().trim();
    form['priority'] = $('input:radio[name=priority]:checked').val();

    // checks
    if (form["priority"] === undefined) {
        bsalert("Please select the priority level.");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        bsalert("Please dispatch at least one ambulance.");
        return;
    }

    // address information
    form['neighborhood'] = currentAddress['neighborhood'];
    form['city'] = currentAddress['city'];
    form['state'] = currentAddress['state'];
    form['country'] = currentAddress['country'];
    form['zipcode'] = currentAddress['zipcode'];
    form['location'] = currentAddress['location'];

    // Has the user modified the street address?
    if (street_address != currentAddress['street_address']) {

        // parse street address
        var address = geocoder.parse_street_address(street_address, form['country']);

        form['number'] = address['number'];
        form['street'] = address['street'];
        form['unit'] = address['unit'];

    } else {

        form['number'] = currentAddress['number'];
        form['street'] = currentAddress['street'];
        form['unit'] = currentAddress['unit'];

    }

    // ambulances
    var ambulances = [];
    for (var id in dispatchingAmbulances)
        if (dispatchingAmbulances.hasOwnProperty(id))
            ambulances.push({ 'ambulance_id': id });
    form['ambulances'] = ambulances;

    // patients
    var patients = [];
    for (var index in currentPatients)
        if (currentPatients.hasOwnProperty(index)) {
            var patient = currentPatients[index];
            var obj = { 'name': patient[0] };
            if (patient[1])
                // add age
                obj['age'] = patient[1];
            patients.push(obj);
        }
    form['patients'] = patients;

    // make json call
    let postJsonUrl = 'api/call/';
    console.log("Will post '" + JSON.stringify(form) + "'");

    var CSRFToken = getCookie('csrftoken');

    // retrieve csrf token
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!CSRFSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", CSRFToken);
            }
        }
    })

    // make ajax call
    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: form,
        success: function (data) {

            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

            // Show modal
            bsalert(sucessMsg, 'alert-success', 'Success');
            // $('.modal-title').html('Success');
            // $('.modal-body').html(successMsg).addClass('alert-success');
            // $("#dispatchModal").modal('show');

            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {

            // Show modal
            // $('.modal-title').html('Failure');
            // $('.modal-body').html(textStatus + ": " + errorThrown).addClass('alert-danger');
            // $("#dispatchModal").modal('show');
            bsalert(textStatus + ": " + errorThrown);

            endDispatching();
        }
    });
}

// patient functions

var addPatient = function(index) {

    console.log('Adding patient index ' + index);

    var name = $('#patient-' + index + '-name').val().trim();
    var age = $('#patient-' + index + '-age').val().trim();

    // is name empty?
    if (!name) {
        bsalert('Empty name');
        return;
    }

    // add name
    currentPatients[index] = [name, age];
    newPatientIndex++;

    // change button symbol
    var symbol = $('#patient-' + index + '-symbol');
    symbol.removeClass('fa-plus');
    symbol.addClass('fa-minus');

    // change button action from add to remove
    $('#patients').find('#patient-' + index + '-button')
        .off()
        .on('click', function(e) { removePatient(index); });

    // add new form
    addPatientForm(newPatientIndex);

}

var removePatient = function(index) {

    console.log('Removing patient index ' + index);

    // remove from storage
    delete currentPatients[index];

    // remove from form
    $('#patients')
        .find('#patient-' + index + '-form')
        .remove();

}

var addPatientForm = function(index) {

    // add new patient form entry
    $('#patients').append(newPatientForm(index, 'fa-plus'));

    // bind addPatient to click
    $('#patients')
        .on('click',
            '#patient-' + index + '-button',
            function(e) { addPatient(index); });

}

var newPatientForm = function(index, symbol) {

    var html =
        '
' +
            '
' +
                '<input id="patient-' + index + '-name" ' +
                       'type="text" ' +
                       'class="form-control" ' +
                       'placeholder="Name">' +
            '
' +
            '
' +
                '<input id="patient-' + index + '-age" ' +
                       'type="number" min="0" ' +
                       'class="form-control" ' +
                       'placeholder="Age">' +
            '
' +
            '
' +
                '<button class="btn btn-default new-patient" ' +
                       ' type="button" ' +
                       ' id="patient-' + index + '-button">' +
                    '' +
                '</button>' +
            '
' +
        '
';

    // console.log('html = "' + html + '"');

    return html;

}

// connect actions to inputs

$("#street").change(function () {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-coordinates').change(function() {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-address').change(function() {

    // update address?
    if ($('#update-address').prop('checked'))
        updateCurrentAddress(currentLocation);

});

$('#dispatch_form_collapse').submit(function (e) {

   // prevent normal form submission
    e.preventDefault();

    // dispatch call
    dispatchCall();

});

// CSRF functions

function CSRFSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
<commit_msg>Multiple ready functions in javascript.<commit_after>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
	iconUrl: '/static/icons/place_marker.png',
	iconSize: [40, 40],
	iconAnchor: [20, 40],
	popupAnchor: [0,-40]
});

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var currentPatients;
var newPatientIndex;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    $('#start_dispatch_button').hide();

    // Update current location
    updateCurrentLocation(mymap.getCenter());

    // Update current address
    updateCurrentAddress(currentLocation);

    // Clear current currentPatients
    currentPatients = {};
    newPatientIndex = 0;

    // Initialize patient form
    $('#patients').empty();

    // add new patient form entry
    addPatientForm(newPatientIndex);

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();

    $('#start_dispatch_button').show();

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        bsalert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = ambulance;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

var updateCurrentLocation = function(location) {

    console.log('Setting current location to: ' + location.lat + ', ' + location.lng);

    // set currentLocation
    currentLocation = location;

    // update coordinates on form
    $('#curr-lat').html(currentLocation.lat);
    $('#curr-lng').html(currentLocation.lng);

    // remove existing marker
    markersGroup.clearLayers();

    // laydown marker
    var marker = L.marker(location,
        {
            icon: placeIcon,
            draggable: true
        })
        .addTo(markersGroup);
    markersGroup.addTo(mymap);

    // pan to location
    mymap.panTo(location);

    // events
    marker.on('dragend', function(e) {

        // update current location
        updateCurrentLocation(marker.getLatLng());

        // update address?
        if ($('#update-address').prop('checked'))
            updateCurrentAddress(currentLocation);

    })

}

var updateCurrentAddress = function(location) {

    var options = {
        types: 'address',
        limit: 1
    };
    geocoder.reverse(location, options,
        function (results, status) {

        if (status != "success") {
            bsalert("Could not geocode:\nError " + status + ", " + results['error']);
            return;
        }

        // quick return if found nothing
        if (results.length == 0) {
            console.log('Got nothing from geocode');
            return;
        }

        // parse features into current address
        currentAddress = geocoder.parse_feature(results[0]);

        console.log(
            'Setting currentAddress to:'
            + '\nnumber: ' + currentAddress['number']
            + '\nstreet: ' + currentAddress['street']
            + '\nunit: ' + currentAddress['unit']
            + '\nlocation: ' + currentAddress['location']['latitude']
            + ',' + currentAddress['location']['longitude']
            + '\nneighborhood: ' + currentAddress['neighborhood']
            + '\nzipcode: ' + currentAddress['zipcode']
            + '\ncity: ' + currentAddress['city']
            + '\nstate: ' + currentAddress['state']
            + '\ncountry: ' + currentAddress['country']
        );

        // set input text
        $('#street').val(currentAddress['street_address']);

    });

}

var updateCoordinates = function() {

    // when the user changes the street address
    var address =$('#street').val();

    // quick return if no address
    if (!address)
        return;

    // otherwise geocode and update
    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocoder.geocode(address, options,
        function (results, status) {

            if (status != "success") {
                bsalert("Could not geocode:\nError " + status + ", " + results['error']);
                return;
            }

            // quick return if found nothing
            if (results.length == 0) {
                console.log('Got nothing from geocode');
                return;
            }

            // parse features into address
            var address = geocoder.parse_feature(results[0]);

            console.log(
                'Setting currentLocation to:'
                + '\nnumber: ' + address['number']
                + '\nstreet: ' + address['street']
                + '\nunit: ' + address['unit']
                + '\nlocation: ' + address['location']['latitude']
                + ',' + address['location']['longitude']
                + '\nneighborhood: ' + address['neighborhood']
                + '\nzipcode: ' + address['zipcode']
                + '\ncity: ' + address['city']
                + '\nstate: ' + address['state']
                + '\ncountry: ' + address['country']
            );

            // set current location
            updateCurrentLocation({
                lat: address['location']['latitude'],
                lng: address['location']['longitude']
            });

        });
}

function dispatchCall() {

    var form = {};

    // call information
    var street_address = $('#street').val().trim();
    form['details'] = $('#comment').val().trim();
    form['priority'] = $('input:radio[name=priority]:checked').val();

    // checks
    if (form["priority"] === undefined) {
        bsalert("Please select the priority level.");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        bsalert("Please dispatch at least one ambulance.");
        return;
    }

    // address information
    form['neighborhood'] = currentAddress['neighborhood'];
    form['city'] = currentAddress['city'];
    form['state'] = currentAddress['state'];
    form['country'] = currentAddress['country'];
    form['zipcode'] = currentAddress['zipcode'];
    form['location'] = currentAddress['location'];

    // Has the user modified the street address?
    if (street_address != currentAddress['street_address']) {

        // parse street address
        var address = geocoder.parse_street_address(street_address, form['country']);

        form['number'] = address['number'];
        form['street'] = address['street'];
        form['unit'] = address['unit'];

    } else {

        form['number'] = currentAddress['number'];
        form['street'] = currentAddress['street'];
        form['unit'] = currentAddress['unit'];

    }

    // ambulances
    var ambulances = [];
    for (var id in dispatchingAmbulances)
        if (dispatchingAmbulances.hasOwnProperty(id))
            ambulances.push({ 'ambulance_id': id });
    form['ambulances'] = ambulances;

    // patients
    var patients = [];
    for (var index in currentPatients)
        if (currentPatients.hasOwnProperty(index)) {
            var patient = currentPatients[index];
            var obj = { 'name': patient[0] };
            if (patient[1])
                // add age
                obj['age'] = patient[1];
            patients.push(obj);
        }
    form['patients'] = patients;

    // make json call
    let postJsonUrl = 'api/call/';
    console.log("Will post '" + JSON.stringify(form) + "'");

    var CSRFToken = getCookie('csrftoken');

    // retrieve csrf token
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!CSRFSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", CSRFToken);
            }
        }
    })

    // make ajax call
    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: form,
        success: function (data) {

            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

            // Show modal
            bsalert(sucessMsg, 'alert-success', 'Success');
            // $('.modal-title').html('Success');
            // $('.modal-body').html(successMsg).addClass('alert-success');
            // $("#dispatchModal").modal('show');

            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {

            // Show modal
            // $('.modal-title').html('Failure');
            // $('.modal-body').html(textStatus + ": " + errorThrown).addClass('alert-danger');
            // $("#dispatchModal").modal('show');
            bsalert(textStatus + ": " + errorThrown);

            endDispatching();
        }
    });
}

// patient functions

var addPatient = function(index) {

    console.log('Adding patient index ' + index);

    var name = $('#patient-' + index + '-name').val().trim();
    var age = $('#patient-' + index + '-age').val().trim();

    // is name empty?
    if (!name) {
        bsalert('Empty name');
        return;
    }

    // add name
    currentPatients[index] = [name, age];
    newPatientIndex++;

    // change button symbol
    var symbol = $('#patient-' + index + '-symbol');
    symbol.removeClass('fa-plus');
    symbol.addClass('fa-minus');

    // change button action from add to remove
    $('#patients').find('#patient-' + index + '-button')
        .off()
        .on('click', function(e) { removePatient(index); });

    // add new form
    addPatientForm(newPatientIndex);

}

var removePatient = function(index) {

    console.log('Removing patient index ' + index);

    // remove from storage
    delete currentPatients[index];

    // remove from form
    $('#patients')
        .find('#patient-' + index + '-form')
        .remove();

}

var addPatientForm = function(index) {

    // add new patient form entry
    $('#patients').append(newPatientForm(index, 'fa-plus'));

    // bind addPatient to click
    $('#patients')
        .on('click',
            '#patient-' + index + '-button',
            function(e) { addPatient(index); });

}

var newPatientForm = function(index, symbol) {

    var html =
        '
' +
            '
' +
                '<input id="patient-' + index + '-name" ' +
                       'type="text" ' +
                       'class="form-control" ' +
                       'placeholder="Name">' +
            '
' +
            '
' +
                '<input id="patient-' + index + '-age" ' +
                       'type="number" min="0" ' +
                       'class="form-control" ' +
                       'placeholder="Age">' +
            '
' +
            '
' +
                '<button class="btn btn-default new-patient" ' +
                       ' type="button" ' +
                       ' id="patient-' + index + '-button">' +
                    '' +
                '</button>' +
            '
' +
        '
';

    // console.log('html = "' + html + '"');

    return html;

}

$(document).ready(function() {

    // connect actions to inputs

    $("#street").change(function () {

        // update coordinates?
        if ($('#update-coordinates').prop('checked'))
            updateCoordinates();

    });

    $('#update-coordinates').change(function () {

        // update coordinates?
        if ($('#update-coordinates').prop('checked'))
            updateCoordinates();

    });

    $('#update-address').change(function () {

        // update address?
        if ($('#update-address').prop('checked'))
            updateCurrentAddress(currentLocation);

    });

    $('#dispatch_form_collapse').submit(function (e) {

        // prevent normal form submission
        e.preventDefault();

        // dispatch call
        dispatchCall();

    });

});

// CSRF functions

function CSRFSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var child_process = require('child_process'),
	program = require('commander'),
	watch = require('node-watch'),
	chalk = require('chalk'),
	_ = require('lodash');

var exec = child_process.exec,
	spawn = child_process.spawn;

// Configure CLI parameters.
require('pkginfo')(module);
program
	.version(module.exports.version)
	.description(module.exports.description)
	.option('-c, --command [cmd]', 'command to run, and to restart when files change')
	.option('-w, --watch [path]', 'directory or file to watch for changes')
	.parse(process.argv);

// Start process and listen for shutdown event.
var child;
var start = function () {
	child = exec(program.command);
	child.stdout.pipe(process.stdout);
	child.stderr.pipe(process.stderr);
	child.on('close', function (code, signal) {
		if (code !== 8) {
			console.log(chalk.black.bgRed(' Process has died. Waiting for changes to restart. '));
		}
	});
}

// Listen for file changes and, when they occur, restart process.
watch(program.watch, _.debounce(function(path) {
	console.log(chalk.green(' → Change detected on "%s". Restarting process.'), path);
	child.kill();
	start();
}, 1000));

// Initialize.
start();
console.log(chalk.black.bgGreen(' Watching %s/ for changes. '), program.watch);
<commit_msg>output help when required parameters are omitted<commit_after>#!/usr/bin/env node

var exec = require('child_process').exec,
	program = require('commander'),
	watch = require('node-watch'),
	chalk = require('chalk'),
	_ = require('lodash');

// Configure CLI parameters.
require('pkginfo')(module);
program
	.version(module.exports.version)
	.description(module.exports.description)
	.usage('--command [command] --watch [path]')
	.option('-c, --command [cmd]', 'command to run, and to restart when files change')
	.option('-w, --watch [path]', 'directory or file to watch for changes')
	.parse(process.argv);

if (!program.command || !program.watch) {
	program.help();
}

// Start process and listen for shutdown event.
var child;
var start = function () {
	child = exec(program.command);
	child.stdout.pipe(process.stdout);
	child.stderr.pipe(process.stderr);
	child.on('close', function (code, signal) {
		if (code !== 8) {
			console.log(chalk.black.bgRed(' Process has died. Waiting for changes to restart. '));
		}
	});
};

// Listen for file changes and, when they occur, restart process.
watch(program.watch, _.debounce(function(path) {
	console.log(chalk.green(' → Change detected on "%s". Restarting process.'), path);
	child.kill();
	start();
}, 1000));

// Initialize.
start();
console.log(chalk.black.bgGreen(' Watching %s/ for changes. '), program.watch);
<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	$("#testjs").click(function(e) {
		$('.jumbotron h1').text("Javascript is connected");
		$('#testjs').text("Please Wait...");
		$(".jumbotron p").toggleClass("active");
	});

	// Add any additional listeners here
	// example: $("#div-id").click(functionToCall);
	$("a.thumbnail").click(projectClick);
 	$("#submitBtn").click(updateProject);
}
function updateProject(e) {
   var projectID = $('#project').val();
   $(projectID).animate({
      width: $('#width').val()
   });

   var newText = $('#description').val();
   $(projectID + " .project-description").text(newText);
}
function projectClick(e) {
  // Cancel the default action, which prevents the page from reloading

    e.preventDefault();

//testing some things
    var javatext = $('#testjs').text()
    if (javatext == "Please Wait...") {
	$('#testjs').text("Javascript running");
    }

    //$('#testjs').text("Javascript running");

    // In an event listener, $(this) is the leement that fired the event
    var projectTitle = $(this).find("p").text();
    var jumbotronHeader = $(".jumbotron h1");
    jumbotronHeader.text(projectTitle);
    //$(this).css("background-color", "#7fff00");
    var containingProject = $(this).closest(".project");
    var description = $(containingProject).find(".project-description");
    if (description.length == 0) {
       $(containingProject).append("

Description of the project.

");
    }
    var projectImage = $(this).find("img");
    projectImage.toggle();
    description.toggle();

}
<commit_msg>fixed a bug. stretch goal should still be accomplished. description toggles.<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	$("#testjs").click(function(e) {
		$('.jumbotron h1').text("Javascript is connected");
		$('#testjs').text("Please Wait...");
		$(".jumbotron p").toggleClass("active");
	});

	// Add any additional listeners here
	// example: $("#div-id").click(functionToCall);
	$("a.thumbnail").click(projectClick);
 	$("#submitBtn").click(updateProject);
}
function updateProject(e) {
   var projectID = $('#project').val();
   $(projectID).animate({
      width: $('#width').val()
   });

   var newText = $('#description').val();
   $(projectID + " .project-description").text(newText);
}
function projectClick(e) {
  // Cancel the default action, which prevents the page from reloading

    e.preventDefault();

//testing some things
    var javatext = $('#testjs').text()
    if (javatext == "Please Wait...") {
	$('#testjs').text("Javascript running");
    }

    //$('#testjs').text("Javascript running");

    // In an event listener, $(this) is the leement that fired the event
    var projectTitle = $(this).find("p").text();
    var jumbotronHeader = $(".jumbotron h1");
    jumbotronHeader.text(projectTitle);
    //$(this).css("background-color", "#7fff00");
    var containingProject = $(this).closest(".project");
    var description = $(containingProject).find(".project-description");
    if (description.length == 0) {
       $(containingProject).append("

Description of the project.

");
    }
    var projectImage = $(this).find("img");

    description.toggle();
}

<|endoftext|>


<commit_before>const TelegramBot = require('node-telegram-bot-api');
var gcloud = require('google-cloud');
var vision = gcloud.vision;

const token = 'API TOKEN';
const bot = new TelegramBot(token, {polling: true});

var vision = vision({
    projectId: 'telegram-160918',
    keyFilename: './path/to/api/key'
});

bot.onText(/\/help/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;

  var text = `Do you ever look at porn and wonder if what you're looking at is actually porn? Watson is here to help. Watson is an artificially intelligent sentient with vision capabilities. It can detect sentiment in faces, discern landmarks, logos, extract text from images, and more. Send Watson a pic and give it a try`;
  bot.sendMessage(chatId, text);
});

bot.on('photo', function(msg) {
    const chatId = msg.chat.id;
    bot.sendMessage(chatId, 'Hmm let\'s see..');
    var photoId = msg.photo[msg.photo.length-1].file_id;
    var path = bot.downloadFile(photoId, "./public/img").then(function (path) {
        var types = [
            'face',
            'label',
            'landmark',
            'logo',
            'text',
            'safeSearch'
        ];

        vision.detect(path, types, function(err, detections, apiResponse) {

  // detections = [
  //   // Detections for image.jpg:
  //   {
  //     faces: [...],
  //     labels: [...],
  //     landmarks: [...],
  //     logos: [...],
  //     text: [...],
  //     safeSearch: {...},
  //   },
  // ]

  // faces = [
  //   {
  //     angles: {
  //       pan: -8.1090336,
  //       roll: -5.0002542,
  //       tilt: 18.012161
  //     },
  //     bounds: {
  //       head: [
  //         {
  //           x: 1
  //         },
  //         {
  //           x: 295
  //         },
  //         {
  //           x: 295,
  //           y: 301
  //         },
  //         {
  //           x: 1,
  //           y: 301
  //         }
  //       ],
  //       face: [
  //         {
  //           x: 28,
  //           y: 40
  //         },
  //         {
  //           x: 250,
  //           y: 40
  //         },
  //         {
  //           x: 250,
  //           y: 262
  //         },
  //         {
  //           x: 28,
  //           y: 262
  //         }
  //       ]
  //     },
  //     features: {
  //       confidence: 34.489909,
  //       chin: {
  //         center: {
  //           x: 143.34183,
  //           y: 262.22998,
  //           z: -57.388493
  //         },
  //         left: {
  //           x: 63.102425,
  //           y: 248.99081,
  //           z: 44.207638
  //         },
  //         right: {
  //           x: 241.72728,
  //           y: 225.53488,
  //           z: 19.758242
  //         }
  //       },
  //       ears: {
  //         left: {
  //           x: 54.872219,
  //           y: 207.23712,
  //           z: 97.030685
  //         },
  //         right: {
  //           x: 252.67567,
  //           y: 180.43124,
  //           z: 70.15992
  //         }
  //       },
  //       eyebrows: {
  //         left: {
  //           left: {
  //             x: 58.790176,
  //             y: 113.28249,
  //             z: 17.89735
  //           },
  //           right: {
  //             x: 106.14151,
  //             y: 98.593758,
  //             z: -13.116687
  //           },
  //           top: {
  //             x: 80.248711,
  //             y: 94.04303,
  //             z: 0.21131183
  //           }
  //         },
  //         right: {
  //           left: {
  //             x: 148.61565,
  //             y: 92.294594,
  //             z: -18.804882
  //           },
  //           right: {
  //             x: 204.40808,
  //             y: 94.300117,
  //             z: -2.0009689
  //           },
  //           top: {
  //             x: 174.70135,
  //             y: 81.580917,
  //             z: -12.702137
  //           }
  //         }
  //       },
  //       eyes: {
  //         left: {
  //           bottom: {
  //             x: 84.883934,
  //             y: 134.59479,
  //             z: -2.8677137
  //           },
  //           center: {
  //             x: 83.707092,
  //             y: 128.34,
  //             z: -0.00013388535
  //           },
  //           left: {
  //             x: 72.213913,
  //             y: 132.04138,
  //             z: 9.6985674
  //           },
  //           pupil: {
  //             x: 86.531624,
  //             y: 126.49807,
  //             z: -2.2496929
  //           },
  //           right: {
  //             x: 105.28892,
  //             y: 125.57655,
  //             z: -2.51554
  //           },
  //           top: {
  //             x: 86.706947,
  //             y: 119.47144,
  //             z: -4.1606765
  //           }
  //         },
  //         right: {
  //           bottom: {
  //             x: 179.30353,
  //             y: 121.03307,
  //             z: -14.843414
  //           },
  //           center: {
  //             x: 181.17694,
  //             y: 115.16437,
  //             z: -12.82961
  //           },
  //           left: {
  //             x: 158.2863,
  //             y: 118.491,
  //             z: -9.723031
  //           },
  //           pupil: {
  //             x: 175.99976,
  //             y: 114.64407,
  //             z: -14.53744
  //           },
  //           right: {
  //             x: 194.59413,
  //             y: 115.91954,
  //             z: -6.952745
  //           },
  //           top: {
  //             x: 173.99446,
  //             y: 107.94287,
  //             z: -16.050705
  //           }
  //         }
  //       },
  //       forehead: {
  //         x: 126.53813,
  //         y: 93.812057,
  //         z: -18.863352
  //       },
  //       lips: {
  //         bottom: {
  //           x: 137.28528,
  //           y: 219.23564,
  //           z: -56.663128
  //         },
  //         top: {
  //           x: 134.74164,
  //           y: 192.50438,
  //           z: -53.876408
  //         }
  //       },
  //       mouth: {
  //         center: {
  //           x: 136.43481,
  //           y: 204.37952,
  //           z: -51.620205
  //         },
  //         left: {
  //           x: 104.53558,
  //           y: 214.05037,
  //           z: -30.056231
  //         },
  //         right: {
  //           x: 173.79134,
  //           y: 204.99333,
  //           z: -39.725758
  //         }
  //       },
  //       nose: {
  //         bottom: {
  //           center: {
  //             x: 133.81947,
  //             y: 173.16437,
  //             z: -48.287724
  //           },
  //           left: {
  //             x: 110.98372,
  //             y: 173.61331,
  //             z: -29.7784
  //           },
  //           right: {
  //             x: 161.31354,
  //             y: 168.24527,
  //             z: -36.1628
  //           }
  //         },
  //         tip: {
  //           x: 128.14919,
  //           y: 153.68129,
  //           z: -63.198204
  //         },
  //         top: {
  //           x: 127.83745,
  //           y: 110.17557,
  //           z: -22.650913
  //         }
  //       }
  //     },
  //     confidence: 56.748849,
  //     anger: false,
  //     blurred: false,
  //     headwear: false,
  //     joy: false,
  //     sorrow: false,
  //     surprise: false,
  //     underExposed: false
  //   }
  // ]

  // labels = [
  //   'classical sculpture',
  //   'statue',
  //   'landmark',
  //   'ancient history',
  //   'artwork'
  // ]

  // landmarks = [
  //   {
  //     desc: 'Mount Rushmore',
  //     id: '/m/019dvv',
  //     score: 28.651705,
  //     bounds: [
  //       {
  //         x: 79,
  //         y: 130
  //       },
  //       {
  //         x: 284,
  //         y: 130
  //       },
  //       {
  //         x: 284,
  //         y: 226
  //       },
  //       {
  //         x: 79,
  //         y: 226
  //       }
  //     ],
  //     locations: [
  //       {
  //         latitude: 43.878264,
  //         longitude: -103.45700740814209
  //       }
  //     ]
  //   }
  // ]

  // logos = [
  //   {
  //     desc: 'Google',
  //     id: '/m/045c7b',
  //     score: 64.35439,
  //     bounds: [
  //       {
  //         x: 11,
  //         y: 11
  //       },
  //       {
  //         x: 330,
  //         y: 11
  //       },
  //       {
  //         x: 330,
  //         y: 72
  //       },
  //       {
  //         x: 11,
  //         y: 72
  //       }
  //     ]
  //   }
  // ]

  // safeSearch = {
  //   adult: false,
  //   medical: false,
  //   spoof: false,
  //   violence: true
  // }

            var response = '';

            if(detections['faces']) {
                if(detections['faces'].length > 0) {
                var faceSentiment = 'I\'m seeing a face. ';

                if(detections['faces'][0]['joy']) {
                    faceSentiment += 'Looks very happy :)';
                }

                if(detections['faces'][0]['sorrow']) {
                    faceSentiment += 'Face full of sorrow :(';
                }

                if(detections['faces'][0]['anger']) {
                    faceSentiment += 'Looks angry';
                }

                if(detections['faces'][0]['surprise']) {
                    faceSentiment += 'Looks surprised';
                }

                response += faceSentiment += '/n';
                }
            }

            if(detections['labels']) {
                    if(detections['labels'].length > 0) {
                        var chosenValue = Math.random() < 0.5 ? 1 : 2;
                        if(chosenValue === 1) {
                            var text = "Getting a " + detections['labels'][0] + " or " + detections['labels'][1] + " vibe. \n";
                            response += text;
                        } else {
                            var text = "Looks like a " + detections['labels'][0] + " or " + detections['labels'][1] + ". \n";
                            response += text;
                        }

                    }
            }

            if(detections['landmarks']) {
                if(detections['landmarks'].length > 0) {
                    var landmark = '\nI\ think i\'m seeing ' + detections['landmarks'][0] + '\n';
                    response += landmark;
                }
            }

            if(detections['logos']) {
                if(detections['logos'].length > 0) {
                    var logo = "I think that's the logo of " + detections['logos'];
                    response += logo;
                }
            }

            if(detections['text']) {
                if(detections['text'].length > 0) {
                    var text = "\nI'm seeing ";
                    text += " some text in the image. It says\n\n";
                    text += "\"\n";
                    text +=  detections['text'][0];
                    text += "\"";

                    response += text;
                }
            }

            if(detections['safeSearch']['adult']) {
                var text = "GULP. I'm seeing naughty content.";
                response += text;
            }

            bot.sendMessage(chatId, response);
        });

    });

    bot.on('message', (msg) => {
        const chatId = msg.chat.id;
        var text = `I'm textually impaired. Just images please. \help for more on what I could do`;
        bot.sendMessage(chatId, text);
        // send a message to the chat acknowledging receipt of their message
    });
});
<commit_msg>Update app.js<commit_after>const TelegramBot = require('node-telegram-bot-api');
var gcloud = require('google-cloud');
var vision = gcloud.vision;

const token = 'API TOKEN';
const bot = new TelegramBot(token, {polling: true});

var vision = vision({
    projectId: 'telegram-160918',
    keyFilename: './path/to/api/key'
});

bot.onText(/\/help/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;

  var text = `Do you ever look at porn and wonder if what you're looking at is actually porn? Watson is here to help. Watson is an artificially intelligent sentient with vision capabilities. It can detect sentiment in faces, discern landmarks, logos, extract text from images, and more. Send Watson a pic and give it a try`;
  bot.sendMessage(chatId, text);
});

bot.on('photo', function(msg) {
    const chatId = msg.chat.id;
    bot.sendMessage(chatId, 'Hmm let\'s see..');
    var photoId = msg.photo[msg.photo.length-1].file_id;
    var path = bot.downloadFile(photoId, "./public/img").then(function (path) {
        var types = [
            'face',
            'label',
            'landmark',
            'logo',
            'text',
            'safeSearch'
        ];

        vision.detect(path, types, function(err, detections, apiResponse) {

  // detections = [
  //   // Detections for image.jpg:
  //   {
  //     faces: [...],
  //     labels: [...],
  //     landmarks: [...],
  //     logos: [...],
  //     text: [...],
  //     safeSearch: {...},
  //   },
  // ]

  // faces = [
  //   {
  //     angles: {
  //       pan: -8.1090336,
  //       roll: -5.0002542,
  //       tilt: 18.012161
  //     },
  //     bounds: {
  //       head: [
  //         {
  //           x: 1
  //         },
  //         {
  //           x: 295
  //         },
  //         {
  //           x: 295,
  //           y: 301
  //         },
  //         {
  //           x: 1,
  //           y: 301
  //         }
  //       ],
  //       face: [
  //         {
  //           x: 28,
  //           y: 40
  //         },
  //         {
  //           x: 250,
  //           y: 40
  //         },
  //         {
  //           x: 250,
  //           y: 262
  //         },
  //         {
  //           x: 28,
  //           y: 262
  //         }
  //       ]
  //     },
  //     features: {
  //       confidence: 34.489909,
  //       chin: {
  //         center: {
  //           x: 143.34183,
  //           y: 262.22998,
  //           z: -57.388493
  //         },
  //         left: {
  //           x: 63.102425,
  //           y: 248.99081,
  //           z: 44.207638
  //         },
  //         right: {
  //           x: 241.72728,
  //           y: 225.53488,
  //           z: 19.758242
  //         }
  //       },
  //       ears: {
  //         left: {
  //           x: 54.872219,
  //           y: 207.23712,
  //           z: 97.030685
  //         },
  //         right: {
  //           x: 252.67567,
  //           y: 180.43124,
  //           z: 70.15992
  //         }
  //       },
  //       eyebrows: {
  //         left: {
  //           left: {
  //             x: 58.790176,
  //             y: 113.28249,
  //             z: 17.89735
  //           },
  //           right: {
  //             x: 106.14151,
  //             y: 98.593758,
  //             z: -13.116687
  //           },
  //           top: {
  //             x: 80.248711,
  //             y: 94.04303,
  //             z: 0.21131183
  //           }
  //         },
  //         right: {
  //           left: {
  //             x: 148.61565,
  //             y: 92.294594,
  //             z: -18.804882
  //           },
  //           right: {
  //             x: 204.40808,
  //             y: 94.300117,
  //             z: -2.0009689
  //           },
  //           top: {
  //             x: 174.70135,
  //             y: 81.580917,
  //             z: -12.702137
  //           }
  //         }
  //       },
  //       eyes: {
  //         left: {
  //           bottom: {
  //             x: 84.883934,
  //             y: 134.59479,
  //             z: -2.8677137
  //           },
  //           center: {
  //             x: 83.707092,
  //             y: 128.34,
  //             z: -0.00013388535
  //           },
  //           left: {
  //             x: 72.213913,
  //             y: 132.04138,
  //             z: 9.6985674
  //           },
  //           pupil: {
  //             x: 86.531624,
  //             y: 126.49807,
  //             z: -2.2496929
  //           },
  //           right: {
  //             x: 105.28892,
  //             y: 125.57655,
  //             z: -2.51554
  //           },
  //           top: {
  //             x: 86.706947,
  //             y: 119.47144,
  //             z: -4.1606765
  //           }
  //         },
  //         right: {
  //           bottom: {
  //             x: 179.30353,
  //             y: 121.03307,
  //             z: -14.843414
  //           },
  //           center: {
  //             x: 181.17694,
  //             y: 115.16437,
  //             z: -12.82961
  //           },
  //           left: {
  //             x: 158.2863,
  //             y: 118.491,
  //             z: -9.723031
  //           },
  //           pupil: {
  //             x: 175.99976,
  //             y: 114.64407,
  //             z: -14.53744
  //           },
  //           right: {
  //             x: 194.59413,
  //             y: 115.91954,
  //             z: -6.952745
  //           },
  //           top: {
  //             x: 173.99446,
  //             y: 107.94287,
  //             z: -16.050705
  //           }
  //         }
  //       },
  //       forehead: {
  //         x: 126.53813,
  //         y: 93.812057,
  //         z: -18.863352
  //       },
  //       lips: {
  //         bottom: {
  //           x: 137.28528,
  //           y: 219.23564,
  //           z: -56.663128
  //         },
  //         top: {
  //           x: 134.74164,
  //           y: 192.50438,
  //           z: -53.876408
  //         }
  //       },
  //       mouth: {
  //         center: {
  //           x: 136.43481,
  //           y: 204.37952,
  //           z: -51.620205
  //         },
  //         left: {
  //           x: 104.53558,
  //           y: 214.05037,
  //           z: -30.056231
  //         },
  //         right: {
  //           x: 173.79134,
  //           y: 204.99333,
  //           z: -39.725758
  //         }
  //       },
  //       nose: {
  //         bottom: {
  //           center: {
  //             x: 133.81947,
  //             y: 173.16437,
  //             z: -48.287724
  //           },
  //           left: {
  //             x: 110.98372,
  //             y: 173.61331,
  //             z: -29.7784
  //           },
  //           right: {
  //             x: 161.31354,
  //             y: 168.24527,
  //             z: -36.1628
  //           }
  //         },
  //         tip: {
  //           x: 128.14919,
  //           y: 153.68129,
  //           z: -63.198204
  //         },
  //         top: {
  //           x: 127.83745,
  //           y: 110.17557,
  //           z: -22.650913
  //         }
  //       }
  //     },
  //     confidence: 56.748849,
  //     anger: false,
  //     blurred: false,
  //     headwear: false,
  //     joy: false,
  //     sorrow: false,
  //     surprise: false,
  //     underExposed: false
  //   }
  // ]

  // labels = [
  //   'classical sculpture',
  //   'statue',
  //   'landmark',
  //   'ancient history',
  //   'artwork'
  // ]

  // landmarks = [
  //   {
  //     desc: 'Mount Rushmore',
  //     id: '/m/019dvv',
  //     score: 28.651705,
  //     bounds: [
  //       {
  //         x: 79,
  //         y: 130
  //       },
  //       {
  //         x: 284,
  //         y: 130
  //       },
  //       {
  //         x: 284,
  //         y: 226
  //       },
  //       {
  //         x: 79,
  //         y: 226
  //       }
  //     ],
  //     locations: [
  //       {
  //         latitude: 43.878264,
  //         longitude: -103.45700740814209
  //       }
  //     ]
  //   }
  // ]

  // logos = [
  //   {
  //     desc: 'Google',
  //     id: '/m/045c7b',
  //     score: 64.35439,
  //     bounds: [
  //       {
  //         x: 11,
  //         y: 11
  //       },
  //       {
  //         x: 330,
  //         y: 11
  //       },
  //       {
  //         x: 330,
  //         y: 72
  //       },
  //       {
  //         x: 11,
  //         y: 72
  //       }
  //     ]
  //   }
  // ]

  // safeSearch = {
  //   adult: false,
  //   medical: false,
  //   spoof: false,
  //   violence: true
  // }

            var response = '';

            if(detections['faces']) {
                if(detections['faces'].length > 0) {
                var faceSentiment = 'I\'m seeing a face. ';

                if(detections['faces'][0]['joy']) {
                    faceSentiment += 'Looks very happy :)';
                }

                if(detections['faces'][0]['sorrow']) {
                    faceSentiment += 'Face full of sorrow :(';
                }

                if(detections['faces'][0]['anger']) {
                    faceSentiment += 'Looks angry';
                }

                if(detections['faces'][0]['surprise']) {
                    faceSentiment += 'Looks surprised';
                }

                response += faceSentiment += '/n';
                }
            }

            if(detections['labels']) {
                    if(detections['labels'].length > 0) {
                        var chosenValue = Math.random() < 0.5 ? 1 : 2;
                        if(chosenValue === 1) {
                            var text = "Getting a " + detections['labels'][0] + " or " + detections['labels'][1] + " vibe. \n";
                            response += text;
                        } else {
                            var text = "Looks like a " + detections['labels'][0] + " or " + detections['labels'][1] + ". \n";
                            response += text;
                        }

                    }
            }

            if(detections['landmarks']) {
                if(detections['landmarks'].length > 0) {
                    var landmark = '\nI\ think i\'m seeing ' + detections['landmarks'][0] + '\n';
                    response += landmark;
                }
            }

            if(detections['logos']) {
                if(detections['logos'].length > 0) {
                    var logo = "I think that's the logo of " + detections['logos'];
                    response += logo;
                }
            }

            if(detections['text']) {
                if(detections['text'].length > 0) {
                    var text = "\nI'm seeing ";
                    text += " some text in the image. It says\n\n";
                    text += "\"\n";
                    text +=  detections['text'][0];
                    text += "\"";

                    response += text;
                }
            }

            if(detections['safeSearch']['adult']) {
                var text = "GULP. I'm seeing naughty content.";
                response += text;
            }

            bot.sendMessage(chatId, response);
        });

    });

    bot.on('message', (msg) => {
        const chatId = msg.chat.id;
        var text = `I'm textually impaired. Just images please. /help for more on what I could do`;
        bot.sendMessage(chatId, text);
        // send a message to the chat acknowledging receipt of their message
    });
});
<|endoftext|>


<commit_before>app.factory('socket', function ($rootScope) {
  var socket = io.connect('localhost:' + (process.env.PORT || '5050'), {reconnect: true});
  return {
      joinRoom: function(roomName, playerName, isObserver) {
        socket.emit('joinRoom', roomName, playerName, isObserver);
      },
      leaveRoom: function() {
        socket.emit('leaveRoom');
      },
      updateRoom: function(callback) {
          socket.on('updateRoom', callback);
      },
      updateRoomList: function(callback) {
          socket.on('updateRoomList', callback);
      },
      getActiveRooms: function(roomList) {
          socket.emit('getActiveRooms', roomList);
      },
      setEstimate: function(value) {
        socket.emit('setEstimate', value);
      },
      toggleCards: function() {
        socket.emit('toggleCards');
      },
      resetHistory: function() {
        socket.emit('resetHistory');
      },
      setNextStory: function(nextStory) {
        socket.emit('nextStory', nextStory);
      },
      getSocketId: function() {
        return socket.id;
      }

  };
});<commit_msg>More port nonsense<commit_after>app.factory('socket', function ($rootScope) {
  var socket = io.connect('localhost'), {reconnect: true});
  return {
      joinRoom: function(roomName, playerName, isObserver) {
        socket.emit('joinRoom', roomName, playerName, isObserver);
      },
      leaveRoom: function() {
        socket.emit('leaveRoom');
      },
      updateRoom: function(callback) {
          socket.on('updateRoom', callback);
      },
      updateRoomList: function(callback) {
          socket.on('updateRoomList', callback);
      },
      getActiveRooms: function(roomList) {
          socket.emit('getActiveRooms', roomList);
      },
      setEstimate: function(value) {
        socket.emit('setEstimate', value);
      },
      toggleCards: function() {
        socket.emit('toggleCards');
      },
      resetHistory: function() {
        socket.emit('resetHistory');
      },
      setNextStory: function(nextStory) {
        socket.emit('nextStory', nextStory);
      },
      getSocketId: function() {
        return socket.id;
      }

  };
});<|endoftext|>


<commit_before>/* D3 function for drawing temperatures and rain bars in same svg */
var temprain = function(el, json, attr, xformat, yaxisleg, width, height) {
    var margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = width - margin.left - margin.right,
        height = height - margin.top - margin.bottom;

    var svg = d3.select(el).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    addGradient(svg, width, height);

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .tickFormat(xformat)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    x.domain(d3.extent(json, function(d) { return d.date; }));
    y.domain([d3.min(json, function(d) { return d.tempmin }), d3.max(json, function(d) { return d.tempmax; })]);

    // Y Axis grid
    var yrule = svg.selectAll("g.y")
        .data(y.ticks(10))
        .enter().append("g")
        .attr("class", "y axis")
      .append("svg:line")
        .attr("class", "yLine")
        .attr("x1", 0)
        .attr("x2", width)
        .attr("y1", y)
        .attr("y2", y)
        .attr("stroke-dasharray", "5,5")
        .style('stroke', function(d, i) {
            if(d == 0) {
                return 'steelblue';
            }
            return '#eee';
        })
        .style("shape-rendering", "crispEdges")
        ;

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    // Y Axis legend
    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text(yaxisleg);

    // Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.temp); })
        .interpolate("basis")

    var pathos = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke", "red")
      .attr("d", line)
    // Low Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.tempmin); })
        .interpolate("basis")
    var pathoslow = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke-dasharray", "5,5")
      .attr("stroke", "steelblue")
      .attr("d", line)
    // High Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.tempmax); })
        .interpolate("basis")
    var pathoslow = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke-dasharray", "5,5")
      .attr("stroke", "darkred")
      .attr("d", line)

    /* Pressure section */

    x.domain(d3.extent(json, function(d) { return d.date; }));
    var y = d3.scale.linear()
        .range([height, 0]);
    //y.domain(d3.extent(json, function(d) { return d.barometer; }));
    // hard coded minmax
    y.domain([950, 1050]);
    // Pressure line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.barometer); })
        .interpolate("basis")

    // Pressure path
    var pathospressure = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke", "darkgreen")
      .attr("stroke-opacity", "0.2")
      .attr("d", line)

    /* Rain bar section */

    var x = d3.time.scale()
        .range([0, 1]);

    var y = d3.scale.linear()
        .range([height, 0]);

    x.domain(json.map(function(d) { return d.date; }));
    y.domain([0, d3.max(json, function(d) { return d.daily_rain; })]);

    var barxpos = function(d) {
      var nr = x(d.date);
      var bwidth = (width/json.length)*0.8
      var barmargin = (width/json.length)*0.2
      var barx = width-bwidth;
      return  nr*bwidth + nr*barmargin;
    }

    svg.selectAll(".bar")
      .data(json)
    .enter().append("rect")
      .attr("class", "bar")
      .attr('rx', 3)
      .attr('ry', 3)
      .attr("x", barxpos )
      .attr("width", (width/json.length)*0.8)
      .attr("y", function(d) { return height; })
      .attr("height", function(d) { return 0; })
      .on("mouseover", function(d,i){
          d3.select(this)
          .attr("stroke-width", "3px");

      var x; var y;
      if (d3.event.pageX != undefined && d3.event.pageY != undefined) {
          x = d3.event.pageX;
          y = d3.event.pageY;
      } else {
          x = d3.event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = d3.event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
      }

      var bubble_code = "
Date: "
          + d.timestamp + "
  Rain: " + Number(d.daily_rain).toFixed(1) + " mm
"
          + "
";
      $("body").append(bubble_code);

      }).on("mouseout", function(d,i){
          d3.select(this)
          .attr("stroke-width", "1px");
      $("#tt").remove();
      })

      .transition().delay(function (d,i){ return 300;})
      .duration(150)
      .attr("y", function(d) { return y(d.daily_rain); })
      .attr("height", function(d) { return height - y(d.daily_rain); })

      ;

    var valfmt = function(d) {
        var nr = d.daily_rain;
        if (nr == 0) return '';
        if (nr < 1 )
            return Number(nr).toFixed(1);
        return parseInt(nr);
    }
    svg.selectAll("text.score")
        .data(json)
        .enter().append("text")
        .attr("x", barxpos)
        .attr("y", function(d){ return y(d.daily_rain) + 10 } )
        .attr("dx", (width/json.length)*0.4)
        .attr("dy", (width/json.length)*0.4)
        .attr("text-anchor", "middle")
        .attr('class', 'score')
        .style('font-size', function(d) {
            // Compute proper font size
            w = (width/json.length)*0.6;
            return w + 'px' })
        .text(valfmt)

  var focus = svg.append("g")
      .attr("class", "focus");

  focus.append("line")
      .attr("class", "x")
      .attr("y1", y(0) - 6)
      .attr("y2", y(0) + 6);

  focus.append("line")
      .attr("class", "y")
      .attr("x1", width - 6)
      .attr("x2", width + 6);

  focus.append("circle")
      .attr("r", 3.5);

  /*
  svg.append("rect")
      .attr("class", "overlay")
      .attr("width", width)
      .attr("height", height)
      .on("mousemove", mousemove);

  function mousemove() {
    var d = json[Math.round((x.invert(d3.mouse(this)[0]) - json[0].date) / 60*60*24)];
    focus.select("circle").attr("transform", "translate(" + x(d[0]) + "," + y(d[1]) + ")");
    focus.select(".x").attr("transform", "translate(" + x(d[0]) + ",0)");
    focus.select(".y").attr("transform", "translate(0," + y(d[1]) + ")");
    svg.selectAll(".x.axis path").style("fill-opacity", Math.random()); // XXX Chrome redraw bug
  }*/
}

var addGradient = function(target, w, h) {
    var gradient = target.append("svg:defs")
      .append("svg:linearGradient")
        .attr("id", "gradient")
        .attr("x1", "0%")
        .attr("y1", "0%")
        .attr("x2", "100%")
        .attr("y2", "100%")
        .attr("spreadMethod", "pad");

    gradient.append("svg:stop")
        .attr("offset", "0%")
        .attr("stop-color", "#fff")
        .attr("stop-opacity", 1);

    gradient.append("svg:stop")
        .attr("offset", "100%")
        .attr("stop-color", "#f2f2f2")
        .attr("stop-opacity", 1);

    target.append("svg:rect")
        .attr("width", w)
        .attr("height", h)
        .style("fill", "url(#gradient)");
}
<commit_msg>tune gradient<commit_after>/* D3 function for drawing temperatures and rain bars in same svg */
var temprain = function(el, json, attr, xformat, yaxisleg, width, height) {
    var margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = width - margin.left - margin.right,
        height = height - margin.top - margin.bottom;

    var svg = d3.select(el).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    addGradient(svg, width, height);

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .tickFormat(xformat)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    x.domain(d3.extent(json, function(d) { return d.date; }));
    y.domain([d3.min(json, function(d) { return d.tempmin }), d3.max(json, function(d) { return d.tempmax; })]);

    // Y Axis grid
    var yrule = svg.selectAll("g.y")
        .data(y.ticks(10))
        .enter().append("g")
        .attr("class", "y axis")
      .append("svg:line")
        .attr("class", "yLine")
        .attr("x1", 0)
        .attr("x2", width)
        .attr("y1", y)
        .attr("y2", y)
        .style('stroke', function(d, i) {
            if(d == 0) {
                return 'steelblue';
            }
            return '#ededed';
        })
        .style("shape-rendering", "crispEdges")
        ;

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    // Y Axis legend
    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text(yaxisleg);

    // Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.temp); })
        .interpolate("basis")

    var pathos = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke", "red")
      .attr("d", line)
    // Low Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.tempmin); })
        .interpolate("basis")
    var pathoslow = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke-dasharray", "5,5")
      .attr("stroke", "steelblue")
      .attr("d", line)
    // High Temp line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.tempmax); })
        .interpolate("basis")
    var pathoslow = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke-dasharray", "5,5")
      .attr("stroke", "darkred")
      .attr("d", line)

    /* Pressure section */

    x.domain(d3.extent(json, function(d) { return d.date; }));
    var y = d3.scale.linear()
        .range([height, 0]);
    //y.domain(d3.extent(json, function(d) { return d.barometer; }));
    // hard coded minmax
    y.domain([950, 1050]);
    // Pressure line
    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.barometer); })
        .interpolate("basis")

    // Pressure path
    var pathospressure = svg.append("path")
      .datum(json)
      .attr("class", "line")
      .attr("stroke", "darkgreen")
      .attr("stroke-opacity", "0.2")
      .attr("d", line)

    /* Rain bar section */

    var x = d3.time.scale()
        .range([0, 1]);

    var y = d3.scale.linear()
        .range([height, 0]);

    x.domain(json.map(function(d) { return d.date; }));
    y.domain([0, d3.max(json, function(d) { return d.daily_rain; })]);

    var barxpos = function(d) {
      var nr = x(d.date);
      var bwidth = (width/json.length)*0.8
      var barmargin = (width/json.length)*0.2
      var barx = width-bwidth;
      return  nr*bwidth + nr*barmargin;
    }

    svg.selectAll(".bar")
      .data(json)
    .enter().append("rect")
      .attr("class", "bar")
      .attr('rx', 3)
      .attr('ry', 3)
      .attr("x", barxpos )
      .attr("width", (width/json.length)*0.8)
      .attr("y", function(d) { return height; })
      .attr("height", function(d) { return 0; })
      .on("mouseover", function(d,i){
          d3.select(this)
          .attr("stroke-width", "3px");

      var x; var y;
      if (d3.event.pageX != undefined && d3.event.pageY != undefined) {
          x = d3.event.pageX;
          y = d3.event.pageY;
      } else {
          x = d3.event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = d3.event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
      }

      var bubble_code = "
Date: "
          + d.timestamp + "
  Rain: " + Number(d.daily_rain).toFixed(1) + " mm
"
          + "
";
      $("body").append(bubble_code);

      }).on("mouseout", function(d,i){
          d3.select(this)
          .attr("stroke-width", "1px");
      $("#tt").remove();
      })

      .transition().delay(function (d,i){ return 300;})
      .duration(150)
      .attr("y", function(d) { return y(d.daily_rain); })
      .attr("height", function(d) { return height - y(d.daily_rain); })

      ;

    var valfmt = function(d) {
        var nr = d.daily_rain;
        if (nr == 0) return '';
        if (nr < 1 )
            return Number(nr).toFixed(1);
        return parseInt(nr);
    }
    svg.selectAll("text.score")
        .data(json)
        .enter().append("text")
        .attr("x", barxpos)
        .attr("y", function(d){ return y(d.daily_rain) + 10 } )
        .attr("dx", (width/json.length)*0.4)
        .attr("dy", (width/json.length)*0.4)
        .attr("text-anchor", "middle")
        .attr('class', 'score')
        .style('font-size', function(d) {
            // Compute proper font size
            w = (width/json.length)*0.6;
            return w + 'px' })
        .text(valfmt)

  var focus = svg.append("g")
      .attr("class", "focus");

  focus.append("line")
      .attr("class", "x")
      .attr("y1", y(0) - 6)
      .attr("y2", y(0) + 6);

  focus.append("line")
      .attr("class", "y")
      .attr("x1", width - 6)
      .attr("x2", width + 6);

  focus.append("circle")
      .attr("r", 3.5);

  /*
  svg.append("rect")
      .attr("class", "overlay")
      .attr("width", width)
      .attr("height", height)
      .on("mousemove", mousemove);

  function mousemove() {
    var d = json[Math.round((x.invert(d3.mouse(this)[0]) - json[0].date) / 60*60*24)];
    focus.select("circle").attr("transform", "translate(" + x(d[0]) + "," + y(d[1]) + ")");
    focus.select(".x").attr("transform", "translate(" + x(d[0]) + ",0)");
    focus.select(".y").attr("transform", "translate(0," + y(d[1]) + ")");
    svg.selectAll(".x.axis path").style("fill-opacity", Math.random()); // XXX Chrome redraw bug
  }*/
}

var addGradient = function(target, w, h) {
    var gradient = target.append("svg:defs")
      .append("svg:linearGradient")
        .attr("id", "gradient")
        .attr("x1", "0%")
        .attr("y1", "0%")
        .attr("x2", "0%")
        .attr("y2", "100%")
        .attr("spreadMethod", "pad");

    gradient.append("svg:stop")
        .attr("offset", "0%")
        .attr("stop-color", "#fff")
        .attr("stop-opacity", 1);

    gradient.append("svg:stop")
        .attr("offset", "100%")
        .attr("stop-color", "#f2f2f2")
        .attr("stop-opacity", 1);

    target.append("svg:rect")
        .attr("width", w)
        .attr("height", h)
        .style("fill", "url(#gradient)");
}
<|endoftext|>