<commit_before>/*
	Xexun TK102 GPS server for Node.js

	Author:  Franklin van de Meent
	Website: http://frankl.in
	Contact: fr@nkl.in
	Twitter: @unknownt

	Source:  http://fvdm.github.com/nodejs-tk102
*/

// settings
var serverIP = '0.0.0.0';
var serverPort = 1337;
var maxConnections = 100;
var idleTimeout = 10;

// INIT
var net = require('net');
var server = net.createServer( function( socket ) {
	if( idleTimeout > 0 ) {
		socket.setTimeout( idleTimeout * 1000, function() {
			socket.end();
		});
	}
}).listen( serverPort, serverIP );

server.maxConnections = maxConnections;

// connect
server.on( 'connection', function( socket ) {
	socket.setEncoding( 'utf8' );

	// data
	socket.on( 'data', function( raw ) {
		var gps = tk102( raw );
		console.log( gps );
	});
});

function tk102( raw ) {
	// 1203292316,0031698765432,GPRMC,211657.000,A,5213.0247,N,00516.7757,E,0.00,273.30,290312,,,A*62,F,imei:123456789012345,123
	var raw = raw.replace( /(^[\s\t\r\n]+|[\s\t\r\n]+$)/, '' );
	var str = raw.split(',');
	var data = {};

	// only continue with correct input, else the server may quit...
	if( raw.indexOf(',GPRMC,') && str.length == 18 ) {

		// parse
		var datetime = str[0].replace( /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/, function( match, year, month, day, hour, minute ) {
			return '20'+ year +'-'+ month +'-'+ day +' '+ hour +':'+ minute
		});
		var gpsdate = str[11].replace( /([0-9]{2})([0-9]{2})([0-9]{2})/, function( match, day, month, year ) {
			return '20'+ year +'-'+ month +'-'+ day;
		});
		var gpstime = str[3].replace( /([0-9]{2})([0-9]{2})([0-9]{2})\.([0-9]{3})/, function( match, hour, minute, second, ms ) {
			return hour +':'+ minute +':'+ second +'.'+ ms;
		});

		data = {
			'raw':		raw,
			'datetime':	datetime,
			'phone':	str[1],
			'gps': {
				'date':		gpsdate,
				'time':		gpstime,
				'signal':	str[15],
				'fix':		str[4] == 'A' ? 'active' : 'invalid'
			},
			'geo': {
				'latitude':	parseFloat( fixGeo( str[5], str[6] ) ),
				'longitude':	parseFloat( fixGeo( str[7], str[8] ) ),
				'heading':	parseInt( str[10] )
			},
			'kmh':		parseFloat( str[9] ),
			'imei':		str[16].replace( 'imei:', '' )
		};
	}

	// done
	return data;
}

// clean geo positions
function fixGeo( one, two ) {
	var one = (two == 'S' || two == 'W' ? '-' : '') + one;
	one = one / 100 +'';
	one = one.replace( /^([0-9]+)\.([0-9]+)$/, function( match, num, dec ) {
		return num +'.'+ dec.substr(0,6);
	});
	return one;
}
<commit_msg>Speed is in knots instead of kmh<commit_after>/*
	Xexun TK102 GPS server for Node.js

	Author:  Franklin van de Meent
	Website: http://frankl.in
	Contact: fr@nkl.in
	Twitter: @unknownt

	Source:  http://fvdm.github.com/nodejs-tk102
*/

// settings
var serverIP = '0.0.0.0';
var serverPort = 1337;
var maxConnections = 100;
var idleTimeout = 10;

// INIT
var net = require('net');
var server = net.createServer( function( socket ) {
	if( idleTimeout > 0 ) {
		socket.setTimeout( idleTimeout * 1000, function() {
			socket.end();
		});
	}
}).listen( serverPort, serverIP );

server.maxConnections = maxConnections;

// connect
server.on( 'connection', function( socket ) {
	socket.setEncoding( 'utf8' );

	// data
	socket.on( 'data', function( raw ) {
		var gps = tk102( raw );
		console.log( gps );
	});
});

function tk102( raw ) {
	// 1203292316,0031698765432,GPRMC,211657.000,A,5213.0247,N,00516.7757,E,0.00,273.30,290312,,,A*62,F,imei:123456789012345,123
	var raw = raw.replace( /(^[\s\t\r\n]+|[\s\t\r\n]+$)/, '' );
	var str = raw.split(',');
	var data = {};

	// only continue with correct input, else the server may quit...
	if( raw.indexOf(',GPRMC,') && str.length == 18 ) {

		// parse
		var datetime = str[0].replace( /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/, function( match, year, month, day, hour, minute ) {
			return '20'+ year +'-'+ month +'-'+ day +' '+ hour +':'+ minute
		});
		var gpsdate = str[11].replace( /([0-9]{2})([0-9]{2})([0-9]{2})/, function( match, day, month, year ) {
			return '20'+ year +'-'+ month +'-'+ day;
		});
		var gpstime = str[3].replace( /([0-9]{2})([0-9]{2})([0-9]{2})\.([0-9]{3})/, function( match, hour, minute, second, ms ) {
			return hour +':'+ minute +':'+ second +'.'+ ms;
		});

		data = {
			'raw':		raw,
			'datetime':	datetime,
			'phone':	str[1],
			'gps': {
				'date':		gpsdate,
				'time':		gpstime,
				'signal':	str[15],
				'fix':		str[4] == 'A' ? 'active' : 'invalid'
			},
			'geo': {
				'latitude':	parseFloat( fixGeo( str[5], str[6] ) ),
				'longitude':	parseFloat( fixGeo( str[7], str[8] ) ),
				'heading':	parseInt( str[10] )
			},
			'knots':	Math.round( str[9] * 1000 ) / 1000,
			'kmh':		Math.round( str[9] * 1.852 * 1000 ) / 1000,
			'mph':		Math.round( str[9] * 1.151 * 1000 ) / 1000,
			'imei':		str[16].replace( 'imei:', '' )
		};
	}

	// done
	return data;
}

// clean geo positions
function fixGeo( one, two ) {
	var one = (two == 'S' || two == 'W' ? '-' : '') + one;
	one = one / 100 +'';
	one = one.replace( /^([0-9]+)\.([0-9]+)$/, function( match, num, dec ) {
		return num +'.'+ dec.substr(0,6);
	});
	return one;
}
<|endoftext|>


<commit_before>require('fileapi');

var backbone = require('backbone');
var backboneBase = require('backbone-base');
var getUri = require('get-uri');
var Goodtables = require('../goodtables');
var jsonEditor = require('json-editor');
var jtsInfer = require('jts-infer');
var highlight = require('highlight-redux');
var UploadView = require('./upload');
var registry = require('./registry');
var _ = require('underscore');
var $ = require('jquery');

// Upload data file and populate .resource array with item
DataUploadView = backbone.BaseView.extend({
  events: {
    // Set up and append .resources row
    'change [data-id=input]': function(E) {
      FileAPI.readAsText(FileAPI.getFiles(E.currentTarget)[0], (function (EV) {
        if(EV.type === 'load') {
          getUri(['data', EV.target.type, 'utf-8'].join(':') + ',' + EV.result, (function (E, R) {
            if(E) throw E;

            jtsInfer(R, (function(E, S, SR) {
              if(E) throw E;

              this.options.form.getEditor('root.resources').addRow({
                name: EV.target.name,
                path: EV.target.name,
                schema: S
              });

              // Save data source
              _.last(this.options.form.getEditor('root.resources').rows).dataSource = EV.result;
            }).bind(this));
          }).bind(this));
        } else if( EV.type ==='progress' ) {
          this.setProgress(EV.loaded/EV.total * 100);
        } else {
          this.setError('File upload failed');
        }

        this.$(E.currentTarget).val('');
      }).bind(this));
    },

    'click [data-id=upload-data-file]': function() { this.$('[data-id=input]').trigger('click'); }
  },

  render: function() {
    this.$el
      .append('<input data-id="input" type="file" accept="text/csv" style="display: none;">')

      .append(
        $(this.options.form.theme.getButton('Upload data file', '', 'Upload data file'))
          .attr('data-id', 'upload-data-file')
      );

    return this;
  },

  setError: function() { return this; },
  setProgress: function() { return this; }
});

module.exports = {
  DescriptorEditView: backbone.BaseView.extend({
    activate: function(state) {
      backbone.BaseView.prototype.activate.call(this, state);
      this.layout.upload.activate(state);
      return this;
    },

    clearResourceValidation: function() {
      this.$('#resources-validation-messages [data-id=messages]').remove();
      return this;
    },

    events: {
      'click #validate-resources': function() {
        var
          goodTables = new Goodtables({method: 'post'});

        // Clear previous
        this.clearResourceValidation();

        _.each(this.layout.form.getEditor('root.resources').rows, function(R) {
          goodTables.run(R.dataSource, JSON.stringify({fields: _.map(R.schema.properties, function(V, K) {
              return _.extend(V, {name: K}) })}
          )).then(
            function(M) {
              // Ok
              window.APP.$('#resources-validation-messages').append(
                _.map(M.isValid() ? ['Validation Success'] : M.getValidationErrors(), function(M) {
                  return ['
', M.result_message, '
'].join('');
                }));
            }
          );
        });
      }
    },

    initialize: function(options) {
      highlight.configure({useBR: true});
      return backbone.BaseView.prototype.initialize.call(this, options);
    },

    render: function() {
      this.layout.upload = new UploadView({el: window.APP.$('#upload-data-package'), parent: this});
      this.layout.registryList = new registry.ListView({el: window.APP.$('#registry-list'), parent: this});
      return this;
    },

    // Utility method to remove empty values from object recursive
    compactObject: function(data) {
      _.each(data, function(v, k) {
        if(_.isEmpty(v)) {
          delete data[k];
        } else if(_.isArray(v) || _.isObject(v)) {
          v = this.compactObject(v);

          if(_.isArray(v))
            v = _.compact(v);

          if(_.isEmpty(v))
            delete data[k];
          else data[k] = v;
        }
      }, this);

      return data;
    },

    getFilledValues: function() { return this.compactObject(this.layout.form.getValue()); },
    getValue: function () { return this.layout.form.getValue(); },
    hasChanges: function() { return Boolean(this.changed); },

    reset: function(schema) {
      var formData;

      this.clearResourceValidation();

      // Clean up previous state
      if(this.layout.form) {
        formData = this.getFilledValues();
        this.layout.form.destroy();
        this.layout.uploadData.undelegateEvents().remove();
      }

      this.layout.form = new JSONEditor(this.$('[data-id=form-container]').get(0), {
        schema: schema,
        theme: 'bootstrap3'
      });

      this.layout.uploadData = (new DataUploadView({
        el: this.layout.form.theme.getHeaderButtonHolder(),
        form: this.layout.form,
        parent: this
      })).render();

      this.layout.form.on('ready', (function() {
        // There is no any good way to bind events to custom button or even add cutsom button
        $(this.layout.form.getEditor('root.resources').container)
          .children('h3').append(this.layout.uploadData.el);

        // Detecting changes
        this.changed = false;

        // After `ready` event fired, editor fire `change` event regarding to the initial changes
        this.layout.form.on('change', _.after(2, (function() {
          this.changed = true;
          window.APP.layout.download.reset(this.layout.form.getValue()).activate();
          this.showResult();
        }).bind(this)));

        // If on the previous form was entered values try to apply it to new form
        if(formData) {
          this.layout.form.setValue(_.extend({}, this.layout.form.getValue(formData), formData));

          // Expand editors if it have value
          _.each(this.$('[data-schemapath][data-schemapath!=root]:has(.json-editor-btn-collapse)'), function(E) {
              if(_.isEmpty(this.layout.form.getEditor($(E).data('schemapath')).getValue()))
                $(E).find('.json-editor-btn-collapse').click();
          }, this);
        } else
          // Collapse all
          this.$('.row .json-editor-btn-collapse').click();

      }).bind(this));
    },

    showResult: function() {
      $('#json-code').html(highlight.fixMarkup(
        highlight.highlight('json', JSON.stringify(this.layout.form.getValue(), undefined, 2)).value
      ));

      return this;
    }
  })
};
<commit_msg>Comment to goodtables schema format (#33)<commit_after>require('fileapi');

var backbone = require('backbone');
var backboneBase = require('backbone-base');
var getUri = require('get-uri');
var Goodtables = require('../goodtables');
var jsonEditor = require('json-editor');
var jtsInfer = require('jts-infer');
var highlight = require('highlight-redux');
var UploadView = require('./upload');
var registry = require('./registry');
var _ = require('underscore');
var $ = require('jquery');

// Upload data file and populate .resource array with item
DataUploadView = backbone.BaseView.extend({
  events: {
    // Set up and append .resources row
    'change [data-id=input]': function(E) {
      FileAPI.readAsText(FileAPI.getFiles(E.currentTarget)[0], (function (EV) {
        if(EV.type === 'load') {
          getUri(['data', EV.target.type, 'utf-8'].join(':') + ',' + EV.result, (function (E, R) {
            if(E) throw E;

            jtsInfer(R, (function(E, S, SR) {
              if(E) throw E;

              this.options.form.getEditor('root.resources').addRow({
                name: EV.target.name,
                path: EV.target.name,
                schema: S
              });

              // Save data source
              _.last(this.options.form.getEditor('root.resources').rows).dataSource = EV.result;
            }).bind(this));
          }).bind(this));
        } else if( EV.type ==='progress' ) {
          this.setProgress(EV.loaded/EV.total * 100);
        } else {
          this.setError('File upload failed');
        }

        this.$(E.currentTarget).val('');
      }).bind(this));
    },

    'click [data-id=upload-data-file]': function() { this.$('[data-id=input]').trigger('click'); }
  },

  render: function() {
    this.$el
      .append('<input data-id="input" type="file" accept="text/csv" style="display: none;">')

      .append(
        $(this.options.form.theme.getButton('Upload data file', '', 'Upload data file'))
          .attr('data-id', 'upload-data-file')
      );

    return this;
  },

  setError: function() { return this; },
  setProgress: function() { return this; }
});

module.exports = {
  DescriptorEditView: backbone.BaseView.extend({
    activate: function(state) {
      backbone.BaseView.prototype.activate.call(this, state);
      this.layout.upload.activate(state);
      return this;
    },

    clearResourceValidation: function() {
      this.$('#resources-validation-messages [data-id=messages]').remove();
      return this;
    },

    events: {
      'click #validate-resources': function() {
        var
          goodTables = new Goodtables({method: 'post'});

        // Clear previous
        this.clearResourceValidation();

        _.each(this.layout.form.getEditor('root.resources').rows, function(R) {
          // Goodtables schema format {fields: [{name:'colname'...},...]}
          // Example https://raw.githubusercontent.com/okfn/goodtables/master/examples/test_schema.json
          goodTables.run(R.dataSource, JSON.stringify({fields: _.map(R.schema.properties, function(V, K) {
              return _.extend(V, {name: K}) })}
          )).then(
            function(M) {
              // Ok
              window.APP.$('#resources-validation-messages').append(
                _.map(M.isValid() ? ['Validation Success'] : M.getValidationErrors(), function(M) {
                  return ['
', M.result_message, '
'].join('');
                }));
            }
          );
        });
      }
    },

    initialize: function(options) {
      highlight.configure({useBR: true});
      return backbone.BaseView.prototype.initialize.call(this, options);
    },

    render: function() {
      this.layout.upload = new UploadView({el: window.APP.$('#upload-data-package'), parent: this});
      this.layout.registryList = new registry.ListView({el: window.APP.$('#registry-list'), parent: this});
      return this;
    },

    // Utility method to remove empty values from object recursive
    compactObject: function(data) {
      _.each(data, function(v, k) {
        if(_.isEmpty(v)) {
          delete data[k];
        } else if(_.isArray(v) || _.isObject(v)) {
          v = this.compactObject(v);

          if(_.isArray(v))
            v = _.compact(v);

          if(_.isEmpty(v))
            delete data[k];
          else data[k] = v;
        }
      }, this);

      return data;
    },

    getFilledValues: function() { return this.compactObject(this.layout.form.getValue()); },
    getValue: function () { return this.layout.form.getValue(); },
    hasChanges: function() { return Boolean(this.changed); },

    reset: function(schema) {
      var formData;

      this.clearResourceValidation();

      // Clean up previous state
      if(this.layout.form) {
        formData = this.getFilledValues();
        this.layout.form.destroy();
        this.layout.uploadData.undelegateEvents().remove();
      }

      this.layout.form = new JSONEditor(this.$('[data-id=form-container]').get(0), {
        schema: schema,
        theme: 'bootstrap3'
      });

      this.layout.uploadData = (new DataUploadView({
        el: this.layout.form.theme.getHeaderButtonHolder(),
        form: this.layout.form,
        parent: this
      })).render();

      this.layout.form.on('ready', (function() {
        // There is no any good way to bind events to custom button or even add cutsom button
        $(this.layout.form.getEditor('root.resources').container)
          .children('h3').append(this.layout.uploadData.el);

        // Detecting changes
        this.changed = false;

        // After `ready` event fired, editor fire `change` event regarding to the initial changes
        this.layout.form.on('change', _.after(2, (function() {
          this.changed = true;
          window.APP.layout.download.reset(this.layout.form.getValue()).activate();
          this.showResult();
        }).bind(this)));

        // If on the previous form was entered values try to apply it to new form
        if(formData) {
          this.layout.form.setValue(_.extend({}, this.layout.form.getValue(formData), formData));

          // Expand editors if it have value
          _.each(this.$('[data-schemapath][data-schemapath!=root]:has(.json-editor-btn-collapse)'), function(E) {
              if(_.isEmpty(this.layout.form.getEditor($(E).data('schemapath')).getValue()))
                $(E).find('.json-editor-btn-collapse').click();
          }, this);
        } else
          // Collapse all
          this.$('.row .json-editor-btn-collapse').click();

      }).bind(this));
    },

    showResult: function() {
      $('#json-code').html(highlight.fixMarkup(
        highlight.highlight('json', JSON.stringify(this.layout.form.getValue(), undefined, 2)).value
      ));

      return this;
    }
  })
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

// Constants
import { EXPLORE_SECTIONS } from 'layout/explore/constants';

// Styles
import './styles.scss';

function ExploreDiscover(props) {
  const { setSidebarSection } = props;
  return (

Trending datasets

 setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
          >
                        SEE ALL DATA

Related topics

 setSidebarSection(EXPLORE_SECTIONS.TOPICS)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.TOPICS)}
          >
                        SEE ALL

Recent updated

 setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
          >
                        SEE ALL DATA

Related dashboards

          {/* <Link/> didn't work for some reason... */}

                        SEE ALL

  );
}

ExploreDiscover.propTypes = { setSidebarSection: PropTypes.func.isRequired };

export default ExploreDiscover;
<commit_msg>topics list added to explore-discover<commit_after>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';

// Constants
import { EXPLORE_SECTIONS } from 'layout/explore/constants';

// Services
import { fetchRWConfig } from 'services/config';

// Components
import TopicsList from 'layout/explore/explore-topics/list';

// Styles
import './styles.scss';

function ExploreDiscover(props) {
  const { setSidebarSection } = props;
  const [config, setConfig] = useState({
    highlightedDastasets: [],
    relatedTopics: [],
    recentUpdated: [],
    relatedDashboards: []
  });

  useEffect(() => {
    setConfig(fetchRWConfig());
  }, []);

  const {
    relatedTopics,
    recentUpdated,
    relatedDashboards
  } = config;

  return (

Trending datasets

 setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
          >
                        SEE ALL DATA

Related topics

 setSidebarSection(EXPLORE_SECTIONS.TOPICS)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.TOPICS)}
          >
                        SEE ALL

        {relatedTopics.length > 0 &&
          <TopicsList
            topics={relatedTopics}
            onClick={(id) => {
              props.setFiltersSearch('');
              props.resetFiltersSort();
              props.setFiltersSelected({ key: 'topics', list: [id] });
              props.setDatasetsPage(1);
              props.fetchDatasets();
              props.setSidebarSection(EXPLORE_SECTIONS.ALL_DATA);
            }}
          />
        }

Recent updated

 setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
            onKeyPress={() => setSidebarSection(EXPLORE_SECTIONS.ALL_DATA)}
          >
                        SEE ALL DATA

Related dashboards

          {/* <Link/> didn't work for some reason... */}

                        SEE ALL

  );
}

ExploreDiscover.propTypes = {
  setSidebarSection: PropTypes.func.isRequired,
  setFiltersSearch: PropTypes.func.isRequired,
  resetFiltersSort: PropTypes.func.isRequired,
  setDatasetsPage: PropTypes.func.isRequired,
  fetchDatasets: PropTypes.func.isRequired,
  setFiltersSelected: PropTypes.func.isRequired
};

export default ExploreDiscover;
<|endoftext|>


<commit_before>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node / CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals.
    factory(jQuery);
  }
})(function ($) {

  'use strict';

  var NAMESPACE = 'qor.chooser';
  var EVENT_ENABLE = 'enable.' + NAMESPACE;
  var EVENT_DISABLE = 'disable.' + NAMESPACE;

  function QorChooser(element, options) {
    this.$element = $(element);
    this.options = $.extend({}, QorChooser.DEFAULTS, $.isPlainObject(options) && options);
    this.init();
  }

  QorChooser.prototype = {
    constructor: QorChooser,

    init: function () {
      var $this = this.$element;

      if (!$this.prop('multiple')) {
        if ($this.children('[selected]').length) {
          $this.prepend('<option value=""></option>');
        } else {
          $this.prepend('<option value="" selected></option>');
        }
      }

      $this.chosen({
        // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
        allow_single_deselect: true,
        disable_search_threshold: 10,
        width: '100%'
      });
    },

    destroy: function () {
      this.$element.chosen('destroy');
    },
  };

  QorChooser.DEFAULTS = {};

  QorChooser.plugin = function (options) {
    return this.each(function () {
      var $this = $(this);
      var data = $this.data(NAMESPACE);
      var fn;

      if (!data) {
        if (!$.fn.chosen) {
          return;
        }

        if (/destroy/.test(options)) {
          return;
        }

        $this.data(NAMESPACE, (data = new QorChooser(this, options)));
      }

      if (typeof options === 'string' && $.isFunction(fn = data[options])) {
        fn.apply(data);
      }
    });
  };

  $(function () {
    var selector = 'select[data-toggle="qor.chooser"]';

    $(document).
      on(EVENT_DISABLE, function (e) {
        QorChooser.plugin.call($(selector, e.target), 'destroy');
      }).
      on(EVENT_ENABLE, function (e) {
        QorChooser.plugin.call($(selector, e.target));
      }).
      triggerHandler(EVENT_ENABLE);
  });

  return QorChooser;

});
<commit_msg>Fix bug of QOR Chooser destroy<commit_after>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node / CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals.
    factory(jQuery);
  }
})(function ($) {

  'use strict';

  var NAMESPACE = 'qor.chooser';
  var EVENT_ENABLE = 'enable.' + NAMESPACE;
  var EVENT_DISABLE = 'disable.' + NAMESPACE;

  function QorChooser(element, options) {
    this.$element = $(element);
    this.options = $.extend({}, QorChooser.DEFAULTS, $.isPlainObject(options) && options);
    this.init();
  }

  QorChooser.prototype = {
    constructor: QorChooser,

    init: function () {
      var $this = this.$element;

      if (!$this.prop('multiple')) {
        if ($this.children('[selected]').length) {
          $this.prepend('<option value=""></option>');
        } else {
          $this.prepend('<option value="" selected></option>');
        }
      }

      $this.chosen({
        // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
        allow_single_deselect: true,
        disable_search_threshold: 10,
        width: '100%'
      });
    },

    destroy: function () {
      this.$element.chosen('destroy').removeData(NAMESPACE);
    },
  };

  QorChooser.DEFAULTS = {};

  QorChooser.plugin = function (options) {
    return this.each(function () {
      var $this = $(this);
      var data = $this.data(NAMESPACE);
      var fn;

      if (!data) {
        if (!$.fn.chosen) {
          return;
        }

        if (/destroy/.test(options)) {
          return;
        }

        $this.data(NAMESPACE, (data = new QorChooser(this, options)));
      }

      if (typeof options === 'string' && $.isFunction(fn = data[options])) {
        fn.apply(data);
      }
    });
  };

  $(function () {
    var selector = 'select[data-toggle="qor.chooser"]';

    $(document).
      on(EVENT_DISABLE, function (e) {
        QorChooser.plugin.call($(selector, e.target), 'destroy');
      }).
      on(EVENT_ENABLE, function (e) {
        QorChooser.plugin.call($(selector, e.target));
      }).
      triggerHandler(EVENT_ENABLE);
  });

  return QorChooser;

});
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Card from "./GroupPageCard";
import Map from "@agir/carte/common/Map";
import FeatherIcon from "@agir/front/genericComponents/FeatherIcon";

const StyledMap = styled.div`
  height: 308px;

  @media (max-width: ${style.collapse}px) {
    height: 155px;
  }
`;
const StyledAddress = styled.div`
  margin-top: 1rem;
  margin-bottom: 0;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;

  &:first-child {
    margin-top: 0;
  }

  p {
    margin-left: 0.5rem;
    margin-bottom: 0;
    display: flex;
    flex-flow: column nowrap;
    font-size: 0.875rem;
    color: ${style.black500};
    line-height: 1.5;
    font-weight: 400;

    span {
      &:first-child {
        font-weight: 500;
        color: ${style.black1000};
      }
    }

    &:last-child {
      margin-left: auto;
    }

    a {
      font-weight: 500;
      text-decoration: none;
      color: ${style.primary500};
    }
  }
`;

const GroupLocation = (props) => {
  const { location, iconConfiguration, routes } = props;

  if (!location || Object.values(location).filter(Boolean).length === 0) {
    return null;
  }

  const {
    name,
    address1,
    address2,
    city,
    zip,
    state,
    country,
    coordinates,
  } = location;

  return (
    <Card title="Accès" editUrl={routes && routes.edit} outlined>
      {coordinates && Array.isArray(coordinates.coordinates) ? (

      ) : null}

    </Card>
  );
};

GroupLocation.propTypes = {
  iconConfiguration: PropTypes.object,
  location: PropTypes.shape({
    name: PropTypes.string,
    address1: PropTypes.string,
    address2: PropTypes.string,
    city: PropTypes.string,
    zip: PropTypes.string,
    state: PropTypes.string,
    country: PropTypes.string,
    coordinates: PropTypes.shape({
      coordinates: PropTypes.arrayOf(PropTypes.number),
    }),
  }).isRequired,
  routes: PropTypes.object,
};
export default GroupLocation;
<commit_msg>fix: empty GroupLocation card<commit_after>import PropTypes from "prop-types";
import React from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Card from "./GroupPageCard";
import Map from "@agir/carte/common/Map";
import FeatherIcon from "@agir/front/genericComponents/FeatherIcon";

const StyledMap = styled.div`
  height: 308px;

  @media (max-width: ${style.collapse}px) {
    height: 155px;
  }
`;
const StyledAddress = styled.div`
  margin-top: 1rem;
  margin-bottom: 0;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;

  &:first-child {
    margin-top: 0;
  }

  p {
    margin-left: 0.5rem;
    margin-bottom: 0;
    display: flex;
    flex-flow: column nowrap;
    font-size: 0.875rem;
    color: ${style.black500};
    line-height: 1.5;
    font-weight: 400;

    span {
      &:first-child {
        font-weight: 500;
        color: ${style.black1000};
      }
    }

    &:last-child {
      margin-left: auto;
    }

    a {
      font-weight: 500;
      text-decoration: none;
      color: ${style.primary500};
    }
  }
`;

const GroupLocation = (props) => {
  const { location, iconConfiguration, routes } = props;

  if (!location || Object.values(location).filter(Boolean).length === 0) {
    return null;
  }

  const {
    name,
    address1,
    address2,
    city,
    zip,
    state,
    country,
    coordinates,
  } = location;

  if (
    !name &&
    !address1 &&
    !address2 &&
    !city &&
    !zip &&
    !state &&
    !country &&
    !coordinates
  ) {
    return null;
  }

  return (
    <Card title="Accès" editUrl={routes && routes.edit} outlined>
      {coordinates && Array.isArray(coordinates.coordinates) ? (

      ) : null}

    </Card>
  );
};

GroupLocation.propTypes = {
  iconConfiguration: PropTypes.object,
  location: PropTypes.shape({
    name: PropTypes.string,
    address1: PropTypes.string,
    address2: PropTypes.string,
    city: PropTypes.string,
    zip: PropTypes.string,
    state: PropTypes.string,
    country: PropTypes.string,
    coordinates: PropTypes.shape({
      coordinates: PropTypes.arrayOf(PropTypes.number),
    }),
  }).isRequired,
  routes: PropTypes.object,
};
export default GroupLocation;
<|endoftext|>


<commit_before>// Eclass-Assignment-Filter

// (function () {
  // var btn = document.createElement("BUTTON");
  // var t = document.createTextNode("미제출 보기");
  // btn.appendChild(t);
  // btn.onclick = function(){
	  // var term = "미제출";
	  // var tables = document.getElementsByClassName('list-table');
	  // var table = table[0];
	  // var tr = table.getElementsByTagName('TR');
	  // for(var i = 0; i < tr.length; i++){
		  // var td = tr[i].getElementsByTagName('TD');
		  // for(var j = 0; j < td.length; j++){
			  // if(td[j].innerHTML == term){
				  // td[j].innerHTML = "찾았다.";
			  // }
		  // }
	  // }
	  // };
  // document.body.appendChild(btn);
// })();

(function () {
  var term = "미제출";
  var tables = document.getElementsByClassName('list-table');
  var table = table[0];
  var tr = table.getElementsByTagName('TR');
  for(var i = 0; i < tr.length; i++){
	  var td = tr[i].getElementsByTagName('TD');
	  for(var j = 0; j < td.length; j++){
		  if(td[j].innerHTML == term){
			  td[j].innerHTML = "찾았다.";
		  }
	  }
  }
})();<commit_msg>test05<commit_after>// Eclass-Assignment-Filter

// (function () {
  // var btn = document.createElement("BUTTON");
  // var t = document.createTextNode("미제출 보기");
  // btn.appendChild(t);
  // btn.onclick = function(){
	  // var term = "미제출";
	  // var tables = document.getElementsByClassName('list-table');
	  // var table = table[0];
	  // var tr = table.getElementsByTagName('TR');
	  // for(var i = 0; i < tr.length; i++){
		  // var td = tr[i].getElementsByTagName('TD');
		  // for(var j = 0; j < td.length; j++){
			  // if(td[j].innerHTML == term){
				  // td[j].innerHTML = "찾았다.";
			  // }
		  // }
	  // }
	  // };
  // document.body.appendChild(btn);
// })();

(function () {
  var term = "미제출";
  var tables = document.getElementsByClassName('list-table');
  var table = tables[0];
  var tr = table.getElementsByTagName('TR');
  for(var i = 0; i < tr.length; i++){
	  var td = tr[i].getElementsByTagName('TD');
	  for(var j = 0; j < td.length; j++){
		  if(td[j].innerHTML == term){
			  td[j].innerHTML = "찾았다.";
		  }
	  }
  }
})();<|endoftext|>


<commit_before>'use strict';

var td              = require('testdouble');
var cordovaAssets   = require('../../../lib/utils/cordova-assets');
var expect          = require('../../helpers/expect');
var fsUtils         = require('../../../lib/utils/fs-utils');
var logger          = require('../../../lib/utils/logger');
var contains        = td.matchers.contains;

describe('Get Platform Assets Util', function() {
  describe('getPaths', function() {
    it('is valid for ios', function() {
      var assets = cordovaAssets.getPaths('ios', 'fakeProjectPath');
      var expectedPath = 'platforms/ios/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('is valid for android', function() {
      var assets = cordovaAssets.getPaths('android', 'fakeProjectPath');
      var expectedPath = 'platforms/android/assets/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('is valid for browser', function() {
      var assets = cordovaAssets.getPaths('browser', 'fakeProjectPath');
      var expectedPath = 'platforms/browser/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('adds cordova_plugins.js to files', function() {
      var assets = cordovaAssets.getPaths('ios', 'fakeProjectPath');
      expect(assets.files).to.deep.equal(['cordova_plugins.js', 'cordova.js']);
    });
  });

  describe('validatePaths', function() {
    it('throws an error if assetsPath is undefined', function() {
      expect(function() {
        cordovaAssets.validatePaths();
      }).to.throw(
        'ember-cordova: Platform asset path undefined, cant build'
      );
    });

    it('throws an error if cordova.js does not exist', function() {
      td.replace(fsUtils, 'existsSync', function(path) {
        return path !== 'path/cordova.js'
      });

      var warnDouble = td.replace(logger, 'warn');
      cordovaAssets.validatePaths('fakeAssetPath', 'fakeProjectPath');

      td.verify(warnDouble(contains('Did not find')));
      td.verify(warnDouble(contains('cordova.js')));
    });

    it('throws an error if cordova_plugins.js does not exist', function() {
      td.replace(fsUtils, 'existsSync', function(path) {
        return path !== 'path/cordova_plugins.js'
      });

      var warnDouble = td.replace(logger, 'warn');
      cordovaAssets.validatePaths('fakeAssetPath', 'fakeProjectPath');

      td.verify(warnDouble(contains('Did not find')));
      td.verify(warnDouble(contains('cordova_plugins.js')));
    });
  });
});
<commit_msg>fix(test): cordovaAssets.getPaths should return config.xml<commit_after>'use strict';

var td              = require('testdouble');
var cordovaAssets   = require('../../../lib/utils/cordova-assets');
var expect          = require('../../helpers/expect');
var fsUtils         = require('../../../lib/utils/fs-utils');
var logger          = require('../../../lib/utils/logger');
var contains        = td.matchers.contains;

describe('Get Platform Assets Util', function() {
  describe('getPaths', function() {
    it('is valid for ios', function() {
      var assets = cordovaAssets.getPaths('ios', 'fakeProjectPath');
      var expectedPath = 'platforms/ios/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('is valid for android', function() {
      var assets = cordovaAssets.getPaths('android', 'fakeProjectPath');
      var expectedPath = 'platforms/android/assets/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('is valid for browser', function() {
      var assets = cordovaAssets.getPaths('browser', 'fakeProjectPath');
      var expectedPath = 'platforms/browser/www';
      expect(assets.assetsPath).to.equal(expectedPath);
    });

    it('adds cordova_plugins.js to files', function() {
      var assets = cordovaAssets.getPaths('ios', 'fakeProjectPath');
      expect(assets.files).to.deep.equal(
        ['cordova_plugins.js', 'cordova.js', 'config.xml']
      );
    });
  });

  describe('validatePaths', function() {
    it('throws an error if assetsPath is undefined', function() {
      expect(function() {
        cordovaAssets.validatePaths();
      }).to.throw(
        'ember-cordova: Platform asset path undefined, cant build'
      );
    });

    it('throws an error if cordova.js does not exist', function() {
      td.replace(fsUtils, 'existsSync', function(path) {
        return path !== 'path/cordova.js'
      });

      var warnDouble = td.replace(logger, 'warn');
      cordovaAssets.validatePaths('fakeAssetPath', 'fakeProjectPath');

      td.verify(warnDouble(contains('Did not find')));
      td.verify(warnDouble(contains('cordova.js')));
    });

    it('throws an error if cordova_plugins.js does not exist', function() {
      td.replace(fsUtils, 'existsSync', function(path) {
        return path !== 'path/cordova_plugins.js'
      });

      var warnDouble = td.replace(logger, 'warn');
      cordovaAssets.validatePaths('fakeAssetPath', 'fakeProjectPath');

      td.verify(warnDouble(contains('Did not find')));
      td.verify(warnDouble(contains('cordova_plugins.js')));
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = Em.Route.extend({
  route: '/highAvailability/enable',

  enter: function (router) {
    Em.run.next(function () {
      var highAvailabilityWizardController = router.get('highAvailabilityWizardController');
      App.router.get('updateController').set('isWorking', false);
      var popup = App.ModalPopup.show({
        classNames: ['full-width-modal'],
        header: Em.I18n.t('admin.highAvailability.wizard.header'),
        bodyClass: App.HighAvailabilityWizardView.extend({
          controller: highAvailabilityWizardController
        }),
        primary: Em.I18n.t('form.cancel'),
        showFooter: false,
        secondary: null,
        hideCloseButton: function () {
          var currStep = App.router.get('highAvailabilityWizardController.currentStep');
          switch (currStep) {
            case "5" :
            case "7" :
            case "9" :
              if(App.supports.autoRollbackHA){
                this.set('showCloseButton', false);
              }else{
                this.set('showCloseButton', true);
              }
              break;
            default :
              this.set('showCloseButton', true);
          }
        }.observes('App.router.highAvailabilityWizardController.currentStep'),

        onClose: function () {
          var currStep = App.router.get('highAvailabilityWizardController.currentStep');
          var highAvailabilityProgressPageController = App.router.get('highAvailabilityProgressPageController');
          if (currStep == "6" && App.supports.autoRollbackHA){
            highAvailabilityProgressPageController.tasks.push({
              command: "startZooKeeperServers",
              status: "FAILED"
            })
            highAvailabilityProgressPageController.rollback();
          }else if(currStep == "8" && App.supports.autoRollbackHA){
            highAvailabilityProgressPageController.tasks.push({
              command: "startSecondNameNode",
              status: "FAILED"
            })
            highAvailabilityProgressPageController.rollback();
          }else{
            if(parseInt(currStep) > 4 && !App.supports.autoRollbackHA){
              highAvailabilityProgressPageController.manualRollback();
            }else {
              this.hide();
              App.router.get('highAvailabilityWizardController').setCurrentStep('1');
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.admin.adminHighAvailability');
            }
          }
        },
        didInsertElement: function () {
          this.fitHeight();
        }
      });
      highAvailabilityWizardController.set('popup', popup);
      App.clusterStatus.updateFromServer();
      var currentClusterStatus = App.clusterStatus.get('value');
      if (currentClusterStatus) {
        switch (currentClusterStatus.clusterState) {
          case 'HIGH_AVAILABILITY_DEPLOY' :
            App.db.data = currentClusterStatus.localdb;
            highAvailabilityWizardController.setCurrentStep(currentClusterStatus.localdb.HighAvailabilityWizard.currentStep);
            break;
          default:
            var currStep = App.router.get('highAvailabilityWizardController.currentStep');
            highAvailabilityWizardController.setCurrentStep(currStep);
            break;
        }
      }
      router.transitionTo('step' + highAvailabilityWizardController.get('currentStep'));
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep1', controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.saveNameServiceId(router.get('highAvailabilityWizardStep1Controller.content.nameServiceId'));
      router.transitionTo('step2');
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep2', controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      var highAvailabilityWizardStep2Controller = router.get('highAvailabilityWizardStep2Controller');
      controller.saveMasterComponentHosts(highAvailabilityWizardStep2Controller);
      router.transitionTo('step3');
    },
    back: function (router) {
      router.transitionTo('step1');
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep3',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      router.transitionTo('step4');
    },
    back: function (router) {
      router.transitionTo('step2');
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep4',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step5');
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('5');
      controller.setLowerStepsDisable(5);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep5',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step6');
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep6',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      router.transitionTo('step7');
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep7',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step8');
    }
  }),

  step8: Em.Route.extend({
    route: '/step8',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('8');
      controller.setLowerStepsDisable(8);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep8',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      App.showConfirmationPopup(function() {
        router.transitionTo('step9');
      }, Em.I18n.t('admin.highAvailability.wizard.step8.confirmPopup.body'));
    }
  }),

  step9: Em.Route.extend({
    route: '/step9',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('9');
      controller.setLowerStepsDisable(9);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep9',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      controller.finish();
      controller.clearStorageData();
      controller.get('popup').hide();
      App.clusterStatus.setClusterStatus({
        clusterName: controller.get('content.cluster.name'),
        clusterState: 'HIGH_AVAILABILITY_COMPLETED',
        wizardControllerName: 'highAvailabilityWizardController',
        localdb: App.db.data
      });
      router.transitionTo('main.index');
      location.reload();
    }
  }),

  gotoStep1: Em.Router.transitionTo('step1'),

  gotoStep2: Em.Router.transitionTo('step2'),

  gotoStep3: Em.Router.transitionTo('step3'),

  gotoStep4: Em.Router.transitionTo('step4'),

  gotoStep5: Em.Router.transitionTo('step5'),

  gotoStep6: Em.Router.transitionTo('step6'),

  gotoStep7: Em.Router.transitionTo('step7'),

  gotoStep8: Em.Router.transitionTo('step8'),

  gotoStep9: Em.Router.transitionTo('step9')
});
<commit_msg>AMBARI-3444. Refreshing page on steps "Initialize JournalNodes"/"Initialize Metadata" of HA wizard returns to previous step with all steps completed. (alexantonenko)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = Em.Route.extend({
  route: '/highAvailability/enable',

  enter: function (router) {
    Em.run.next(function () {
      var highAvailabilityWizardController = router.get('highAvailabilityWizardController');
      App.router.get('updateController').set('isWorking', false);
      var popup = App.ModalPopup.show({
        classNames: ['full-width-modal'],
        header: Em.I18n.t('admin.highAvailability.wizard.header'),
        bodyClass: App.HighAvailabilityWizardView.extend({
          controller: highAvailabilityWizardController
        }),
        primary: Em.I18n.t('form.cancel'),
        showFooter: false,
        secondary: null,
        hideCloseButton: function () {
          var currStep = App.router.get('highAvailabilityWizardController.currentStep');
          switch (currStep) {
            case "5" :
            case "7" :
            case "9" :
              if(App.supports.autoRollbackHA){
                this.set('showCloseButton', false);
              }else{
                this.set('showCloseButton', true);
              }
              break;
            default :
              this.set('showCloseButton', true);
          }
        }.observes('App.router.highAvailabilityWizardController.currentStep'),

        onClose: function () {
          var currStep = App.router.get('highAvailabilityWizardController.currentStep');
          var highAvailabilityProgressPageController = App.router.get('highAvailabilityProgressPageController');
          if (currStep == "6" && App.supports.autoRollbackHA){
            highAvailabilityProgressPageController.tasks.push({
              command: "startZooKeeperServers",
              status: "FAILED"
            })
            highAvailabilityProgressPageController.rollback();
          }else if(currStep == "8" && App.supports.autoRollbackHA){
            highAvailabilityProgressPageController.tasks.push({
              command: "startSecondNameNode",
              status: "FAILED"
            })
            highAvailabilityProgressPageController.rollback();
          }else{
            if(parseInt(currStep) > 4 && !App.supports.autoRollbackHA){
              highAvailabilityProgressPageController.manualRollback();
            }else {
              this.hide();
              App.router.get('highAvailabilityWizardController').setCurrentStep('1');
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.admin.adminHighAvailability');
            }
          }
        },
        didInsertElement: function () {
          this.fitHeight();
        }
      });
      highAvailabilityWizardController.set('popup', popup);
      App.clusterStatus.updateFromServer();
      var currentClusterStatus = App.clusterStatus.get('value');
      if (currentClusterStatus) {
        switch (currentClusterStatus.clusterState) {
          case 'HIGH_AVAILABILITY_DEPLOY' :
            App.db.data = currentClusterStatus.localdb;
            highAvailabilityWizardController.setCurrentStep(currentClusterStatus.localdb.HighAvailabilityWizard.currentStep);
            break;
          default:
            var currStep = App.router.get('highAvailabilityWizardController.currentStep');
            highAvailabilityWizardController.setCurrentStep(currStep);
            break;
        }
      }
      router.transitionTo('step' + highAvailabilityWizardController.get('currentStep'));
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep1', controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.saveNameServiceId(router.get('highAvailabilityWizardStep1Controller.content.nameServiceId'));
      router.transitionTo('step2');
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep2', controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      var highAvailabilityWizardStep2Controller = router.get('highAvailabilityWizardStep2Controller');
      controller.saveMasterComponentHosts(highAvailabilityWizardStep2Controller);
      router.transitionTo('step3');
    },
    back: function (router) {
      router.transitionTo('step1');
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep3',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      router.transitionTo('step4');
    },
    back: function (router) {
      router.transitionTo('step2');
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep4',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step5');
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('5');
      controller.setLowerStepsDisable(5);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep5',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step6');
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      App.clusterStatus.setClusterStatus({
        clusterName: this.get('content.cluster.name'),
        clusterState: 'HIGH_AVAILABILITY_DEPLOY',
        wizardControllerName: this.get('content.controllerName'),
        localdb: App.db.data
      });
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep6',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      router.transitionTo('step7');
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep7',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      router.transitionTo('step8');
    }
  }),

  step8: Em.Route.extend({
    route: '/step8',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('8');
      controller.setLowerStepsDisable(8);
      App.clusterStatus.setClusterStatus({
        clusterName: this.get('content.cluster.name'),
        clusterState: 'HIGH_AVAILABILITY_DEPLOY',
        wizardControllerName: this.get('content.controllerName'),
        localdb: App.db.data
      });
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep8',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      App.showConfirmationPopup(function() {
        router.transitionTo('step9');
      }, Em.I18n.t('admin.highAvailability.wizard.step8.confirmPopup.body'));
    }
  }),

  step9: Em.Route.extend({
    route: '/step9',
    connectOutlets: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.setCurrentStep('9');
      controller.setLowerStepsDisable(9);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('highAvailabilityWizardStep9',  controller.get('content'));
      })
    },
    unroutePath: function () {
      return false;
    },
    next: function (router) {
      var controller = router.get('highAvailabilityWizardController');
      controller.clearTasksData();
      controller.finish();
      controller.clearStorageData();
      controller.get('popup').hide();
      App.clusterStatus.setClusterStatus({
        clusterName: controller.get('content.cluster.name'),
        clusterState: 'HIGH_AVAILABILITY_COMPLETED',
        wizardControllerName: 'highAvailabilityWizardController',
        localdb: App.db.data
      });
      router.transitionTo('main.index');
      location.reload();
    }
  }),

  gotoStep1: Em.Router.transitionTo('step1'),

  gotoStep2: Em.Router.transitionTo('step2'),

  gotoStep3: Em.Router.transitionTo('step3'),

  gotoStep4: Em.Router.transitionTo('step4'),

  gotoStep5: Em.Router.transitionTo('step5'),

  gotoStep6: Em.Router.transitionTo('step6'),

  gotoStep7: Em.Router.transitionTo('step7'),

  gotoStep8: Em.Router.transitionTo('step8'),

  gotoStep9: Em.Router.transitionTo('step9')
});
<|endoftext|>


<commit_before>// confu by stagas

var fs = require('fs')
  , path = require('path')
  , Hash = require('hashish')

module.exports = function() {
  var args = [].slice.call(arguments)

  // normalize config path
  configPath = path.join.apply(this, args)

  // extract root
  var rootPath = path.dirname(configPath)

  // parse config
  config = JSON.parse(fs.readFileSync(configPath, 'utf8'))

  if (config.paths) {
    // get paths relative to root
    config.paths = Hash.map(config.paths, function(pathName) {
      return pathName[0] !== '/' ? path.join(rootPath, pathName) : pathName
    })
  } else config.paths = {}

  // convenience
  config.paths.root = rootPath
  config.paths.config = configPath

  return config
}<commit_msg>Actually resolves now<commit_after>// confu by stagas

var fs = require('fs')
  , path = require('path')
  , Hash = require('hashish')

module.exports = function() {
  var args = [].slice.call(arguments)

  // normalize config path
  configPath = path.resolve(path.join.apply(this, args))

  // extract root
  var rootPath = path.dirname(configPath)

  // parse config
  config = JSON.parse(fs.readFileSync(configPath, 'utf8'))

  if (config.paths) {
    // get paths relative to root
    config.paths = Hash.map(config.paths, function(pathName) {
      return pathName[0] !== '/' ? path.join(rootPath, pathName) : pathName
    })
  } else config.paths = {}

  // convenience
  config.paths.root = rootPath
  config.paths.config = configPath

  return config
}<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var React = require('react');
var mui = require('material-ui');
var classNames = require('classnames');
var Combokeys = require('combokeys');
var ThemeManager = new mui.Styles.ThemeManager();

var {Paper, Styles: { Colors: { blue500, red500, lightGreen500 }}} = mui;
var IconButton = require('./IconButton');
var { getButtons, getButtonGroups } = require('../buttons');
var DrawingSurface = require('./DrawingSurface');
var { setHotkey } = require('../actions');

require('../styles/Editor.less');

function setTheme() {
  let palette = ThemeManager.getCurrentTheme().palette;
  palette.primary1Color = blue500;
  palette.primary2Color = red500;
  palette.primary3Color = lightGreen500;
  ThemeManager.setPalette(palette);
}

function setDefaultHotkeys(dispatch, combokeys, ripples) {
  _.forEach(getButtons(), ({hotkey}, name) => {
    dispatch(setHotkey(combokeys, ripples, name, hotkey));
  });
}

const STYLES = {
  floatCircle: { padding: '0px', width: 42, height: 42 },
  smallIcon: { padding: '6px', width: 36, height: 36, margin: '3px' }
};

const DEFAULT_ICON_STYLE = { padding: '9px', width: 42, height: 42, margin: '3px' };

var Editor = React.createClass({

  childContextTypes: {
    muiTheme: React.PropTypes.object
  },

  getChildContext() {
    return {
      muiTheme: ThemeManager.getCurrentTheme()
    };
  },

  componentWillMount() {
    setTheme();
    this.ripples = Object.create(null);
  },

  setRipple(name, start, end) {
    let ripple = this.ripples[name];
    if (!ripple) {
      ripple = [];
    }
    ripple.push({start, end})

    this.ripples[name] = ripple;
  },

  componentDidMount() {
    this.interval = setInterval(this.onResize, 100);

    // add ripples to indicate hotkey has occured in hidden toolbars
    let buttons = getButtons();
    let bs = getButtonGroups(buttons);
    let float = _.flatten(_.values(bs.float));
    _.forEach(buttons, b => {
      if (!_.contains(float, b)) {
        this.ripples[b.name].push(this.ripples.showToolbars[0]);
      }
    });

    this.combokeys = new Combokeys(document);
    setDefaultHotkeys(this.props.dispatch, this.combokeys, this.ripples);
  },

  // shouldComponentUpdate(nextProps, nextState) {
  //   return false;
  // },

  componentWillUnmount() {
    this.combokeys.detach();
  },

  getTimeline() {
    return {
      render: (key) => <Timeline key={key} />
    };
  },

  getButtonGroups() {
    let b = getButtons(this.props.dispatch);

    b.toggleTimeControl.transform = `rotate(${this.props.timeControlVisible ? 0 : 180}deg)`;

    let bs = getButtonGroups(b);

    let addStyle = style => button => {
      button = _.clone(button);
      button.style = style;
      return button;
    };

    bs.float.left = bs.float.left.map(addStyle(STYLES.floatCircle));
    bs.float.right = bs.float.right.map(addStyle(STYLES.floatCircle));
    bs.float.middle = bs.float.middle.map(addStyle(STYLES.smallIcon));

    _.values(bs.bottom).concat(_.values(bs.timeControl)).forEach(buttonGroup => {
      buttonGroup.forEach(button => {
        button.tooltipPosition = 'top-center';
      });
    });

    bs.timeControl.middle = [this.getTimeline()];

    return bs;
  },

  isGroupDisabled(toolbar) {
    switch (toolbar) {
      case 'float':
        return this.props.toolbarsVisible;
      case 'top':
      case 'bottom':
        return !this.props.toolbarsVisible;
      case 'timeControl':
        return !this.props.toolbarsVisible || !this.props.timeControlVisible;
    }
  },

  renderButtons() {
    let bs = this.getButtonGroups();
    return _.mapValues(bs, (buttonGroups, toolbar) =>
      _.mapValues(buttonGroups, (buttonGroup, position) =>
        _.map(buttonGroup, ({ name, tooltip, icon, boundAction, style, render, ...props }, i) =>
          (render) ? render(toolbar + position + i) :
          <IconButton {...props}
            key={toolbar + position + i}
            onTouchTap={boundAction}
            style={style || DEFAULT_ICON_STYLE}
            disabled={this.isGroupDisabled(toolbar) || !boundAction}
            tooltip={this.props.selected.help ? tooltip : null}
            selected={this.props.selected[name]}
            setRipple={(start, end) => this.setRipple(name, start, end)}
          >
            { icon }
          </IconButton>
        )
      )
    );
  },

  render() {
    let {
      float,
      top,
      bottom,
      timeControl
    } = this.renderButtons();

    let {
      toolbarsVisible,
      timeControlVisible
    } = this.props;

    return (

        <DrawingSurface dispatch={this.props.dispatch} />
        <FloatBar closed={toolbarsVisible}>
          { float }
        </FloatBar>
        <TopBar closed={!toolbarsVisible}>
          { top }
        </TopBar>
        <BottomBar
          buttonGroups={bottom}
          closed={!toolbarsVisible}
          timeControlGroup={timeControl}
          timeControlClosed={!timeControlVisible}
        >
          { bottom }
          { timeControl }
        </BottomBar>

    );
  }
});

var Timeline = React.createClass({
  render() {
    return (

        <input type='range' min={0} max={100} defaultValue={0} style={{width: '100%'}} />

    );
  }
})

var ButtonGroups = React.createClass({
  render() {
    return (
      <Toolbar className={this.props.className}>
        {['left', 'middle', 'right'].map( position =>

            { this.props.children[position] }

        )}
      </Toolbar>
    );
  }
})

var FloatBar = React.createClass({

  render() {
    let closed = this.props.closed;
    return (

        {this.props.children.left.map( (child, i) =>
          <FloatPaper key={i} className={classNames({closed: closed})} circle={true}>
            { child }
          </FloatPaper>
        )}
        <FloatPaper className={classNames('float-paper-bar', {closed: closed})}>
          <Toolbar className='float-toolbar'>
            { this.props.children.middle }
          </Toolbar>
        </FloatPaper>
        {this.props.children.right.map( (child, i) =>
          <FloatPaper key={-i-1} className={classNames({closed: closed})} circle={true}>
            { child }
          </FloatPaper>
        )}

    );
  }
})

var TopBar = React.createClass({

  render() {
    let closed = this.props.closed;
    return (
      <PaperBar className={classNames('top', {closed: closed})}>
        <ButtonGroups className='top'>
          { this.props.children }
        </ButtonGroups>
      </PaperBar>
    );
  }
})

var BottomBar = React.createClass({

  render() {
    let closed = this.props.closed;
    let timeControlClosed = this.props.timeControlClosed;

    let bottomPaperBarClass = !timeControlClosed ? 'bottom-extended' : 'bottom';

    return (
      <PaperBar className={classNames(bottomPaperBarClass, {closed: closed})}>
        <ButtonGroups>
          { this.props.children[0] }
        </ButtonGroups>

            { _.flatten(_.values(this.props.children[1])) }

      </PaperBar>
    );
  }
})

function blockEvent(e) {
  e.preventDefault();
}

var Toolbar = React.createClass({
  render() {
    return (

        {this.props.children}

    );
  }
});

var PaperBar = React.createClass({
  render() {
    return (
      <Paper
        className={'paper-bar ' + (this.props.className || '')}
        rounded={false}
        transitionEnabled={false}
        onTouchStart={blockEvent}
        onMouseDown={blockEvent}
      >
        {this.props.children}
      </Paper>
    );
  }
});

var FloatPaper = React.createClass({
  render() {
    return (
      <Paper
        className={classNames('float-paper', this.props.className)}
        circle={this.props.circle}
        style={{boxShadow: 'null'}}
        transitionEnabled={false}
        onTouchStart={blockEvent}
        onMouseDown={blockEvent}
      >
        {this.props.children}
      </Paper>
    );
  }
});

module.exports = Editor;

<commit_msg>add Editor.shouldComponentUpdate<commit_after>'use strict';

var _ = require('lodash');
var React = require('react');
var mui = require('material-ui');
var classNames = require('classnames');
var Combokeys = require('combokeys');
var ThemeManager = new mui.Styles.ThemeManager();

var {Paper, Styles: { Colors: { blue500, red500, lightGreen500 }}} = mui;
var IconButton = require('./IconButton');
var { getButtons, getButtonGroups } = require('../buttons');
var DrawingSurface = require('./DrawingSurface');
var { setHotkey } = require('../actions');

require('../styles/Editor.less');

function setTheme() {
  let palette = ThemeManager.getCurrentTheme().palette;
  palette.primary1Color = blue500;
  palette.primary2Color = red500;
  palette.primary3Color = lightGreen500;
  ThemeManager.setPalette(palette);
}

function setDefaultHotkeys(dispatch, combokeys, ripples) {
  _.forEach(getButtons(), ({hotkey}, name) => {
    dispatch(setHotkey(combokeys, ripples, name, hotkey));
  });
}

const STYLES = {
  floatCircle: { padding: '0px', width: 42, height: 42 },
  smallIcon: { padding: '6px', width: 36, height: 36, margin: '3px' }
};

const DEFAULT_ICON_STYLE = { padding: '9px', width: 42, height: 42, margin: '3px' };

var Editor = React.createClass({

  childContextTypes: {
    muiTheme: React.PropTypes.object
  },

  getChildContext() {
    return {
      muiTheme: ThemeManager.getCurrentTheme()
    };
  },

  componentWillMount() {
    setTheme();
    this.ripples = Object.create(null);
  },

  setRipple(name, start, end) {
    let ripple = this.ripples[name];
    if (!ripple) {
      ripple = [];
    }
    ripple.push({start, end})

    this.ripples[name] = ripple;
  },

  componentDidMount() {
    this.interval = setInterval(this.onResize, 100);

    // add ripples to indicate hotkey has occured in hidden toolbars
    let buttons = getButtons();
    let bs = getButtonGroups(buttons);
    let float = _.flatten(_.values(bs.float));
    _.forEach(buttons, b => {
      if (!_.contains(float, b)) {
        this.ripples[b.name].push(this.ripples.showToolbars[0]);
      }
    });

    this.combokeys = new Combokeys(document);
    setDefaultHotkeys(this.props.dispatch, this.combokeys, this.ripples);
  },

  shouldComponentUpdate(nextProps) {
    let {
      toolbarsVisible,
      timeControlVisible,
      selected
    } = this.props;

    let {
      toolbarsVisible: toolbarsVisible_,
      timeControlVisible: timeControlVisible_,
      selected: selected_
    } = nextProps;

    return toolbarsVisible !== toolbarsVisible_
      || timeControlVisible !== timeControlVisible_
      || !_.isEqual(selected, selected_);
  },

  componentWillUnmount() {
    this.combokeys.detach();
  },

  getTimeline() {
    return {
      render: (key) => <Timeline key={key} />
    };
  },

  getButtonGroups() {
    let b = getButtons(this.props.dispatch);

    b.toggleTimeControl.transform = `rotate(${this.props.timeControlVisible ? 0 : 180}deg)`;

    let bs = getButtonGroups(b);

    let addStyle = style => button => {
      button = _.clone(button);
      button.style = style;
      return button;
    };

    bs.float.left = bs.float.left.map(addStyle(STYLES.floatCircle));
    bs.float.right = bs.float.right.map(addStyle(STYLES.floatCircle));
    bs.float.middle = bs.float.middle.map(addStyle(STYLES.smallIcon));

    _.values(bs.bottom).concat(_.values(bs.timeControl)).forEach(buttonGroup => {
      buttonGroup.forEach(button => {
        button.tooltipPosition = 'top-center';
      });
    });

    bs.timeControl.middle = [this.getTimeline()];

    return bs;
  },

  isGroupDisabled(toolbar) {
    switch (toolbar) {
      case 'float':
        return this.props.toolbarsVisible;
      case 'top':
      case 'bottom':
        return !this.props.toolbarsVisible;
      case 'timeControl':
        return !this.props.toolbarsVisible || !this.props.timeControlVisible;
    }
  },

  renderButtons() {
    let bs = this.getButtonGroups();
    return _.mapValues(bs, (buttonGroups, toolbar) =>
      _.mapValues(buttonGroups, (buttonGroup, position) =>
        _.map(buttonGroup, ({ name, tooltip, icon, boundAction, style, render, ...props }, i) =>
          (render) ? render(toolbar + position + i) :
          <IconButton {...props}
            key={toolbar + position + i}
            onTouchTap={boundAction}
            style={style || DEFAULT_ICON_STYLE}
            disabled={this.isGroupDisabled(toolbar) || !boundAction}
            tooltip={this.props.selected.help ? tooltip : null}
            selected={this.props.selected[name]}
            setRipple={(start, end) => this.setRipple(name, start, end)}
          >
            { icon }
          </IconButton>
        )
      )
    );
  },

  render() {
    let {
      float,
      top,
      bottom,
      timeControl
    } = this.renderButtons();

    let {
      toolbarsVisible,
      timeControlVisible
    } = this.props;

    return (

        <DrawingSurface dispatch={this.props.dispatch} />
        <FloatBar closed={toolbarsVisible}>
          { float }
        </FloatBar>
        <TopBar closed={!toolbarsVisible}>
          { top }
        </TopBar>
        <BottomBar
          buttonGroups={bottom}
          closed={!toolbarsVisible}
          timeControlGroup={timeControl}
          timeControlClosed={!timeControlVisible}
        >
          { bottom }
          { timeControl }
        </BottomBar>

    );
  }
});

var Timeline = React.createClass({
  render() {
    return (

        <input type='range' min={0} max={100} defaultValue={0} style={{width: '100%'}} />

    );
  }
})

var ButtonGroups = React.createClass({
  render() {
    return (
      <Toolbar className={this.props.className}>
        {['left', 'middle', 'right'].map( position =>

            { this.props.children[position] }

        )}
      </Toolbar>
    );
  }
})

var FloatBar = React.createClass({

  render() {
    let closed = this.props.closed;
    return (

        {this.props.children.left.map( (child, i) =>
          <FloatPaper key={i} className={classNames({closed: closed})} circle={true}>
            { child }
          </FloatPaper>
        )}
        <FloatPaper className={classNames('float-paper-bar', {closed: closed})}>
          <Toolbar className='float-toolbar'>
            { this.props.children.middle }
          </Toolbar>
        </FloatPaper>
        {this.props.children.right.map( (child, i) =>
          <FloatPaper key={-i-1} className={classNames({closed: closed})} circle={true}>
            { child }
          </FloatPaper>
        )}

    );
  }
})

var TopBar = React.createClass({

  render() {
    let closed = this.props.closed;
    return (
      <PaperBar className={classNames('top', {closed: closed})}>
        <ButtonGroups className='top'>
          { this.props.children }
        </ButtonGroups>
      </PaperBar>
    );
  }
})

var BottomBar = React.createClass({

  render() {
    let closed = this.props.closed;
    let timeControlClosed = this.props.timeControlClosed;

    let bottomPaperBarClass = !timeControlClosed ? 'bottom-extended' : 'bottom';

    return (
      <PaperBar className={classNames(bottomPaperBarClass, {closed: closed})}>
        <ButtonGroups>
          { this.props.children[0] }
        </ButtonGroups>

            { _.flatten(_.values(this.props.children[1])) }

      </PaperBar>
    );
  }
})

function blockEvent(e) {
  e.preventDefault();
}

var Toolbar = React.createClass({
  render() {
    return (

        {this.props.children}

    );
  }
});

var PaperBar = React.createClass({
  render() {
    return (
      <Paper
        className={'paper-bar ' + (this.props.className || '')}
        rounded={false}
        transitionEnabled={false}
        onTouchStart={blockEvent}
        onMouseDown={blockEvent}
      >
        {this.props.children}
      </Paper>
    );
  }
});

var FloatPaper = React.createClass({
  render() {
    return (
      <Paper
        className={classNames('float-paper', this.props.className)}
        circle={this.props.circle}
        style={{boxShadow: 'null'}}
        transitionEnabled={false}
        onTouchStart={blockEvent}
        onMouseDown={blockEvent}
      >
        {this.props.children}
      </Paper>
    );
  }
});

module.exports = Editor;

<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var OpenSimToolbar = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	//container.setPaddingTop('10px');
    // This causes 3 columns of buttons:
	container.dom.style.width = '120px';
	container.setId( 'opensim_toolbar' );

	var buttons = new UI.Panel();
	container.add( buttons );

	var camera = editor.camera;
    // +X
	var viewx = new UI.Button(false, 'icons/frontView_axes.png').onClick(function () {

	    viewfromPlusX();

	});
	viewx.dom.title = 'Front';
	buttons.add(viewx);
	function viewfromPlusX() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    //var helper = new THREE.BoundingBoxHelper(modelObject, 0xff0000);
	    //helper.update();
	    // If you want a visible bounding box
	    //editor.scene.add(helper);
	    // create a sphere at new CameraPos
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.x = bbox.max.x + distance;
	    editor.updateCamera(newpos, center);

    };
    // +Y
	var viewplusy = new UI.Button(false, 'icons/topView_axes.png').onClick(function () {
	    viewfromPlusY();
	});
	viewplusy.dom.title = 'Top';
	buttons.add(viewplusy);
	function viewfromPlusY() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.y = bbox.max.y + distance;
	    editor.updateCamera(newpos, center);

    };
    // +Z
	var viewplusz = new UI.Button(false, 'icons/rightView_axes.png').onClick(function () {
	    viewfromPlusZ();
	});
	viewplusz.dom.title = 'Left';
	buttons.add(viewplusz);
	function viewfromPlusZ() {

	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y)/2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.z = bbox.max.z + distance;
	    editor.updateCamera(newpos, center);

    };
    // -X
	var viewminx = new UI.Button(false, 'icons/backView_axes.png').onClick(function () {
		viewfromMinusX();
	});
	viewminx.dom.title = 'Back';
	buttons.add(viewminx);
	function viewfromMinusX() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.x = bbox.min.x - distance;
	    editor.updateCamera(newpos, center);

    };
    // -Y
	var viewminy = new UI.Button(false, 'icons/bottomView_axes.png').onClick(function () {
	    viewfromMinusY();
	});
	viewminy.dom.title = 'Bottom';
	buttons.add(viewminy);
	function viewfromMinusY() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.y = bbox.min.y - distance;
	    editor.updateCamera(newpos, center);

    };
    // -Z
	var viewminz = new UI.Button(false, 'icons/leftView_axes.png').onClick(function () {
	    viewfromMinusZ();
	});
	viewminz.dom.title = 'Right';
	buttons.add(viewminz);
	function viewfromMinusZ() {

	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y)/2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.z = bbox.min.z - distance;
	    editor.updateCamera(newpos, center);

	};

	var view_zoomout = new UI.Button(false, 'icons/zoom-out.png').onClick(function () {
	    editor.viewZoom(-100);
	});
	view_zoomout.dom.title = 'Zoom-out';
	buttons.add(view_zoomout);
	var view_zoomin = new UI.Button(false, 'icons/zoom-in.png').onClick(function () {
	    editor.viewZoom(+100);
	});
	view_zoomin.dom.title = 'Zoom-in';
	buttons.add(view_zoomin);
	var view_refit = new UI.Button(false, 'icons/refit.png').onClick(function () {
	    //var modelObject = editor.scene.getObjectByName('OpenSimModel');
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    //var newpos = new THREE.Vector3().copy(camera.location);
	    var fov = camera.fov * (Math.PI / 180);
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z);
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    //var helper = new THREE.BoundingBoxHelper(modelObject, 0xff0000);
	    //helper.update();
	    //editor.scene.add(helper);
	    // Zoom out only if model is outside view, also zoom in if too small
	    var curDistance = center.distanceTo(camera.position);
	    editor.viewZoom(curDistance - distance);

	});
	view_refit.dom.title = 'Fit model(s) in visualizer window using current camera orientation';
	buttons.add(view_refit);

	var snapshot = new UI.Button(false, 'icons/camera.gif').onClick(function () {
            saveAsImage();
	});
	snapshot.dom.title = 'Snapshot';
	buttons.add(snapshot);

	function computeModelBbox() {
	    var modelObject = editor.scene.getObjectByName('OpenSimModel');
	    return (new THREE.Box3().setFromObject(modelObject));
	};
	function saveAsImage() {
		editor.signals.hiresRender.dispatch();
	};
	var recordButton = new UI.Button(false, 'icons/video.png');
	var recordStatus = false;
	recordButton.onClick(function () {
		recordStatus = !recordStatus;
		if (recordStatus) // Dark gray if recording
			recordButton.dom.style.backgroundColor = "#888888";
		else // default
			recordButton.dom.style.backgroundColor = "";
		toggleRecord();

	});
	recordButton.dom.title = 'Record Start/Stop';
	buttons.add(recordButton);
	function toggleRecord() {
            editor.toggleRecord();
        }
	return container;

}
<commit_msg>Clarify comment<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var OpenSimToolbar = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	//container.setPaddingTop('10px');
    // This causes 3 columns of buttons:
	container.dom.style.width = '120px';
	container.setId( 'opensim_toolbar' );

	var buttons = new UI.Panel();
	container.add( buttons );

	var camera = editor.camera;
    // +X
	var viewx = new UI.Button(false, 'icons/frontView_axes.png').onClick(function () {

	    viewfromPlusX();

	});
	viewx.dom.title = 'Front';
	buttons.add(viewx);
	function viewfromPlusX() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    //var helper = new THREE.BoundingBoxHelper(modelObject, 0xff0000);
	    //helper.update();
	    // If you want a visible bounding box
	    //editor.scene.add(helper);
	    // create a sphere at new CameraPos
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.x = bbox.max.x + distance;
	    editor.updateCamera(newpos, center);

    };
    // +Y
	var viewplusy = new UI.Button(false, 'icons/topView_axes.png').onClick(function () {
	    viewfromPlusY();
	});
	viewplusy.dom.title = 'Top';
	buttons.add(viewplusy);
	function viewfromPlusY() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.y = bbox.max.y + distance;
	    editor.updateCamera(newpos, center);

    };
    // +Z
	var viewplusz = new UI.Button(false, 'icons/rightView_axes.png').onClick(function () {
	    viewfromPlusZ();
	});
	viewplusz.dom.title = 'Left';
	buttons.add(viewplusz);
	function viewfromPlusZ() {

	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y)/2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.z = bbox.max.z + distance;
	    editor.updateCamera(newpos, center);

    };
    // -X
	var viewminx = new UI.Button(false, 'icons/backView_axes.png').onClick(function () {
		viewfromMinusX();
	});
	viewminx.dom.title = 'Back';
	buttons.add(viewminx);
	function viewfromMinusX() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.x = bbox.min.x - distance;
	    editor.updateCamera(newpos, center);

    };
    // -Y
	var viewminy = new UI.Button(false, 'icons/bottomView_axes.png').onClick(function () {
	    viewfromMinusY();
	});
	viewminy.dom.title = 'Bottom';
	buttons.add(viewminy);
	function viewfromMinusY() {
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.z - bbox.min.z) / 2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.y = bbox.min.y - distance;
	    editor.updateCamera(newpos, center);

    };
    // -Z
	var viewminz = new UI.Button(false, 'icons/leftView_axes.png').onClick(function () {
	    viewfromMinusZ();
	});
	viewminz.dom.title = 'Right';
	buttons.add(viewminz);
	function viewfromMinusZ() {

	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    var newpos = new THREE.Vector3().copy(center);
	    var fov = editor.camera.fov * (Math.PI / 180);
	    // Calculate the camera distance
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y)/2;
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    newpos.z = bbox.min.z - distance;
	    editor.updateCamera(newpos, center);

	};

	var view_zoomout = new UI.Button(false, 'icons/zoom-out.png').onClick(function () {
	    editor.viewZoom(-100);
	});
	view_zoomout.dom.title = 'Zoom-out';
	buttons.add(view_zoomout);
	var view_zoomin = new UI.Button(false, 'icons/zoom-in.png').onClick(function () {
	    editor.viewZoom(+100);
	});
	view_zoomin.dom.title = 'Zoom-in';
	buttons.add(view_zoomin);
	var view_refit = new UI.Button(false, 'icons/refit.png').onClick(function () {
	    //var modelObject = editor.scene.getObjectByName('OpenSimModel');
	    var bbox = computeModelBbox();
	    var center = new THREE.Vector3();
	    bbox.center(center);
	    //var newpos = new THREE.Vector3().copy(camera.location);
	    var fov = camera.fov * (Math.PI / 180);
	    var objectSize = Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z);
	    var distance = Math.abs(objectSize / Math.sin(fov / 2));
	    //var helper = new THREE.BoundingBoxHelper(modelObject, 0xff0000);
	    //helper.update();
	    //editor.scene.add(helper);
	    // Zoom out only if model is outside view, also zoom in if too small
	    var curDistance = center.distanceTo(camera.position);
	    editor.viewZoom(curDistance - distance);

	});
	view_refit.dom.title = 'Fit model(s) in visualizer window using current camera orientation';
	buttons.add(view_refit);

	var snapshot = new UI.Button(false, 'icons/camera.gif').onClick(function () {
            saveAsImage();
	});
	snapshot.dom.title = 'Snapshot';
	buttons.add(snapshot);

	function computeModelBbox() {
	    var modelObject = editor.scene.getObjectByName('OpenSimModel');
	    return (new THREE.Box3().setFromObject(modelObject));
	};
	function saveAsImage() {
		editor.signals.hiresRender.dispatch();
	};
	var recordButton = new UI.Button(false, 'icons/video.png');
	var recordStatus = false;
	recordButton.onClick(function () {
		recordStatus = !recordStatus;
		if (recordStatus) // Dark gray if recording, should be done in CSS
			recordButton.dom.style.backgroundColor = "#888888";
		else // default
			recordButton.dom.style.backgroundColor = "";
		toggleRecord();

	});
	recordButton.dom.title = 'Record Start/Stop';
	buttons.add(recordButton);
	function toggleRecord() {
            editor.toggleRecord();
        }
	return container;

}
<|endoftext|>


<commit_before>if( sharing_js_options && sharing_js_options.counts ) {
	WPCOMSharing.done_urls_jpssp = [];

	var JPSSP_Sharing = {
		get_counts: function( url ) {
			var https_url, http_url, urls, id, service, service_urls, service_url;

			id = WPCOM_sharing_counts[ url ];

			if('undefined' != typeof WPCOMSharing.done_urls_jpssp[ id ] ) {
				return;
			}

			https_url = encodeURIComponent( url.replace( /^http:\/\//i, 'https://' ) );
			http_url  = encodeURIComponent( url.replace( /^https:\/\//i, 'http://' ) );

			urls = {
				feedly: [
					feedly_api + '?url=' + encodeURIComponent( url ) + '&callback=JPSSP_Sharing.update_feedly_count'
				],
				hatena: [
					'http://api.b.st-hatena.com/entry.counts?url=' +
						https_url +
						'&url=' +
						http_url +
						'&callback=JPSSP_Sharing.update_hatena_count'
				],
				google: [
					google_api + '?url=' + encodeURIComponent( url ) + '&callback=JPSSP_Sharing.update_google_count'
				]
			};

			for( service in urls ) {
				if( ! jQuery('a[data-shared=sharing-' + service + '-' + id  + ']').length ) {
					continue;
				}

				while( ( service_url = urls[ service ].pop() ) ) {
					jQuery.getScript( service_url );
				}
			}
			WPCOMSharing.done_urls_jpssp[ id ] = true;
		},
		update_feedly_count: function( data ) {
			if( feedly_smart ) {
				jQuery('.sd-social-official .feedly_button .count-number span').text( data.subscribers );
				jQuery('.sd-social-official .feedly_button .count-wrap').show();
			} else {
				if('undefined' != typeof data.subscribers && ( data.subscribers * 1 ) > 0 ) {
					WPCOMSharing.inject_share_count('sharing-feedly-' + WPCOM_sharing_counts[ data.url ], data.subscribers );
				}
			}
		},
		update_hatena_count: function( data ) {
			if('undefined' != typeof data && 'undefined' != typeof Object.keys( data ) && Object.keys( data ).length > 0 ){
				if('undefined' != typeof data[ Object.keys( data )[0] ] ) {
					shareCount += data[ Object.keys( data )[0] ];
				}

				if('undefined' != typeof data[ Object.keys( data )[1] ] ) {
					shareCount += data[ Object.keys( data )[1] ];
				}

				if( shareCount > 0 ) {
					WPCOMSharing.inject_share_count('sharing-hatena-' + WPCOM_sharing_counts[ WPCOMSharing.get_permalink( Object.keys( data )[0] ) ], shareCount );
				}
			}
		},
		update_google_count: function( data ) {
			if('undefined' != typeof data.count && ( data.count * 1 ) > 0 ) {
				WPCOMSharing.inject_share_count('sharing-google-' + WPCOM_sharing_counts[ data.url ], data.count );
			}
		}
	};
}

jQuery(document).ready(function($) {
	if('undefined' != typeof WPCOM_sharing_counts ) {
		for( var url in WPCOM_sharing_counts ) {
			JPSSP_Sharing.get_counts( url );
		}
	}
});
<commit_msg>Hatena doesn't provide secure connections to API<commit_after>if( sharing_js_options && sharing_js_options.counts ) {
	WPCOMSharing.done_urls_jpssp = [];

	var JPSSP_Sharing = {
		get_counts: function( url ) {
			var https_url, http_url, urls, id, service, service_urls, service_url;

			id = WPCOM_sharing_counts[ url ];

			if('undefined' != typeof WPCOMSharing.done_urls_jpssp[ id ] ) {
				return;
			}

			https_url = encodeURIComponent( url.replace( /^http:\/\//i, 'https://' ) );
			http_url  = encodeURIComponent( url.replace( /^https:\/\//i, 'http://' ) );

			urls = {
				feedly: [
					feedly_api + '?url=' + encodeURIComponent( url ) + '&callback=JPSSP_Sharing.update_feedly_count'
				],
				hatena: [
					'http://api.b.st-hatena.com/entry.counts?url=' +
						https_url +
						'&url=' +
						http_url +
						'&callback=JPSSP_Sharing.update_hatena_count'
				],
				google: [
					google_api + '?url=' + encodeURIComponent( url ) + '&callback=JPSSP_Sharing.update_google_count'
				]
			};

			if('https:' == window.location.protocol ) {
				delete urls['hatena'];
			}

			for( service in urls ) {
				if( ! jQuery('a[data-shared=sharing-' + service + '-' + id  + ']').length ) {
					continue;
				}

				while( ( service_url = urls[ service ].pop() ) ) {
					jQuery.getScript( service_url );
				}
			}
			WPCOMSharing.done_urls_jpssp[ id ] = true;
		},
		update_feedly_count: function( data ) {
			if( feedly_smart ) {
				jQuery('.sd-social-official .feedly_button .count-number span').text( data.subscribers );
				jQuery('.sd-social-official .feedly_button .count-wrap').show();
			} else {
				if('undefined' != typeof data.subscribers && ( data.subscribers * 1 ) > 0 ) {
					WPCOMSharing.inject_share_count('sharing-feedly-' + WPCOM_sharing_counts[ data.url ], data.subscribers );
				}
			}
		},
		update_hatena_count: function( data ) {
			if('undefined' != typeof data && 'undefined' != typeof Object.keys( data ) && Object.keys( data ).length > 0 ){
				if('undefined' != typeof data[ Object.keys( data )[0] ] ) {
					shareCount += data[ Object.keys( data )[0] ];
				}

				if('undefined' != typeof data[ Object.keys( data )[1] ] ) {
					shareCount += data[ Object.keys( data )[1] ];
				}

				if( shareCount > 0 ) {
					WPCOMSharing.inject_share_count('sharing-hatena-' + WPCOM_sharing_counts[ WPCOMSharing.get_permalink( Object.keys( data )[0] ) ], shareCount );
				}
			}
		},
		update_google_count: function( data ) {
			if('undefined' != typeof data.count && ( data.count * 1 ) > 0 ) {
				WPCOMSharing.inject_share_count('sharing-google-' + WPCOM_sharing_counts[ data.url ], data.count );
			}
		}
	};
}

jQuery(document).ready(function($) {
	if('undefined' != typeof WPCOM_sharing_counts ) {
		for( var url in WPCOM_sharing_counts ) {
			JPSSP_Sharing.get_counts( url );
		}
	}
});
<|endoftext|>