<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

let map;
/** Editable marker that displays when a user clicks in the map */
let editMarker;
let userLocation;
let markers = [];
let fetchedMarkers = [];
let markerLat;
let markerLng;
let reportsForMarkers = [];

/** Creates a map and adds it to the page. */
function createMap(){
    map = new google.maps.Map(document.getElementById('map'), {
        center: getUserLocation(),
        zoom:15});

    /** When the user clicks on the map, show a marker with a form the user can edit. */
    map.addListener('click', (event) => {
        markerLat = event.latLng.lat();
        markerLng = event.latLng.lng();
        createMarkerForEdit(event.latLng.lat(), event.latLng.lng());
    });

    var controlDiv = document.getElementById('floating-panel');
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
    fetchMarkers();
}

/** Fetches markers from the backend and adds them to the map. */
function fetchMarkers(){
    fetch('/markers').then(response => response.json()).then((markers) => {
        markers.forEach((marker) => {
            createMarkerForDisplay(marker.lat, marker.lng, marker.crimeType, marker.date, marker.time, marker.description);
        });
    });
}

/** Creates a marker that shows a read-only info window when clicked. */
function createMarkerForDisplay(lat, lng, crimeType, date, time, address, description){
    const marker = new google.maps.Marker({position: {lat: lat, lng: lng, map: map}});

    var infoWindow = new google.maps.InfoWindow({content: crimeType, date, time, address, description});

    marker.addListener('click', () => {
        infoWindow.open(map, marker);
    });
}

/** Sends a marker to the backend for saving. */
function postMarker(lat, lng, type, date, time, address, description){
    const params = new URLSearchParams();

    params.append('lat', lat);
    params.append('lng', lng);
    params.append('crimeType', type);
    params.append('date', date);
    params.append('time', time);
    params.append('address', address);
    params.append('description', description);

    fetch('/markers', {method: 'POST', body: params})
    .catch((error) => {
        console.error(error);
    });
}

/** Creates a marker that shows a textbox the user can edit. */
function createMarkerForEdit(lat, lng){
    /** If we are already showing an editable marker, then remove it. */
    if(editMarker){
        editMarker.setMap(null);
    }

    editMarker = new google.maps.Marker({position: {lat: lat, lng: lng}, map: map});

    let infoWindow = new google.maps.InfoWindow({content: buildInfoWindow(lat, lng)});

    /** When the user closes the editable info window, remove the marker. */
    google.maps.event.addListener(infoWindow, 'closeclick', () => {
        editMarker.setMap(null);
    });

    infoWindow.open(map, editMarker);
}

/** Builds and returns HTML elements that show an editable textbox and submit button. */
function buildInfoWindow(lat,lng){
    const clone = document.getElementById('reportsForm').cloneNode(true);
    clone.id = "";
    clone.style.display = 'block';
    return clone;
}

function submitFormData(element){
    postMarker(markerLat, markerLng, getRadioValueCrimes(element), document.getElementById('date').value, document.getElementById('time').value, document.getElementById('address').value, document.getElementById('description').value);
    createMarkerForDisplay(markerLat, markerLng, getRadioValueCrimes(), document.getElementById('date').value, document.getElementById('time').value, document.getElementById('address').value, document.getElementById('description').value);
    editMarker.setMap(null);
}

/** Looks for the value checked in the type of crime report's section. */
function getRadioValueCrimes(){
    if(document.getElementById('homicide').checked) {
        return document.getElementById('homicide').value;
    }else if(document.getElementById('sexualAssault').checked) {
        return document.getElementById('sexualAssault').value;
    }else if(document.getElementById('robbery').checked) {
        return document.getElementById('robbery').value;
    }else if(document.getElementById('harassment').checked) {
        return document.getElementById('harassment').value;
    }else if(document.getElementById('kidnapping').checked) {
        return document.getElementById('kidnapping').value;
    }else if(document.getElementById('drugs').checked) {
        return document.getElementById('drugs').value;
    }else{
        return document.getElementById('other').value;
    }
}

/**
Puts a marker on the user's location
 */
function getUserLocation() {
    var infoWindow = new google.maps.InfoWindow;
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
        userLocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        var marker = new google.maps.Marker({
            position: userLocation,
            map: map,
            title: 'User location'
        });
        marker.setMap(map);
        map.setCenter(userLocation);
        },
        function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
          // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
    return userLocation;
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    infoWindow.open(map);
}

/**
Show/Hide Heatmap
 */
var heatmap;
function initHeatMap() {
    heatmap = new google.maps.visualization.HeatmapLayer({
    data: getPoints(),
    map: map
    });
}

function toggleHeatmap() {
    heatmap.setMap(heatmap.getMap() ? null : map);
}

function getPoints() {
    var heatPoints = [];
    var individualPoint;
        fetch('/markers').then(response => response.json()).then((markers) => {
        markers.forEach((marker) => {
            individualPoint = new google.maps.LatLng(marker.lat, marker.lng);
            heatPoints.push(individualPoint);
        });
    });
    return heatPoints;
}

var reportsSideBar = document.getElementById("sideBar");

var filters = document.getElementById("filters");

var span = document.getElementsByClassName("close")[0];

var apply = document.getElementById("apply");

// When the user clicks the button, open the modal
filters.onclick = function() {
  reportsSideBar.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  reportsSideBar.style.display = "none";
}

apply.onclick = function(){
  reportsSideBar.style.display = "none";
}

/**
Hide and show markers of reports
 */
function showMarkers(){
   // Shows any markers currently in the array.
    fetchReportMarkers();
}

function hideMarkers(){
    //Hides any markers currently in the array.
  for (var i = 0; i < fetchedMarkers.length; i++) {
      fetchedMarkers[i].setMap(null);
  }
}

function fetchReportMarkers(){
    var markerReport;
    fetch('/markers').then(response => response.json()).then((markers) => {
        markers.forEach((marker) => {
            markerReport =new google.maps.Marker({
            position: new google.maps.LatLng(marker.lat, marker.lng),
            map: map
            });
            fetchedMarkers.push(markerReport);
            reportsForMarkers.push(marker);
            markerReport.setMap(map);
        });
    });
}

function route() {
    console.log("HEYYYYYY");
    let directionsService = new google.maps.DirectionsService();
    let directionsDisplay = new google.maps.DirectionsRenderer();
    let request = {
        origin: new google.maps.LatLng(31.742485, -106.485468),
        destination: new google.maps.LatLng(31.774414, -106.501199),
        provideRouteAlternatives: true,
        travelMode: 'DRIVING'
    }

    let markerTry = new google.maps.LatLng({lat: 31.761679, lng: -106.491667});

    directionsDisplay.setMap(map);
    directionsService.route(request, function(result, status) {
        if (status === 'OK') {
            console.log(result.routes.length);

            /*for (var i =0; i < result.routes.length; i++) {
                new google.maps.DirectionsRenderer({
                map: map,
                directions: result,
                routeIndex: i
                });
            }*/

            var counter = 0;

            /*console.log(route.legs[0].steps.length);
            console.log("Here we go again");
            console.log(route.legs[0].steps[0].start_location.lat());
            console.log(route.legs[0].steps[0].start_location.lng());
            console.log(route.legs[0].steps[0].end_location.lat());
            console.log(route.legs[0].steps[0].end_location.lng());
            console.log(route.legs[0].steps[0].distance);*/
            /*superMath(route.legs[0].steps[0].start_location, markerTry ,route.legs[0].steps[0].end_location);*/

            var routeIndex = 0;
            var lessCrimesInRoute = 1000;

        for (var r=0; r < result.routes.length; r++){
            var route = result.routes[r];

            for (var j=0; j < route.legs[0].steps.length; j++){
                var routeArray = new google.maps.Polyline({
                path: [
                    new google.maps.LatLng(route.legs[0].steps[j].start_location.lat(), route.legs[0].steps[j].start_location.lng()),
                    new google.maps.LatLng(route.legs[0].steps[j].end_location.lat(), route.legs[0].steps[j].end_location.lng())
                ]
                });
                for (var l=0; l < markers.length; l++){
                    var myPosition = new google.maps.LatLng(markers[l].getPosition().lat(), markers[l].getPosition().lng());

                    if (google.maps.geometry.poly.isLocationOnEdge(myPosition, routeArray, 0.0005)) {

                        console.log("Relocate!");
                        console.log(l);
                        console.log(route.legs[0].steps[j].end_location.lat());
                        console.log(route.legs[0].steps[j].end_location.lng());
                        counter++;
                    }
                }
            }

            if (counter < lessCrimesInRoute) {
                lessCrimesInRoute = counter;
                routeIndex = r;
                console.log(r);
            }
            counter = 0;
        }

        console.log(routeIndex);

                new google.maps.DirectionsRenderer({
                map: map,
                directions: result,
                routeIndex: routeIndex
                });
        }
    });
    console.log("2222222");
}

function superMath(point1, point2, point3) {
    console.log(point1.lat());
    console.log(point1.lng());
    console.log(point2.lat());
    console.log(point2.lng());
    console.log(point3.lat());
    console.log(point3.lng());

    var a = (point1.lat() - point3.lat()) * (point1.lat() - point3.lat());

    var b = (point1.lng() - point3.lng()) * (point1.lng() - point3.lng());

    var c = Math.sqrt(a+b);

    console.log(c);
}
<commit_msg>Add error handling for fetch function<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

let map;
/** Editable marker that displays when a user clicks in the map */
let editMarker;
let userLocation;
let markers = [];
let fetchedMarkers = [];
let markerLat;
let markerLng;
let reportsForMarkers = [];

/** Creates a map and adds it to the page. */
function createMap(){
    map = new google.maps.Map(document.getElementById('map'), {
        center: getUserLocation(),
        zoom:15});

    /** When the user clicks on the map, show a marker with a form the user can edit. */
    map.addListener('click', (event) => {
        markerLat = event.latLng.lat();
        markerLng = event.latLng.lng();
        createMarkerForEdit(event.latLng.lat(), event.latLng.lng());
    });

    var controlDiv = document.getElementById('floating-panel');
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
    fetchMarkers();
}

/** Fetches markers from the backend and adds them to the map. */
function fetchMarkers(){
    fetch('/markers').then(response => response.json()).then((markers) => {
        markers.forEach((marker) => {
            createMarkerForDisplay(marker.lat, marker.lng, marker.crimeType, marker.date, marker.time, marker.description);
        });
    });
}

/** Creates a marker that shows a read-only info window when clicked. */
function createMarkerForDisplay(lat, lng, crimeType, date, time, address, description){
    const marker = new google.maps.Marker({position: {lat: lat, lng: lng, map: map}});

    var infoWindow = new google.maps.InfoWindow({content: crimeType, date, time, address, description});

    marker.addListener('click', () => {
        infoWindow.open(map, marker);
    });
}

/** Sends a marker to the backend for saving. */
function postMarker(lat, lng, type, date, time, address, description){
    const params = new URLSearchParams();

    params.append('lat', lat);
    params.append('lng', lng);
    params.append('crimeType', type);
    params.append('date', date);
    params.append('time', time);
    params.append('address', address);
    params.append('description', description);

    fetch('/markers', {method: 'POST', body: params})
    .catch((error) => {
        console.error(error);
    });
}

/** Creates a marker that shows a textbox the user can edit. */
function createMarkerForEdit(lat, lng){
    /** If we are already showing an editable marker, then remove it. */
    if(editMarker){
        editMarker.setMap(null);
    }

    editMarker = new google.maps.Marker({position: {lat: lat, lng: lng}, map: map});

    let infoWindow = new google.maps.InfoWindow({content: buildInfoWindow(lat, lng)});

    /** When the user closes the editable info window, remove the marker. */
    google.maps.event.addListener(infoWindow, 'closeclick', () => {
        editMarker.setMap(null);
    });

    infoWindow.open(map, editMarker);
}

/** Builds and returns HTML elements that show an editable textbox and submit button. */
function buildInfoWindow(lat,lng){
    const clone = document.getElementById('reportsForm').cloneNode(true);
    clone.id = "";
    clone.style.display = 'block';
    return clone;
}

function submitFormData(element){
    postMarker(markerLat, markerLng, getRadioValueCrimes(element), document.getElementById('date').value, document.getElementById('time').value, document.getElementById('address').value, document.getElementById('description').value);
    createMarkerForDisplay(markerLat, markerLng, getRadioValueCrimes(), document.getElementById('date').value, document.getElementById('time').value, document.getElementById('address').value, document.getElementById('description').value);
    editMarker.setMap(null);
}

/** Looks for the value checked in the type of crime report's section. */
function getRadioValueCrimes(){
    if(document.getElementById('homicide').checked) {
        return document.getElementById('homicide').value;
    }else if(document.getElementById('sexualAssault').checked) {
        return document.getElementById('sexualAssault').value;
    }else if(document.getElementById('robbery').checked) {
        return document.getElementById('robbery').value;
    }else if(document.getElementById('harassment').checked) {
        return document.getElementById('harassment').value;
    }else if(document.getElementById('kidnapping').checked) {
        return document.getElementById('kidnapping').value;
    }else if(document.getElementById('drugs').checked) {
        return document.getElementById('drugs').value;
    }else{
        return document.getElementById('other').value;
    }
}

/**
Puts a marker on the user's location
 */
function getUserLocation() {
    var infoWindow = new google.maps.InfoWindow;
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
        userLocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        var marker = new google.maps.Marker({
            position: userLocation,
            map: map,
            title: 'User location'
        });
        marker.setMap(map);
        map.setCenter(userLocation);
        },
        function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
          // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
    return userLocation;
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    infoWindow.open(map);
}

/**
Show/Hide Heatmap
 */
var heatmap;
function initHeatMap() {
    heatmap = new google.maps.visualization.HeatmapLayer({
    data: getPoints(),
    map: map
    });
}

function toggleHeatmap() {
    heatmap.setMap(heatmap.getMap() ? null : map);
}

function getPoints() {
    var heatPoints = [];
    var individualPoint;
        fetch('/markers')
        .then(response => response.json())
        .then((markers) => {
        markers.forEach((marker) => {
            individualPoint = new google.maps.LatLng(marker.lat, marker.lng);
            heatPoints.push(individualPoint);
        });
    })
    .catch((error) => {
        console.error(error);
    });
    return heatPoints;
}

var reportsSideBar = document.getElementById("sideBar");

var filters = document.getElementById("filters");

var span = document.getElementsByClassName("close")[0];

var apply = document.getElementById("apply");

// When the user clicks the button, open the modal
filters.onclick = function() {
  reportsSideBar.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  reportsSideBar.style.display = "none";
}

apply.onclick = function(){
  reportsSideBar.style.display = "none";
}

/**
Hide and show markers of reports
 */
function showMarkers(){
   // Shows any markers currently in the array.
    fetchReportMarkers();
}

function hideMarkers(){
    //Hides any markers currently in the array.
  for (var i = 0; i < fetchedMarkers.length; i++) {
      fetchedMarkers[i].setMap(null);
  }
}

function fetchReportMarkers(){
    var markerReport;
    fetch('/markers').then(response => response.json()).then((markers) => {
        markers.forEach((marker) => {
            markerReport =new google.maps.Marker({
            position: new google.maps.LatLng(marker.lat, marker.lng),
            map: map
            });
            fetchedMarkers.push(markerReport);
            reportsForMarkers.push(marker);
            markerReport.setMap(map);
        });
    })
    .catch((error) => {
        console.error(error);
    });
}

function route() {
    console.log("HEYYYYYY");
    let directionsService = new google.maps.DirectionsService();
    let directionsDisplay = new google.maps.DirectionsRenderer();
    let request = {
        origin: new google.maps.LatLng(31.742485, -106.485468),
        destination: new google.maps.LatLng(31.774414, -106.501199),
        provideRouteAlternatives: true,
        travelMode: 'DRIVING'
    }

    let markerTry = new google.maps.LatLng({lat: 31.761679, lng: -106.491667});

    directionsDisplay.setMap(map);
    directionsService.route(request, function(result, status) {
        if (status === 'OK') {
            console.log(result.routes.length);

            /*for (var i =0; i < result.routes.length; i++) {
                new google.maps.DirectionsRenderer({
                map: map,
                directions: result,
                routeIndex: i
                });
            }*/

            var counter = 0;

            /*console.log(route.legs[0].steps.length);
            console.log("Here we go again");
            console.log(route.legs[0].steps[0].start_location.lat());
            console.log(route.legs[0].steps[0].start_location.lng());
            console.log(route.legs[0].steps[0].end_location.lat());
            console.log(route.legs[0].steps[0].end_location.lng());
            console.log(route.legs[0].steps[0].distance);*/
            /*superMath(route.legs[0].steps[0].start_location, markerTry ,route.legs[0].steps[0].end_location);*/

            var routeIndex = 0;
            var lessCrimesInRoute = 1000;

        for (var r=0; r < result.routes.length; r++){
            var route = result.routes[r];

            for (var j=0; j < route.legs[0].steps.length; j++){
                var routeArray = new google.maps.Polyline({
                path: [
                    new google.maps.LatLng(route.legs[0].steps[j].start_location.lat(), route.legs[0].steps[j].start_location.lng()),
                    new google.maps.LatLng(route.legs[0].steps[j].end_location.lat(), route.legs[0].steps[j].end_location.lng())
                ]
                });
                for (var l=0; l < markers.length; l++){
                    var myPosition = new google.maps.LatLng(markers[l].getPosition().lat(), markers[l].getPosition().lng());

                    if (google.maps.geometry.poly.isLocationOnEdge(myPosition, routeArray, 0.0005)) {

                        console.log("Relocate!");
                        console.log(l);
                        console.log(route.legs[0].steps[j].end_location.lat());
                        console.log(route.legs[0].steps[j].end_location.lng());
                        counter++;
                    }
                }
            }

            if (counter < lessCrimesInRoute) {
                lessCrimesInRoute = counter;
                routeIndex = r;
                console.log(r);
            }
            counter = 0;
        }

        console.log(routeIndex);

                new google.maps.DirectionsRenderer({
                map: map,
                directions: result,
                routeIndex: routeIndex
                });
        }
    });
    console.log("2222222");
}

function superMath(point1, point2, point3) {
    console.log(point1.lat());
    console.log(point1.lng());
    console.log(point2.lat());
    console.log(point2.lng());
    console.log(point3.lat());
    console.log(point3.lng());

    var a = (point1.lat() - point3.lat()) * (point1.lat() - point3.lat());

    var b = (point1.lng() - point3.lng()) * (point1.lng() - point3.lng());

    var c = Math.sqrt(a+b);

    console.log(c);
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var extend         = require('extend');
var requestFactory = require('../../lib/requestwrapper');

/**
 *
 * @param options
 * @constructor
 */
function Conversation(options) {

  // Check if 'version_date' was provided
  if (typeof options.version_date === 'undefined') {
    throw new Error('Argument error: version_date was not specified, use 2016-01-24');
  }

  // Default URL
  var serviceDefaults = {
    url: 'https://gateway.watsonplatform.net/conversation-experimental/api',
    qs: {
      version: options.version_date
    }
  };

  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

Conversation.prototype.workspaces = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/',
      method: 'GET',
      json: true,
      qs: pick(params, ['export'])
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.createWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/',
      method: 'POST',
      json: true,
      body: pick(params, ['name', 'description', 'language', 'metadata'])
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.deleteWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'DELETE',
      json: true,
      path: params
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.getWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'GET',
      json: true,
      path: params,
      qs: pick(params, ['export'])
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.updateWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'POST',
      json: true,
      body: pick(params, ['name', 'description', 'language', 'metadata']),
      path: params
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.message;

module.exports = Dialog;
<commit_msg>add message method<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var extend         = require('extend');
var requestFactory = require('../../lib/requestwrapper');

/**
 *
 * @param options
 * @constructor
 */
function Conversation(options) {

  // Check if 'version_date' was provided
  if (typeof options.version_date === 'undefined') {
    throw new Error('Argument error: version_date was not specified, use 2016-01-24');
  }

  // Default URL
  var serviceDefaults = {
    url: 'https://gateway.watsonplatform.net/conversation-experimental/api',
    qs: {
      version: options.version_date
    }
  };

  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

Conversation.prototype.workspaces = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/',
      method: 'GET',
      json: true,
      qs: pick(params, ['export'])
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.createWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/',
      method: 'POST',
      json: true,
      body: pick(params, ['name', 'description', 'language', 'metadata'])
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.deleteWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'DELETE',
      json: true,
      path: params
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.getWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'GET',
      json: true,
      path: params,
      qs: pick(params, ['export'])
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.updateWorkspace = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}',
      method: 'POST',
      json: true,
      body: pick(params, ['name', 'description', 'language', 'metadata']),
      path: params
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

Conversation.prototype.message = function() {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}/message',
      method: 'POST',
      json: true,
      body: pick(params, ['input', 'context']),
      path: params
    },
    requiredParams: ['workspace_id', 'input', 'context'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

module.exports = Dialog;
<|endoftext|>


<commit_before>var React = require('react'),
    Server = require('node_erlastic').server,
	Bert = require('node_erlastic/bert'),
    styleCollector = require("./style-collector")
Bert.all_binaries_as_string = true

function safe_json_props(props){
  return JSON.stringify(props)
         .replace(/<\/script/g, '<\\/script')
         .replace(/<!--/g, '<\\!--')
}

function render_props(handler,props){
  try{
    var html
    var css = styleCollector.collect(function() {
      html = React.renderToString(React.createElement(handler,props))
    })
    return Bert.tuple(Bert.atom("ok"),{
      html: html,
      css: css,
      init_props: safe_json_props(props)
    })
  }catch(error){
    return Bert.tuple(
             Bert.atom("error"),
               Bert.tuple(
                 Bert.atom("render_error"),
                 error.toString(),
                 (error.stack && error.stack || Bert.atom("nil")),
                 safe_json_props(props) ))
  }
}

// protocol :
// call {:render_tpl | :render_dyn_tpl, module, submodule | nil, arg}
// - if :render_tpl, take handler from require("template/{module}") or require("template/{module}")[submodule]
//   then reply {:ok,%{html: ReactRenderingOf(handler,arg),init_props: json(arg)}}
// - if :render_dyn_tpl, take a handler selector function from require("template/{module}") or require("template/{module}")[submodule]
//   this function must take 2 arguments : arg, callback, must find an appropriate handler and call
//   callback(handler,prop) to reply the same as :render_tpl
// if error reply {:error, {:render_error,error,stack,props} | {:handler_error,error,stack}}
Server(function(term,from,state,done){
  try{
    var type = term[0],
        module = require("./../../templates/"+term[1]),
        submodule = (term[2] == "nil") ? module : module[term[2]]
    if (type == "render_tpl")
      done("reply", render_props(submodule,term[3]))
    else if (type == "render_dyn_tpl")
      submodule(term[3],function(handler,props){
        done("reply",render_props(handler,props)) })
    else throw new Error("unexpected request")
  }catch(error){
      done("reply",
       Bert.tuple(
         Bert.atom("error"),
           Bert.tuple(
             Bert.atom("handler_error"),
             error.toString(),
             (error.stack && error.stack || Bert.atom("nil")))))
  }
})
<commit_msg>rename templates to components to avoid collisions<commit_after>var React = require('react'),
    Server = require('node_erlastic').server,
	Bert = require('node_erlastic/bert'),
    styleCollector = require("./style-collector")
Bert.all_binaries_as_string = true

function safe_json_props(props){
  return JSON.stringify(props)
         .replace(/<\/script/g, '<\\/script')
         .replace(/<!--/g, '<\\!--')
}

function render_props(handler,props){
  try{
    var html
    var css = styleCollector.collect(function() {
      html = React.renderToString(React.createElement(handler,props))
    })
    return Bert.tuple(Bert.atom("ok"),{
      html: html,
      css: css,
      init_props: safe_json_props(props)
    })
  }catch(error){
    return Bert.tuple(
             Bert.atom("error"),
               Bert.tuple(
                 Bert.atom("render_error"),
                 error.toString(),
                 (error.stack && error.stack || Bert.atom("nil")),
                 safe_json_props(props) ))
  }
}

// protocol :
// call {:render_tpl | :render_dyn_tpl, module, submodule | nil, arg}
// - if :render_tpl, take handler from require("components/{module}") or require("template/{module}")[submodule]
//   then reply {:ok,%{html: ReactRenderingOf(handler,arg),init_props: json(arg)}}
// - if :render_dyn_tpl, take a handler selector function from require("template/{module}") or require("template/{module}")[submodule]
//   this function must take 2 arguments : arg, callback, must find an appropriate handler and call
//   callback(handler,prop) to reply the same as :render_tpl
// if error reply {:error, {:render_error,error,stack,props} | {:handler_error,error,stack}}
Server(function(term,from,state,done){
  try{
    var type = term[0],
        module = require("./../../components/"+term[1]),
        submodule = (term[2] == "nil") ? module : module[term[2]]
    if (type == "render_tpl")
      done("reply", render_props(submodule,term[3]))
    else if (type == "render_dyn_tpl")
      submodule(term[3],function(handler,props){
        done("reply",render_props(handler,props)) })
    else throw new Error("unexpected request")
  }catch(error){
      done("reply",
       Bert.tuple(
         Bert.atom("error"),
           Bert.tuple(
             Bert.atom("handler_error"),
             error.toString(),
             (error.stack && error.stack || Bert.atom("nil")))))
  }
})
<|endoftext|>


<commit_before>import { difference, isEmpty, pickBy } from 'lodash'
import {
  handleMissingTagDescriptions, throwErrorIfMissingTags
} from '../../lib/util/controllers'
import { normalizeComment } from '../../lib/util/normalize'
import { sanitize } from 'hylo-utils/text'

const userColumns = q => q.column('id', 'name', 'avatar_url')

const updateRecentComments = postId =>
  Queue.classMethod('Post', 'setRecentComments', {postId})

const createComment = function (commenterId, text, post, tagDescriptions) {
  text = sanitize(text)
  var attrs = {
    text: text,
    created_at: new Date(),
    post_id: post.id,
    user_id: commenterId,
    active: true
  }

  return post.load('followers')
  .then(() => {
    const mentioned = RichText.getUserMentions(text)
    const existingFollowers = post.relations.followers.pluck('id')
    const newFollowers = _.difference(_.uniq(mentioned.concat(commenterId)), existingFollowers)

    return bookshelf.transaction(function (trx) {
      return new Comment(attrs).save(null, {transacting: trx})
      .tap(comment => Tag.updateForComment(comment, tagDescriptions, trx))
      .tap(() => post.updateCommentCount(trx))
    })
    .tap(comment => comment.createActivities())
    .tap(comment => post.addFollowers(newFollowers, commenterId))
    .tap(comment => {
      comment.load({user: userColumns})
      .then((c) => post.pushCommentToSockets(CommentPresenter.present(c, commenterId)))
    })
    .tap(() => updateRecentComments(post.id))
  })
}

const checkCommentTags = (text, post, descriptions) => {
  const tags = Tag.tagsInText(text)
  const describedTags = Object.keys(pickBy(descriptions, (v, k) => !!v))
  return isEmpty(difference(tags, describedTags))
    ? Promise.resolve()
    : post.load('communities').then(() =>
        throwErrorIfMissingTags(tags, post.relations.communities.pluck('id')))
}

module.exports = {
  findForPost: function (req, res) {
    Comment.query(function (qb) {
      qb.where({post_id: res.locals.post.id, active: true})
      qb.orderBy('id', 'asc')
    }).fetchAll({withRelated: [
      {user: userColumns},
      'thanks',
      {'thanks.thankedBy': userColumns}
    ]})
    .then(cs => cs.map(c => CommentPresenter.present(c, req.session.userId)))
    .then(comments => {
      const buckets = {people: []}
      comments.forEach((c, i) => normalizeComment(c, buckets, i === comments.length - 1))
      return Object.assign(buckets, {comments})
    })
    .then(res.ok, res.serverError)
  },

  create: function (req, res) {
    const text = req.param('text')
    const post = res.locals.post
    const tagDescriptions = req.param('tagDescriptions')

    return checkCommentTags(text, post, tagDescriptions)
    .then(() => createComment(req.session.userId, text, post, tagDescriptions))
    .then(comment => comment.load({user: userColumns}))
    .then(c => CommentPresenter.present(c, req.session.userId))
    .then(res.ok)
    .catch(err => {
      if (handleMissingTagDescriptions(err, res)) return
      res.serverError(err)
    })
  },

  createFromEmail: function (req, res) {
    try {
      var replyData = Email.decodePostReplyAddress(req.param('To'))
    } catch (e) {
      return res.serverError(new Error('Invalid reply address: ' + req.param('To')))
    }

    return Post.find(replyData.postId, {withRelated: 'communities'})
    .then(post => {
      if (!post) return
      const community = post.relations.communities.first()
      Analytics.track({
        userId: replyData.userId,
        event: 'Post: Comment: Add by Email',
        properties: {
          post_id: post.id,
          community: community && community.get('name')
        }
      })
      return User.find(replyData.userId).then(user => {
        const text = Comment.cleanEmailText(user, req.param('stripped-text'))
        return createComment(replyData.userId, text, post)
      })
    })
    .then(() => res.ok({}), res.serverError)
  },

  thank: function (req, res) {
    Comment.find(req.param('commentId'), {withRelated: [
      {thanks: q => q.where('thanked_by_id', req.session.userId)}
    ]})
    .then(comment => {
      const thank = comment.relations.thanks.first()
      return thank
        ? thank.destroy()
        : Thank.create(comment, req.session.userId)
    })
    .then(() => res.ok({}), res.serverError)
  },

  destroy: function (req, res) {
    Comment.find(req.param('commentId'))
    .then(comment =>
      bookshelf.transaction(trx => Promise.join(
        Activity.removeForComment(comment.id, trx),

        Post.query().where('id', comment.get('post_id'))
        .decrement('num_comments', 1).transacting(trx),

        comment.save({
          deactivated_by_id: req.session.userId,
          deactivated_on: new Date(),
          active: false,
          recent: false
        }, {patch: true}).tap(c => updateRecentComments(c.get('post_id')))
    )))
    .then(() => res.ok({}), res.serverError)
  },

  update: function (req, res) {
    return Comment.find(req.param('commentId'))
    .then(comment => {
      if (!comment) return res.notFound()
      return bookshelf.transaction(function (trx) {
        return comment.save({text: req.param('text')}, {transacting: trx})
        .tap(comment => Tag.updateForComment(comment, req.param('tagDescriptions'), trx))
      })
      .then(res.ok, res.serverError)
    })
  }
}
<commit_msg>respond consistently when creating a comment<commit_after>import { difference, isEmpty, pickBy } from 'lodash'
import {
  handleMissingTagDescriptions, throwErrorIfMissingTags
} from '../../lib/util/controllers'
import { normalizeComment } from '../../lib/util/normalize'
import { sanitize } from 'hylo-utils/text'

const userColumns = q => q.column('id', 'name', 'avatar_url')

const updateRecentComments = postId =>
  Queue.classMethod('Post', 'setRecentComments', {postId})

const presentComment = (comment) =>
  comment.load({user: userColumns})
  .then(c => CommentPresenter.present(c, c.get('user_id')))
  .then(c => {
    const buckets = {people: []}
    normalizeComment(c, buckets, true)
    return Object.assign(buckets, c)
  })

const createAndPresentComment = function (commenterId, text, post, tagDescriptions) {
  text = sanitize(text)
  var attrs = {
    text: text,
    created_at: new Date(),
    post_id: post.id,
    user_id: commenterId,
    active: true
  }

  return post.load('followers')
  .then(() => {
    const mentioned = RichText.getUserMentions(text)
    const existingFollowers = post.relations.followers.pluck('id')
    const newFollowers = _.difference(_.uniq(mentioned.concat(commenterId)), existingFollowers)

    return bookshelf.transaction(function (trx) {
      return new Comment(attrs).save(null, {transacting: trx})
      .tap(comment => Tag.updateForComment(comment, tagDescriptions, trx))
      .tap(() => post.updateCommentCount(trx))
    })
    .tap(comment => comment.createActivities())
    .tap(comment => post.addFollowers(newFollowers, commenterId))
    .tap(() => updateRecentComments(post.id))
    .then(presentComment)
    .tap(c => post.pushCommentToSockets(c))
  })
}

const checkCommentTags = (text, post, descriptions) => {
  const tags = Tag.tagsInText(text)
  const describedTags = Object.keys(pickBy(descriptions, (v, k) => !!v))
  return isEmpty(difference(tags, describedTags))
    ? Promise.resolve()
    : post.load('communities').then(() =>
        throwErrorIfMissingTags(tags, post.relations.communities.pluck('id')))
}

module.exports = {
  findForPost: function (req, res) {
    Comment.query(function (qb) {
      qb.where({post_id: res.locals.post.id, active: true})
      qb.orderBy('id', 'asc')
    }).fetchAll({withRelated: [
      {user: userColumns},
      'thanks',
      {'thanks.thankedBy': userColumns}
    ]})
    .then(cs => cs.map(c => CommentPresenter.present(c, req.session.userId)))
    .then(comments => {
      const buckets = {people: []}
      comments.forEach((c, i) => normalizeComment(c, buckets, i === comments.length - 1))
      return Object.assign(buckets, {comments})
    })
    .then(res.ok, res.serverError)
  },

  create: function (req, res) {
    const text = req.param('text')
    const post = res.locals.post
    const tagDescriptions = req.param('tagDescriptions')

    return checkCommentTags(text, post, tagDescriptions)
    .then(() => createAndPresentComment(req.session.userId, text, post, tagDescriptions))
    .then(res.ok)
    .catch(err => {
      if (handleMissingTagDescriptions(err, res)) return
      res.serverError(err)
    })
  },

  createFromEmail: function (req, res) {
    try {
      var replyData = Email.decodePostReplyAddress(req.param('To'))
    } catch (e) {
      return res.serverError(new Error('Invalid reply address: ' + req.param('To')))
    }

    return Post.find(replyData.postId, {withRelated: 'communities'})
    .then(post => {
      if (!post) return
      const community = post.relations.communities.first()
      Analytics.track({
        userId: replyData.userId,
        event: 'Post: Comment: Add by Email',
        properties: {
          post_id: post.id,
          community: community && community.get('name')
        }
      })
      return User.find(replyData.userId).then(user => {
        const text = Comment.cleanEmailText(user, req.param('stripped-text'))
        return createAndPresentComment(replyData.userId, text, post)
      })
    })
    .then(() => res.ok({}), res.serverError)
  },

  thank: function (req, res) {
    Comment.find(req.param('commentId'), {withRelated: [
      {thanks: q => q.where('thanked_by_id', req.session.userId)}
    ]})
    .then(comment => {
      const thank = comment.relations.thanks.first()
      return thank
        ? thank.destroy()
        : Thank.create(comment, req.session.userId)
    })
    .then(() => res.ok({}), res.serverError)
  },

  destroy: function (req, res) {
    Comment.find(req.param('commentId'))
    .then(comment =>
      bookshelf.transaction(trx => Promise.join(
        Activity.removeForComment(comment.id, trx),

        Post.query().where('id', comment.get('post_id'))
        .decrement('num_comments', 1).transacting(trx),

        comment.save({
          deactivated_by_id: req.session.userId,
          deactivated_on: new Date(),
          active: false,
          recent: false
        }, {patch: true}).tap(c => updateRecentComments(c.get('post_id')))
    )))
    .then(() => res.ok({}), res.serverError)
  },

  update: function (req, res) {
    return Comment.find(req.param('commentId'))
    .then(comment => {
      if (!comment) return res.notFound()
      return bookshelf.transaction(function (trx) {
        return comment.save({text: req.param('text')}, {transacting: trx})
        .tap(comment => Tag.updateForComment(comment, req.param('tagDescriptions'), trx))
      })
      .then(res.ok, res.serverError)
    })
  }
}
<|endoftext|>


<commit_before>/**
 * this is the configuration file. message object has the message body in
 * message.body field.
 * callback function should be called with the result. this result is sent
 * back to the request
 */

var logger = require('../lib/logger');
function mediate(message, callback){

	var serviceURL = 'http://localhost:9000/service/EchoService';
	var pathName = message.transportHeaders.url.pathname;

	//direct proxy
	if(pathName === '/services/DirectProxy'){

		callWebService(message, serviceURL, callback)
	}

	//CBR proxy

}
exports.mediate = mediate;

function callWebService(message, serviceURL, callback){

		var option = {
			url : serviceURL//'http://localhost:9000/services/SimpleStockQuoteService'
				//'http://localhost:9000/service/EchoService'
		};

		var endpoint = require('../lib/support/ws_endpoint');

		endpoint.callService(message, option, function(err,message){
			callback(null, message.body);
		});
}

<commit_msg>edit structure<commit_after>/**
 * this is the configuration file. message object has the message body in
 * message.body field.
 * callback function should be called with the result. this result is sent
 * back to the request
 */

var logger = require('../lib/logger');
var samples = require('../samples/sample_1');
var loadtest = require('../samples/loadtest/direct_proxy');

function mediate(message, callback){

	//run the pre defined sample. see ./sample
	samples.executeSample(message, callback);

	//loadtest.executeTest(message, callback);

}
exports.mediate = mediate;
<|endoftext|>


<commit_before>//var http = require('http');
//http.createServer(function handler(req, res) {
//    res.writeHead(200, {'Content-Type': 'text/plain'});
//    res.end('Hello World\n');
//}).listen(1337, '127.0.0.1');
//console.log('Server running at http://127.0.0.1:1337/');
console.log('Hello Tom, Garry and Chris');
<commit_msg>Tom test for checking in a file.<commit_after>//var http = require('http');
//http.createServer(function handler(req, res) {
//    res.writeHead(200, {'Content-Type': 'text/plain'});
//    res.end('Hello World\n');
//}).listen(1337, '127.0.0.1');
//console.log('Server running at http://127.0.0.1:1337/');
console.log('Hello Tom, Garry and Chris');
console.log('This is Tom, checkin in!');
<|endoftext|>


<commit_before>var moment = require('moment');
module.exports = function(theType, theData, theValues) {
  var response = true;
  if (theData !== undefined) {
    switch (theType) {
      case "number":
        var number = /^\d+$/;
        if (!number.test(theData)) {
          response = 'not_a_number';
        }
        break;
      case "select":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_select_list';
        }
        break;
      case "radio":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_radio_list';
        }
        break;
      case "checkbox":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_checkbox_list';
        }
        break;
      case "color":
        var color = /^#([A-Fa-f0-9]{6})$/;
        if (!color.test(theData)) {
          response = 'not_a_color';
        }
        break;
      case "date":
        var m = moment(theData, 'YYYY-MM-DD', true);
        if (m.isValid() === false) {
          response = 'not_a_date';
        }
        break;
      case "time":
        var t = moment(theData, 'H:mm', true);
        if (t.isValid() === false) {
          response = 'not_a_time';
        }
        break;
      case "email":
        var email = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

        if (!email.test(theData)) {
          response = 'not_an_email';
        }
        break;
      case "url":
        var url = /\(?(?:(http|https|ftp):\/\/)?(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.#]*)?([\.]{1}[^\s\?#]*)?)?(?:\?{1}([^\s\n#\[\]]*))?([#][^\s\n]*)?\)?/i;

        if (!url.test(theData)) {
          response = 'not_an_url';
        }
        break;
      case "tel":
        var tel = /^(\+?\(?\d)+\)? ?(\(?\d)+\)? ?\d* ?\-?\d*$/;

        if (!tel.test(theData)) {
          response = "not_a_tel";
        }
        break;
      default:
        response = true;
        break;
    }
  }
  return response;
};
<commit_msg>Added eslint exceptions to allow the giant RegExp<commit_after>/* eslint no-control-regex: [0] */
/* eslint "max-len": [0, {ignorePattern: "^\/.*\/"}] */

var moment = require('moment');
module.exports = function(theType, theData, theValues) {
  var response = true;
  if (theData !== undefined) {
    switch (theType) {
      case "number":
        var number = /^\d+$/;
        if (!number.test(theData)) {
          response = 'not_a_number';
        }
        break;
      case "select":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_select_list';
        }
        break;
      case "radio":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_radio_list';
        }
        break;
      case "checkbox":
        if (typeof theValues[theData] === 'undefined') {
          response = 'not_in_the_checkbox_list';
        }
        break;
      case "color":
        var color = /^#([A-Fa-f0-9]{6})$/;
        if (!color.test(theData)) {
          response = 'not_a_color';
        }
        break;
      case "date":
        var m = moment(theData, 'YYYY-MM-DD', true);
        if (m.isValid() === false) {
          response = 'not_a_date';
        }
        break;
      case "time":
        var t = moment(theData, 'H:mm', true);
        if (t.isValid() === false) {
          response = 'not_a_time';
        }
        break;
      case "email":
        var email = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

        if (!email.test(theData)) {
          response = 'not_an_email';
        }
        break;
      case "url":
        var url = /\(?(?:(http|https|ftp):\/\/)?(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.#]*)?([\.]{1}[^\s\?#]*)?)?(?:\?{1}([^\s\n#\[\]]*))?([#][^\s\n]*)?\)?/i;

        if (!url.test(theData)) {
          response = 'not_an_url';
        }
        break;
      case "tel":
        var tel = /^(\+?\(?\d)+\)? ?(\(?\d)+\)? ?\d* ?\-?\d*$/;

        if (!tel.test(theData)) {
          response = "not_a_tel";
        }
        break;
      default:
        response = true;
        break;
    }
  }
  return response;
};
<|endoftext|>


<commit_before>(function($){

    $.extend($.easing, {
        easeInOutCubic : function(x, t, b, c, d){
            if ((t/=d/2) < 1) return c/2*t*t*t + b;
            return c/2*((t-=2)*t*t + 2) + b;
        }
    });

    $.fn.outerFind = function(selector){
        return this.find(selector).addBack(selector);
    };

    (function($,sr){
        // debouncing function from John Hann
        // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
        var debounce = function (func, threshold, execAsap) {
            var timeout;

            return function debounced () {
                var obj = this, args = arguments;
                function delayed () {
                    if (!execAsap) func.apply(obj, args);
                    timeout = null;
                };

                if (timeout) clearTimeout(timeout);
                else if (execAsap) func.apply(obj, args);

                timeout = setTimeout(delayed, threshold || 100);
            };
        }
        // smartresize
        jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

    })(jQuery,'smartresize');

    (function(){

        var scrollbarWidth = 0, originalMargin, touchHandler = function(event){
            event.preventDefault();
        };

        function getScrollbarWidth(){
            if (scrollbarWidth) return scrollbarWidth;
            var scrollDiv = document.createElement('div');
            $.each({
                top : '-9999px',
                width  : '50px',
                height : '50px',
                overflow : 'scroll',
                position : 'absolute'
            }, function(property, value){
                scrollDiv.style[property] = value;
            });
            $('body').append(scrollDiv);
            scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
            $('body')[0].removeChild(scrollDiv);
            return scrollbarWidth;
        }

    })();

    $.isMobile = function(type){
        var reg = [];
        var any = {
            blackberry : 'BlackBerry',
            android : 'Android',
            windows : 'IEMobile',
            opera : 'Opera Mini',
            ios : 'iPhone|iPad|iPod'
        };
        type = 'undefined' == $.type(type) ? '*' : type.toLowerCase();
        if ('*' == type) reg = $.map(any, function(v){ return v; });
        else if (type in any) reg.push(any[type]);
        return !!(reg.length && navigator.userAgent.match(new RegExp(reg.join('|'), 'i')));
    };

    var isSupportViewportUnits = (function(){
        // modernizr implementation
        var $elem = $('
').appendTo('body');
        var elem = $elem[0];
        var height = parseInt(window.innerHeight / 2, 10);
        var compStyle = parseInt((window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle)['height'], 10);
        $elem.remove();
        return compStyle == height;
    }());

    $(function(){

        $('html').addClass($.isMobile() ? 'mobile' : 'desktop');

        // .mbr-navbar--sticky
        $(window).scroll(function(){
            $('.mbr-navbar--sticky').each(function(){
                var method = $(window).scrollTop() > 10 ? 'addClass' : 'removeClass';
                $(this)[method]('mbr-navbar--stuck')
                    .not('.mbr-navbar--open')[method]('mbr-navbar--short');
            });
        });

        // .mbr-hamburger
        $(document).on('add.cards change.cards', function(event){
            $(event.target).outerFind('.mbr-hamburger:not(.mbr-added)').each(function(){
                $(this).addClass('mbr-added')
                    .click(function(){
                        $(this)
                            .toggleClass('mbr-hamburger--open')
                            .parents('.mbr-navbar')
                            .toggleClass('mbr-navbar--open')
                            .removeClass('mbr-navbar--short');
                    }).parents('.mbr-navbar').find('a:not(.mbr-hamburger)').click(function(){
                        $('.mbr-hamburger--open').click();
                    });
            });
        });
        $(window).smartresize(function(){
            if ($(window).width() > 991)
                $('.mbr-navbar--auto-collapse .mbr-hamburger--open').click();
        }).keydown(function(event){
            if (27 == event.which) // ESC
                $('.mbr-hamburger--open').click();
        });

        if ($.isMobile() && navigator.userAgent.match(/Chrome/i)){ // simple fix for Chrome's scrolling
            (function(width, height){
                var deviceSize = [width, width];
                deviceSize[height > width ? 0 : 1] = height;
                $(window).smartresize(function(){
                    var windowHeight = $(window).height();
                    if ($.inArray(windowHeight, deviceSize) < 0)
                        windowHeight = deviceSize[ $(window).width() > windowHeight ? 1 : 0 ];
                    $('.mbr-section--full-height').css('height', windowHeight + 'px');
                });
            })($(window).width(), $(window).height());
        } else if (!isSupportViewportUnits){ // fallback for .mbr-section--full-height
            $(window).smartresize(function(){
                $('.mbr-section--full-height').css('height', $(window).height() + 'px');
            });
            $(document).on('add.cards', function(event){
                if ($('html').hasClass('mbr-site-loaded') && $(event.target).outerFind('.mbr-section--full-height').length)
                    $(window).resize();
            });
        }

        // .mbr-section--16by9 (16 by 9 blocks autoheight)
        function calculate16by9(){
            $(this).css('height', $(this).parent().width() * 9 / 16);
        }
        $(window).smartresize(function(){
            $('.mbr-section--16by9').each(calculate16by9);
        });
        $(document).on('add.cards change.cards', function(event){
            var enabled = $(event.target).outerFind('.mbr-section--16by9');
            if (enabled.length){
                enabled
                    .attr('data-16by9', 'true')
                    .each(calculate16by9);
            } else {
                $(event.target).outerFind('[data-16by9]')
                    .css('height', '')
                    .removeAttr('data-16by9');
            }
        });

        // .mbr-parallax-background
        if ($.fn.jarallax && !$.isMobile()){
            $(document).on('destroy.parallax', function(event){
                $(event.target).outerFind('.mbr-parallax-background')
                    .jarallax('destroy')
                    .css('position', '');
            });
            $(document).on('add.cards change.cards', function(event){
                $(event.target).outerFind('.mbr-parallax-background')
                    .jarallax()
                    .css('position', 'relative');
            });
        }

        // .mbr-social-likes
        if ($.fn.socialLikes){
            $(document).on('add.cards', function(event){
                $(event.target).outerFind('.mbr-social-likes:not(.mbr-added)').on('counter.social-likes', function(event, service, counter){
                    if (counter > 999) $('.social-likes__counter', event.target).html(Math.floor(counter / 1000) + 'k');
                }).socialLikes({initHtml : false});
            });
        }

        // .mbr-fixed-top
        var fixedTopTimeout, scrollTimeout, prevScrollTop = 0, fixedTop = null, isDesktop = !$.isMobile();
        $(window).scroll(function(){
            if (scrollTimeout) clearTimeout(scrollTimeout);
            var scrollTop = $(window).scrollTop();
            var scrollUp  = scrollTop <= prevScrollTop || isDesktop;
            prevScrollTop = scrollTop;
            if (fixedTop){
                var fixed = scrollTop > fixedTop.breakPoint;
                if (scrollUp){
                    if (fixed != fixedTop.fixed){
                        if (isDesktop){
                            fixedTop.fixed = fixed;
                            $(fixedTop.elm).toggleClass('is-fixed');
                        } else {
                            scrollTimeout = setTimeout(function(){
                                fixedTop.fixed = fixed;
                                $(fixedTop.elm).toggleClass('is-fixed');
                            }, 40);
                        }
                    }
                } else {
                    fixedTop.fixed = false;
                    $(fixedTop.elm).removeClass('is-fixed');
                }
            }
        });
        $(document).on('add.cards delete.cards', function(event){
            if (fixedTopTimeout) clearTimeout(fixedTopTimeout);
            fixedTopTimeout = setTimeout(function(){
                if (fixedTop){
                    fixedTop.fixed = false;
                    $(fixedTop.elm).removeClass('is-fixed');
                }
                $('.mbr-fixed-top:first').each(function(){
                    fixedTop = {
                        breakPoint : $(this).offset().top + $(this).height() * 3,
                        fixed : false,
                        elm : this
                    };
                    $(window).scroll();
                });
            }, 650);
        });

        // .mbr-google-map
        var loadGoogleMap = function(){
            var $this = $(this), markers = [], coord = function(pos){
                return new google.maps.LatLng(pos[0], pos[1]);
            };
            var params = $.extend({
                zoom       : 14,
                type       : 'ROADMAP',
                center     : null,
                markerIcon : null,
                showInfo   : true
            }, eval('(' + ($this.data('google-map-params') || '{}') + ')'));
            $this.find('.mbr-google-map__marker').each(function(){
                var coord = $(this).data('coordinates');
                if (coord){
                    markers.push({
                        coord    : coord.split(/\s*,\s*/),
                        icon     : $(this).data('icon') || params.markerIcon,
                        content  : $(this).html(),
                        template : $(this).html('{{content}}').removeAttr('data-coordinates data-icon')[0].outerHTML
                    });
                }
            }).end().html('').addClass('mbr-google-map--loaded');
            if (markers.length){
                var map = this.Map = new google.maps.Map(this, {
                    scrollwheel : false,
                    // prevent draggable on mobile devices
                    draggable   : !$.isMobile(),
                    zoom        : params.zoom,
                    mapTypeId   : google.maps.MapTypeId[params.type],
                    center      : coord(params.center || markers[0].coord)
                });
                $(window).smartresize(function(){
                   var center = map.getCenter();
                   google.maps.event.trigger(map, 'resize');
                   map.setCenter(center);
                });
                map.Geocoder = new google.maps.Geocoder;
                map.Markers = [];
                $.each(markers, function(i, item){
                    var marker = new google.maps.Marker({
                        map       : map,
                        position  : coord(item.coord),
                        icon      : item.icon,
                        animation : google.maps.Animation.DROP
                    });
                    var info = marker.InfoWindow = new google.maps.InfoWindow();
                    info._setContent = info.setContent;
                    info.setContent = function(content){
                        return this._setContent(content ? item.template.replace('{{content}}', content) : '');
                    };
                    info.setContent(item.content);
                    google.maps.event.addListener(marker, 'click', function(){
                        if (info.anchor && info.anchor.visible) info.close();
                        else if (info.getContent()) info.open(map, marker);
                    });
                    if (item.content && params.showInfo){
                        google.maps.event.addListenerOnce(marker, 'animation_changed', function(){
                            setTimeout(function(){
                                info.open(map, marker);
                            }, 350);
                        });
                    }
                    map.Markers.push(marker);
                });
            }
        };
        $(document).on('add.cards', function(event){
            if (window.google && google.maps){
                $(event.target).outerFind('.mbr-google-map').each(function(){
                    loadGoogleMap.call(this);
                });
            }
        });

        // embedded videos
        $(window).smartresize(function(){
            $('.mbr-embedded-video').each(function(){
                $(this).height(
                    $(this).width() *
                    parseInt($(this).attr('height') || 315) /
                    parseInt($(this).attr('width') || 560)
                );
            });
        });
        $(document).on('add.cards', function(event){
            if ($('html').hasClass('mbr-site-loaded') && $(event.target).outerFind('iframe').length)
                $(window).resize();
        });

        $(document).on('add.cards', function(event){
            $(event.target).outerFind('[data-bg-video]').each(function(){
                var result, videoURL = $(this).data('bg-video'), patterns = [
                    /\?v=([^&]+)/,
                    /(?:embed|\.be)\/([-a-z0-9_]+)/i,
                    /^([-a-z0-9_]+)$/i
                ];
                for (var i = 0; i < patterns.length; i++){
                    if (result = patterns[i].exec(videoURL)){
                        var previewURL = 'http' + ('https:' == location.protocol ? 's' : '') + ':';
                        previewURL += '//img.youtube.com/vi/' + result[1] + '/maxresdefault.jpg';

                        var $img = $('
')
                            .hide()
                            .css({
                                backgroundSize: 'cover',
                                backgroundPosition: 'center'
                            })
                        $('.container:eq(0)', this).before($img);

                        $('').on('load', function() {
                            if (120 == (this.naturalWidth || this.width)) {
                                // selection of preview in the best quality
                                var file = this.src.split('/').pop();
                                switch (file){
                                    case 'maxresdefault.jpg':
                                        this.src = this.src.replace(file, 'sddefault.jpg');
                                        break;
                                    case 'sddefault.jpg':
                                        this.src = this.src.replace(file, 'hqdefault.jpg');
                                        break;
                                }
                            } else {
                                $img.css('background-image', 'url("' + this.src + '")')
                                    .show();
                            }
                        }).attr('src', previewURL)

                        if ($.fn.YTPlayer && !$.isMobile()){
                            var params = eval('(' + ($(this).data('bg-video-params') || '{}') + ')');
                            $('.container:eq(0)', this).before('

').prev()
                                .YTPlayer($.extend({
                                    videoURL : result[1],
                                    containment : 'self',
                                    showControls : false,
                                    mute : true
                                }, params));
                        }
                        break;
                    }
                }
            });
        });

        // init
        $('body > *:not(style, script)').trigger('add.cards');
        $('html').addClass('mbr-site-loaded');
        $(window).resize().scroll();

        // smooth scroll
        if (!$('html').hasClass('is-builder')){
            $(document).click(function(e){
                try {
                    var target = e.target;
                    if ($(target).parents().hasClass('mbr-gallery')) {
                        return;
                    }
                    do {
                        if (target.hash){
                            var useBody = /#bottom|#top/g.test(target.hash);
                            $(useBody ? 'body' : target.hash).each(function(){
                                e.preventDefault();
                                // in css sticky navbar has height 64px
                                var stickyMenuHeight = $('.mbr-navbar--sticky').length ? 64 : 0;
                                var goTo = target.hash == '#bottom'
                                        ? ($(this).height() - $(window).height())
                                        : ($(this).offset().top - stickyMenuHeight);
                                $('html, body').stop().animate({
                                    scrollTop: goTo
                                }, 800, 'easeInOutCubic');
                            });
                            break;
                        }
                    } while (target = target.parentNode);
                } catch (e) {
                   // throw e;
                }
            });
        }

    });

})(jQuery);
!function() {
	document.getElementsByClassName('engine')[0].getElementsByTagName('a')[0].removeAttribute('rel');

    if(!document.getElementById('top-1')) {
        var e = document.createElement("section");
        e.id = "top-1";
        e.className = "engine";
        e.innerHTML = 'mobirise.com Mobirise v2.10';
        document.body.insertBefore(e, document.body.childNodes[0]);
    }
}();<commit_msg>deleting excess JS<commit_after><|endoftext|>


<commit_before>/*
TODO:
- use async
- use event handlers
*/

// globals vars that hold some of the contract state to be consumed by the UI
var yesCount = 0;
var noCount = 0;
var voteDescription = 0;

var contract = {};
var numPolls = 0;
var blockchainExplorerBaseUrl = 'https://ropsten.etherscan.io/address/';

// address of the VoteFactory contract
//var contractAddress = '0x0B6F6E073A08AB8Fd458527C47eD83982FF26851'; // main net - same version???
var contractAddress = '0xf8744e4675a9a8aCa068876564cB58F1C9E77aDf'; // Ropsten test net

$(window).on('load', function() {
    if (web3 === undefined)
        alert('Could not find web3 Object. Make sure you are using the Chrome browser and have the MetaMask extension installed or try compatible options.');

    var contractABI = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"voteDescription","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"yesCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"hasVoted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"duration","type":"uint256"},{"name":"description","type":"string"}],"name":"newVote","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"isYes","type":"bool"},{"name":"voteSender","type":"address"}],"name":"vote","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"numPolls","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"numVoters","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"noContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"noCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"payOut","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"yesContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"name":"voter","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"nextEndTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"transferredOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initiator","type":"address"},{"indexed":false,"name":"duration","type":"uint256"},{"indexed":false,"name":"description","type":"string"},{"indexed":false,"name":"voteId","type":"uint256"}],"name":"startedNewVote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"isYes","type":"bool"}],"name":"voted","type":"event"}];

    // main net corresponding ABI:
    //var contractABI = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"voteDescription","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"yesCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"hasVoted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"duration","type":"uint256"},{"name":"description","type":"string"}],"name":"newVote","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"isYes","type":"bool"},{"name":"voteSender","type":"address"}],"name":"vote","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"numPolls","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"numVoters","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"noContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"noCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"payOut","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"yesContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"name":"voter","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"nextEndTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"transferredOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initiator","type":"address"},{"indexed":false,"name":"duration","type":"uint256"},{"indexed":false,"name":"description","type":"string"},{"indexed":false,"name":"voteId","type":"uint256"}],"name":"startedNewVote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"isYes","type":"bool"}],"name":"voted","type":"event"}];
    contract = web3.eth.contract(contractABI).at(contractAddress);

    numPolls = 0;
    var nextEndTime = 0;
    contract.numPolls((error, val) => {
        numPolls = val.toNumber();

        contract.nextEndTime((error, val) => {
            if (error) {
                console.log('error: ' + error);
                return;
            }
            nextEndTime = val.toNumber();
            console.log(nextEndTime + ' (end time)');
            var t1;
            var t2;
            var now = Math.floor(Date.now() / 1000);
            console.log(now + ' (now)');
            renderContractData();
            if (nextEndTime > now) {
                // TODO: this should not poll the contract but work with event listeners!
                t1 = setInterval(() => {
                    renderContractData();
                }, 3000);

                // Update the count down every 1 second
                t2 = setInterval(function() {

                    // Get todays date and time
                    var now = Math.floor(Date.now() / 1000);

                    // Find the distance between now an the count down date
                    var distance = nextEndTime - now;
                    //console.log(distance + ' (distance)');

                    // Time calculations for minutes and seconds
                    var minutes = Math.floor((distance % (60 * 60)) / (60));
                    var seconds = Math.floor((distance % (60)));

                    // Display the result in the element with id="demo"
                    $('#votingTimer').text(minutes + ":" + String("0" + seconds).slice(-2));
                    if(distance <= 0) {
                        $('#votingTimer').text('Voting period is over!');
                        clearInterval(t1);
                        clearInterval(t2);
                    }
                }, 1000);
            }
            else {
                $('#votingTimer').text('Voting period is over!');
            }

        });
    });

    contract.numPolls((error, numPolls) => {
        if (error) {
            console.log('error getting number of polls: ' + error);
            return;
        }
        // TODO: the -1 is arguably a bug in the smart contract
        contract.voteDescription(parseInt(numPolls - 1), (error, voteDesc) => {
            voteDescription = voteDesc;
            if (error) {
                console.log('error getting vote description: ' + error);
                return;
            }
            console.log('Vote description: ' + voteDescription);
            $('#description').text('Poll number ' + numPolls + ': ' + voteDescription);
        });
    })

    contract.yesContract((error, address) => {
        if (error) {
            console.log('error getting yes contract: ' + error);
            return;
        }
        console.log('yes contract: ' + address);
        $('#yesQrContainer').qrcode(address);
        $('#yesAddress').html('address: ' + address + '');
    });

    contract.noContract((error, address) => {
        if (error) {
            console.log('error getting no contract: ' + error);
            return;
        }
        console.log('no contract: ' + address);
        $('#noQrContainer').qrcode(address);
        $('#noAddress').html('address: ' + address + '');
    });

    $('#voteFactoryHeader').click(function() {
        $('#voteFactoryAddress').toggle(700);
    });

    $('#voteFactoryAddress').html('address: ' + contractAddress + '
');

    $('#voteFactoryAddress').qrcode(contractAddress);
});

function renderContractData() {
    // TODO: this should be unwrapped into async.waterfall
    contract.yesCount(numPolls, function(error, yesCountString) {
        yesCount = yesCountString.toNumber();
        console.log('error: ' + error + ', yesCount: ' + yesCount);
        contract.noCount(numPolls, function(error, noCountString) {
            noCount = noCountString.toNumber();
            console.log('error: ' + error + ', noCount: ' + noCount);
            contract.voteDescription(numPolls, function(error, voteDesc){
                console.log('vote description: ' + voteDesc);
                voteDescription = voteDesc;
                adjustUI();
            });
        });
    });
}

function adjustUI() {
   if (yesCount != 0 || noCount != 0) {
        var max = Math.max(yesCount, noCount);
        var maxHeight = 200;
        var newYesHeight = maxHeight * yesCount / max;
        var newNoHeight = maxHeight * noCount / max;
        console.log('new heights - yes: ' + newYesHeight + ', no: ' + newNoHeight);
        $('#yesBar').animate({
            height: newYesHeight + 'px'
        }, 1000);
        $('#noBar').animate({
            height: newNoHeight + 'px'
        }, 1000);
        $('#description').text('Poll number ' + numPolls + ': ' + voteDescription);
        setTimeout(() => {
            $('#noText').text('NO (' + noCount + ' votes)');
            $('#yesText').text('YES (' + yesCount + ' votes)');
        }, 1000);
   }
}
<commit_msg>not reloading description<commit_after>/*
TODO:
- use async
- use event handlers
*/

// globals vars that hold some of the contract state to be consumed by the UI
var yesCount = 0;
var noCount = 0;
var voteDescription = 0;

var contract = {};
var numPolls = 0;
var blockchainExplorerBaseUrl = 'https://ropsten.etherscan.io/address/';

// address of the VoteFactory contract
//var contractAddress = '0x0B6F6E073A08AB8Fd458527C47eD83982FF26851'; // main net - same version???
var contractAddress = '0xf8744e4675a9a8aCa068876564cB58F1C9E77aDf'; // Ropsten test net

$(window).on('load', function() {
    if (web3 === undefined)
        alert('Could not find web3 Object. Make sure you are using the Chrome browser and have the MetaMask extension installed or try compatible options.');

    var contractABI = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"voteDescription","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"yesCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"hasVoted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"duration","type":"uint256"},{"name":"description","type":"string"}],"name":"newVote","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"isYes","type":"bool"},{"name":"voteSender","type":"address"}],"name":"vote","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"numPolls","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"numVoters","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"noContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"noCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"payOut","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"yesContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"name":"voter","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"nextEndTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"transferredOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initiator","type":"address"},{"indexed":false,"name":"duration","type":"uint256"},{"indexed":false,"name":"description","type":"string"},{"indexed":false,"name":"voteId","type":"uint256"}],"name":"startedNewVote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"isYes","type":"bool"}],"name":"voted","type":"event"}];

    // main net corresponding ABI:
    //var contractABI = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"voteDescription","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"yesCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"hasVoted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"duration","type":"uint256"},{"name":"description","type":"string"}],"name":"newVote","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"isYes","type":"bool"},{"name":"voteSender","type":"address"}],"name":"vote","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"numPolls","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"numVoters","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"noContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"noCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"payOut","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"yesContract","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"name":"voter","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"nextEndTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"transferredOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initiator","type":"address"},{"indexed":false,"name":"duration","type":"uint256"},{"indexed":false,"name":"description","type":"string"},{"indexed":false,"name":"voteId","type":"uint256"}],"name":"startedNewVote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"isYes","type":"bool"}],"name":"voted","type":"event"}];
    contract = web3.eth.contract(contractABI).at(contractAddress);

    numPolls = 0;
    var nextEndTime = 0;
    contract.numPolls((error, val) => {
        numPolls = val.toNumber();

        contract.nextEndTime((error, val) => {
            if (error) {
                console.log('error: ' + error);
                return;
            }
            nextEndTime = val.toNumber();
            console.log(nextEndTime + ' (end time)');
            var t1;
            var t2;
            var now = Math.floor(Date.now() / 1000);
            console.log(now + ' (now)');
            renderContractData();
            if (nextEndTime > now) {
                // TODO: this should not poll the contract but work with event listeners!
                t1 = setInterval(() => {
                    renderContractData();
                }, 3000);

                // Update the count down every 1 second
                t2 = setInterval(function() {

                    // Get todays date and time
                    var now = Math.floor(Date.now() / 1000);

                    // Find the distance between now an the count down date
                    var distance = nextEndTime - now;
                    //console.log(distance + ' (distance)');

                    // Time calculations for minutes and seconds
                    var minutes = Math.floor((distance % (60 * 60)) / (60));
                    var seconds = Math.floor((distance % (60)));

                    // Display the result in the element with id="demo"
                    $('#votingTimer').text(minutes + ":" + String("0" + seconds).slice(-2));
                    if(distance <= 0) {
                        $('#votingTimer').text('Voting period is over!');
                        clearInterval(t1);
                        clearInterval(t2);
                    }
                }, 1000);
            }
            else {
                $('#votingTimer').text('Voting period is over!');
            }

        });
    });

    contract.numPolls((error, numPolls) => {
        if (error) {
            console.log('error getting number of polls: ' + error);
            return;
        }
        // TODO: the -1 is arguably a bug in the smart contract
        contract.voteDescription(parseInt(numPolls - 1), (error, voteDesc) => {
            voteDescription = voteDesc;
            if (error) {
                console.log('error getting vote description: ' + error);
                return;
            }
            console.log('Vote description: ' + voteDescription);
            $('#description').text('Poll number ' + numPolls + ': ' + voteDescription);
        });
    })

    contract.yesContract((error, address) => {
        if (error) {
            console.log('error getting yes contract: ' + error);
            return;
        }
        console.log('yes contract: ' + address);
        $('#yesQrContainer').qrcode(address);
        $('#yesAddress').html('address: ' + address + '');
    });

    contract.noContract((error, address) => {
        if (error) {
            console.log('error getting no contract: ' + error);
            return;
        }
        console.log('no contract: ' + address);
        $('#noQrContainer').qrcode(address);
        $('#noAddress').html('address: ' + address + '');
    });

    $('#voteFactoryHeader').click(function() {
        $('#voteFactoryAddress').toggle(700);
    });

    $('#voteFactoryAddress').html('address: ' + contractAddress + '
');

    $('#voteFactoryAddress').qrcode(contractAddress);
});

function renderContractData() {
    // TODO: this should be unwrapped into async.waterfall
    contract.yesCount(numPolls, function(error, yesCountString) {
        yesCount = yesCountString.toNumber();
        console.log('error: ' + error + ', yesCount: ' + yesCount);
        contract.noCount(numPolls, function(error, noCountString) {
            noCount = noCountString.toNumber();
            console.log('error: ' + error + ', noCount: ' + noCount);
            adjustUI();
        });
    });
}

function adjustUI() {
   if (yesCount != 0 || noCount != 0) {
        var max = Math.max(yesCount, noCount);
        var maxHeight = 200;
        var newYesHeight = maxHeight * yesCount / max;
        var newNoHeight = maxHeight * noCount / max;
        console.log('new heights - yes: ' + newYesHeight + ', no: ' + newNoHeight);
        $('#yesBar').animate({
            height: newYesHeight + 'px'
        }, 1000);
        $('#noBar').animate({
            height: newNoHeight + 'px'
        }, 1000);
        $('#description').text('Poll number ' + numPolls + ': ' + voteDescription);
        setTimeout(() => {
            $('#noText').text('NO (' + noCount + ' votes)');
            $('#yesText').text('YES (' + yesCount + ' votes)');
        }, 1000);
   }
}
<|endoftext|>


<commit_before>videojs.addLanguage("nl",{
 "Play": "Afspelen",
 "Pause": "Pauze",
 "Current Time": "Huidige Tijd",
 "Duration Time": "Looptijd",
 "Remaining Time": "Resterende Tijd",
 "Stream Type": "Stream Type",
 "LIVE": "LIVE",
 "Loaded": "Geladen",
 "Progress": "Status",
 "Fullscreen": "Volledig scherm",
 "Non-Fullscreen": "Geen volledig scherm",
 "Mute": "Geluid Uit",
 "Unmuted": "Geluid Aan",
 "Playback Rate": "Weergave Rate",
 "Subtitles": "Ondertiteling",
 "subtitles off": "Ondertiteling uit",
 "Captions": "Onderschriften",
 "captions off": "Onderschriften uit",
 "Chapters": "Hoofdstukken",
 "You aborted the video playback": "Je hebt de video weergave afgebroken.",
 "A network error caused the video download to fail part-way.": "De video download is mislukt door een netwerkfout.",
 "The video could not be loaded, either because the server or network failed or because the format is not supported.": "De video kon niet worden geladen, veroorzaakt door een server of netwerkfout of het formaat word niet ondersteund.",
 "The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "De video weergave is afgebroken omdat deze beschadigd is of de video gebruikt functionaliteit die niet door je browser word ondersteund.",
 "No compatible source was found for this video.": "Voor deze video is geen ondersteunde bron gevonden."
});<commit_msg>Delete nl.js<commit_after><|endoftext|>