<commit_before>var colors  = require('colors');
console.log('images.js entered'.cyan);
/////// END DEPENDENCIES

/////// INSTAGRAM
var ig = require('instagram-node').instagram();

//import Instagram secrets from json file
var instagram_secrets = require('../secrets.json').instagram;

//set up secrets for Instagram module
ig.use({ client_id: instagram_secrets.client_id,
    client_secret: instagram_secrets.client_secret });
/////// END INSTAGRAM

// Polls Instagram API to see if there are any updates
// if so, stores them in the mongodb
exports.fetch = function(res){
	ig.tag_media_recent('architecture', function(err, medias, pagination, limit) {

		if(err){
			console.log('instagram.js::fetch() err with msg: ' + err);
		}else{
			console.log('instagram.js::'.cyan + 'returned from fetch() with: \n');
			console.dir(pagination);

			res.render('feeds', { title: 'OfficeUS Outposts', medias: medias });
		}
	});
};

exports.test = function(){
	console.log('ig.test()'.cyan);
};<commit_msg>using fetch handler for recursive fetch calls<commit_after>var colors  = require('colors');
console.log('images.js entered'.cyan);
/////// END DEPENDENCIES

/////// INSTAGRAM
var ig = require('instagram-node').instagram();

//import Instagram secrets from json file
var instagram_secrets = require('../secrets.json').instagram;

//set up secrets for Instagram module
ig.use({ client_id: instagram_secrets.client_id,
    client_secret: instagram_secrets.client_secret });
/////// END INSTAGRAM

var image_array = [];

var fetchHandler = function(err, result, pagination, limit) {
  // Your implementation here
  if(err){
		console.log('instagram.js::fetchHandler() err with msg: ' + err);
	}else{
		console.log('instagram.js::'.cyan + 'returned from fetch() with: \n');
		console.dir(pagination);

		image_array.push(medias);

		if(pagination.next){
			pagination.next( fetchHandler );
		}else{
			res.render('feeds', { title: 'OfficeUS Outposts', medias: image_array });
		}
	}
};

// Polls Instagram API to see if there are any updates
// if so, stores them in the mongodb
exports.fetch = function(res){
	ig.tag_media_recent( 'architecture', fetchHandler );
};

exports.test = function(){
	console.log('ig.test()'.cyan);
};<|endoftext|>


<commit_before>//var cache = false;

var engine = caramel.engine('handlebars', (function () {
   // return {
   // };
}()));<commit_msg>new debug render for caramel.<commit_after>var engine = caramel.engine('handlebars', (function () {
    //to do move this code to caramel
    /*
    return {
        render: function (data, meta) {

            var replacer = function (match, pIndent, pKey, pVal, pEnd) {
                var key = '';
                var val = '';
                var str = '';
                var r = pIndent || '';
                if (pKey)
                    r = r + key + pKey.replace(/[": ]/g, '') + ': ';
                if (pVal)
                    r = r + (pVal[0] == '"' ? str : val) + pVal + '';
                return r + (pEnd || '');
            };
            var prettyPrint = function (obj) {
                var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
                return JSON.stringify(obj, null, 3)
                    .replace(/&/g, '&').replace(/\\"/g, '"')
                    .replace(/</g, '<').replace(/>/g, '>')
                    .replace(jsonLine, replacer);
            };

            print('
')
            print(prettyPrint(data));
            print('
');
        }
    };
    */
}()));
<|endoftext|>


<commit_before>define(function (require) {

  var React = require('react'),
      Backbone = require('backbone'),
      PreviewPanel = require('./PreviewPanel.react'),
      ButtonBar = require('./ButtonBar.react'),
      InstanceList = require('./instance/InstanceList.react'),
      VolumeList = require('./volume/VolumeList.react'),
      stores = require('stores'),
      actions = require('actions'),
      Instance = require('models/Instance'),
      Volume = require('models/Volume');

  return React.createClass({

    propTypes: {
      project: React.PropTypes.instanceOf(Backbone.Model).isRequired
    },

    getInitialState: function(){
      return {
        selectedResource: null,
        previewedResource: null,
        selectedResources: new Backbone.Collection()
      }
    },

    updateState: function(){
      var project = this.props.project,
          projectInstances = stores.ProjectInstanceStore.getInstancesFor(project),
          projectVolumes = stores.ProjectVolumeStore.getVolumesFor(project),
          selectedResourcesClone = this.state.selectedResources.models.slice(0),
          state = this.getInitialState();

      if (this.isMounted()) {
        // Remove any selected resources that are no longer in the project
        selectedResourcesClone.map(function(selectedResource){
          var instanceInProject = selectedResource instanceof Instance && projectInstances.get(selectedResource),
              volumeInProject = selectedResource instanceof Volume && projectVolumes.get(selectedResource),
              resourceInProject = instanceInProject || volumeInProject;

          if(resourceInProject) state.selectedResources.add(selectedResource);
        });

        // Hold onto selected resource if it still exists in the project
        if(state.selectedResources.indexOf(this.state.selectedResource) >= 0) {
          state.selectedResource = this.state.selectedResource;
          state.previewedResource = this.state.previewedResource;
        }

        this.setState(state);
      }
    },

    onResourceSelected: function(resource){
      var selectedResources = this.state.selectedResources;

      // Add the resource to the list of selected resources
      selectedResources.push(resource);

      this.setState({
        selectedResource: resource,
        previewedResource: resource,
        selectedResources: selectedResources
      });
    },

    onResourceDeselected: function(resource){
      var selectedResources = this.state.selectedResources,
          previewedResource = this.state.previewedResource;

      // Remove the resources from the list of selected resources
      selectedResources.remove(resource);

      // If the resource is equal to the currently previewed resource, change
      // the previewed resource to the last resource the user selected
      if(previewedResource === resource){
        previewedResource = selectedResources.last();
      }

      this.setState({
        selectedResource: previewedResource,
        previewedResource: previewedResource,
        selectedResources: selectedResources
      });
    },

    onPreviewResource: function(resource){
      var selectedResources = this.state.selectedResources;

      // todo: figure out why I did this...
      selectedResources.reset();
      selectedResources.push(resource);

      this.setState({
        selectedResource: resource,
        previewedResource: resource,
        selectedResources: selectedResources
      });
    },

    onMoveSelectedResources: function(){
      actions.ProjectActions.moveResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    onDeleteSelectedResources: function(){
      actions.ProjectActions.deleteResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    onReportSelectedResources: function(){
      actions.ProjectActions.reportResources(
        this.props.project,
        this.state.selectedResources
      );
    },

    onRemoveSelectedResources: function(){
      actions.ProjectActions.removeResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    render: function () {
      var project = this.props.project,
          projectInstances = stores.ProjectInstanceStore.getInstancesFor(project),
          projectVolumes = stores.ProjectVolumeStore.getVolumesFor(project),
          previewedResource = this.state.previewedResource,
          selectedResources = this.state.selectedResources,
          selectedResource = this.state.selectedResource,
          isButtonBarVisible;

      if(!projectInstances || !projectVolumes) return

;

      // Only show the action button bar if the user has selected resources
      isButtonBarVisible = this.state.selectedResources.length > 0;

      return (

          <ButtonBar
            isVisible={isButtonBarVisible}
            onMoveSelectedResources={this.onMoveSelectedResources}
            onDeleteSelectedResources={this.onDeleteSelectedResources}
            onReportSelectedResources={this.onReportSelectedResources}
            onRemoveSelectedResources={this.onRemoveSelectedResources}
            previewedResource={previewedResource}
            project={project}
          />

              <InstanceList
                instances={projectInstances}
                onResourceSelected={this.onResourceSelected}
                onResourceDeselected={this.onResourceDeselected}
                onPreviewResource={this.onPreviewResource}
                previewedResource={previewedResource}
                selectedResources={selectedResources}
              />
              <VolumeList
                volumes={projectVolumes}
                onResourceSelected={this.onResourceSelected}
                onResourceDeselected={this.onResourceDeselected}
                onPreviewResource={this.onPreviewResource}
                previewedResource={previewedResource}
                selectedResources={selectedResources}
              />

            <PreviewPanel resource={selectedResource}/>

      );
    }

  });

});
<commit_msg>changed call from actions.ProjectActions to modals.ProjectModals<commit_after>define(function (require) {

  var React = require('react'),
      Backbone = require('backbone'),
      PreviewPanel = require('./PreviewPanel.react'),
      ButtonBar = require('./ButtonBar.react'),
      InstanceList = require('./instance/InstanceList.react'),
      VolumeList = require('./volume/VolumeList.react'),
      modals = require('modals'),
      stores = require('stores'),
      actions = require('actions'),
      Instance = require('models/Instance'),
      Volume = require('models/Volume');

  return React.createClass({

    propTypes: {
      project: React.PropTypes.instanceOf(Backbone.Model).isRequired
    },

    getInitialState: function(){
      return {
        selectedResource: null,
        previewedResource: null,
        selectedResources: new Backbone.Collection()
      }
    },

    updateState: function(){
      var project = this.props.project,
          projectInstances = stores.ProjectInstanceStore.getInstancesFor(project),
          projectVolumes = stores.ProjectVolumeStore.getVolumesFor(project),
          selectedResourcesClone = this.state.selectedResources.models.slice(0),
          state = this.getInitialState();

      if (this.isMounted()) {
        // Remove any selected resources that are no longer in the project
        selectedResourcesClone.map(function(selectedResource){
          var instanceInProject = selectedResource instanceof Instance && projectInstances.get(selectedResource),
              volumeInProject = selectedResource instanceof Volume && projectVolumes.get(selectedResource),
              resourceInProject = instanceInProject || volumeInProject;

          if(resourceInProject) state.selectedResources.add(selectedResource);
        });

        // Hold onto selected resource if it still exists in the project
        if(state.selectedResources.indexOf(this.state.selectedResource) >= 0) {
          state.selectedResource = this.state.selectedResource;
          state.previewedResource = this.state.previewedResource;
        }

        this.setState(state);
      }
    },

    onResourceSelected: function(resource){
      var selectedResources = this.state.selectedResources;

      // Add the resource to the list of selected resources
      selectedResources.push(resource);

      this.setState({
        selectedResource: resource,
        previewedResource: resource,
        selectedResources: selectedResources
      });
    },

    onResourceDeselected: function(resource){
      var selectedResources = this.state.selectedResources,
          previewedResource = this.state.previewedResource;

      // Remove the resources from the list of selected resources
      selectedResources.remove(resource);

      // If the resource is equal to the currently previewed resource, change
      // the previewed resource to the last resource the user selected
      if(previewedResource === resource){
        previewedResource = selectedResources.last();
      }

      this.setState({
        selectedResource: previewedResource,
        previewedResource: previewedResource,
        selectedResources: selectedResources
      });
    },

    onPreviewResource: function(resource){
      var selectedResources = this.state.selectedResources;

      // todo: figure out why I did this...
      selectedResources.reset();
      selectedResources.push(resource);

      this.setState({
        selectedResource: resource,
        previewedResource: resource,
        selectedResources: selectedResources
      });
    },

    onMoveSelectedResources: function(){
      modals.ProjectModals.moveResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    onDeleteSelectedResources: function(){
      actions.ProjectActions.deleteResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    onReportSelectedResources: function(){
      actions.ProjectActions.reportResources(
        this.props.project,
        this.state.selectedResources
      );
    },

    onRemoveSelectedResources: function(){
      actions.ProjectActions.removeResources(
        this.state.selectedResources,
        this.props.project
      );
    },

    render: function () {
      var project = this.props.project,
          projectInstances = stores.ProjectInstanceStore.getInstancesFor(project),
          projectVolumes = stores.ProjectVolumeStore.getVolumesFor(project),
          previewedResource = this.state.previewedResource,
          selectedResources = this.state.selectedResources,
          selectedResource = this.state.selectedResource,
          isButtonBarVisible;

      if(!projectInstances || !projectVolumes) return

;

      // Only show the action button bar if the user has selected resources
      isButtonBarVisible = this.state.selectedResources.length > 0;

      return (

          <ButtonBar
            isVisible={isButtonBarVisible}
            onMoveSelectedResources={this.onMoveSelectedResources}
            onDeleteSelectedResources={this.onDeleteSelectedResources}
            onReportSelectedResources={this.onReportSelectedResources}
            onRemoveSelectedResources={this.onRemoveSelectedResources}
            previewedResource={previewedResource}
            project={project}
          />

              <InstanceList
                instances={projectInstances}
                onResourceSelected={this.onResourceSelected}
                onResourceDeselected={this.onResourceDeselected}
                onPreviewResource={this.onPreviewResource}
                previewedResource={previewedResource}
                selectedResources={selectedResources}
              />
              <VolumeList
                volumes={projectVolumes}
                onResourceSelected={this.onResourceSelected}
                onResourceDeselected={this.onResourceDeselected}
                onPreviewResource={this.onPreviewResource}
                previewedResource={previewedResource}
                selectedResources={selectedResources}
              />

            <PreviewPanel resource={selectedResource}/>

      );
    }

  });

});
<|endoftext|>


<commit_before>// Survey scripts
$('#user_meeting_meeting_time').datetimepicker({
  dateFormat: 'D dd M yy',
  timeFormat: 'HH:mm:ss z',
  timezoneList: [
    { value: -300, label: 'Eastern'},
    { value: -360, label: 'Central' },
    { value: -420, label: 'Mountain' },
    { value: -480, label: 'Pacific' }
  ]
});<commit_msg>Updated date formatting, which caused the date/time widget to not update correctly on edit. This was identified in Issue #38.<commit_after>(function($)
{
  var currentDate = '';
  var dateField = $('#user_meeting_meeting_time');
  if (dateField.val() != '')
  {
    currentDate = dateField.val();
  }
  dateField.datetimepicker({
    dateFormat: 'yy-mm-dd',
    timeFormat: 'HH:mm:ss z',
    defaultValue: currentDate,
    timezoneList: [
      { value: -300, label: 'Eastern'},
      { value: -360, label: 'Central' },
      { value: -420, label: 'Mountain' },
      { value: -480, label: 'Pacific' }
    ]
  });
})(jQuery);
<|endoftext|>


<commit_before>DP.RealTime = function() {
    this.setup();
}

DP.RealTime.prototype = {
  setup: function() {
    if (typeof Pusher == 'function') {
      this.pusher = new Pusher(DP.PUSHER_KEY);
      this.channel = this.pusher.subscribe(DP.Round.url);
      this.channel.bind('new:charge', _.bind(this.newCharge, this));
      console.log(["Subscribing to real-time", this.pusher, this.channel]);
    }

    this.reloader = setInterval(_.bind(this.reloadDonations, this), 1000*60);
    this.timer = setInterval(_.bind(this.renderTimer, this), 1000*1);
  },

  newCharge: function() {
    console.log(["REAL-TIME: New Charge", arguments]);
    this.reloadDonations();
  },

  reloadDonations: function() {
    $.get('/api/rounds/' + DP.Round.url, {}, this.renderDonations);
  },

  renderDonations: function(data) {
    console.log(["Round status", data]);
    $('.donations').html(data.donations_template);
    $('.payment-info').html(data.payment_info_template);
    if (data.closed) {
      window.location.href = window.location.href;
    }
  },

  renderTimer: function() {
    var minutes, seconds;
    var $timer;
    var seconds_left = (new Date(DP.Round.expire_time) - new Date()) / 1000;

    if (seconds_left <= 0) {
      window.location.href = window.location.href;
    }

    $timer = $('.timer');
    minutes = Math.floor(seconds_left / 60);
    seconds = Math.round(seconds_left % 60);
    if (seconds <= 9) seconds = "0" + seconds;
    $timer.html(minutes + ":" + seconds + " time left");
  }
};
<commit_msg>Redisplay time left every 100ms<commit_after>DP.RealTime = function() {
    this.setup();
}

DP.RealTime.prototype = {
  setup: function() {
    if (typeof Pusher == 'function') {
      this.pusher = new Pusher(DP.PUSHER_KEY);
      this.channel = this.pusher.subscribe(DP.Round.url);
      this.channel.bind('new:charge', _.bind(this.newCharge, this));
      console.log(["Subscribing to real-time", this.pusher, this.channel]);
    }

    this.reloader = setInterval(_.bind(this.reloadDonations, this), 1000*60);
    this.timer = setInterval(_.bind(this.renderTimer, this), 100);
  },

  newCharge: function() {
    console.log(["REAL-TIME: New Charge", arguments]);
    this.reloadDonations();
  },

  reloadDonations: function() {
    $.get('/api/rounds/' + DP.Round.url, {}, this.renderDonations);
  },

  renderDonations: function(data) {
    console.log(["Round status", data]);
    $('.donations').html(data.donations_template);
    $('.payment-info').html(data.payment_info_template);
    if (data.closed) {
      window.location.href = window.location.href;
    }
  },

  renderTimer: function() {
    var minutes, seconds;
    var $timer;
    var seconds_left = (new Date(DP.Round.expire_time) - new Date()) / 1000;

    if (seconds_left <= 0) {
      window.location.href = window.location.href;
    }

    $timer = $('.timer');
    minutes = Math.floor(seconds_left / 60);
    seconds = Math.round(seconds_left % 60);
    if (seconds <= 9) seconds = "0" + seconds;
    $timer.html(minutes + ":" + seconds + " time left");
  }
};
<|endoftext|>


<commit_before>$.extend({ keys: function(obj){ if (typeof Object.keys == 'function') return Object.keys(obj);
				var a = [];
				$.each(obj, function(k){ a.push(k) });
				return a;
			      }
});

/* set up a jquery object with the datepicker. if isotarget defined,
   add the change date event handler for ISO string conversion
*/
  var updates = ["estimated_enrollment", "student_annotation", "lecture_date", "required", "visibility"];

 $(document).on("ready page:load", function(e) {
                 if ($("body").hasClass("c_reserves")) {
		    if ($("body").hasClass("a_edit") ) {
		       setupDatepicker($("#reserve_lecture_date"), $("#iso_date"));
		    }
		    else if ( $("body").hasClass("a_new") ||
			       $("body").hasClass("a_create") ) {
			setupDatepicker($("#reserve_lecture_date"), $("#iso_date"));
			material_type_change($("#reserve_input_material_type")); /* when we come back with an error */
			$("#reserve_input_material_type").on("change", function(e) {
			    material_type_change($(this));
			});
			$("div.reserve_input_hollis_system_number .col-sm-9").append("<input type='button' class='btn btn-default btn-ajax nonjournal' value='Autofill' name='hollis_fill' id='hollis_fill'/>");
			$("#hollis_fill").on("click", function(e){
			    fill_hollis(e, $("#reserve_input_hollis_system_number").val());
			    });
			$("div.reserve_input_doi .col-sm-9").append("<input type='button' class='btn btn-default btn-ajax journal' value='Autofill' name='article_fill' id='article_fill'/>");
		        $("#article_fill").on("click", function(e){
                            fill_article(e, $("#reserve_input_doi").val());
                            });

		    }
		 }
});

  /*   COMMON FUNCTIONS */

  function setupDatepicker($which, $isotarget) {
	 $which.datepicker({
                       startDate: "now",
                       endDate: "+365d",
                       clearBtn: true,
                       todayHighlight: true,
                       toggleActive: true,
                       orientation: "top auto"
	});
	if (typeof $isotarget == "object") {
	   $which.datepicker().on("changeDate", function(e) {
	      $isotarget.val(e.date.toISOString());
	   });
	}
  }

/*
 **  CREATION FUNCTION(S)
*/

function fill_hollis(e, id) {
    e.preventDefault();
    if (typeof id === "undefined") {
        console.log("No hollis number!");
    }
    else {
	auto_fill("hollis", id)
    }
}
function fill_article(e, id) {
    e.preventDefault();
    if (typeof id === "undefined") {
        console.log("No DOI or PUBMED number!");
    }
    else {
        auto_fill("journal", id)
    }
}

function auto_fill(type,id) {
    $.getJSON('/presto/' + type + '?id=' + encodeURIComponent(id))
	.done(function(data, status, jqXHR) {
            if (data) {
		if (data.status === 200) {
		   var list = $('#switchable :input')
			.not(':button, :submit, :reset, :hidden, :radio, :checkbox');
		    $('#switchable :input')
			.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
			.val('');  /* clear the inputs */
		    $.each($.keys(data), function(i, v) {
			if (v !== "status") {
			    $("#"+v).val(data[v]);
			}
		    });
		}
	    }
	    else {
	    }
	} )
	.fail(function(data, status,jqXHR) {
	    console.log("YOU LOSE!");
	});
}

function material_type_change($this) {
    var val = $this.val();
    if (val === "") {
	switch_type("");
    }
    else {
	var type = ($this.val() === "Journal Article")? "JOURNAL" : "NON_JOURNAL";
	switch_type(type);
    }
    return;
}

/* shows and hides elements according to type */
 function switch_type(type) {
     $("#switchable").hide();
     if (type === "JOURNAL") {
	 $(".nonjournal").hide();
	 $(".journal").show();
     }
     else if (type === "NON_JOURNAL") {
	 $(".nonjournal").show();
	 $(".journal").hide();
     }
     else { return; }
     $(".both").show();
     $("#switchable").show();
 }

/*
 **  EDIT FUNCTIONS
*/
  function submitUpdate(e) {
      e.preventDefault();
      var change = false;
      for ( i = 0; i < updates.length; i++) {
	    if ($("#o_"+updates[i]).val() !== $("#reserve_" + updates[i]).val()) {
		change = true;
		break;
	  }
      }
      if (!change) {
	  alert("No changes have been made");
	  return false;
      } else {
	  $(this).submit();
      }
}

<commit_msg>Make sure DOI/PUBMED number remains after auto-fill<commit_after>$.extend({ keys: function(obj){ if (typeof Object.keys == 'function') return Object.keys(obj);
				var a = [];
				$.each(obj, function(k){ a.push(k) });
				return a;
			      }
});

/* set up a jquery object with the datepicker. if isotarget defined,
   add the change date event handler for ISO string conversion
*/
  var updates = ["estimated_enrollment", "student_annotation", "lecture_date", "required", "visibility"];

 $(document).on("ready page:load", function(e) {
                 if ($("body").hasClass("c_reserves")) {
		    if ($("body").hasClass("a_edit") ) {
		       setupDatepicker($("#reserve_lecture_date"), $("#iso_date"));
		    }
		    else if ( $("body").hasClass("a_new") ||
			       $("body").hasClass("a_create") ) {
			setupDatepicker($("#reserve_lecture_date"), $("#iso_date"));
			material_type_change($("#reserve_input_material_type")); /* when we come back with an error */
			$("#reserve_input_material_type").on("change", function(e) {
			    material_type_change($(this));
			});
			$("div.reserve_input_hollis_system_number .col-sm-9").append("<input type='button' class='btn btn-default btn-ajax nonjournal' value='Autofill' name='hollis_fill' id='hollis_fill'/>");
			$("#hollis_fill").on("click", function(e){
			    fill_hollis(e, $("#reserve_input_hollis_system_number").val());
			    });
			$("div.reserve_input_doi .col-sm-9").append("<input type='button' class='btn btn-default btn-ajax journal' value='Autofill' name='article_fill' id='article_fill'/>");
		        $("#article_fill").on("click", function(e){
                            fill_article(e, $("#reserve_input_doi").val());
                            });

		    }
		 }
});

  /*   COMMON FUNCTIONS */

  function setupDatepicker($which, $isotarget) {
	 $which.datepicker({
                       startDate: "now",
                       endDate: "+365d",
                       clearBtn: true,
                       todayHighlight: true,
                       toggleActive: true,
                       orientation: "top auto"
	});
	if (typeof $isotarget == "object") {
	   $which.datepicker().on("changeDate", function(e) {
	      $isotarget.val(e.date.toISOString());
	   });
	}
  }

/*
 **  CREATION FUNCTION(S)
*/

function fill_hollis(e, id) {
    e.preventDefault();
    if (typeof id === "undefined") {
        console.log("No hollis number!");
    }
    else {
	auto_fill("hollis", id)
    }
}
function fill_article(e, id) {
    e.preventDefault();
    if (typeof id === "undefined") {
        console.log("No DOI or PUBMED number!");
    }
    else {
        auto_fill("journal", id)
    }
}

function auto_fill(type,id) {
    $.getJSON('/presto/' + type + '?id=' + encodeURIComponent(id))
	.done(function(data, status, jqXHR) {
            if (data) {
		if (data.status === 200) {
		   var list = $('#switchable :input')
			.not(':button, :submit, :reset, :hidden, :radio, :checkbox');
		    $('#switchable :input')
			.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
			.val('');  /* clear the inputs */
		    $.each($.keys(data), function(i, v) {
			if (v !== "status") {
			    $("#"+v).val(data[v]);
			}
		    });
		    if ($("#reserve_input_doi").val() == '') {
			$("#reserve_input_doi").val(id);
		    }
		}
	    }
	    else {
	    }
	} )
	.fail(function(data, status,jqXHR) {
	    console.log("YOU LOSE!");
	});
}

function material_type_change($this) {
    var val = $this.val();
    if (val === "") {
	switch_type("");
    }
    else {
	var type = ($this.val() === "Journal Article")? "JOURNAL" : "NON_JOURNAL";
	switch_type(type);
    }
    return;
}

/* shows and hides elements according to type */
 function switch_type(type) {
     $("#switchable").hide();
     if (type === "JOURNAL") {
	 $(".nonjournal").hide();
	 $(".journal").show();
     }
     else if (type === "NON_JOURNAL") {
	 $(".nonjournal").show();
	 $(".journal").hide();
     }
     else { return; }
     $(".both").show();
     $("#switchable").show();
 }

/*
 **  EDIT FUNCTIONS
*/
  function submitUpdate(e) {
      e.preventDefault();
      var change = false;
      for ( i = 0; i < updates.length; i++) {
	    if ($("#o_"+updates[i]).val() !== $("#reserve_" + updates[i]).val()) {
		change = true;
		break;
	  }
      }
      if (!change) {
	  alert("No changes have been made");
	  return false;
      } else {
	  $(this).submit();
      }
}

<|endoftext|>


<commit_before>$(function () {
    const el = $('#vis-network');
    if (!el.length) {
        return;
    }
    el.on('resize', function () {
        el.css('height', window.innerHeight - 75 + 'px');
    }());

    el.find('span').text('Die Knoten werden geknüpft...');

    $.ajax({
        type: 'GET',
        url: 'dependencies/data.json',
        success: function (response) {
            el.html('');
            el.removeClass('loading');
            if (response.nodes && response.edges && response.participationEdges) {
                render(response.nodes, response.edges, response.participationEdges);
            } else {
                $(document).trigger('add-alerts', {
                    message: 'Unerwartetes Datenformat der Beziehungsdaten',
                    priority: 'error'
                });
            }
        },
        error: function () {
            $(document).trigger('add-alerts', {
                message: 'Die Beziehungsdaten konnten nicht geladen werden',
                priority: 'error'
            });
        }
    });

    render = function (nodes, edges, participationEdges) {
        var filterGroups = null,
            filterShowParticipants = null,
            filterShowParticipationEdges = null,
            filterIncludeChoices = [],
            nodesView;

        const container = document.getElementById('vis-network'),
            edgesSet = new vis.DataSet(edges),
            nodesSet = new vis.DataSet(nodes);

        const filtersInputEls = $('.filters input'),
            filterIncludeChoicesEls = $('.filter-entities input.f'),
            updateFilterConfiguration = function () {
                filterGroups = {};
                filtersInputEls.each(function () {
                    const filterEl = $(this);
                    if (filterEl.prop('checked')) {
                        const property = filterEl.data('property'),
                            value = filterEl.data('value'),
                            nodes = filterEl.data('nodes');
                        if (!filterGroups[property]) {
                            filterGroups[property] = [];
                        }
                        filterGroups[property].push({
                            value: value,
                            nodes: nodes.split(',')
                        });
                    }
                });
                filterShowParticipants = false;
                filterShowParticipationEdges = false;
                filterIncludeChoices = [];
                filterIncludeChoicesEls.each(function () {
                    var filterEl = $(this);
                    if (filterEl.prop('checked')) {
                        var type = filterEl.data('type'),
                            bid = filterEl.data('bid');

                        switch (type) {
                            case 'participation-edges':
                                filterShowParticipationEdges = true;
                                break;
                            case 'participant':
                                filterShowParticipants = true;
                                break;
                            case 'choice':
                                filterIncludeChoices.push(bid);
                                break;
                        }
                    }
                });
                if (nodesView) {
                    nodesView.refresh();
                    $('#display').click();
                }
            };
        filtersInputEls.on('change', updateFilterConfiguration);
        filterIncludeChoicesEls.on('change', updateFilterConfiguration);

        $('#btnShowParticipationEdges').on('change', function () {
            if ($(this).prop('checked')) {
                showParticipationEdges();
            } else {
                hideParticipationEdges();
            }
        });
        updateFilterConfiguration();

        nodesView = new vis.DataView(nodesSet, {
                filter: function (item) {
                    var type = item.type;

                    if (!filterShowParticipants && type === 'participant') {
                        return false;
                    }
                    if (type === 'choice' && $.inArray(item.bid, filterIncludeChoices) === -1) {
                        return false;
                    }

                    if (filterGroups === null) {
                        return true;
                    }
                    var acceptGroup = false;
                    $.each(filterGroups, function (groupName, acceptedValues) {
                        var groupValue = item[groupName];
                        acceptGroup = false;

                        $.each(acceptedValues, function (key, acceptedConfiguration) {
                            var acceptedValue = acceptedConfiguration.value,
                                filterableNodes = acceptedConfiguration.nodes;

                            if ($.inArray(type, filterableNodes) === -1
                                || groupValue === acceptedValue) {
                                acceptGroup = true;
                                return false;
                            }
                        });
                        if (!acceptGroup) {
                            return false;
                        }
                    });

                    return acceptGroup;
                }
            });

        const hideParticipationEdges = function () {
                var edges = edgesSet.get({
                    filter: function (item) {
                        return (item.type === 'participation');
                    }
                });
                $.each(edges, function (key, edge) {
                    edgesSet.remove(edge.id);
                });
            },
            showParticipationEdges = function () {
                hideParticipationEdges();
                $.each(participationEdges, function (key, edge) {
                    edgesSet.add(edge);
                });
            };

        const connectToChoice = function (nodeHuman, nodeChoice) {
            var nodeHumanId = nodeHuman.id,
                nodeChoiceId = nodeChoice.id,
                newBid = nodeChoice.bid,
                connectedNodes = network.getConnectedNodes(nodeHumanId);

            if ($.inArray(nodeChoiceId, connectedNodes) !== -1) {
                return false; //already part of this group
            }

            //remove other connections to same bid
            var connectedEdges = network.getConnectedEdges(nodeHumanId);
            $.each(connectedEdges, function (key, connectedEdgeId) {
                var connectedEdge = edgesSet.get(connectedEdgeId);
                if (connectedEdge.bid === newBid) {
                    edgesSet.remove(connectedEdgeId);
                }
            });

            var newEdges = edgesSet.add({
                from: nodeHumanId,
                to: nodeChoiceId,
                bid: newBid,
                choiceId: nodeChoice.choiceId,
                color: {color: nodeChoice.color},
                dashes: true
            });
            if (!newEdges) {
                debugger
            }
            nodesView.refresh();
            $.ajax({
                type: 'POST',
                url: '/admin/event/' + el.data('eid') + '/dependencies/change_group_assignment/' + nodeHumanId,
                data: {
                    _token: el.data('token'),
                    bid: newBid,
                    choiceId: nodeChoice.choiceId
                },
                success: function (response) {
                    if (response.success) {
                        edgesSet.update({id: newEdges[0], dashes: false});
                    } else {
                        location.reload();
                    }
                },
                error: function () {
                    location.reload();
                }
            });
            network.addEdgeMode();
            updateGroupTitles();
        };

        var options = {
            layout: {improvedLayout: false},
            manipulation: {
                enabled: false,
                addEdge: function (edgeData, callback) {
                    if (edgeData.from === edgeData.to) {
                        return; //not adding self connections
                    } else {
                        var nodeFrom = nodesSet.get(edgeData.from),
                            nodeFromType = nodeFrom.type,
                            nodeTo = nodesSet.get(edgeData.to),
                            nodeToType = nodeTo.type;

                        if ((nodeFromType !== 'choice' && nodeToType !== 'choice')
                            || (nodeFromType === 'choice' && nodeToType === 'choice')
                        ) {
                            return; //only able to connect choices but not only choices
                        }
                        if (nodeFromType === 'choice') {
                            //swap nodes in order to ensure connection has correct direction
                            var nodeTmp = nodeFrom;
                            nodeFrom = nodeTo;
                            nodeTo = nodeTmp;
                        }

                        connectToChoice(nodeFrom, nodeTo, callback);
                    }
                }
            },
            nodes: {
                font: {
                    face: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                    multi: 'md'
                },
                scaling: {
                    min: 20,
                    max: 60
                }
            },
            edges: {
                font: {
                    face: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                    multi: 'html'
                },
                scaling: {
                    min: 0.5,
                    max: 5
                }
            }
        };

        const formatNumber = function (number) {
            number = (Math.round(number * 10) / 10);
            var stringNumber = number.toString();
            return stringNumber.replace('.', ',');
        };

        var network = new vis.Network(
            container,
            {
                nodes: nodesView,
                edges: edgesSet
            },
            options
        );
        const updateGroupTitles = function () {
            var nodeUpdates = [],
                edgeUpdates = [];

            nodesSet.forEach(function (node) {
                if (node.type === 'choice') {
                    var connectedNodeIds = network.getConnectedNodes(node.id),
                        groupAges = [],
                        label,
                        median,
                        mean,
                        range,
                        distance,
                        nodeSize = (connectedNodeIds.length * 1.5) + 20;
                    $.each(connectedNodeIds, function (key, connectedNodeId) {
                        var connectedNode = nodesSet.get(connectedNodeId);
                        if (connectedNode.type === 'participant') {
                            if (connectedNode.age) {
                                groupAges.push(connectedNode.age);
                            }
                        }
                    });

                    if (node.shortTitle) {
                        label = '*' + node.shortTitle + '*';
                    }
                    if (groupAges.length) {
                        label += "\n";
                        median = eMedian(groupAges);
                        mean = eMean(groupAges);
                        distance = (Math.max(...groupAges) - Math.min(...groupAges));

                        label += ' ~' + formatNumber(median);
                        label += ' x' + formatNumber(mean);
                        label += ' d' + formatNumber(distance);

                        if (node.label === label
                            && node.median === median
                            && node.mean === mean
                            && node.distance === distance
                            && node.nodeSize === nodeSize) {
                            return true;
                        }
                        nodeUpdates.push({
                            id: node.id,
                            label: label,
                            median: median,
                            mean: mean,
                            distance: distance,
                            value: nodeSize
                        });
                        var connectedEdges = network.getConnectedEdges(node.id);
                        $.each(connectedEdges, function (key, connectedEdgeId) {
                            var connectedEdge = edgesSet.get(connectedEdgeId),
                                connectedNode = nodesSet.get(connectedEdge.from),
                                edgeDistance;
                            if (!connectedNode || connectedNode.type !== 'participant' || connectedEdge.type !== 'choice') {
                                return;
                            }
                            edgeDistance = (connectedNode.age - mean) + 0.25;
                            if (edgeDistance < 0) {
                                edgeDistance *= -1;
                            }
                            edgeUpdates.push({
                                id: connectedEdgeId,
                                value: edgeDistance
                            });
                        });
                    } else if (node.label !== label) {
                        nodeUpdates.push({
                            id: node.id,
                            label: label,
                            median: 0,
                            mean: 0,
                            distance: 0,
                            value: nodeSize
                        });
                    }
                }
            });

            var handleQueue = function () {
                var update;
                if (nodeUpdates.length) {
                    update = nodeUpdates.shift();
                    nodesSet.update(update);
                }
                if (edgeUpdates.length) {
                    update = edgeUpdates.shift();
                    edgesSet.update(update);
                }
                scheduleQueue();
            }, scheduleQueue = function () {
                if (nodeUpdates.length || edgeUpdates.length) {
                    window.setTimeout(handleQueue, 1);
                }
            };
            scheduleQueue();
        };

        const modalParticipantEl = $('#modalParticipant'),
            modalParticipantBodyEl = jQuery(modalParticipantEl.find('.modal-body .row')[0]),
            participantDetails = {};
        network.on("doubleClick", function (params) {
            if (params.nodes.length !== 1) {
                return;
            }
            var nodeId = params.nodes[0];
            if (network.isCluster(nodeId)) {
                network.openCluster(nodeId);
            } else {
                var node = nodesSet.get(nodeId);

                switch (node.type) {
                    case 'choice':
                        var clusterOptionsByData = {
                            processProperties: function (clusterOptions, childNodes) {
                                clusterOptions.label = node.label + ' [' + (childNodes.length - 1) + ']';
                                clusterOptions.color = node.color;
                                clusterOptions.shape = node.shape;
                                return clusterOptions;
                            },
                            clusterNodeProperties: {
                                borderWidth: 2,
                                shapeProperties: {borderDashes: [5, 2]}
                            }
                        };
                        network.clusterByConnection(nodeId, clusterOptionsByData);
                        break;
                    case 'participant':
                        modalParticipantEl.data('aid', node.aid);
                        jQuery(modalParticipantEl.find('h4')[0]).text(node.label);
                        jQuery(modalParticipantEl.find('.modal-footer a')[0]).attr('href', '/admin/event/' + modalParticipantEl.data('eid') + '/participant/' + node.aid);
                        modalParticipantEl.modal('show');
                        break;
                }
            }
        });

        const hydrateParticipantDetails = function (content) {
            modalParticipantBodyEl.html('

');
            const items = jQuery.parseHTML(content);
            const target = jQuery(modalParticipantBodyEl.find('div')[0]);

            jQuery.each(items, function (index, item) {
                target.append(item);
            });

            modalParticipantBodyEl.find('a').each(function () {
                const el = jQuery(this);
                el.attr('target', '_blank');
                el.html(el.text() + ' ');
            });
        };

        modalParticipantEl.on('show.bs.modal', function (event) {
            const aid = modalParticipantEl.data('aid');
            modalParticipantBodyEl.toggleClass('loading-text', true);
            if (commonCache.has('participant-partial-details.a'+aid)) {
                hydrateParticipantDetails(commonCache.get('participant-partial-details.a'+aid));
            } else {
                modalParticipantBodyEl.html('

Die Anmeldungdetails werden nachgeschlagen...

');
            }

            jQuery.ajax({
                type: 'GET',
                dataType: 'text',
                url: '/admin/event/' + modalParticipantEl.data('eid') + '/participant/' + aid + '/partial',
                success: function (content, statusText) {
                    modalParticipantBodyEl.toggleClass('loading-text', false);
                    hydrateParticipantDetails(content);
                    commonCache.set('participant-partial-details.a'+aid, content);
                },
                error: function () {
                    modalParticipantBodyEl.toggleClass('loading-text', false);
                    modalParticipantBodyEl.html('

Die Anmeldungdetails konnten nicht geladen werden.

');
                }
            });
        });

        network.on("selectNode", function (params) {
            if (params.nodes.length !== 1) {
                return;
            }
            var nodeId = params.nodes[0],
                node = nodesSet.get(nodeId);
        });
        $('.modes label').on('change', function () {
            var el = $(this),
                elInput = el.find('input'),
                mode = elInput.attr('id');

            if (mode === 'add-edge') {
                network.addEdgeMode();
            } else {
                network.disableEditMode();
            }
        });

        updateGroupTitles();
        nodesView.refresh();
    };
});<commit_msg>Prevented DOM text reinterpreted as HTML<commit_after>$(function () {
    const el = $('#vis-network');
    if (!el.length) {
        return;
    }
    el.on('resize', function () {
        el.css('height', window.innerHeight - 75 + 'px');
    }());

    el.find('span').text('Die Knoten werden geknüpft...');

    $.ajax({
        type: 'GET',
        url: 'dependencies/data.json',
        success: function (response) {
            el.html('');
            el.removeClass('loading');
            if (response.nodes && response.edges && response.participationEdges) {
                render(response.nodes, response.edges, response.participationEdges);
            } else {
                $(document).trigger('add-alerts', {
                    message: 'Unerwartetes Datenformat der Beziehungsdaten',
                    priority: 'error'
                });
            }
        },
        error: function () {
            $(document).trigger('add-alerts', {
                message: 'Die Beziehungsdaten konnten nicht geladen werden',
                priority: 'error'
            });
        }
    });

    render = function (nodes, edges, participationEdges) {
        var filterGroups = null,
            filterShowParticipants = null,
            filterShowParticipationEdges = null,
            filterIncludeChoices = [],
            nodesView;

        const container = document.getElementById('vis-network'),
            edgesSet = new vis.DataSet(edges),
            nodesSet = new vis.DataSet(nodes);

        const filtersInputEls = $('.filters input'),
            filterIncludeChoicesEls = $('.filter-entities input.f'),
            updateFilterConfiguration = function () {
                filterGroups = {};
                filtersInputEls.each(function () {
                    const filterEl = $(this);
                    if (filterEl.prop('checked')) {
                        const property = filterEl.data('property'),
                            value = filterEl.data('value'),
                            nodes = filterEl.data('nodes');
                        if (!filterGroups[property]) {
                            filterGroups[property] = [];
                        }
                        filterGroups[property].push({
                            value: value,
                            nodes: nodes.split(',')
                        });
                    }
                });
                filterShowParticipants = false;
                filterShowParticipationEdges = false;
                filterIncludeChoices = [];
                filterIncludeChoicesEls.each(function () {
                    var filterEl = $(this);
                    if (filterEl.prop('checked')) {
                        var type = filterEl.data('type'),
                            bid = filterEl.data('bid');

                        switch (type) {
                            case 'participation-edges':
                                filterShowParticipationEdges = true;
                                break;
                            case 'participant':
                                filterShowParticipants = true;
                                break;
                            case 'choice':
                                filterIncludeChoices.push(bid);
                                break;
                        }
                    }
                });
                if (nodesView) {
                    nodesView.refresh();
                    $('#display').click();
                }
            };
        filtersInputEls.on('change', updateFilterConfiguration);
        filterIncludeChoicesEls.on('change', updateFilterConfiguration);

        $('#btnShowParticipationEdges').on('change', function () {
            if ($(this).prop('checked')) {
                showParticipationEdges();
            } else {
                hideParticipationEdges();
            }
        });
        updateFilterConfiguration();

        nodesView = new vis.DataView(nodesSet, {
                filter: function (item) {
                    var type = item.type;

                    if (!filterShowParticipants && type === 'participant') {
                        return false;
                    }
                    if (type === 'choice' && $.inArray(item.bid, filterIncludeChoices) === -1) {
                        return false;
                    }

                    if (filterGroups === null) {
                        return true;
                    }
                    var acceptGroup = false;
                    $.each(filterGroups, function (groupName, acceptedValues) {
                        var groupValue = item[groupName];
                        acceptGroup = false;

                        $.each(acceptedValues, function (key, acceptedConfiguration) {
                            var acceptedValue = acceptedConfiguration.value,
                                filterableNodes = acceptedConfiguration.nodes;

                            if ($.inArray(type, filterableNodes) === -1
                                || groupValue === acceptedValue) {
                                acceptGroup = true;
                                return false;
                            }
                        });
                        if (!acceptGroup) {
                            return false;
                        }
                    });

                    return acceptGroup;
                }
            });

        const hideParticipationEdges = function () {
                var edges = edgesSet.get({
                    filter: function (item) {
                        return (item.type === 'participation');
                    }
                });
                $.each(edges, function (key, edge) {
                    edgesSet.remove(edge.id);
                });
            },
            showParticipationEdges = function () {
                hideParticipationEdges();
                $.each(participationEdges, function (key, edge) {
                    edgesSet.add(edge);
                });
            };

        const connectToChoice = function (nodeHuman, nodeChoice) {
            var nodeHumanId = nodeHuman.id,
                nodeChoiceId = nodeChoice.id,
                newBid = nodeChoice.bid,
                connectedNodes = network.getConnectedNodes(nodeHumanId);

            if ($.inArray(nodeChoiceId, connectedNodes) !== -1) {
                return false; //already part of this group
            }

            //remove other connections to same bid
            var connectedEdges = network.getConnectedEdges(nodeHumanId);
            $.each(connectedEdges, function (key, connectedEdgeId) {
                var connectedEdge = edgesSet.get(connectedEdgeId);
                if (connectedEdge.bid === newBid) {
                    edgesSet.remove(connectedEdgeId);
                }
            });

            var newEdges = edgesSet.add({
                from: nodeHumanId,
                to: nodeChoiceId,
                bid: newBid,
                choiceId: nodeChoice.choiceId,
                color: {color: nodeChoice.color},
                dashes: true
            });
            if (!newEdges) {
                debugger
            }
            nodesView.refresh();
            $.ajax({
                type: 'POST',
                url: '/admin/event/' + el.data('eid') + '/dependencies/change_group_assignment/' + nodeHumanId,
                data: {
                    _token: el.data('token'),
                    bid: newBid,
                    choiceId: nodeChoice.choiceId
                },
                success: function (response) {
                    if (response.success) {
                        edgesSet.update({id: newEdges[0], dashes: false});
                    } else {
                        location.reload();
                    }
                },
                error: function () {
                    location.reload();
                }
            });
            network.addEdgeMode();
            updateGroupTitles();
        };

        var options = {
            layout: {improvedLayout: false},
            manipulation: {
                enabled: false,
                addEdge: function (edgeData, callback) {
                    if (edgeData.from === edgeData.to) {
                        return; //not adding self connections
                    } else {
                        var nodeFrom = nodesSet.get(edgeData.from),
                            nodeFromType = nodeFrom.type,
                            nodeTo = nodesSet.get(edgeData.to),
                            nodeToType = nodeTo.type;

                        if ((nodeFromType !== 'choice' && nodeToType !== 'choice')
                            || (nodeFromType === 'choice' && nodeToType === 'choice')
                        ) {
                            return; //only able to connect choices but not only choices
                        }
                        if (nodeFromType === 'choice') {
                            //swap nodes in order to ensure connection has correct direction
                            var nodeTmp = nodeFrom;
                            nodeFrom = nodeTo;
                            nodeTo = nodeTmp;
                        }

                        connectToChoice(nodeFrom, nodeTo, callback);
                    }
                }
            },
            nodes: {
                font: {
                    face: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                    multi: 'md'
                },
                scaling: {
                    min: 20,
                    max: 60
                }
            },
            edges: {
                font: {
                    face: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                    multi: 'html'
                },
                scaling: {
                    min: 0.5,
                    max: 5
                }
            }
        };

        const formatNumber = function (number) {
            number = (Math.round(number * 10) / 10);
            var stringNumber = number.toString();
            return stringNumber.replace('.', ',');
        };

        var network = new vis.Network(
            container,
            {
                nodes: nodesView,
                edges: edgesSet
            },
            options
        );
        const updateGroupTitles = function () {
            var nodeUpdates = [],
                edgeUpdates = [];

            nodesSet.forEach(function (node) {
                if (node.type === 'choice') {
                    var connectedNodeIds = network.getConnectedNodes(node.id),
                        groupAges = [],
                        label,
                        median,
                        mean,
                        range,
                        distance,
                        nodeSize = (connectedNodeIds.length * 1.5) + 20;
                    $.each(connectedNodeIds, function (key, connectedNodeId) {
                        var connectedNode = nodesSet.get(connectedNodeId);
                        if (connectedNode.type === 'participant') {
                            if (connectedNode.age) {
                                groupAges.push(connectedNode.age);
                            }
                        }
                    });

                    if (node.shortTitle) {
                        label = '*' + node.shortTitle + '*';
                    }
                    if (groupAges.length) {
                        label += "\n";
                        median = eMedian(groupAges);
                        mean = eMean(groupAges);
                        distance = (Math.max(...groupAges) - Math.min(...groupAges));

                        label += ' ~' + formatNumber(median);
                        label += ' x' + formatNumber(mean);
                        label += ' d' + formatNumber(distance);

                        if (node.label === label
                            && node.median === median
                            && node.mean === mean
                            && node.distance === distance
                            && node.nodeSize === nodeSize) {
                            return true;
                        }
                        nodeUpdates.push({
                            id: node.id,
                            label: label,
                            median: median,
                            mean: mean,
                            distance: distance,
                            value: nodeSize
                        });
                        var connectedEdges = network.getConnectedEdges(node.id);
                        $.each(connectedEdges, function (key, connectedEdgeId) {
                            var connectedEdge = edgesSet.get(connectedEdgeId),
                                connectedNode = nodesSet.get(connectedEdge.from),
                                edgeDistance;
                            if (!connectedNode || connectedNode.type !== 'participant' || connectedEdge.type !== 'choice') {
                                return;
                            }
                            edgeDistance = (connectedNode.age - mean) + 0.25;
                            if (edgeDistance < 0) {
                                edgeDistance *= -1;
                            }
                            edgeUpdates.push({
                                id: connectedEdgeId,
                                value: edgeDistance
                            });
                        });
                    } else if (node.label !== label) {
                        nodeUpdates.push({
                            id: node.id,
                            label: label,
                            median: 0,
                            mean: 0,
                            distance: 0,
                            value: nodeSize
                        });
                    }
                }
            });

            var handleQueue = function () {
                var update;
                if (nodeUpdates.length) {
                    update = nodeUpdates.shift();
                    nodesSet.update(update);
                }
                if (edgeUpdates.length) {
                    update = edgeUpdates.shift();
                    edgesSet.update(update);
                }
                scheduleQueue();
            }, scheduleQueue = function () {
                if (nodeUpdates.length || edgeUpdates.length) {
                    window.setTimeout(handleQueue, 1);
                }
            };
            scheduleQueue();
        };

        const modalParticipantEl = $('#modalParticipant'),
            modalParticipantBodyEl = jQuery(modalParticipantEl.find('.modal-body .row')[0]),
            participantDetails = {};
        network.on("doubleClick", function (params) {
            if (params.nodes.length !== 1) {
                return;
            }
            var nodeId = params.nodes[0];
            if (network.isCluster(nodeId)) {
                network.openCluster(nodeId);
            } else {
                var node = nodesSet.get(nodeId);

                switch (node.type) {
                    case 'choice':
                        var clusterOptionsByData = {
                            processProperties: function (clusterOptions, childNodes) {
                                clusterOptions.label = node.label + ' [' + (childNodes.length - 1) + ']';
                                clusterOptions.color = node.color;
                                clusterOptions.shape = node.shape;
                                return clusterOptions;
                            },
                            clusterNodeProperties: {
                                borderWidth: 2,
                                shapeProperties: {borderDashes: [5, 2]}
                            }
                        };
                        network.clusterByConnection(nodeId, clusterOptionsByData);
                        break;
                    case 'participant':
                        modalParticipantEl.data('aid', node.aid);
                        jQuery(modalParticipantEl.find('h4')[0]).text(node.label);
                        jQuery(modalParticipantEl.find('.modal-footer a')[0]).attr('href', '/admin/event/' + modalParticipantEl.data('eid') + '/participant/' + node.aid);
                        modalParticipantEl.modal('show');
                        break;
                }
            }
        });

        const hydrateParticipantDetails = function (content) {
            modalParticipantBodyEl.html('

');
            const items = jQuery.parseHTML(content);
            const target = jQuery(modalParticipantBodyEl.find('div')[0]);

            jQuery.each(items, function (index, item) {
                target.append(item);
            });

            modalParticipantBodyEl.find('a').each(function () {
                const el = jQuery(this);
                el.attr('target', '_blank');
                el.html(eHtml(el.text()) + ' ');
            });
        };

        modalParticipantEl.on('show.bs.modal', function (event) {
            const aid = modalParticipantEl.data('aid');
            modalParticipantBodyEl.toggleClass('loading-text', true);
            if (commonCache.has('participant-partial-details.a'+aid)) {
                hydrateParticipantDetails(commonCache.get('participant-partial-details.a'+aid));
            } else {
                modalParticipantBodyEl.html('

Die Anmeldungdetails werden nachgeschlagen...

');
            }

            jQuery.ajax({
                type: 'GET',
                dataType: 'text',
                url: '/admin/event/' + modalParticipantEl.data('eid') + '/participant/' + aid + '/partial',
                success: function (content, statusText) {
                    modalParticipantBodyEl.toggleClass('loading-text', false);
                    hydrateParticipantDetails(content);
                    commonCache.set('participant-partial-details.a'+aid, content);
                },
                error: function () {
                    modalParticipantBodyEl.toggleClass('loading-text', false);
                    modalParticipantBodyEl.html('

Die Anmeldungdetails konnten nicht geladen werden.

');
                }
            });
        });

        network.on("selectNode", function (params) {
            if (params.nodes.length !== 1) {
                return;
            }
            var nodeId = params.nodes[0],
                node = nodesSet.get(nodeId);
        });
        $('.modes label').on('change', function () {
            var el = $(this),
                elInput = el.find('input'),
                mode = elInput.attr('id');

            if (mode === 'add-edge') {
                network.addEdgeMode();
            } else {
                network.disableEditMode();
            }
        });

        updateGroupTitles();
        nodesView.refresh();
    };
});<|endoftext|>


<commit_before>/**
 * Created by vytautassugintas on 06/04/16.
 */
(function() {
"use strict";
angular.module("myApp").constant("SERVER", {
	//"ip": "https://openkudos.com/api"
	"ip": "http://localhost:8080/"
})
})();
<commit_msg>Changing URL<commit_after>/**
 * Created by vytautassugintas on 06/04/16.
 */
(function() {
"use strict";
angular.module("myApp").constant("SERVER", {
	"ip": "https://openkudos.com/api"
	//"ip": "http://localhost:8080/"
})
})();
<|endoftext|>


<commit_before>/**
 * Step 2
 * Where you prompt users for options (where you'd call this.prompt()).
 */

import chalk from 'chalk';
import questions from '../questions';

function askQuestions(title, questions, done) {
  this.log(chalk.yellow(`\n${title} questions:`));

  this.prompt(questions, answers => {
    this.answers = Object.assign(this.answers || {}, answers);
    done();
  });
}

export default {
  askApp: function () {
    let done = this.async();
    askQuestions.call(this, 'Application', questions.app, done);
  },

  askConfig: function () {
    let done = this.async();
    askQuestions.call(this, 'Configuration', questions.config, done);
  },

  askLogger: function () {
    let done = this.async();
    askQuestions.call(this, 'Logger', questions.logger, done);
  },

  askBlueprint: function () {
    let done = this.async();
    askQuestions.call(this, 'Blueprint', questions.blueprint, done);
  },

  askController: function () {
    let done = this.async();
    askQuestions.call(this, 'Controller', questions.controller, done);
  },

  askHook: function () {
    let done = this.async();
    askQuestions.call(this, 'Hook', questions.hook, done);
  },

  askCron: function () {
    let done = this.async();
    askQuestions.call(this, 'Cron', questions.cron, done);
  },

  askSwagger: function () {
    let done = this.async();
    askQuestions.call(this, 'Swagger', questions.swagger, done);
  },

  askAuthentication: function () {
    let done = this.async();
    askQuestions.call(this, 'Authentication', questions.authentication, done);
  },

  askService: function () {
    let done = this.async();
    askQuestions.call(this, 'Service', questions.service, done);
  }
};
<commit_msg>refactor(app): Refactoring in prompting step<commit_after>/**
 * Step 2
 * Where you prompt users for options (where you'd call this.prompt()).
 */

import chalk from 'chalk';
import questions from '../questions';

function askQuestions(title, questions, done) {
  this.log(chalk.yellow(`\n${title} questions:`));

  this.prompt(questions, answers => {
    this.answers = Object.assign(this.answers || {}, answers);
    done();
  });
}

export default {
  askApp: function () {
    askQuestions.call(this, 'Application', questions.app, this.async());
  },

  askConfig: function () {
    askQuestions.call(this, 'Configuration', questions.config, this.async());
  },

  askLogger: function () {
    askQuestions.call(this, 'Logger', questions.logger, this.async());
  },

  askBlueprint: function () {
    askQuestions.call(this, 'Blueprint', questions.blueprint, this.async());
  },

  askController: function () {
    askQuestions.call(this, 'Controller', questions.controller, this.async());
  },

  askHook: function () {
    askQuestions.call(this, 'Hook', questions.hook, this.async());
  },

  askCron: function () {
    askQuestions.call(this, 'Cron', questions.cron, this.async());
  },

  askSwagger: function () {
    askQuestions.call(this, 'Swagger', questions.swagger, this.async());
  },

  askAuthentication: function () {
    askQuestions.call(this, 'Authentication', questions.authentication, this.async());
  },

  askService: function () {
    askQuestions.call(this, 'Service', questions.service, this.async());
  }
};
<|endoftext|>


<commit_before>// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser)
// https://github.com/RReverser/jsx-transpiler

// jsx

var esutils = require("esutils");
var t       = require("../../types");
var _       = require("lodash");

exports.XJSIdentifier = function (node) {
  if (esutils.keyword.isIdentifierName(node.name)) {
    node.type = "Identifier";
  } else {
    return t.literal(node.name);
  }
};

exports.XJSNamespacedName = function (node, parent, file) {
  throw file.errorWithNode(node, "Namespace tags are not supported. ReactJSX is not XML.");
};

exports.XJSMemberExpression = {
  exit: function (node) {
    node.computed = t.isLiteral(node.property);
    node.type = "MemberExpression";
  }
};

exports.XJSExpressionContainer = function (node) {
  return node.expression;
};

exports.XJSAttribute = {
  exit: function (node) {
    var value = node.value || t.literal(true);
    return t.inherits(t.property("init", node.name, value), node);
  }
};

var isTag = function(tagName) {
  return (/^[a-z]|\-/).test(tagName);
};

exports.XJSOpeningElement = {
  exit: function (node, parent, file) {
    var reactCompat = file.opts.reactCompat;
    var tagExpr = node.name;
    var args = [];

    var tagName;
    if (t.isIdentifier(tagExpr)) {
      tagName = tagExpr.name;
    } else if (t.isLiteral(tagExpr)) {
      tagName = tagExpr.value;
    }

    if (!reactCompat) {
      if (tagName && isTag(tagName)) {
        args.push(t.literal(tagName));
      } else {
        args.push(tagExpr);
      }
    }

    var attribs = node.attributes;
    if (attribs.length) {
      var _props = [];
      var objs = [];

      // so basically in order to support spread elements we
      // loop over all the attributes, breaking on spreads
      // we then push a new object containing all prior attributes
      // to an array for later processing

      var pushProps = function () {
        if (!_props.length) return;

        objs.push(t.objectExpression(_props));
        _props = [];
      };

      while (attribs.length) {
        var prop = attribs.shift();
        if (t.isXJSSpreadAttribute(prop)) {
          pushProps();
          objs.push(prop.argument);
        } else {
          _props.push(prop);
        }
      }

      pushProps();

      if (objs.length === 1) {
        // only one object
        attribs = objs[0];
      } else {
        // looks like we have multiple objects
        if (!t.isObjectExpression(objs[0])) {
          objs.unshift(t.objectExpression([]));
        }

        // spread it
        attribs = t.callExpression(
          t.memberExpression(t.identifier("React"), t.identifier("__spread")),
          objs
        );
      }
    } else {
      attribs = t.literal(null);
    }

    args.push(attribs);

    if (reactCompat) {
      if (tagName && isTag(tagName)) {
        return t.callExpression(
          t.memberExpression(
            t.memberExpression(t.identifier("React"), t.identifier("DOM")),
            tagExpr,
            t.isLiteral(tagExpr)
          ),
          args
        );
      }
    } else {
      tagExpr = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
    }

    return t.callExpression(tagExpr, args);
  }
};

exports.XJSElement = {
  exit: function (node) {
    var callExpr = node.openingElement;

    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];

      if (t.isLiteral(child) && _.isString(child.value)) {
        var lines = child.value.split(/\r\n|\n|\r/);

        for (var i2 = 0; i2 < lines.length; i2++) {
          var line = lines[i2];

          var isFirstLine = i2 === 0;
          var isLastLine = i2 === lines.length - 1;

          // replace rendered whitespace tabs with spaces
          var trimmedLine = line.replace(/\t/g, " ");

          // trim whitespace touching a newline
          if (!isFirstLine) {
            trimmedLine = trimmedLine.replace(/^[ ]+/, "");
          }

          // trim whitespace touching an endline
          if (!isLastLine) {
            trimmedLine = trimmedLine.replace(/[ ]+$/, "");
          }

          if (trimmedLine) {
            callExpr.arguments.push(t.literal(trimmedLine));
          }
        }

        continue;
      } else if (t.isXJSEmptyExpression(child)) {
        continue;
      }

      callExpr.arguments.push(child);
    }

    if (callExpr.arguments.length >= 3) {
      callExpr._prettyCall = true;
    }

    return t.inherits(callExpr, node);
  }
};

// display names

var addDisplayName = function (id, call) {
  if (!call || !t.isCallExpression(call)) return;

  var callee = call.callee;
  if (!t.isMemberExpression(callee)) return;

  // not React
  var obj = callee.object;
  if (!t.isIdentifier(obj, { name: "React" })) return;

  // not createClass
  var prop = callee.property;
  if (!t.isIdentifier(prop, { name: "createClass" })) return;

  // no arguments
  var args = call.arguments;
  if (args.length !== 1) return;

  // not an object
  var first = args[0];
  if (!t.isObjectExpression(first)) return;

  var props = first.properties;
  var safe = true;

  for (var i = 0; i < props.length; i++) {
    prop = props[i];
    if (t.isIdentifier(prop.key, { name: "displayName" })) {
      safe = false;
      break;
    }
  }

  if (safe) {
    props.unshift(t.property("init", t.identifier("displayName"), t.literal(id)));
  }
};

exports.AssignmentExpression =
exports.Property =
exports.VariableDeclarator = function (node) {
  var left, right;

  if (t.isAssignmentExpression(node)) {
    left = node.left;
    right = node.right;
  } else if (t.isProperty(node)) {
    left = node.key;
    right = node.value;
  } else if (t.isVariableDeclarator(node)) {
    left = node.id;
    right = node.init;
  }

  if (t.isMemberExpression(left)) {
    left = left.property;
  }

  if (t.isIdentifier(left)) {
    addDisplayName(left.name, right);
  }
};
<commit_msg>clean up react/jsx transformer<commit_after>// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser)
// https://github.com/RReverser/jsx-transpiler

// jsx

var esutils = require("esutils");
var t       = require("../../types");
var _       = require("lodash");

exports.XJSIdentifier = function (node) {
  if (esutils.keyword.isIdentifierName(node.name)) {
    node.type = "Identifier";
  } else {
    return t.literal(node.name);
  }
};

exports.XJSNamespacedName = function (node, parent, file) {
  throw file.errorWithNode(node, "Namespace tags are not supported. ReactJSX is not XML.");
};

exports.XJSMemberExpression = {
  exit: function (node) {
    node.computed = t.isLiteral(node.property);
    node.type = "MemberExpression";
  }
};

exports.XJSExpressionContainer = function (node) {
  return node.expression;
};

exports.XJSAttribute = {
  exit: function (node) {
    var value = node.value || t.literal(true);
    return t.inherits(t.property("init", node.name, value), node);
  }
};

var isCompatTag = function(tagName) {
  return /^[a-z]|\-/.test(tagName);
};

exports.XJSOpeningElement = {
  exit: function (node, parent, file) {
    var reactCompat = file.opts.reactCompat;
    var tagExpr = node.name;
    var args = [];

    var tagName;
    if (t.isIdentifier(tagExpr)) {
      tagName = tagExpr.name;
    } else if (t.isLiteral(tagExpr)) {
      tagName = tagExpr.value;
    }

    if (!reactCompat) {
      if (tagName && isCompatTag(tagName)) {
        args.push(t.literal(tagName));
      } else {
        args.push(tagExpr);
      }
    }

    var attribs = node.attributes;
    if (attribs.length) {
      attribs = buildXJSOpeningElementAttributes(attribs);
    } else {
      attribs = t.literal(null);
    }

    args.push(attribs);

    if (reactCompat) {
      if (tagName && isCompatTag(tagName)) {
        return t.callExpression(
          t.memberExpression(
            t.memberExpression(t.identifier("React"), t.identifier("DOM")),
            tagExpr,
            t.isLiteral(tagExpr)
          ),
          args
        );
      }
    } else {
      tagExpr = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
    }

    return t.callExpression(tagExpr, args);
  }
};

/**
 * The logic for this is quite terse. It's because we need to
 * support spread elements. We loop over all attributes,
 * breaking on spreads, we then push a new object containg
 * all prior attributes to an array for later processing.
 */

var buildXJSOpeningElementAttributes = function (attribs) {
  var _props = [];
  var objs = [];

  var pushProps = function () {
    if (!_props.length) return;

    objs.push(t.objectExpression(_props));
    _props = [];
  };

  while (attribs.length) {
    var prop = attribs.shift();
    if (t.isXJSSpreadAttribute(prop)) {
      pushProps();
      objs.push(prop.argument);
    } else {
      _props.push(prop);
    }
  }

  pushProps();

  if (objs.length === 1) {
    // only one object
    attribs = objs[0];
  } else {
    // looks like we have multiple objects
    if (!t.isObjectExpression(objs[0])) {
      objs.unshift(t.objectExpression([]));
    }

    // spread it
    attribs = t.callExpression(
      t.memberExpression(t.identifier("React"), t.identifier("__spread")),
      objs
    );
  }

  return attribs;
};

exports.XJSElement = {
  exit: function (node) {
    var callExpr = node.openingElement;

    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];

      if (t.isLiteral(child) && _.isString(child.value)) {
        cleanXJSElementLiteralChild(child, callExpr.arguments);
        continue;
      } else if (t.isXJSEmptyExpression(child)) {
        continue;
      }

      callExpr.arguments.push(child);
    }

    if (callExpr.arguments.length >= 3) {
      callExpr._prettyCall = true;
    }

    return t.inherits(callExpr, node);
  }
};

var cleanXJSElementLiteralChild = function (child, args) {
  var lines = child.value.split(/\r\n|\n|\r/);

  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];

    var isFirstLine = i === 0;
    var isLastLine = i === lines.length - 1;

    // replace rendered whitespace tabs with spaces
    var trimmedLine = line.replace(/\t/g, " ");

    // trim whitespace touching a newline
    if (!isFirstLine) {
      trimmedLine = trimmedLine.replace(/^[ ]+/, "");
    }

    // trim whitespace touching an endline
    if (!isLastLine) {
      trimmedLine = trimmedLine.replace(/[ ]+$/, "");
    }

    if (trimmedLine) {
      args.push(t.literal(trimmedLine));
    }
  }
};

// display names

var isCreateClass = function (call) {
  if (!call || !t.isCallExpression(call)) return false;

  var callee = call.callee;
  if (!t.isMemberExpression(callee)) return false;

  // not React call member object
  var obj = callee.object;
  if (!t.isIdentifier(obj, { name: "React" })) return false;

  // not createClass call member property
  var prop = callee.property;
  if (!t.isIdentifier(prop, { name: "createClass" })) return false;

  // no call arguments
  var args = call.arguments;
  if (args.length !== 1) return false;

  // first call arg is not an object
  var first = args[0];
  if (!t.isObjectExpression(first)) return;

  return true;
};

var addDisplayName = function (id, call) {
  if (!isCreateClass(call)) return;

  var props = call.arguments[0].properties;
  var safe = true;

  for (var i = 0; i < props.length; i++) {
    prop = props[i];
    if (t.isIdentifier(prop.key, { name: "displayName" })) {
      safe = false;
      break;
    }
  }

  if (safe) {
    props.unshift(t.property("init", t.identifier("displayName"), t.literal(id)));
  }
};

exports.AssignmentExpression =
exports.Property =
exports.VariableDeclarator = function (node) {
  var left, right;

  if (t.isAssignmentExpression(node)) {
    left = node.left;
    right = node.right;
  } else if (t.isProperty(node)) {
    left = node.key;
    right = node.value;
  } else if (t.isVariableDeclarator(node)) {
    left = node.id;
    right = node.init;
  }

  if (t.isMemberExpression(left)) {
    left = left.property;
  }

  if (t.isIdentifier(left)) {
    addDisplayName(left.name, right);
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import GeneratePalette from '../domain/GeneratePalette'

var PaletteGenerator = React.createClass({
  getInitialState: function () {
    return {
      startHue: 25,
      minDelta: 18,
      maxL: 90,
      minL: 25,
      maxC: 65,
      minC: 35,
      lcPrecision: 0.5,
      hPrecision: 1
    };
  },

  generate: function () {
    GeneratePalette(this.state);
  },

  startHue: function (event) { this.setState({startHue: event.target.value}); },
  minDelta: function (event) { this.setState({minDelta: event.target.value}); },
  maxL: function (event) { this.setState({maxL: event.target.value}); },
  minL: function (event) { this.setState({minL: event.target.value}); },
  maxC: function (event) { this.setState({maxC: event.target.value}); },
  minC: function (event) { this.setState({minC: event.target.value}); },
  lcPrecision: function (event) { this.setState({lcPrecision: event.target.value}); },
  hPrecision: function (event) { this.setState({hPrecision: event.target.value}); },

  render: function () {
    return (

Generate palette

Start hue: <input value={this.state.startHue} onChange={this.startHue} />

H precision: <input value={this.state.hPrecision} onChange={this.hPrecision} />

L/C precision: <input value={this.state.lcPrecision} onChange={this.lcPrecision} />

Min deltaE: <input value={this.state.minDelta} onChange={this.minDelta} />

Min L: <input value={this.state.minL} onChange={this.minL} />

Max L: <input value={this.state.maxL} onChange={this.maxL} />

Min C: <input value={this.state.minC} onChange={this.minC} />

Max C: <input value={this.state.maxC} onChange={this.maxC} />

<button onClick={this.generate}>Generate</button>

    );
  }
});

export default PaletteGenerator;
<commit_msg>Adjust start parameters<commit_after>import React from 'react';
import GeneratePalette from '../domain/GeneratePalette'

var PaletteGenerator = React.createClass({
  getInitialState: function () {
    return {
      startHue: 30,
      minDelta: 10,
      maxL: 90,
      minL: 25,
      maxC: 90,
      minC: 35,
      lcPrecision: 2,
      hPrecision: 3
    };
  },

  generate: function () {
    GeneratePalette(this.state);
  },

  startHue: function (event) { this.setState({startHue: event.target.value}); },
  minDelta: function (event) { this.setState({minDelta: event.target.value}); },
  maxL: function (event) { this.setState({maxL: event.target.value}); },
  minL: function (event) { this.setState({minL: event.target.value}); },
  maxC: function (event) { this.setState({maxC: event.target.value}); },
  minC: function (event) { this.setState({minC: event.target.value}); },
  lcPrecision: function (event) { this.setState({lcPrecision: event.target.value}); },
  hPrecision: function (event) { this.setState({hPrecision: event.target.value}); },

  render: function () {
    return (

Generate palette

Start hue: <input value={this.state.startHue} onChange={this.startHue} />

H precision: <input value={this.state.hPrecision} onChange={this.hPrecision} />

L/C precision: <input value={this.state.lcPrecision} onChange={this.lcPrecision} />

Min deltaE: <input value={this.state.minDelta} onChange={this.minDelta} />

Min L: <input value={this.state.minL} onChange={this.minL} />

Max L: <input value={this.state.maxL} onChange={this.maxL} />

Min C: <input value={this.state.minC} onChange={this.minC} />

Max C: <input value={this.state.maxC} onChange={this.maxC} />

<button onClick={this.generate}>Generate</button>

    );
  }
});

export default PaletteGenerator;
<|endoftext|>


<commit_before>"use strict";

var React = require('react');
var Panel = require('react-bootstrap').Panel;
var Well = require('react-bootstrap').Well;

var ipcRenderer = require('electron').ipcRenderer;
var remote = require('electron').remote;
var Menu = remote.Menu;
var MenuItem = remote.MenuItem;
var currentWindow = remote.getCurrentWindow();

var Blink1Service = require('../../server/blink1Service');
var PatternsService = require('../../server/patternsService');
var VirtualBlink1 = require('./virtualBlink1');

var PreferencesModal = require('./preferencesModal');
var log = require('../../logger');

var Blink1Status = React.createClass({

	getInitialState: function() {
		return {
			blink1Color: Blink1Service.getCurrentColor(),
			statusStr: Blink1Service.getStatusString(),
			serialNumber: Blink1Service.serialNumberForDisplay(),
			blink1Serials: Blink1Service.getAllSerials(),
			iftttKey: Blink1Service.getIftttKey(),
			currentPattern: '-',
			showForm: false
		};
	},
	componentDidMount: function() {
		var self = this;
		Blink1Service.addChangeListener( this.updateColorState, "blink1Status" );
		PatternsService.addChangeListener( this.updatePatternState, "blink1Status" );

		ipcRenderer.on('openPreferences', function( /*event,arg*/ ) {
			self.setState({showForm: true});
		});

		this.makeMenu();
	},
	updateColorState: function(/*currentColor,  colors,ledn */) {
		this.setState({
						blink1ColorLast: Blink1Service.getCurrentColor(),//currentColor,
						statusStr: Blink1Service.getStatusString(),
						serialNumber: Blink1Service.serialNumberForDisplay(),
						blink1Serials: Blink1Service.getAllSerials(),
						iftttKey: Blink1Service.getIftttKey()
					});
	},
	updatePatternState: function() {
		this.setState({currentPattern: PatternsService.getPlayingInfo()});
	},

	onIftttKeyClick: function() {
		log.msg("Blink1Status.onIfttKeyClick!");
	},
	onPrefsClick: function() {
		this.setState({showForm: true});
	},
	saveForm: function(/*data*/) {
		this.setState({ showForm: false });
	},
	cancelForm: function() {
		this.setState({ showForm: false });
	},
	showIfttContextMenu: function(event) {
		log.msg("Blink1Status.showIfttContextMenu: ",event);
        var menu = this.makeMenu();
		menu.popup(currentWindow);
	},
	// doContextMenu: function(event, eventKey, arg) {
	// 	log.msg("Blink1Status.doContextMenu: eventKey:",eventKey, "arg:",arg);
	// 	//this.props.onEdit(eventKey, this.props.idx, arg);
	// },
	makeMenu: function() {
		var mymenu = new Menu();
		// mymenu.append( new MenuItem({label:'copy', click: self.doContextMenu.bind(null,null, 'copyiftttkey', null)}) );
		mymenu.append( new MenuItem({label:'Copy IFTTT Key', role:'copy'} ));
        // mymenu.append( new MenuItem({label:'Edit Host Id', click: this.doEditHostId} ));
		return mymenu;
	},
	render: function() {
		// console.log("blink1Status.render: ", this.state.blink1Color);
		var currentPattern = this.state.currentPattern;
		if( !currentPattern ) { currentPattern = '-'; }
		var labelStyle = {width: 80, display: "inline-block"};
		var serialNums = "serials:\n";
		this.state.blink1Serials.forEach(function(s){ serialNums+= "blink1:"+s+"\n"; });
		var onlineStatus = (navigator.onLine ? 'network online' : 'network offline');

		// <VirtualBlink1 blink1Color={this.state.blink1Color} /> // FIXME
		var header =
Device <button style={{float:'right' }} bsStyle='link' onClick={this.onPrefsClick}></button>
;

		return (
			<Panel header={header} style={{ width: 280, height: 320, margin:5, padding:0 }}>
				<PreferencesModal show={this.state.showForm}
					onSave={this.saveForm} onCancel={this.cancelForm} blink1Serials={this.state.blink1Serials} />

				<VirtualBlink1 />

				<Well bsSize="small" style={{margin: 0}}>

						Status:
						{this.state.statusStr}

						Serial num:

							{this.state.serialNumber}

						IFTTT Key:

							{this.state.iftttKey}

						Source/Patt:
						{currentPattern}

				</Well>
			</Panel>
		);
	}

});

module.exports = Blink1Status;
<commit_msg>added better view of playingPatternSource in Status view<commit_after>"use strict";

var React = require('react');
var Panel = require('react-bootstrap').Panel;
var Well = require('react-bootstrap').Well;

var ipcRenderer = require('electron').ipcRenderer;
var remote = require('electron').remote;
var Menu = remote.Menu;
var MenuItem = remote.MenuItem;
var currentWindow = remote.getCurrentWindow();

var Blink1Service = require('../../server/blink1Service');
var PatternsService = require('../../server/patternsService');
var VirtualBlink1 = require('./virtualBlink1');

var PreferencesModal = require('./preferencesModal');
var log = require('../../logger');

var Blink1Status = React.createClass({

	getInitialState: function() {
		return {
			blink1Color: Blink1Service.getCurrentColor(),
			statusStr: Blink1Service.getStatusString(),
			serialNumber: Blink1Service.serialNumberForDisplay(),
			blink1Serials: Blink1Service.getAllSerials(),
			iftttKey: Blink1Service.getIftttKey(),
			currentPattern: '-',
			showForm: false
		};
	},
	componentDidMount: function() {
		var self = this;
		Blink1Service.addChangeListener( this.updateColorState, "blink1Status" );
		PatternsService.addChangeListener( this.updatePatternState, "blink1Status" );

		ipcRenderer.on('openPreferences', function( /*event,arg*/ ) {
			self.setState({showForm: true});
		});

		this.makeMenu();
	},
	updateColorState: function(/*currentColor,  colors,ledn */) {
		this.setState({
						blink1ColorLast: Blink1Service.getCurrentColor(),//currentColor,
						statusStr: Blink1Service.getStatusString(),
						serialNumber: Blink1Service.serialNumberForDisplay(),
						blink1Serials: Blink1Service.getAllSerials(),
						iftttKey: Blink1Service.getIftttKey()
					});
	},
	updatePatternState: function() {
		this.setState( {
            currentPattern: PatternsService.getPlayingPatternName(),
            currentSource: PatternsService.getPlayingPatternSource() });
	},

	onIftttKeyClick: function() {
		log.msg("Blink1Status.onIfttKeyClick!");
	},
	onPrefsClick: function() {
		this.setState({showForm: true});
	},
	saveForm: function(/*data*/) {
		this.setState({ showForm: false });
	},
	cancelForm: function() {
		this.setState({ showForm: false });
	},
	showIfttContextMenu: function(event) {
		log.msg("Blink1Status.showIfttContextMenu: ",event);
        var menu = this.makeMenu();
		menu.popup(currentWindow);
	},
	// doContextMenu: function(event, eventKey, arg) {
	// 	log.msg("Blink1Status.doContextMenu: eventKey:",eventKey, "arg:",arg);
	// 	//this.props.onEdit(eventKey, this.props.idx, arg);
	// },
	makeMenu: function() {
		var mymenu = new Menu();
		// mymenu.append( new MenuItem({label:'copy', click: self.doContextMenu.bind(null,null, 'copyiftttkey', null)}) );
		mymenu.append( new MenuItem({label:'Copy IFTTT Key', role:'copy'} ));
        // mymenu.append( new MenuItem({label:'Edit Host Id', click: this.doEditHostId} ));
		return mymenu;
	},
	render: function() {
		// console.log("blink1Status.render: ", this.state.blink1Color);
		var currentPattern = this.state.currentPattern;
		if( !currentPattern ) { currentPattern = '-'; }
        var currentSource = this.state.currentSource;
        if( !currentSource ) { currentSource = '-'; }

		var labelStyle = {width: 80, display: "inline-block", textAlign:'right', paddingRight:5};
		var serialNums = "serials:\n";
		this.state.blink1Serials.forEach(function(s){ serialNums+= "blink1:"+s+"\n"; });
		var onlineStatus = (navigator.onLine ? 'network online' : 'network offline');

		// <VirtualBlink1 blink1Color={this.state.blink1Color} /> // FIXME
		var header =
Device <button style={{float:'right' }} bsStyle='link' onClick={this.onPrefsClick}></button>
;

		return (
			<Panel header={header} style={{ width: 280, height: 320, margin:5, padding:0 }}>
				<PreferencesModal show={this.state.showForm}
					onSave={this.saveForm} onCancel={this.cancelForm} blink1Serials={this.state.blink1Serials} />

				<VirtualBlink1 />

				<Well bsSize="small" style={{margin: 0}}>

						Status:
						{this.state.statusStr}

						Serial num:

							{this.state.serialNumber}

						IFTTT Key:

							{this.state.iftttKey}

                        Source:
                        {currentSource}

						Pattern:
                        {currentPattern}

				</Well>
			</Panel>
		);
	}

});

module.exports = Blink1Status;
<|endoftext|>


<commit_before>
import '../../css/login/corpus-list'

import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import { routerActions } from 'react-router-redux'
import { FormattedMessage as T, FormattedRelative as D } from 'react-intl'

// abstract component
class CorpusListItem extends React.Component {
  constructor (props) {
    super(props)
    this.selectCorpus = this.selectCorpus.bind(this)
  }

  selectCorpus () {
    const { actions, server, corpus, dispatch } = this.props
    const path = corpus.password ? '/login/corpus-login-form' : 'browser'
    actions.selectCorpus(server, corpus)
    dispatch(routerActions.push(path))
  }

  render () {
    const { password, name, status, webentities_in, created_at,
      last_activity } = this.props.corpus

    return (

          { password &&  }
          { name }
          { status === 'ready' &&  }

<T id="webentities" values={ { count: webentities_in } } />

          <T id="created-ago" values={ { relative: <D value={ created_at } /> } } />
           -
          <T id="used-ago" values={ { relative: <D value={ last_activity } /> } } />

    )
  }
}

CorpusListItem.propTypes = {
  actions: PropTypes.object.isRequired,
  corpus: PropTypes.object.isRequired,
  server: PropTypes.object.isRequired,
  dispatch: PropTypes.func
}

const CorpusList = (props) => {

  const { actions, dispatch, server, status } = props
  const corpora = Object.keys(props.corpora)
    .sort()
    .map((k) => props.corpora[k])

  if (!corpora.length) return null

  const hypheStatus = status && status.corpus_running &&
    (

        ,
        <T id="running-corpora" values={ { count: status.corpus_running } } />

    )

  return (

        <T id="available-corpora" values={ { count: corpora.length } } />
        { hypheStatus }

          { corpora.map((corpus) =>

              <CorpusListItem actions={ actions } server={ server } corpus={ corpus } dispatch={ dispatch } />

          ) }

        <Link className="btn btn-primary" to="/login/corpus-form"><T id="create-corpus" /></Link>

  )
}

CorpusList.propTypes = {
  actions: PropTypes.object.isRequired,
  dispatch: PropTypes.func,
  corpora: PropTypes.object.isRequired,
  server: PropTypes.object.isRequired,
  status: PropTypes.object
}

export default CorpusList
<commit_msg>fix(CorpusList): cast corpus_running to real boolean<commit_after>
import '../../css/login/corpus-list'

import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import { routerActions } from 'react-router-redux'
import { FormattedMessage as T, FormattedRelative as D } from 'react-intl'

// abstract component
class CorpusListItem extends React.Component {
  constructor (props) {
    super(props)
    this.selectCorpus = this.selectCorpus.bind(this)
  }

  selectCorpus () {
    const { actions, server, corpus, dispatch } = this.props
    const path = corpus.password ? '/login/corpus-login-form' : 'browser'
    actions.selectCorpus(server, corpus)
    dispatch(routerActions.push(path))
  }

  render () {
    const { password, name, status, webentities_in, created_at,
      last_activity } = this.props.corpus

    return (

          { password &&  }
          { name }
          { status === 'ready' &&  }

<T id="webentities" values={ { count: webentities_in } } />

          <T id="created-ago" values={ { relative: <D value={ created_at } /> } } />
           -
          <T id="used-ago" values={ { relative: <D value={ last_activity } /> } } />

    )
  }
}

CorpusListItem.propTypes = {
  actions: PropTypes.object.isRequired,
  corpus: PropTypes.object.isRequired,
  server: PropTypes.object.isRequired,
  dispatch: PropTypes.func
}

const CorpusList = (props) => {

  const { actions, dispatch, server, status } = props
  const corpora = Object.keys(props.corpora)
    .sort()
    .map((k) => props.corpora[k])

  if (!corpora.length) return null

  const hypheStatus = status && Boolean(status.corpus_running) &&
    (

        ,
        <T id="running-corpora" values={ { count: status.corpus_running } } />

    )

  return (

        <T id="available-corpora" values={ { count: corpora.length } } />
        { hypheStatus }

          { corpora.map((corpus) =>

              <CorpusListItem actions={ actions } server={ server } corpus={ corpus } dispatch={ dispatch } />

          ) }

        <Link className="btn btn-primary" to="/login/corpus-form"><T id="create-corpus" /></Link>

  )
}

CorpusList.propTypes = {
  actions: PropTypes.object.isRequired,
  dispatch: PropTypes.func,
  corpora: PropTypes.object.isRequired,
  server: PropTypes.object.isRequired,
  status: PropTypes.object
}

export default CorpusList
<|endoftext|>