<commit_before>/* PushMenu()
 * ==========
 * Adds the push menu functionality to the sidebar.
 *
 * @type Function
 * @usage: $('.btn').pushMenu(options)
 *          or add [data-toggle="offcanvas"] to any toggle button
 *          Pass any option as data-option="value"
 */
+function ($) {
  'use strict'

  var DataKey = 'lte.pushmenu'

  var Default = {
    collapseScreenSize   : 767,
    expandOnHover        : false,
    expandTransitionDelay: 200
  }

  var Selector = {
    collapsed     : '.sidebar-collapse',
    open          : '.sidebar-open',
    mainSidebar   : '.main-sidebar',
    contentWrapper: '.content-wrapper',
    searchInput   : '.sidebar-form .form-control',
    button        : '[data-toggle="offcanvas"]',
    mini          : '.sidebar-mini',
    expanded      : '.sidebar-expanded-on-hover',
    layoutFixed   : '.fixed'
  }

  var ClassName = {
    collapsed    : 'sidebar-collapse',
    open         : 'sidebar-open',
    mini         : 'sidebar-mini',
    expanded     : 'sidebar-expanded-on-hover',
    expandFeature: 'sidebar-mini-expand-feature',
    layoutFixed  : 'fixed'
  }

  var Event = {
    expanded : 'expanded.pushMenu',
    collapsed: 'collapsed.pushMenu'
  }

  // PushMenu Class Definition
  // =========================
  var PushMenu = function (options) {
    this.options = options
    this.init()
  }

  PushMenu.prototype.init = function () {
    if (this.options.expandOnHover
      || ($('body').is(Selector.mini + Selector.layoutFixed))) {
      this.expandOnHover()
      $('body').addClass(ClassName.expandFeature)
    }

    $(Selector.contentWrapper).click(function () {
      // Enable hide menu when clicking on the content-wrapper on small screens
      if ($(window).width() <= this.options.collapseScreenSize && $('body').hasClass(ClassName.open)) {
        this.close()
      }
    }.bind(this))

    // __Fix for android devices
    $(Selector.searchInput).click(function (e) {
      e.stopPropagation()
    })
  }

  PushMenu.prototype.toggle = function () {
    var windowWidth = $(window).width()
    var isOpen      = !$('body').hasClass(ClassName.collapsed)

    if (windowWidth <= this.options.collapseScreenSize) {
      isOpen = $('body').hasClass(ClassName.open)
    }

    if (!isOpen) {
      this.open()
    } else {
      this.close()
    }
  }

  PushMenu.prototype.open = function () {
    var windowWidth = $(window).width()

    if (windowWidth > this.options.collapseScreenSize) {
      $('body').removeClass(ClassName.collapsed)
        .trigger($.Event(Event.expanded))
    }
    else {
      $('body').addClass(ClassName.open)
        .trigger($.Event(Event.expanded))
    }
  }

  PushMenu.prototype.close = function () {
    var windowWidth = $(window).width()
    if (windowWidth > this.options.collapseScreenSize) {
      $('body').addClass(ClassName.collapsed)
        .trigger($.Event(Event.collapsed))
    } else {
      $('body').removeClass(ClassName.open + ' ' + ClassName.collapsed)
        .trigger($.Event(Event.collapsed))
    }
  }

  PushMenu.prototype.expandOnHover = function () {
    $(Selector.mainSidebar).hover(function () {
      if ($('body').is(Selector.mini + Selector.collapsed)
        && $(window).width() > this.options.collapseScreenSize) {
        this.expand()
      }
    }.bind(this), function () {
      if ($('body').is(Selector.expanded)) {
        this.collapse()
      }
    }.bind(this))
  }

  PushMenu.prototype.expand = function () {
    setTimeout(function () {
      $('body').removeClass(ClassName.collapsed)
        .addClass(ClassName.expanded)
    }, this.options.expandTransitionDelay)
  }

  PushMenu.prototype.collapse = function () {
    setTimeout(function () {
      $('body').removeClass(ClassName.expanded)
        .addClass(ClassName.collapsed)
    }, this.options.expandTransitionDelay)
  }

  // PushMenu Plugin Definition
  // ==========================
  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data(DataKey)

      if (!data) {
        var options = $.extend({}, Default, $this.data(), typeof option == 'object' && option)
        $this.data(DataKey, (data = new PushMenu(options)))
      }

      if (option == 'toggle') data.toggle()
    })
  }

  var old = $.fn.pushMenu

  $.fn.pushMenu             = Plugin
  $.fn.pushMenu.Constructor = PushMenu

  // No Conflict Mode
  // ================
  $.fn.pushMenu.noConflict = function () {
    $.fn.pushMenu = old
    return this
  }

  // Data API
  // ========
  $(document).on('click', Selector.button, function (e) {
    e.preventDefault()
    Plugin.call($(this), 'toggle')
  })
  $(window).on('load', function () {
    Plugin.call($(Selector.button), {})
  })
}(jQuery)
<commit_msg>Update data selector to match the name of the plugin<commit_after>/* PushMenu()
 * ==========
 * Adds the push menu functionality to the sidebar.
 *
 * @usage: $('.btn').pushMenu(options)
 *          or add [data-toggle="push-menu"] to any toggle button
 *          Pass any option as data-option="value"
 */
+function ($) {
  'use strict'

  var DataKey = 'lte.pushmenu'

  var Default = {
    collapseScreenSize   : 767,
    expandOnHover        : false,
    expandTransitionDelay: 200
  }

  var Selector = {
    collapsed     : '.sidebar-collapse',
    open          : '.sidebar-open',
    mainSidebar   : '.main-sidebar',
    contentWrapper: '.content-wrapper',
    searchInput   : '.sidebar-form .form-control',
    button        : '[data-toggle="push-menu"]',
    mini          : '.sidebar-mini',
    expanded      : '.sidebar-expanded-on-hover',
    layoutFixed   : '.fixed'
  }

  var ClassName = {
    collapsed    : 'sidebar-collapse',
    open         : 'sidebar-open',
    mini         : 'sidebar-mini',
    expanded     : 'sidebar-expanded-on-hover',
    expandFeature: 'sidebar-mini-expand-feature',
    layoutFixed  : 'fixed'
  }

  var Event = {
    expanded : 'expanded.pushMenu',
    collapsed: 'collapsed.pushMenu'
  }

  // PushMenu Class Definition
  // =========================
  var PushMenu = function (options) {
    this.options = options
    this.init()
  }

  PushMenu.prototype.init = function () {
    if (this.options.expandOnHover
      || ($('body').is(Selector.mini + Selector.layoutFixed))) {
      this.expandOnHover()
      $('body').addClass(ClassName.expandFeature)
    }

    $(Selector.contentWrapper).click(function () {
      // Enable hide menu when clicking on the content-wrapper on small screens
      if ($(window).width() <= this.options.collapseScreenSize && $('body').hasClass(ClassName.open)) {
        this.close()
      }
    }.bind(this))

    // __Fix for android devices
    $(Selector.searchInput).click(function (e) {
      e.stopPropagation()
    })
  }

  PushMenu.prototype.toggle = function () {
    var windowWidth = $(window).width()
    var isOpen      = !$('body').hasClass(ClassName.collapsed)

    if (windowWidth <= this.options.collapseScreenSize) {
      isOpen = $('body').hasClass(ClassName.open)
    }

    if (!isOpen) {
      this.open()
    } else {
      this.close()
    }
  }

  PushMenu.prototype.open = function () {
    var windowWidth = $(window).width()

    if (windowWidth > this.options.collapseScreenSize) {
      $('body').removeClass(ClassName.collapsed)
        .trigger($.Event(Event.expanded))
    }
    else {
      $('body').addClass(ClassName.open)
        .trigger($.Event(Event.expanded))
    }
  }

  PushMenu.prototype.close = function () {
    var windowWidth = $(window).width()
    if (windowWidth > this.options.collapseScreenSize) {
      $('body').addClass(ClassName.collapsed)
        .trigger($.Event(Event.collapsed))
    } else {
      $('body').removeClass(ClassName.open + ' ' + ClassName.collapsed)
        .trigger($.Event(Event.collapsed))
    }
  }

  PushMenu.prototype.expandOnHover = function () {
    $(Selector.mainSidebar).hover(function () {
      if ($('body').is(Selector.mini + Selector.collapsed)
        && $(window).width() > this.options.collapseScreenSize) {
        this.expand()
      }
    }.bind(this), function () {
      if ($('body').is(Selector.expanded)) {
        this.collapse()
      }
    }.bind(this))
  }

  PushMenu.prototype.expand = function () {
    setTimeout(function () {
      $('body').removeClass(ClassName.collapsed)
        .addClass(ClassName.expanded)
    }, this.options.expandTransitionDelay)
  }

  PushMenu.prototype.collapse = function () {
    setTimeout(function () {
      $('body').removeClass(ClassName.expanded)
        .addClass(ClassName.collapsed)
    }, this.options.expandTransitionDelay)
  }

  // PushMenu Plugin Definition
  // ==========================
  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data(DataKey)

      if (!data) {
        var options = $.extend({}, Default, $this.data(), typeof option == 'object' && option)
        $this.data(DataKey, (data = new PushMenu(options)))
      }

      if (option == 'toggle') data.toggle()
    })
  }

  var old = $.fn.pushMenu

  $.fn.pushMenu             = Plugin
  $.fn.pushMenu.Constructor = PushMenu

  // No Conflict Mode
  // ================
  $.fn.pushMenu.noConflict = function () {
    $.fn.pushMenu = old
    return this
  }

  // Data API
  // ========
  $(document).on('click', Selector.button, function (e) {
    e.preventDefault()
    Plugin.call($(this), 'toggle')
  })
  $(window).on('load', function () {
    Plugin.call($(Selector.button))
  })
}(jQuery)
<|endoftext|>


<commit_before>define('app/models/machine', [
    'ember'
    ],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: null,
            checkedMonitoring: false,
            state: 'stopped',

            reboot: function() {
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function() {
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function() {
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function() {
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback) {
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    try {
                        host = this.public_ips[0];
                    } catch (error) {
                        // no ip or dns_name so nowhere to check, can't test the key
                        this.set('hasKey', false);
                    }
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function() {
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state') == 'running' && that.get('uptimeFromServer') &&
                        that.get('uptimeChecked')) {

                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    } else {
                        return;
                    }
                }, 1000);
            },

            checkUptime: function() {
                if (this.state == 'running') {
                    var host;
                    if (this.extra && this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        try {
                            host = this.public_ips[0];
                        } catch (error) {
                            // no ip or dns_name so nowhere to check, can't test the key
                            this.set('hasKey', false);
                        }
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            error(textstate);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function() {
                var that = this;
                $.ajax({
                    url: URL_PREFIX + '/backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    dataType: 'jsonp',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.get('state') == 'running') {
                    this.startUptimeTimer();
                    this.checkUptime();
                } else {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                }
            }.observes('state'),

            changeMonitoring: function() {
                if (!this.checkedMonitoring) {
                    this.checkedMonitoring = true;
                    return false;
                }

                var oldValue = !this.hasMonitoring;
                warn("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    try {
                        host = this.public_ips[0];
                    } catch (error) {
                        // no ip or dns_name so nowhere to check, can't test the key
                        this.set('hasKey', false);
                    }
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                that.set('pendingMonitoring', true);

                $.ajax({
                    url: URL_PREFIX + '/backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'jsonp',
                    success: function(data) {
                        if ('monitoring' in data) {
                            that.set('hasMonitoring', data.monitoring);
                            that.set('pendingMonitoring', false);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                        that.set('pendingMonitoring', false);
                    }
                });
            },

            init: function() {
                this._super();
                var that = this;

                this.tags = Ember.ArrayController.create();

                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }
        });
    }
);
<commit_msg>Deprecate checkedMonitoring and introduce pendingMonitoring.<commit_after>define('app/models/machine', [
    'ember'
    ],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: null,
            pendingMonitoring: false,
            state: 'stopped',

            reboot: function() {
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function() {
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function() {
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function() {
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback) {
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    try {
                        host = this.public_ips[0];
                    } catch (error) {
                        // no ip or dns_name so nowhere to check, can't test the key
                        this.set('hasKey', false);
                    }
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function() {
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state') == 'running' && that.get('uptimeFromServer') &&
                        that.get('uptimeChecked')) {

                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    } else {
                        return;
                    }
                }, 1000);
            },

            checkUptime: function() {
                if (this.state == 'running') {
                    var host;
                    if (this.extra && this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        try {
                            host = this.public_ips[0];
                        } catch (error) {
                            // no ip or dns_name so nowhere to check, can't test the key
                            this.set('hasKey', false);
                        }
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            error(textstate);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function() {
                var that = this;
                $.ajax({
                    url: URL_PREFIX + '/backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    dataType: 'jsonp',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.get('state') == 'running') {
                    this.startUptimeTimer();
                    this.checkUptime();
                } else {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                }
            }.observes('state'),

            changeMonitoring: function() {
                var oldValue = !this.hasMonitoring;
                warn("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    try {
                        host = this.public_ips[0];
                    } catch (error) {
                        // no ip or dns_name so nowhere to check, can't test the key
                        this.set('hasKey', false);
                    }
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                this.set('pendingMonitoring', true);

                $.ajax({
                    url: URL_PREFIX + '/backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'jsonp',
                    success: function(data) {
                        if ('monitoring' in data) {
                            that.set('hasMonitoring', data.monitoring);
                            that.set('pendingMonitoring', false);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                        that.set('pendingMonitoring', false);
                    }
                });
            },

            init: function() {
                this._super();
                var that = this;

                this.tags = Ember.ArrayController.create();

                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }
        });
    }
);
<|endoftext|>


<commit_before>// // Place all the behaviors and hooks related to the matching controller here.
// // All this logic will automatically be available in application.js.

var ready;
ready = function() {
	var typingTimer;
	var doneTypingInterval = 1000;
	$('.room_input').change(function() {
		// clearTimeout(typingTimer);
		// typingTimer = setTimeout(checkVacancy, doneTypingInterval);
		equipment_ids = [];
		$(".equipment:checked").each(function(){ equipment_ids.push($(this).attr('id'))});
		var data = {}
		data['room'] = {}

		data_1 = {
			size: $('#room_size').val(),
 			property: $('#').val(),
 			equipment: equipment_ids
 		};

 		var dict = {};
 		dict['equipment'] = {};
		for(i in equipment_ids ) {
			dict['equipment'][equipment_ids[i]]	=  $('#' + equipment_ids[i]).val();
		}
		data['room'] = data_1;

		$.ajax({
			url: '/rooms/getValidRooms',
			type: 'POST',
			data: data,
			dataType: 'json',
			beforeSend: function(xhr) {
			 	xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));},
			 success:(function(data){
			 	var i = 0;
			 	msg = "";
			 	for(key in data) {
			 		if(msg == "") {
			 			msg = '
<a tabindex="' + i + '" class="" data-normalized-text="A-1.1">'+ data[key]['name'] + '
';
			 		}
			 		else {
			 			msg += '
<a tabindex="' + i + '" class="" data-normalized-text="A-1.1">'+ data[key]['name'] + '
';
			 		}
			 	}
			 	$(".selectpicker.dropdown-menu").html(msg)
			 })
		});
	});
}
$(document).ready(ready);
$(document).on('page:load', ready);<commit_msg>set timing event for input changes<commit_after>// // Place all the behaviors and hooks related to the matching controller here.
// // All this logic will automatically be available in application.js.

var ready;
ready = function() {
	var typingTimer;
	var doneTypingInterval = 1000;

	$('.room_input').change(function() {
		clearTimeout(typingTimer);
		typingTimer = setTimeout(getValidRooms, doneTypingInterval);
	});

	function getValidRooms(){
		equipment_ids = [];
		$(".equipment:checked").each(function(){ equipment_ids.push($(this).attr('id'))});
		var data = {}
		data['room'] = {}

		data_1 = {
			size: $('#room_size').val(),
 			property: $('#').val(),
 			equipment: equipment_ids
 		};

 		var dict = {};
 		dict['equipment'] = {};
		for(i in equipment_ids ) {
			dict['equipment'][equipment_ids[i]]	=  $('#' + equipment_ids[i]).val();
		}
		data['room'] = data_1;

		$.ajax({
			url: '/rooms/getValidRooms',
			type: 'POST',
			data: data,
			dataType: 'json',
			beforeSend: function(xhr) {
			 	xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));},
			 success:(function(data){
			 	var i = 0;
			 	msg = "";
			 	for(key in data) {
			 		if(msg == "") {
			 			msg = '
<a tabindex="' + i + '" class="" data-normalized-text="A-1.1">'+ data[key]['name'] + '
';
			 		}
			 		else {
			 			msg += '
<a tabindex="' + i + '" class="" data-normalized-text="A-1.1">'+ data[key]['name'] + '
';
			 		}
			 	}
			 	$(".selectpicker.dropdown-menu").html(msg)
			 })
		});
	 }
}
$(document).ready(ready);
$(document).on('page:load', ready);<|endoftext|>


<commit_before>/**
 * Define Sp Site Object constructor
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.SP.Site = function(url) {

    // Set URL to current site if no url passed in.
    return this.url = url ? url : _spPageContextInfo.webAbsoluteUrl;
};

/**
 * Define Sp User Object constructor
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.SP.User = function(username) {

    // Set URL to current site if no url passed in.
    this.id = username ? username : _spPageContextInfo.userId;
    this.loginName = username ? username : _spPageContextInfo.userLoginName;
    this.isAdmin = username ? false : _spPageContextInfo.isSiteAdmin;
};

/**
 * Define Yam Object constructor & ensure login
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.Yam.User = function(userId) {

    if (!window.yam) {
        //@todo: Update error messages to SP notifications?
        console.log('Please ensure that you have included Yammer SDK and added a valid Client Id');
    }

    this.id = userId ? userId : 'current';
};

/**
 * Define Yam Object constructor & ensure login
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.Yam.Messages = function(feedId, feedType) {

    if (!window.yam) {
        //@todo: Update error messages to SP notifications?
        console.log('Please ensure that you have included Yammer SDK and added a valid Client Id');
    }

    this.feedId = feedId;
    this.feedType = feedType;

};
<commit_msg>chore(core): remove return on object declaration<commit_after>/**
 * Define Sp Site Object constructor
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.SP.Site = function(url) {

    // Set URL to current site if no url passed in.
    this.url = url ? url : _spPageContextInfo.webAbsoluteUrl;
};

/**
 * Define Sp User Object constructor
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.SP.User = function(username) {

    // Set URL to current site if no url passed in.
    this.id = username ? username : _spPageContextInfo.userId;
    this.loginName = username ? username : _spPageContextInfo.userLoginName;
    this.isAdmin = username ? false : _spPageContextInfo.isSiteAdmin;
};

/**
 * Define Yam Object constructor & ensure login
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.Yam.User = function(userId) {

    if (!window.yam) {
        //@todo: Update error messages to SP notifications?
        console.log('Please ensure that you have included Yammer SDK and added a valid Client Id');
    }

    this.id = userId ? userId : 'current';
};

/**
 * Define Yam Object constructor & ensure login
 * @params  url  url of Sharepoint site
 * @return  void
 */
SPOC.Yam.Messages = function(feedId, feedType) {

    if (!window.yam) {
        //@todo: Update error messages to SP notifications?
        console.log('Please ensure that you have included Yammer SDK and added a valid Client Id');
    }

    this.feedId = feedId;
    this.feedType = feedType;

};
<|endoftext|>


<commit_before>$(document).ready(function() {
    var copyTextBtn = document.querySelector('.copy-text-btn');

    copyTextBtn.addEventListener('click', function (event) {
        var copyTextarea = document.querySelector('.copy-text');
        copyTextarea.focus();
        copyTextarea.select();

        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copying text command was ' + msg);
        } catch (err) {
            console.log('Unable to copy');
        }
    });
});
<commit_msg>Convert global JS to JQuery<commit_after>$(document).ready(function() {
    var copyTextBtn = $('.copy-text-btn');

    $(copyTextBtn).on('click', function() {
        var copyTextarea = $('.copy-text');
        copyTextarea.focus();
        copyTextarea.select();
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copying text command was ' + msg);
        } catch (err) {
            console.log('Unable to copy');
        }
    });
});
<|endoftext|>


<commit_before>// @flow
/* eslint-disable react/prefer-stateless-function */

import React from "react";
import { Link, withRouter } from "react-router-dom";
import { Layout, Menu, Icon } from "antd";
import { connect } from "react-redux";
import Request from "libs/request";
import Utils from "libs/utils";
import LoginView from "admin/views/auth/login_view";
import { logoutUserAction } from "oxalis/model/actions/user_actions";
import Store from "oxalis/store";

import type { OxalisState } from "oxalis/store";
import type { APIUserType } from "admin/api_flow_types";
import type { ReactRouterHistoryType } from "react_router";

const { SubMenu } = Menu;
const { Header } = Layout;

type StateProps = {
  activeUser: ?APIUserType,
};

type Props = {
  isAuthenticated: boolean,
  history: ReactRouterHistoryType,
} & StateProps;

class Navbar extends React.PureComponent<Props> {
  handleLogout = async () => {
    await Request.receiveJSON("/api/auth/logout");
    Store.dispatch(logoutUserAction());
  };

  render() {
    const navbarStyle = {
      padding: 0,
      position: "fixed",
      width: "100%",
      zIndex: 1000,
      height: 48,
      display: "flex",
      alignItems: "center",
      color: "rgba(255, 255, 255, 0.67)",
      background: "#404040",
    };

    const isAuthenticated = this.props.isAuthenticated && this.props.activeUser != null;
    const isAdmin =
      this.props.activeUser != null ? Utils.isUserAdmin(this.props.activeUser) : false;

    const menuItems = [];
    menuItems.push(
      <Menu.Item key="/dashboard">
        <Link to="/dashboard">
          <Icon type="home" />
          Dashboard
        </Link>
      </Menu.Item>,
    );

    if (isAdmin) {
      menuItems.push(
        <SubMenu
          key="sub1"
          title={

              <Icon type="setting" />Administration

          }
        >
          <Menu.Item key="/users">
            <Link to="/users">Users</Link>
          </Menu.Item>
          <Menu.Item key="/teams">
            <Link to="/teams">Teams</Link>
          </Menu.Item>
          <Menu.Item key="/projects">
            <Link to="/projects">Projects</Link>
          </Menu.Item>
          <Menu.Item key="/tasks">
            <Link to="/tasks">Tasks</Link>
          </Menu.Item>
          <Menu.Item key="/taskTypes">
            <Link to="/taskTypes">Task Types</Link>
          </Menu.Item>
          <Menu.Item key="/scripts">
            <Link to="/scripts">Scripts</Link>
          </Menu.Item>
        </SubMenu>,
        <SubMenu
          key="sub2"
          title={

              <Icon type="line-chart" />Statistics

          }
        >
          <Menu.Item key="/statistics">
            <Link to="/statistics">Statistics</Link>
          </Menu.Item>
          <Menu.Item key="/reports/timetracking">
            <Link to="/reports/timetracking">Time Tracking</Link>
          </Menu.Item>
          <Menu.Item key="/reports/projectProgress">
            <Link to="/reports/projectProgress">Project Progress</Link>
          </Menu.Item>
          <Menu.Item key="/reports/openTasks">
            <Link to="/reports/openTasks">Open Tasks</Link>
          </Menu.Item>
        </SubMenu>,
      );
    }

    menuItems.push(
      <SubMenu
        key="sub3"
        title={

            <Icon type="medicine-box" />Help

        }
      >
        <Menu.Item key="11">

            Frontend API Documentation

        </Menu.Item>
        <Menu.Item key="/help/keyboardshortcuts">

            Keyboard Shortcuts

        </Menu.Item>
      </SubMenu>,
    );

    if (isAdmin) {
      menuItems.push(
        <Menu.Item key="13">

            <Icon type="notification" />
            Discussion Board

        </Menu.Item>,
      );
    }

    return (

        <Menu
          mode="horizontal"
          defaultSelectedkeys={[this.props.history.location.pathname]}
          style={{ lineHeight: "48px", flex: isAuthenticated ? "1" : undefined }}
          theme="dark"
        >
          <Menu.Item key="0">
            <Link to="/" style={{ fontWeight: 400 }}>

              webKnossos
            </Link>
          </Menu.Item>
          {isAuthenticated && this.props.activeUser != null
            ? menuItems.concat([
                <SubMenu
                  key="sub4"
                  className="pull-right"
                  title={

                      <Icon type="user" />
                      {`${this.props.activeUser.firstName} ${this.props.activeUser.lastName}`}

                  }
                >
                  <Menu.Item key="resetpassword">
                    <Link to="/auth/changePassword">Change Password</Link>
                  </Menu.Item>
                  <Menu.Item key="token">
                    <Link to="/auth/token">Auth Token</Link>
                  </Menu.Item>
                  <Menu.Item key="logout">
                    <Link to="/" onClick={this.handleLogout}>
                      Logout
                    </Link>
                  </Menu.Item>
                </SubMenu>,
              ])
            : null}
        </Menu>
        {!isAuthenticated ? (

            <LoginView layout="inline" />

        ) : null}

    );
  }
}

const mapStateToProps = (state: OxalisState): StateProps => ({
  activeUser: state.activeUser,
});

export default withRouter(connect(mapStateToProps)(Navbar));
<commit_msg>add redirect for login view within navbar<commit_after>// @flow
/* eslint-disable react/prefer-stateless-function */

import React from "react";
import { Link, withRouter } from "react-router-dom";
import { Layout, Menu, Icon } from "antd";
import { connect } from "react-redux";
import Request from "libs/request";
import Utils from "libs/utils";
import LoginView from "admin/views/auth/login_view";
import { logoutUserAction } from "oxalis/model/actions/user_actions";
import Store from "oxalis/store";

import type { OxalisState } from "oxalis/store";
import type { APIUserType } from "admin/api_flow_types";
import type { ReactRouterHistoryType } from "react_router";

const { SubMenu } = Menu;
const { Header } = Layout;

type StateProps = {
  activeUser: ?APIUserType,
};

type Props = {
  isAuthenticated: boolean,
  history: ReactRouterHistoryType,
} & StateProps;

class Navbar extends React.PureComponent<Props> {
  handleLogout = async () => {
    await Request.receiveJSON("/api/auth/logout");
    Store.dispatch(logoutUserAction());
  };

  render() {
    const navbarStyle = {
      padding: 0,
      position: "fixed",
      width: "100%",
      zIndex: 1000,
      height: 48,
      display: "flex",
      alignItems: "center",
      color: "rgba(255, 255, 255, 0.67)",
      background: "#404040",
    };

    const isAuthenticated = this.props.isAuthenticated && this.props.activeUser != null;
    const isAdmin =
      this.props.activeUser != null ? Utils.isUserAdmin(this.props.activeUser) : false;

    const menuItems = [];
    menuItems.push(
      <Menu.Item key="/dashboard">
        <Link to="/dashboard">
          <Icon type="home" />
          Dashboard
        </Link>
      </Menu.Item>,
    );

    if (isAdmin) {
      menuItems.push(
        <SubMenu
          key="sub1"
          title={

              <Icon type="setting" />Administration

          }
        >
          <Menu.Item key="/users">
            <Link to="/users">Users</Link>
          </Menu.Item>
          <Menu.Item key="/teams">
            <Link to="/teams">Teams</Link>
          </Menu.Item>
          <Menu.Item key="/projects">
            <Link to="/projects">Projects</Link>
          </Menu.Item>
          <Menu.Item key="/tasks">
            <Link to="/tasks">Tasks</Link>
          </Menu.Item>
          <Menu.Item key="/taskTypes">
            <Link to="/taskTypes">Task Types</Link>
          </Menu.Item>
          <Menu.Item key="/scripts">
            <Link to="/scripts">Scripts</Link>
          </Menu.Item>
        </SubMenu>,
        <SubMenu
          key="sub2"
          title={

              <Icon type="line-chart" />Statistics

          }
        >
          <Menu.Item key="/statistics">
            <Link to="/statistics">Statistics</Link>
          </Menu.Item>
          <Menu.Item key="/reports/timetracking">
            <Link to="/reports/timetracking">Time Tracking</Link>
          </Menu.Item>
          <Menu.Item key="/reports/projectProgress">
            <Link to="/reports/projectProgress">Project Progress</Link>
          </Menu.Item>
          <Menu.Item key="/reports/openTasks">
            <Link to="/reports/openTasks">Open Tasks</Link>
          </Menu.Item>
        </SubMenu>,
      );
    }

    menuItems.push(
      <SubMenu
        key="sub3"
        title={

            <Icon type="medicine-box" />Help

        }
      >
        <Menu.Item key="11">

            Frontend API Documentation

        </Menu.Item>
        <Menu.Item key="/help/keyboardshortcuts">

            Keyboard Shortcuts

        </Menu.Item>
      </SubMenu>,
    );

    if (isAdmin) {
      menuItems.push(
        <Menu.Item key="13">

            <Icon type="notification" />
            Discussion Board

        </Menu.Item>,
      );
    }

    return (

        <Menu
          mode="horizontal"
          defaultSelectedkeys={[this.props.history.location.pathname]}
          style={{ lineHeight: "48px", flex: isAuthenticated ? "1" : undefined }}
          theme="dark"
        >
          <Menu.Item key="0">
            <Link to="/" style={{ fontWeight: 400 }}>

              webKnossos
            </Link>
          </Menu.Item>
          {isAuthenticated && this.props.activeUser != null
            ? menuItems.concat([
                <SubMenu
                  key="sub4"
                  className="pull-right"
                  title={

                      <Icon type="user" />
                      {`${this.props.activeUser.firstName} ${this.props.activeUser.lastName}`}

                  }
                >
                  <Menu.Item key="resetpassword">
                    <Link to="/auth/changePassword">Change Password</Link>
                  </Menu.Item>
                  <Menu.Item key="token">
                    <Link to="/auth/token">Auth Token</Link>
                  </Menu.Item>
                  <Menu.Item key="logout">
                    <Link to="/" onClick={this.handleLogout}>
                      Logout
                    </Link>
                  </Menu.Item>
                </SubMenu>,
              ])
            : null}
        </Menu>
        {!isAuthenticated ? (

            <LoginView layout="inline" redirect={this.props.history.location.pathname} />

        ) : null}

    );
  }
}

const mapStateToProps = (state: OxalisState): StateProps => ({
  activeUser: state.activeUser,
});

export default withRouter(connect(mapStateToProps)(Navbar));
<|endoftext|>


<commit_before>/* File: images.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

/*jshint unused: true */
/*exported utils */

var utils = require('./utils'),
	request = require('supertest'),
	express = require('express'),
	imageService = require('../../../api/services/images'),
	app = express();

describe('Service:Image', function() {

	it('Service:Image:CropImage', function(done) {
		app.post('/images', function(req, res) {
			req.body = {
				DataCrop: {
					srcImg: 'test/spec/backend/files/cours.png',
					w: 596,
					h: 83,
					x: 96,
					y: 6
				}
			};
			imageService.cropImage(req, res);
		});
		request(app).post('/images').expect(200, done);
	});

	it('Service:Image:Oceriser', function(done) {
		app.post('/oceriser', function(req, res) {
			req.body = {
				sourceImage: 'test/spec/backend/files/image_a_oceriser.png'
			};
			imageService.oceriser(req, res);
		});
		request(app).post('/oceriser').expect(200, done);
	});

	it('Service:Image:ConvertsPdfToPng', function(done) {
		app.post('/pdfimage', function(req, res) {
			req.body = {
				pdfData: {
					source: 'test/spec/backend/files/grammaire.pdf',
					page: 0
				}
			};
			imageService.convertsPdfToPng(req, res);
		});
		request(app).post('/pdfimage').expect(200, done);
	});

	it('Service:Image:UploadFiles', function(done) {
		app.post('/fileupload', function(req, res) {
			req.files = {
				uploadedFile: [{
					fieldName: 'uploadedFile',
					originalFilename: 'cours.png',
					path: 'test/spec/backend/files/cours.png',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="cours.png"',
						'content-type': 'image/png'
					},
					size: 179151,
					name: 'cours.png',
					type: 'image/png'
				}, {
					fieldName: 'uploadedFile',
					originalFilename: 'exercice.jpg',
					path: 'test/spec/backend/files/exercice.jpg',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="exercice.jpg"',
						'content-type': 'image/jpg'
					},
					size: 179151,
					name: 'exercice.jpg',
					type: 'image/jpg'
				}, {
					fieldName: 'uploadedFile',
					originalFilename: 'grammaire.pdf',
					path: 'test/spec/backend/files/grammaire.pdf',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="grammaire.pdf"',
						'content-type': 'application/pdf'
					},
					size: 89386,
					name: 'grammaire.pdf',
					type: 'application/pdf'
				}]
			};
			imageService.uploadFiles(req, res);
		});
		request(app).post('/fileupload').expect(200, done);
	});

	it('Service:Image:TextToSpeech', function(done) {
		app.post('/texttospeech', function(req, res) {
			req.body = {
				text: 'Un example de texte'
			};
			imageService.textToSpeech(req, res);
		});
		request(app).post('/texttospeech').expect(200, done);
	});

	it('Service:Image:EspeakTextToSpeech', function(done) {
		app.post('/espeaktexttospeechdemo', function(req, res) {
			req.body = {
				text: 'Un example de texte'
			};
			imageService.espeakTextToSpeech(req, res);
		});
		request(app).post('/espeaktexttospeechdemo').expect(200, done);
	});

});<commit_msg>Commenter les tests unitaires coté Backend de la fonction ConvertsPdfToPng.<commit_after>/* File: images.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

/*jshint unused: true */
/*exported utils */

var utils = require('./utils'),
	request = require('supertest'),
	express = require('express'),
	imageService = require('../../../api/services/images'),
	app = express();

describe('Service:Image', function() {

	it('Service:Image:CropImage', function(done) {
		app.post('/images', function(req, res) {
			req.body = {
				DataCrop: {
					srcImg: 'test/spec/backend/files/cours.png',
					w: 596,
					h: 83,
					x: 96,
					y: 6
				}
			};
			imageService.cropImage(req, res);
		});
		request(app).post('/images').expect(200, done);
	});

	it('Service:Image:Oceriser', function(done) {
		app.post('/oceriser', function(req, res) {
			req.body = {
				sourceImage: 'test/spec/backend/files/image_a_oceriser.png'
			};
			imageService.oceriser(req, res);
		});
		request(app).post('/oceriser').expect(200, done);
	});

//	it('Service:Image:ConvertsPdfToPng', function(done) {
//		app.post('/pdfimage', function(req, res) {
//			req.body = {
//				pdfData: {
//					source: 'test/spec/backend/files/grammaire.pdf',
//					page: 0
//				}
//			};
//			imageService.convertsPdfToPng(req, res);
//		});
//		request(app).post('/pdfimage').expect(200, done);
//	});

	it('Service:Image:UploadFiles', function(done) {
		app.post('/fileupload', function(req, res) {
			req.files = {
				uploadedFile: [{
					fieldName: 'uploadedFile',
					originalFilename: 'cours.png',
					path: 'test/spec/backend/files/cours.png',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="cours.png"',
						'content-type': 'image/png'
					},
					size: 179151,
					name: 'cours.png',
					type: 'image/png'
				}, {
					fieldName: 'uploadedFile',
					originalFilename: 'exercice.jpg',
					path: 'test/spec/backend/files/exercice.jpg',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="exercice.jpg"',
						'content-type': 'image/jpg'
					},
					size: 179151,
					name: 'exercice.jpg',
					type: 'image/jpg'
				}, {
					fieldName: 'uploadedFile',
					originalFilename: 'grammaire.pdf',
					path: 'test/spec/backend/files/grammaire.pdf',
					headers: {
						'content-disposition': 'form-data; name="uploadedFile"; filename="grammaire.pdf"',
						'content-type': 'application/pdf'
					},
					size: 89386,
					name: 'grammaire.pdf',
					type: 'application/pdf'
				}]
			};
			imageService.uploadFiles(req, res);
		});
		request(app).post('/fileupload').expect(200, done);
	});

	it('Service:Image:TextToSpeech', function(done) {
		app.post('/texttospeech', function(req, res) {
			req.body = {
				text: 'Un example de texte'
			};
			imageService.textToSpeech(req, res);
		});
		request(app).post('/texttospeech').expect(200, done);
	});

	it('Service:Image:EspeakTextToSpeech', function(done) {
		app.post('/espeaktexttospeechdemo', function(req, res) {
			req.body = {
				text: 'Un example de texte'
			};
			imageService.espeakTextToSpeech(req, res);
		});
		request(app).post('/espeaktexttospeechdemo').expect(200, done);
	});

});<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');

module.exports = {
    rootDir: path.resolve(__dirname, '..'),
    srcDir: path.resolve(__dirname, '..', 'docs', 'nuxt'),
    dev: process.env.NODE_ENV !== 'production',

    head: {
        title: 'BootstrapVue',
        meta: [
            {charset: 'utf-8'},
            {name: 'viewport', content: 'width=device-width, initial-scale=1'}
        ],
        link: [
            {rel: 'icon', href: '/banner.png', sizes: '16x16', type: 'image/png'}
        ]
    },

    loading: {
        color: '#4fc08d'
    },

    build: {
        extend(config) {
            config.module.rules.push({
                test: /\.md$/,
                use: [
                    {loader: 'html-loader'},
                    {loader: 'highlight-loader'},
                    {loader: 'markdown-loader', options: {}}
                ]
            });
        }
    },

    generate: {
        dir: 'docs-dist',
        routes: () => {
            return fs.readdirSync('docs/components')
                .filter(c => c !== 'index.js' && c[0] !== '_')
                .map(component => '/docs/components/' + component);
        }
    },

    plugins: [
        '~plugins/bootstrap-vue.js',
        '~plugins/codemirror.js',
        '~plugins/ga.js'
    ],
    css: [
        path.resolve(__dirname, '../node_modules/bootstrap/dist/css/bootstrap.css'),
        path.resolve(__dirname, '../node_modules/highlightjs/styles/github-gist.css'),
        path.resolve(__dirname, '../node_modules/codemirror/lib/codemirror.css'),
        '~assets/css/docs.min.css',
        '~assets/css/styles.css'
    ]
};
<commit_msg>[docs] extractCSS<commit_after>const path = require('path');
const fs = require('fs');

module.exports = {
    rootDir: path.resolve(__dirname, '..'),
    srcDir: path.resolve(__dirname, '..', 'docs', 'nuxt'),
    dev: process.env.NODE_ENV !== 'production',

    head: {
        title: 'BootstrapVue',
        meta: [
            {charset: 'utf-8'},
            {name: 'viewport', content: 'width=device-width, initial-scale=1'}
        ],
        link: [
            {rel: 'icon', href: '/banner.png', sizes: '16x16', type: 'image/png'}
        ]
    },

    loading: {
        color: '#4fc08d'
    },

    build: {
        extractCSS: true,
        extend(config) {
            config.module.rules.push({
                test: /\.md$/,
                use: [
                    {loader: 'html-loader'},
                    {loader: 'highlight-loader'},
                    {loader: 'markdown-loader', options: {}}
                ]
            });
        }
    },

    generate: {
        dir: 'docs-dist',
        routes: () => {
            return fs.readdirSync('docs/components')
                .filter(c => c !== 'index.js' && c[0] !== '_')
                .map(component => '/docs/components/' + component);
        }
    },

    plugins: [
        '~plugins/bootstrap-vue.js',
        '~plugins/codemirror.js',
        '~plugins/ga.js'
    ],
    css: [
        path.resolve(__dirname, '../node_modules/bootstrap/dist/css/bootstrap.css'),
        path.resolve(__dirname, '../node_modules/highlightjs/styles/github-gist.css'),
        path.resolve(__dirname, '../node_modules/codemirror/lib/codemirror.css'),
        '~assets/css/docs.min.css',
        '~assets/css/styles.css'
    ]
};
<|endoftext|>


<commit_before>if (typeof Obtvse === 'undefined') {
  var displayGist = function(selector, gistResponse) {
    $(selector).html(gistResponse.div);
  };

  // TODO: bad, don't add functions to jQuery
  var getGist = function(id, success) {
    $.ajax({
          url: 'https://gist.github.com/' + id + '.json',
          dataType: 'jsonp',
          success: function(gist) {
            success("#" + id, gist);
          }
      });
  };

  Obtvse = {
    /**
     * Find all divs that should have gists fetched and rendered.
     *
     * The "id" attribute of the elements that match the given
     * selector should be equal to the gist id.
     */
    renderGists: function(selector) {
      $(selector).each(function() {
        getGist(this.id, displayGist)
      });
    }
  };
}<commit_msg>removed TODO<commit_after>if (typeof Obtvse === 'undefined') {
  var displayGist = function(selector, gistResponse) {
    $(selector).html(gistResponse.div);
  };

  var getGist = function(id, success) {
    $.ajax({
          url: 'https://gist.github.com/' + id + '.json',
          dataType: 'jsonp',
          success: function(gist) {
            success("#" + id, gist);
          }
      });
  };

  Obtvse = {
    /**
     * Find all divs that should have gists fetched and rendered.
     *
     * The "id" attribute of the elements that match the given
     * selector should be equal to the gist id.
     */
    renderGists: function(selector) {
      $(selector).each(function() {
        getGist(this.id, displayGist)
      });
    }
  };
}<|endoftext|>


<commit_before>$(document).ready(function() {
  hideAllSections();
  hideProjectSections():
  $("#about-content").show();

  $(".navItem").click(function(event) {
    event.preventDefault();
    hideProjectSections():
    showPanel(this);
    if (this.id == "resume") {
    //not showing on hosted version
      hideResumeSections();
      $("#technicalSkills-content").show();
    }
  });

  $(".resumeItem").click(function(event) {
    event.preventDefault();
    hideResumeSections();
    $("#" + this.id + "-content").show();
  });
//
//   $(".resumeItem").click(function(event) {
//     event.preventDefault();
//     showResumeSection(this);
//   });
//
  $(".contactButton").click(function(event) {
    event.preventDefault();
    showPanel(this);
  });
//
  $(".projectItem").click(function(event) {
    event.preventDefault();
    showProjectSections(this);
  });
//
});

function hideAllSections() {
  $("#projects-content").hide();
  $("#resume-content").hide();
  $("#blog-content").hide();
  $("#contact-content").hide();
  $("#about-content").hide();
  $("#trailInfo-content").hide();
  $("#altFuel-content").hide();
  $("#yogaFlow-content").hide();
}

function showPanel(section){
  hideAllSections();
   $("#" + section.id + "-content").show();
}

function hideResumeSections() {
  var items = document.querySelectorAll(".resumeSection");
  for (var i = 0; i < items.length; i++) {
    $("#" + items[i].id + "-content").hide();
  }
}

function hideProjectSections() {
  var items = document.querySelectorAll(".project");
  for (var i = 0; i < items.length; i++) {
    $("#" + items[i].id + "-content").hide();
  }
}

function showProjectSections(section) {
  hideAllSections();
  $("#" + section.id + "-content").show();
}
<commit_msg>loading pics<commit_after>$(document).ready(function() {
  hideAllSections();
  hideProjectSections():
  $("#about-content").show();

  $(".navItem").click(function(event) {
    event.preventDefault();
    hideProjectSections():
    showPanel(this);
    if (this.id == "resume") {
    //not showing on hosted version
      hideResumeSections();
      $("#technicalSkills-content").show();
    }
  });

  $(".resumeItem").click(function(event) {
    event.preventDefault();
    hideResumeSections();
    $("#" + this.id + "-content").show();
  });
//
//   $(".resumeItem").click(function(event) {
//     event.preventDefault();
//     showResumeSection(this);
//   });
//
  $(".contactButton").click(function(event) {
    event.preventDefault();
    showPanel(this);
  });
//
  $(".projectItem").click(function(event) {
    event.preventDefault();
    showProjectSections(this);
  });
//
});

function hideAllSections() {
  $("#projects-content").hide();
  $("#resume-content").hide();
  $("#blog-content").hide();
  $("#contact-content").hide();
  $("#about-content").hide();
  $("#trailInfo-content").hide();
  $("#altFuel-content").hide();
  $("#yogaFlow-content").hide();
}

function showPanel(section){
  hideAllSections();
   $("#" + section.id + "-content").show();
}

function hideResumeSections() {
  var items = document.querySelectorAll(".resumeSection");
  for (var i = 0; i < items.length; i++) {
    $("#" + items[i].id + "-content").hide();
  }
}

function hideProjectSections() {
  var items = document.querySelectorAll(".projectDisplay");
  for (var i = 0; i < items.length; i++) {
    $("#" + items[i].id + "-content").hide();
  }
}

function showProjectSections(section) {
  hideAllSections();
  $("#" + section.id + "-content").show();
}
<|endoftext|>


<commit_before>'use strict';

var syncExec = require('sync-exec');
var assert = require('assert');
var fs = require('fs');

// JS Only
describe('lint - Source', function(){

  var jsResult = './test/logs/lint-source-js.txt';

  var js = 'eslint' +
        ' --ext .js' +
        ' -c .eslintrc' +
        ' --ignore-path .eslintignore' +
        ' --quiet' +
        ' src/*';

  it('it should pass', function(done){

    syncExec('mkdir -p ./test/logs; rm -f ' + jsResult);

    var result = syncExec(js);

    if (result){
      fs.writeFile(jsResult, result, function(){});
    }

    assert.equal(result.stdout, '');
    assert.equal(result.stderr, '');
    assert.equal(result.status, 0);

    done();
  });
});
<commit_msg>[updated] linter spec<commit_after>'use strict';

var syncExec = require('sync-exec');
var assert = require('assert');

// JS Only
describe('lint - Source', function(){

  var js = 'eslint' +
        ' --ext .js' +
        ' -c .eslintrc' +
        ' --ignore-path .eslintignore' +
        ' --quiet' +
        ' src/*';

  it('it should pass', function(done){

    var result = syncExec(js);

    assert.equal(result.stdout, '');
    assert.equal(result.stderr, '');
    assert.equal(result.status, 0);

    done();
  });
});
<|endoftext|>


<commit_before>// Survey scripts
$('#user_meeting_meeting_time').datetimepicker({
  dateFormat: 'D dd M yy',
  timeFormat: 'HH:mm:ss z',
  timezoneList: [
    { value: -300, label: 'Eastern'},
    { value: -360, label: 'Central' },
    { value: -420, label: 'Mountain' },
    { value: -480, label: 'Pacific' }
  ]
});

/*
 * Helper function to make hiding/showing/clear more DRY
 *
 * @param changeNode The jquery object node to watch for changes
 * @param hideNode the jquery object node to hide
 * @param checkVal the string value to check for (if true, hide)
 * @param clearField the jquery object to clear the value of
 */
hideShowClear = function (changeNode, hideNode, checkVal, clearField)
{
  changeNode.change(function ()
  {
    if (this.value === checkVal)
    {
      hideNode.removeClass('hide');
    }
    else
    {
      hideNode.addClass('hide');

      if (clearField !== false) clearField.val('');
    }
  });
};

// show/hide meeting text field
hideShowClear($('#meeting_type'), $('#meeting_type_explaination').parent().parent(),
  'Other', $('#meeting_type_explaination') );

// show/hide invocation-related fields
hideShowClear($('#invocation_conducted'), $('.invocation_only'),
  'Yes', false );

// show/hide speaker preaching explanation
hideShowClear($('#speaker_preached'), $('#preached_explain').parent().parent(),
  'Yes', $('preached_explain') );

// show/hide religion fields
hideShowClear($('#religion'), $('#other_religion').parent().parent(),
  'Other', $('#other_religion'));

// show/hide denomination fields
hideShowClear($('#denomination'), $('#other_denomination').parent().parent(),
  'Other', $('#other_denomination'));

// show/hide praised fields
hideShowClear($('#speaker_praised'), $('#praised_explain').parent().parent(),
  'Yes', $('#praised_explain'));

// submit validation
$('#submit').click(function(e)
{
  if ($('#policy:checked').val() !== 'on')
  {
    alert('Please review and agree to the policy before submission.');
    e.preventDefault();
  }
  else
  {// todo remove alert and preventDefaul() when the form can actually post
    alert("Submitted! Well, not really. This is just a placeholder. ")
    e.preventDefault();
  }
});

<commit_msg>Added show/hide functionality.<commit_after>// Survey scripts
$('#user_meeting_meeting_time').datetimepicker({
  dateFormat: 'D dd M yy',
  timeFormat: 'HH:mm:ss z',
  timezoneList: [
    { value: -300, label: 'Eastern'},
    { value: -360, label: 'Central' },
    { value: -420, label: 'Mountain' },
    { value: -480, label: 'Pacific' }
  ]
});

/*
 * Helper function to make hiding/showing/clear more DRY
 *
 * @param changeNode The jquery object node to watch for changes
 * @param hideNode the jquery object node to hide
 * @param checkVal the string value to check for (if true, hide)
 * @param clearField the jquery object to clear the value of
 */
hideShowClear = function (changeNode, hideNode, checkVal, clearField)
{
  changeNode.change(function ()
  {
    if (this.value === checkVal)
    {
      hideNode.removeClass('hide');
    }
    else
    {
      hideNode.addClass('hide');

      if (clearField !== false) clearField.val('');
    }
  });
};

// show/hide invocation-related fields
hideShowClear($('#user_meeting_invocation_conducted'), $('.invocation_only'),
  'Yes', false );

// show/hide speaker preaching explanation
var preached = $('#user_meeting_speaker_preached');
hideShowClear(preached, preached.next(),
  'Yes, Explain', preached.next() );

// show/hide praised fields
var praised = $('#user_meeting_speaker_praised');
hideShowClear(praised, praised.next(),
  'Yes, Explain', praised.next());

// submit validation
$('#submit').click(function(e)
{
  if ($('#policy:checked').val() !== 'on')
  {
    alert('Please review and agree to the policy before submission.');
    e.preventDefault();
  }
  else
  {// todo remove alert and preventDefaul() when the form can actually post
    alert("Submitted! Well, not really. This is just a placeholder. ")
    e.preventDefault();
  }
});

<|endoftext|>


<commit_before>
// Can anyone fill in the blanks??

var scaleModes = {
    major: {
        ionian:  	[2,2,1,2,2,2,1], // last 1 added for 'wrap around'
        dorian: 	[2,1,2,2,2,1, "?"],
        phyrigian:  [1,2,2,2,1,2, "?"],
        lydian:     [2,2,2,1,2,2, "?"],
        mixolydian: [2,2,1,2,2,1, "?"],
        aeolian:    [2,1,2,2,1,2, "?"],
        locrian:    [1,2,2,1,2,2, "?"]
    },
    harmonic_minor: {
        harmminor: 		[2,1,2,2,1,3, "?"],
        locriansharpsix:[1,2,2,1,3,1, "?"],
        ionianaug:     	[2,2,1,3,1,2, "?"],
        romanian: 		[2,1,3,1,2,1, "?"],
        phrygiandom:   	[1,3,1,2,1,2, "?"],
        lydiansharptwo: [3,1,2,1,2,2, "?"],
        ultralocrian:   [1,2,1,2,2,1, "?"]
    },
    melodic_minor: {
        jazz_minor: 		[2,1,2,2,2,2, "?"],
        dorianflatnine: 	[1,2,2,2,2,1, "?"],
        lydianaug: 			[2,2,2,2,1,2, "?"],
        lydiandom: 			[2,2,2,1,2,1, "?"],
        mixolydianflatsix: 	[2,2,1,2,1,2, "?"],
        semilocrian: 		[2,1,2,1,2,2, "?"],
        superlocrian: 		[1,2,1,2,2,2, "?"]
    }
};<commit_msg>'wrap around' intervals added - still to be verified<commit_after>
// Can anyone fill in the blanks??

var scaleModes = {
    major: {
        ionian:  	[2,2,1,2,2,2,1], // last 1 added for 'wrap around'
        dorian: 	[2,1,2,2,2,1,2],
        phyrigian:  [1,2,2,2,1,2,2],
        lydian:     [2,2,2,1,2,2,1],
        mixolydian: [2,2,1,2,2,1,2],
        aeolian:    [2,1,2,2,1,2,2],
        locrian:    [1,2,2,1,2,2,2]
    },
    harmonic_minor: {
        harmminor: 		[2,1,2,2,1,3,1],
        locriansharpsix:[1,2,2,1,3,1,2],
        ionianaug:     	[2,2,1,3,1,2,1],
        romanian: 		[2,1,3,1,2,1,2],
        phrygiandom:   	[1,3,1,2,1,2,2],
        lydiansharptwo: [3,1,2,1,2,2,1],
        ultralocrian:   [1,2,1,2,2,1,3]
    },
    melodic_minor: {
        jazz_minor: 		[2,1,2,2,2,2,1],
        dorianflatnine: 	[1,2,2,2,2,1,2],
        lydianaug: 			[2,2,2,2,1,2,1],
        lydiandom: 			[2,2,2,1,2,1,2],
        mixolydianflatsix: 	[2,2,1,2,1,2,2],
        semilocrian: 		[2,1,2,1,2,2,2],
        superlocrian: 		[1,2,1,2,2,2,2]
    }
};<|endoftext|>


<commit_before>angular.module('YoutubeRemote').factory('socket', function($rootScope) {
	var host = location.origin.replace(/^https/, 'http');
	var server = io.connect(host);
	return {
		on: function (eventName, callback) {
			server.on(eventName, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					callback.apply(server, args);
				});
			});
		},
		emit: function (eventName, data, callback) {
			server.emit(eventName, data, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					if (callback) {
						callback.apply(socket, args);
					}
				});
			});
		}
	};
});<commit_msg>Reconfig host url<commit_after>angular.module('YoutubeRemote').factory('socket', function($rootScope) {
	var host = location.origin;
	var server = io.connect(host);
	return {
		on: function (eventName, callback) {
			server.on(eventName, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					callback.apply(server, args);
				});
			});
		},
		emit: function (eventName, data, callback) {
			server.emit(eventName, data, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					if (callback) {
						callback.apply(socket, args);
					}
				});
			});
		}
	};
});<|endoftext|>


<commit_before>var player = {
    "name": "Ness",
    "face": 3,
    "skin": [217, 183, 31],
    "hair": 0,
    "hairColor": [0, 0, 0],
    "tshirt": 'e',
    "tColor": [255, 0, 0],
    'hp': 50,
    'mp': 10,
    'maxhp': 50,
    'maxmp': 10,
    'xp': 0,
    'nextLevel': 100,
    'money': 0,
     x: 300,
     y: 200
 };

var command = 'Enter X';
 var thingToBeEntered = 'ThingToBeEntered';
var enteredText = '';
 var text = document.getElementById('textArea');
 var playArea = document.getElementById('playArea');
 var sumbit = document.getElementById('submitButtonArea');
var textInput = document.getElementById('textInput');

function pickFace() {
  text.innerHTML = 'Pick a face shape:';
  var thingie = '<button onclick="setFaceShape(0)">()</button> '
  thingie += '<button onclick="setFaceShape(1)">( )</button>';
  thingie += '<button onclick="setFaceShape(2)">(  )</button>';
  thingie += '<button onclick="setFaceShape(3)">(   )</button>';
  thingie += '<button onclick="pickSkin()">OK</button>';
  sumbit.innerHTML = thingie;
}

function submitText() {
  switch(thingToBeEntered) {
    case 'name':
      player.name = enteredText;
      document.getElementById('name').innerHTML = player.name;
      pickFace();
      break;
  }
}

function deleteText() {
  if (enteredText.length > 0) {
    enteredText = enteredText.substr(0,enteredText.length-1);
    text.innerHTML = command + enteredText;
    if (thingToBeEntered == 'name'){
      document.getElementById('name').innerHTML = enteredText;
    }
  }
}

function UConScreenKeyboard() {
  var abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  var thingie = '';
  for (var i = 0; i < abc.length; i++) {
    abc[i] = abc[i].toUpperCase();
    thingie += '<button onclick="enterLetter(\''+ abc[i] + '\')">' + abc[i] + '</button>' ;
  }
  thingie += '<button onclick="enterLetter(\' \')">_</button>';
  thingie += '<button onclick="LConScreenKeyboard()">A^a</button>';
  thingie += '<button onclick="deleteText()">Del</button>';
  thingie += '<button onclick="submitText()">OK</button>';
  sumbit.innerHTML = thingie;
}

function LConScreenKeyboard() {
  var abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  var thingie = '';
  for (var i = 0; i < abc.length; i++) {
    thingie += '<button onclick="enterLetter(\''+ abc[i] + '\')">' + abc[i] + '</button>' ;
  }
  thingie += '<button onclick="enterLetter(\' \')">_</button>';
  thingie += '<button onclick="UConScreenKeyboard()">a^A</button>';
  thingie += '<button onclick="deleteText()">Del</button>';
  thingie += '<button onclick="submitText()">OK</button>';
  sumbit.innerHTML = thingie;
}

function enterLetter(l) {
  enteredText += l;
  text.innerHTML = command + enteredText;
  if (thingToBeEntered == 'name'){
    document.getElementById('name').innerHTML = enteredText;
  }
  if (enteredText.length = 1) {
    LConScreenKeyboard();
  }
}

function enterName() {
  command = 'Enter name: ';
  text.innerHTML = command;
  thingToBeEntered = 'name';
  enteredText = '';
  text.innerHTML = command + enteredText;
  document.getElementById('name').innerHTML = enteredText;
  UConScreenKeyboard();
}

function pickSkin() {
     text.innerHTML = 'Pick skin tone:';
     var thingie = '<button class="skin0" onclick="setSkinTone(0)">_</button> ';
     thingie += '<button class="skin1" onclick="setSkinTone(1)">_</button> ';
     thingie += '<button class="skin2" onclick="setSkinTone(2)">_</button> ';
     thingie += '<button class="skin3" onclick="setSkinTone(3)">_</button> ';
     thingie += '<button class="skin4" onclick="setSkinTone(4)">_</button> ';
     thingie += '<button onclick="pickShirt()">OK</button>';
     sumbit.innerHTML = thingie;
}

function pickShirtColor() {
     text.innerHTML = 'Pick shirt color:';
     var thingie = '<button class="shirt0" onclick="setShirtColor(0)">_</button> ';
     thingie += '<button class="shirt1" onclick="setShirtColor(1)">_</button> ';
     thingie += '<button class="shirt2" onclick="setShirtColor(2)">_</button> ';
     sumbit.innerHTML = thingie;
}

function setShirtColor(o) {
  switch(o) {
  case 0:
    player.tColor = [255,0,0];
    break;
  case 1:
    player.tColor = [0,100,0];
    break;
  case 2:
    player.tColor = [0,0,255];
    break;
  }
}

function pickShirt() {
     text.innerHTML = 'Pick tshirt logo:';
     var thingie = '<button onclick="setTshirt(2.7)">e</button> ';
     thingie += '<button onclick="setTshirt(3.14)">π</button> ';
     thingie += '<button onclick="setTshirt(6.2)">τ</button> ';
     thingie += '<button onclick="setTshirt(0)">ϕ</button> ';
     thingie += '<button onclick="setTshirt(1)">μ</button> ';
     thingie += '<button onclick="setTshirt(2)">λ</button> ';
     thingie += '<button onclick="pickShirtColor()">OK</button>';
     sumbit.innerHTML = thingie;
}

function setTshirt(o) {
  switch(o) {
   case 3.14:
     player.tshirt = 'π';
     break;
   case 2.7:
     player.tshirt = 'e';
     break;
   case 6.2:
     player.tshirt = 'τ';
     break;
   case 0:
     player.tshirt = 'ϕ';
     break;
   case 1:
     player.tshirt = 'μ';
     break;
   case 2:
     player.tshirt = 'λ';
     break;
  }
}

function setFaceShape(o) {
  player.face = o;
}

function setSkinTone(o) {
  switch(o) {
  case 0:
    player.skin = [141,85,36];
    break;
  case 1:
    player.skin = [198,134,66];
    break;
  case 2:
    player.skin = [224,172,105];
    break;
  case 3:
    player.skin = [241,194,125];
    break;
  case 4:
    player.skin = [255,219,172];
    break;
  }
}

/*
function updateStats() {
    document.getElementById('hp').innerHTML = 'HP: ' + player.hp + '/' + player.maxhp;
    document.getElementById('mp').innerHTML = 'MP: ' + player.mp + '/' + player.maxmp;
    document.getElementById('xp').innerHTML = 'XP: ' + player.xp + '/' + player.nextLevel;
    document.getElementById('money').innerHTML = '$' + player.money;
}
*/

enterName();
//updateStats();
<commit_msg>Update charCreation.js<commit_after>var player = {
    "name": "Ness",
    "face": 3,
    "skin": [217, 183, 31],
    "hair": 0,
    "hairColor": [0, 0, 0],
    "tshirt": 'e',
    "tColor": [255, 0, 0],
    'hp': 50,
    'mp': 10,
    'maxhp': 50,
    'maxmp': 10,
    'xp': 0,
    'nextLevel': 100,
    'money': 0,
     x: 300,
     y: 200
 };

var command = 'Enter X';
 var thingToBeEntered = 'ThingToBeEntered';
var enteredText = '';
 var text = document.getElementById('textArea');
 var playArea = document.getElementById('playArea');
 var sumbit = document.getElementById('submitButtonArea');
var textInput = document.getElementById('textInput');

function pickFace() {
  text.innerHTML = 'Pick a face shape:';
  var thingie = '<button onclick="setFaceShape(0)">()</button> '
  thingie += '<button onclick="setFaceShape(1)">( )</button>';
  thingie += '<button onclick="setFaceShape(2)">(  )</button>';
  thingie += '<button onclick="setFaceShape(3)">(   )</button>';
  thingie += '<button onclick="pickSkin()">OK</button>';
  sumbit.innerHTML = thingie;
}

function submitText() {
  switch(thingToBeEntered) {
    case 'name':
      player.name = enteredText;
      document.getElementById('name').innerHTML = player.name;
      pickFace();
      break;
  }
}

function deleteText() {
  if (enteredText.length > 0) {
    enteredText = enteredText.substr(0,enteredText.length-1);
    text.innerHTML = command + enteredText;
    if (thingToBeEntered == 'name'){
      document.getElementById('name').innerHTML = enteredText;
    }
  }
}

function UConScreenKeyboard() {
  var abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  var thingie = '';
  for (var i = 0; i < abc.length; i++) {
    abc[i] = abc[i].toUpperCase();
    thingie += '<button onclick="enterLetter(\''+ abc[i] + '\')">' + abc[i] + '</button>' ;
  }
  thingie += '<button onclick="enterLetter(\' \')">_</button>';
  thingie += '<button onclick="LConScreenKeyboard()">A^a</button>';
  thingie += '<button onclick="deleteText()">Del</button>';
  thingie += '<button onclick="submitText()">OK</button>';
  sumbit.innerHTML = thingie;
}

function LConScreenKeyboard() {
  var abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  var thingie = '';
  for (var i = 0; i < abc.length; i++) {
    thingie += '<button onclick="enterLetter(\''+ abc[i] + '\')">' + abc[i] + '</button>' ;
  }
  thingie += '<button onclick="enterLetter(\' \')">_</button>';
  thingie += '<button onclick="UConScreenKeyboard()">a^A</button>';
  thingie += '<button onclick="deleteText()">Del</button>';
  thingie += '<button onclick="submitText()">OK</button>';
  sumbit.innerHTML = thingie;
}

function enterLetter(l) {
  enteredText += l;
  text.innerHTML = command + enteredText;
  if (thingToBeEntered == 'name'){
    document.getElementById('name').innerHTML = enteredText;
  }
  if (enteredText.length = 1) {
    LConScreenKeyboard();
  }
}

function enterName() {
  command = 'Enter name: ';
  text.innerHTML = command;
  thingToBeEntered = 'name';
  enteredText = '';
  text.innerHTML = command + enteredText;
  document.getElementById('name').innerHTML = enteredText;
  UConScreenKeyboard();
}

function pickSkin() {
     text.innerHTML = 'Pick skin tone:';
     var thingie = '<button class="skin0" onclick="setSkinTone(0)">_</button> ';
     thingie += '<button class="skin1" onclick="setSkinTone(1)">_</button> ';
     thingie += '<button class="skin2" onclick="setSkinTone(2)">_</button> ';
     thingie += '<button class="skin3" onclick="setSkinTone(3)">_</button> ';
     thingie += '<button class="skin4" onclick="setSkinTone(4)">_</button> ';
     thingie += '<button onclick="pickShirt()">OK</button>';
     sumbit.innerHTML = thingie;
}

function pickShirtColor() {
     text.innerHTML = 'Pick shirt color:';
     var thingie = '<button class="shirt0" onclick="setShirtColor(0)">_</button> ';
     thingie += '<button class="shirt1" onclick="setShirtColor(1)">_</button> ';
     thingie += '<button class="shirt2" onclick="setShirtColor(2)">_</button> ';
     sumbit.innerHTML = thingie;
}

function setShirtColor(o) {
  switch(o) {
  case 0:
    player.tColor = [255,0,0];
    break;
  case 1:
    player.tColor = [0,100,0];
    break;
  case 2:
    player.tColor = [0,0,255];
    break;
  }
}

function pickShirt() {
     text.innerHTML = 'Pick tshirt logo:';
     var thingie = '<button onclick="setTshirt(2.7)">e</button> ';
     thingie += '<button onclick="setTshirt(3.14)">π</button> ';
     thingie += '<button onclick="setTshirt(6.2)">τ</button> ';
     thingie += '<button onclick="setTshirt(0)">ϕ</button> ';
     thingie += '<button onclick="setTshirt(1)">μ</button> ';
     thingie += '<button onclick="setTshirt(2)">λ</button> ';
     thingie += '<button onclick="pickShirtColor()">OK</button>';
     sumbit.innerHTML = thingie;
}

function setTshirt(o) {
  switch(o) {
   case 3.14:
     player.tshirt = 'π';
     break;
   case 2.7:
     player.tshirt = 'e';
     break;
   case 6.2:
     player.tshirt = 'τ';
     break;
   case 0:
     player.tshirt = 'ϕ';
     break;
   case 1:
     player.tshirt = 'μ';
     break;
   case 2:
     player.tshirt = 'λ';
     break;
  }
}

function setFaceShape(o) {
  player.face = o;
}

function setSkinTone(o) {
  switch(o) {
  case 0:
    player.skin = [141,85,36];
    break;
  case 1:
    player.skin = [198,134,66];
    break;
  case 2:
    player.skin = [224,172,105];
    break;
  case 3:
    player.skin = [241,194,125];
    break;
  case 4:
    player.skin = [255,219,172];
    break;
  }
}

function updateStats() {
    document.getElementById('hp').innerHTML = 'HP: ' + player.hp + '/' + player.maxhp;
    document.getElementById('mp').innerHTML = 'MP: ' + player.mp + '/' + player.maxmp;
    document.getElementById('xp').innerHTML = 'XP: ' + player.xp + '/' + player.nextLevel;
    document.getElementById('money').innerHTML = '$' + player.money;
}

enterName();
updateStats();
<|endoftext|>