<commit_before>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore.js') || window._,
      _._ || _
    );

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

  /*--------------------------------------------------------------------------*/

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash,
          numbers = [],
          object = {},
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      var ctor = function() { },
          func = function(greeting) { return greeting + ': ' + this.name; };

      var lodashBoundNormal = lodash.bind(func, { 'name': 'moe' }),
          lodashBoundCtor = lodash.bind(ctor, { 'name': 'moe' }),
          lodashBoundPartial = lodash.bind(func, { 'name': 'moe' }, 'hi');

      var _boundNormal = _.bind(func, { 'name': 'moe' }),
          _boundCtor = _.bind(ctor, { 'name': 'moe' }),
          _boundPartial = _.bind(func, { 'name': 'moe' }, 'hi');

      for (var index = 0; index < 20; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(n) {
        return { 'num': n };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      console.log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      console.log(event.target + '');
    },
    'onComplete': function() {
      var fastest = this.filter('fastest').pluck('name'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        console.log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      } else {
        console.log(fastest + ' is the fastest.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        // report results
        if (score.lodash >= score.underscore) {
          console.log('\nLo-Dash is ' + (score.lodash / score.underscore).toFixed(2) + 'x faster than Underscore.');
        } else {
          console.log('\nUnderscore is ' + (score.underscore / score.lodash).toFixed(2) + 'x faster than Lo-Dash.');
        }
      }
    }
  });

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('bind call')
      .add('Lo-Dash', function() {
        lodash.bind(func, { 'name': 'moe' }, 'hi');
      })
      .add('Underscore', function() {
        _.bind(func, { 'name': 'moe' }, 'hi');
      })
  );

  suites.push(
    Benchmark.Suite('bound normal')
      .add('Lo-Dash', function() {
        lodashBoundNormal();
      })
      .add('Underscore', function() {
        _boundNormal();
      })
  );

  suites.push(
    Benchmark.Suite('bound partial')
      .add('Lo-Dash', function() {
        lodashBoundPartial();
      })
      .add('Underscore', function() {
        _boundPartial();
      })
  );

  suites.push(
    Benchmark.Suite('bound constructor')
      .add('Lo-Dash', function() {
        new lodashBoundCtor();
      })
      .add('Underscore', function() {
        new _boundCtor();
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]]);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]]);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]], true);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]], true);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('difference')
      .add('Lo-Dash', function() {
        lodash.difference(numbers, [5, 25, 10, 30]);
      })
      .add('Underscore', function() {
        _.difference(numbers, [5, 25, 10, 30]);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('groupBy callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return Math.floor(num); });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return Math.floor(num); });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(obj) {
          return obj.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(obj) {
          return obj.num;
        });
      })
  );
  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pick')
      .add('Lo-Dash', function() {
        lodash.pick(object, 'key6', 'key13');
      })
      .add('Underscore', function() {
        _.pick(object, 'key6', 'key13');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('union')
      .add('Lo-Dash', function() {
        lodash.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
      })
      .add('Underscore', function() {
        _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

  /*--------------------------------------------------------------------------*/

  if (Benchmark.platform + '') {
    console.log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<commit_msg>Cleanup perf.js.<commit_after>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore.js') || window._,
      _._ || _
    );

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

  /*--------------------------------------------------------------------------*/

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash;

      var numbers = [],
          object = {},
          fourNumbers = [5, 25, 10, 30],
          nestedNumbers = [1, [2], [3, [[4]]]],
          twoNumbers = [12, 21],
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      var ctor = function() { },
          func = function(greeting) { return greeting + ': ' + this.name; };

      var lodashBoundNormal = lodash.bind(func, { 'name': 'moe' }),
          lodashBoundCtor = lodash.bind(ctor, { 'name': 'moe' }),
          lodashBoundPartial = lodash.bind(func, { 'name': 'moe' }, 'hi');

      var _boundNormal = _.bind(func, { 'name': 'moe' }),
          _boundCtor = _.bind(ctor, { 'name': 'moe' }),
          _boundPartial = _.bind(func, { 'name': 'moe' }, 'hi');

      for (var index = 0; index < 20; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(n) {
        return { 'num': n };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      console.log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      console.log(event.target + '');
    },
    'onComplete': function() {
      var fastest = this.filter('fastest').pluck('name'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        console.log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      } else {
        console.log(fastest + ' is the fastest.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        // report results
        if (score.lodash >= score.underscore) {
          console.log('\nLo-Dash is ' + (score.lodash / score.underscore).toFixed(2) + 'x faster than Underscore.');
        } else {
          console.log('\nUnderscore is ' + (score.underscore / score.lodash).toFixed(2) + 'x faster than Lo-Dash.');
        }
      }
    }
  });

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('bind call')
      .add('Lo-Dash', function() {
        lodash.bind(func, { 'name': 'moe' }, 'hi');
      })
      .add('Underscore', function() {
        _.bind(func, { 'name': 'moe' }, 'hi');
      })
  );

  suites.push(
    Benchmark.Suite('bound normal')
      .add('Lo-Dash', function() {
        lodashBoundNormal();
      })
      .add('Underscore', function() {
        _boundNormal();
      })
  );

  suites.push(
    Benchmark.Suite('bound partial')
      .add('Lo-Dash', function() {
        lodashBoundPartial();
      })
      .add('Underscore', function() {
        _boundPartial();
      })
  );

  suites.push(
    Benchmark.Suite('bound constructor')
      .add('Lo-Dash', function() {
        new lodashBoundCtor();
      })
      .add('Underscore', function() {
        new _boundCtor();
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers, true);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers, true);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('difference')
      .add('Lo-Dash', function() {
        lodash.difference(numbers, fourNumbers);
      })
      .add('Underscore', function() {
        _.difference(numbers, fourNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('groupBy callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return Math.floor(num); });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return Math.floor(num); });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('intersection')
      .add('Lo-Dash', function() {
        lodash.intersection(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.intersection(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(obj) {
          return obj.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(obj) {
          return obj.num;
        });
      })
  );
  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pick')
      .add('Lo-Dash', function() {
        lodash.pick(object, 'key6', 'key13');
      })
      .add('Underscore', function() {
        _.pick(object, 'key6', 'key13');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('union')
      .add('Lo-Dash', function() {
        lodash.union(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.union(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

  /*--------------------------------------------------------------------------*/

  if (Benchmark.platform + '') {
    console.log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<|endoftext|>


<commit_before>/* eslint-disable no-console */
'use strict';

const async = require('async');
const os = require('os');
const path = require('path');
const rimraf = require('rimraf');
const superagent = require('superagent');

const COMPUTATIONS_DIRECTORY = path.join(
  os.tmpdir(),
  'coinstac-server-core',
  'computations'
);

const DATABASE_DIRECTORY = path.join(
  os.tmpdir(),
  'coinstac-server-core',
  'dbs'
);

async.parallel([
  cb1 => {
    async.parallel([
      cb1a => {
        console.log('Removing database dir…');
        rimraf(DATABASE_DIRECTORY, error => {
          if (error) {
            cb1a(error);
          } else {
            console.log('Database dir removed');
            cb1a(null);
          }
        });
      },
      cb1b => {
        console.log('Removing computations dir…');
        rimraf(COMPUTATIONS_DIRECTORY, error => {
          if (error) {
            cb1b(error);
          } else {
            console.log('Computations dir removed');
            cb1b(null);
          }
        });
      },
    ], cb1);
  },
  cb2 => {
    async.waterfall([
      cb2a => {
        superagent
          .get('http://localhost:5984/_all_dbs')
          .set('Accept', 'application/json')
          .end(cb2a);
      },
      (response, cb2b) => {
        async.map(
          response.body.filter(name => name.charAt(0) !== '_'),
          (dbName, cb2b1) => {
            superagent
              .delete(`http://localhost:5984/${dbName}`)
              .set('Accept', 'application/json')
              .end((error, deleteResponse) => {
                const body = deleteResponse.body;

                if (error) {
                  cb2b1(error);
                } else if (!body.ok) {
                  cb2b1(body);
                } else {
                  console.log(`Removed database: ${dbName}`);
                  cb2b1(null);
                }
              });
          },
          cb2b
        );
      },
    ], cb2);
  },
], error => {
  if (error) {
    console.error(error);
  }
});
/* eslint-enable no-console */

<commit_msg>Fix removed dir paths.<commit_after>/* eslint-disable no-console */
'use strict';

const async = require('async');
const os = require('os');
const path = require('path');
const rimraf = require('rimraf');
const superagent = require('superagent');

async.parallel([
  cb1 => {
    async.parallel([
      cb1a => {
        console.log('Removing database dir…');
        rimraf(path.join(os.tmpDir(), 'coinstac'), error => {
          if (error) {
            cb1a(error);
          } else {
            console.log('Database dir removed');
            cb1a(null);
          }
        });
      },
      cb1b => {
        console.log('Removing computations dir…');
        rimraf(path.join(os.tmpDir(), 'coinstac-server-core'), error => {
          if (error) {
            cb1b(error);
          } else {
            console.log('Computations dir removed');
            cb1b(null);
          }
        });
      },
    ], cb1);
  },
  cb2 => {
    async.waterfall([
      cb2a => {
        superagent
          .get('http://localhost:5984/_all_dbs')
          .set('Accept', 'application/json')
          .end(cb2a);
      },
      (response, cb2b) => {
        async.map(
          response.body.filter(name => name.charAt(0) !== '_'),
          (dbName, cb2b1) => {
            superagent
              .delete(`http://localhost:5984/${dbName}`)
              .set('Accept', 'application/json')
              .end((error, deleteResponse) => {
                const body = deleteResponse.body;

                if (error) {
                  cb2b1(error);
                } else if (!body.ok) {
                  cb2b1(body);
                } else {
                  console.log(`Removed database: ${dbName}`);
                  cb2b1(null);
                }
              });
          },
          cb2b
        );
      },
    ], cb2);
  },
], error => {
  if (error) {
    console.error(error);
  }
});
/* eslint-enable no-console */

<|endoftext|>


<commit_before>/* eslint camelcase: "off" */
(function() {
  'use strict';

  angular.module('app.components')
    .factory('OwnershipServiceModal', OwnershipServiceFactory);

  /** @ngInject */
  function OwnershipServiceFactory($modal) {
    var modalService = {
      showModal: showModal,
    };

    return modalService;

    function showModal(serviceDetails) {
      var modalOptions = {
        templateUrl: 'app/components/ownership-service-modal/ownership-service-modal.html',
        controller: OwnershipServiceModalController,
        controllerAs: 'vm',
        size: 'lg',
        resolve: {
          serviceDetails: resolveServiceDetails,
          users: resolveUsers,
          groups: resolveGroups,
        },
      };
      var modal = $modal.open(modalOptions);

      return modal.result;

      /** @ngInject */
      function resolveServiceDetails(CollectionsApi) {
        var requestAttributes = [
          'evm_owner.userid',
          'miq_group.description',
        ];
        var options = {attributes: requestAttributes};

        return CollectionsApi.get('services', serviceDetails.id, options);
      }
    }
  }

  /** @ngInject */
  function resolveUsers(CollectionsApi) {
    var options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'};

    return CollectionsApi.query('users', options);
  }

  /** @ngInject */
  function resolveGroups(CollectionsApi) {
    var options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'};

    return CollectionsApi.query('groups', options);
  }

  /** @ngInject */
  function OwnershipServiceModalController(serviceDetails, $state, $modalInstance, CollectionsApi, EventNotifications, users, groups, sprintf) {
    var vm = this;

    vm.service = serviceDetails;
    vm.saveOwnership = saveOwnership;
    vm.users = users;
    vm.groups = groups;

    vm.modalData = {
      'action': 'set_ownership',
      'resource': {
        'owner': {
          'userid': vm.service.evm_owner && vm.service.evm_owner.userid || '',
        },
        'group': {
          'description': vm.service.miq_group && vm.service.miq_group.description || '',
        },
      },
    };
    activate();

    function activate() {
    }

    function saveOwnership() {
      CollectionsApi.post('services', vm.service.id, {}, vm.modalData).then(saveSuccess, saveFailure);

      function saveSuccess() {
        $modalInstance.close();
        EventNotifications.success(__(sprintf("%s ownership was saved.", vm.service.name)));
        $state.go($state.current, {}, {reload: true});
      }

      function saveFailure() {
        EventNotifications.error(__('There was an error saving ownership of this service.'));
      }
    }
  }
})();
<commit_msg>Don't apply __() on a dynamic expression<commit_after>/* eslint camelcase: "off" */
(function() {
  'use strict';

  angular.module('app.components')
    .factory('OwnershipServiceModal', OwnershipServiceFactory);

  /** @ngInject */
  function OwnershipServiceFactory($modal) {
    var modalService = {
      showModal: showModal,
    };

    return modalService;

    function showModal(serviceDetails) {
      var modalOptions = {
        templateUrl: 'app/components/ownership-service-modal/ownership-service-modal.html',
        controller: OwnershipServiceModalController,
        controllerAs: 'vm',
        size: 'lg',
        resolve: {
          serviceDetails: resolveServiceDetails,
          users: resolveUsers,
          groups: resolveGroups,
        },
      };
      var modal = $modal.open(modalOptions);

      return modal.result;

      /** @ngInject */
      function resolveServiceDetails(CollectionsApi) {
        var requestAttributes = [
          'evm_owner.userid',
          'miq_group.description',
        ];
        var options = {attributes: requestAttributes};

        return CollectionsApi.get('services', serviceDetails.id, options);
      }
    }
  }

  /** @ngInject */
  function resolveUsers(CollectionsApi) {
    var options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'};

    return CollectionsApi.query('users', options);
  }

  /** @ngInject */
  function resolveGroups(CollectionsApi) {
    var options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'};

    return CollectionsApi.query('groups', options);
  }

  /** @ngInject */
  function OwnershipServiceModalController(serviceDetails, $state, $modalInstance, CollectionsApi, EventNotifications, users, groups, sprintf) {
    var vm = this;

    vm.service = serviceDetails;
    vm.saveOwnership = saveOwnership;
    vm.users = users;
    vm.groups = groups;

    vm.modalData = {
      'action': 'set_ownership',
      'resource': {
        'owner': {
          'userid': vm.service.evm_owner && vm.service.evm_owner.userid || '',
        },
        'group': {
          'description': vm.service.miq_group && vm.service.miq_group.description || '',
        },
      },
    };
    activate();

    function activate() {
    }

    function saveOwnership() {
      CollectionsApi.post('services', vm.service.id, {}, vm.modalData).then(saveSuccess, saveFailure);

      function saveSuccess() {
        $modalInstance.close();
        EventNotifications.success(sprintf(__("%s ownership was saved."), vm.service.name));
        $state.go($state.current, {}, {reload: true});
      }

      function saveFailure() {
        EventNotifications.error(__('There was an error saving ownership of this service.'));
      }
    }
  }
})();
<|endoftext|>


<commit_before>/*jslint browser: true*/

( function( vui ) {

	// Check if the provided vui global is defined, otherwise try to require it if
	// we're in a CommonJS environment; otherwise we'll just fail out
	if( vui === undefined ) {
		if( typeof require === 'function' ) {
			vui = require('../../core');
		} else {
			throw new Error('load vui first');
		}
	}

	// Export the vui object if we're in a CommonJS environment.
	// It will already be on the window otherwise
	if( typeof module === 'object' && typeof module.exports === 'object' ) {
		module.exports = vui;
	}

	var $ = vui.$;

	$.widget( "vui.vui_moreless", {

		options: {
			height: '4em',
			lineHeight: 'normal',
			title: {
				more: "more",
				less: "less"
			},
			color: '#FAFAFA'
		},

		_$moreblur: null,
		_$moreless: null,
		_$morelink: null,
		pollingVariable: null,

		_accessibileButton: function( title, iconClass ) {
			var me = this;
			me._$morelink.empty();
			me._$morelink.append( '' );
			if( !this.options.accessible ) {
				me._$morelink.attr( 'aria-hidden', 'true' );
				me._$morelink.append( title );
			} else {
				me._$morelink.attr( 'aria-role', 'button' );
				title = $( '' + title + '' );
				me._$morelink.append( title );
			}
		},

		_create: function() {
			var me = this;

			me._$moreless = $( this.element );
			me._$morelink = $( '
' );
			me._$moreless.after(  me._$morelink );

			me.options.title.more = me._$moreless.attr( 'data-moreless-moretitle' ) !== undefined ? me._$moreless.attr( 'data-moreless-moretitle' ) : me.options.title.more;
			me.options.title.less = me._$moreless.attr( 'data-moreless-lesstitle' ) !== undefined ? me._$moreless.attr( 'data-moreless-lesstitle' ) : me.options.title.less;
			me.options.accessible = me._$moreless.attr( 'data-moreless-accessible' ) !== undefined && me._$moreless.attr( 'data-moreless-accessible' ) !== "False"? true : false;
			me.options.color = me._$moreless.attr( 'data-moreless-blurcolor' ) !== undefined ? me._$moreless.attr( 'data-moreless-blurcolor' ) : me.options.color;

			var lineHeight =  me._$moreless.attr( 'data-moreless-lineHeight' ) !== undefined ? me._$moreless.attr( 'data-moreless-lineHeight' ) : me.options.lineHeight;
			me._$moreless.css( 'line-height', lineHeight );

			var $breakafter =  me._$moreless.find( '.vui-moreless-breakafter' );
			var height = 0;

			if( $breakafter.length ) {
				$breakafter = $( $breakafter[0] );
				//determine hieght based on bottom on node with breakafter class
				height = ( $breakafter.position().top - me._$moreless.position().top ) + $breakafter.get( 0 ).scrollHeight;

			} else {
				height = me._$moreless.attr( 'data-moreless-height' ) !== undefined ? me._$moreless.attr( 'data-moreless-height' ) : me.options.height;

				if( height.indexOf( '%' ) > -1 ) { //convert percent to px to prevent loss of transition
					height = parseInt( ( me._$moreless.get( 0 ).scrollHeight * ( parseInt( height, 10 ) / 100 ) ) + 0.5, 10 );
				}

				me._$moreblur = $( '
');
				me.BlurColor( me.options.color );
				me._$moreless.after( me._$moreblur );
			}

			me._$moreless.height( height );

			me._accessibileButton( me.options.title.more, 'vui-icon-moreless-chevron-down' );

			me._$morelink.on( 'click', function( e ) {
				me._switchMoreLess( height );
			} );

			me._$morelink.on( 'keypress', function( e ) {
				var keyCode = e.keyCode || e.which;

				if( keyCode === 13 ) {
					me._switchMoreLess( height );
				}
			} );

			var isTab = false;

			$( document ).keydown( function( e ) {
				var keyCode = e.keyCode || e.which;

				if( keyCode === 9 ) {
					isTab = true;
				} else {
					isTab = false;
				}
			} );

			me._$moreless.focusin( function( event ) {
				if( ! me._$moreless.hasClass( 'vui-moreless-more' ) && isTab ) {
					me._$moreless.get( 0 ).scrollTop = 0;
					me._$morelink.focus();
					isTab = false;
				}
			});

			var moreLessHeight = parseInt(height, 10);

			me._fixMoreLess(moreLessHeight);
			$(window).load(function() {
				me._startPolling(500, moreLessHeight);
			} );
		},

		_hexToRgb: function( inHex) {
			if( inHex.indexOf('#') > -1 ) {
				inHex = inHex.substring(1);
			}
			// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
			if (inHex.length === 3) {
				var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
				inHex = inHex.replace(shorthandRegex, function (m, r, g, b) {
					return r + r + g + g + b + b;
				} );
			}

			var bigint = parseInt( inHex, 16);
			var r = (bigint >> 16) & 255;
			var g = (bigint >> 8) & 255;
			var b = bigint & 255;

			return {
				red: r,
				green: g,
				blue: b
			};
		},

		_startPolling: function (timeout, morelessHeight) {
			var me = this;

			me._fixMoreLess(morelessHeight);

			me.pollingVariable = setTimeout(
				function() {
					me._startPolling(
						timeout < 10000 ? timeout * 2 : timeout,
						morelessHeight
					);
				},
				timeout
			);
		},

		_fixMoreLess: function (morelessHeight) {
			var me = this;

			if (me._$moreless.hasClass('vui-moreless-more')) {
				return;
			}

			me._hideShowMore(morelessHeight);
			me._showShowMore(morelessHeight);
		},

		_hideShowMore: function (morelessHeight) {
			var me = this;

			var scrollHeight = me._$moreless.get(0).scrollHeight;
			var childrenHeight = me._$moreless.children().height();

			// we use the children's height instead of the scroll height because on page load,
			// the scroll height will be equal to the moreless height if the control is present
			// if they are equal then the control will stay in its same state, not changing anything
			// therefore we calculate the childrens height and use that the first time
			// we can't use the children's height everytime because it messes up when we use break after

			var h = scrollHeight == morelessHeight ? childrenHeight : scrollHeight;

			if (me._$moreless &&
				h < morelessHeight) {

				me._$moreless.height( h );
				me._$morelink.css( 'display', 'none' );

				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'none' );
				}
			} else if (me._$moreless &&
				h != me._$moreless.height()) {

				me._$moreless.height(h);
			}
		},

		_showShowMore: function(morelessHeight) {
			var me = this;

			var scrollHeight = me._$moreless.get(0).scrollHeight;
			var childrenHeight = me._$moreless.children().height();

			var h = scrollHeight == morelessHeight ? childrenHeight : scrollHeight;

			if (me._$moreless &&
				h >= morelessHeight) {

				me._$moreless.height(morelessHeight);
				me._$morelink.css( 'display', 'inherit' );

				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'inherit' );
				}
			}
		},

		_switchMoreLess: function( inHeight ) {
			var me = this;

			if (!me._$moreless.hasClass('vui-moreless-transition-effect')) {
				me._$moreless.addClass('vui-moreless-transition-effect');
			}

			if( me._$moreless.hasClass( 'vui-moreless-more' ) ) {
				me._$moreless.removeClass( 'vui-moreless-more' );
				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'block' );
				}
				me._$moreless.css( 'height', inHeight );
				me._accessibileButton(  me.options.title.more, 'vui-icon-moreless-chevron-down' );
				me._$moreless.trigger( 'vui-moreless-collapse' );
			} else {
				me._$moreless.addClass( 'vui-moreless-more' );
				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'none' );
				}
				me._$moreless.css( 'height',  me._$moreless.get( 0 ).scrollHeight );
				me._accessibileButton( this.options.title.less, 'vui-icon-moreless-chevron-up' );
				me._$moreless.trigger( 'vui-moreless-expand' );
			}
		},

		_destroy: function () {
			var me = this;
			if (me.pollingVariable !== null) {
				clearInterval(me.pollingVariable);
			}

			me.pollingVariable = false;
		},

		BlurColor: function( inColor ) {
			var me = this;
			if( me._$moreblur !== null ) {
				var rgba0 = 'rgba( 250, 250, 250, 0)';
				var rgba1 = 'rgba( 250, 250, 250, 1)';

				if( inColor.indexOf( '#' ) > -1 ) {
					var rgb = me._hexToRgb( inColor );
					rgba0 = 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ', 0)';
					rgba1 = 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ', 1)';
				}
				var moz = '-moz-linear-gradient(top, ' + rgba0 + ' 0%, '+ rgba1 + ' 100%)';
				var webkit1 = '-webkit-gradient(linear, left top, left bottom, color-stop(0%, ' + rgba0 + '), color-stop(100%, '+ rgba1 + '))'; /* Chrome,Safari4+ */
				var webkit2 = '-webkit-linear-gradient(top, ' + rgba0 + ' 0%, ' + rgba1 + '100%)'; /* Chrome10+,Safari5.1+ */
				var o = '-o-linear-gradient(top, ' + rgba0 + ' 0%, ' + rgba1 + ' 100%)'; /* Opera 11.10+ */
				var ms = '-ms-linear-gradient(top, ' + rgba0 + ' 0%, '+ rgba1 + ' 100%)';/* IE10+ */
				var general = 'linear-gradient(to bottom, ' + rgba0 + ' 0%, ' + rgba1 + ' 100%)';/* W3C */

				me._$moreblur.css( { 'background': 'transparent' } )
					.css( { 'background': moz } )
					.css( { 'background': webkit1 } )
					.css( { 'background': webkit2 } )
					.css( { 'background': o } )
					.css( { 'background': ms } )
					.css( { 'background': general } );
			}
		},

		isExpanded: function( node ) {
			return $( node ).hasClass( 'vui-moreless-more' );
		},

		Refresh: function( inColor ){
			if( inColor !== null ) {
				this.BlurColor( inColor );
			}
			this._fixMoreLess();
		}

	} );

	vui.addClassInitializer(
		'vui-moreless',
		function( node ) {
			$( node ).vui_moreless();
		}
	);

} )( window.vui );<commit_msg>Putting "use strict" in all our JS.<commit_after>/*jslint browser: true*/

( function( vui ) {

	'use strict';

	// Check if the provided vui global is defined, otherwise try to require it if
	// we're in a CommonJS environment; otherwise we'll just fail out
	if( vui === undefined ) {
		if( typeof require === 'function' ) {
			vui = require('../../core');
		} else {
			throw new Error('load vui first');
		}
	}

	// Export the vui object if we're in a CommonJS environment.
	// It will already be on the window otherwise
	if( typeof module === 'object' && typeof module.exports === 'object' ) {
		module.exports = vui;
	}

	var $ = vui.$;

	$.widget( "vui.vui_moreless", {

		options: {
			height: '4em',
			lineHeight: 'normal',
			title: {
				more: "more",
				less: "less"
			},
			color: '#FAFAFA'
		},

		_$moreblur: null,
		_$moreless: null,
		_$morelink: null,
		pollingVariable: null,

		_accessibileButton: function( title, iconClass ) {
			var me = this;
			me._$morelink.empty();
			me._$morelink.append( '' );
			if( !this.options.accessible ) {
				me._$morelink.attr( 'aria-hidden', 'true' );
				me._$morelink.append( title );
			} else {
				me._$morelink.attr( 'aria-role', 'button' );
				title = $( '' + title + '' );
				me._$morelink.append( title );
			}
		},

		_create: function() {
			var me = this;

			me._$moreless = $( this.element );
			me._$morelink = $( '
' );
			me._$moreless.after(  me._$morelink );

			me.options.title.more = me._$moreless.attr( 'data-moreless-moretitle' ) !== undefined ? me._$moreless.attr( 'data-moreless-moretitle' ) : me.options.title.more;
			me.options.title.less = me._$moreless.attr( 'data-moreless-lesstitle' ) !== undefined ? me._$moreless.attr( 'data-moreless-lesstitle' ) : me.options.title.less;
			me.options.accessible = me._$moreless.attr( 'data-moreless-accessible' ) !== undefined && me._$moreless.attr( 'data-moreless-accessible' ) !== "False"? true : false;
			me.options.color = me._$moreless.attr( 'data-moreless-blurcolor' ) !== undefined ? me._$moreless.attr( 'data-moreless-blurcolor' ) : me.options.color;

			var lineHeight =  me._$moreless.attr( 'data-moreless-lineHeight' ) !== undefined ? me._$moreless.attr( 'data-moreless-lineHeight' ) : me.options.lineHeight;
			me._$moreless.css( 'line-height', lineHeight );

			var $breakafter =  me._$moreless.find( '.vui-moreless-breakafter' );
			var height = 0;

			if( $breakafter.length ) {
				$breakafter = $( $breakafter[0] );
				//determine hieght based on bottom on node with breakafter class
				height = ( $breakafter.position().top - me._$moreless.position().top ) + $breakafter.get( 0 ).scrollHeight;

			} else {
				height = me._$moreless.attr( 'data-moreless-height' ) !== undefined ? me._$moreless.attr( 'data-moreless-height' ) : me.options.height;

				if( height.indexOf( '%' ) > -1 ) { //convert percent to px to prevent loss of transition
					height = parseInt( ( me._$moreless.get( 0 ).scrollHeight * ( parseInt( height, 10 ) / 100 ) ) + 0.5, 10 );
				}

				me._$moreblur = $( '
');
				me.BlurColor( me.options.color );
				me._$moreless.after( me._$moreblur );
			}

			me._$moreless.height( height );

			me._accessibileButton( me.options.title.more, 'vui-icon-moreless-chevron-down' );

			me._$morelink.on( 'click', function( e ) {
				me._switchMoreLess( height );
			} );

			me._$morelink.on( 'keypress', function( e ) {
				var keyCode = e.keyCode || e.which;

				if( keyCode === 13 ) {
					me._switchMoreLess( height );
				}
			} );

			var isTab = false;

			$( document ).keydown( function( e ) {
				var keyCode = e.keyCode || e.which;

				if( keyCode === 9 ) {
					isTab = true;
				} else {
					isTab = false;
				}
			} );

			me._$moreless.focusin( function( event ) {
				if( ! me._$moreless.hasClass( 'vui-moreless-more' ) && isTab ) {
					me._$moreless.get( 0 ).scrollTop = 0;
					me._$morelink.focus();
					isTab = false;
				}
			});

			var moreLessHeight = parseInt(height, 10);

			me._fixMoreLess(moreLessHeight);
			$(window).load(function() {
				me._startPolling(500, moreLessHeight);
			} );
		},

		_hexToRgb: function( inHex) {
			if( inHex.indexOf('#') > -1 ) {
				inHex = inHex.substring(1);
			}
			// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
			if (inHex.length === 3) {
				var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
				inHex = inHex.replace(shorthandRegex, function (m, r, g, b) {
					return r + r + g + g + b + b;
				} );
			}

			var bigint = parseInt( inHex, 16);
			var r = (bigint >> 16) & 255;
			var g = (bigint >> 8) & 255;
			var b = bigint & 255;

			return {
				red: r,
				green: g,
				blue: b
			};
		},

		_startPolling: function (timeout, morelessHeight) {
			var me = this;

			me._fixMoreLess(morelessHeight);

			me.pollingVariable = setTimeout(
				function() {
					me._startPolling(
						timeout < 10000 ? timeout * 2 : timeout,
						morelessHeight
					);
				},
				timeout
			);
		},

		_fixMoreLess: function (morelessHeight) {
			var me = this;

			if (me._$moreless.hasClass('vui-moreless-more')) {
				return;
			}

			me._hideShowMore(morelessHeight);
			me._showShowMore(morelessHeight);
		},

		_hideShowMore: function (morelessHeight) {
			var me = this;

			var scrollHeight = me._$moreless.get(0).scrollHeight;
			var childrenHeight = me._$moreless.children().height();

			// we use the children's height instead of the scroll height because on page load,
			// the scroll height will be equal to the moreless height if the control is present
			// if they are equal then the control will stay in its same state, not changing anything
			// therefore we calculate the childrens height and use that the first time
			// we can't use the children's height everytime because it messes up when we use break after

			var h = scrollHeight == morelessHeight ? childrenHeight : scrollHeight;

			if (me._$moreless &&
				h < morelessHeight) {

				me._$moreless.height( h );
				me._$morelink.css( 'display', 'none' );

				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'none' );
				}
			} else if (me._$moreless &&
				h != me._$moreless.height()) {

				me._$moreless.height(h);
			}
		},

		_showShowMore: function(morelessHeight) {
			var me = this;

			var scrollHeight = me._$moreless.get(0).scrollHeight;
			var childrenHeight = me._$moreless.children().height();

			var h = scrollHeight == morelessHeight ? childrenHeight : scrollHeight;

			if (me._$moreless &&
				h >= morelessHeight) {

				me._$moreless.height(morelessHeight);
				me._$morelink.css( 'display', 'inherit' );

				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'inherit' );
				}
			}
		},

		_switchMoreLess: function( inHeight ) {
			var me = this;

			if (!me._$moreless.hasClass('vui-moreless-transition-effect')) {
				me._$moreless.addClass('vui-moreless-transition-effect');
			}

			if( me._$moreless.hasClass( 'vui-moreless-more' ) ) {
				me._$moreless.removeClass( 'vui-moreless-more' );
				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'block' );
				}
				me._$moreless.css( 'height', inHeight );
				me._accessibileButton(  me.options.title.more, 'vui-icon-moreless-chevron-down' );
				me._$moreless.trigger( 'vui-moreless-collapse' );
			} else {
				me._$moreless.addClass( 'vui-moreless-more' );
				if( me._$moreblur ) {
					me._$moreblur.css( 'display', 'none' );
				}
				me._$moreless.css( 'height',  me._$moreless.get( 0 ).scrollHeight );
				me._accessibileButton( this.options.title.less, 'vui-icon-moreless-chevron-up' );
				me._$moreless.trigger( 'vui-moreless-expand' );
			}
		},

		_destroy: function () {
			var me = this;
			if (me.pollingVariable !== null) {
				clearInterval(me.pollingVariable);
			}

			me.pollingVariable = false;
		},

		BlurColor: function( inColor ) {
			var me = this;
			if( me._$moreblur !== null ) {
				var rgba0 = 'rgba( 250, 250, 250, 0)';
				var rgba1 = 'rgba( 250, 250, 250, 1)';

				if( inColor.indexOf( '#' ) > -1 ) {
					var rgb = me._hexToRgb( inColor );
					rgba0 = 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ', 0)';
					rgba1 = 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ', 1)';
				}
				var moz = '-moz-linear-gradient(top, ' + rgba0 + ' 0%, '+ rgba1 + ' 100%)';
				var webkit1 = '-webkit-gradient(linear, left top, left bottom, color-stop(0%, ' + rgba0 + '), color-stop(100%, '+ rgba1 + '))'; /* Chrome,Safari4+ */
				var webkit2 = '-webkit-linear-gradient(top, ' + rgba0 + ' 0%, ' + rgba1 + '100%)'; /* Chrome10+,Safari5.1+ */
				var o = '-o-linear-gradient(top, ' + rgba0 + ' 0%, ' + rgba1 + ' 100%)'; /* Opera 11.10+ */
				var ms = '-ms-linear-gradient(top, ' + rgba0 + ' 0%, '+ rgba1 + ' 100%)';/* IE10+ */
				var general = 'linear-gradient(to bottom, ' + rgba0 + ' 0%, ' + rgba1 + ' 100%)';/* W3C */

				me._$moreblur.css( { 'background': 'transparent' } )
					.css( { 'background': moz } )
					.css( { 'background': webkit1 } )
					.css( { 'background': webkit2 } )
					.css( { 'background': o } )
					.css( { 'background': ms } )
					.css( { 'background': general } );
			}
		},

		isExpanded: function( node ) {
			return $( node ).hasClass( 'vui-moreless-more' );
		},

		Refresh: function( inColor ){
			if( inColor !== null ) {
				this.BlurColor( inColor );
			}
			this._fixMoreLess();
		}

	} );

	vui.addClassInitializer(
		'vui-moreless',
		function( node ) {
			$( node ).vui_moreless();
		}
	);

} )( window.vui );<|endoftext|>


<commit_before><commit_msg>Minor bug with the correct answer in hard mode - issue #4<commit_after><|endoftext|>


<commit_before>var selected_node = null;
function getSlideShow() {
    // 부모창이 있는지 체크
    if(typeof(opener)=="undefined") return;

    // 부모 위지윅 에디터에서 선택된 영역이 있으면 처리
    var node = opener.editorPrevNode;
    var selected_images = "";
    if(node && node.nodeName == "DIV") {
        selected_node = node;

        var width = xWidth(selected_node)-6;
        var gallery_style = selected_node.getAttribute("gallery_style");
        var gallery_align = selected_node.getAttribute("gallery_align");
        var border_color = selected_node.getAttribute("border_color");
        var bg_color = selected_node.getAttribute("bg_color");
        var border_thickness = selected_node.getAttribute("border_thickness");
        if(!border_thickness) border_thickness = 1;

        xGetElementById("width").value = width;

        if(gallery_style=="list") xGetElementById("gallery_style").selectedIndex = 1;
        else xGetElementById("gallery_style").selectedIndex = 0;

        if(!gallery_align || gallery_align=="center") xGetElementById("gallery_align").selectedIndex = 0;
        else if(gallery_align=="left") xGetElementById("gallery_align").selectedIndex = 1;
        else if(gallery_align=="right") xGetElementById("gallery_align").selectedIndex = 2;

        xGetElementById("border_thickness").value = border_thickness;

        xGetElementById("border_color_input").value = border_color;
        manual_select_color("border", xGetElementById("border_color_input"));

        xGetElementById("bg_color_input").value = bg_color;
        manual_select_color("bg", xGetElementById("bg_color_input"));

        selected_images = xInnerHtml(selected_node);
    }

    // 부모창의 업로드된 파일중 이미지 목록을 모두 가져와서 세팅
    var fo = xGetElementById("fo");
    var upload_target_srl = fo.upload_target_srl.value;

    var parent_list_obj = opener.xGetElementById("uploaded_file_list_"+upload_target_srl);

    var list_obj = xGetElementById("image_list");

    for(var i=0;i<parent_list_obj.length;i++) {
        var opt = parent_list_obj.options[i];
        var file_srl = opt.value;
        var file_obj = opener.uploaded_files[file_srl];
        var filename = file_obj.uploaded_filename;
        if((/(jpg|jpeg|gif|png)$/i).test(filename)) {
            var selected = false;
            if(selected_images.indexOf(filename)!=-1) selected = true;
            var opt = new Option(opt.text, opt.value, false, selected);
            list_obj.options.add(opt);
        }
    }
}

function insertSlideShow() {
    if(typeof(opener)=="undefined") return;

    var list = new Array();
    var list_obj = xGetElementById("image_list");
    for(var i=0;i<list_obj.length;i++) {
        var opt = list_obj.options[i];
        if(opt.selected) {
            var file_srl = opt.value;
            var file_obj = opener.uploaded_files[file_srl];
            var filename = file_obj.uploaded_filename;
            list[list.length] = filename;
        }
    }

    if(!list.length) {
        window.close();
        return;
    }

    var width = xGetElementById("width").value;

    var gallery_style = xGetElementById("gallery_style").options[xGetElementById("gallery_style").selectedIndex].value;
    var gallery_align = xGetElementById("gallery_align").options[xGetElementById("gallery_align").selectedIndex].value;
    var border_thickness = xGetElementById("border_thickness").value;
    var border_color = xGetElementById("border_color_input").value;
    var bg_color = xGetElementById("bg_color_input").value;

    var images_list = "";
    for(var i=0; i<list.length;i++) {
        images_list += list[i].trim()+"\n";
    }

    if(selected_node) {
        selected_node.setAttribute("width", width);
        selected_node.setAttribute("gallery_style", gallery_style);
        selected_node.setAttribute("gallery_align", gallery_align);
        selected_node.setAttribute("border_thickness", border_thickness);
        selected_node.setAttribute("border_color", border_color);
        selected_node.setAttribute("bg_color", bg_color);
        selected_node.style.width = width+"px";
        xInnerHtml(selected_node, images_list);
    } else {
        var text = "
"+images_list+"
";
        opener.editorFocus(opener.editorPrevSrl);
        var iframe_obj = opener.editorGetIFrame(opener.editorPrevSrl)
        opener.editorReplaceHTML(iframe_obj, text);
    }

    opener.editorFocus(opener.editorPrevSrl);

    window.close();
}

/* 색상 클릭시 */
function select_color(type, code) {
  xGetElementById(type+"_preview_color").style.backgroundColor = "#"+code;
  xGetElementById(type+"_color_input").value = code;
}

/* 수동 색상 변경시 */
function manual_select_color(type, obj) {
  if(obj.value.length!=6) return;
  code = obj.value;
  xGetElementById(type+"_preview_color").style.backgroundColor = "#"+code;
}

/* 색상표를 출력 */
function printColor(type, blank_img_src) {
  var colorTable = new Array('22','44','66','88','AA','CC','EE');
  var html = "";

  for(var i=0;i<8;i+=1) html += printColorBlock(type, i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16), blank_img_src);

  for(var i=0; i<colorTable.length; i+=3) {
    for(var j=0; j<colorTable.length; j+=2) {
      for(var k=0; k<colorTable.length; k++) {
        var code = colorTable[i] + colorTable[j] + colorTable[k];
        html += printColorBlock(type, code, blank_img_src);
      }
    }
  }

  for(var i=8;i<16;i+=1) html += printColorBlock(type, i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16), blank_img_src);

  document.write(html);
}

/* 개별 색상 block 출력 함수 */
function printColorBlock(type, code, blank_img_src) {
  if(type=="bg") {
    return "
<\/div>";
  } else {
    return "
<\/div>";
  }
}

xAddEventListener(window, "load", getSlideShow);
<commit_msg><commit_after>var selected_node = null;
function getSlideShow() {
    // 부모창이 있는지 체크
    if(typeof(opener)=="undefined") return;

    // 부모 위지윅 에디터에서 선택된 영역이 있으면 처리
    var node = opener.editorPrevNode;
    var selected_images = "";
    if(node && node.nodeName == "DIV") {
        selected_node = node;

        var width = xWidth(selected_node)-6;
        var gallery_style = selected_node.getAttribute("gallery_style");
        var gallery_align = selected_node.getAttribute("gallery_align");
        var border_color = selected_node.getAttribute("border_color");
        var bg_color = selected_node.getAttribute("bg_color");
        var border_thickness = selected_node.getAttribute("border_thickness");
        if(!border_thickness) border_thickness = 1;

        xGetElementById("width").value = width;

        if(gallery_style=="list") xGetElementById("gallery_style").selectedIndex = 1;
        else xGetElementById("gallery_style").selectedIndex = 0;

        if(!gallery_align || gallery_align=="center") xGetElementById("gallery_align").selectedIndex = 0;
        else if(gallery_align=="left") xGetElementById("gallery_align").selectedIndex = 1;
        else if(gallery_align=="right") xGetElementById("gallery_align").selectedIndex = 2;

        xGetElementById("border_thickness").value = border_thickness;

        xGetElementById("border_color_input").value = border_color;
        manual_select_color("border", xGetElementById("border_color_input"));

        xGetElementById("bg_color_input").value = bg_color;
        manual_select_color("bg", xGetElementById("bg_color_input"));

        selected_images = xInnerHtml(selected_node);
    }

    // 부모창의 업로드된 파일중 이미지 목록을 모두 가져와서 세팅
    var fo = xGetElementById("fo");
    var upload_target_srl = fo.upload_target_srl.value;

    var parent_list_obj = opener.xGetElementById("uploaded_file_list_"+upload_target_srl);

    var list_obj = xGetElementById("image_list");

    for(var i=0;i<parent_list_obj.length;i++) {
        var opt = parent_list_obj.options[i];
        var file_srl = opt.value;
        var file_obj = opener.uploaded_files[file_srl];
        var filename = file_obj.uploaded_filename;
        if((/(jpg|jpeg|gif|png)$/i).test(filename)) {
            var selected = false;
            if(selected_images.indexOf(filename)!=-1) selected = true;
            var opt = new Option(opt.text, opt.value, false, selected);
            list_obj.options.add(opt);
        }
    }
}

function insertSlideShow() {
    if(typeof(opener)=="undefined") return;

    var list = new Array();
    var list_obj = xGetElementById("image_list");
    for(var i=0;i<list_obj.length;i++) {
        var opt = list_obj.options[i];
        if(opt.selected) {
            var file_srl = opt.value;
            var file_obj = opener.uploaded_files[file_srl];
            var filename = file_obj.uploaded_filename;
            list[list.length] = filename;
        }
    }

    if(!list.length) {
        window.close();
        return;
    }

    var width = xGetElementById("width").value;

    var gallery_style = xGetElementById("gallery_style").options[xGetElementById("gallery_style").selectedIndex].value;
    var gallery_align = xGetElementById("gallery_align").options[xGetElementById("gallery_align").selectedIndex].value;
    var border_thickness = xGetElementById("border_thickness").value;
    var border_color = xGetElementById("border_color_input").value;
    var bg_color = xGetElementById("bg_color_input").value;

    var images_list = "";
    for(var i=0; i<list.length;i++) {
        images_list += list[i].trim()+"\n";
    }
    if(selected_node) {
        selected_node.setAttribute("width", width);
        selected_node.setAttribute("gallery_style", gallery_style);
        selected_node.setAttribute("gallery_align", gallery_align);
        selected_node.setAttribute("border_thickness", border_thickness);
        selected_node.setAttribute("border_color", border_color);
        selected_node.setAttribute("bg_color", bg_color);
        selected_node.style.width = width+"px";
        xInnerHtml(selected_node, images_list);
    } else {
        var text = "
"+images_list+"
";
        opener.editorFocus(opener.editorPrevSrl);
        var iframe_obj = opener.editorGetIFrame(opener.editorPrevSrl)
        opener.editorReplaceHTML(iframe_obj, text);
    }

    opener.editorFocus(opener.editorPrevSrl);

    window.close();
}

/* 색상 클릭시 */
function select_color(type, code) {
  xGetElementById(type+"_preview_color").style.backgroundColor = "#"+code;
  xGetElementById(type+"_color_input").value = code;
}

/* 수동 색상 변경시 */
function manual_select_color(type, obj) {
  if(obj.value.length!=6) return;
  code = obj.value;
  xGetElementById(type+"_preview_color").style.backgroundColor = "#"+code;
}

/* 색상표를 출력 */
function printColor(type, blank_img_src) {
  var colorTable = new Array('22','44','66','88','AA','CC','EE');
  var html = "";

  for(var i=0;i<8;i+=1) html += printColorBlock(type, i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16), blank_img_src);

  for(var i=0; i<colorTable.length; i+=3) {
    for(var j=0; j<colorTable.length; j+=2) {
      for(var k=0; k<colorTable.length; k++) {
        var code = colorTable[i] + colorTable[j] + colorTable[k];
        html += printColorBlock(type, code, blank_img_src);
      }
    }
  }

  for(var i=8;i<16;i+=1) html += printColorBlock(type, i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16)+i.toString(16), blank_img_src);

  document.write(html);
}

/* 개별 색상 block 출력 함수 */
function printColorBlock(type, code, blank_img_src) {
  if(type=="bg") {
    return "
<\/div>";
  } else {
    return "
<\/div>";
  }
}

xAddEventListener(window, "load", getSlideShow);
<|endoftext|>


<commit_before>var miio = require('./lib');

// var vacuum = python.import('mirobot/protocol');

class MiHome {

  constructor (name, ip, port, token, model) {
    this.ip = ip;
    this.port = port
    this.token = token;
    this.name = name
    this.model = model
    this.device = null;
  }

  load () {
    var that = this;

    return that.loading = new Promise(function(resolve, reject){

      if (that.model == 'vacuum') {
        that.device = miio.createDevice({
          address: that.ip,
          token: that.token,
          model: 'rockrobo.vacuum.v1'
        });

        that.device.init()
        .then(() => {
          console.log(that.model + " init success");
          resolve(that);
        })
        .catch(err => {
          console.error(that.model + " init error: " + err);
          reject(err);
        });
      }
      else {

        if (that.token == null) {
          var para = { address: that.ip };
        }
        else {
          var para = { address: that.ip, token: that.token };
        };

        miio.device(para)
          .then(device => {
              that.device = device;
              console.log(that.name + " " + that.device.type + " init success");
              resolve(that);
            })
          .catch(err => {
          console.error(that.name + " init error: " + err);
          reject(err);
        });
      }
    });
  }

  exec(cmd) {
    var that = this;

    if (cmd == 'Stop') {
      cmd = 'Charge';
    }

    switch (cmd) {
      case 'Start':

        if (this.device.type == 'vacuum') {
          this.device.start()
            .then(res => console.log(this.name + " start result : " + res))
            .catch(err => console.error(this.name + " start error: " + err));
        }

        break;

      case 'Charge':

        if (this.device.type == 'vacuum') {
          this.device.charge()
            .then(res => console.log(this.name + " charge result : " + res))
            .catch(err => console.error(this.name + " charge error: " + err));
        }

        break;

      case 'Pause':

        if (this.device.type == 'vacuum') {
          this.device.pause()
            .then(res => console.log(this.name + " pause result : " + res))
            .catch(err => console.error(this.name + " pause error: " + err));
        }

        break;

      case 'List':
        if (this.device.type == 'gateway') {
          this.list();
        }

        break;

      case 'PowerOff':
        if (this.device.type == 'light') {
          this.device.setPower(false)
            .then(res => console.log(this.name + " PowerOff result : " + res))
            .catch(err => console.error(this.name + " PowerOff error: " + err));
        }
        else {
          this.powerSet(false);
        }

        break;
      case 'PowerOn':

        if (this.device.type == 'light') {
          this.device.setPower(true)
            .then(res => console.log(this.name + " PowerOn result : " + res))
            .catch(err => console.error(this.name + " PowerOn error: " + err));
        }
        else {
          this.powerSet(true);
        }
        break;

      case 'PowerStatus':
        this.powerStatus();
        break;

      case 'LightStatus':
        if (this.device.type == 'light') {
          console.log(this.name + " Color Temp: " + this.device.colorTemperature);
        }
        break;

      default:
        console.log('Invalid type:' + cmd);
    }

    return;

  }

  powerOn() {
    var that = this;

    if(this.device.hasCapability('power')) {
      this.device.setPower(true)
        .then(console.log(this.name + ":Power On"))
        .catch(console.error(this.name + "Failed to Power On"));
    }

  }

  _deviecPowerSet(inputDevice, cmd) {
    var that = this;

    for (var i=0; i<inputDevice.powerChannels.length; i++) {
      console.log("Chan " + i);
      inputDevice.setPower(i, cmd)
      .then(power => console.log(inputDevice.type + " Power " + power))
      .catch(err => console.error(inputDevice.type + " Failed: " + err));
    }
  }

  _deviecPowerStatus(inputDevice) {
    var that = this;

    for (var i=0; i<inputDevice.powerChannels.length; i++) {
      console.log(inputDevice.type + " power " + inputDevice.power(JSON.stringify(i)));
    }
  }

  powerSet(cmd) {
    var that = this;

    if(that.device.type == 'gateway') {
      that.device.on('deviceAvailable', subDevice => {
        if (subDevice.type == 'power-plug') {

          that._deviecPowerSet(subDevice,cmd);
        }

        return;
      });
    }
    else {
      that._deviecPowerSet(that.device,cmd);
    }
  }

  powerStatus() {
    var that = this;

    if(that.device.type == 'gateway') {
      that.device.on('deviceAvailable', subDevice => {
        if (subDevice.type == 'power-plug') {

          that._deviecPowerStatus(subDevice);
        }

        return;
      });
    }
    else {
      that._deviecPowerStatus(that.device);
    }
  }

  list() {
    var that = this;
    console.log('All SubDevice:');

    that.device.on('deviceAvailable', subDevice => {
      console.log('ID: ' + subDevice.id + ' Model:' + subDevice.model + ' Type:' + subDevice.type );

      if (subDevice.model == 'lumi.switch') {
          console.log('Actions: ' + subDevice.actions );
          debugger;

          var data = {"cmd":"write","model":"switch","sid":subDevice.id, "data":"{\"status\":\"click\"}" };
          that.device.devApi.send(data);
                 // {"cmd":"write","model":"switch","sid":"112316","short_id":4343, }

        }

      return;

    });

    if(that.device.devices) {

      that.device.devices.forEach(function(item){
        console.log('-' + item);
      })
    }

  }

};

module.exports = MiHome;<commit_msg>update testing case<commit_after>var miio = require('./lib');

// var vacuum = python.import('mirobot/protocol');

class MiHome {

  constructor (name, ip, port, token, model) {
    this.ip = ip;
    this.port = port
    this.token = token;
    this.name = name
    this.model = model
    this.device = null;
  }

  load () {
    var that = this;

    return that.loading = new Promise(function(resolve, reject){

      if (that.model == 'vacuum') {
        that.device = miio.createDevice({
          address: that.ip,
          token: that.token,
          model: 'rockrobo.vacuum.v1'
        });

        that.device.init()
        .then(() => {
          console.log(that.model + " init success");
          resolve(that);
        })
        .catch(err => {
          console.error(that.model + " init error: " + err);
          reject(err);
        });
      }
      else {

        if (that.token == null) {
          var para = { address: that.ip };
        }
        else {
          var para = { address: that.ip, token: that.token };
        };

        miio.device(para)
          .then(device => {
              that.device = device;
              console.log(that.name + " " + that.device.type + " init success");
              resolve(that);
            })
          .catch(err => {
          console.error(that.name + " init error: " + err);
          reject(err);
        });
      }
    });
  }

  exec(cmd) {
    var that = this;

    if (cmd == 'Stop') {
      cmd = 'Charge';
    }

    switch (cmd) {
      case 'Start':

        if (this.device.type == 'vacuum') {
          this.device.start()
            .then(res => console.log(this.name + " start result : " + res))
            .catch(err => console.error(this.name + " start error: " + err));
        }

        break;

      case 'Charge':

        if (this.device.type == 'vacuum') {
          this.device.charge()
            .then(res => console.log(this.name + " charge result : " + res))
            .catch(err => console.error(this.name + " charge error: " + err));
        }

        break;

      case 'Pause':

        if (this.device.type == 'vacuum') {
          this.device.pause()
            .then(res => console.log(this.name + " pause result : " + res))
            .catch(err => console.error(this.name + " pause error: " + err));
        }

        break;

      case 'List':
        if (this.device.type == 'gateway') {
          this.list();
        }

        break;

      case 'PowerOff':
        if (this.device.type == 'light') {
          this.device.setPower(false)
            .then(res => console.log(this.name + " PowerOff result : " + res))
            .catch(err => console.error(this.name + " PowerOff error: " + err));
        }
        else {
          this.powerSet(false);
        }

        break;
      case 'PowerOn':

        if (this.device.type == 'light') {
          this.device.setPower(true)
            .then(res => console.log(this.name + " PowerOn result : " + res))
            .catch(err => console.error(this.name + " PowerOn error: " + err));
        }
        else {
          this.powerSet(true);
        }
        break;

      case 'PowerStatus':
        this.powerStatus();
        break;

      case 'LightStatus':
        if (this.device.type == 'light') {
          console.log(this.name + " Color Temp: " + this.device.colorTemperature);
        }
        break;

      default:
        console.log('Invalid type:' + cmd);
    }

    return;

  }

  powerOn() {
    var that = this;

    if(this.device.hasCapability('power')) {
      this.device.setPower(true)
        .then(console.log(this.name + ":Power On"))
        .catch(console.error(this.name + "Failed to Power On"));
    }

  }

  _deviecPowerSet(inputDevice, cmd) {
    var that = this;

    for (var i=0; i<inputDevice.powerChannels.length; i++) {
      console.log("Chan " + i);
      inputDevice.setPower(i, cmd)
      .then(power => console.log(inputDevice.type + " Power " + power))
      .catch(err => console.error(inputDevice.type + " Failed: " + err));
    }
  }

  _deviecPowerStatus(inputDevice) {
    var that = this;

    for (var i=0; i<inputDevice.powerChannels.length; i++) {
      console.log(inputDevice.type + " power " + inputDevice.power(JSON.stringify(i)));
    }
  }

  powerSet(cmd) {
    var that = this;

    if(that.device.type == 'gateway') {
      that.device.on('deviceAvailable', subDevice => {
        if (subDevice.type == 'power-plug') {

          that._deviecPowerSet(subDevice,cmd);
        }

        return;
      });
    }
    else {
      that._deviecPowerSet(that.device,cmd);
    }
  }

  powerStatus() {
    var that = this;

    if(that.device.type == 'gateway') {
      that.device.on('deviceAvailable', subDevice => {
        if (subDevice.type == 'power-plug') {

          that._deviecPowerStatus(subDevice);
        }

        return;
      });
    }
    else {
      that._deviecPowerStatus(that.device);
    }
  }

  list() {
    var that = this;
    console.log('All SubDevice:');

    that.device.on('deviceAvailable', subDevice => {
      console.log('ID: ' + subDevice.id + ' Model:' + subDevice.model + ' Type:' + subDevice.type );

      if (subDevice.model == 'lumi.switch') {
          console.log('Actions: ' + subDevice.actions );
          debugger;

          var data = {"cmd":"write","model":"switch","sid":subDevice.id, "short_id":2014, "data":"{\"status\":\"click\"}" };
          that.device.devApi.send(data);
                 // 0: data = {"cmd":"read_ack","model":"switch","sid":"158d000155e11d","short_id":2014,"data":"{\"voltage\":3062}"}

        }

      return;

    });

    if(that.device.devices) {

      that.device.devices.forEach(function(item){
        console.log('-' + item);
      })
    }

  }

};

module.exports = MiHome;<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular.module('exceptionless.filter')
        .factory('filterService', ['$rootScope', function ($rootScope) {
            var _rawfilter;
            var _organizationFilter;
            var _projectFilter;
            var _timeFilter;

            function apply(source) {
                return angular.extend({}, getDefaultOptions(), source);
            }

            function buildFilter() {
                return [_organizationFilter, _projectFilter, _timeFilter, _rawfilter].join(' ');
            }

            function fireFilterChanged() {
                $rootScope.$emit('filterChanged', getDefaultOptions());
            }

            function getDefaultOptions() {
                return {
                    filter: buildFilter(),
                    time: 'last 30 days',
                    offset: getTimeZoneOffset()
                };
            }

            function getTimeZoneOffset() {
                return new Date().getTimezoneOffset() * -1;
            }

            function setOrganization(id) {
                var filter = 'organization:' + id;
                if (angular.equals(filter, _organizationFilter)) {
                    return;
                }

                if (id) {
                    _organizationFilter = filter;
                    _projectFilter = void 0;
                } else {
                    _organizationFilter = void 0;
                }
                fireFilterChanged();
            }

            function setProject(id) {
                var filter = 'project:' + id;
                if (angular.equals(filter, _projectFilter)) {
                    return;
                }

                if (id) {
                    _projectFilter = filter;
                    _organizationFilter = void 0;
                } else {
                    _projectFilter = void 0;
                }

                fireFilterChanged();
            }

            function setTime(time) {
                var filter = 'time:' + time;
                if (angular.equals(filter, _timeFilter)) {
                    return;
                }

                _timeFilter = time ? filter : void 0;
                fireFilterChanged();
            }

            function setFilter(filter) {
                if (angular.equals(filter, _rawfilter)) {
                    return;
                }

                _rawfilter = filter;
                fireFilterChanged();
            }

            var service = {
                apply: apply,
                setFilter: setFilter,
                setOrganization: setOrganization,
                setProject: setProject,
                setTime: setTime
            };

            return service;
        }
    ]);
}());
<commit_msg>Updates to the filter service.<commit_after>(function () {
    'use strict';

    angular.module('exceptionless.filter')
        .factory('filterService', ['$rootScope', function ($rootScope) {
            var _rawfilter;
            var _organizationFilter;
            var _projectFilter;
            var _timeFilter;

            function apply(source) {
                return angular.extend({}, getDefaultOptions(), source);
            }

            function buildFilter() {
                var filters = [];
                if (_organizationFilter)
                    filters.push(_organizationFilter);

                if (_projectFilter)
                    filters.push(_projectFilter);

                if (_rawfilter)
                    filters.push(_rawfilter);

                return filters.join(' ');
            }

            function fireFilterChanged() {
                $rootScope.$emit('filterChanged', getDefaultOptions());
            }

            function getDefaultOptions() {
                var options = { offset: getTimeZoneOffset() };

                var filter = buildFilter();
                if (filter) {
                    angular.extend(options, { filter: filter });
                }

                if (_timeFilter) {
                    angular.extend(options, { time: _timeFilter });
                }

                return options;
            }

            function getTimeZoneOffset() {
                return new Date().getTimezoneOffset() * -1;
            }

            function setOrganization(id) {
                var filter = 'organization:' + id;
                if (angular.equals(filter, _organizationFilter)) {
                    return;
                }

                if (id) {
                    _organizationFilter = filter;
                    _projectFilter = void 0;
                } else {
                    _organizationFilter = void 0;
                }
                fireFilterChanged();
            }

            function setProject(id) {
                var filter = 'project:' + id;
                if (angular.equals(filter, _projectFilter)) {
                    return;
                }

                if (id) {
                    _projectFilter = filter;
                    _organizationFilter = void 0;
                } else {
                    _projectFilter = void 0;
                }

                fireFilterChanged();
            }

            function setTime(time) {
                var filter = 'time:' + time;
                if (angular.equals(filter, _timeFilter)) {
                    return;
                }

                _timeFilter = time ? filter : void 0;
                fireFilterChanged();
            }

            function setFilter(filter) {
                if (angular.equals(filter, _rawfilter)) {
                    return;
                }

                _rawfilter = filter;
                fireFilterChanged();
            }

            var service = {
                apply: apply,
                setFilter: setFilter,
                setOrganization: setOrganization,
                setProject: setProject,
                setTime: setTime
            };

            return service;
        }
    ]);
}());
<|endoftext|>


<commit_before>window.Lunchiatto = (function(Backbone, Marionette) {
  Marionette.Renderer.oldRender = Marionette.Renderer.render;
  Marionette.Renderer.render = function(template, data) {
    if (typeof template === 'function') { template = template(); }

    if (!JST[template]) {
      return Marionette.Renderer.oldRender(template, data);
    }
    return JST[template](data);
  };

  const App = new Marionette.Application();

  App.Behaviors = {};

  App.currentUser = undefined;

  App.pageSize = 10;
  App.animationDurationMedium = 500;

  App.getUsers = () => {
    if(App.allUsers) {
      return new Promise((resolve, reject) => { resolve(App.allUsers) });
    }

    return new Promise((resolve, reject) => {
      new App.Entities.Users([]).fetch({
        success: (users) => {
          App.allUsers = users;
          resolve(users);
        },
        error: () => { reject("Something went wrong") }
      });
    });
  };

  App.usersWithoutMe = () => {
    if(App.allUsers) {
      return App.allUsers.reject((user) => {
        console.log(user);
        return user.get("id") === App.currentUser.id;
      });
    } else {
      throw new Error("Users not preloaded");
    }
  };

  App.on('start', function() {
    const $title = $('head title');
    App.router = new App.Router({controller: App.Controller});

    App.root = new App.Root.Layout;

    Marionette.Behaviors.behaviorsLookup = () => App.Behaviors;
    App.currentUser = new App.Entities.User(gon.currentUser);
    App.vent.on('reload:current:user', () => App.currentUser.fetch());
    App.vent.on('set:html:title', title => $title.text(title));

    $(document).foundation();
    if (App.currentUser.loggedIn()) {
      App.Panel.Controller.showNavbar();
    }

    Backbone.history.start({
      pushState: true});

    const menuIcon = $('.menu-icon');
    const navigation = $('.top-bar');

    $('body').on('click', '[data-navigate]', function(e) {
      if (e.metaKey) { return; }
      e.preventDefault();
      $title.text('Lunchiatto');
      const href = $(e.currentTarget).attr('href');
      App.router.navigate(href, {trigger: true});
      if (navigation.hasClass('expanded')) { menuIcon.click(); }
      return navigation.click();
    });
  });
  return App;
})(Backbone, Marionette);

$(() => Lunchiatto.start());
<commit_msg>Fetch user from /api/users/me<commit_after>window.Lunchiatto = (function(Backbone, Marionette) {
  Marionette.Renderer.oldRender = Marionette.Renderer.render;
  Marionette.Renderer.render = function(template, data) {
    if (typeof template === 'function') { template = template(); }

    if (!JST[template]) {
      return Marionette.Renderer.oldRender(template, data);
    }
    return JST[template](data);
  };

  const App = new Marionette.Application();

  App.Behaviors = {};

  App.currentUser = undefined;

  App.pageSize = 10;
  App.animationDurationMedium = 500;

  App.getUsers = () => {
    if(App.allUsers) {
      return new Promise((resolve, reject) => { resolve(App.allUsers) });
    }

    return new Promise((resolve, reject) => {
      new App.Entities.Users([]).fetch({
        success: (users) => {
          App.allUsers = users;
          resolve(users);
        },
        error: () => { reject("Something went wrong") }
      });
    });
  };

  App.usersWithoutMe = () => {
    if(App.allUsers) {
      return App.allUsers.reject((user) => {
        console.log(user);
        return user.get("id") === App.currentUser.id;
      });
    } else {
      throw new Error("Users not preloaded");
    }
  };

  App.on('start', function() {
    const $title = $('head title');
    App.router = new App.Router({controller: App.Controller});

    App.root = new App.Root.Layout;

    Marionette.Behaviors.behaviorsLookup = () => App.Behaviors;
    App.currentUser = new App.Entities.Me()
    App.currentUser.fetch({complete: () => {
      if (App.currentUser.loggedIn()) {
        App.Panel.Controller.showNavbar();
      }

      Backbone.history.start({pushState: true});
    }});

    App.vent.on('reload:current:user', () => App.currentUser.fetch());
    App.vent.on('set:html:title', title => $title.text(title));

    $(document).foundation();

    const menuIcon = $('.menu-icon');
    const navigation = $('.top-bar');

    $('body').on('click', '[data-navigate]', function(e) {
      if (e.metaKey) { return; }
      e.preventDefault();
      $title.text('Lunchiatto');
      const href = $(e.currentTarget).attr('href');
      App.router.navigate(href, {trigger: true});
      if (navigation.hasClass('expanded')) { menuIcon.click(); }
      return navigation.click();
    });
  });
  return App;
})(Backbone, Marionette);

$(() => Lunchiatto.start());
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var Utilities = require('./modules/Utilities');
var Banners = require('./modules/Banners');
var Config = require('./modules/Config');
var BuildConfig = require('./modules/BuildConfig');
var ConsoleHelper = require('./modules/ConsoleHelper');
var ErrorHandling = require('./modules/ErrorHandling');
var Plugins = require('./modules/Plugins');
var ComponentHelper = require('./modules/ComponentHelper');
var folderList = Utilities.getFolders(Config.paths.componentsPath);
var Template = require('./modules/Template');

//
// Clean/Delete Tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-nuke', function () {
    return Plugins.del.sync([Config.paths.distSamples + '/Components']);
});

//
// Copying Files Tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-copyIgnoredFiles', function() {
    return Config.ignoreComponentJSLinting.map(function(element) {
        var src = element.src;
        var dist = element.dist;
        return gulp.src(src)
            .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                title: "Copying Ignored Files"
            })))
            .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
            .pipe(Plugins.changed(dist))
            .pipe(gulp.dest(dist));
    });
});

gulp.task('ComponentSamples-copyAssets', function() {
    var paths = [
        Config.paths.componentsPath + '/**/*.jpg',
        Config.paths.componentsPath + '/**/*.png',
        Config.paths.componentsPath + '/**/*.gif'
    ];

    return gulp.src(paths)
        .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                title: "Copying Component Assets"
            })))
        .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
        .pipe(Plugins.changed(Config.paths.distSamples + '/Components'))
        .pipe(gulp.dest(Config.paths.distSamples + '/Components'));
});

gulp.task('ComponentSamples-styleHinting',  function() {
   return gulp.src(Config.paths.componentsPath + '/**/*.scss')
      .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
      .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
          title: "Checking SASS Compile errors and linting"
      })))
     .pipe(Plugins.sasslint())
     .pipe(ErrorHandling.SASSlintErrors());

 });

//
// Styles tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-buildStyles', function() {
   return folderList.map(function(componentName) {
        var srcTemplate = Config.paths.templatePath + '/'+ BuildConfig.template;
        var destFolder = Config.paths.distSampleComponents + '/' + componentName;
        var srcFolderName = Config.paths.componentsPath + '/' + componentName;
        var manifest = Utilities.parseManifest(srcFolderName + '/' + componentName + '.json');
        var deps = manifest.dependencies || [];
        var distFolderName = Config.paths.distSampleComponents + '/' + componentName;
        var hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.' + BuildConfig.fileExtension, '.css');

        if (hasFileChanged) {
            return ComponentHelper.buildComponentStyles(
                        destFolder,
                        srcTemplate,
                        componentName,
                        deps,
                        BuildConfig.processorPlugin,
                        BuildConfig.processorName,
                        BuildConfig.compileErrorHandler
                    );
        } else {
            return;
        }

   });
});

gulp.task('ComponentSamples-handlebars', function(cb) {
   //Get components for Handlebar
   Config.handleBarsConfig.batch = [];
    for(var i=0; i < folderList.length; i++) {
       var folderName = folderList[i];
       var srcFolderName = Config.paths.componentsPath + '/' + folderName;
       // Push to Handlebars config
       Config.handleBarsConfig.batch.push('./' + srcFolderName);

    }
    cb();
});

gulp.task('ComponentSamples-template', ["ComponentSamples-handlebars"], function(cb) {
  var _template = new Template(folderList, Config.paths.distJS, Config.paths.componentsPath, function() {
    cb();
  }.bind(this));
  _template.init();
});

//
// Sample Component Building
// ----------------------------------------------------------------------------
gulp.task('ComponentSamples-build', ['ComponentSamples-handlebars'], function() {
   var streams = [];

   for(var i=0; i < folderList.length; i++) {
       var folderName = folderList[i];
       var srcFolderName = Config.paths.componentsPath + '/' + folderName;
       var distFolderName = Config.paths.distSampleComponents + '/' + folderName;
       var hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.html');
       hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.json');

       if (hasFileChanged) {
           var manifest = Utilities.parseManifest(srcFolderName + '/' + folderName + '.json');
           var filesArray = manifest.fileOrder;
           var componentPipe;
           var fileGlob = Utilities.getManifestFileList(filesArray, Config.paths.componentsPath + '/' + folderName);

           componentPipe = gulp.src(fileGlob)
           .pipe(Plugins.plumber(ErrorHandling.oneErrorInPipe))
           .pipe(Plugins.gulpif(manifest.wrapBranches, Plugins.wrap('
<%= contents %>
')))
           .pipe(Plugins.handlebars(manifest, Config.handleBarsConfig))
           .pipe(Plugins.fileinclude())
           .pipe(Plugins.concat("index.html"))
           .pipe(Plugins.wrap(
                {
                    src:  Config.paths.templatePath + '/componentSampleTemplate.html'
                },
                {
                    componentName: folderName
                }
           ))
           .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                    title: "Building Sample Component " + folderName
                })))
           .pipe(gulp.dest(Config.paths.distSamples + '/Components/' +  folderName));

           // Add stream
           streams.push(componentPipe);
       }
   }

   if (streams.length > 0) {
       return Plugins.mergeStream(streams);
   } else {
       return;
   }
});

//
// Rolled up Build tasks
// ----------------------------------------------------------------------------

var ComponentSamplesTasks = [
    'ComponentSamples-build',
    'ComponentSamples-copyAssets',
    'ComponentSamples-styleHinting',
    'ComponentSamples-buildStyles',
    'ComponentJS',
    'ComponentSamples-copyIgnoredFiles'
];

//Build Fabric Component Samples
gulp.task('ComponentSamples', ComponentSamplesTasks);

//
// Fabric Messages
// ----------------------------------------------------------------------------
gulp.task('ComponentSamples-finished', ComponentSamplesTasks, function () {
    console.log(ConsoleHelper.generateSuccess(Config.componentSamplesFinished, true));
});

gulp.task('ComponentSamples-updated', ComponentSamplesTasks, function () {
    console.log(ConsoleHelper.generateSuccess(Config.componentSamplesUpdate));
});

//
// Watch Tasks
// ----------------------------------------------------------------------------

// Watches all src fabric components but, builds the samples only
gulp.task('ComponentSamples-watch', ['ComponentSamples'], function () {
    return gulp.watch(Config.paths.componentsPath + '/**/*', Plugins.batch(function (events, done) {
        Plugins.runSequence('ComponentSamples', 'ComponentSamples-updated', done);
    }));
});<commit_msg>Added template library to main tasks<commit_after>var gulp = require('gulp');
var fs = require('fs');
var Utilities = require('./modules/Utilities');
var Banners = require('./modules/Banners');
var Config = require('./modules/Config');
var BuildConfig = require('./modules/BuildConfig');
var ConsoleHelper = require('./modules/ConsoleHelper');
var ErrorHandling = require('./modules/ErrorHandling');
var Plugins = require('./modules/Plugins');
var ComponentHelper = require('./modules/ComponentHelper');
var folderList = Utilities.getFolders(Config.paths.componentsPath);
var Template = require('./modules/Template');

//
// Clean/Delete Tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-nuke', function () {
    return Plugins.del.sync([Config.paths.distSamples + '/Components']);
});

//
// Copying Files Tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-copyIgnoredFiles', function() {
    return Config.ignoreComponentJSLinting.map(function(element) {
        var src = element.src;
        var dist = element.dist;
        return gulp.src(src)
            .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                title: "Copying Ignored Files"
            })))
            .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
            .pipe(Plugins.changed(dist))
            .pipe(gulp.dest(dist));
    });
});

gulp.task('ComponentSamples-copyAssets', function() {
    var paths = [
        Config.paths.componentsPath + '/**/*.jpg',
        Config.paths.componentsPath + '/**/*.png',
        Config.paths.componentsPath + '/**/*.gif'
    ];

    return gulp.src(paths)
        .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                title: "Copying Component Assets"
            })))
        .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
        .pipe(Plugins.changed(Config.paths.distSamples + '/Components'))
        .pipe(gulp.dest(Config.paths.distSamples + '/Components'));
});

gulp.task('ComponentSamples-styleHinting',  function() {
   return gulp.src(Config.paths.componentsPath + '/**/*.scss')
      .pipe(Plugins.plumber(ErrorHandling.onErrorInPipe))
      .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
          title: "Checking SASS Compile errors and linting"
      })))
     .pipe(Plugins.sasslint())
     .pipe(ErrorHandling.SASSlintErrors());

 });

//
// Styles tasks
// ----------------------------------------------------------------------------

gulp.task('ComponentSamples-buildStyles', function() {
   return folderList.map(function(componentName) {
        var srcTemplate = Config.paths.templatePath + '/'+ BuildConfig.template;
        var destFolder = Config.paths.distSampleComponents + '/' + componentName;
        var srcFolderName = Config.paths.componentsPath + '/' + componentName;
        var manifest = Utilities.parseManifest(srcFolderName + '/' + componentName + '.json');
        var deps = manifest.dependencies || [];
        var distFolderName = Config.paths.distSampleComponents + '/' + componentName;
        var hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.' + BuildConfig.fileExtension, '.css');

        if (hasFileChanged) {
            return ComponentHelper.buildComponentStyles(
                        destFolder,
                        srcTemplate,
                        componentName,
                        deps,
                        BuildConfig.processorPlugin,
                        BuildConfig.processorName,
                        BuildConfig.compileErrorHandler
                    );
        } else {
            return;
        }

   });
});

gulp.task('ComponentSamples-handlebars', function(cb) {
   //Get components for Handlebar
   Config.handleBarsConfig.batch = [];
    for(var i=0; i < folderList.length; i++) {
       var folderName = folderList[i];
       var srcFolderName = Config.paths.componentsPath + '/' + folderName;
       // Push to Handlebars config
       Config.handleBarsConfig.batch.push('./' + srcFolderName);

    }
    cb();
});

gulp.task('ComponentSamples-template', ["ComponentSamples-handlebars"], function(cb) {
  var _template = new Template(folderList, Config.paths.distJS, Config.paths.componentsPath, function() {
    cb();
  }.bind(this));
  _template.init();
});

//
// Sample Component Building
// ----------------------------------------------------------------------------
gulp.task('ComponentSamples-build', ['ComponentSamples-handlebars'], function() {
   var streams = [];

   for(var i=0; i < folderList.length; i++) {
       var folderName = folderList[i];
       var srcFolderName = Config.paths.componentsPath + '/' + folderName;
       var distFolderName = Config.paths.distSampleComponents + '/' + folderName;
       var hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.html');
       hasFileChanged = Utilities.hasFileChangedInFolder(srcFolderName, distFolderName, '.json');

       if (hasFileChanged) {
           var manifest = Utilities.parseManifest(srcFolderName + '/' + folderName + '.json');
           var filesArray = manifest.fileOrder;
           var componentPipe;
           var fileGlob = Utilities.getManifestFileList(filesArray, Config.paths.componentsPath + '/' + folderName);

           componentPipe = gulp.src(fileGlob)
           .pipe(Plugins.plumber(ErrorHandling.oneErrorInPipe))
           .pipe(Plugins.gulpif(manifest.wrapBranches, Plugins.wrap('
<%= contents %>
')))
           .pipe(Plugins.handlebars(manifest, Config.handleBarsConfig))
           .pipe(Plugins.fileinclude())
           .pipe(Plugins.concat("index.html"))
           .pipe(Plugins.wrap(
                {
                    src:  Config.paths.templatePath + '/componentSampleTemplate.html'
                },
                {
                    componentName: folderName
                }
           ))
           .pipe(Plugins.gulpif(Config.debugMode, Plugins.debug({
                    title: "Building Sample Component " + folderName
                })))
           .pipe(gulp.dest(Config.paths.distSamples + '/Components/' +  folderName));

           // Add stream
           streams.push(componentPipe);
       }
   }

   if (streams.length > 0) {
       return Plugins.mergeStream(streams);
   } else {
       return;
   }
});

//
// Rolled up Build tasks
// ----------------------------------------------------------------------------

var ComponentSamplesTasks = [
    'ComponentSamples-build',
    'ComponentSamples-copyAssets',
    'ComponentSamples-styleHinting',
    'ComponentSamples-buildStyles',
    'ComponentJS',
    'ComponentSamples-copyIgnoredFiles',
    "ComponentSamples-template"
];

//Build Fabric Component Samples
gulp.task('ComponentSamples', ComponentSamplesTasks);

//
// Fabric Messages
// ----------------------------------------------------------------------------
gulp.task('ComponentSamples-finished', ComponentSamplesTasks, function () {
    console.log(ConsoleHelper.generateSuccess(Config.componentSamplesFinished, true));
});

gulp.task('ComponentSamples-updated', ComponentSamplesTasks, function () {
    console.log(ConsoleHelper.generateSuccess(Config.componentSamplesUpdate));
});

//
// Watch Tasks
// ----------------------------------------------------------------------------

// Watches all src fabric components but, builds the samples only
gulp.task('ComponentSamples-watch', ['ComponentSamples'], function () {
    return gulp.watch(Config.paths.componentsPath + '/**/*', Plugins.batch(function (events, done) {
        Plugins.runSequence('ComponentSamples', 'ComponentSamples-updated', done);
    }));
});<|endoftext|>