<commit_before>/**************************
 Script to convert EPrint
 front page boxes into
 Bootstrap panels
***************************/
var j = jQuery.noConflict();

j(document).ready(function () {

	//initialisting
	var panel = j('.ep_toolbox');
	var unwrap = j('.ep_toolbox_content');
	var panelHeading = j('.ep_toolbox a');
	if (j('.ep_toolbox_content b').length){
		var panelTextNode = j('.ep_toolbox_content b');
		alert("test");
	}else {
		j('.ep_toolbox_content').contents().each(function(){
			 if(this.nodeName == "#text" && j.trim(this.nodeValue) !== ''){
        			j(this).wrap('

');
    			}
		});
	}

	//add the classes and the wrappers
	panel.addClass('panel panel-default panel-docklands-fp');
	panelTextNode.wrap('

');
	panelHeading.wrap('

');

	// Removing some stuff that isnt needed
	panel.find('br').remove();
	unwrap.children().unwrap();
	//j('.panel .panel-body p').is(':empty').remove();
	panel.removeClass('ep_toolbox').addClass('frontpage-panel');

});

<commit_msg>replaced the b witha strong<commit_after>/**************************
 Script to convert EPrint
 front page boxes into
 Bootstrap panels
***************************/
var j = jQuery.noConflict();

j(document).ready(function () {

	//initialisting
	var panel = j('.ep_toolbox');
	var unwrap = j('.ep_toolbox_content');
	var panelHeading = j('.ep_toolbox a');
	if (j('.ep_toolbox_content b').length){
		j('.ep_toolbox_content b').wrap('

');

	}else {
		j('.ep_toolbox_content').contents().each(function(){
			 if(this.nodeName == "#text" && j.trim(this.nodeValue) !== ''){
        			j(this).wrap('

');
    			}
		});
	}

	//remove that b and replace with strong
	j('.ep_toolbox_content b').replaceWith(function(){
		return j('').html(j(this).html());
	});

	//add the classes and the wrappers
	panel.addClass('panel panel-default panel-docklands-fp');
	//panelTextNode.wrap('

');
	panelHeading.wrap('

');

	// Removing some stuff that isnt needed
	panel.find('br').remove();
	unwrap.children().unwrap();
	//j('.panel .panel-body p').is(':empty').remove();
	panel.removeClass('ep_toolbox').addClass('frontpage-panel');

});

<|endoftext|>


<commit_before>
simply.text({ title: 'Address', body: 'Resolving... please wait' });

function showResults(data) {
	var roadaddr = data.address.road;
	if(data.address.house) {
		roadaddr = roadaddr + ' ' + data.address.house;
	}
	var msg = roadaddr + '\n' +
		data.address.suburb + ' / ' + data.address.city_district + '\n' +
		data.address.postcode + '  ' + data.address.city;
	simply.body(msg);
    simply.scrollable(true);
}

navigator.geolocation.getCurrentPosition(function(pos) {
  var coords = pos.coords;
//&json_callback=showResults
  var reverseGeocodeUrl = 'http://open.mapquestapi.com/nominatim/v1/reverse.php?' +
  'format=json&units=metric' +
  '&lat=' + coords.latitude +
  '&lon=' + coords.longitude;
  ajax({ url: reverseGeocodeUrl, type: 'json' }, showResults);
},function(err) {
	simply.body('Error resolving location');
}, {
  enableHighAccuracy: true,
  timeout: 60000,
  maximumAge: 0
});<commit_msg>Move scrollable to start<commit_after>
simply.text({ title: 'Address', body: 'Resolving... please wait' });
simply.scrollable(true);

function showResults(data) {
	var roadaddr = data.address.road;
	if(data.address.house) {
		roadaddr = roadaddr + ' ' + data.address.house;
	}
	var msg = roadaddr + '\n' +
		data.address.suburb + ' / ' + data.address.city_district + '\n' +
		data.address.postcode + '  ' + data.address.city;
	simply.body(msg);
}

navigator.geolocation.getCurrentPosition(function(pos) {
  var coords = pos.coords;
//&json_callback=showResults
  var reverseGeocodeUrl = 'http://open.mapquestapi.com/nominatim/v1/reverse.php?' +
  'format=json&units=metric' +
  '&lat=' + coords.latitude +
  '&lon=' + coords.longitude;
  ajax({ url: reverseGeocodeUrl, type: 'json' }, showResults);
},function(err) {
	simply.body('Error resolving location');
}, {
  enableHighAccuracy: true,
  timeout: 60000,
  maximumAge: 0
});<|endoftext|>


<commit_before>/*
 * This adds a geocoder powered by pelias to a leaflet map
 * TODO: Better comments
 */

L.Control.Geocoder = L.Control.extend({
  options: {
    position: 'topleft',
    attribution: 'Geocoding by Pelias',
    url: '//pelias.mapzen.com',
    placeholder: 'Search',
    title: 'Search',
    bbox: false,
    latlon: null,
    layers: 'poi,admin,address',
    point_icon: '/img/point_icon.png',
    polygon_icon: '/img/polygon_icon.png'
  },

  initialize: function (options) {
    L.Util.setOptions(this, options);
    this.marker;
    this.markers = [];

    this.throttle = L.Util.throttle ? L.Util.throttle : L.Util.limitExecByInterval;
  },

  getLayers: function (params) {
    var layers = this.options.layers;

    if ( !layers ) {
      return params;
    }

    params.layers = layers;
    return params;
  },

  getBoundingBoxParam: function (params) {
    var bbox= this.options.bbox;

    if ( !bbox ) {
      return params;
    }

    if ( (typeof bbox !== 'object') || !bbox.isValid() ) {
      bbox = this._map.getBounds();
    }

    var bbox_center  = bbox.getCenter();
    params.bbox = bbox.toBBoxString();
    params.lat  = bbox_center.lat;
    params.lon  = bbox_center.lng;
    return params;
  },

  getLatLonParam: function (params) {
    /*
     * this.options.latlon can be one of the following
     * [50, 30] //Array
     * {lon: 30, lat: 50} //Object
     * {lat: 50, lng: 30} //Object
     * L.latLng(50, 30) //Object
     * true //Boolean - take the map center
     * false //Boolean - No latlon to be considered
    */
    var latlon= this.options.latlon;

    if ( !latlon ) {
      return params;
    }

    if (latlon.constructor === Array) {
      // TODO Check for array size, throw errors if invalid lat/lon
      params.lat = latlon[0];
      params.lon = latlon[1];
    } else if (typeof latlon !== 'object') {
      // fallback to the map's center L.latLng()
      latlon = this._map.getCenter();
    } else {
      // TODO Check for valid L.LatLng Object or Object thats in the form of {lat:..,lon:..}
      // TODO Check for valid lat/lon values, Error handling
      params.lat = latlon.lat;
      params.lon = latlon.lng ? latlon.lng : latlon.lon;
    }
    return params;
  },

  search: function(input) {
    var url = this.options.url + '/search';
    var params = {
      input: input
    };

    this.callPelias(url, params);
  },

  suggest: function(input) {
    var url = this.options.url + '/suggest';

    // TODO make geo context optional (with completion suggester v2)
    // /suggest while typing requires lat/lon
    // https://github.com/elasticsearch/elasticsearch/issues/6444
    // https://github.com/elastic/elasticsearch/issues/10746
    var geo = this._map.getCenter();

    var params = {
      input: input,
      lat: geo.lat,
      lon: geo.lng
    };

    this.callPelias(url, params);
  },

  callPelias: function(endpoint, params) {
    params = this.getBoundingBoxParam( params );
    params = this.getLatLonParam( params );
    params = this.getLayers( params );

    // Since we always use properties.text we dont need the details
    // See https://github.com/pelias/api/releases/tag/1.2.0
    params.details = false;

    L.DomUtil.addClass(this._input, 'pelias-loading');

    AJAX.request(endpoint, params, function(err, results) {
      if (results && results.features) {
        L.DomUtil.removeClass(this._input, 'pelias-loading');
        this.showResults(results.features);
      }
    }, this);
  },

  highlight: function( text, focus ){
    var r = RegExp( '('+ focus + ')', 'gi' );
    return text.replace( r, '$1' );
  },

  getMeta: function( type ) {
    var point_icon = this.options.point_icon;
    var polygon_icon = this.options.polygon_icon;

    if( type.match('geoname') ){
      return { icon: point_icon, title: 'source: geonames'};
    } else if( type.match('osm') ||
               type.match('osmway')  ||
               type.match('osmnode') ||
               type.match('osmaddress')){
      return { icon: point_icon, title: 'source: openstreetmap'};
    } else if( type.match('admin0') ||
               type.match('admin1') ||
               type.match('admin2') ||
               type.match('locality') ||
               type.match('neighborhood') ||
               type.match('local_admin') ){
      return { icon: polygon_icon, title: 'source: quattroshapes'};
    } else if( type.match('openaddresses') ){
      return { icon: point_icon, title: 'source: openaddresses'};
    }
    return { icon: point_icon, title: 'source: default'};
  },

  showResults: function(features) {
    var list;
    var self = this;
    var results_container = this._results;
    results_container.innerHTML = '';
    results_container.style.display = 'block';
    // manage result box height
    results_container.style.maxHeight = (this._map.getSize().y - results_container.offsetTop - this._container.offsetTop - 10) + 'px';

    features.forEach( function( feature ){
      if(!list) {
        list = L.DomUtil.create('ul', 'pelias-list', results_container);
      }

      var result_item = L.DomUtil.create('li', 'pelias-result', list);
      var result_meta = self.getMeta(feature.properties.layer);

      result_item.layer  = feature.properties.layer;
      result_item.coords = feature.geometry.coordinates;

      var layer_icon_con = L.DomUtil.create('span', 'layer_icon_container', result_item);
      var layer_icon     = L.DomUtil.create('img', 'layer_icon', layer_icon_con);
      layer_icon.src  = result_meta.icon;
      layer_icon.title= result_meta.title;
      result_item.innerHTML += self.highlight(feature.properties.text, self._input.value);
    });
  },

  removeMarkers: function() {
    for (i=0; i<this.markers.length; i++) {
      this._map.removeLayer(this.markers[i]);
    }
    this.markers = [];
  },

  showMarker: function(text, coords) {
    this.removeMarkers();

    var geo = [coords[1], coords[0]];
    this._map.setView( geo, this._map.getZoom() || 8 );

    this.marker = new L.marker(geo).bindPopup(text);
    this._map.addLayer(this.marker);
    this.markers.push(this.marker);
    this.marker.openPopup();
  },

  clear: function(){
    this._results.style.display = 'none';
    // this._results.innerHTML = '';
    // this._input.value = '';
    // this._input.placeholder = '';
    // this._input.blur();

    // L.DomUtil.removeClass(this._container, 'pelias-expanded');
  },

  onAdd: function (map) {
    var container = L.DomUtil.create('div',
        'pelias-control leaflet-bar leaflet-control');

    var self = this;
    this._layer = new L.LayerGroup();
    this._layer.addTo(map);

    this._container = container;

    this._input = L.DomUtil.create('input', 'pelias-input leaflet-bar', this._container);
    this._input.title = this.options.title;

    this._results = L.DomUtil.create('div', 'pelias-results leaflet-bar', this._container);

    L.DomEvent
      .on(this._input, 'focus', function(e){
          this._input.placeholder = this.options.placeholder;
          this._results.style.display = 'block';
          L.DomUtil.addClass(this._container, 'pelias-expanded');
        }, this)
      .on(this._container, 'click', function(e){
          this._input.focus();
        }, this)
      .on(this._input, 'blur', function(e){
          this.clear();
        }, this)
      .on(this._input, 'keydown', function(e){
          var list = this._results.querySelectorAll('.' + 'pelias-result');
          var selected = this._results.querySelectorAll('.' + 'pelias-selected')[0];
          var selectedPosition;

          for (var i = 0; i < list.length; i++) {
            if(list[i] === selected){
              selectedPosition = i;
              break;
            }
          }

          // TODO cleanup
          switch(e.keyCode) {
            // 13 = enter
            case 13:
              if(selected){
                this.showMarker(selected.innerHTML, selected['coords']);
                this.clear();
              } else {
                // perform a full text search on enter
                var text = (e.target || e.srcElement).value;
                this.search(text);
              }
              L.DomEvent.preventDefault(e);
              break;
            // 38 = up arrow
            case 38:
              if(selected){
                L.DomUtil.removeClass(selected, 'pelias-selected');
              }

              var previousItem = list[selectedPosition-1];

              if(selected && previousItem) {
                L.DomUtil.addClass(previousItem, 'pelias-selected');
              } else {
                L.DomUtil.addClass(list[list.length-1], 'pelias-selected');
              }
              L.DomEvent.preventDefault(e);
              break;
            // 40 = down arrow
            case 40:
              if(selected){
                L.DomUtil.removeClass(selected, 'pelias-selected');
              }

              var nextItem = list[selectedPosition+1];

              if(selected && nextItem) {
                L.DomUtil.addClass(nextItem, 'pelias-selected');
              } else {
                L.DomUtil.addClass(list[0], 'pelias-selected');
              }
              L.DomEvent.preventDefault(e);
              break;
            // all other keys
            default:
              break;
          }
        }, this)
      .on(this._input, 'keyup', this.throttle(function(e){
          var key = e.which || e.keyCode;
          var text = (e.target || e.srcElement).value;

          // minimum 3 characters for suggestions
          // keyCode 27 = esc key (esc should clear results)
          if(text.length < 2 || key === 27) {
            this._results.innerHTML = '';
            this._results.style.display = 'none';
            L.DomUtil.removeClass(this._input, 'pelias-loading');
            return;
          }

          if(key !== 13 && key !== 38 && key !== 40){
            if(this._input.value !== this._lastValue){
              this._lastValue = this._input.value;
              this.suggest(text);
            }
          }
        }, 50, this), this)
      .on(this._results, 'mousedown', function(e){
          var selected = e.target;
          this.showMarker(selected.innerHTML, selected['coords']);
          this.clear();
          L.DomEvent.preventDefault(e);
        }, this)
      .on(this._results, 'mouseover', function(e){
          if(map.scrollWheelZoom.enabled() && map.options.scrollWheelZoom){
            map.scrollWheelZoom.disable();
          }
        })
      .on(this._results, 'mouseout', function(e){
          if(!map.scrollWheelZoom.enabled() && map.options.scrollWheelZoom){
            map.scrollWheelZoom.enable();
          }
        });

    L.DomEvent.disableClickPropagation(this._container);
    if (map.attributionControl) {
      map.attributionControl.addAttribution(this.options.attribution);
    }
    return container;
  },

  onRemove: function (map) {
    map.attributionControl.removeAttribution(this.options.attribution);
  }
});

L.control.geocoder = function (options) {
  return new L.Control.Geocoder(options);
};

/*
 * AJAX Utitity function (implements basic HTTP get)
 * TODO check for maximum length for a GET req
 * TODO alternatively POST if GET cannot be done
 * TODO fallback to JSONP if CORS isnt supported
 */
var AJAX = {
  serialize: function(params) {
    var data = '';

    for (var key in params){
      if(params.hasOwnProperty(key)){
        var param = params[key];
        var type = param.toString();
        var value;

        if(data.length){
          data += '&';
        }

        switch(type) {
          case '[object Array]':
            value = (param[0].toString() === '[object Object]') ? JSON.stringify(param) : param.join(',');
            break;
          case '[object Object]':
            value = JSON.stringify(param);
            break;
          case '[object Date]':
            value = param.valueOf();
            break;
          default:
            value = param;
            break;
        }

        data += encodeURIComponent(key) + '=' + encodeURIComponent(value);
      }
    }

    return data;
  },
  http_request: function(callback, context){
    var httpRequest = new XMLHttpRequest();

    httpRequest.onerror = function(e) {
      httpRequest.onreadystatechange = L.Util.falseFn;

      callback.call(context, {
        error: {
          code: 500,
          message: 'XMLHttpRequest Error'
        }
      }, null);
    };

    httpRequest.onreadystatechange = function(){
      var response;
      var error;

      if (httpRequest.readyState === 4) {
        try {
          response = JSON.parse(httpRequest.responseText);
        } catch(e) {
          response = null;
          error = {
            code: 500,
            message: 'Parse Error'
          };
        }

        if (!error && response.error) {
          error = response.error;
          response = null;
        }

        httpRequest.onerror = L.Util.falseFn;

        callback.call(context, error, response);
      }
    };

    return httpRequest;
  },
  request: function(url, params, callback, context) {
    var paramString   = this.serialize(params);
    var httpRequest   = this.http_request(callback, context);

    httpRequest.open('GET', url + '?' + paramString);
    httpRequest.send(null);
  }
}
<commit_msg>links fix<commit_after>/*
 * This adds a geocoder powered by pelias to a leaflet map
 * TODO: Better comments
 */

L.Control.Geocoder = L.Control.extend({
  options: {
    position: 'topleft',
    attribution: 'Geocoding by Pelias',
    url: '//pelias.mapzen.com',
    placeholder: 'Search',
    title: 'Search',
    bbox: false,
    latlon: null,
    layers: 'poi,admin,address',
    point_icon: 'img/point_icon.png',
    polygon_icon: 'img/polygon_icon.png'
  },

  initialize: function (options) {
    L.Util.setOptions(this, options);
    this.marker;
    this.markers = [];

    this.throttle = L.Util.throttle ? L.Util.throttle : L.Util.limitExecByInterval;
  },

  getLayers: function (params) {
    var layers = this.options.layers;

    if ( !layers ) {
      return params;
    }

    params.layers = layers;
    return params;
  },

  getBoundingBoxParam: function (params) {
    var bbox= this.options.bbox;

    if ( !bbox ) {
      return params;
    }

    if ( (typeof bbox !== 'object') || !bbox.isValid() ) {
      bbox = this._map.getBounds();
    }

    var bbox_center  = bbox.getCenter();
    params.bbox = bbox.toBBoxString();
    params.lat  = bbox_center.lat;
    params.lon  = bbox_center.lng;
    return params;
  },

  getLatLonParam: function (params) {
    /*
     * this.options.latlon can be one of the following
     * [50, 30] //Array
     * {lon: 30, lat: 50} //Object
     * {lat: 50, lng: 30} //Object
     * L.latLng(50, 30) //Object
     * true //Boolean - take the map center
     * false //Boolean - No latlon to be considered
    */
    var latlon= this.options.latlon;

    if ( !latlon ) {
      return params;
    }

    if (latlon.constructor === Array) {
      // TODO Check for array size, throw errors if invalid lat/lon
      params.lat = latlon[0];
      params.lon = latlon[1];
    } else if (typeof latlon !== 'object') {
      // fallback to the map's center L.latLng()
      latlon = this._map.getCenter();
    } else {
      // TODO Check for valid L.LatLng Object or Object thats in the form of {lat:..,lon:..}
      // TODO Check for valid lat/lon values, Error handling
      params.lat = latlon.lat;
      params.lon = latlon.lng ? latlon.lng : latlon.lon;
    }
    return params;
  },

  search: function(input) {
    var url = this.options.url + '/search';
    var params = {
      input: input
    };

    this.callPelias(url, params);
  },

  suggest: function(input) {
    var url = this.options.url + '/suggest';

    // TODO make geo context optional (with completion suggester v2)
    // /suggest while typing requires lat/lon
    // https://github.com/elasticsearch/elasticsearch/issues/6444
    // https://github.com/elastic/elasticsearch/issues/10746
    var geo = this._map.getCenter();

    var params = {
      input: input,
      lat: geo.lat,
      lon: geo.lng
    };

    this.callPelias(url, params);
  },

  callPelias: function(endpoint, params) {
    params = this.getBoundingBoxParam( params );
    params = this.getLatLonParam( params );
    params = this.getLayers( params );

    // Since we always use properties.text we dont need the details
    // See https://github.com/pelias/api/releases/tag/1.2.0
    params.details = false;

    L.DomUtil.addClass(this._input, 'pelias-loading');

    AJAX.request(endpoint, params, function(err, results) {
      if (results && results.features) {
        L.DomUtil.removeClass(this._input, 'pelias-loading');
        this.showResults(results.features);
      }
    }, this);
  },

  highlight: function( text, focus ){
    var r = RegExp( '('+ focus + ')', 'gi' );
    return text.replace( r, '$1' );
  },

  getMeta: function( type ) {
    var point_icon = this.options.point_icon;
    var polygon_icon = this.options.polygon_icon;

    if( type.match('geoname') ){
      return { icon: point_icon, title: 'source: geonames'};
    } else if( type.match('osm') ||
               type.match('osmway')  ||
               type.match('osmnode') ||
               type.match('osmaddress')){
      return { icon: point_icon, title: 'source: openstreetmap'};
    } else if( type.match('admin0') ||
               type.match('admin1') ||
               type.match('admin2') ||
               type.match('locality') ||
               type.match('neighborhood') ||
               type.match('local_admin') ){
      return { icon: polygon_icon, title: 'source: quattroshapes'};
    } else if( type.match('openaddresses') ){
      return { icon: point_icon, title: 'source: openaddresses'};
    }
    return { icon: point_icon, title: 'source: default'};
  },

  showResults: function(features) {
    var list;
    var self = this;
    var results_container = this._results;
    results_container.innerHTML = '';
    results_container.style.display = 'block';
    // manage result box height
    results_container.style.maxHeight = (this._map.getSize().y - results_container.offsetTop - this._container.offsetTop - 10) + 'px';

    features.forEach( function( feature ){
      if(!list) {
        list = L.DomUtil.create('ul', 'pelias-list', results_container);
      }

      var result_item = L.DomUtil.create('li', 'pelias-result', list);
      var result_meta = self.getMeta(feature.properties.layer);

      result_item.layer  = feature.properties.layer;
      result_item.coords = feature.geometry.coordinates;

      var layer_icon_con = L.DomUtil.create('span', 'layer_icon_container', result_item);
      var layer_icon     = L.DomUtil.create('img', 'layer_icon', layer_icon_con);
      layer_icon.src  = result_meta.icon;
      layer_icon.title= result_meta.title;
      result_item.innerHTML += self.highlight(feature.properties.text, self._input.value);
    });
  },

  removeMarkers: function() {
    for (i=0; i<this.markers.length; i++) {
      this._map.removeLayer(this.markers[i]);
    }
    this.markers = [];
  },

  showMarker: function(text, coords) {
    this.removeMarkers();

    var geo = [coords[1], coords[0]];
    this._map.setView( geo, this._map.getZoom() || 8 );

    this.marker = new L.marker(geo).bindPopup(text);
    this._map.addLayer(this.marker);
    this.markers.push(this.marker);
    this.marker.openPopup();
  },

  clear: function(){
    this._results.style.display = 'none';
    // this._results.innerHTML = '';
    // this._input.value = '';
    // this._input.placeholder = '';
    // this._input.blur();

    // L.DomUtil.removeClass(this._container, 'pelias-expanded');
  },

  onAdd: function (map) {
    var container = L.DomUtil.create('div',
        'pelias-control leaflet-bar leaflet-control');

    var self = this;
    this._layer = new L.LayerGroup();
    this._layer.addTo(map);

    this._container = container;

    this._input = L.DomUtil.create('input', 'pelias-input leaflet-bar', this._container);
    this._input.title = this.options.title;

    this._results = L.DomUtil.create('div', 'pelias-results leaflet-bar', this._container);

    L.DomEvent
      .on(this._input, 'focus', function(e){
          this._input.placeholder = this.options.placeholder;
          this._results.style.display = 'block';
          L.DomUtil.addClass(this._container, 'pelias-expanded');
        }, this)
      .on(this._container, 'click', function(e){
          this._input.focus();
        }, this)
      .on(this._input, 'blur', function(e){
          this.clear();
        }, this)
      .on(this._input, 'keydown', function(e){
          var list = this._results.querySelectorAll('.' + 'pelias-result');
          var selected = this._results.querySelectorAll('.' + 'pelias-selected')[0];
          var selectedPosition;

          for (var i = 0; i < list.length; i++) {
            if(list[i] === selected){
              selectedPosition = i;
              break;
            }
          }

          // TODO cleanup
          switch(e.keyCode) {
            // 13 = enter
            case 13:
              if(selected){
                this.showMarker(selected.innerHTML, selected['coords']);
                this.clear();
              } else {
                // perform a full text search on enter
                var text = (e.target || e.srcElement).value;
                this.search(text);
              }
              L.DomEvent.preventDefault(e);
              break;
            // 38 = up arrow
            case 38:
              if(selected){
                L.DomUtil.removeClass(selected, 'pelias-selected');
              }

              var previousItem = list[selectedPosition-1];

              if(selected && previousItem) {
                L.DomUtil.addClass(previousItem, 'pelias-selected');
              } else {
                L.DomUtil.addClass(list[list.length-1], 'pelias-selected');
              }
              L.DomEvent.preventDefault(e);
              break;
            // 40 = down arrow
            case 40:
              if(selected){
                L.DomUtil.removeClass(selected, 'pelias-selected');
              }

              var nextItem = list[selectedPosition+1];

              if(selected && nextItem) {
                L.DomUtil.addClass(nextItem, 'pelias-selected');
              } else {
                L.DomUtil.addClass(list[0], 'pelias-selected');
              }
              L.DomEvent.preventDefault(e);
              break;
            // all other keys
            default:
              break;
          }
        }, this)
      .on(this._input, 'keyup', this.throttle(function(e){
          var key = e.which || e.keyCode;
          var text = (e.target || e.srcElement).value;

          // minimum 3 characters for suggestions
          // keyCode 27 = esc key (esc should clear results)
          if(text.length < 2 || key === 27) {
            this._results.innerHTML = '';
            this._results.style.display = 'none';
            L.DomUtil.removeClass(this._input, 'pelias-loading');
            return;
          }

          if(key !== 13 && key !== 38 && key !== 40){
            if(this._input.value !== this._lastValue){
              this._lastValue = this._input.value;
              this.suggest(text);
            }
          }
        }, 50, this), this)
      .on(this._results, 'mousedown', function(e){
          var selected = e.target;
          this.showMarker(selected.innerHTML, selected['coords']);
          this.clear();
          L.DomEvent.preventDefault(e);
        }, this)
      .on(this._results, 'mouseover', function(e){
          if(map.scrollWheelZoom.enabled() && map.options.scrollWheelZoom){
            map.scrollWheelZoom.disable();
          }
        })
      .on(this._results, 'mouseout', function(e){
          if(!map.scrollWheelZoom.enabled() && map.options.scrollWheelZoom){
            map.scrollWheelZoom.enable();
          }
        });

    L.DomEvent.disableClickPropagation(this._container);
    if (map.attributionControl) {
      map.attributionControl.addAttribution(this.options.attribution);
    }
    return container;
  },

  onRemove: function (map) {
    map.attributionControl.removeAttribution(this.options.attribution);
  }
});

L.control.geocoder = function (options) {
  return new L.Control.Geocoder(options);
};

/*
 * AJAX Utitity function (implements basic HTTP get)
 * TODO check for maximum length for a GET req
 * TODO alternatively POST if GET cannot be done
 * TODO fallback to JSONP if CORS isnt supported
 */
var AJAX = {
  serialize: function(params) {
    var data = '';

    for (var key in params){
      if(params.hasOwnProperty(key)){
        var param = params[key];
        var type = param.toString();
        var value;

        if(data.length){
          data += '&';
        }

        switch(type) {
          case '[object Array]':
            value = (param[0].toString() === '[object Object]') ? JSON.stringify(param) : param.join(',');
            break;
          case '[object Object]':
            value = JSON.stringify(param);
            break;
          case '[object Date]':
            value = param.valueOf();
            break;
          default:
            value = param;
            break;
        }

        data += encodeURIComponent(key) + '=' + encodeURIComponent(value);
      }
    }

    return data;
  },
  http_request: function(callback, context){
    var httpRequest = new XMLHttpRequest();

    httpRequest.onerror = function(e) {
      httpRequest.onreadystatechange = L.Util.falseFn;

      callback.call(context, {
        error: {
          code: 500,
          message: 'XMLHttpRequest Error'
        }
      }, null);
    };

    httpRequest.onreadystatechange = function(){
      var response;
      var error;

      if (httpRequest.readyState === 4) {
        try {
          response = JSON.parse(httpRequest.responseText);
        } catch(e) {
          response = null;
          error = {
            code: 500,
            message: 'Parse Error'
          };
        }

        if (!error && response.error) {
          error = response.error;
          response = null;
        }

        httpRequest.onerror = L.Util.falseFn;

        callback.call(context, error, response);
      }
    };

    return httpRequest;
  },
  request: function(url, params, callback, context) {
    var paramString   = this.serialize(params);
    var httpRequest   = this.http_request(callback, context);

    httpRequest.open('GET', url + '?' + paramString);
    httpRequest.send(null);
  }
}
<|endoftext|>


<commit_before>'use strict';

const { Component, PropTypes } = require('react');
const { bind, hasValueProp, indexOf } = require('../tool/component');
const { classNames, composition } = require('../tool/className');
const { constant } = require('../tool/func');
const { findDOMNode } = require('react-dom');
const { generateId, hasUniqueValues, mapKey, mapKeyBasedOnPos } = require('../tool/identity');
const { isUndefined, noop } = require('../tool/func');
const Option = require('./Option');
const Overlay = require('./Overlay');
const React = require('react');
const fuzzysearch = require('fuzzysearch');
const reactOutsideEvent = require('../mixin/ReactOutsideEvent');
const warning = require('../tool/warning');

var didWarnForDefaultValue = false;

class Select extends Component {
  constructor(props) {
    super(props);

    bind(this, [
      'onControlBlur',
      'onControlFocus',
      'onInputChange',
      'onKeyDown',
      'onMenuToggle',
      'onOptionFocus',
      'onOptionSelect',
    ]);

    this.controlled = hasValueProp(props);

    if (process.env.NODE_ENV !== 'production' && this.controlled && !didWarnForDefaultValue) { // eslint-disable-line no-undef
      warning(isUndefined(props.defaultValue),
        'Select elements must be either controlled or uncontrolled ' +
        '(specify either the value prop, or the defaultValue prop, but not ' +
        'both). Decide between using a controlled or uncontrolled select ' +
        'element and remove one of these props. More info: ' +
        'https://fb.me/react-controlled-components');

      didWarnForDefaultValue = true;
    }

    this.updateKeyMapper(props.hasUniqValues, props.options);

    var value = this.controlled
      ? props.value
      : props.defaultValue;

    var selected = !isUndefined(value)
      ? indexOf(props.options, value)
      : 0; // in case of uncontrolled component

    this.state = {
      focused: -1,
      inFocus: false,
      inputValue: '',
      isOpened: false,
      prefix: generateId(),
      selected,
    };
  }

  closeMenu() {
    this.setState({
      isOpened: false,
      focused: -1,
      inputValue: '',
    });
  }

  openMenu() {
    this.setState({
      isOpened: true,
      focused: this.state.selected,
    });
  }

  componentDidUpdate() {
    if (this.refs.menu && this.refs.selected && this.state.isOpened && !this.wereOptionsShown) {
      this.wereOptionsShown = true;

      const menu = findDOMNode(this.refs.menu);
      const selected = findDOMNode(this.refs.selected);
      menu.scrollTop = selected.offsetTop;
    } else if (!this.state.isOpened) {
      this.wereOptionsShown = false;
    }

    if (this.wasKeyPressed && this.refs.menu && this.refs.selected) {
      this.wasKeyPressed = false;

      const menu = findDOMNode(this.refs.menu);
      const selected = findDOMNode(this.refs.selected);
      const menuRect = menu.getBoundingClientRect();
      const selectedRect = selected.getBoundingClientRect();
      if (selectedRect.bottom > menuRect.bottom || selectedRect.top < menuRect.top) {
        menu.scrollTop = selected.offsetTop + selected.clientHeight - menu.offsetHeight;
      }
    }
  }

  componentWillReceiveProps({ hasUniqValues, options, value }) {
    if (this.controlled) {
      this.setState({
        selected: indexOf(options, value),
      });
    }

    if (this.props.hasUniqValues !== hasUniqValues) {
      this.updateKeyMapper(hasUniqValues, options);
    }
  }

  focus() {
    if (this.refs.label) {
      this.refs.label.focus();
    }
  }

  focusNextOption() {
    const nextFocused = this.state.focused + 1;
    if (nextFocused === this.props.options.length) return;
    this.wasKeyPressed = true;
    this.setState({focused: nextFocused});
  }

  focusPreviousOption() {
    const { focused } = this.state;
    if (focused === 0) return;
    this.wasKeyPressed = true;
    this.setState({focused: focused === -1
      ? this.props.options.length - 1
      : focused - 1});
  }

  /**
   * @param  {object} option
   * @param  {string} option.label
   * @return {string}
   */
  getHaystack(option) {
    return option.label;
  }

  /**
   * @param  {number} selected
   * @return {string}
   */
  getSelectedLabel(selected) {
    return selected !== -1
      ? this.props.options[selected].label
      : this.props.placeholder;
  }

  /**
   * @param  {number} selected
   * @return {string}
   */
  getSelectedValue(selected) {
    return selected !== -1
      ? this.props.options[selected].value
      : '';
  }

  onControlBlur() {}

  onControlFocus() {
    if (this._openAfterFocus !== false) {
      return void this.setState({
        isOpened: true,
      });
    }

    this.__openAfterFocus = true;
  }

  onInputChange(e) {
    this.setState({
      inputValue: e.target.value,
      isOpened: true,
    });
  }

  onKeyDown(e) {
    if (this.props.disabled) return;

    const { isOpened } = this.state;

    switch (e.keyCode) {
    case 9: // tab
      if (!isOpened) return;
      return void this.closeMenu();

    case 13: // enter
      if (!isOpened) return;
      e.stopPropagation();
      this.updateValue(e, this.state.focused);
      break;

    case 27: // esc
      if (!isOpened) return;
      this.closeMenu();
      this.focus();
      break;

    case 32: // space
      if (this.props.isSearchable) return;

      if (!isOpened) {
        this.openMenu();
      } else {
        this.updateValue(e, this.state.focused);
      }

      break;

    case 38: // up
      if (!isOpened) {
        this.openMenu();
      } else {
        this.focusPreviousOption();
      }

      break;

    case 40: // down
      if (!isOpened) {
        this.openMenu();
      } else {
        this.focusNextOption();
      }

      break;

    default:
      return;
    }

    e.preventDefault();
  }

  onMenuToggle() {
    if (this.state.isOpened) {
      return void this.closeMenu();
    }

    return void this.openMenu();
  }

  /**
   * @param {object} e
   * @param {*} _
   * @param {number} tc
   */
  onOptionFocus(e, _, tc) {
    if (this.state.focused === tc) return;
    this.setState({focused: tc});
  }

  /**
   * @param {object} e
   * @param {*} _
   * @param {number} tc
   */
  onOptionSelect(e, _, tc) {
    this._openAfterFocus = false;
    this.updateValue(e, tc);
    this.focus();
  }

  onOutsideEvent() {
    this._openAfterFocus = true;
    if (!this.state.isOpened) return;
    this.closeMenu();
  }

  /**
   * @param {boolean} hasUniqValues
   * @param {object[]} options
   */
  updateKeyMapper(hasUniqValues, options) {
    this.mapKey = !(hasUniqValues && hasUniqueValues(options))
      ? mapKeyBasedOnPos
      : mapKey;
  }

  /**
   * @param {object} e
   * @param {number} nextSelected
   */
  updateValue(e, nextSelected) {
    const nextState = {isOpened: false};

    if (nextSelected === -1 || nextSelected === this.state.selected) {
      return void this.setState(nextState);
    }

    if (!this.controlled) {
      nextState.selected = nextSelected;
    }

    if (this.props.isSearchable) {
      nextState.inputValue = '';
    }

    this.setState(nextState);
    this.props.onChange(e, {value: this.props.options[nextSelected].value});
  }

  render() {
    return (

        {this.renderValue()}
        {this.renderLabel()}
        {this.renderMenu()}

    );
  }

  renderLabel() {
    const { styles } = this.props;

    if (!this.props.isSearchable) {
      return (
        <button
          className={classNames(styles.control, {
            [styles.isClosedControl]: !this.state.isOpened,
            [styles.isOpenedControl]: this.state.isOpened,
          })}
          disabled={this.props.disabled}
          onClick={this.onMenuToggle}
          onKeyDown={this.onKeyDown}
          ref='label'
          tabIndex={this.props.tabIndex || 0}>
          {this.getSelectedLabel(this.state.selected)}
        </button>
      );
    }

    return (

        {this.state.inputValue ? '' : this.getSelectedLabel(this.state.selected)}
        <input
          className={this.props.styles.input}
          disabled={this.props.disabled}
          onBlur={this.onControlBlur}
          onChange={this.onInputChange}
          onFocus={this.onControlFocus}
          onKeyDown={this.onKeyDown}
          ref='label'
          tabIndex={this.props.tabIndex || 0}
          type='text'
          value={this.state.inputValue}/>

    );
  }

  renderMenu() {
    const { styles } = this.props;

    return (
      <Overlay
        className={classNames(styles.menu, {
          [styles.isFixedMenu]: this.props.isFixed,
          [styles.isClosedMenu]: !this.state.isOpened,
          [styles.isOpenedMenu]: this.state.isOpened,
        })}
        ref='menu'>
        {this.renderOptions()}
      </Overlay>
    );
  }

  /**
   * @param  {option} option
   * @return {string}
   */
  renderOption(option) {
    return option.label;
  }

  renderOptions() {
    if (!this.state.isOpened) {
      return null;
    }

    const { isFixed, isSearchable, options, styles } = this.props;
    const { focused, prefix, selected } = this.state;
    const inputValue = this.state.inputValue.toLowerCase();
    const filter = isSearchable
      ? fuzzysearch
      : constant(true);

    const getHaystack = this.props.getHaystack || this.getHaystack;
    const renderOption = this.props.renderOption || this.renderOption;
    const list = [];

    for (var length = options.length, i = 0; i < length; ++i) {
      const option = options[i];

      if (!filter(inputValue, getHaystack(option).toLowerCase())) {
        continue;
      }

      const isFocused = focused === i;
      const isSelected = selected === i;
      const ref = isFocused
        ? 'selected'
        : null;

      list.push((
        <Option
          {...option}
          className={classNames(styles.item, {
            [styles.isFixedItem]: isFixed,
            [styles.isFocusedItem]: isFocused,
            [styles.isSelectedItem]: isSelected,
          })}
          isFocused={isFocused}
          key={this.mapKey(prefix, option.value, i)}
          onFocus={this.onOptionFocus}
          onSelect={this.onOptionSelect}
          ref={ref}
          tc={i}>
          {renderOption(option)}
        </Option>
      ));
    }

    if (isSearchable && list.length === 0) {
      list.push((
        <Option
          className={styles.empty}>
          {this.props.noResults}
        </Option>
      ));
    }

    return list;
  }

  renderValue() {
    return (
      <input
        className={this.props.styles.native}
        disabled={this.props.disabled}
        name={this.props.name}
        type='hidden'
        value={this.getSelectedValue(this.state.selected)}/>
    );
  }
}

Select.defaultProps = {
  hasUniqValues: true,
  isFixed: true,
  isSearchable: false,
  noResults: 'No results found',
  onChange: noop,
  placeholder: '—',
  styleName: 'wrapper',
  styles: {},
};

Select.propTypes = {
  getHaystack: PropTypes.func,
  hasUniqValues: PropTypes.bool,
  isFixed: PropTypes.bool,
  isSearchable: PropTypes.bool,
  name: PropTypes.string.isRequired,
  noResults: PropTypes.string,
  onChange: PropTypes.func,
  options: PropTypes.array,
  placeholder: PropTypes.string,
  renderOption: PropTypes.func,
  styleName: PropTypes.string,
  styles: PropTypes.shape({
    control: PropTypes.string.isRequired,
    input: PropTypes.string.isRequired,
    isClosedControl: PropTypes.string.isRequired,
    isClosedMenu: PropTypes.string.isRequired,
    isFixedItem: PropTypes.string.isRequired,
    isFixedMenu: PropTypes.string.isRequired,
    isFocusedItem: PropTypes.string.isRequired,
    isOpenedControl: PropTypes.string.isRequired,
    isOpenedMenu: PropTypes.string.isRequired,
    isSelectedItem: PropTypes.string.isRequired,
    item: PropTypes.string.isRequired,
    menu: PropTypes.string.isRequired,
    wrapper: PropTypes.string,
  }),
};

module.exports = reactOutsideEvent(Select, ['click']);
<commit_msg>added missing types<commit_after>'use strict';

const { Component, PropTypes } = require('react');
const { bind, hasValueProp, indexOf } = require('../tool/component');
const { classNames, composition } = require('../tool/className');
const { constant } = require('../tool/func');
const { findDOMNode } = require('react-dom');
const { generateId, hasUniqueValues, mapKey, mapKeyBasedOnPos } = require('../tool/identity');
const { isUndefined, noop } = require('../tool/func');
const Option = require('./Option');
const Overlay = require('./Overlay');
const React = require('react');
const fuzzysearch = require('fuzzysearch');
const reactOutsideEvent = require('../mixin/ReactOutsideEvent');
const warning = require('../tool/warning');

var didWarnForDefaultValue = false;

class Select extends Component {
  constructor(props) {
    super(props);

    bind(this, [
      'onControlBlur',
      'onControlFocus',
      'onInputChange',
      'onKeyDown',
      'onMenuToggle',
      'onOptionFocus',
      'onOptionSelect',
    ]);

    this.controlled = hasValueProp(props);

    if (process.env.NODE_ENV !== 'production' && this.controlled && !didWarnForDefaultValue) { // eslint-disable-line no-undef
      warning(isUndefined(props.defaultValue),
        'Select elements must be either controlled or uncontrolled ' +
        '(specify either the value prop, or the defaultValue prop, but not ' +
        'both). Decide between using a controlled or uncontrolled select ' +
        'element and remove one of these props. More info: ' +
        'https://fb.me/react-controlled-components');

      didWarnForDefaultValue = true;
    }

    this.updateKeyMapper(props.hasUniqValues, props.options);

    var value = this.controlled
      ? props.value
      : props.defaultValue;

    var selected = !isUndefined(value)
      ? indexOf(props.options, value)
      : 0; // in case of uncontrolled component

    this.state = {
      focused: -1,
      inFocus: false,
      inputValue: '',
      isOpened: false,
      prefix: generateId(),
      selected,
    };
  }

  closeMenu() {
    this.setState({
      isOpened: false,
      focused: -1,
      inputValue: '',
    });
  }

  openMenu() {
    this.setState({
      isOpened: true,
      focused: this.state.selected,
    });
  }

  componentDidUpdate() {
    if (this.refs.menu && this.refs.selected && this.state.isOpened && !this.wereOptionsShown) {
      this.wereOptionsShown = true;

      const menu = findDOMNode(this.refs.menu);
      const selected = findDOMNode(this.refs.selected);
      menu.scrollTop = selected.offsetTop;
    } else if (!this.state.isOpened) {
      this.wereOptionsShown = false;
    }

    if (this.wasKeyPressed && this.refs.menu && this.refs.selected) {
      this.wasKeyPressed = false;

      const menu = findDOMNode(this.refs.menu);
      const selected = findDOMNode(this.refs.selected);
      const menuRect = menu.getBoundingClientRect();
      const selectedRect = selected.getBoundingClientRect();
      if (selectedRect.bottom > menuRect.bottom || selectedRect.top < menuRect.top) {
        menu.scrollTop = selected.offsetTop + selected.clientHeight - menu.offsetHeight;
      }
    }
  }

  componentWillReceiveProps({ hasUniqValues, options, value }) {
    if (this.controlled) {
      this.setState({
        selected: indexOf(options, value),
      });
    }

    if (this.props.hasUniqValues !== hasUniqValues) {
      this.updateKeyMapper(hasUniqValues, options);
    }
  }

  focus() {
    if (this.refs.label) {
      this.refs.label.focus();
    }
  }

  focusNextOption() {
    const nextFocused = this.state.focused + 1;
    if (nextFocused === this.props.options.length) return;
    this.wasKeyPressed = true;
    this.setState({focused: nextFocused});
  }

  focusPreviousOption() {
    const { focused } = this.state;
    if (focused === 0) return;
    this.wasKeyPressed = true;
    this.setState({focused: focused === -1
      ? this.props.options.length - 1
      : focused - 1});
  }

  /**
   * @param  {object} option
   * @param  {string} option.label
   * @return {string}
   */
  getHaystack(option) {
    return option.label;
  }

  /**
   * @param  {number} selected
   * @return {string}
   */
  getSelectedLabel(selected) {
    return selected !== -1
      ? this.props.options[selected].label
      : this.props.placeholder;
  }

  /**
   * @param  {number} selected
   * @return {string}
   */
  getSelectedValue(selected) {
    return selected !== -1
      ? this.props.options[selected].value
      : '';
  }

  onControlBlur() {}

  onControlFocus() {
    if (this._openAfterFocus !== false) {
      return void this.setState({
        isOpened: true,
      });
    }

    this.__openAfterFocus = true;
  }

  onInputChange(e) {
    this.setState({
      inputValue: e.target.value,
      isOpened: true,
    });
  }

  onKeyDown(e) {
    if (this.props.disabled) return;

    const { isOpened } = this.state;

    switch (e.keyCode) {
    case 9: // tab
      if (!isOpened) return;
      return void this.closeMenu();

    case 13: // enter
      if (!isOpened) return;
      e.stopPropagation();
      this.updateValue(e, this.state.focused);
      break;

    case 27: // esc
      if (!isOpened) return;
      this.closeMenu();
      this.focus();
      break;

    case 32: // space
      if (this.props.isSearchable) return;

      if (!isOpened) {
        this.openMenu();
      } else {
        this.updateValue(e, this.state.focused);
      }

      break;

    case 38: // up
      if (!isOpened) {
        this.openMenu();
      } else {
        this.focusPreviousOption();
      }

      break;

    case 40: // down
      if (!isOpened) {
        this.openMenu();
      } else {
        this.focusNextOption();
      }

      break;

    default:
      return;
    }

    e.preventDefault();
  }

  onMenuToggle() {
    if (this.state.isOpened) {
      return void this.closeMenu();
    }

    return void this.openMenu();
  }

  /**
   * @param {object} e
   * @param {*} _
   * @param {number} tc
   */
  onOptionFocus(e, _, tc) {
    if (this.state.focused === tc) return;
    this.setState({focused: tc});
  }

  /**
   * @param {object} e
   * @param {*} _
   * @param {number} tc
   */
  onOptionSelect(e, _, tc) {
    this._openAfterFocus = false;
    this.updateValue(e, tc);
    this.focus();
  }

  onOutsideEvent() {
    this._openAfterFocus = true;
    if (!this.state.isOpened) return;
    this.closeMenu();
  }

  /**
   * @param {boolean} hasUniqValues
   * @param {object[]} options
   */
  updateKeyMapper(hasUniqValues, options) {
    this.mapKey = !(hasUniqValues && hasUniqueValues(options))
      ? mapKeyBasedOnPos
      : mapKey;
  }

  /**
   * @param {object} e
   * @param {number} nextSelected
   */
  updateValue(e, nextSelected) {
    const nextState = {isOpened: false};

    if (nextSelected === -1 || nextSelected === this.state.selected) {
      return void this.setState(nextState);
    }

    if (!this.controlled) {
      nextState.selected = nextSelected;
    }

    if (this.props.isSearchable) {
      nextState.inputValue = '';
    }

    this.setState(nextState);
    this.props.onChange(e, {value: this.props.options[nextSelected].value});
  }

  render() {
    return (

        {this.renderValue()}
        {this.renderLabel()}
        {this.renderMenu()}

    );
  }

  renderLabel() {
    const { styles } = this.props;

    if (!this.props.isSearchable) {
      return (
        <button
          className={classNames(styles.control, {
            [styles.isClosedControl]: !this.state.isOpened,
            [styles.isOpenedControl]: this.state.isOpened,
          })}
          disabled={this.props.disabled}
          onClick={this.onMenuToggle}
          onKeyDown={this.onKeyDown}
          ref='label'
          tabIndex={this.props.tabIndex || 0}>
          {this.getSelectedLabel(this.state.selected)}
        </button>
      );
    }

    return (

        {this.state.inputValue ? '' : this.getSelectedLabel(this.state.selected)}
        <input
          className={this.props.styles.input}
          disabled={this.props.disabled}
          onBlur={this.onControlBlur}
          onChange={this.onInputChange}
          onFocus={this.onControlFocus}
          onKeyDown={this.onKeyDown}
          ref='label'
          tabIndex={this.props.tabIndex || 0}
          type='text'
          value={this.state.inputValue}/>

    );
  }

  renderMenu() {
    const { styles } = this.props;

    return (
      <Overlay
        className={classNames(styles.menu, {
          [styles.isFixedMenu]: this.props.isFixed,
          [styles.isClosedMenu]: !this.state.isOpened,
          [styles.isOpenedMenu]: this.state.isOpened,
        })}
        ref='menu'>
        {this.renderOptions()}
      </Overlay>
    );
  }

  /**
   * @param  {option} option
   * @return {string}
   */
  renderOption(option) {
    return option.label;
  }

  renderOptions() {
    if (!this.state.isOpened) {
      return null;
    }

    const { isFixed, isSearchable, options, styles } = this.props;
    const { focused, prefix, selected } = this.state;
    const inputValue = this.state.inputValue.toLowerCase();
    const filter = isSearchable
      ? fuzzysearch
      : constant(true);

    const getHaystack = this.props.getHaystack || this.getHaystack;
    const renderOption = this.props.renderOption || this.renderOption;
    const list = [];

    for (var length = options.length, i = 0; i < length; ++i) {
      const option = options[i];

      if (!filter(inputValue, getHaystack(option).toLowerCase())) {
        continue;
      }

      const isFocused = focused === i;
      const isSelected = selected === i;
      const ref = isFocused
        ? 'selected'
        : null;

      list.push((
        <Option
          {...option}
          className={classNames(styles.item, {
            [styles.isFixedItem]: isFixed,
            [styles.isFocusedItem]: isFocused,
            [styles.isSelectedItem]: isSelected,
          })}
          isFocused={isFocused}
          key={this.mapKey(prefix, option.value, i)}
          onFocus={this.onOptionFocus}
          onSelect={this.onOptionSelect}
          ref={ref}
          tc={i}>
          {renderOption(option)}
        </Option>
      ));
    }

    if (isSearchable && list.length === 0) {
      list.push((
        <Option
          className={styles.empty}>
          {this.props.noResults}
        </Option>
      ));
    }

    return list;
  }

  renderValue() {
    return (
      <input
        className={this.props.styles.native}
        disabled={this.props.disabled}
        name={this.props.name}
        type='hidden'
        value={this.getSelectedValue(this.state.selected)}/>
    );
  }
}

Select.defaultProps = {
  hasUniqValues: true,
  isFixed: true,
  isSearchable: false,
  noResults: 'No results found',
  onChange: noop,
  placeholder: '—',
  styleName: 'wrapper',
  styles: {},
};

Select.propTypes = {
  getHaystack: PropTypes.func,
  hasUniqValues: PropTypes.bool,
  isFixed: PropTypes.bool,
  isSearchable: PropTypes.bool,
  name: PropTypes.string.isRequired,
  noResults: PropTypes.string,
  onChange: PropTypes.func,
  options: PropTypes.array,
  placeholder: PropTypes.string,
  renderOption: PropTypes.func,
  styleName: PropTypes.string,
  styles: PropTypes.shape({
    control: PropTypes.string.isRequired,
    empty: PropTypes.string.isRequired,
    input: PropTypes.string.isRequired,
    isClosedControl: PropTypes.string.isRequired,
    isClosedMenu: PropTypes.string.isRequired,
    isFixedItem: PropTypes.string.isRequired,
    isFixedMenu: PropTypes.string.isRequired,
    isFocusedItem: PropTypes.string.isRequired,
    isOpenedControl: PropTypes.string.isRequired,
    isOpenedMenu: PropTypes.string.isRequired,
    isSelectedItem: PropTypes.string.isRequired,
    item: PropTypes.string.isRequired,
    menu: PropTypes.string.isRequired,
    native: PropTypes.string.isRequired,
    wrapper: PropTypes.string,
  }),
};

module.exports = reactOutsideEvent(Select, ['click']);
<|endoftext|>


<commit_before>Crafty.defineScene('Navigation', (function() {

  /**
   *  Creates a NavNode entity based on the supplied
   *  data.
   *
   *  @private
   *  @param {object} nodeData - Objected describing desired NavNode.
   *  @return {NavNode} The new NavNode
   */

  var navNodeFactory = function(nodeData) {
    if(typeof nodeData === 'string') {
      nodeData = JSON.parse(nodeData);
    }
    return Crafty.e('NavNode')
      .attr(nodeData.attr)
  };

  console.log('fdsdfs');

  return function(sceneData) {

  };
})());
<commit_msg>building navigation scene<commit_after>Crafty.defineScene('Navigation', (function() {

  /**
   *  Creates a NavNode entity based on the supplied
   *  data.
   *
   *  @private
   *  @param {Object} nodeData - Object describing desired NavNode.
   *  @return {NavNode} The new NavNode
   */

  var navNodeFactory = function(nodeData) {
    var node;

    if(typeof nodeData === 'string') {
      nodeData = JSON.parse(nodeData);
    }

    node = Crafty.e('NavNode')
      .attr(nodeData.attr)

    if(typeof nodeData.image !== 'undefined') {
      node.css('background','url('+nodeData.image+') center');
    }

    return node;
  },

  /**
   *  Creates NavNodes from an array of NavNode data.
   *
   *  @private
   *  @param {Array} nodesData - Array of NavNode data
   *  @return {NavNode} Array of the new NavNodes
   */
  createNavNodes = function(nodesData) {
    var nodesCount = nodesData.length,
      nodeIndex = 0,
      nodes = [];

    for(;nodeIndex < nodesCount; nodeIndex+=1) {
      nodes[nodeIndex] = navNodeFactory(nodesData[nodeIndex]);
    }

    return nodes;
  }

  return function(sceneData) {

    var background = Crafty.e('Outerspace')
      .attr({
        w: sceneData.width,
        h: sceneData.height,
        x: 0,
        y: 0
      });

    if(sceneData.nodes instanceof Array) {
      createNavNodes(sceneData.nodes);
    }

    Crafty.viewport.clampToEntities = true;
    Crafty.viewport.x = sceneData.viewport.x;
    Crafty.viewport.y = sceneData.viewport.y;
    Crafty.viewport.mouselook(true);
  };
})());
<|endoftext|>


<commit_before>window.addEventListener("load", function () {

	// Grabbing elements from the page
	const music = document.querySelector('#music');
	const player = document.querySelector('#player');
	const playButton = document.querySelector('#pButton');
	const playHead = document.querySelector('#playhead');
	const timeLine = document.querySelector('#timeline');

	// Section for functions
	function togglePlay () {	// function to toggle play/pause
		music[music.paused ? 'play' : 'pause']();
	}

	function updateButton () {	// Function to handle play/pause icon
		if(!music.paused){
			playButton.classList.remove('play');
			playButton.classList.add('pause');
		}
		else {
			playButton.classList.remove('pause');
			playButton.classList.add('play');
		}
	}

	function handleProgress () {	// A  function to handle song duration bar
		var percent = (music.currentTime / music.duration ) * 100;
		if (percent==100) {
			percent = 0;
			order.push(order.shift());	// Take the completed one and place it at the end of playlist
			music.src = order[0];	// Change the source of the audio element
			music.play();
			updateButton();
		}
		playHead.style.marginLeft = (percent / 100) * 364  + "px";	// Geez -_-
	}

	function scrub (e) {	// function to enable track seek
		const scrubTime = (e.offsetX / 362) * music.duration;
		music.currentTime = scrubTime;
	}

	// The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle (based on SE answer).
	function shuffle(array) {
		var currentIndex = array.length, temporaryValue, randomIndex;
		// While there remain elements to shuffle
		while (0 !== currentIndex) {
			// Pick a remaining element
			randomIndex = Math.floor(Math.random() * currentIndex);
			currentIndex -= 1;
			// And swap it with the current element.
			temporaryValue = array[currentIndex];
			array[currentIndex] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		}
		return array;
	}

	// Entry Point !
	let order = shuffle(openings);
	music.src = order[0];
	music.play();
	updateButton();

	// Section for handling events
	playButton.addEventListener('click', togglePlay);
	playButton.addEventListener('click', updateButton);

	music.addEventListener('timeupdate', handleProgress);

	let mousedown = false;	// variable to keep track mousedown event
	timeline.addEventListener('mousedown', ()  => mousedown = true);
	timeline.addEventListener('mouseup', () => mousedown =  false);
	timeline.addEventListener('mousemove', (e) => mousedown && scrub(e));

});

//===============================================================================================================================================

openings = ["http://lyricmp3skull.org/s363640c/file/death-note-ls-theme/18366160.mp3",
			"https://r6---sn-gwpa-civs.googlevideo.com/videoplayback?dur=89.652&mv=m&mt=1498729062&ms=au&mn=sn-gwpa-civs&source=youtube&clen=6680565&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cexpire&id=o-AN0O-ErM-KU1UEcXYdGnbv-lTA5FNIiZXmjV3J3hDXNW&initcwndbps=410000&ip=47.247.15.86&ei=zMpUWbz_EZubogPbgLnoAw&pl=22&requiressl=yes&gcr=in&gir=yes&expire=1498750764&signature=C5FEC56BB067D773F22C8A220DDA4BD92E978C58.DF3408473318470BDEBCD0EA264C3FF9EEAB9FA5&lmt=1492910207161683&itag=18&key=yt6&mime=video%2Fmp4&mm=31&ipbits=0",
			"http://lyricmp3skull.org/s363640c/file/boku-no-hero-academia-season-2-ed-1/317870688.mp3",
			"http://w20.youtubeinmp3.com/download/get/?id=Q0v3ajXh5S0&r=N31suCidRZYtTdO0vmb4ZMMTVc2pFJYc&t=Tokyo+Ghoul+Unravel+-+Lyrics",
			"http://w29.youtubeinmp3.com/download/get/?id=ddbtDaXAvbA&r=dzieK0ydsMjT4CRCdgHtBbNVSZFy1ocg&t=MagiThe+Kingdom+of+Magic+Ending+1+Lyrics+%28Vostfr%29"
			]<commit_msg>some doc addition<commit_after>window.addEventListener("load", function () {

	// Grabbing elements from the page =====================================================================
	const music = document.querySelector('#music');
	const player = document.querySelector('#player');
	const playButton = document.querySelector('#pButton');
	const playHead = document.querySelector('#playhead');
	const timeLine = document.querySelector('#timeline');

	// Section for functions
	function togglePlay () {	// function to toggle play/pause
		music[music.paused ? 'play' : 'pause']();
	}

	function updateButton () {	// Function to handle play/pause icon
		if(!music.paused){
			playButton.classList.remove('play');
			playButton.classList.add('pause');
		}
		else {
			playButton.classList.remove('pause');
			playButton.classList.add('play');
		}
	}

	function handleProgress () {	// A  function to handle song duration bar
		var percent = (music.currentTime / music.duration ) * 100;
		if (percent==100) {
			percent = 0;
			order.push(order.shift());	// Take the completed one and place it at the end of playlist
			music.src = order[0];	// Change the source of the audio element
			music.play();
			updateButton();
		}
		playHead.style.marginLeft = (percent / 100) * 364  + "px";	// Geez -_-
	}

	function scrub (e) {	// function to enable track seek
		const scrubTime = (e.offsetX / 362) * music.duration;
		music.currentTime = scrubTime;
	}

	// The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle (based on SE answer).
	function shuffle(array) {
		var currentIndex = array.length, temporaryValue, randomIndex;
		// While there remain elements to shuffle
		while (0 !== currentIndex) {
			// Pick a remaining element
			randomIndex = Math.floor(Math.random() * currentIndex);
			currentIndex -= 1;
			// And swap it with the current element.
			temporaryValue = array[currentIndex];
			array[currentIndex] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		}
		return array;
	}

	// Entry Point !
	let order = shuffle(openings);
	music.src = order[0];
	music.play();
	updateButton();

	// Section for handling events
	playButton.addEventListener('click', togglePlay);
	playButton.addEventListener('click', updateButton);

	music.addEventListener('timeupdate', handleProgress);

	let mousedown = false;	// variable to keep track mousedown event
	timeline.addEventListener('mousedown', ()  => mousedown = true);
	timeline.addEventListener('mouseup', () => mousedown =  false);
	timeline.addEventListener('mousemove', (e) => mousedown && scrub(e));

});

//===============================================================================================================================================

openings = ["http://lyricmp3skull.org/s363640c/file/death-note-ls-theme/18366160.mp3",
			"https://r6---sn-gwpa-civs.googlevideo.com/videoplayback?dur=89.652&mv=m&mt=1498729062&ms=au&mn=sn-gwpa-civs&source=youtube&clen=6680565&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cexpire&id=o-AN0O-ErM-KU1UEcXYdGnbv-lTA5FNIiZXmjV3J3hDXNW&initcwndbps=410000&ip=47.247.15.86&ei=zMpUWbz_EZubogPbgLnoAw&pl=22&requiressl=yes&gcr=in&gir=yes&expire=1498750764&signature=C5FEC56BB067D773F22C8A220DDA4BD92E978C58.DF3408473318470BDEBCD0EA264C3FF9EEAB9FA5&lmt=1492910207161683&itag=18&key=yt6&mime=video%2Fmp4&mm=31&ipbits=0",
			"http://lyricmp3skull.org/s363640c/file/boku-no-hero-academia-season-2-ed-1/317870688.mp3",
			"http://w20.youtubeinmp3.com/download/get/?id=Q0v3ajXh5S0&r=N31suCidRZYtTdO0vmb4ZMMTVc2pFJYc&t=Tokyo+Ghoul+Unravel+-+Lyrics",
			"http://w29.youtubeinmp3.com/download/get/?id=ddbtDaXAvbA&r=dzieK0ydsMjT4CRCdgHtBbNVSZFy1ocg&t=MagiThe+Kingdom+of+Magic+Ending+1+Lyrics+%28Vostfr%29"
			]<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

let [,, src] = process.argv;
let transform = eval(src) || (line => line);
let env = new Set();

require('readline')
    .createInterface({
        input: process.stdin
    })
    .on('line', line => {
        let columns = line.match(/('(\\'|[^'])*'|"(\\"|[^"])*"|\/(\\\/|[^\/])*\/|(\\ |[^ ])+|[\w-]+)/g) || [];
        let value = transform(line, columns, env);
        if (value != null) {
            console.log(value);
        }
    });
<commit_msg>Support "close" event<commit_after>#!/usr/bin/env node
'use strict';

let [,, onLineSrc, onCloseSrc ] = process.argv;
let onLine = eval(onLineSrc) || (line => line);
let onClose = eval(onCloseSrc) || (() => undefined);
let env = new Set();

require('readline')
    .createInterface({
        input: process.stdin
    })
    .on('line', line => {
        let columns = line.match(/('(\\'|[^'])*'|"(\\"|[^"])*"|\/(\\\/|[^\/])*\/|(\\ |[^ ])+|[\w-]+)/g) || [];
        let value = onLine(line, columns, env);
        if (value != null) {
            console.log(value);
        }
    })
    .on('close', () => {
        onClose(env);
    });
<|endoftext|>


<commit_before>[1,"De-identification"],
  [2,"Make sure all personally-identifying information (PII) is removed! If you wish to deposit all variables in the survey for completeness, create de-identified versions of variables containing PII as described below and attach a list of all PII variables that should not be released with your submission."],
    [3,"DROP names of survey respondents, household members, enumerator, and associated contact information. DROP names of villages as well if they are characterized as personally identifiable in survey context."],
    [3,"ENCRYPT categorical variables by simply dropping the labels for encoded variables (if string, encode first). This applies to names of schools, village and possibly names of other administrative units (will differ by country and by project)."],
    [3,"MASK values of GPS coordinates if GPS information is related to the research question. Otherwise, remove GPS variables."],
  [2,"If results haven't been published yet, list any variables identifying treatment assignment and flag them as embargoed on the submission form to prevent their usage before the final paper is published. "],
  [2,"Remove or embargo any sensitive, potentially identifying information according to survey context. Possible examples include religion and ethnicity."],
[1,"Data Cleaning"],
  [2,"Recommended: Use the JPAL/PII_Scan (https://github.com/J-PAL/stata_PII_scan) as a filter to check if all pii has been dropped."]
  [2,"Does the ID variable uniquely identify observations?"],
  [2,"Does the ID variable uniquely identify observations?"],
  [2,"Are all variables labelled?"],
  [2,"Do all factor variables have value labels?"],
  [2,"Do all value labels match with the labels mentioned in the questionnaire"],
  [2,"Are all missing values correctly coded and labelled?"],
  [2,"Did you check for missing values otherwise not mentioned in the data entry dictionary (paper-based survey) or --- (Computer-based survey)"],
  [2,"Do variable names match the accompanying questionnaire?"],
  [2,"Is the ID the first variable listed?"],
  [2,"Do the order of the variables in the dataset match the order of the questions in the survey questionnaire?"],
[1,"Saving Data Set"],
  [2,"Use the cleaned dataset that does not include constructed variables"],
  [2,"Compress the dataset to reduce file size"],
  [2,"Save in the earliest Stata version compatible with your data formats and in a different folder than where the raw dataset is present"],
[1,"Supporting Documents"],
  [2,"IE Concept Note"],
  [2,"Questionnaires"],
    [3,"Paper format equivalent is better than CTO form"],
    [3,"Names of villages, schools, health facilities, etc listed as response options should be removed"],
  [2,"Enumerator manuals"],
  [2, "Field work details: dates on which the field work occurred, total number of households visited, refusal rates, total number of households and individuals included in the final sample, problems that occurred during the administration of the survey (strikes, inclement weather, inability to enter parts of the country)"],
  [2,"Data cleaning documentation:"],
    [3,"Codes for missing in survey and in dataset"],
    [3,"Record of any corrections made in the associated do-file and in a separate document."],
    [3,"If variables were masked for de-identification, report method used"],
    [3,"If applicable, describe how to link observations across data files (e.g. through Master Dataset)"],
  [2,"Data dictionary and list of datasets included, if applicable"],
  [2,"Code Review document indicating our efforts to adhere to reproducability guidelines are met."],
  [2,"Baseline report, if available"],
  [2,"Methodology description"],
  [2,"Publication citation"],
[1,"Submission"],
  [2,"We recommend publishing data sets as impact evaluation surveys under licensed access"],
  [2,"Go to MicroData Library Home Page (http://microdatalib.worldbank.org/) and log in with your UPI and passcode."],
  [2,"Click the link to “Deposit data” and next “Sign in to get started”."],
  [2,"If you are a returning user, all the projects that you have deposited will show up in the list either as “DRAFT” or “PROCESSED”. If you are a first-time user, click “Create New Project” to start with the process. Mandatory fields will be marked with stars. Provide “Title”, “Short name”, one paragraph of “Description” and Collaboration which will the email address of other Bank staff who may be authorized to make future edit and review this project. All the information provided here can be edited later."],
  [2,"Fill each field as much as possible based on project information, which can be found in concept note, baseline report or other project documents."],
  [2,"Load data files and other documents"],
  [2,"Review by Team Member: Send the links to project editing page to PIs, project manager, field coordinators and other team members for review and comments before submitting the project."],
  [2,"Review by Data Group:  After submitting the project, staff from Development Data Group will review the form and uploaded data files, confirm the successful documentation and access authority, or contact the project creator with further questions."]
<commit_msg>Update chk_microdata.js<commit_after>[1,"De-identification"],
  [2,"Make sure all personally-identifying information (PII) is removed! If you wish to deposit all variables in the survey for completeness, create de-identified versions of variables containing PII as described below and attach a list of all PII variables that should not be released with your submission."],
    [3,"DROP names of survey respondents, household members, enumerator, and associated contact information. DROP names of villages as well if they are characterized as personally identifiable in survey context."],
    [3,"ENCRYPT categorical variables by simply dropping the labels for encoded variables (if string, encode first). This applies to names of schools, village and possibly names of other administrative units (will differ by country and by project)."],
    [3,"MASK values of GPS coordinates if GPS information is related to the research question. Otherwise, remove GPS variables."],
  [2,"If results haven't been published yet, list any variables identifying treatment assignment and flag them as embargoed on the submission form to prevent their usage before the final paper is published. "],
  [2,"Remove or embargo any sensitive, potentially identifying information according to survey context. Possible examples include religion and ethnicity."],
[1,"Data Cleaning"],
  [2,"Recommended: Use the JPAL/PII_Scan (https://github.com/J-PAL/stata_PII_scan) as a filter to check if all pii has been dropped."]
  [2,"Recommended: Install the iefieldkit package from DIME Wiki to use the iecodebook command for data cleaning purposes"],
  [2,"Does the ID variable uniquely identify observations?"],
  [2,"Are all variables labelled?"],
  [2,"Do all factor variables have value labels?"],
  [2,"Do all value labels match with the labels mentioned in the questionnaire"],
  [2,"Are all missing values correctly coded and labelled?"],
  [2,"Did you check for missing values otherwise not mentioned in the data entry dictionary (paper-based survey) or --- (Computer-based survey)"],
  [2,"Do variable names match the accompanying questionnaire?"],
  [2,"Is the ID the first variable listed?"],
  [2,"Do the order of the variables in the dataset match the order of the questions in the survey questionnaire?"],
[1,"Saving Data Set"],
  [2,"Use the cleaned dataset that does not include constructed variables"],
  [2,"Compress the dataset to reduce file size"],
  [2,"Save in the earliest Stata version compatible with your data formats and in a different folder than where the raw dataset is present"],
[1,"Supporting Documents"],
  [2,"IE Concept Note"],
  [2,"Questionnaires"],
    [3,"Paper format equivalent is better than CTO form"],
    [3,"Names of villages, schools, health facilities, etc listed as response options should be removed"],
  [2,"Enumerator manuals"],
  [2, "Field work details: dates on which the field work occurred, total number of households visited, refusal rates, total number of households and individuals included in the final sample, problems that occurred during the administration of the survey (strikes, inclement weather, inability to enter parts of the country)"],
  [2,"Data cleaning documentation:"],
    [3,"Codes for missing values in survey and in dataset"],
    [3,"Record changes made during the data cleaning process in an easy to share manner."],
    [3,"If variables were masked for de-identification, report method used"],
    [3,"If applicable, describe how to link observations across data files (e.g. through Master Dataset)"],
  [2,"Data dictionary and list of datasets included, if applicable"],
  [2,"Code Review document indicating our efforts to adhere to reproducability guidelines are met."],
  [2,"Baseline report, if available"],
  [2,"Methodology description"],
  [2,"Publication citation"],
[1,"Submission"],
  [2,"We recommend publishing data sets as impact evaluation surveys under licensed access"],
  [2,"Go to MicroData Library Home Page (http://microdatalib.worldbank.org/) and log in with your UPI and passcode."],
  [2,"Click the link to “Deposit data” and next “Sign in to get started”."],
  [2,"If you are a returning user, all the projects that you have deposited will show up in the list either as “DRAFT” or “PROCESSED”. If you are a first-time user, click “Create New Project” to start with the process. Mandatory fields will be marked with stars. Provide “Title”, “Short name”, one paragraph of “Description” and Collaboration which will the email address of other Bank staff who may be authorized to make future edit and review this project. All the information provided here can be edited later."],
  [2,"Fill each field as much as possible based on project information, which can be found in concept note, baseline report or other project documents."],
  [2,"Load data files and other documents"],
  [2,"If required, embargo access to data until completion of the project"]
  [2,"Review by Team Member: Send the links to project editing page to PIs, project manager, field coordinators and other team members for review and comments before submitting the project."],
  [2,"Review by Data Group:  After submitting the project, staff from Development Data Group will review the form and uploaded data files, confirm the successful documentation and access authority, or contact the project creator with further questions."]
<|endoftext|>


<commit_before>[1,"Data Cleaning"],
  [2,"Does the ID variable uniquely identify observations?"],
  [2,"Are all variables labelled?"],
  [2,"Is any factor variable missing value labels?"],
  [2,"Are all missing values coded correctly?"],
  [2,"Do variable names match the accompanying questionnaire?"],
  [2,"Is the ID the first variable listed?"],
  [2,"Does the other variables’ order match the accompanying questionnaire?"],
[1,"De-identification"],
  [2,"Make sure all personally-identifying information (PII) is removed!"],
    [3,"DROP names of survey respondent, household members, enumerator, and associated contact information"],
    [3,"ENCRYPT categorical variables by simply dropping the labels for encoded variables (if string, encode first). This applies to names of schools, village and possibly names of other administrative units (will differ by country and by project)"],
    [3,"MASK values of GPS coordinates if GPS information is related to the research question. Otherwise, remove GPS variables"],
  [2,"Remove variables identifying treatment assignment"],
  [2,"Remove any sensitive, potentially identifying information according to survey context. Possible examples include religion and ethnicity."],
[1,"Saving Data Set"],
  [2,"Use the cleaned dataset that does not include constructed variables"],
  [2,"Use compress to reduce the file size"],
  [2,"Save in the earliest Stata version compatible with your data formats"],
[1,"Supporting Documents"],
  [2,"Questionnaires"],
    [3,"Paper format equivalent is better than CTO form"],
    [3,"Names of villages, schools, health facilities, etc listed as response options should be removed"],
  [2,"Data dictionary, if applicable"],
  [2,"Enumerator manuals"],
  [2,"IE Concept Note"],
  [2,"Baseline report, if available"],
  [2,"Methodology description"],
  [2,"Publications citation"],
  [2,"Data cleaning documentation:"],
    [3,"Codes for missing in survey and in dataset"],
    [3,"Record of any corrections made"],
    [3,"If variables were masked for de-identification, report method used"],
[1,"Submission"],
  [2,"We recommend publishing data sets as impact evaluation surveys under licensed access"],
  [2,"Go to MicroData Library Home Page (http://microdatalib.worldbank.org/) and log in with your UPI and passcode."],
  [2,"Click the link to “Deposit data” and next “Sign in to get started”."],
  [2,"If you are a returning user, all the projects that you have deposited will show up in the list either as “DRAFT” or “PROCESSED”. If you are a first-time user, click “Create New Project” to start with the process. Mandatory fields will be marked with stars. Provide “Title”, “Short name”, one paragraph of “Description” and Collaboration which will the email address of other Bank staff who may be authorized to make future edit and review this project. All the information provided here can be edited later."],
  [2,"Fill each field as much as possible based on project information, which can be found in concept note, baseline report or other project documents."],
  [2,"Load data files and other documents"],
  [2,"Review by Team Member: Send the links to project editing page to PIs, project manager, field coordinators and other team members for review and comments before submitting the project."],
  [2,"Review by Data Group:  After submitting the project, staff from Development Data Group will review the form and uploaded data files, confirm the successful documentation and access authority, or contact the project creator with further questions."]
<commit_msg>updated microdata checklist<commit_after>[1,"Data Cleaning"],
  [2,"Does the ID variable uniquely identify observations?"],
  [2,"Are all variables labelled?"],
  [2,"Do all factor variables have value labels?"],
  [2,"Are all missing values correctly coded and labelled?"],
  [2,"Do variable names match the accompanying questionnaire?"],
  [2,"Is the ID the first variable listed?"],
  [2,"Does the other variables’ order match the accompanying questionnaire?"],
[1,"De-identification"],
  [2,"Make sure all personally-identifying information (PII) is removed! If you wish to deposit all variables in the survey for completeness, create de-identified versions of variables containing PII as described below and attach a list of all PII variables that should not be released to you submission"],
    [3,"DROP names of survey respondent, household members, enumerator, and associated contact information"],
    [3,"ENCRYPT categorical variables by simply dropping the labels for encoded variables (if string, encode first). This applies to names of schools, village and possibly names of other administrative units (will differ by country and by project)"],
    [3,"MASK values of GPS coordinates if GPS information is related to the research question. Otherwise, remove GPS variables"],
  [2,"If results haven't been published yet, list any variables identifying treatment assignment and flag them as embargoed on the submission form"],
  [2,"Remove or embargo any sensitive, potentially identifying information according to survey context. Possible examples include religion and ethnicity."],
[1,"Saving Data Set"],
  [2,"Use the cleaned dataset that does not include constructed variables"],
  [2,"Use compress to reduce the file size"],
  [2,"Save in the earliest Stata version compatible with your data formats"],
[1,"Supporting Documents"],
  [2,"IE Concept Note"],
  [2,"Questionnaires"],
    [3,"Paper format equivalent is better than CTO form"],
    [3,"Names of villages, schools, health facilities, etc listed as response options should be removed"],
  [2,"Enumerator manuals"],
  [2, "Field work details: dates on which the field work occurred, total number of households visited, refusal rates, total number of households and individuals included in the final sample, problems that occurred during the administration of the survey (strikes, inclement weather, inability to enter parts of the country)"],
  [2,"Data cleaning documentation:"],
    [3,"Codes for missing in survey and in dataset"],
    [3,"Record of any corrections made"],
    [3,"If variables were masked for de-identification, report method used"],
	[3,"If applicable, describe how to link observations across data files (e.g. through Master Dataset)"],
  [2,"Data dictionary and list of datasets included, if applicable"],
  [2,"Baseline report, if available"],
  [2,"Methodology description"],
  [2,"Publications citation"],
[1,"Submission"],
  [2,"We recommend publishing data sets as impact evaluation surveys under licensed access"],
  [2,"Go to MicroData Library Home Page (http://microdatalib.worldbank.org/) and log in with your UPI and passcode."],
  [2,"Click the link to “Deposit data” and next “Sign in to get started”."],
  [2,"If you are a returning user, all the projects that you have deposited will show up in the list either as “DRAFT” or “PROCESSED”. If you are a first-time user, click “Create New Project” to start with the process. Mandatory fields will be marked with stars. Provide “Title”, “Short name”, one paragraph of “Description” and Collaboration which will the email address of other Bank staff who may be authorized to make future edit and review this project. All the information provided here can be edited later."],
  [2,"Fill each field as much as possible based on project information, which can be found in concept note, baseline report or other project documents."],
  [2,"Load data files and other documents"],
  [2,"Review by Team Member: Send the links to project editing page to PIs, project manager, field coordinators and other team members for review and comments before submitting the project."],
  [2,"Review by Data Group:  After submitting the project, staff from Development Data Group will review the form and uploaded data files, confirm the successful documentation and access authority, or contact the project creator with further questions."]
<|endoftext|>


<commit_before>import Ember from 'ember';
import { configurable } from 'affinity-engine';
import { Direction } from 'affinity-engine-stage';
import { BusPublisherMixin } from 'ember-message-bus';
import multiton from 'ember-multiton-service';

const {
  computed,
  get,
  getProperties,
  merge,
  set
} = Ember;

export default Direction.extend(BusPublisherMixin, {
  config: multiton('affinity-engine/config', 'engineId'),

  attrs: computed(() => Ember.Object.create({
    transitions: Ember.A()
  })),

  _configurationTiers: [
    'attrs',
    'config.attrs.component.stage.direction.layer',
    'config.attrs.component.stage',
    'config.attrs'
  ],

  _directableDefinition: computed('_configurationTiers', {
    get() {
      const configurationTiers = get(this, '_configurationTiers');

      return {
        animationAdapter: configurable(configurationTiers, 'animationLibrary'),
        layer: configurable(configurationTiers, 'layer'),
        transitions: configurable(configurationTiers, 'transitions')
      }
    }
  }),

  _setup(layer) {
    this._entryPoint();

    set(this, 'attrs.layer', layer);

    return this;
  },

  _reset() {
    this._super();

    get(this, 'attrs.transitions').clear();
  },

  transition(effect, duration, options = {}, type = 'transition') {
    this._entryPoint();

    const transitions = get(this, 'attrs.transitions');

    transitions.pushObject(merge({ duration, effect, type, queue: 'main' }, options));

    return this;
  },

  _perform(priorSceneRecord, resolve) {
    const {
      _directableDefinition,
      attrs,
      engineId,
      windowId
    } = getProperties(this, '_directableDefinition', 'attrs', 'engineId', 'windowId');

    const layer = get(attrs, 'layer');

    set(this, '_restartingEngine', true);

    this.publish(`ae:${engineId}:${windowId}:${layer}:shouldDirectLayer`, { attrs, direction: this, priorSceneRecord, resolve, engineId, windowId }, _directableDefinition);
  }
});
<commit_msg>return to using array configurable<commit_after>import Ember from 'ember';
import { configurable, deepArrayConfigurable } from 'affinity-engine';
import { Direction } from 'affinity-engine-stage';
import { BusPublisherMixin } from 'ember-message-bus';
import multiton from 'ember-multiton-service';

const {
  computed,
  get,
  getProperties,
  merge,
  set
} = Ember;

export default Direction.extend(BusPublisherMixin, {
  config: multiton('affinity-engine/config', 'engineId'),

  attrs: computed(() => Ember.Object.create({
    transitions: Ember.A()
  })),

  _configurationTiers: [
    'attrs',
    'config.attrs.component.stage.direction.layer',
    'config.attrs.component.stage',
    'config.attrs'
  ],

  _directableDefinition: computed('_configurationTiers', {
    get() {
      const configurationTiers = get(this, '_configurationTiers');

      return {
        animationAdapter: configurable(configurationTiers, 'animationLibrary'),
        layer: configurable(configurationTiers, 'layer'),
        transitions: deepArrayConfigurable(configurationTiers, 'attrs.transitions', 'transition')
      }
    }
  }),

  _setup(layer) {
    this._entryPoint();

    set(this, 'attrs.layer', layer);

    return this;
  },

  _reset() {
    this._super();

    get(this, 'attrs.transitions').clear();
  },

  transition(effect, duration, options = {}, type = 'transition') {
    this._entryPoint();

    const transitions = get(this, 'attrs.transitions');

    transitions.pushObject(merge({ duration, effect, type, queue: 'main' }, options));

    return this;
  },

  _perform(priorSceneRecord, resolve) {
    const {
      _directableDefinition,
      attrs,
      engineId,
      windowId
    } = getProperties(this, '_directableDefinition', 'attrs', 'engineId', 'windowId');

    const layer = get(attrs, 'layer');

    set(this, '_restartingEngine', true);

    this.publish(`ae:${engineId}:${windowId}:${layer}:shouldDirectLayer`, { attrs, direction: this, priorSceneRecord, resolve, engineId, windowId }, _directableDefinition);
  }
});
<|endoftext|>