<commit_before>//= require bootstrap-datepicker.min
//= require umakadata/chart-helper

var waitingDialog = waitingDialog || (function ($) {
  'use strict';
  return {
    show: function (message, options) {
      // Assigning defaults
      if (typeof options === 'undefined') {
        options = {};
      }
      if (typeof message === 'undefined') {
        message = 'Loading';
      }
      var settings = $.extend({
        dialogSize: 'm',
        progressType: '',
        onHide: null // This callback runs after the dialog was hidden
      }, options);

      var dialog = $("#dialog");

      dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
      dialog.find('.progress-bar').attr('class', 'progress-bar');
      if (settings.progressType) {
        dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
      }
      dialog.find('h3').text(message);

      if (typeof settings.onHide === 'function') {
        dialog.off('hidden.bs.modal').on('hidden.bs.modal', function () {
          settings.onHide.call($dialog);
        });
      }
      dialog.modal();
    },
    hide: function () {
      $("#dialog").modal('hide');
    }
  };
})(jQuery);

var dataLoader = (function ($) {
  var endpointId = null;
  var raderLoaded = false;
  var scoreLoaded = false;
  var startDate = '';
  return {
    load: function (endpoint_id, evaluation_id, start_date) {
      endpointId = endpoint_id;
      raderLoaded = false;
      scoreLoaded = false;
      waitingDialog.show('Loading Endpoint Information...');
      dataLoader.showInfo(endpointId, evaluation_id);
      startDate = start_date;
    },

    done: function () {
      if (raderLoaded && scoreLoaded) {
        waitingDialog.hide();
        $('#jump-button').on("click", function () {
          var input_date = $("#calendar").val();
          var param = (input_date === '') ? '' : '?date=' + input_date;
          $.getJSON("/api/endpoints/" + endpointId + "/created_at" + param, function (json) {
            var evaluation_id = json['evaluation_id'];
            if (evaluation_id === '') {
              $('#get_evaluation_id').modal();
            } else {
              location.href = "/endpoints/" + endpointId + "/" + evaluation_id + param
            }
          });
        });
        $('#calendar').datepicker({
          autoclose: true,
          startDate: "#" + startDate,
          endDate: new Date(),
          format: 'dd-M-yyyy',
          todayHighlight: true
        });
      }
    },

    showInfo: function (endpoint_id, evaluation_id) {
      $.ajax({
        type: "GET",
        url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info"
      }).done(function (element) {
        var html = $.parseHTML(element);
        $("#endpoint_info").html(html);
        dataLoader.showRadar(endpoint_id, evaluation_id);
        dataLoader.showScoreHistory(endpoint_id, evaluation_id);
      }).fail(function () {
        alert('Failed to load Endpoint Information.');
        waitingDialog.hide();
      });
    },

    showRadar: function (endpoint_id, evaluation_id) {
      $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
        var data = json['data'];
        var avg = json['avg'];
        var context = $("#radar");
        var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
        new Chart(context, {
          type: 'radar',
          data: {
            labels: labels,
            datasets: [
              {
                label: "Target",
                backgroundColor: "rgba(151,187,205,0.2)",
                borderColor: "rgba(151,187,205,1)",
                pointBorderColor: "rgba(151,187,205,1)",
                pointBackgroundColor: "#fff",
                data: data
              },
              {
                label: "Average",
                backgroundColor: "rgba(220,220,220,0.5)",
                borderColor: "rgba(220,220,220,1)",
                pointBorderColor: "rgba(220,220,220,1)",
                pointBackgroundColor: "#fff",
                data: avg
              }
            ]
          },
          options: {
            responsive: true
          }
        });
        dataLoader.setScoresOnLabels(labels, data);
        raderLoaded = true;
        dataLoader.done();
      });
    },

    setScoresOnLabels: function (labels, data) {
      var status;
      for (var i = 0; i < 6; ++i) {
        $('#' + labels[i] + '_score').text('(' + data[i] + ')');
        if (data[i] < 20) {
          status = 'poor';
        } else if (data[i] < 40) {
          status = 'below_average'
        } else if (data[i] < 60) {
          status = 'average'
        } else if (data[i] < 80) {
          status = 'good'
        } else {
          status = 'excellent';
        }
        $('.' + labels[i]).addClass(status)
      }
    },

    appendOptions: function (datasets) {
      datasets['datasets'].forEach(function (element) {
        var label = element['label'];

        if (label) {
          element['lineTension'] = 0;
          // set all 'pointBackgroundColor' to white
          element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
          // set the area under the line not to fill
          element['fill'] = false;
        }

        switch (label.toLowerCase()) {
          case 'availability':
            element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
            break;
          case 'freshness':
            element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
            break;
          case 'operation':
            element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
            break;
          case 'usefulness':
            element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
            break;
          case 'validity':
            element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
            break;
          case 'performance':
            element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
            break;
          case 'rank':
            element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
            break;
          default:
            break;
        }
      });
    },

    showScoreHistory: function (endpoint_id, evaluation_id) {
      $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
        var context = $("#score_history");
        dataLoader.appendOptions(json);
        var labels = json['labels'];
        json['labels'] = labels.map(formatDate);
        var options = make_scale_options();
        options['datasetFill'] = false;
        var lineChart = new Chart(context, {
          type: 'line',
          data: json,
          options: options
        });
        dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
        scoreLoaded = true;
        dataLoader.done();
      });
    },

    addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
      $(context).on("click", function (evt) {
        var activePoints = lineChart.getElementsAtEvent(evt);
        if (activePoints.length === 0) {
          return
        }
        var index = activePoints[0]['_index'];
        var datestring = labels[index];
        $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
          var evaluation_id = json['evaluation_id'];
          if (evaluation_id === '') {
            $('#get_evaluation_id').modal();
          } else {
            location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
          }
        });
      });
    }
  }
})(jQuery);

$(document).ready(function() {
  var endpoint_id = $("#endpoint_id").text().trim();
  var evaluation_id = $("#evaluation_id").text().trim();
  var start_date = $("#start_date").text().trim();
  dataLoader.load(endpoint_id, evaluation_id, start_date);
});
<commit_msg>add chart.js<commit_after>//= require Chart.min
//= require bootstrap-datepicker.min
//= require umakadata/chart-helper

var waitingDialog = waitingDialog || (function ($) {
  'use strict';
  return {
    show: function (message, options) {
      // Assigning defaults
      if (typeof options === 'undefined') {
        options = {};
      }
      if (typeof message === 'undefined') {
        message = 'Loading';
      }
      var settings = $.extend({
        dialogSize: 'm',
        progressType: '',
        onHide: null // This callback runs after the dialog was hidden
      }, options);

      var dialog = $("#dialog");

      dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
      dialog.find('.progress-bar').attr('class', 'progress-bar');
      if (settings.progressType) {
        dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
      }
      dialog.find('h3').text(message);

      if (typeof settings.onHide === 'function') {
        dialog.off('hidden.bs.modal').on('hidden.bs.modal', function () {
          settings.onHide.call($dialog);
        });
      }
      dialog.modal();
    },
    hide: function () {
      $("#dialog").modal('hide');
    }
  };
})(jQuery);

var dataLoader = (function ($) {
  var endpointId = null;
  var raderLoaded = false;
  var scoreLoaded = false;
  var startDate = '';
  return {
    load: function (endpoint_id, evaluation_id, start_date) {
      endpointId = endpoint_id;
      raderLoaded = false;
      scoreLoaded = false;
      waitingDialog.show('Loading Endpoint Information...');
      dataLoader.showInfo(endpointId, evaluation_id);
      startDate = start_date;
    },

    done: function () {
      if (raderLoaded && scoreLoaded) {
        waitingDialog.hide();
        $('#jump-button').on("click", function () {
          var input_date = $("#calendar").val();
          var param = (input_date === '') ? '' : '?date=' + input_date;
          $.getJSON("/api/endpoints/" + endpointId + "/created_at" + param, function (json) {
            var evaluation_id = json['evaluation_id'];
            if (evaluation_id === '') {
              $('#get_evaluation_id').modal();
            } else {
              location.href = "/endpoints/" + endpointId + "/" + evaluation_id + param
            }
          });
        });
        $('#calendar').datepicker({
          autoclose: true,
          startDate: "#" + startDate,
          endDate: new Date(),
          format: 'dd-M-yyyy',
          todayHighlight: true
        });
      }
    },

    showInfo: function (endpoint_id, evaluation_id) {
      $.ajax({
        type: "GET",
        url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info"
      }).done(function (element) {
        var html = $.parseHTML(element);
        $("#endpoint_info").html(html);
        dataLoader.showRadar(endpoint_id, evaluation_id);
        dataLoader.showScoreHistory(endpoint_id, evaluation_id);
      }).fail(function () {
        alert('Failed to load Endpoint Information.');
        waitingDialog.hide();
      });
    },

    showRadar: function (endpoint_id, evaluation_id) {
      $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
        var data = json['data'];
        var avg = json['avg'];
        var context = $("#radar");
        var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
        new Chart(context, {
          type: 'radar',
          data: {
            labels: labels,
            datasets: [
              {
                label: "Target",
                backgroundColor: "rgba(151,187,205,0.2)",
                borderColor: "rgba(151,187,205,1)",
                pointBorderColor: "rgba(151,187,205,1)",
                pointBackgroundColor: "#fff",
                data: data
              },
              {
                label: "Average",
                backgroundColor: "rgba(220,220,220,0.5)",
                borderColor: "rgba(220,220,220,1)",
                pointBorderColor: "rgba(220,220,220,1)",
                pointBackgroundColor: "#fff",
                data: avg
              }
            ]
          },
          options: {
            responsive: true
          }
        });
        dataLoader.setScoresOnLabels(labels, data);
        raderLoaded = true;
        dataLoader.done();
      });
    },

    setScoresOnLabels: function (labels, data) {
      var status;
      for (var i = 0; i < 6; ++i) {
        $('#' + labels[i] + '_score').text('(' + data[i] + ')');
        if (data[i] < 20) {
          status = 'poor';
        } else if (data[i] < 40) {
          status = 'below_average'
        } else if (data[i] < 60) {
          status = 'average'
        } else if (data[i] < 80) {
          status = 'good'
        } else {
          status = 'excellent';
        }
        $('.' + labels[i]).addClass(status)
      }
    },

    appendOptions: function (datasets) {
      datasets['datasets'].forEach(function (element) {
        var label = element['label'];

        if (label) {
          element['lineTension'] = 0;
          // set all 'pointBackgroundColor' to white
          element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
          // set the area under the line not to fill
          element['fill'] = false;
        }

        switch (label.toLowerCase()) {
          case 'availability':
            element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
            break;
          case 'freshness':
            element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
            break;
          case 'operation':
            element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
            break;
          case 'usefulness':
            element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
            break;
          case 'validity':
            element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
            break;
          case 'performance':
            element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
            break;
          case 'rank':
            element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
            element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
            break;
          default:
            break;
        }
      });
    },

    showScoreHistory: function (endpoint_id, evaluation_id) {
      $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
        var context = $("#score_history");
        dataLoader.appendOptions(json);
        var labels = json['labels'];
        json['labels'] = labels.map(formatDate);
        var options = make_scale_options();
        options['datasetFill'] = false;
        var lineChart = new Chart(context, {
          type: 'line',
          data: json,
          options: options
        });
        dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
        scoreLoaded = true;
        dataLoader.done();
      });
    },

    addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
      $(context).on("click", function (evt) {
        var activePoints = lineChart.getElementsAtEvent(evt);
        if (activePoints.length === 0) {
          return
        }
        var index = activePoints[0]['_index'];
        var datestring = labels[index];
        $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
          var evaluation_id = json['evaluation_id'];
          if (evaluation_id === '') {
            $('#get_evaluation_id').modal();
          } else {
            location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
          }
        });
      });
    }
  }
})(jQuery);

$(document).ready(function() {
  var endpoint_id = $("#endpoint_id").text().trim();
  var evaluation_id = $("#evaluation_id").text().trim();
  var start_date = $("#start_date").text().trim();
  dataLoader.load(endpoint_id, evaluation_id, start_date);
});
<|endoftext|>


<commit_before>sparqplug.detail.object = {type:"detail","title":"Object","description":"View query history.","icon":"","css":"sparqplug.detail.object.css"};
plugins['urn:sparqplug:sparqlenvironment.detail.object:0.1'] = sparqplug.detail.object;

sparqplug.detail.object.load = function () {
	$('#sparqplug-detail-object').append("

")
	environment.bindToEvent('selectedObject', this.selected );
}

sparqplug.detail.object.selected = function (data,dataset) {
	obj = data.object;
	datasetObject = environment.getDatasetObject(dataset);

	$detail = $("#sparqplug-detail-object");
	$detail.empty();

	$obj_display = $('
',{
		text: $.resolvePrefix(obj,datasetObject),
		class: 'header'
	});

	$obj_verbs = $('
',{
		class: 'verb-list'
	});

	obj_string = '<'+obj+'>'; // should check for prefix

	// TO-DO stop using versbForObject and verbsForDirectObject.
	// Use custom query that retrieves both at once.

	$obj_verbs.append("
Verbs as Subject
");

	$.each($.verbsForObject(obj_string,datasetObject),function (index, verb) {
		$obj_verb = $('',{
			text: $.resolvePrefix(verb.value,datasetObject),
			class: 'verb-item'
		});
		$obj_verb.data('obj',obj);
		$obj_verb.data('verb', verb.value);

		$obj_verb.click(function () {
			environment.performQuery('SELECT ?object WHERE { <'+$(this).data('obj')+'> <'+$(this).data('verb')+'> ?object }',datasetObject);
		});

		$obj_verbs.append($obj_verb);
		$obj_verbs.append('
');
	});

	$obj_verbs.append("
Verbs as Object
");

	$.each($.verbsForDirectObject(obj_string,datasetObject),function (index, verb) {
		$obj_verb = $('',{
			text: $.resolvePrefix(verb.value,datasetObject),
			class: 'verb-item'
		});
		$obj_verb.data('obj',obj);
		$obj_verb.data('verb', verb.value);

		$obj_verb.click(function () {
			environment.performQuery('SELECT ?subject WHERE { ?subject <'+$(this).data('verb')+'> <'+$(this).data('obj')+'> }');
		});

		$obj_verbs.append($obj_verb);
		$obj_verbs.append('
');

	});

	$detail.append($obj_display);
	$detail.append($obj_verbs);
}

sparqplug.detail.object.createHistoryli = function (query, index) {
	li = $("
",{
				text: query
			}).click(function(){
				query = this.innerHTML;
				environment.performQuery(query);
			});
			return li;
}
<commit_msg>fix getting dataset from data passed<commit_after>sparqplug.detail.object = {type:"detail","title":"Object","description":"View query history.","icon":"","css":"sparqplug.detail.object.css"};
plugins['urn:sparqplug:sparqlenvironment.detail.object:0.1'] = sparqplug.detail.object;

sparqplug.detail.object.load = function () {
	$('#sparqplug-detail-object').append("

")
	environment.bindToEvent('selectedObject', this.selected );
}

sparqplug.detail.object.selected = function (data) {
	obj = data.object;
	datasetObject = environment.getDatasetObject(data.dataset);

	$detail = $("#sparqplug-detail-object");
	$detail.empty();

	$obj_display = $('
',{
		text: $.resolvePrefix(obj,datasetObject),
		class: 'header'
	});

	$obj_verbs = $('
',{
		class: 'verb-list'
	});

	obj_string = '<'+obj+'>'; // should check for prefix

	// TO-DO stop using versbForObject and verbsForDirectObject.
	// Use custom query that retrieves both at once.

	$obj_verbs.append("
Verbs as Subject
");

	$.each($.verbsForObject(obj_string,datasetObject),function (index, verb) {
		$obj_verb = $('',{
			text: $.resolvePrefix(verb.value,datasetObject),
			class: 'verb-item'
		});
		$obj_verb.data('obj',obj);
		$obj_verb.data('verb', verb.value);

		$obj_verb.click(function () {
			environment.performQuery('SELECT ?object WHERE { <'+$(this).data('obj')+'> <'+$(this).data('verb')+'> ?object }',datasetObject);
		});

		$obj_verbs.append($obj_verb);
		$obj_verbs.append('
');
	});

	$obj_verbs.append("
Verbs as Object
");

	$.each($.verbsForDirectObject(obj_string,datasetObject),function (index, verb) {
		$obj_verb = $('',{
			text: $.resolvePrefix(verb.value,datasetObject),
			class: 'verb-item'
		});
		$obj_verb.data('obj',obj);
		$obj_verb.data('verb', verb.value);

		$obj_verb.click(function () {
			environment.performQuery('SELECT ?subject WHERE { ?subject <'+$(this).data('verb')+'> <'+$(this).data('obj')+'> }');
		});

		$obj_verbs.append($obj_verb);
		$obj_verbs.append('
');

	});

	$detail.append($obj_display);
	$detail.append($obj_verbs);
}

sparqplug.detail.object.createHistoryli = function (query, index) {
	li = $("
",{
				text: query
			}).click(function(){
				query = this.innerHTML;
				environment.performQuery(query);
			});
			return li;
}
<|endoftext|>


<commit_before>module.exports = {
  afterInstall: function() {
    return this.addBowerPackageToProject('coverflow');
  }
};
<commit_msg>Add jQuery UI<commit_after>module.exports = {
  afterInstall: function() {
    return this.addBowerPackageToProject('coverflow');
    return this.addBowerPackageToProject('jquery-ui');
  }
};
<|endoftext|>


<commit_before>var form_data = {};
var information = $('.alert');

var Settings = React.createClass({
	getInitialState: function(){
		return {
			user_info: {},
			employee_type: 'individual'
		}
	},
	_back: function( event ){
		event.preventDefault();
		event.stopPropagation();
		location.href = "";
	},
	_handleClick: function( event )
	{
		event.preventDefault();
		event.stopPropagation();
		var $node = $( event.target );
		var formData = $node.parent().serialize();
		formData = formData+"&employee_type="+this.state.employee_type;

		if( this.state.user_info.hasOwnProperty('id_passport')
			&& this.state.user_info.hasOwnProperty('email')
			&& this.state.user_info.hasOwnProperty('phone1')
			&& this.state.user_info.hasOwnProperty('phone2')
			&& this.state.user_info.hasOwnProperty('address')
			&& this.state.user_info.hasOwnProperty('education_level')
			&& this.state.user_info.hasOwnProperty('certificate')
			&& this.state.user_info.hasOwnProperty('city_town')
			&& this.state.user_info.hasOwnProperty('estate_locality')
			&& this.state.user_info.hasOwnProperty('school'))
			{
					this._submit( formData );
			}
			else
			{
				var node = $(ReactDOM.findDOMNode(this));
				var info_div = node.find('div.alert');
				info_div.removeClass('alert-info').addClass('alert-danger').html('Fill in all the required fields').toggle(700);
			}

	},
	_validate: function( event )
	{
		event.preventDefault();
		event.stopPropagation();

		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

		var node = event.target, $node = $( node ), $type = $node.attr('type');

		if($type == 'text' && typeof($node.val()) == 'string' && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'email' && typeof($node.val()) == 'string' && re.test($node.val()) && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'number' && isNaN( $node.val() ) == false && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'password' && typeof($node.val()) == 'string' && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( event.type === "change" && $node.val() !== '--SELECT--' )
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else
		{
			$node.parent().children('i').removeClass('glyphicon-ok').addClass('glyphicon-warning-sign');
		}
	},
	_submit: function( data )
	{
		$.ajax({
			url: '/janta/index.php/Employee_registration/employeeData',
			type: 'POST',
			dataType: 'json',
			data: data,
		})
		.done(function( response ) {
			if( response['status'] == 'registered'){
				status.show('slideDown').removeClass('warning').addClass('success').html("User is Registered");
				ReactDOM.render(<Settings />, document.getElementById('choice'));
			}else if( response['exists'] == true ){
				status.show('slideDown').removeClass('success').addClass('warning').html("User is already Registered!!");
			}
		})
		.fail(function( response ) {
			console.log( response );
		})
	},
	render: function() {
		return (

Registering

Please fill in all the blanks

		<form className = "form-inline" encType = "multipart-form/data">

					ID/Passport Number:
<input type = "number" name = "id_passport" className = "form-control" placeholder = "ID/Passport Number" onBlur={this._validate}/>

				Email:
<input type = "email" name = "email" className = "form-control" placeholder = "Email" onBlur={this._validate}/>

				Phone number:
<input type = "number" name = "phone1" className = "form-control" placeholder = "Phone number 1" onBlur={this._validate}/>

				Phone number:
<input type = "number" name = "phone2" className = "form-control" placeholder = "Phone number 2" onBlur={this._validate}/>

				Address:
<input type = "text" name = "address" className = "form-control" placeholder = "Address" onBlur={this._validate}/>

				Highest Education Level:

					<select className = "form-control" name = "education_level" onChange ={this._validate}>
						<option>--SELECT--</option>
						<option>Ph.D</option>
						<option>Masters Degree</option>
						<option>Undergraduate Degree</option>
						<option>Diploma</option>
						<option>High school</option>
						<option>Primary School</option>
					</select>

				City/Town:

					<select className = "form-control" name = "city_town" type = "select" onChange ={this._validate}>
						<option>--SELECT--</option>
						<option>Nairobi</option>
						<option>Nakuru</option>
						<option>Mombasa</option>
						<option>Kisumu</option>
						<option>Eldoret</option>
						<option>Nyeri</option>
					</select>

				Estate Locality:
<input type = "text" name = "estate_locality" className = "form-control" placeholder = "Estate Locality" onBlur={this._validate}/>

				Certificate:
<input type = "text" name = "certificate" className = "form-control" placeholder = "Certificate" onBlur={this._validate}/>

				Institution Name:
<input type = "text" name = "school" className = "form-control" placeholder = "Institution Name" onBlur={this._validate}/>

				<button type="button" className="btn btn-success" onClick={this._handleClick}>Submit</button>
		</form>

		);
	}
});

ReactDOM.render(<Settings />, document.getElementById('form'));<commit_msg>housekeeping<commit_after>var form_data = {};
var information = $('.alert');

var Settings = React.createClass({
	getInitialState: function(){
		return {
			user_info: {},
			employee_type: 'individual'
		}
	},
	_back: function( event ){
		event.preventDefault();
		event.stopPropagation();
		location.href = "";
	},
	_handleClick: function( event )
	{
		event.preventDefault();
		event.stopPropagation();
		var $node = $( event.target );
		var formData = $node.parent().serialize();
		formData = formData+"&employee_type="+this.state.employee_type;

		if( this.state.user_info.hasOwnProperty('id_passport')		// this checks whether the form was well filled
			&& this.state.user_info.hasOwnProperty('email')
			&& this.state.user_info.hasOwnProperty('phone1')
			&& this.state.user_info.hasOwnProperty('phone2')
			&& this.state.user_info.hasOwnProperty('address')
			&& this.state.user_info.hasOwnProperty('education_level')
			&& this.state.user_info.hasOwnProperty('certificate')
			&& this.state.user_info.hasOwnProperty('city_town')
			&& this.state.user_info.hasOwnProperty('estate_locality')
			&& this.state.user_info.hasOwnProperty('school'))
			{
					this._submit( formData );
			}
			else
			{
				var node = $(ReactDOM.findDOMNode(this));
				var info_div = node.find('div.alert');
				info_div.removeClass('alert-info').addClass('alert-danger').html('Fill in all the required fields').toggle(700);
			}

	},
	_validate: function( event )
	{
		event.preventDefault();
		event.stopPropagation();

		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

		var node = event.target, $node = $( node ), $type = $node.attr('type');

		if($type == 'text' && typeof($node.val()) == 'string' && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'email' && typeof($node.val()) == 'string' && re.test($node.val()) && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'number' && isNaN( $node.val() ) == false && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( $type == 'password' && typeof($node.val()) == 'string' && $node.val() !== "")
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else if( event.type === "change" && $node.val() !== '--SELECT--' )
		{
			$node.parent().children('i').removeClass('glyphicon-warning-sign').addClass('glyphicon-ok');
			form_data[$node.attr('name')] = $node.val();
			this.setState({user_info: form_data});
		}
		else
		{
			$node.parent().children('i').removeClass('glyphicon-ok').addClass('glyphicon-warning-sign');
		}
	},
	_submit: function( data )
	{
		$.ajax({
			url: '/janta/index.php/Employee_registration/employeeData',
			type: 'POST',
			dataType: 'json',
			data: data,
		})
		.done(function( response ) {
			if( response['status'] == 'registered'){
				status.show('slideDown').removeClass('warning').addClass('success').html("User is Registered");
				ReactDOM.render(<Settings />, document.getElementById('choice'));
			}else if( response['exists'] == true ){
				status.show('slideDown').removeClass('success').addClass('warning').html("User is already Registered!!");
			}
		})
		.fail(function( response ) {
			console.log( response );
		})
	},
	render: function() {
		return (

Registering

Please fill in all the blanks

		<form className = "form-inline" encType = "multipart-form/data">

							ID/Passport Number:
<input type = "number" name = "id_passport" className = "form-control" placeholder = "ID/Passport Number" onBlur={this._validate}/>

						Email:
<input type = "email" name = "email" className = "form-control" placeholder = "Email" onBlur={this._validate}/>

						Phone number:
<input type = "number" name = "phone1" className = "form-control" placeholder = "Phone number 1" onBlur={this._validate}/>

						Phone number:
<input type = "number" name = "phone2" className = "form-control" placeholder = "Phone number 2" onBlur={this._validate}/>

						Address:
<input type = "text" name = "address" className = "form-control" placeholder = "Address" onBlur={this._validate}/>

						Highest Education Level:

							<select className = "form-control" name = "education_level" onChange ={this._validate}>
								<option>--SELECT--</option>
								<option>Ph.D</option>
								<option>Masters Degree</option>
								<option>Undergraduate Degree</option>
								<option>Diploma</option>
								<option>High school</option>
								<option>Primary School</option>
							</select>

						City/Town:

							<select className = "form-control" name = "city_town" type = "select" onChange ={this._validate}>
								<option>--SELECT--</option>
								<option>Nairobi</option>
								<option>Nakuru</option>
								<option>Mombasa</option>
								<option>Kisumu</option>
								<option>Eldoret</option>
								<option>Nyeri</option>
							</select>

						Estate Locality:
<input type = "text" name = "estate_locality" className = "form-control" placeholder = "Estate Locality" onBlur={this._validate}/>

						Certificate:
<input type = "text" name = "certificate" className = "form-control" placeholder = "Certificate" onBlur={this._validate}/>

						Institution Name:
<input type = "text" name = "school" className = "form-control" placeholder = "Institution Name" onBlur={this._validate}/>

						<button type="button" className="btn btn-success" onClick={this._handleClick}>Submit</button>
				</form>

		);
	}
});

ReactDOM.render(<Settings />, document.getElementById('form'));<|endoftext|>


<commit_before>// Firebase child's
var ref = new Firebase('https://cepatsembuh.firebaseio.com'),
    puskesmas = ref.child('puskesmas'),
  	faskes = puskesmas.child('kelapa_gading');

function antrian(){
 var ref = new Firebase('https://cepatsembuh.firebaseio.com'),
     puskesmas = ref.child('puskesmas'),
     faskes = puskesmas.child('kelapa_gading');

  // Input's
  var nama = $('#name').val(),
      nik = $('#nik').val(),
      no = $('#no').val(),
      poli = $('#poli').val();

 // Poli child's
 var bpu = faskes.child('bpu'),
     bpg = faskes.child('bpg'),
     kia = faskes.child('kia');

 if (poli == 'null') {
  alert('Anda belum memilih poli');
 } else if (nama == '') {
  alert('Anda belum memasukan nama anda');
 } else if (nik.length != 16) {
  alert('Anda belum memasukan nik');
 } else if (no_rujuk.length != 20) {
  alert('Anda belum memasukan nomor BPJS');
 } else if (poli == 'bpu') {
  bpu.transaction(function(currentRank){
    current = currentRank;
    next = currentRank + 1;

  return next;
 }, function(error, snapshot, committed){
      alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

      var pasien = faskes.child('pasien');
      pasien.push().set({
       nama: nama,
       nik: nik,
       no: no,
       no_antrian: next,
       poli: 'bpu'
      })
  })
 } else if (poli == 'bpg'){
   bpg.transaction(function(currentRank){
     current = currentRank;
     next = currentRank + 1;

     return next;
  }, function(error, snapshot, committed){
       alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

       var pasien = faskes.child('pasien');
       pasien.push().set({
        nama: nama,
        nik: nik,
        no: no,
        no_antrian: next,
        poli: 'bpg'
       })
   })
 } else if (poli == 'kia'){
   kia.transaction(function(currentRank){
     current = currentRank;
     next = currentRank + 1;

     return next;
  }, function(error, snapshot, committed){
       alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

       var pasien = faskes.child('pasien');
       pasien.push().set({
        nama: nama,
        nik: nik,
        no: no,
        no_antrian: next,
        poli: 'kia'
       })
   })
 }
}
<commit_msg>Wrong var name<commit_after>// Firebase child's
var ref = new Firebase('https://cepatsembuh.firebaseio.com'),
    puskesmas = ref.child('puskesmas'),
  	faskes = puskesmas.child('kelapa_gading');

function antrian(){
 var ref = new Firebase('https://cepatsembuh.firebaseio.com'),
     puskesmas = ref.child('puskesmas'),
     faskes = puskesmas.child('kelapa_gading');

  // Input's
  var nama = $('#name').val(),
      nik = $('#nik').val(),
      no = $('#no').val(),
      poli = $('#poli').val();

 // Poli child's
 var bpu = faskes.child('bpu'),
     bpg = faskes.child('bpg'),
     kia = faskes.child('kia');

 if (poli == 'null') {
  alert('Anda belum memilih poli');
 } else if (nama == '') {
  alert('Anda belum memasukan nama anda');
 } else if (nik.length != 16) {
  alert('Anda belum memasukan nik');
 } else if (no.length != 20) {
  alert('Anda belum memasukan nomor BPJS');
 } else if (poli == 'bpu') {
  bpu.transaction(function(currentRank){
    current = currentRank;
    next = currentRank + 1;

  return next;
 }, function(error, snapshot, committed){
      alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

      var pasien = faskes.child('pasien');
      pasien.push().set({
       nama: nama,
       nik: nik,
       no: no,
       no_antrian: next,
       poli: 'bpu'
      })
  })
 } else if (poli == 'bpg'){
   bpg.transaction(function(currentRank){
     current = currentRank;
     next = currentRank + 1;

     return next;
  }, function(error, snapshot, committed){
       alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

       var pasien = faskes.child('pasien');
       pasien.push().set({
        nama: nama,
        nik: nik,
        no: no,
        no_antrian: next,
        poli: 'bpg'
       })
   })
 } else if (poli == 'kia'){
   kia.transaction(function(currentRank){
     current = currentRank;
     next = currentRank + 1;

     return next;
  }, function(error, snapshot, committed){
       alert('Nomor Antrian Anda:' + next + '\n' + '\n' + '*Tunjukan nomor antrian ini kepada puskesmas');

       var pasien = faskes.child('pasien');
       pasien.push().set({
        nama: nama,
        nik: nik,
        no: no,
        no_antrian: next,
        poli: 'kia'
       })
   })
 }
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';

import TouchRipple from 'src/TouchRipple';

class NavMenuItem extends Component {

    constructor(props) {

        super(props);

        this.menuHeight = 50;
        this.subMenuIndent = 20;

        this.menuGroupMousedownHandle = this::this.menuGroupMousedownHandle;
        this.menuMousedownHandle = this::this.menuMousedownHandle;

    }

    menuGroupMousedownHandle() {

        const {expandMenuName, options, expandMenu} = this.props;

        if (expandMenuName === options.text) {
            expandMenu('');
        } else {
            expandMenu(options.text);
        }

    }

    menuMousedownHandle() {
        const {options, depth, expandMenu, updateActivatedMenu} = this.props;
        depth === 0 && expandMenu('');
        updateActivatedMenu(options);
    }

    render() {

        const {expandMenuName, activatedMenu, options, depth, expandMenu, updateActivatedMenu} = this.props;
        const {menuHeight, subMenuIndent} = this;

        const collapsed = expandMenuName !== options.text,
            hasChildren = options.children && options.children.length > 0;

        return (
            <div className={`nav-menu-item ${collapsed ? 'collapsed' : ''} ${hasChildren ? 'hasChildren' : ''}`}>

                {/* title or link */}
                {
                    hasChildren ?
                        (

                                    {options.text}

                                <TouchRipple/>

                        )
                        :
                        (
                            <Link
                                className={'nav-menu-item-link' + (activatedMenu && activatedMenu.route === options.route ? ' router-link-active' : '')}
                                to={options.route}
                                disabled={options.disabled}
                                onClick={this.menuMousedownHandle}>

                                    {options.text}

                                <TouchRipple/>

                            </Link>
                        )
                }

                {/* sub menu */}
                {
                    hasChildren
                        ? (

                                {
                                    options.children.map((item, index) =>
                                        <NavMenuItem key={index}
                                                     expandMenuName={expandMenuName}
                                                     activatedMenu={activatedMenu}
                                                     options={item}
                                                     depth={depth + 1}
                                                     expandMenu={expandMenu}
                                                     updateActivatedMenu={updateActivatedMenu}/>
                                    )
                                }

                        )
                        : null
                }

        );

    }
}

NavMenuItem.propTypes = {

    expandMenuName: PropTypes.string,
    activatedMenu: PropTypes.object,

    options: PropTypes.object,
    depth: PropTypes.number,

    expandMenu: PropTypes.func,
    updateActivatedMenu: PropTypes.func

};

NavMenuItem.defaultProps = {

    expandMenuName: '',
    activatedMenu: null,

    options: null,
    depth: 0

};

export default NavMenuItem;<commit_msg>update NavMenuItem<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import classNames from 'classnames';

import TouchRipple from 'src/TouchRipple';

class NavMenuItem extends Component {

    constructor(props) {

        super(props);

        this.menuHeight = 50;
        this.subMenuIndent = 20;

    }

    menuGroupMousedownHandler = () => {

        const {expandMenuName, options, expandMenu} = this.props;

        if (expandMenuName === options.text) {
            expandMenu('');
        } else {
            expandMenu(options.text);
        }

    };

    menuMousedownHandler = () => {
        const {options, depth, expandMenu, updateActivatedMenu} = this.props;
        depth === 0 && expandMenu('');
        updateActivatedMenu(options);
    };

    render() {

        const {expandMenuName, activatedMenu, options, depth, expandMenu, updateActivatedMenu} = this.props,
            {menuHeight, subMenuIndent} = this,

            collapsed = expandMenuName !== options.text,
            hasChildren = options.children && options.children.length > 0,

            linkClassName = classNames('nav-menu-item-link', {
                'router-link-active': activatedMenu && activatedMenu.route === options.route
            });

        return (
            <div className={`nav-menu-item ${collapsed ? 'collapsed' : ''} ${hasChildren ? 'hasChildren' : ''}`}>

                {/* title or link */}
                {
                    hasChildren ?

                                {options.text}

                            <TouchRipple/>

                        :
                        <Link className={linkClassName}
                              to={options.route}
                              disabled={options.disabled}
                              onClick={this.menuMousedownHandler}>

                                {options.text}

                            <TouchRipple/>

                        </Link>
                }

                {/* sub menu */}
                {
                    hasChildren ?

                            {
                                options && options.children && options.children.map((item, index) =>
                                    <NavMenuItem key={index}
                                                 expandMenuName={expandMenuName}
                                                 activatedMenu={activatedMenu}
                                                 options={item}
                                                 depth={depth + 1}
                                                 expandMenu={expandMenu}
                                                 updateActivatedMenu={updateActivatedMenu}/>
                                )
                            }

                        :
                        null
                }

        );

    }
}

NavMenuItem.propTypes = {

    expandMenuName: PropTypes.string,
    activatedMenu: PropTypes.object,

    options: PropTypes.object,
    depth: PropTypes.number,

    expandMenu: PropTypes.func,
    updateActivatedMenu: PropTypes.func

};

NavMenuItem.defaultProps = {
    expandMenuName: '',
    depth: 0
};

export default NavMenuItem;<|endoftext|>


<commit_before>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = [];
        self.displayedNodes = [];
        //self.lastLogin = '';
        // NEED TO FIGURE OUT WHAT TO DO ABOUT LASTLOGIN.
        self.lastLogin = '2016-01-01T15:20:11.531000';
        self.commentsCount = {};
        self.logsCount = {};
        self.sortState = m.prop();
        self.countState = m.prop();

        // Load node list
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors', 'page[size]': 100}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result){
            result.data.forEach(function(node){
                self.nodes.push(node);
            });
            self.sortDateDescending();
            self.countState = 10;
            self.displayedNodes = self.nodes.splice(0, 10)
        });

        // Load last login
        self.getLastLoginDate = function () {
            var url = $osf.apiV2Url('users/me/', {});
            var promise = m.request({method: 'GET', url: url, config : xhrconfig});
            promise.then(function(result) {
                self.lastLogin = result.data.attributes.last_login
            }
            );
            return promise
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };
        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors == 2) {
                return self.getFamilyName(0, node) + ' and ' +
                        self.getFamilyName(1, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                        self.getFamilyName(1, node) + ', ' +
                        self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.getRecentComments = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/comments/',
                { query : { 'filter[date_modified][gte]': self.lastLogin}}
            );
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result) {
                self.commentsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentCommentCount = function (node) {
            if (node.id in self.commentsCount) {
                return self.commentsCount[node.id]
            }
            else {
                self.getRecentComments(node);
                return self.commentsCount[node.id]
            }
        };

        self.getRecentLogs = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/logs/', { query : {'filter[action][ne]': 'comment_added',
                'filter[date][gte]': self.lastLogin}});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result){
                self.logsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentLogsCount = function(node) {
            if (node.id in self.logsCount){
                return self.logsCount[node.id]
            }
            else {
                self.getRecentLogs(node);
                return self.logsCount[node.id]
          }
        };

        self.loadUpToTen = function () {
            requested = self.nodes.splice(0, 10);
            for (i = 0; i < requested.length; i++) {
                self.displayedNodes.push(requested[i])
            }
            self.countState = self.displayedNodes.length;
            return self.displayedNodes
        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreToNodeList = function (missingNodes) {
            for (i = 0; i < missingNodes.length ; i++) {
                self.nodes.push(missingNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'alphaAsc';
            return self.displayedNodes
        };

        self.sortAlphabeticalDescending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'alphaDesc';
            return self.displayedNodes

        };

        self.sortDateDescending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'dateDesc';
            return self.displayedNodes
        };

        self.sortDateAscending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'dateAsc';
            return self.displayedNodes
        };

        //self.getLastLoginDate()

    },
    view : function(ctrl) {
        function projectView(project) {
            return m('tr', [
                m('td', m("a", {href: '/'+ project.id}, project.attributes.title)),
                m('td', ctrl.getContributors(project)),
                m('td', ctrl.formatDate(project)),
                m('td', ctrl.loadRecentCommentCount(project)),
                m('td', ctrl.loadRecentLogsCount(project))
            ])
        }

        function loadMoreButton() {
            if (ctrl.nodes.length !== 0){
                return m('button', { onclick: function() {
                    ctrl.loadUpToTen() }
                }, 'Load more')
            }
        }

        return m('div', [
            m('input[type=search]', 'Quick search projects'),
            m('div', {'class': 'container-fluid'},
                m('table', [
                    m('tr', [
                        m('th', {class: 'col-md-5'}, 'Name',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortAlphabeticalAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                                ctrl.sortAlphabeticalDescending()
                            }})),
                        m('th', {class: 'col-md-3'}, 'Contributors'),
                        m('th', {class: 'col-md-2'}, 'Modified',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortDateAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                               ctrl.sortDateDescending()
                           }})
                        ),
                        m('th', {class: 'col-md-1'}, 'New comments'),
                        m('th', {class: 'col-md-1'}, 'New logs')
                    ]),

                    ctrl.displayedNodes.map(function(n){
                        return projectView(n)
                    }),
                    loadMoreButton()
            ])
            )
        ])
    }
};

module.exports = quickSearchProject;

<commit_msg>Add method to quick search projects on title.<commit_after>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = [];
        self.displayedNodes = [];
        //self.lastLogin = '';
        // NEED TO FIGURE OUT WHAT TO DO ABOUT LASTLOGIN.
        self.lastLogin = '2016-01-01T15:20:11.531000';
        self.commentsCount = {};
        self.logsCount = {};
        self.sortState = m.prop();
        self.countState = m.prop();

        // Load node list
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors', 'page[size]': 100}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result){
            result.data.forEach(function(node){
                self.nodes.push(node);
            });
            self.sortDateDescending();
            self.countState = 10;
            self.displayedNodes = self.nodes.splice(0, 10)
        });

        // Load last login
        self.getLastLoginDate = function () {
            var url = $osf.apiV2Url('users/me/', {});
            var promise = m.request({method: 'GET', url: url, config : xhrconfig});
            promise.then(function(result) {
                self.lastLogin = result.data.attributes.last_login
            }
            );
            return promise
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };
        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors == 2) {
                return self.getFamilyName(0, node) + ' and ' +
                        self.getFamilyName(1, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                        self.getFamilyName(1, node) + ', ' +
                        self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.getRecentComments = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/comments/',
                { query : { 'filter[date_modified][gte]': self.lastLogin}}
            );
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result) {
                self.commentsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentCommentCount = function (node) {
            if (node.id in self.commentsCount) {
                return self.commentsCount[node.id]
            }
            else {
                self.getRecentComments(node);
                return self.commentsCount[node.id]
            }
        };

        self.getRecentLogs = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/logs/', { query : {'filter[action][ne]': 'comment_added',
                'filter[date][gte]': self.lastLogin}});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result){
                self.logsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentLogsCount = function(node) {
            if (node.id in self.logsCount){
                return self.logsCount[node.id]
            }
            else {
                self.getRecentLogs(node);
                return self.logsCount[node.id]
          }
        };

        self.loadUpToTen = function () {
            requested = self.nodes.splice(0, 10);
            for (i = 0; i < requested.length; i++) {
                self.displayedNodes.push(requested[i])
            }
            self.countState = self.displayedNodes.length;
            return self.displayedNodes
        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreToNodeList = function (missingNodes) {
            for (i = 0; i < missingNodes.length ; i++) {
                self.nodes.push(missingNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'alphaAsc';
            return self.displayedNodes
        };

        self.sortAlphabeticalDescending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'alphaDesc';
            return self.displayedNodes

        };

        self.sortDateDescending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'dateDesc';
            return self.displayedNodes
        };

        self.sortDateAscending = function () {
            self.restoreToNodeList(self.displayedNodes);
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, self.countState);
            self.sortState = 'dateAsc';
            return self.displayedNodes
        };

        self.quickSearch = function () {
            var query = document.getElementById('searchQuery').value;
            self.restoreToNodeList(self.nonMatchingNodes);
            self.restoreToNodeList(self.displayedNodes);
            self.displayedNodes = [];
            self.nonMatchingNodes = [];
            // if backspace completely, previous nodes with prior sorting/count will be displayed
            if (query === '') {
                self.sortByPreviousField();
                return self.displayedNodes

            }
            else {
                for (var n = self.nodes.length - 1; n >= 0; n--) {
                    if (self.nodes[n].attributes.title.toUpperCase().indexOf(query.toUpperCase()) === -1) {
                        self.nonMatchingNodes.push(self.nodes[n]);
                        self.nodes.splice(n, 1)
                    }
                }
                console.log(self.nodes)
                var numDisplay = Math.min(self.nodes.length, self.countState);
                for (var i = 0; i < numDisplay; i++) {
                    self.displayedNodes.push(self.nodes[i])

                }
                self.nodes.splice(0, numDisplay);
                console.log(self.displayedNodes);
                return self.displayedNodes
            }

        };
        //self.getLastLoginDate()

    },
    view : function(ctrl) {
        function projectView(project) {
            console.log(ctrl.nodes.length, ctrl.displayedNodes.length, ctrl.nonMatchingNodes.length, ctrl.sortState, ctrl.countState)
            return m('tr', [
                m('td', m("a", {href: '/'+ project.id}, project.attributes.title)),
                m('td', ctrl.getContributors(project)),
                m('td', ctrl.formatDate(project)),
                m('td', ctrl.loadRecentCommentCount(project)),
                m('td', ctrl.loadRecentLogsCount(project))
            ])
        }

        function loadMoreButton() {
            if (ctrl.nodes.length !== 0){
                return m('button', { onclick: function() {
                    ctrl.loadUpToTen() }
                }, 'Load more')
            }
        }

        return m('div', [
            m('input[type=search]', {id: 'searchQuery', onkeyup: function() {ctrl.quickSearch()}}, 'Quick search projects'),
            m('div', {'class': 'container-fluid'},
                m('table', [
                    m('tr', [
                        m('th', {class: 'col-md-5'}, 'Name',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortAlphabeticalAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                                ctrl.sortAlphabeticalDescending()
                            }})),
                        m('th', {class: 'col-md-3'}, 'Contributors'),
                        m('th', {class: 'col-md-2'}, 'Modified',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortDateAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                               ctrl.sortDateDescending()
                           }})
                        ),
                        m('th', {class: 'col-md-1'}, 'New comments'),
                        m('th', {class: 'col-md-1'}, 'New logs')
                    ]),

                    ctrl.displayedNodes.map(function(n){
                        return projectView(n)
                    }),
                    loadMoreButton()
            ])
            )
        ])
    }
};

module.exports = quickSearchProject;

<|endoftext|>


<commit_before>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

ns.push({
	'alias': 'hasClassSupport',
	'path': '@stdlib/utils/detect-class-support',
	'value': require( '@stdlib/utils/detect-class-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasFunctionNameSupport',
	'path': '@stdlib/utils/detect-function-name-support',
	'value': require( '@stdlib/utils/detect-function-name-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasGeneratorSupport',
	'path': '@stdlib/utils/detect-generator-support',
	'value': require( '@stdlib/utils/detect-generator-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasMapSupport',
	'path': '@stdlib/utils/detect-map-support',
	'value': require( '@stdlib/utils/detect-map-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasSetSupport',
	'path': '@stdlib/utils/detect-set-support',
	'value': require( '@stdlib/utils/detect-set-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasSymbolSupport',
	'path': '@stdlib/utils/detect-symbol-support',
	'value': require( '@stdlib/utils/detect-symbol-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasToStringTagSupport',
	'path': '@stdlib/utils/detect-tostringtag-support',
	'value': require( '@stdlib/utils/detect-tostringtag-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakMapSupport',
	'path': '@stdlib/utils/detect-weakmap-support',
	'value': require( '@stdlib/utils/detect-weakmap-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakSetSupport',
	'path': '@stdlib/utils/detect-weakset-support',
	'value': require( '@stdlib/utils/detect-weakset-support' ),
	'type': 'Function',
	'related': []
});

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/**
 * Code from http://www.html5rocks.com/en/tutorials/doodles/gamepad/
 * with tester switched out for DRONE.Gamepad
 */
var gamepadSupport = {
    TYPICAL_BUTTON_COUNT: 16,
    TYPICAL_AXIS_COUNT: 4,
    ticking: false,
    gamepads: [],
    prevRawGamepadTypes: [],
    prevTimestamps: [],
    sendUpdates: false,
    init: function () {
        var gamepadSupportAvailable = navigator.getGamepads ||
            !!navigator.webkitGetGamepads ||
            !!navigator.webkitGamepads;
        if (!gamepadSupportAvailable) {
            DRONE.Gamepad.showNotSupported();
        } else {
            // Check and see if gamepadconnected/gamepaddisconnected is supported.
            // If so, listen for those events and don't start polling until a gamepad
            // has been connected.
            if ('ongamepadconnected' in window) {
              window.addEventListener('gamepadconnected',
                                    gamepadSupport.onGamepadConnect, false);
              window.addEventListener('gamepaddisconnected',
                                      gamepadSupport.onGamepadDisconnect, false);
            } else {
              // If connection events are not supported just start polling
              gamepadSupport.startPolling();
            }
        }
    },
    onGamepadConnect: function (event) {
        gamepadSupport.gamepads.push(event.gamepad);
        DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);
        gamepadSupport.startPolling();
    },
    onGamepadDisconnect: function (event) {
        for (var i in gamepadSupport.gamepads) {
            if (gamepadSupport.gamepads[i].index == event.gamepad.index) {
                gamepadSupport.gamepads.splice(i, 1);
                break;
            }
        }
        if (gamepadSupport.gamepads.length === 0) {
            gamepadSupport.stopPolling();
        }
        DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);
    },
    startPolling: function () {
        if (!gamepadSupport.ticking) {
            gamepadSupport.ticking = true;
            gamepadSupport.tick();
        }
    },
    stopPolling: function () {
        gamepadSupport.ticking = false;
    },
    tick: function () {
        gamepadSupport.pollStatus();
        gamepadSupport.scheduleNextTick();
    },
    scheduleNextTick: function () {
        if (gamepadSupport.ticking) {
            if (window.requestAnimationFrame) {
                window.requestAnimationFrame(gamepadSupport.tick);
            } else if (window.mozRequestAnimationFrame) {
                window.mozRequestAnimationFrame(gamepadSupport.tick);
            } else if (window.webkitRequestAnimationFrame) {
                window.webkitRequestAnimationFrame(gamepadSupport.tick);
            }
        }
    },
    pollStatus: function () {
        gamepadSupport.pollGamepads();
        for (var i in gamepadSupport.gamepads) {
            var gamepad = gamepadSupport.gamepads[i];
            gamepadSupport.updateDisplay(i);
        }
    },
    pollGamepads: function () {
        var rawGamepads =
            (navigator.getGamepads && navigator.getGamepads()) ||
            (navigator.webkitGetGamepads && navigator.webkitGetGamepads());
        if (rawGamepads) {
            gamepadSupport.gamepads = [];
            var gamepadsChanged = false;
            for (var i = 0; i < rawGamepads.length; i++) {
                if (typeof rawGamepads[i] != gamepadSupport.prevRawGamepadTypes[i]) {
                    gamepadsChanged = true;
                    gamepadSupport.prevRawGamepadTypes[i] = typeof rawGamepads[i];
                }
                if (rawGamepads[i]) {
                    gamepadSupport.gamepads.push(rawGamepads[i]);
                }
            }

            DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);

        }
    },
    updateDisplay: function (gamepadId) {

        if(this.sendUpdates) {
            var gamepad = gamepadSupport.gamepads[gamepadId];
            DRONE.Gamepad.updateButton(gamepad.buttons[0], gamepadId, 'button-1');
            DRONE.Gamepad.updateButton(gamepad.buttons[1], gamepadId, 'button-2');
            DRONE.Gamepad.updateButton(gamepad.buttons[2], gamepadId, 'button-3');
            DRONE.Gamepad.updateButton(gamepad.buttons[3], gamepadId, 'button-4');
            DRONE.Gamepad.updateButton(gamepad.buttons[4], gamepadId, 'button-left-shoulder-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[6], gamepadId, 'button-left-shoulder-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[5], gamepadId, 'button-right-shoulder-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[7], gamepadId, 'button-right-shoulder-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[8], gamepadId, 'button-select');
            DRONE.Gamepad.updateButton(gamepad.buttons[9], gamepadId, 'button-start');
            DRONE.Gamepad.updateButton(gamepad.buttons[10], gamepadId, 'stick-1');
            DRONE.Gamepad.updateButton(gamepad.buttons[11], gamepadId, 'stick-2');
            DRONE.Gamepad.updateButton(gamepad.buttons[12], gamepadId, 'button-dpad-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[13], gamepadId, 'button-dpad-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[14], gamepadId, 'button-dpad-left');
            DRONE.Gamepad.updateButton(gamepad.buttons[15], gamepadId, 'button-dpad-right');

            DRONE.Gamepad.updateAxis(gamepad.axes[0], gamepadId, 'stick-1-axis-x', 'stick-1', true);
            DRONE.Gamepad.updateAxis(gamepad.axes[1], gamepadId, 'stick-1-axis-y', 'stick-1', false);
            DRONE.Gamepad.updateAxis(gamepad.axes[2], gamepadId, 'stick-2-axis-x', 'stick-2', true);
            DRONE.Gamepad.updateAxis(gamepad.axes[3], gamepadId, 'stick-2-axis-y', 'stick-2', false);
            var extraButtonId = gamepadSupport.TYPICAL_BUTTON_COUNT;
            while (typeof gamepad.buttons[extraButtonId] != 'undefined') {
                DRONE.Gamepad.updateButton(gamepad.buttons[extraButtonId], gamepadId, 'extra-button-' + extraButtonId);
                extraButtonId++;
            }
            var extraAxisId = gamepadSupport.TYPICAL_AXIS_COUNT;
            while (typeof gamepad.axes[extraAxisId] != 'undefined') {
                DRONE.Gamepad.updateAxis(gamepad.axes[extraAxisId], gamepadId, 'extra-axis-' + extraAxisId);
                extraAxisId++;
            }
        }

        this.sendUpdates = !this.sendUpdates;
    }
};
<commit_msg>parrot-ar-drone: throttle gamepad events by timestamp<commit_after>/**
 * Code from http://www.html5rocks.com/en/tutorials/doodles/gamepad/
 * with tester switched out for DRONE.Gamepad
 */
var gamepadSupport = {
    TYPICAL_BUTTON_COUNT: 16,
    TYPICAL_AXIS_COUNT: 4,
    ticking: false,
    gamepads: [],
    prevRawGamepadTypes: [],
    prevTimestamps: [],
    sendUpdates: false,
    init: function () {
        var gamepadSupportAvailable = navigator.getGamepads ||
            !!navigator.webkitGetGamepads ||
            !!navigator.webkitGamepads;
        if (!gamepadSupportAvailable) {
            DRONE.Gamepad.showNotSupported();
        } else {
            // Check and see if gamepadconnected/gamepaddisconnected is supported.
            // If so, listen for those events and don't start polling until a gamepad
            // has been connected.
            if ('ongamepadconnected' in window) {
              window.addEventListener('gamepadconnected',
                                    gamepadSupport.onGamepadConnect, false);
              window.addEventListener('gamepaddisconnected',
                                      gamepadSupport.onGamepadDisconnect, false);
            } else {
              // If connection events are not supported just start polling
              gamepadSupport.startPolling();
            }
        }
    },
    onGamepadConnect: function (event) {
        gamepadSupport.gamepads.push(event.gamepad);
        DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);
        gamepadSupport.startPolling();
    },
    onGamepadDisconnect: function (event) {
        for (var i in gamepadSupport.gamepads) {
            if (gamepadSupport.gamepads[i].index == event.gamepad.index) {
                gamepadSupport.gamepads.splice(i, 1);
                break;
            }
        }
        if (gamepadSupport.gamepads.length === 0) {
            gamepadSupport.stopPolling();
        }
        DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);
    },
    startPolling: function () {
        if (!gamepadSupport.ticking) {
            gamepadSupport.ticking = true;
            gamepadSupport.tick();
        }
    },
    stopPolling: function () {
        gamepadSupport.ticking = false;
    },
    tick: function () {
        gamepadSupport.pollStatus();
        gamepadSupport.scheduleNextTick();
    },
    scheduleNextTick: function () {
        if (gamepadSupport.ticking) {
            if (window.requestAnimationFrame) {
                window.requestAnimationFrame(gamepadSupport.tick);
            } else if (window.mozRequestAnimationFrame) {
                window.mozRequestAnimationFrame(gamepadSupport.tick);
            } else if (window.webkitRequestAnimationFrame) {
                window.webkitRequestAnimationFrame(gamepadSupport.tick);
            }
        }
    },
    pollStatus: function () {
        gamepadSupport.pollGamepads();
        for (var i in gamepadSupport.gamepads) {
            var gamepad = gamepadSupport.gamepads[i];
            if (gamepad.timestamp &&
                (gamepad.timestamp == gamepadSupport.prevTimestamps[i])) {
              continue;
            }
            gamepadSupport.prevTimestamps[i] = gamepad.timestamp;
            gamepadSupport.updateDisplay(i);
        }
    },
    pollGamepads: function () {
        var rawGamepads =
            (navigator.getGamepads && navigator.getGamepads()) ||
            (navigator.webkitGetGamepads && navigator.webkitGetGamepads());
        if (rawGamepads) {
            gamepadSupport.gamepads = [];
            var gamepadsChanged = false;
            for (var i = 0; i < rawGamepads.length; i++) {
                if (typeof rawGamepads[i] != gamepadSupport.prevRawGamepadTypes[i]) {
                    gamepadsChanged = true;
                    gamepadSupport.prevRawGamepadTypes[i] = typeof rawGamepads[i];
                }
                if (rawGamepads[i]) {
                    gamepadSupport.gamepads.push(rawGamepads[i]);
                }
            }

            DRONE.Gamepad.updateGamepads(gamepadSupport.gamepads);

        }
    },
    updateDisplay: function (gamepadId) {

        if(this.sendUpdates) {
            var gamepad = gamepadSupport.gamepads[gamepadId];
            DRONE.Gamepad.updateButton(gamepad.buttons[0], gamepadId, 'button-1');
            DRONE.Gamepad.updateButton(gamepad.buttons[1], gamepadId, 'button-2');
            DRONE.Gamepad.updateButton(gamepad.buttons[2], gamepadId, 'button-3');
            DRONE.Gamepad.updateButton(gamepad.buttons[3], gamepadId, 'button-4');
            DRONE.Gamepad.updateButton(gamepad.buttons[4], gamepadId, 'button-left-shoulder-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[6], gamepadId, 'button-left-shoulder-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[5], gamepadId, 'button-right-shoulder-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[7], gamepadId, 'button-right-shoulder-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[8], gamepadId, 'button-select');
            DRONE.Gamepad.updateButton(gamepad.buttons[9], gamepadId, 'button-start');
            DRONE.Gamepad.updateButton(gamepad.buttons[10], gamepadId, 'stick-1');
            DRONE.Gamepad.updateButton(gamepad.buttons[11], gamepadId, 'stick-2');
            DRONE.Gamepad.updateButton(gamepad.buttons[12], gamepadId, 'button-dpad-top');
            DRONE.Gamepad.updateButton(gamepad.buttons[13], gamepadId, 'button-dpad-bottom');
            DRONE.Gamepad.updateButton(gamepad.buttons[14], gamepadId, 'button-dpad-left');
            DRONE.Gamepad.updateButton(gamepad.buttons[15], gamepadId, 'button-dpad-right');

            DRONE.Gamepad.updateAxis(gamepad.axes[0], gamepadId, 'stick-1-axis-x', 'stick-1', true);
            DRONE.Gamepad.updateAxis(gamepad.axes[1], gamepadId, 'stick-1-axis-y', 'stick-1', false);
            DRONE.Gamepad.updateAxis(gamepad.axes[2], gamepadId, 'stick-2-axis-x', 'stick-2', true);
            DRONE.Gamepad.updateAxis(gamepad.axes[3], gamepadId, 'stick-2-axis-y', 'stick-2', false);
            var extraButtonId = gamepadSupport.TYPICAL_BUTTON_COUNT;
            while (typeof gamepad.buttons[extraButtonId] != 'undefined') {
                DRONE.Gamepad.updateButton(gamepad.buttons[extraButtonId], gamepadId, 'extra-button-' + extraButtonId);
                extraButtonId++;
            }
            var extraAxisId = gamepadSupport.TYPICAL_AXIS_COUNT;
            while (typeof gamepad.axes[extraAxisId] != 'undefined') {
                DRONE.Gamepad.updateAxis(gamepad.axes[extraAxisId], gamepadId, 'extra-axis-' + extraAxisId);
                extraAxisId++;
            }
        }

        this.sendUpdates = !this.sendUpdates;
    }
};
<|endoftext|>


<commit_before>$(document).on('click', 'div.item-action a', function () {
  var href = $(this).attr('href');
  $('form').attr('action', href);
});

$(document).on('click', '.btn-favorite', function (e) {
  e.stopImmediatePropagation();

  var id = $(this).data('id'),
      url = $(this).data('url'),
      button = $(this).children('i'),
      className = button[0].classList[1],
      pathName = window.location.pathname;

  $.ajax({
    url: url,
    dataType: 'json',
    success: function (data) {
      if (pathName === '/profile/') {
        var elements = document.querySelectorAll("#" + id),
            count = document.querySelector('span#' + data.id),
            comma = document.querySelector('span#comma'),
            text = document.querySelector('span.text-muted#' + data.id),
            dataCount;

        elements.forEach(function(node){
          node.parentNode.removeChild(node);
        });

        switch (data.id) {
          case 'events':
            dataCount = data.event_count;
            break;
          case 'artists':
            dataCount = data.artist_count;
            break;
        }

        if (dataCount) {
          count.textContent = dataCount;
        } else {
          var tab = document.querySelector('div.tab-pane#tab_' + data.id),
              tabRow = document.querySelector('div.row#' + data.id),
              tabModal = document.querySelector('div.modal#' + data.id),
              bookmark = document.querySelector('div.tab-pane#tab_bookmark'),
              bookmarkRow = document.querySelector('div.row#bookmark_' + data.id),
              bookmarkModal = document.querySelector('div.modal#bookmark_' + data.id);

          text.remove();
          count.remove();

          if (comma) {
            comma.remove();
          }

          bookmark.replaceChild(bookmarkModal.cloneNode(true), bookmarkRow);
          $('div.modal#bookmark_' + data.id + ':first').removeClass('modal');

          tab.replaceChild(tabModal.cloneNode(true), tabRow);
          $('div.modal#' + data.id + ':first').removeClass('modal');
        }
      } else {
        var selector = '#' + id + ' span.item-meta-stats',
            userCount = document.querySelector(selector),
            userCountClass = $(selector).hasClass('text-xs');

        switch (className) {
          case 'fa-star':
            button.removeClass('fa-star');
            button.addClass('fa-star-o');
            break;
          case 'fa-star-o':
            button.removeClass('fa-star-o');
            button.addClass('fa-star');
            break;
        }

        if (data.user_count) {
          if (userCountClass) {
            userCount.innerHTML = ' ' + data.user_count;
          } else {
            userCount.innerHTML = data.user_count;
          }
        } else {
          userCount.innerHTML = '&nbsp';
        }
      }
    }
  });
});
<commit_msg>Fix Venue modal in profile<commit_after>$(document).on('click', 'div.item-action a', function () {
  var href = $(this).attr('href');
  $('form').attr('action', href);
});

$(document).on('click', '.btn-favorite', function (e) {
  e.stopImmediatePropagation();

  var id = $(this).data('id'),
      url = $(this).data('url'),
      button = $(this).children('i'),
      className = button[0].classList[1],
      pathName = window.location.pathname;

  $.ajax({
    url: url,
    dataType: 'json',
    success: function (data) {
      if (pathName === '/profile/') {
        var elements = document.querySelectorAll("#" + id),
            count = document.querySelector('span#' + data.id),
            comma = document.querySelector('span#comma'),
            text = document.querySelector('span.text-muted#' + data.id),
            dataCount;

        elements.forEach(function(node){
          node.parentNode.removeChild(node);
        });

        switch (data.id) {
          case 'events':
            dataCount = data.event_count;
            break;
          case 'artists':
            dataCount = data.artist_count;
            break;
        }

        if (dataCount) {
          count.textContent = dataCount;
        } else {
          var tab = document.querySelector('div.tab-pane#tab_' + data.id),
              tabRow = document.querySelector('div.row#' + data.id),
              tabModal = document.querySelector('div.modal#' + data.id),
              bookmark = document.querySelector('div.tab-pane#tab_bookmark'),
              bookmarkRow = document.querySelector('div.row#bookmark_' + data.id),
              bookmarkModal = document.querySelector('div.modal#bookmark_' + data.id);

          if (text) {
            text.remove();
          }

          if (count) {
            count.remove();
          }

          if (comma) {
            comma.remove();
          }

          if (bookmark && bookmarkRow && bookmarkModal) {
            bookmark.replaceChild(bookmarkModal.cloneNode(true), bookmarkRow);
            $('div.modal#bookmark_' + data.id + ':first').removeClass('modal');
          }

          if (tab && tabRow && tabModal) {
            tab.replaceChild(tabModal.cloneNode(true), tabRow);
            $('div.modal#' + data.id + ':first').removeClass('modal');
          }
        }
      } else {
        var selector = '#' + id + ' span.item-meta-stats',
            userCount = document.querySelector(selector),
            userCountClass = $(selector).hasClass('text-xs');

        switch (className) {
          case 'fa-star':
            button.removeClass('fa-star');
            button.addClass('fa-star-o');
            break;
          case 'fa-star-o':
            button.removeClass('fa-star-o');
            button.addClass('fa-star');
            break;
        }

        if (data.user_count) {
          if (userCountClass) {
            userCount.innerHTML = ' ' + data.user_count;
          } else {
            userCount.innerHTML = data.user_count;
          }
        } else {
          userCount.innerHTML = '&nbsp';
        }
      }
    }
  });
});
<|endoftext|>


<commit_before>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3.0

var streams = [
    ['audio/ogg', "http://engine.wuvt.vt.edu:8000/wuvt.ogg"],
    ['audio/aac', "http://engine.wuvt.vt.edu:8000/wuvt.aac"]
];
var streamPlaying = false;

function initPlayer() {
    var playBtn = $('<button>');
    playBtn.attr('title', "Play");
    playBtn.attr('id', "stream_btn");
    playBtn.text("Play/Stop");
    $('#robot').append(playBtn);

    var volBtn = $('<button>');
    volBtn.attr('title', "Volume Control");
    volBtn.attr('id', "volume_btn");
    volBtn.text("Volume Control");
    $('#robot').append(volBtn);

    var audioTag = document.createElement('audio');

    for(i in streams) {
        var stream = streams[i];
        if(audioTag.canPlayType(stream[0])) {
            initStream(stream[0], stream[1]);
            return;
        }
    }

    $('#stream_btn').addClass('disabled');
    $('#stream_btn').click(warnBrokenPlayer);

    $('#volume_btn').addClass('disabled');
    $('#volume_btn').click(warnBrokenPlayer);
}

function initStream(streamMime, streamUrl) {
    // This doesn't work on Chrome for Android:
    // https://code.google.com/p/chromium/issues/detail?id=178297

    $('#stream_btn').click(function() {
        if(!streamPlaying) {
            var stream = document.createElement('audio');
            $(stream).attr('id', "wuvt_stream");
            $(stream).attr('type', streamMime);
            $(stream).attr('src', streamUrl);
            $('body').append(stream);

            stream.addEventListener('play', function() {
                $('#stream_btn').addClass('playing');
                $('#stream_btn').attr('title', "Stop");
                $('#stream_btn').removeAttr('disabled');
            });

            // workaround to deal with playback stopping when metadata changes
            // https://bugzil.la/455165
            stream.addEventListener("ended", function() {
                $('#wuvt_stream').attr('src', "");
                $('#wuvt_stream').attr('src', streamUrl);
            });

            // chrome workaround for the same thing
            // https://code.google.com/p/chromium/issues/detail?id=175281
            stream.addEventListener("error", function() {
                $('#wuvt_stream').attr('src', "");
                $('#wuvt_stream').attr('src', streamUrl);
                $('#wuvt_stream').trigger('play');
            });

            stream.play();

            // display an alert after 5 seconds if the stream hasn't started
            window.setTimeout(function() {
                if(streamPlaying && !$('#stream_btn').hasClass('playing')) {
                    alert("Streaming problems? Check the Listen Live page for other ways to listen to WUVT!");
                }
            }, 5000);

            streamPlaying = true;
            $('#stream_btn').attr('title', "Buffering...");
            $('#stream_btn').attr('disabled', "disabled");
        }
        else {
            $('#wuvt_stream').attr('src', "");
            $('#wuvt_stream').remove();

            streamPlaying = false;
            $('#stream_btn').removeClass('playing');
            $('#stream_btn').attr('title', "Play");

            $('#volume_box').removeClass('visible');
        }

        return false;
    });

    initVolume();
}

function initVolume() {
    var volbox = document.createElement('div');
    $(volbox).attr('id', "volume_box");

    // create volume slider
    var slider = document.createElement('div');
    $(slider).attr('id', "volume_slider");
    $(volbox).append(slider);

    // create mute button
    var mutebtn = document.createElement('button');
    $(mutebtn).attr('id', "volume_mute_btn");
    $(mutebtn).attr('title', "Mute");
    $(mutebtn).text("Mute");
    $(volbox).append(mutebtn);

    $('#mainheader').append(volbox);

    // adjust volume box placement
    $(document).ready(positionVolumeBox);
    $(document).on('pageChange', positionVolumeBox);

    $('#volume_btn').click(function() {
        $('#volume_btn').toggleClass('active');
        $('#volume_box').toggleClass('visible');
    });

    $('#volume_slider').slider({
        'orientation': "vertical",
        'value': 1,
        'step': 0.05,
        'range': "min",
        'max': 1,
        'animate': false,
        'slide': function(e, slider) {
            $('#wuvt_stream').prop('muted', false);
            $('#wuvt_stream').prop('volume', slider.value);
        },
    });

    $('#volume_mute_btn').click(function() {
        if(!$('#wuvt_stream').prop('muted')) {
            $('#wuvt_stream').prop('muted', true);
            $('#volume_slider').slider('option', 'value', 0);
        }
        else {
            $('#wuvt_stream').prop('muted', false);
            $('#volume_slider').slider('option', 'value',
                $('#wuvt_stream').prop('volume'));
        }
    });
}

function positionVolumeBox() {
    $('#volume_btn').removeClass('active');
    $('#volume_box').removeClass('visible');

    var btn = $('#volume_btn');
    var offsetTop = btn.offset().top + btn.outerHeight();
    var offsetLeft = btn.offset().left + (btn.outerWidth() / 2) -
        ($('#volume_box').outerWidth() / 2);
    $('#volume_box').css('top', offsetTop + "px");
    $('#volume_box').css('left', offsetLeft + "px");
}

function warnBrokenPlayer() {
    alert("Sorry, the WUVT live stream player is not supported by your browser. Please see the Listen Live page for other ways to listen to WUVT, or switch to Google Chrome or Mozilla Firefox.");
}

// @license-end
<commit_msg>the stream now works in chrome for android<commit_after>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3.0

var streams = [
    ['audio/ogg', "http://engine.wuvt.vt.edu:8000/wuvt.ogg"],
    ['audio/aac', "http://engine.wuvt.vt.edu:8000/wuvt.aac"]
];
var streamPlaying = false;

function initPlayer() {
    var playBtn = $('<button>');
    playBtn.attr('title', "Play");
    playBtn.attr('id', "stream_btn");
    playBtn.text("Play/Stop");
    $('#robot').append(playBtn);

    var volBtn = $('<button>');
    volBtn.attr('title', "Volume Control");
    volBtn.attr('id', "volume_btn");
    volBtn.text("Volume Control");
    $('#robot').append(volBtn);

    var audioTag = document.createElement('audio');

    for(i in streams) {
        var stream = streams[i];
        if(audioTag.canPlayType(stream[0])) {
            initStream(stream[0], stream[1]);
            return;
        }
    }

    $('#stream_btn').addClass('disabled');
    $('#stream_btn').click(warnBrokenPlayer);

    $('#volume_btn').addClass('disabled');
    $('#volume_btn').click(warnBrokenPlayer);
}

function initStream(streamMime, streamUrl) {
    $('#stream_btn').click(function() {
        if(!streamPlaying) {
            var stream = document.createElement('audio');
            $(stream).attr('id', "wuvt_stream");
            $(stream).attr('type', streamMime);
            $(stream).attr('src', streamUrl);
            $('body').append(stream);

            stream.addEventListener('play', function() {
                $('#stream_btn').addClass('playing');
                $('#stream_btn').attr('title', "Stop");
                $('#stream_btn').removeAttr('disabled');
            });

            // workaround to deal with playback stopping when metadata changes
            // https://bugzil.la/455165
            stream.addEventListener("ended", function() {
                $('#wuvt_stream').attr('src', "");
                $('#wuvt_stream').attr('src', streamUrl);
            });

            // chrome workaround for the same thing
            // https://code.google.com/p/chromium/issues/detail?id=175281
            stream.addEventListener("error", function() {
                $('#wuvt_stream').attr('src', "");
                $('#wuvt_stream').attr('src', streamUrl);
                $('#wuvt_stream').trigger('play');
            });

            stream.play();

            // display an alert after 5 seconds if the stream hasn't started
            window.setTimeout(function() {
                if(streamPlaying && !$('#stream_btn').hasClass('playing')) {
                    alert("Streaming problems? Check the Listen Live page for other ways to listen to WUVT!");
                }
            }, 5000);

            streamPlaying = true;
            $('#stream_btn').attr('title', "Buffering...");
            $('#stream_btn').attr('disabled', "disabled");
        }
        else {
            $('#wuvt_stream').attr('src', "");
            $('#wuvt_stream').remove();

            streamPlaying = false;
            $('#stream_btn').removeClass('playing');
            $('#stream_btn').attr('title', "Play");

            $('#volume_box').removeClass('visible');
        }

        return false;
    });

    initVolume();
}

function initVolume() {
    var volbox = document.createElement('div');
    $(volbox).attr('id', "volume_box");

    // create volume slider
    var slider = document.createElement('div');
    $(slider).attr('id', "volume_slider");
    $(volbox).append(slider);

    // create mute button
    var mutebtn = document.createElement('button');
    $(mutebtn).attr('id', "volume_mute_btn");
    $(mutebtn).attr('title', "Mute");
    $(mutebtn).text("Mute");
    $(volbox).append(mutebtn);

    $('#mainheader').append(volbox);

    // adjust volume box placement
    $(document).ready(positionVolumeBox);
    $(document).on('pageChange', positionVolumeBox);

    $('#volume_btn').click(function() {
        $('#volume_btn').toggleClass('active');
        $('#volume_box').toggleClass('visible');
    });

    $('#volume_slider').slider({
        'orientation': "vertical",
        'value': 1,
        'step': 0.05,
        'range': "min",
        'max': 1,
        'animate': false,
        'slide': function(e, slider) {
            $('#wuvt_stream').prop('muted', false);
            $('#wuvt_stream').prop('volume', slider.value);
        },
    });

    $('#volume_mute_btn').click(function() {
        if(!$('#wuvt_stream').prop('muted')) {
            $('#wuvt_stream').prop('muted', true);
            $('#volume_slider').slider('option', 'value', 0);
        }
        else {
            $('#wuvt_stream').prop('muted', false);
            $('#volume_slider').slider('option', 'value',
                $('#wuvt_stream').prop('volume'));
        }
    });
}

function positionVolumeBox() {
    $('#volume_btn').removeClass('active');
    $('#volume_box').removeClass('visible');

    var btn = $('#volume_btn');
    var offsetTop = btn.offset().top + btn.outerHeight();
    var offsetLeft = btn.offset().left + (btn.outerWidth() / 2) -
        ($('#volume_box').outerWidth() / 2);
    $('#volume_box').css('top', offsetTop + "px");
    $('#volume_box').css('left', offsetLeft + "px");
}

function warnBrokenPlayer() {
    alert("Sorry, the WUVT live stream player is not supported by your browser. Please see the Listen Live page for other ways to listen to WUVT, or switch to Google Chrome or Mozilla Firefox.");
}

// @license-end
<|endoftext|>