<commit_before>var Clock;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Clock = (function() {
  function Clock() {
    this.config = {
      age: 25,
      gender: 'male',
      bmi: 25,
      expectancy: 75,
      hue: 195,
      checkcolors: false,
      lightlabels: true,
      smoker: false,
      reverse: false,
      rotate: false,
      rotate_context: 'minute',
      show_labels: true,
      show_percentage: false,
      show_grid: false,
      line_width: 50
    };
    this.contexts_available = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'life', 'century', 'millenium', 'earth'];
    this.contexts_enabled = ['minute', 'hour', 'day', 'week', 'month', 'year', 'life'];
    this.rings = [];
    this.styles = {};
    this.canvas = $('#clock')[0];
    this.ctx = this.canvas.getContext('2d');
    window.clock = this;
  }
  Clock.prototype.initialize = function() {
    if (!this.translated) {
      this.ctx.translate(0.5, 0.5);
      this.translated = true;
    }
    this.loadConfig();
    this.setRings();
    this.calculateExpectancy();
    $('body').live('click', function(e) {
      if (e.target.id === 'options-toggle') {
        return $('#options').toggle();
      } else if (e.target.id.match(/clock$|okay$/ || e.target.nodeName === 'body')) {
        return $('#options').hide();
      } else if (e.target.id === 'reset') {
        if (confirm("Delete saved configuration data for this clock?")) {
          delete window.localStorage['config'];
          return window.location.href = window.location.href;
        }
      }
    });
    $('#clock-options').delegate('input, select', 'change click keyup blur', function() {
      if ($(this).attr('type') === 'range') {
        clock.config[$(this)[0].className] = Math.max(Math.min($(this).val(), $(this).attr('max')), $(this).attr('min'));
      } else if ($(this).attr('type') === 'checkbox') {
        clock.config[$(this)[0].className] = $(this).attr('checked') === 'checked';
      } else if ($(this)[0].nodeName.toLowerCase() === 'select') {
        clock.config[$(this)[0].className] = $(this).val();
      }
      clock.setRings();
      return clock.saveConfig();
    });
    $('#personal-options').delegate('input, select', 'change click keyup blur', function() {
      if ($(this)[0].className.match(/gender|bmi|age|birthday/)) {
        clock.config[$(this)[0].className] = $(this).val().toLowerCase();
      } else if ($(this)[0].className.match(/smoker/)) {
        clock.config['smoker'] = !!$(this).attr('checked');
      }
      clock.calculateExpectancy();
      return clock.saveConfig();
    });
    window.onresize = __bind(function() {
      var margin;
      margin = (window.outerHeight - clock.canvas.height) / 4;
      margin = parseInt(Math.max(margin, 0)) + "px";
      return this.canvas.style.marginTop = margin;
    }, this);
    window.onresize();
    this.setTime('all');
    window.setInterval((__bind(function() {
      return this.setTime('all');
    }, this)), 1000);
    window.setInterval((__bind(function() {
      return this.setTime('minute');
    }, this)), 20);
    return window.setInterval((__bind(function() {
      return this.saveConfig();
    }, this)), 10000);
  };
  Clock.prototype.calculateExpectancy = function() {
    var birthday, current, expectancy;
    current = new Date();
    birthday = new Date(this.config.birthday);
    this.config.age = (current.getTime() - birthday.getTime()) / 86400000 / 365;
    expectancy = {
      'male': 75,
      'female': 80
    }[this.config.gender];
    if (this.config.bmi <= 18) {
      expectancy -= Math.max(18 - this.config.bmi, (18 - this.config.bmi) / 2);
    }
    if (this.config.bmi > 25) {
      expectancy -= Math.min(this.config.bmi - 25, (this.config.bmi - 25) / 2);
    }
    if (this.config.smoker) {
      expectancy -= 10;
    }
    $('.expectancy.output').text(this.config.expectancy = parseInt(expectancy));
    return $('.age.output').text(parseInt(this.config.age * 100) / 100);
  };
  Clock.prototype.loadConfig = function() {
    var config, item, _results;
    try {
      if (window.localStorage['config']) {
        config = JSON.parse(window.localStorage['config']);
      }
    } catch (error) {
      config = false;
    }
    if (config instanceof Object) {
      this.config = config;
      $('#options').hide();
    }
    _results = [];
    for (item in this.config) {
      _results.push($("." + item).length ? $("." + item).attr('type') === 'checkbox' ? $("." + item)[0].checked = !!this.config[item] : $("." + item).val(this.config[item]) : void 0);
    }
    return _results;
  };
  Clock.prototype.saveConfig = function() {
    return window.localStorage['config'] = JSON.stringify(this.config);
  };
  Clock.prototype.setRings = function() {
    var item, _i, _len, _ref, _results;
    _ref = this.contexts_enabled;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      item = _ref[_i];
      if (this.config['reverse'] === true) {
        this.rings[item] = (this.config.line_width * _i) + this.config.line_width;
      } else {
        this.rings[item] = _len * this.config.line_width - this.config.line_width * _i;
      }
      _results.push(this.styles[item] = "hsl(" + this.config.hue + ", 100%, " + (60 - (_i / (_len * 2)) * 100) + "%)");
    }
    return _results;
  };
  Clock.prototype.draw = function(end, context) {
    var radius, start;
    radius = this.rings[context];
    this.ctx.beginPath();
    this.ctx.lineWidth = this.config.line_width + 2;
    this.ctx.strokeStyle = this.styles[context];
    start = Math.PI * 1.5;
    end -= 15;
    end /= 60;
    end *= Math.PI * 2;
    this.ctx.arc(this.canvas.width / 2, this.canvas.height / 2, radius, end, start, true);
    this.ctx.stroke();
    return this.ctx.closePath();
  };
  Clock.prototype.drawText = function() {
    var font_size, item, line, percent, text, x, x_offset, y, y_offset, _results;
    font_size = 15;
    this.ctx.font = "bold " + (font_size - 2) + "px arial";
    x_offset = 5;
    y_offset = font_size;
    _results = [];
    for (item in this.rings) {
      percent = parseInt((this.styles[item].split(' ')[this.styles[item].split(' ').length - 1]).split(')')[0]);
      if (this.config.lightlabels) {
        this.ctx.fillStyle = 'white';
      } else {
        this.ctx.fillStyle = 'black';
      }
      text = [];
      if (this.config.show_percentage) {
        text.push("" + (parseInt(clock[item] / 60 * 100)) + "%");
      }
      if (this.config.show_labels) {
        text.push(item);
      }
      _results.push((function() {
        var _i, _len, _results2;
        _results2 = [];
        for (_i = 0, _len = text.length; _i < _len; _i++) {
          line = text[_i];
          y = (this.canvas.height / 2 - this.rings[item] + y_offset / (3 - text.length)) - (_i * font_size);
          x = this.canvas.width / 2 + x_offset;
          _results2.push(this.ctx.fillText(line, x, y));
        }
        return _results2;
      }).call(this));
    }
    return _results;
  };
  Clock.prototype.drawGrid = function() {
    this.ctx.beginPath();
    this.ctx.lineWidth = 1;
    this.ctx.strokeStyle = 'rgba(0,0,0,.6)';
    if (this.config.show_grid) {
      this.ctx.moveTo(this.canvas.width / 2, 0);
      this.ctx.lineTo(this.canvas.width / 2, this.canvas.height);
      this.ctx.moveTo(0, this.canvas.height / 2);
      this.ctx.lineTo(this.canvas.width, this.canvas.height / 2);
    } else {
      this.ctx.moveTo(this.canvas.width / 2, 0);
      this.ctx.lineTo(this.canvas.width / 2, this.canvas.height / 2);
    }
    this.ctx.stroke();
    return this.ctx.closePath();
  };
  Clock.prototype.changeColors = function() {
    if (!this.config.changecolors) {
      return false;
    }
    clock.config.hue += .01;
    clock.setRings();
    if (clock.config.hue >= 359.99) {
      return clock.config.hue = 0;
    }
  };
  Clock.prototype.rotateClock = function(context) {
    var rotate;
    if (context == null) {
      context = 'all';
    }
    if (!this.config.rotate) {
      $('body').removeClass('rotating');
      rotate = 0;
    } else {
      rotate = -parseInt(clock[this.config.rotate_context] * 6 * 1000) / 1000;
      $('body').addClass('rotating');
    }
    return $('#clock').css({
      '-webkit-transform': "rotate(" + rotate + "deg)",
      '-moz-transform': "rotate(" + rotate + "deg)"
    });
  };
  Clock.prototype.drawClock = function(context) {
    var item, _i, _len, _ref;
    if (context == null) {
      context = 'all';
    }
    this.ctx.fillStyle = 'black';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    _ref = this.contexts_enabled;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      item = _ref[_i];
      if (item === context || 'all') {
        this.draw(clock[item], item);
      }
    }
    if (this.minute > 60) {
      this.minute = 0;
    }
    this.drawGrid(context);
    this.drawText();
    return this.rotateClock(context);
  };
  Clock.prototype.setTime = function(context) {
    var d, d2;
    if (context == null) {
      context = 'all';
    }
    d = new Date();
    d2 = new Date(d.getFullYear(), 0, 1);
    if (context === 'second' || 'all') {
      this.second = ((new Date()).getMilliseconds() / 1000) * 60;
    }
    if (context === 'minute') {
      this.minute = d.getSeconds() + (parseInt(d.getTime() / 10) % parseInt(d.getTime() / 1000)) / 100;
    }
    if (context === 'hour' || 'all') {
      this.hour = d.getMinutes() + (this.minute / 60);
    }
    if (context === 'day' || 'all') {
      this.day = (d.getHours() + (this.hour / 60)) / 24 * 60;
    }
    if (context === 'week' || 'all') {
      this.week = ((d.getDay() - d.getHours() / 24) / 7) * 60;
    }
    if (context === 'month' || 'all') {
      this.month = (d.getDate() / (32 - new Date(d.getYear(), d.getMonth(), 32).getDate())) * 60 - (1 - this.day / 60);
    }
    if (context === 'year' || 'all') {
      this.year = (Math.ceil((d - d2) / 86400000) + this.day / 60) / 365 * 60;
    }
    if (context === 'decade' || 'all') {
      this.decade = (d.getYear() % 10 + ((Math.ceil((d - d2) / 86400000)) / 365) + this.hour / 60 / 365) / 10 * 60;
    }
    if (context === 'life' || 'all') {
      this.life = ((this.config.age * 365 * 24 + (Math.ceil((d - d2) / 86400000)) + this.hour / 60) / (this.config.expectancy * 365 * 24)) * 60;
      if (this.life === 60) {
        $('.age').val(this.config.age = 1);
      }
    }
    if (context === 'century' || 'all') {
      this.century = (((new Date()).getFullYear() % 100) / 100) * 60;
    }
    if (context === 'millenium' || 'all') {
      this.millenium = (((new Date()).getFullYear() % 1000) / 1000) * 60;
    }
    if (context === 'earth' || 'all') {
      this.earth = ((4570000000 + (new Date()).getTime() / 30000000000) / 10000000000) * 60;
    }
    this.drawClock(context);
    if (context === 'all') {
      return this.changeColors();
    }
  };
  return Clock;
})();<commit_msg>Update clock.js<commit_after>var Clock;

Clock = (function() {

  function Clock() {
    this.config = {
      age: 25,
      gender: 'male',
      bmi: 25,
      expectancy: 75,
      hue: 195,
      checkcolors: false,
      lightlabels: true,
      smoker: false,
      reverse: false,
      rotate: false,
      rotate_context: 'minute',
      show_labels: true,
      show_percentage: false,
      show_grid: false,
      line_width: 50
    };
    this.contexts_available = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'life', 'century', 'millenium', 'earth'];
    this.contexts_enabled = ['minute', 'hour', 'day', 'week', 'month', 'year', 'life'];
    this.rings = [];
    this.styles = {};
    this.canvas = $('#clock')[0];
    this.ctx = this.canvas.getContext('2d');
    window.clock = this;
  }

  Clock.prototype.initialize = function() {
    var _this = this;
    if (!this.translated) {
      this.ctx.translate(0.5, 0.5);
      this.translated = true;
    }
    this.loadConfig();
    this.setRings();
    this.calculateExpectancy();
    $('body').live('click', function(e) {
      if (e.target.id === 'options-toggle') {
        return $('#options').toggle();
      } else if (e.target.id.match(/clock$|okay$/ || e.target.nodeName === 'body')) {
        return $('#options').hide();
      } else if (e.target.id === 'reset') {
        if (confirm("Delete saved configuration data for this clock?")) {
          delete window.localStorage['config'];
          return window.location.href = window.location.href;
        }
      }
    });
    $('#clock-options').delegate('input, select', 'change click keyup blur', function() {
      if ($(this).attr('type') === 'range') {
        clock.config[$(this)[0].className] = Math.max(Math.min($(this).val(), $(this).attr('max')), $(this).attr('min'));
      } else if ($(this).attr('type') === 'checkbox') {
        clock.config[$(this)[0].className] = $(this).attr('checked') === 'checked';
      } else if ($(this)[0].nodeName.toLowerCase() === 'select') {
        clock.config[$(this)[0].className] = $(this).val();
      }
      clock.setRings();
      return clock.saveConfig();
    });
    $('#personal-options').delegate('input, select', 'change click keyup blur', function() {
      if ($(this)[0].className.match(/gender|bmi|age|birthday/)) {
        clock.config[$(this)[0].className] = $(this).val().toLowerCase();
      } else if ($(this)[0].className.match(/smoker/)) {
        clock.config['smoker'] = !!$(this).attr('checked');
      }
      clock.calculateExpectancy();
      return clock.saveConfig();
    });
    window.onresize = function() {
      var margin;
      margin = (window.outerHeight - clock.canvas.height) / 4;
      margin = parseInt(Math.max(margin, 0)) + "px";
      return _this.canvas.style.marginTop = margin;
    };
    window.onresize();
    this.setTime('all');
    window.setInterval((function() {
      return _this.setTime('all');
    }), 1000);
    window.setInterval((function() {
      return _this.setTime('minute');
    }), 100);
    return window.setInterval((function() {
      return _this.saveConfig();
    }), 10000);
  };

  Clock.prototype.calculateExpectancy = function() {
    var birthday, current, expectancy;
    current = new Date();
    birthday = new Date(this.config.birthday);
    this.config.age = (current.getTime() - birthday.getTime()) / 86400000 / 365;
    expectancy = {
      'male': 75,
      'female': 80
    }[this.config.gender];
    if (this.config.bmi <= 18) {
      expectancy -= Math.max(18 - this.config.bmi, (18 - this.config.bmi) / 2);
    }
    if (this.config.bmi > 25) {
      expectancy -= Math.min(this.config.bmi - 25, (this.config.bmi - 25) / 2);
    }
    if (this.config.smoker) {
      expectancy -= 10;
    }
    $('.expectancy.output').text(this.config.expectancy = parseInt(expectancy));
    return $('.age.output').text(parseInt(this.config.age * 100) / 100);
  };

  Clock.prototype.loadConfig = function() {
    var config, item, _results;
    try {
      if (window.localStorage['config']) {
        config = JSON.parse(window.localStorage['config']);
      }
    } catch (error) {
      config = false;
    }
    if (config instanceof Object) {
      this.config = config;
      $('#options').hide();
    }
    _results = [];
    for (item in this.config) {
      if ($("." + item).length) {
        if ($("." + item).attr('type') === 'checkbox') {
          _results.push($("." + item)[0].checked = !!this.config[item]);
        } else {
          _results.push($("." + item).val(this.config[item]));
        }
      } else {
        _results.push(void 0);
      }
    }
    return _results;
  };

  Clock.prototype.saveConfig = function() {
    return window.localStorage['config'] = JSON.stringify(this.config);
  };

  Clock.prototype.setRings = function() {
    var item, _i, _len, _ref, _results;
    _ref = this.contexts_enabled;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      item = _ref[_i];
      if (this.config['reverse'] === true) {
        this.rings[item] = (this.config.line_width * _i) + this.config.line_width;
      } else {
        this.rings[item] = _len * this.config.line_width - this.config.line_width * _i;
      }
      _results.push(this.styles[item] = "hsl(" + this.config.hue + ", 100%, " + (60 - (_i / (_len * 2)) * 100) + "%)");
    }
    return _results;
  };

  Clock.prototype.draw = function(end, context) {
    var radius, start;
    radius = this.rings[context];
    this.ctx.beginPath();
    this.ctx.lineWidth = this.config.line_width + 2;
    this.ctx.strokeStyle = this.styles[context];
    start = Math.PI * 1.5;
    end -= 15;
    end /= 60;
    end *= Math.PI * 2;
    this.ctx.arc(this.canvas.width / 2, this.canvas.height / 2, radius, end, start, true);
    this.ctx.stroke();
    return this.ctx.closePath();
  };

  Clock.prototype.drawText = function() {
    var font_size, item, line, percent, text, x, x_offset, y, y_offset, _results;
    font_size = 15;
    this.ctx.font = "bold " + (font_size - 2) + "px arial";
    x_offset = 5;
    y_offset = font_size;
    _results = [];
    for (item in this.rings) {
      percent = parseInt((this.styles[item].split(' ')[this.styles[item].split(' ').length - 1]).split(')')[0]);
      if (this.config.lightlabels) {
        this.ctx.fillStyle = 'white';
      } else {
        this.ctx.fillStyle = 'black';
      }
      text = [];
      if (this.config.show_percentage) {
        text.push("" + (parseInt(clock[item] / 60 * 100)) + "%");
      }
      if (this.config.show_labels) {
        text.push(item);
      }
      _results.push((function() {
        var _i, _len, _results1;
        _results1 = [];
        for (_i = 0, _len = text.length; _i < _len; _i++) {
          line = text[_i];
          y = (this.canvas.height / 2 - this.rings[item] + y_offset / (3 - text.length)) - (_i * font_size);
          x = this.canvas.width / 2 + x_offset;
          _results1.push(this.ctx.fillText(line, x, y));
        }
        return _results1;
      }).call(this));
    }
    return _results;
  };

  Clock.prototype.drawGrid = function() {
    this.ctx.beginPath();
    this.ctx.lineWidth = 1;
    this.ctx.strokeStyle = 'rgba(0,0,0,.6)';
    if (this.config.show_grid) {
      this.ctx.moveTo(this.canvas.width / 2, 0);
      this.ctx.lineTo(this.canvas.width / 2, this.canvas.height);
      this.ctx.moveTo(0, this.canvas.height / 2);
      this.ctx.lineTo(this.canvas.width, this.canvas.height / 2);
    } else {
      this.ctx.moveTo(this.canvas.width / 2, 0);
      this.ctx.lineTo(this.canvas.width / 2, this.canvas.height / 2);
    }
    this.ctx.stroke();
    return this.ctx.closePath();
  };

  Clock.prototype.changeColors = function() {
    if (!this.config.changecolors) {
      return false;
    }
    clock.config.hue += .01;
    clock.setRings();
    if (clock.config.hue >= 359.99) {
      return clock.config.hue = 0;
    }
  };

  Clock.prototype.rotateClock = function(context) {
    var rotate;
    if (context == null) {
      context = 'all';
    }
    if (!this.config.rotate) {
      $('body').removeClass('rotating');
      rotate = 0;
    } else {
      rotate = -parseInt(clock[this.config.rotate_context] * 6 * 1000) / 1000;
      $('body').addClass('rotating');
    }
    return $('#clock').css({
      '-webkit-transform': "rotate(" + rotate + "deg)",
      '-moz-transform': "rotate(" + rotate + "deg)"
    });
  };

  Clock.prototype.drawClock = function(context) {
    var item, _i, _len, _ref;
    if (context == null) {
      context = 'all';
    }
    this.ctx.fillStyle = 'black';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    _ref = this.contexts_enabled;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      item = _ref[_i];
      if (item === context || 'all') {
        this.draw(clock[item], item);
      }
    }
    if (this.minute > 60) {
      this.minute = 0;
    }
    this.drawGrid(context);
    this.drawText();
    return this.rotateClock(context);
  };

  Clock.prototype.setTime = function(context) {
    var d, d2;
    if (context == null) {
      context = 'all';
    }
    d = new Date();
    if (context === 'minute') {
      this.minute = d.getSeconds() + (parseInt(d.getTime() / 10) % parseInt(d.getTime() / 1000)) / 100;
    } else {
      d2 = new Date(d.getFullYear(), 0, 1);
      this.second = ((new Date()).getMilliseconds() / 1000) * 60;
      this.hour = d.getMinutes() + (this.minute / 60);
      this.day = (d.getHours() + (this.hour / 60)) / 24 * 60;
      this.week = ((d.getDay() - d.getHours() / 24) / 7) * 60;
      this.month = (d.getDate() / (32 - new Date(d.getYear(), d.getMonth(), 32).getDate())) * 60 - (1 - this.day / 60);
      this.year = (Math.ceil((d - d2) / 86400000) + this.day / 60) / 365 * 60;
      this.decade = (d.getYear() % 10 + ((Math.ceil((d - d2) / 86400000)) / 365) + this.hour / 60 / 365) / 10 * 60;
      this.life = ((this.config.age * 365 * 24 + (Math.ceil((d - d2) / 86400000)) + this.hour / 60) / (this.config.expectancy * 365 * 24)) * 60;
      if (this.life === 60) {
        $('.age').val(this.config.age = 1);
      }
      this.century = (((new Date()).getFullYear() % 100) / 100) * 60;
      this.millenium = (((new Date()).getFullYear() % 1000) / 1000) * 60;
      this.earth = ((4570000000 + (new Date()).getTime() / 30000000000) / 10000000000) * 60;
    }
    this.drawClock(context);
    if (context === 'all') {
      return this.changeColors();
    }
  };

  return Clock;

})();
<|endoftext|>


<commit_before><commit_msg>removed more out commented code<commit_after><|endoftext|>


<commit_before>//     furkan.js 0.1.6

//     (c) 2014-fuckin' ever Eray Arslan
//     furkan(person) may be freely distributed under the MIT license.
//     For all details and documentation:
//     (README.md)

(function(root, factory) {

    if(typeof define === 'function' && define.amd) {

        define(['exports'], function(exports) {
            root.Furkan = factory(root, exports);
        });

    } else if (typeof exports !== 'undefined') {

        factory(root, exports);

    } else {

        root.Furkan = factory(root, {});

    }

}(this, function(root, Furkan) {

    var BAD_ASS = "hi";

    Furkan.VERSION = "0.1.6";

    Furkan.NAME = "Furkan";

    Furkan.ERAY = "fuckin\'";

    Furkan.YES = 1;

    Furkan.NO = 0;

    Furkan.ARRAY = [];

    Furkan.SPACE = " ";

    Furkan.LIP = ":*";

    Furkan.HAPPY = 0;

    Furkan.HOME = "http://wzzp.in:31";

    Furkan.RELATIONSHIP = "Single";

    Furkan.SELFIE = undefined;

    Furkan.kiss = function() {
        this.HAPPY++;
        return this.LIP;
    };

    Furkan.love = function() {
        this.HAPPY--;
        throw new Error("No Way Pointer Exception");
    };

    Furkan.whoami = function() {
        return this.NAME;
    };

    Furkan.status = function() {
        return this.RELATIONSHIP;
    };

    Furkan.mood = function() {
        var tempHappy = this.HAPPY;
        if(tempHappy === 0) {
            return this.ERAY;
        } else if(tempHappy>0 && tempHappy<4) {
            return this.LIP;
        } else {
            return BAD_ASS;
        }
    };

    Furkan.say = function(text) {
        if(text.toLowerCase() === BAD_ASS) {
            if(this.HAPPY-1!==-1) {
                this.HAPPY--;
            }
            throw new Error(
                    this.NAME+
                    this.SPACE+
                    'dont'+
                    this.SPACE+
                    'apply'+
                    this.SPACE+
                    this.ERAY+
                    this.SPACE+
                    'this'+
                    this.SPACE+
                    'text!'
            );
        }
        return text + this.SPACE + this.NAME;
    };

    Furkan.amicute = function() {
        return this.YES;
    };

    Furkan.addSelfie = function(r) {
        var img = document.createElement('img');
        img.src = r.data.avatar_url;
        this.SELFIE.appendChild(img);

        return undefined;
    };

    Furkan.giffMe = function() {
        for (var name in window) {
            if (window[name] === this) {
                return name;
            }
        }

        return undefined;
    };

    Furkan.jsonP = function(url) {
        var script = document.createElement('script');
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    };

    Furkan.service = function(data, service) {
        return (data+" "+service);
    };

    Furkan.call = function(service) {
        this.jsonP(this.HOME+"/?callback="+this.giffMe()+".service&service="+service);
        return undefined;
    };

    Furkan.show = function(n) {
        this.SELFIE = n;
        this.jsonP('https://api.github.com/users/frknbasaran?callback='+this.giffMe()+'.addSelfie');

        this.HAPPY++;this.HAPPY++;this.HAPPY++;

        return undefined;
    };

    Furkan["1337"] = function() {
        return "Furk4n";
    };

    var Dolly = function () {
        var options, src, copy, copyIsArray, clone;
        var target = arguments[0] || {};
        var i = 1;
        var length = arguments.length;
        var deep = false;

        if ( typeof target === "boolean" ) {
            deep = target;
            target = arguments[ i ] || {};
            i++;
        }
        if ( typeof target !== "object" && Object.prototype.toString.call( target ) !== '[object Function]' ) {
            target = {};
        }
        if ( i === length ) {
            target = this;
            i--;
        }
        for ( ; i < length; i++ ) {
            if ( (options = arguments[ i ]) !== null ) {
                for (var name in options ) {
                    src = target[ name ];
                    copy = options[ name ];
                    if ( target === copy ) {
                        continue;
                    }
                    if ( deep && copy && ( (copy.toString()==="[object Object]") ||
                        (copyIsArray = (Object.prototype.toString.call( copy ) === '[object Array]')) ) ) {
                        if ( copyIsArray ) {
                            copyIsArray = false;
                            clone = src && (Object.prototype.toString.call( src ) === '[object Array]') ? src : [];

                        } else {
                            clone = src && (src.toString()==="[object Object]") ? src : {};
                        }
                        target[ name ] = new Dolly( deep, clone, copy );
                    } else if ( copy !== undefined ) {
                        target[ name ] = copy;
                    }
                }
            }
        } return target;
    };

    Furkan.extend = function(args) {
        this.HAPPY--;
        return new Dolly(true,new Dolly(true, {}, Furkan),args);
    };

    return Furkan;

}));
<commit_msg>RELATIONSHIP Updated<commit_after>//     furkan.js 0.1.6

//     (c) 2014-fuckin' ever Eray Arslan
//     furkan(person) may be freely distributed under the MIT license.
//     For all details and documentation:
//     (README.md)

(function(root, factory) {

    if(typeof define === 'function' && define.amd) {

        define(['exports'], function(exports) {
            root.Furkan = factory(root, exports);
        });

    } else if (typeof exports !== 'undefined') {

        factory(root, exports);

    } else {

        root.Furkan = factory(root, {});

    }

}(this, function(root, Furkan) {

    var BAD_ASS = "hi";

    Furkan.VERSION = "0.1.6";

    Furkan.NAME = "Furkan";

    Furkan.ERAY = "fuckin\'";

    Furkan.YES = 1;

    Furkan.NO = 0;

    Furkan.ARRAY = [];

    Furkan.SPACE = " ";

    Furkan.LIP = ":*";

    Furkan.HAPPY = 0;

    Furkan.HOME = "http://wzzp.in:31";

    Furkan.RELATIONSHIP = "Çıktığı Var";

    Furkan.SELFIE = undefined;

    Furkan.kiss = function() {
        this.HAPPY++;
        return this.LIP;
    };

    Furkan.love = function() {
        this.HAPPY--;
        throw new Error("No Way Pointer Exception");
    };

    Furkan.whoami = function() {
        return this.NAME;
    };

    Furkan.status = function() {
        return this.RELATIONSHIP;
    };

    Furkan.mood = function() {
        var tempHappy = this.HAPPY;
        if(tempHappy === 0) {
            return this.ERAY;
        } else if(tempHappy>0 && tempHappy<4) {
            return this.LIP;
        } else {
            return BAD_ASS;
        }
    };

    Furkan.say = function(text) {
        if(text.toLowerCase() === BAD_ASS) {
            if(this.HAPPY-1!==-1) {
                this.HAPPY--;
            }
            throw new Error(
                    this.NAME+
                    this.SPACE+
                    'dont'+
                    this.SPACE+
                    'apply'+
                    this.SPACE+
                    this.ERAY+
                    this.SPACE+
                    'this'+
                    this.SPACE+
                    'text!'
            );
        }
        return text + this.SPACE + this.NAME;
    };

    Furkan.amicute = function() {
        return this.YES;
    };

    Furkan.addSelfie = function(r) {
        var img = document.createElement('img');
        img.src = r.data.avatar_url;
        this.SELFIE.appendChild(img);

        return undefined;
    };

    Furkan.giffMe = function() {
        for (var name in window) {
            if (window[name] === this) {
                return name;
            }
        }

        return undefined;
    };

    Furkan.jsonP = function(url) {
        var script = document.createElement('script');
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    };

    Furkan.service = function(data, service) {
        return (data+" "+service);
    };

    Furkan.call = function(service) {
        this.jsonP(this.HOME+"/?callback="+this.giffMe()+".service&service="+service);
        return undefined;
    };

    Furkan.show = function(n) {
        this.SELFIE = n;
        this.jsonP('https://api.github.com/users/frknbasaran?callback='+this.giffMe()+'.addSelfie');

        this.HAPPY++;this.HAPPY++;this.HAPPY++;

        return undefined;
    };

    Furkan["1337"] = function() {
        return "Furk4n";
    };

    var Dolly = function () {
        var options, src, copy, copyIsArray, clone;
        var target = arguments[0] || {};
        var i = 1;
        var length = arguments.length;
        var deep = false;

        if ( typeof target === "boolean" ) {
            deep = target;
            target = arguments[ i ] || {};
            i++;
        }
        if ( typeof target !== "object" && Object.prototype.toString.call( target ) !== '[object Function]' ) {
            target = {};
        }
        if ( i === length ) {
            target = this;
            i--;
        }
        for ( ; i < length; i++ ) {
            if ( (options = arguments[ i ]) !== null ) {
                for (var name in options ) {
                    src = target[ name ];
                    copy = options[ name ];
                    if ( target === copy ) {
                        continue;
                    }
                    if ( deep && copy && ( (copy.toString()==="[object Object]") ||
                        (copyIsArray = (Object.prototype.toString.call( copy ) === '[object Array]')) ) ) {
                        if ( copyIsArray ) {
                            copyIsArray = false;
                            clone = src && (Object.prototype.toString.call( src ) === '[object Array]') ? src : [];

                        } else {
                            clone = src && (src.toString()==="[object Object]") ? src : {};
                        }
                        target[ name ] = new Dolly( deep, clone, copy );
                    } else if ( copy !== undefined ) {
                        target[ name ] = copy;
                    }
                }
            }
        } return target;
    };

    Furkan.extend = function(args) {
        this.HAPPY--;
        return new Dolly(true,new Dolly(true, {}, Furkan),args);
    };

    return Furkan;

}));
<|endoftext|>


<commit_before>/*
 * index.js: Top-level include for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    http = require('http'),
    flatiron = require('flatiron'),
    haibu = require('../../haibu'),
    async = haibu.common.async;

//
// ### Include Exports
// Export other components in the module
//
exports.Drone   = require('./drone').Drone;
exports.Client  = require('haibu-api').Client;
exports.started = false;

//
// ### function autostart (server, callback)
// #### @server {http.Server} Haibu drone server to autostart drones with.
// #### @callback {function} Continuation to respond to when complete
// Autostarts drones for all applications persisted to
// `haibu.config.get('directories:autostart')`.
//
exports.autostart = function (server, callback) {
  var autostartDir = haibu.config.get('directories:autostart');

  //
  // Helper function which starts multiple drones
  // a given application.
  //
  function startDrones (pkg, done) {
    if (pkg.drones == 0) {
      return done();
    }

    var started = 0;

    async.whilst(function () {
      return started < pkg.drones;
    }, function (next) {
      started++;
      server.drone.start(pkg, next);
    }, done);
  }

  function startDataSystem (files, drones, cb) {
    dataSytemExist = false
    end = false
    if (files.length != 0) {
      file = files.pop()
      fs.readFile(path.join(autostartDir, file), function (err, pkg) {
        if (err) {
          return cb(err);
        }
        try {
          pkg = JSON.parse(pkg.toString());
        }
        catch (ex) {
          return cb(ex);
        }
        if (pkg.name == 'data-system') {
          dataSytemExist = true
          startDrones(pkg, function() {
            startDataSystem(files, drones, cb)
          });
        } else {
          drones.push(pkg)
          startDataSystem(files, drones, cb);
        }
      })
    } else {
      if (dataSytemExist) {
        setTimeout(function(){
          if (!end) {
            end = true
            cb(drones)
          }
        }, 120000)
        checkApps(['data-system'], function(){
          if (!end){
            end = true
            cb(drones);
          }
        });
      } else {
        cb(drones);
      }
    }
  }

  function check (app, cb) {
    setTimeout(function() {
      if (!haibu.server.drone.apps[app]){
        check(app, cb)
      } else {
        cb(null);
      }
    }, 1000)
  }

  function checkApps (apps, cb){
    if (apps.length != 0) {
      app = apps.pop()
      check(app, function(){
        checkApps(apps, cb);
      })
    } else {
      cb(null);
    }
  }

  function startApps (files) {
    proxyPkg = null
    end = false
    apps= []
    startDataSystem(files, [], function(drones){
      async.map(drones, function (pkg, next) {
        //
        // Read each `package.json` manifest file and start
        // the appropriate drones in this `haibu` instance.
        //
        if (pkg.name == "proxy") {
          proxyPkg = pkg
          next()
        } else {
          apps.push(pkg.name)
          startDrones(pkg, next);
        }
      }, function(err, result) {
        setTimeout(function(){
          if (!end)
            end = true
            if (proxyPkg) {
              startDrones(proxyPkg, callback);
            } else {
              callback()
            }
        }, 300000)
        checkApps(apps, function() {
          if (!end){
            end = true
            if (proxyPkg) {
              startDrones(proxyPkg, callback);
            } else {
              callback()
            }
          }
        });
      });
    });
  }

  //
  // Find all drones in directory:
  //   %dir/%sanitized_name.json
  //
  fs.readdir(autostartDir, function (err, files) {
    if (err) {
      return callback(err);
    }
    startApps(files)
  });
}

//
// ### function start (options, callback)
// #### @options {Object} Options to use when starting this module.
// #### @callback {function} Continuation to respond to when complete.
// Starts the haibu `drone` webservice with the specified options.
//
exports.start = function (options, callback) {
  if (exports.started) {
    return callback(null, haibu.running.server);
  }

  function tryAutostart (server) {
    exports.autostart(server, function (err) {
      //
      // Ignore errors from autostart and continue
      // bringing up the haibu `drone` server.
      //
      // Remark: We should report the `err` somewhere
      //
      haibu.emit('start');
      callback(null, server);
    });
  }

  function startServer (err) {
    if (err) {
      return callback(err);
    }

    //
    // Create the server and add the new `http.Server`
    // and `haibu.drone.Drone` instance into the `haibu.running`
    // namespace.
    //
    var drone = new haibu.drone.Drone(options);

    //
    // Setup the `union` server through `flatiron.plugins.http`
    // and then add routes.
    //
    haibu.use(flatiron.plugins.http, options.http || {});
    require('./service').createRouter(drone);

    if (options.port) {
      haibu.listen(options.port);
    }

    haibu.running.server = haibu.server;
    haibu.running.drone  = haibu.server.drone = drone;
    haibu.running.ports  = {};

    //
    // There is a current bug in node that throws here:
    //
    // https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L159
    //
    // It will throw a broken pipe error (EPIPE) when a child process that you
    // are piping to unexpectedly exits. The write function on line 159 is
    // defined here:
    //
    // https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L62
    //
    // This uncaughtExceptionHandler will catch that error,
    // and since it originated with in another sync context,
    // this section will still respond to the request.
    //
    haibu.plugins.exceptions.logger.exitOnError = function (err) {
      if (err.code === 'EPIPE') {
        console.log('expected error:');
        console.log('EPIPE -- probabaly caused by someone pushing a non gzip file.');
        console.log('"net" throws on a broken pipe, current node bug, not haibu.');
        return false;
      }

      return true;
    };

    //
    // Attempt to autostart any applications and respond.
    //
    tryAutostart(haibu.server);
  }

  //
  // Indicate that `haibu.drone` has started
  //
  exports.started = true;

  return haibu.initialized
    ? startServer()
    : haibu.init(options, startServer);
};

//
// ### function stop (callback)
// #### @cleanup {bool} (optional) Remove all autostart files (default=true).
// #### @callback {function} Continuation to respond to when complete.
// Gracefully stops `drone` instance
//
exports.stop = function (cleanup, callback) {
  if (!callback && typeof cleanup === 'function') {
    callback = cleanup;
    cleanup = true;
  }

  if (!exports.started) {
    return callback ? callback() : null;
  }

  exports.started = false;
  haibu.running.server.close();

  // Terminate drones
  haibu.running.drone.destroy(cleanup, callback || function () {});
  haibu.running = {};
};<commit_msg>debug test existence of DS<commit_after>/*
 * index.js: Top-level include for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    http = require('http'),
    flatiron = require('flatiron'),
    haibu = require('../../haibu'),
    async = haibu.common.async;

//
// ### Include Exports
// Export other components in the module
//
exports.Drone   = require('./drone').Drone;
exports.Client  = require('haibu-api').Client;
exports.started = false;

//
// ### function autostart (server, callback)
// #### @server {http.Server} Haibu drone server to autostart drones with.
// #### @callback {function} Continuation to respond to when complete
// Autostarts drones for all applications persisted to
// `haibu.config.get('directories:autostart')`.
//
exports.autostart = function (server, callback) {
  var autostartDir = haibu.config.get('directories:autostart');

  //
  // Helper function which starts multiple drones
  // a given application.
  //
  function startDrones (pkg, done) {
    if (pkg.drones == 0) {
      return done();
    }

    var started = 0;

    async.whilst(function () {
      return started < pkg.drones;
    }, function (next) {
      started++;
      server.drone.start(pkg, next);
    }, done);
  }

  dataSytemExist = false
  endDS = false
  function startDataSystem (files, drones, cb) {
    if (files.length != 0) {
      file = files.pop()
      fs.readFile(path.join(autostartDir, file), function (err, pkg) {
        if (err) {
          return cb(err);
        }
        try {
          pkg = JSON.parse(pkg.toString());
        }
        catch (ex) {
          return cb(ex);
        }
        if (pkg.name == 'data-system') {
          dataSytemExist = true
          startDrones(pkg, function() {
            startDataSystem(files, drones, cb)
          });
        } else {
          drones.push(pkg)
          startDataSystem(files, drones, cb);
        }
      })
    } else {
      if (dataSytemExist) {
        setTimeout(function(){
          if (!endDS) {
            endDS = true
            cb(drones)
          }
        }, 120000)
        checkApps(['data-system'], function(){
          if (!endDS){
            endDS = true
            cb(drones);
          }
        });
      } else {
        cb(drones);
      }
    }
  }

  function check (app, cb) {
    setTimeout(function() {
      if (!haibu.server.drone.apps[app]){
        check(app, cb)
      } else {
        cb(null);
      }
    }, 1000)
  }

  function checkApps (apps, cb){
    if (apps.length != 0) {
      app = apps.pop()
      check(app, function(){
        checkApps(apps, cb);
      })
    } else {
      cb(null);
    }
  }

  function startApps (files) {
    proxyPkg = null
    end = false
    apps= []
    startDataSystem(files, [], function(drones){
      async.map(drones, function (pkg, next) {
        //
        // Read each `package.json` manifest file and start
        // the appropriate drones in this `haibu` instance.
        //
        if (pkg.name == "proxy") {
          proxyPkg = pkg
          next()
        } else {
          apps.push(pkg.name)
          startDrones(pkg, next);
        }
      }, function(err, result) {
        setTimeout(function(){
          if (!end)
            end = true
            if (proxyPkg) {
              startDrones(proxyPkg, callback);
            } else {
              callback()
            }
        }, 300000)
        checkApps(apps, function() {
          if (!end){
            end = true
            if (proxyPkg) {
              startDrones(proxyPkg, callback);
            } else {
              callback()
            }
          }
        });
      });
    });
  }

  //
  // Find all drones in directory:
  //   %dir/%sanitized_name.json
  //
  fs.readdir(autostartDir, function (err, files) {
    if (err) {
      return callback(err);
    }
    startApps(files)
  });
}

//
// ### function start (options, callback)
// #### @options {Object} Options to use when starting this module.
// #### @callback {function} Continuation to respond to when complete.
// Starts the haibu `drone` webservice with the specified options.
//
exports.start = function (options, callback) {
  if (exports.started) {
    return callback(null, haibu.running.server);
  }

  function tryAutostart (server) {
    exports.autostart(server, function (err) {
      //
      // Ignore errors from autostart and continue
      // bringing up the haibu `drone` server.
      //
      // Remark: We should report the `err` somewhere
      //
      haibu.emit('start');
      callback(null, server);
    });
  }

  function startServer (err) {
    if (err) {
      return callback(err);
    }

    //
    // Create the server and add the new `http.Server`
    // and `haibu.drone.Drone` instance into the `haibu.running`
    // namespace.
    //
    var drone = new haibu.drone.Drone(options);

    //
    // Setup the `union` server through `flatiron.plugins.http`
    // and then add routes.
    //
    haibu.use(flatiron.plugins.http, options.http || {});
    require('./service').createRouter(drone);

    if (options.port) {
      haibu.listen(options.port);
    }

    haibu.running.server = haibu.server;
    haibu.running.drone  = haibu.server.drone = drone;
    haibu.running.ports  = {};

    //
    // There is a current bug in node that throws here:
    //
    // https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L159
    //
    // It will throw a broken pipe error (EPIPE) when a child process that you
    // are piping to unexpectedly exits. The write function on line 159 is
    // defined here:
    //
    // https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L62
    //
    // This uncaughtExceptionHandler will catch that error,
    // and since it originated with in another sync context,
    // this section will still respond to the request.
    //
    haibu.plugins.exceptions.logger.exitOnError = function (err) {
      if (err.code === 'EPIPE') {
        console.log('expected error:');
        console.log('EPIPE -- probabaly caused by someone pushing a non gzip file.');
        console.log('"net" throws on a broken pipe, current node bug, not haibu.');
        return false;
      }

      return true;
    };

    //
    // Attempt to autostart any applications and respond.
    //
    tryAutostart(haibu.server);
  }

  //
  // Indicate that `haibu.drone` has started
  //
  exports.started = true;

  return haibu.initialized
    ? startServer()
    : haibu.init(options, startServer);
};

//
// ### function stop (callback)
// #### @cleanup {bool} (optional) Remove all autostart files (default=true).
// #### @callback {function} Continuation to respond to when complete.
// Gracefully stops `drone` instance
//
exports.stop = function (cleanup, callback) {
  if (!callback && typeof cleanup === 'function') {
    callback = cleanup;
    cleanup = true;
  }

  if (!exports.started) {
    return callback ? callback() : null;
  }

  exports.started = false;
  haibu.running.server.close();

  // Terminate drones
  haibu.running.drone.destroy(cleanup, callback || function () {});
  haibu.running = {};
};<|endoftext|>


<commit_before>/**
 * Created by kribh03 on 17-Jun-16.
 */
<commit_msg>Delete CheckBoxDirective.js<commit_after><|endoftext|>


<commit_before>ko.bindingHandlers.min =
{
	update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var min = ko.unwrap(valueAccessor());
		var max = allBindings.get('max');
		var value = $(element).val();

		if(max != undefined && max < min)
		{
			min = max;
		}

		if(value < min)
		{
			// We need to call change() after updating the value in order for knockoutjs to
			// update its observables
			$(element).val(min).change();
		}
		else
		{
			// We need to call change() in order for knockoutjs to
			// update its observables
			$(element).change();
		}

		element.min = min;
	}
};

ko.bindingHandlers.max =
{
	update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var max = ko.unwrap(valueAccessor());
		var min = allBindings.get('min');
		var value = $(element).val();

		if(min != undefined && max < min)
		{
			max = min;
		}

		if(value > max)
		{
			// We need to call change() after updating the value in order for knockoutjs to
			// update its observables
			$(element).val(max).change();
		}
		else
		{
			// We need to call change() in order for knockoutjs to
			// update its observables
			$(element).change();
		}

		element.max = max;
	}
};

ko.bindingHandlers.commandConsoleKeyActions =
{
	init: function(element, valueAccessor, allBindingsAccessor, viewModel)
	{
		$(element).keyup(function(e)
		{
			if(e.which === 13)
			{
				// Return key
				viewModel.sendCommand();
			}
			else if(e.which === 38)
			{
				// Up Arrow
				viewModel.previousCommand();
			}
			else if(e.which === 40)
			{
				// Down Arrow
				viewModel.nextCommand();
			}
		});
	}
};

function Joint(data, viewModel)
{
	var self = this;
	self.viewModel = viewModel;

	self.title = data.title;
	self.jointNumber = ko.observable(data.jointNumber);
	self.inputId = ko.computed(function()
	{
		return self.title.toLowerCase() + "-angle";
	});

	self.min = ko.observable(data.min);
	self.max = ko.observable(data.max);
	self.setPoint = ko.observable(data.setPoint);
	self.currentAngle = ko.observable(self.min() - self.max() / 2);
	self.angleError = ko.observable(0);

	self.PGain = ko.observable(1);
	self.IGain = ko.observable(1);
	self.DGain = ko.observable(1);

	// Setpoint received from serial
	self.serialSetPoint = ko.observable((self.setPoint() != 1) ? 1 : 0);
	self.serialSetPoint.subscribe(function()
	{
		self.setPoint(self.serialSetPoint());
	});

	// Subscribe to changes in the setpoint so we can send the updates to the
	// Arduino using the socket
	self.setPoint.subscribe(function()
	{
		if(self.viewModel.enabled())
		{
			if(self.setPoint() != self.serialSetPoint())
			{
				var command = ko.toJSON(
				{
					command: "setJointAngle",
					jointNumber: self.jointNumber(),
					angle: self.setPoint()
				});

				console.log(command);

				self.viewModel.socket.send(command);
			}
		}
		else
		{
			console.log("Manual control disabled.")
		}
	});

	// Use a computed property to update the Arduino whenever any of the gains change
	ko.computed(function()
	{
		if(self.viewModel.enabled() && self.viewModel.PIDTuningEnabled())
		{
			var command = ko.toJSON(
				{
					command: "setJointGains",
					jointNumber: self.jointNumber(),
					PGain: parseFloat(self.PGain()).toPrecision(3),
					IGain: parseFloat(self.IGain()).toPrecision(3),
					DGain: parseFloat(self.DGain()).toPrecision(3)
				});

			console.log(command);

			self.viewModel.socket.send(command);
		}
	});
}

function Command(data)
{
	var self = this;

	self.command = ko.observable(data.command);
	self.response = ko.observable(data.response);
	self.duration = ko.observable(data.duration || 0);
	self.startTime = Date.now();

	self.durationText = ko.computed(function()
	{
		return self.duration() + "ms";
	});
}

function PrometheusViewModel()
{
	// Data
	var self = this;
	self.socket = null;
	//self.socketServer = 'ws://10.33.0.2:8888/';
	self.socketServer = 'ws://localhost:8888/';

	// Enabled Setting
	self.textEnabled = ko.observable("off");
	self.enabled = ko.computed(function()
	{
		return self.textEnabled() == "on" ? true : false;
	});

	// Settings Screen Stuff
	self.Render3DEnabledText = ko.observable("on");
	self.Render3DEnabled = ko.computed(function()
	{
		return self.Render3DEnabledText() == "on" ? true : false;
	});

	self.Rotate3DEnabledText = ko.observable("off");
	self.Rotate3DEnabled = ko.computed(function()
	{
		return self.Rotate3DEnabledText() == "on" ? true : false;
	});

	self.PIDTuningEnabledText = ko.observable("off");
	self.PIDTuningEnabled = ko.computed(function()
	{
		return self.PIDTuningEnabledText() == "on" ? true : false;
	});

	self.CommandConsoleEnabledText = ko.observable("off");
	self.CommandConsoleEnabled = ko.computed(function()
	{
		return self.CommandConsoleEnabledText() == "on" ? true : false;
	});

	// Joints array
	self.joints = ko.observableArray([]);

	// Command Console Data
	self.commandText = ko.observable().extend({ notify: 'always' });
	self.commandHistory = ko.observableArray();
	self.commandPosition = 0;

	// 3D Rendering
	self.init3D = function()
	{
		self.renderer = new RobotArm(self);

		ko.computed(function()
		{
			self.updateRenderer();
		}).extend({throttle: 100});

		self.updateRenderer();
	};

	self.updateRenderer = function()
	{
		if(self.Render3DEnabled())
		{
			self.renderer.init();
		}
	};

	// Socket
	self.initSocket = function()
	{
		self.socket = new WebSocket(self.socketServer);

		self.socket.onopen = function()
		{
			console.log('Socket Connected!');

			for(var i = 0; i < self.joints().length; i++)
			{
				var command = ko.toJSON(
				{
					command: "getJointGains",
					jointNumber: i
				});

				console.log(command);
				self.socket.send(command);

				var command = ko.toJSON(
				{
					command: "getJointLimits",
					jointNumber: i
				});

				console.log(command);
				self.socket.send(command);
			};
		};

		self.socket.onclose = function()
		{
			console.log('Socket connection lost!');
			self.socket.close();
		};

		self.socket.onmessage = function(event)
		{
			self.receiveSocketData(event.data);
		};
	};

	self.receiveSocketData = function(data)
	{
		// We need to figure out what we are going to do with the command
		// console now that we are using a socket instead of ajax requests
		// because we now have to figure out which response belongs to which
		// command.

		console.log("Data from socket: " + data);

		json = null;

		try
		{
			json = $.parseJSON(data);
		}
		catch(exception)
		{
			console.log("Failed to parse data from socket as JSON. Data:");
			console.log(data);
		}

		if(json != null)
		{
			switch(json.command)
			{
				case "armStatus":
					for(var i = 0; i < self.joints().length; i++)
					{
						self.joints()[i].currentAngle(json.currentAngle[i]);
						self.joints()[i].angleError(json.currentError[i]);
					};
					break;

				case "jointAngle":
					self.joints()[json.jointNumber].currentAngle(json.angle);
					break;

				case "jointSetPoint":
					self.joints()[json.jointNumber].serialSetPoint(json.setPoint);
					break;

				case "jointLimits":
					self.joints()[json.jointNumber].min(json.min);
					self.joints()[json.jointNumber].max(json.max);
					break;

				case "jointGains":
					self.joints()[json.jointNumber].PGain(json.PGain);
					self.joints()[json.jointNumber].IGain(json.IGain);
					self.joints()[json.jointNumber].DGain(json.DGain);
					break;

				case "jointError":
					self.joints()[json.jointNumber].angleError(json.error);
					break;
			}
		}
		else
		{
			console.log("Failed to parse data from socket as JSON. Data:");
			console.log(data);
		}
	};

	// Command Console
	self.sendCommand = function()
	{
		var command = self.commandText();
		self.commandText("");

		var commandData = command.split(" ");

		var index = self.commandHistory().length;
		self.commandPosition = index + 1;
		self.commandHistory.push(new Command({"command": command}));

		var allowedCommands = ["setJointGains", "setJointAngle",
			"getJointAngle", "getJointLimits",
			"getJointGains", "getjointError"];

		if($.inArray(commandData[0], allowedCommands) != -1)
		{
			if(!isNaN(Number(commandData[1])))
			{
				commandData[1] = Number(commandData[1]);
			}

			var command = ko.toJSON(
				{
					command: commandData[0],
					jointNumber: commandData[1]
				});

			switch(commandData[0])
			{
				case "setJointGains":
					if(!isNaN(Number(commandData[2])))
					{
						command.PGain = Number(commandData[2]);

						if(!isNaN(Number(commandData[3])))
						{
							command.IGain = Number(commandData[3]);

							if(!isNaN(Number(commandData[4])))
							{
								command.DGain = Number(commandData[4]);

								self.socket.send(command);
							}
						}
					}

					break;

				case "setJointAngle":
					if(!isNaN(Number(commandData[2])))
					{
						command.angle = Number(commandData[2]);

						self.socket.send(command);
					}

					break;

				case "getJointAngle":
				case "getJointLimits":
				case "getJointGains":
				case "getjointError":
					self.socket.send(command);
					break;

				default:
					self.commandHistory()[index].response("Invalid command");
					break;
			}

			console.log("Data Sent: " + command);
		}
		else
		{
			self.commandHistory()[index].response("Invalid command");
		}
	};

	self.previousCommand = function()
	{
		if(self.commandPosition > 0)
		{
			self.commandPosition -= 1;
			self.commandText(self.commandHistory()[self.commandPosition].command());
		}
	};

	self.nextCommand = function()
	{
		if(self.commandPosition == self.commandHistory().length)
		{
			self.commandText("");
		}
		else if(self.commandPosition == self.commandHistory().length -1)
		{
			self.commandPosition += 1;
			self.commandText("");
		}
		else if(self.commandPosition < self.commandHistory().length - 1)
		{
			self.commandPosition += 1;
			self.commandText(self.commandHistory()[self.commandPosition].command());
		}
	};

	// Other
	self.addJoint = function(data)
	{
		self.joints.push(new Joint(data, self));
	};

	self.initSocket();
	self.init3D();
}

var vm = new PrometheusViewModel()

vm.addJoint({
	title: "Base",
	jointNumber: 0,
	min: 0,
	max: 360,
	setPoint: 0
});

vm.addJoint({
	title: "Shoulder",
	jointNumber: 1,
	min: 0,
	max: 180,
	setPoint: 0
});

vm.addJoint({
	title: "Elbow",
	jointNumber: 2,
	min: 180,
	max: 360,
	setPoint: 360
});

vm.addJoint({
	title: "Wrist",
	jointNumber: 3,
	min: 0,
	max: 359,
	setPoint: 180
});

vm.addJoint({
	title: "Hand",
	jointNumber: 4,
	min: 0,
	max: 359,
	setPoint: 180
});

ko.applyBindings(vm);
<commit_msg>Update socket server URL.<commit_after>ko.bindingHandlers.min =
{
	update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var min = ko.unwrap(valueAccessor());
		var max = allBindings.get('max');
		var value = $(element).val();

		if(max != undefined && max < min)
		{
			min = max;
		}

		if(value < min)
		{
			// We need to call change() after updating the value in order for knockoutjs to
			// update its observables
			$(element).val(min).change();
		}
		else
		{
			// We need to call change() in order for knockoutjs to
			// update its observables
			$(element).change();
		}

		element.min = min;
	}
};

ko.bindingHandlers.max =
{
	update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var max = ko.unwrap(valueAccessor());
		var min = allBindings.get('min');
		var value = $(element).val();

		if(min != undefined && max < min)
		{
			max = min;
		}

		if(value > max)
		{
			// We need to call change() after updating the value in order for knockoutjs to
			// update its observables
			$(element).val(max).change();
		}
		else
		{
			// We need to call change() in order for knockoutjs to
			// update its observables
			$(element).change();
		}

		element.max = max;
	}
};

ko.bindingHandlers.commandConsoleKeyActions =
{
	init: function(element, valueAccessor, allBindingsAccessor, viewModel)
	{
		$(element).keyup(function(e)
		{
			if(e.which === 13)
			{
				// Return key
				viewModel.sendCommand();
			}
			else if(e.which === 38)
			{
				// Up Arrow
				viewModel.previousCommand();
			}
			else if(e.which === 40)
			{
				// Down Arrow
				viewModel.nextCommand();
			}
		});
	}
};

function Joint(data, viewModel)
{
	var self = this;
	self.viewModel = viewModel;

	self.title = data.title;
	self.jointNumber = ko.observable(data.jointNumber);
	self.inputId = ko.computed(function()
	{
		return self.title.toLowerCase() + "-angle";
	});

	self.min = ko.observable(data.min);
	self.max = ko.observable(data.max);
	self.setPoint = ko.observable(data.setPoint);
	self.currentAngle = ko.observable(self.min() - self.max() / 2);
	self.angleError = ko.observable(0);

	self.PGain = ko.observable(1);
	self.IGain = ko.observable(1);
	self.DGain = ko.observable(1);

	// Setpoint received from serial
	self.serialSetPoint = ko.observable((self.setPoint() != 1) ? 1 : 0);
	self.serialSetPoint.subscribe(function()
	{
		self.setPoint(self.serialSetPoint());
	});

	// Subscribe to changes in the setpoint so we can send the updates to the
	// Arduino using the socket
	self.setPoint.subscribe(function()
	{
		if(self.viewModel.enabled())
		{
			if(self.setPoint() != self.serialSetPoint())
			{
				var command = ko.toJSON(
				{
					command: "setJointAngle",
					jointNumber: self.jointNumber(),
					angle: self.setPoint()
				});

				console.log(command);

				self.viewModel.socket.send(command);
			}
		}
		else
		{
			console.log("Manual control disabled.")
		}
	});

	// Use a computed property to update the Arduino whenever any of the gains change
	ko.computed(function()
	{
		if(self.viewModel.enabled() && self.viewModel.PIDTuningEnabled())
		{
			var command = ko.toJSON(
				{
					command: "setJointGains",
					jointNumber: self.jointNumber(),
					PGain: parseFloat(self.PGain()).toPrecision(3),
					IGain: parseFloat(self.IGain()).toPrecision(3),
					DGain: parseFloat(self.DGain()).toPrecision(3)
				});

			console.log(command);

			self.viewModel.socket.send(command);
		}
	});
}

function Command(data)
{
	var self = this;

	self.command = ko.observable(data.command);
	self.response = ko.observable(data.response);
	self.duration = ko.observable(data.duration || 0);
	self.startTime = Date.now();

	self.durationText = ko.computed(function()
	{
		return self.duration() + "ms";
	});
}

function PrometheusViewModel()
{
	// Data
	var self = this;
	self.socket = null;
	self.socketServer = 'ws://10.33.0.2:8888/';
	//self.socketServer = 'ws://localhost:8888/';

	// Enabled Setting
	self.textEnabled = ko.observable("off");
	self.enabled = ko.computed(function()
	{
		return self.textEnabled() == "on" ? true : false;
	});

	// Settings Screen Stuff
	self.Render3DEnabledText = ko.observable("on");
	self.Render3DEnabled = ko.computed(function()
	{
		return self.Render3DEnabledText() == "on" ? true : false;
	});

	self.Rotate3DEnabledText = ko.observable("off");
	self.Rotate3DEnabled = ko.computed(function()
	{
		return self.Rotate3DEnabledText() == "on" ? true : false;
	});

	self.PIDTuningEnabledText = ko.observable("off");
	self.PIDTuningEnabled = ko.computed(function()
	{
		return self.PIDTuningEnabledText() == "on" ? true : false;
	});

	self.CommandConsoleEnabledText = ko.observable("off");
	self.CommandConsoleEnabled = ko.computed(function()
	{
		return self.CommandConsoleEnabledText() == "on" ? true : false;
	});

	// Joints array
	self.joints = ko.observableArray([]);

	// Command Console Data
	self.commandText = ko.observable().extend({ notify: 'always' });
	self.commandHistory = ko.observableArray();
	self.commandPosition = 0;

	// 3D Rendering
	self.init3D = function()
	{
		self.renderer = new RobotArm(self);

		ko.computed(function()
		{
			self.updateRenderer();
		}).extend({throttle: 100});

		self.updateRenderer();
	};

	self.updateRenderer = function()
	{
		if(self.Render3DEnabled())
		{
			self.renderer.init();
		}
	};

	// Socket
	self.initSocket = function()
	{
		self.socket = new WebSocket(self.socketServer);

		self.socket.onopen = function()
		{
			console.log('Socket Connected!');

			for(var i = 0; i < self.joints().length; i++)
			{
				var command = ko.toJSON(
				{
					command: "getJointGains",
					jointNumber: i
				});

				console.log(command);
				self.socket.send(command);

				var command = ko.toJSON(
				{
					command: "getJointLimits",
					jointNumber: i
				});

				console.log(command);
				self.socket.send(command);
			};
		};

		self.socket.onclose = function()
		{
			console.log('Socket connection lost!');
			self.socket.close();
		};

		self.socket.onmessage = function(event)
		{
			self.receiveSocketData(event.data);
		};
	};

	self.receiveSocketData = function(data)
	{
		// We need to figure out what we are going to do with the command
		// console now that we are using a socket instead of ajax requests
		// because we now have to figure out which response belongs to which
		// command.

		console.log("Data from socket: " + data);

		json = null;

		try
		{
			json = $.parseJSON(data);
		}
		catch(exception)
		{
			console.log("Failed to parse data from socket as JSON. Data:");
			console.log(data);
		}

		if(json != null)
		{
			switch(json.command)
			{
				case "armStatus":
					for(var i = 0; i < self.joints().length; i++)
					{
						self.joints()[i].currentAngle(json.currentAngle[i]);
						self.joints()[i].angleError(json.currentError[i]);
					};
					break;

				case "jointAngle":
					self.joints()[json.jointNumber].currentAngle(json.angle);
					break;

				case "jointSetPoint":
					self.joints()[json.jointNumber].serialSetPoint(json.setPoint);
					break;

				case "jointLimits":
					self.joints()[json.jointNumber].min(json.min);
					self.joints()[json.jointNumber].max(json.max);
					break;

				case "jointGains":
					self.joints()[json.jointNumber].PGain(json.PGain);
					self.joints()[json.jointNumber].IGain(json.IGain);
					self.joints()[json.jointNumber].DGain(json.DGain);
					break;

				case "jointError":
					self.joints()[json.jointNumber].angleError(json.error);
					break;
			}
		}
		else
		{
			console.log("Failed to parse data from socket as JSON. Data:");
			console.log(data);
		}
	};

	// Command Console
	self.sendCommand = function()
	{
		var command = self.commandText();
		self.commandText("");

		var commandData = command.split(" ");

		var index = self.commandHistory().length;
		self.commandPosition = index + 1;
		self.commandHistory.push(new Command({"command": command}));

		var allowedCommands = ["setJointGains", "setJointAngle",
			"getJointAngle", "getJointLimits",
			"getJointGains", "getjointError"];

		if($.inArray(commandData[0], allowedCommands) != -1)
		{
			if(!isNaN(Number(commandData[1])))
			{
				commandData[1] = Number(commandData[1]);
			}

			var command = ko.toJSON(
				{
					command: commandData[0],
					jointNumber: commandData[1]
				});

			switch(commandData[0])
			{
				case "setJointGains":
					if(!isNaN(Number(commandData[2])))
					{
						command.PGain = Number(commandData[2]);

						if(!isNaN(Number(commandData[3])))
						{
							command.IGain = Number(commandData[3]);

							if(!isNaN(Number(commandData[4])))
							{
								command.DGain = Number(commandData[4]);

								self.socket.send(command);
							}
						}
					}

					break;

				case "setJointAngle":
					if(!isNaN(Number(commandData[2])))
					{
						command.angle = Number(commandData[2]);

						self.socket.send(command);
					}

					break;

				case "getJointAngle":
				case "getJointLimits":
				case "getJointGains":
				case "getjointError":
					self.socket.send(command);
					break;

				default:
					self.commandHistory()[index].response("Invalid command");
					break;
			}

			console.log("Data Sent: " + command);
		}
		else
		{
			self.commandHistory()[index].response("Invalid command");
		}
	};

	self.previousCommand = function()
	{
		if(self.commandPosition > 0)
		{
			self.commandPosition -= 1;
			self.commandText(self.commandHistory()[self.commandPosition].command());
		}
	};

	self.nextCommand = function()
	{
		if(self.commandPosition == self.commandHistory().length)
		{
			self.commandText("");
		}
		else if(self.commandPosition == self.commandHistory().length -1)
		{
			self.commandPosition += 1;
			self.commandText("");
		}
		else if(self.commandPosition < self.commandHistory().length - 1)
		{
			self.commandPosition += 1;
			self.commandText(self.commandHistory()[self.commandPosition].command());
		}
	};

	// Other
	self.addJoint = function(data)
	{
		self.joints.push(new Joint(data, self));
	};

	self.initSocket();
	self.init3D();
}

var vm = new PrometheusViewModel()

vm.addJoint({
	title: "Base",
	jointNumber: 0,
	min: 0,
	max: 360,
	setPoint: 0
});

vm.addJoint({
	title: "Shoulder",
	jointNumber: 1,
	min: 0,
	max: 180,
	setPoint: 0
});

vm.addJoint({
	title: "Elbow",
	jointNumber: 2,
	min: 180,
	max: 360,
	setPoint: 360
});

vm.addJoint({
	title: "Wrist",
	jointNumber: 3,
	min: 0,
	max: 359,
	setPoint: 180
});

vm.addJoint({
	title: "Hand",
	jointNumber: 4,
	min: 0,
	max: 359,
	setPoint: 180
});

ko.applyBindings(vm);
<|endoftext|>


<commit_before>/**
 * jQuery Library for Multilingual Press
 *
 * @author		fb, rw, ms, th
 * @version		0.8
 * @package		mlp
 * @subpackage	jquery lib
 *
 * @todo		Doc
 */

jQuery.noConflict();
( function( $ ) {

	/**
	 * Class Holder
	 */
	multilingual_press = {

		/**
		 * Initial Function
		 */
		init : function () {
			this.do_blog_checkup();
			this.draw_tab();
			this.bind_ajax_tab_handler();
			this.bind_submit_setting_form();
			this.form_fields_expandable();
		},

		/**
		 *
		 */
		bind_submit_setting_form : function() {

			$( '#multilingualpress_settings' ).live( 'submit', function() {
				// Serialize form field/data
				var serialized_data = $( this ).serialize();
				multilingual_press.submit_form( serialized_data );
				return false;
			} );
		},

		/**
		 *
		 * @param serialized_data
		 */
		submit_form : function( serialized_data ) {

			var multilang_post_data = {
				action: 'save_multilang_settings',
				serialized_data: serialized_data + '&id=' + mlp_loc.blog_id,
				form_nonce: mlp_loc.ajax_form_nonce,
				id: mlp_loc.blog_id
			};

			var multilang_saved_settings = $.ajax( {
				url: ajaxurl,
				data: multilang_post_data,
				async: false,
				type: 'POST',
				success: function ( response ) {
					$( '.wrap > .updated' ).remove();
					return response;
				}
			} ).responseText;

			$( '#multilingualpress_settings' ).before( multilang_saved_settings );
			window.scrollTo(0,0);
		},

		/**
		 *
		 */
		draw_tab: function() {
			$( 'h3.nav-tab-wrapper:first' ).append( '' + mlp_loc.tab_label + '' );
		},

		/**
		 *
		 */
		bind_ajax_tab_handler : function() {

			$( 'a#mlp_settings_tab' ).live( 'click', function() {

				// Set tab active
				$( 'h3.nav-tab-wrapper:first a' ).each( function() {
					$( this ).removeClass( 'nav-tab-active' );
				} );
				$( this ).addClass( 'nav-tab-active' );

				var data = {
					action: 'tab_form',
					id: mlp_loc.blog_id,
					tab_nonce: mlp_loc.ajax_tab_nonce
				};

				// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
				$.post( ajaxurl, data, function( response ) {
					// Replace content
					$( '.wrap:first' ).html( response );
				} );
			} );
		},

		/**
		 *
		 */
		form_fields_expandable : function() {
			$( 'form#multilingualpress_settings .handlediv' ).live( 'click', function() {
				$( this ).parent( '.postbox' ).toggleClass( 'closed' );
			} );
		},

		/**
		 * Retrieves all responses from the blog checkup
		 *
		 * @since	0.8
		 */
		do_blog_checkup : function() {
			if ( ! '#multilingual_press_checkup' )
				return;

			$( '#multilingual_press_checkup_link' ).live( 'click', function() {
				var data = {
					action: 'checkup_blogs'
				};

				$.ajax( {
    				url: ajaxurl,
    				data: data,
    				async: true,
    				success: function ( response ) {
    					$( '#multilingual_press_checkup' ).append( response ).delay( 250 ).animate( {
    						backgroundColor: 'lightYellow',
    						borderBottomColor: '#E6DB55',
    						borderLeftColor: '#E6DB55',
    						borderRightColor: '#E6DB55',
    						borderTopColor: '#E6DB55'
    					}, 500 ).delay( 3500 ).slideUp();
    				}
    			} );
			} );
		}
	};

	$( document ).ready( function( $ ) {
		multilingual_press.init();
	} );

} )( jQuery );<commit_msg>update main JS file<commit_after>/**
 * jQuery Library for Multilingual Press
 *
 * @author		fb, rw, ms, th
 * @version		0.8
 * @package		mlp
 * @subpackage	jquery lib
 *
 * @todo		Doc
 */

jQuery.noConflict();
( function( $ ) {

	/**
	 * Class Holder
	 */
	multilingual_press = {

		/**
		 * Initial Function
		 */
		init : function () {
			this.do_blog_checkup();
			this.draw_tab();
			this.bind_ajax_tab_handler();
			this.bind_submit_setting_form();
			this.form_fields_expandable();
		},

		/**
		 *
		 */
		bind_submit_setting_form : function() {

			$( '#multilingualpress_settings' ).live( 'submit', function() {
				// Serialize form field/data
				var serialized_data = $( this ).serialize();
				multilingual_press.submit_form( serialized_data );
				return false;
			} );
		},

		/**
		 *
		 * @param serialized_data
		 */
		submit_form : function( serialized_data ) {

			var multilang_post_data = {
				action: 'save_multilang_settings',
				serialized_data: serialized_data + '&id=' + mlp_loc.blog_id,
				form_nonce: mlp_loc.ajax_form_nonce,
				id: mlp_loc.blog_id
			};

			var multilang_saved_settings = $.ajax( {
				url: ajaxurl,
				data: multilang_post_data,
				async: false,
				type: 'POST',
				success: function ( response ) {
					$( '.wrap > .updated' ).remove();
					return response;
				}
			} ).responseText;

			$( '#multilingualpress_settings' ).before( multilang_saved_settings );
			window.scrollTo(0,0);
		},

		/**
		 *
		 */
		draw_tab: function() {
			// $( 'h3.nav-tab-wrapper:first' ).append( '' + mlp_loc.tab_label + '' );
		},

		/**
		 *
		 */
		bind_ajax_tab_handler : function() {

			$( 'a#mlp_settings_tab' ).live( 'click', function() {

				// Set tab active
				$( 'h3.nav-tab-wrapper:first a' ).each( function() {
					$( this ).removeClass( 'nav-tab-active' );
				} );
				$( this ).addClass( 'nav-tab-active' );

				var data = {
					action: 'tab_form',
					id: mlp_loc.blog_id,
					tab_nonce: mlp_loc.ajax_tab_nonce
				};

				// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
				$.post( ajaxurl, data, function( response ) {
					// Replace content
					$( '.wrap:first' ).html( response );
				} );
			} );
		},

		/**
		 *
		 */
		form_fields_expandable : function() {
			$( 'form#multilingualpress_settings .handlediv' ).live( 'click', function() {
				$( this ).parent( '.postbox' ).toggleClass( 'closed' );
			} );
		},

		/**
		 * Retrieves all responses from the blog checkup
		 *
		 * @since	0.8
		 */
		do_blog_checkup : function() {
			if ( ! '#multilingual_press_checkup' )
				return;

			$( '#multilingual_press_checkup_link' ).live( 'click', function() {
				var data = {
					action: 'checkup_blogs'
				};

				$.ajax( {
    				url: ajaxurl,
    				data: data,
    				async: true,
    				success: function ( response ) {
    					$( '#multilingual_press_checkup' ).append( response ).delay( 250 ).animate( {
    						backgroundColor: 'lightYellow',
    						borderBottomColor: '#E6DB55',
    						borderLeftColor: '#E6DB55',
    						borderRightColor: '#E6DB55',
    						borderTopColor: '#E6DB55'
    					}, 500 ).delay( 3500 ).slideUp();
    				}
    			} );
			} );
		}
	};

	$( document ).ready( function( $ ) {
		multilingual_press.init();
	} );

} )( jQuery );<|endoftext|>


<commit_before>const path = require('path')
const resolveFrom = require('resolve-from')

exports.name = 'builtin:config-vue'

exports.apply = api => {
  api.hook('createWebpackChain', config => {
    const rule = config.module.rule('vue').test(/\.vue$/)

    const getCacheOptions = () => {
      const vueLoaderPath = path.dirname(require.resolve('vue-loader'))
      const compilerPkg = require(resolveFrom(
        vueLoaderPath,
        '@vue/component-compiler-utils/package'
      ))
      return api.getCacheConfig('vue-loader', {
        'vue-loader': require('vue-loader/package').version,
        '@vue/component-compiler-utils': compilerPkg.version,
        'vue-template-compiler': api.localResolve(
          'vue-template-compiler/package'
        )
          ? api.localRequire('vue-template-compiler/package').version
          : null
      })
    }

    api.webpackUtils.addCacheSupport(rule, getCacheOptions)

    rule
      .use('vue-loader')
      .loader(require.resolve('vue-loader'))
      .options(
        Object.assign(
          {
            // TODO: error with thread-loader
            compiler: api.localRequire('vue-template-compiler')
          },
          // For Vue templates
          api.config.cache && getCacheOptions()
        )
      )

    config.plugin('vue').use(require('vue-loader/lib/plugin'))
  })
}
<commit_msg>feat(vue): add vue 3 support<commit_after>const path = require('path')
const resolveFrom = require('resolve-from')
const logger = require('@poi/logger')
const PoiError = require('../utils/PoiError')

exports.name = 'builtin:config-vue'

exports.apply = api => {
  api.hook('createWebpackChain', config => {
    const rule = config.module.rule('vue').test(/\.vue$/)

    const vueLoaderPath = path.dirname(
      api.localResolve('vue-loader/package.json') ||
        require.resolve('vue-loader/package.json')
    )
    const vueLoaderPkg = require(path.join(vueLoaderPath, 'package.json'))
    const vueLoaderMajorVersion = parseInt(vueLoaderPkg.version, 10)
    const isVue3 = vueLoaderMajorVersion >= 16

    if (isVue3 && vueLoaderPkg.version.includes('beta')) {
      logger.warn(`You are using the beta version of vue-loader, be aware!`)
    }

    const getCacheOptions = () => {
      if (isVue3) {
        const hasSFCCompiler = api.localResolve(
          '@vue/compiler-sfc/package.json'
        )
        if (!hasSFCCompiler) {
          throw new PoiError(
            `Expect @vue/compiler-sfc to be installed in current project`
          )
        }
        return api.getCacheConfig('vue-loader', {
          'vue-loader': vueLoaderPkg.version,
          '@vue/compiler-sfc': hasSFCCompiler
            ? api.localRequire('@vue/compiler-sfc/package.json').version
            : null
        })
      }

      const compilerPkg = require(resolveFrom(
        vueLoaderPath,
        '@vue/component-compiler-utils/package'
      ))
      return api.getCacheConfig('vue-loader', {
        'vue-loader': vueLoaderPkg.version,
        '@vue/component-compiler-utils': compilerPkg.version,
        'vue-template-compiler': api.localResolve(
          'vue-template-compiler/package'
        )
          ? api.localRequire('vue-template-compiler/package').version
          : null
      })
    }

    api.webpackUtils.addCacheSupport(rule, getCacheOptions)

    rule
      .use('vue-loader')
      .loader(require.resolve(vueLoaderPath))
      .options(
        Object.assign(
          {
            // TODO: error with thread-loader
            compiler: isVue3
              ? undefined
              : api.localRequire('vue-template-compiler')
          },
          // For Vue templates
          api.config.cache && getCacheOptions()
        )
      )

    config.plugin('vue').use(require(vueLoaderPath).VueLoaderPlugin)
  })
}
<|endoftext|>


<commit_before>var t = TrelloPowerUp.iframe();

console.log("Loading Clear List JavaScript");

t.render(function(){
    console.log("RENDER");
    populateListItems();
    t.sizeTo('#content');
});

var isClearing = false;

var populateListItems = function() {
    return t.lists('name', 'id')
    .then(function(lists) {
        console.dir(lists);
        var sel = document.getElementById('boardLists');
        var fragment = document.createDocumentFragment();
        lists.forEach(function(list) {
            var opt = document.createElement('option');
            opt.innerHTML = list.name;
            opt.value = list.id;
            fragment.appendChild(opt);
        });
        sel.appendChild(fragment);
    });
};

var getSelectedListId = function() {
    var select = document.getElementById('boardLists');
    return select.options[select.selectedIndex].id;
};

var handleClearClick = function (e) {
    console.log("Clear Click");
    disableClearVotesButton();
    var listId = getSelectedListId();
    return clearVotesForList(listId)
    .then(function() {
        console.log("Votes Cleared");
    })
    .catch(function(err) {
        console.log("ERR: " + err);
    });
};

var disableClearVotesButton = function() {
    var sel = document.getElementById('clearVotes');
    sel.setAttribute("disabled", "");
};

var clearVotesForList = function(listId) {
    return t.cards('id', 'idList')
    .then(function(cards) {
        var promises = [];
        cards.forEach(function(card) {
            if (card.idList === listId) {
                promises.push(clearVotesForCard(card));
            }
        });
        return Promise.all(promises);
    })
};

var clearVotesForCard = function (card) {
    return t.set(card.id, 'shared', 'com.universalmind.trello.DotVotes', 0);
};<commit_msg>Adding logging statements<commit_after>var t = TrelloPowerUp.iframe();

console.log("Loading Clear List JavaScript");

t.render(function(){
    console.log("RENDER");
    populateListItems();
    t.sizeTo('#content');
});

var isClearing = false;

var populateListItems = function() {
    return t.lists('name', 'id')
    .then(function(lists) {
        console.dir(lists);
        var sel = document.getElementById('boardLists');
        var fragment = document.createDocumentFragment();
        lists.forEach(function(list) {
            var opt = document.createElement('option');
            opt.innerHTML = list.name;
            opt.value = list.id;
            fragment.appendChild(opt);
        });
        sel.appendChild(fragment);
    });
};

var getSelectedListId = function() {
    var select = document.getElementById('boardLists');
    return select.options[select.selectedIndex].id;
};

var handleClearClick = function (e) {
    console.log("Clear Click");
    disableClearVotesButton();
    var listId = getSelectedListId();
    return clearVotesForList(listId)
    .then(function() {
        console.log("Votes Cleared");
    })
    .catch(function(err) {
        console.log("ERR: " + err);
    });
};

var disableClearVotesButton = function() {
    var sel = document.getElementById('clearVotes');
    sel.setAttribute("disabled", "");
};

var clearVotesForList = function(listId) {
    return t.cards('id', 'idList')
    .then(function(cards) {
        var promises = [];
        cards.forEach(function(card) {
            if (card.idList === listId) {
                console.log("Card Added To Promises: " + card.name);
                promises.push(clearVotesForCard(card));
            }
        });
        return Promise.all(promises);
    })
};

var clearVotesForCard = function (card) {
    return t.set(card.id, 'shared', 'com.universalmind.trello.DotVotes', 0);
};<|endoftext|>


<commit_before><commit_msg>Change main page buttons to `btn-primary`<commit_after><|endoftext|>


<commit_before>(() => {

    'use strict';

    angular
        .module('app')
        .controller('ConfirmUsersController', ConfirmUsersController);
    ConfirmUsersController.$inject = ['$rootScope', 'growl', '$log', '$route', 'ConfirmUsersService'];

    //This controller allows administrator get, edit, approve or decline unapproved users
    //TODO: make use to getUsers(id) admin.platoonId instead of static id
    //TODO: confirm list of available fields for request to approve user
    //TODO: use function to reload controller after decline or approve user
    //TODO: delete JSON.parse();
    //TODO: try to use angular modal instead of bootstrap ones
    //TODO: test api to approve and decline users
    //TODO: use api to update user data
    //TODO: delete all comments
    function ConfirmUsersController($rootScope, growl, $log, $route, ConfirmUsersService) {
        //Set variables
        const vm = this;
        const editUserModal = '#EditUser';            //name of modal window to edit user
        const confirmDeleteModal = '#ConfirmDelete';  //same, but to confirm decline user
        vm.usersList = [];
        vm.currentUser = {};
        vm.editUser = editUser;
        vm.changeGroup = changeGroup;
        vm.changePlatoon = changePlatoon;
        vm.getSections = getSections;
        vm.approveUser = approveUser;
        vm.declineUser = declineUser;
        vm.showConfirmDecline = showConfirmDecline;

        activate();

        ////

        function activate() {
            $log.debug('Init ConfirmUsersController ...');
            //Get list of unapproved users with same 'platoonId' as admin's
            getUsers(1);
            //init "FooTable" plugin in all tables with 'footable' class
            $(document).ready(function () {
                $('.footable').footable();
            });
            $log.debug('Init complete.');
        }

        //Function to set in 'vm' user list with specified platoonId
        function getUsers(grId) {
            ConfirmUsersService.getUsers({platoonId: grId}).$promise.then((res) => {
                if (res.success) {
                    let result;
                    result = JSON.parse(res.data.message);
                    result.forEach((item) => {
                        item.birthDate = new Date(item.birthDate);  //use 'new Data()' instead of raw int
                    });
                    vm.usersList = result;
                    $log.debug('Load users list:', vm.usersList);
                }
            });
        }

        //Function to edit currentUser
        function editUser(id) {
            vm.currentUser = vm.usersList.find((item) => item.id == id) || {};
            getCities(vm.currentUser.countryId);
            getGroups(vm.currentUser.cityId);
            getPlatoons(vm.currentUser.groupId);
            getSections(vm.currentUser.platoonId);
            getRanks();
            $(editUserModal).modal();       //load modal window in view (maybe incorrect)
            $log.debug('Edit user:', vm.currentUser);
        }

        //Function to approve currentUser
        function approveUser() {
            $(editUserModal).modal('hide'); //immediately hide modal window to prevent double confirm
            let valuesToSend = {
                firstName: vm.currentUser.firstName,
                lastName: vm.currentUser.lastName,
                gender: vm.currentUser.gender,
                telephoneNumber: vm.currentUser.telephoneNumber,
                birthDate: vm.currentUser.birthDate.getTime(),
                cityId: vm.currentUser.cityId,
                groupId: vm.currentUser.groupId,
                platoonId: vm.currentUser.platoonId,
                sectionId: vm.currentUser.sectionId,
                userRank: vm.currentUser.userRank
            };
            ConfirmUsersService.approveUser([vm.currentUser.id],
                (res) => {
                    if (res.success) {
                        growl.success('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' підтверджений');
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
            ConfirmUsersService.updateUser({userId: vm.currentUser.id}, valuesToSend,
                (res) => {
                    if (res.success) {
                        growl.success('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' підтверджений');
                        // $route.reload();
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
        }

        //Function to decline currentUser
        function declineUser() {
            $(confirmDeleteModal).modal('hide');    //prevent double decline
            $(editUserModal).modal('hide');         //also to prevent double decline
            ConfirmUsersService.declineUser([vm.currentUser.id],
                (res) => {
                    if (res.success) {
                        growl.info('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' видалений');
                        $route.reload();
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
        }

        //This additional function needed just to create another modal with 'confirm decline user'
        function showConfirmDecline() {
            $(confirmDeleteModal).modal();
        }

        //function to set in 'vm' list of Cities by countryId
        function getCities(countryId) {
            if (countryId == null) return [];
            ConfirmUsersService.city({countryId: countryId}).$promise.then((res) => {
                if (res.success) {
                    vm.cities = res.data;
                    $log.debug('Set citys list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Groups by cityId
        function getGroups(cityId) {
            if (cityId == null) return [];
            ConfirmUsersService.group({cityId: cityId}).$promise.then((res) => {
                if (res.success) {
                    vm.groups = res.data;
                    $log.debug('Set groups list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Platoons by groupId
        function getPlatoons(groupId) {
            if (groupId == null) return [];
            ConfirmUsersService.platoon({groupId: groupId}).$promise.then((res) => {
                if (res.success) {
                    vm.platoons = res.data;
                    $log.debug('Set platoons list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Sections by platoonId
        function getSections(platoonId) {
            if (platoonId == null) return [];
            ConfirmUsersService.section({platoonId: platoonId}).$promise.then((res) => {
                if (res.success) {
                    vm.sections = res.data;
                    $log.debug('Set sections list: ', res.data);
                }
            });
        }

        //Special function for view to correct change group
        function changeGroup(cityId) {
            getGroups(cityId);
            vm.platoons = [];
            vm.sections = [];
        }

        //Same, but to correct change platoon
        function changePlatoon(groupId) {
            getPlatoons(groupId);
            vm.sections = [];
        }

        //function to set in 'vm' list of Ranks
        function getRanks() {
            ConfirmUsersService.rank().$promise.then((res) => {
                if (res.success) {
                    vm.ranks = res.data;
                    $log.debug('Set ranks list: ', res.data);
                }
            });
        }
    }
})();<commit_msg>Delete JSON parser<commit_after>(() => {

    'use strict';

    angular
        .module('app')
        .controller('ConfirmUsersController', ConfirmUsersController);
    ConfirmUsersController.$inject = ['$rootScope', 'growl', '$log', '$route', 'ConfirmUsersService'];

    //This controller allows administrator get, edit, approve or decline unapproved users
    //TODO: make use to getUsers(id) admin.platoonId instead of static id
    //TODO: use function to reload controller after decline or approve user
    //TODO: try to use angular modal instead of bootstrap ones
    //TODO: test api to approve and decline users
    //TODO: use api to update user data
    //TODO: delete all comments
    function ConfirmUsersController($rootScope, growl, $log, $route, ConfirmUsersService) {
        //Set variables
        const vm = this;
        const editUserModal = '#EditUser';            //name of modal window to edit user
        const confirmDeleteModal = '#ConfirmDelete';  //same, but to confirm decline user
        vm.usersList = [];
        vm.currentUser = {};
        vm.editUser = editUser;
        vm.changeGroup = changeGroup;
        vm.changePlatoon = changePlatoon;
        vm.getSections = getSections;
        vm.approveUser = approveUser;
        vm.declineUser = declineUser;
        vm.showConfirmDecline = showConfirmDecline;

        activate();

        ////

        function activate() {
            $log.debug('Init ConfirmUsersController ...');
            //Get list of unapproved users with same 'platoonId' as admin's
            getUsers(1);
            //init "FooTable" plugin in all tables with 'footable' class
            $(document).ready(function () {
                $('.footable').footable();
            });
            $log.debug('Init complete.');
        }

        //Function to set in 'vm' user list with specified platoonId
        function getUsers(grId) {
            ConfirmUsersService.getUsers({platoonId: grId}).$promise.then((res) => {
                if (res.success) {
                    let result;
                    result = res.data || [];
                    result.forEach((item) => {
                        item.birthDate = new Date(item.birthDate);  //use 'new Data()' instead of raw int
                    });
                    vm.usersList = result;
                    $log.debug('Load users list:', vm.usersList);
                }
            });
        }

        //Function to edit currentUser
        function editUser(id) {
            vm.currentUser = vm.usersList.find((item) => item.id == id) || {};
            getCities(vm.currentUser.countryId);
            getGroups(vm.currentUser.cityId);
            getPlatoons(vm.currentUser.groupId);
            getSections(vm.currentUser.platoonId);
            getRanks();
            $(editUserModal).modal();       //load modal window in view (maybe incorrect)
            $log.debug('Edit user:', vm.currentUser);
        }

        //Function to approve currentUser
        function approveUser() {
            $(editUserModal).modal('hide'); //immediately hide modal window to prevent double confirm
            let valuesToSend = {
                firstName: vm.currentUser.firstName,
                lastName: vm.currentUser.lastName,
                gender: vm.currentUser.gender,
                telephoneNumber: vm.currentUser.telephoneNumber,
                birthDate: vm.currentUser.birthDate.getTime(),
                cityId: vm.currentUser.cityId,
                groupId: vm.currentUser.groupId,
                platoonId: vm.currentUser.platoonId,
                sectionId: vm.currentUser.sectionId,
                userRank: vm.currentUser.userRank
            };
            ConfirmUsersService.approveUser([vm.currentUser.id],
                (res) => {
                    if (res.success) {
                        growl.success('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' підтверджений');
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
            ConfirmUsersService.updateUser({userId: vm.currentUser.id}, valuesToSend,
                (res) => {
                    if (res.success) {
                        growl.success('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' підтверджений');
                        // $route.reload();
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
        }

        //Function to decline currentUser
        function declineUser() {
            $(confirmDeleteModal).modal('hide');    //prevent double decline
            $(editUserModal).modal('hide');         //also to prevent double decline
            ConfirmUsersService.declineUser([vm.currentUser.id],
                (res) => {
                    if (res.success) {
                        growl.info('Користувач ' + vm.currentUser.firstName + ' ' +
                            vm.currentUser.lastName + ' видалений');
                        $route.reload();
                    } else {
                        growl.error('Помилка:' + res.data.message);
                    }
                });
        }

        //This additional function needed just to create another modal with 'confirm decline user'
        function showConfirmDecline() {
            $(confirmDeleteModal).modal();
        }

        //function to set in 'vm' list of Cities by countryId
        function getCities(countryId) {
            if (countryId == null) return [];
            ConfirmUsersService.city({countryId: countryId}).$promise.then((res) => {
                if (res.success) {
                    vm.cities = res.data;
                    $log.debug('Set citys list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Groups by cityId
        function getGroups(cityId) {
            if (cityId == null) return [];
            ConfirmUsersService.group({cityId: cityId}).$promise.then((res) => {
                if (res.success) {
                    vm.groups = res.data;
                    $log.debug('Set groups list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Platoons by groupId
        function getPlatoons(groupId) {
            if (groupId == null) return [];
            ConfirmUsersService.platoon({groupId: groupId}).$promise.then((res) => {
                if (res.success) {
                    vm.platoons = res.data;
                    $log.debug('Set platoons list: ', res.data);
                }
            });
        }

        //function to set in 'vm' list of Sections by platoonId
        function getSections(platoonId) {
            if (platoonId == null) return [];
            ConfirmUsersService.section({platoonId: platoonId}).$promise.then((res) => {
                if (res.success) {
                    vm.sections = res.data;
                    $log.debug('Set sections list: ', res.data);
                }
            });
        }

        //Special function for view to correct change group
        function changeGroup(cityId) {
            getGroups(cityId);
            vm.platoons = [];
            vm.sections = [];
        }

        //Same, but to correct change platoon
        function changePlatoon(groupId) {
            getPlatoons(groupId);
            vm.sections = [];
        }

        //function to set in 'vm' list of Ranks
        function getRanks() {
            ConfirmUsersService.rank().$promise.then((res) => {
                if (res.success) {
                    vm.ranks = res.data;
                    $log.debug('Set ranks list: ', res.data);
                }
            });
        }
    }
})();<|endoftext|>