<commit_before>App.cfg['App.supromongod.view.SuproMongoDB'] = {
    __noctl: true,// view-only stuff uses fast init
    extend: App.view.Window,
    title: l10n.mongo.title,
    wmTooltip: l10n.mongo.modname,
    wmImg: App.backendURL + '/css/supromongod/logo-mongodb.png',
    wmId: 'supromongod.view.SuproMongoDB',
    id: 'supromongod-view-SuproMongoDB',
    requires: ['App.supromongod.view.ControlTools'],
    width: 777, height: 477,// initial
    layout: 'fit',
    bodyStyle:
'font-family: "Lucida Console" monospace; font-size: 10pt;' +
'background-color: black; color: #00FF00;',
    autoScroll: true,
    initComponent: function initSuproMongoDBComponent(){
        this.items = [
        {
            xtype: 'component',
            style: 'white-space: pre-wrap',
            html: l10n.mongo.noload,
            itemId:'log'
        }
        ]
        this.dockedItems = [
        {
            xtype: 'toolbar',
            dock: 'top',
            items:['-',
            {
                xtype: 'component',
                html: l10n.mongo.status,
                itemId: 'status'
            },'->','-',
            {
                text: 'mongo-edit',
                iconCls: 'sm-me',
                tooltip: 'run it manually by script etc/_mongo_edit.[sh,cmd]',
                href: 'http://localhost:2764/'
            },'-',
            {
                text: 'admin web console',
                iconCls: 'sm-ac',
                tooltip: 'enabled by --rest --httpinterface options',
                href: 'http://localhost:' + (
                    App.User.modules.extjs.mongodb_port + 1000
                ) + '/'
            },'-',
            {
                text: l10n.mongo.refreshLog
               ,iconCls: 'sm-rl'
               ,handler: function(toolbar){
                    App.backend.req('/supromongod/lib/api/log',
                    function(err, json){
                        if(!err && 'string' == typeof json){// expecting text
                            err = toolbar.up('panel')
                            err.down('#log').update(json)
                            err.scrollBy(0, 1 << 22, false)
                            return
                        }
                        // json = { success: false, err: "foo" }
                        Ext.Msg.show({
                            title: l10n.errun_title,
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.ERROR,
                            msg: l10n.errapi + '
' + json.err + ''
                        })
                    })
                }
            },
            {
                text: l10n.stsClean
               ,iconCls: 'sm-cl'
               ,handler: function(toolbar){
                    toolbar.up('panel').down('#log').update('')
                }
            }
            ]
        },
            Ext.create('App.supromongod.view.ControlTools')
        ]
        this.callParent()

        this.on('destroy', function(){
           App.backend.req('/supromongod/lib/dev')
        })
    }
}
<commit_msg>define ns for class loader: Ext('App.supromongod.view.SuproMongoDB')<commit_after>Ext.ns ('App.supromongod.view.SuproMongoDB')    // define ns for class loader
App.cfg['App.supromongod.view.SuproMongoDB'] = {// fast init
    __noctl: true,// view-only stuff uses fast init
    extend: App.view.Window,
    title: l10n.mongo.title,
    wmTooltip: l10n.mongo.modname,
    wmImg: App.backendURL + '/css/supromongod/logo-mongodb.png',
    wmId: 'supromongod.view.SuproMongoDB',
    id: 'supromongod-view-SuproMongoDB',
    requires: ['App.supromongod.view.ControlTools'],
    width: 777, height: 477,// initial
    layout: 'fit',
    bodyStyle:
'font-family: "Lucida Console" monospace; font-size: 10pt;' +
'background-color: black; color: #00FF00;',
    autoScroll: true,
    initComponent: function initSuproMongoDBComponent(){
        this.items = [
        {
            xtype: 'component',
            style: 'white-space: pre-wrap',
            html: l10n.mongo.noload,
            itemId:'log'
        }
        ]
        this.dockedItems = [
        {
            xtype: 'toolbar',
            dock: 'top',
            items:['-',
            {
                xtype: 'component',
                html: l10n.mongo.status,
                itemId: 'status'
            },'->','-',
            {
                text: 'mongo-edit',
                iconCls: 'sm-me',
                tooltip: 'run it manually by script etc/_mongo_edit.[sh,cmd]',
                href: 'http://localhost:2764/'
            },'-',
            {
                text: 'admin web console',
                iconCls: 'sm-ac',
                tooltip: 'enabled by --rest --httpinterface options',
                href: 'http://localhost:' + (
                    App.User.modules.extjs.mongodb_port + 1000
                ) + '/'
            },'-',
            {
                text: l10n.mongo.refreshLog
               ,iconCls: 'sm-rl'
               ,handler: function(toolbar){
                    App.backend.req('/supromongod/lib/api/log',
                    function(err, json){
                        if(!err && 'string' == typeof json){// expecting text
                            err = toolbar.up('panel')
                            err.down('#log').update(json)
                            err.scrollBy(0, 1 << 22, false)
                            return
                        }
                        // json = { success: false, err: "foo" }
                        Ext.Msg.show({
                            title: l10n.errun_title,
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.ERROR,
                            msg: l10n.errapi + '
' + json.err + ''
                        })
                    })
                }
            },
            {
                text: l10n.stsClean
               ,iconCls: 'sm-cl'
               ,handler: function(toolbar){
                    toolbar.up('panel').down('#log').update('')
                }
            }
            ]
        },
            Ext.create('App.supromongod.view.ControlTools')
        ]
        this.callParent()

        this.on('destroy', function(){
           App.backend.req('/supromongod/lib/dev')
        })
    }
}
<|endoftext|>


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

    describe('AgendaControllerTest', function () {

        beforeEach(module('scoreApp', 'Mocks', 'stateMock'));
        var self = this;
        const ID_LOCAL_TEST = 1;

        let createController, $scope, config, LocaisMock, ReservasMock,
            AuthService, dependenciasController, $mdDialog, ModalService,
            Reserva, TIPOS_RESERVA;

        beforeEach(inject(defaultInjections(self)));
        afterEach(defaultAfterEach(self));

        beforeEach(inject(function ($injector, $controller, uiCalendarConfig, _LocaisMock_, _AuthService_, _ReservasMock_, _ModalService_, _Reserva_, _TIPOS_RESERVA_) {

            $mdDialog = $injector.get('$mdDialog');
            $scope = self.$rootScope.$new();
            config = uiCalendarConfig;
            LocaisMock = _LocaisMock_;
            AuthService = _AuthService_;
            ReservasMock = _ReservasMock_;
            ModalService = _ModalService_;
            Reserva = _Reserva_;
            TIPOS_RESERVA = _TIPOS_RESERVA_;

            config.calendars = {
                calendario: {
                   fullCalendar: function () {
                       return {type: 'agendaDay'};
                   }
                }
            };

            dependenciasController = {
                $scope,
                local: LocaisMock.getLocal({_id: ID_LOCAL_TEST}),
                uiCalendarConfig: config,
                AuthService,
                ModalService,
                Reserva,
                TIPOS_RESERVA
            };

            createController = function () {
                self.$httpBackend.expectGET(`/api/locais/${ID_LOCAL_TEST}/reservas`).respond([ReservasMock.getReserva()]);
                const controller = $controller('AgendaController as agendaCtrl',dependenciasController);
                self.$httpBackend.flush();

                return controller;
            };
        }));

        describe('AgendaController visualizarReserva deve', () => {
            let controller;
            beforeEach(() => {
                controller = createController();
            });

            it('chamar modal de para visualização de reserva e atualizar as reservas no calendario', done => {
                ModalService.verReserva = sinon.stub().returns(self.$q.when());
                config.calendars.calendario.fullCalendar = sinon.stub();

                controller.visualizarReserva({}).should.be.fulfilled.then(() => {
                    sinon.assert.called(ModalService.verReserva);

                    sinon.assert.calledWith(config.calendars.calendario.fullCalendar, 'removeEvents');
                    sinon.assert.calledWith(config.calendars.calendario.fullCalendar, 'addEventSource', _.first(controller.reservasSource));
                }).should.notify(done);
                $scope.$digest();
            });
        });

        describe('AgendaController calendarioConfig deve', function () {
            let controller;
            beforeEach(() => {
                controller = createController();
            });

            it('ter propriedade calendario.ignoreTimezone como false', () => {
                expect(controller.calendarioConfig.calendario.ignoreTimezone).to.be.false;
            });

            it('ter propriedade calendario.timezone como "local"', () => {
                expect(controller.calendarioConfig.calendario.timezone).to.be.eql('local');
            });
        });

        describe('clickDia deve', function () {

            let controller;

            beforeEach(inject(function () {
                controller = createController();

                AuthService.userTemPermissao = sinon.stub().returns(true);
                $mdDialog.show = sinon.stub();
            }));

           it('Não permitir criação de reservas em horários passados', function () {
               var dataPassada = new Date();
               dataPassada.setFullYear(1980);
               dataPassada.setMonth(10);
               dataPassada.setDate(15);

               controller.clickDia(moment(dataPassada));
               sinon.assert.notCalled($mdDialog.show);
           });

            it('Permitir criação de reservas em horários futuros', function () {
                var dataFutura = new Date(Date.now());
                dataFutura.setMonth(dataFutura.getMonth() + 1);

                controller.clickDia(moment(dataFutura));
                sinon.assert.called($mdDialog.show);
            });

        });

    });
})();
<commit_msg>Testes consertados<commit_after>(function () {
    'use strict';

    describe('AgendaControllerTest', function () {

        beforeEach(module('scoreApp', 'Mocks', 'stateMock'));
        var self = this;
        const ID_LOCAL_TEST = 1;

        let createController, $scope, config, LocaisMock, ReservasMock,
            AuthService, dependenciasController, $mdDialog, ModalService,
            Reserva, TIPOS_RESERVA;

        beforeEach(inject(defaultInjections(self)));
        afterEach(defaultAfterEach(self));

        beforeEach(inject(function ($injector, $controller, uiCalendarConfig, _LocaisMock_, _AuthService_, _ReservasMock_, _ModalService_, _Reserva_, _TIPOS_RESERVA_) {

            $mdDialog = $injector.get('$mdDialog');
            $scope = self.$rootScope.$new();
            config = uiCalendarConfig;
            LocaisMock = _LocaisMock_;
            AuthService = _AuthService_;
            ReservasMock = _ReservasMock_;
            ModalService = _ModalService_;
            Reserva = _Reserva_;
            TIPOS_RESERVA = _TIPOS_RESERVA_;

            config.calendars = {
                calendario: {
                   fullCalendar: function () {
                       return {type: 'agendaDay'};
                   }
                }
            };

            dependenciasController = {
                $scope,
                local: LocaisMock.getLocal({_id: ID_LOCAL_TEST}),
                uiCalendarConfig: config,
                AuthService,
                ModalService,
                Reserva,
                TIPOS_RESERVA
            };

            createController = function () {
                self.$httpBackend.expectGET(`/api/locais/${ID_LOCAL_TEST}/reservas`).respond([ReservasMock.getReserva()]);
                const controller = $controller('AgendaController as agendaCtrl',dependenciasController);
                self.$httpBackend.flush();

                return controller;
            };
        }));

        describe('AgendaController visualizarReserva deve', () => {
            let controller;
            beforeEach(() => {
                controller = createController();
            });

            it('chamar modal de para visualização de reserva e atualizar as reservas no calendario', done => {
                ModalService.verReserva = sinon.stub().returns(self.$q.when());
                config.calendars.calendario.fullCalendar = sinon.stub();

                controller.visualizarReserva({}).should.be.fulfilled.then(() => {
                    sinon.assert.called(ModalService.verReserva);

                    sinon.assert.calledWith(config.calendars.calendario.fullCalendar, 'removeEvents');
                    sinon.assert.calledWith(config.calendars.calendario.fullCalendar, 'addEventSource', _.first(controller.reservasSource));
                }).should.notify(done);
                $scope.$digest();
            });
        });

        describe('AgendaController calendarioConfig deve', function () {
            let controller;
            beforeEach(() => {
                controller = createController();
            });

            it('ter propriedade calendario.ignoreTimezone como false', () => {
                expect(controller.calendarioConfig.calendario.ignoreTimezone).to.be.false;
            });

            it('ter propriedade calendario.timezone como "local"', () => {
                expect(controller.calendarioConfig.calendario.timezone).to.be.eql('local');
            });
        });

        describe('clickDia deve', function () {

            let controller;

            beforeEach(inject(function () {
                controller = createController();

                AuthService.userTemPermissao = sinon.stub().returns(true);
                $mdDialog.show = sinon.stub().returns(self.$q.when());
            }));

           it('Não permitir criação de reservas em horários passados', function () {
               var dataPassada = new Date();
               dataPassada.setFullYear(1980);
               dataPassada.setMonth(10);
               dataPassada.setDate(15);

               controller.clickDia(moment(dataPassada));
               sinon.assert.notCalled($mdDialog.show);
           });

            it('Permitir criação de reservas em horários futuros', function () {
                var dataFutura = new Date(Date.now());
                dataFutura.setMonth(dataFutura.getMonth() + 1);

                controller.clickDia(moment(dataFutura));
                sinon.assert.called($mdDialog.show);
            });

        });

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


<commit_before>(function () {

  /* Probably a better way to do this, but not that I could think of.
   * Chris Rhoden 2013 for PRX and Pop Up Archive.
   */

  var $realRootScope, actuallyIsLoading = 0, pretendLoading = 0, pageLoadings = 0;

  function loading (val) {
    if (val === true) {
      pretendLoading += 1;
    } else if (val === false) {
      pretendLoading -=1;
      if (pretendLoading < 0) pretendLoading = 0;
    } else {
      return (actuallyIsLoading || pretendLoading);
    }
  }

  function pageLoading (val) {
    if (val === true) {
      pageLoadings += 1;
    } else if (val === false) {
      pageLoadings -= 1;
      if (pageLoadings < 0) pageLoadings = 0;
    } else {
      return !!pageLoadings;
    }
  }

  angular.module('ngLoadingIndicators', [])
  .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
    function setIsLoading (data, headersGetter) {
      actuallyIsLoading += 1;
      return data;
    };
    $httpProvider.defaults.transformRequest.push(setIsLoading);
  }])
  .factory('myHttpInterceptor', ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
    if (typeof $rootScope.setIsLoading === 'undefined') {
      $realRootScope = $rootScope;
      $rootScope.loading = loading;
      $rootScope.pageLoading = pageLoading;
    }

    return function (promise) {
      return promise.then(function success(response) {
        actuallyIsLoading -= 1;
        if (actuallyIsLoading < 0) actuallyIsLoading = 0;
        return response;
      }, function error(response) {
        var errCode = response.status;
        // avoid recursion (error throwing error)
        // and only re-route if this was the main request (matches window.location) or a non-404.
        //console.log("error " + errCode + " for path " + $location.path() + " for response", response);
        if (response && response.config) {
          var main_req = '/api' + $location.path();
          if (!$location.search().was && (response.config.url == main_req || !errCode.match(/^(404|5)/) ) ) {
            //console.log("redirect error " + errCode + " for response path " + response.config.url);
            $rootScope.errorLocation = response.config.url;
            $rootScope.prevLocation = $location.absUrl();
            $location.path('/error/' + errCode).search({was:$rootScope.prevLocation})
          }
        };
        actuallyIsLoading -= 1;
        if (actuallyIsLoading < 0) actuallyIsLoading = 0;
        return $q.reject(response);
      });
    };
  }])
  .factory('loading', function() {
    function maskedLoading (val) {
      return loading(val);
    }

    maskedLoading.page = function (val) {
      return pageLoading(val);
    }

    return maskedLoading;
  });
}());

<commit_msg>clarify comments for #990<commit_after>(function () {

  /* Probably a better way to do this, but not that I could think of.
   * Chris Rhoden 2013 for PRX and Pop Up Archive.
   */

  var $realRootScope, actuallyIsLoading = 0, pretendLoading = 0, pageLoadings = 0;

  function loading (val) {
    if (val === true) {
      pretendLoading += 1;
    } else if (val === false) {
      pretendLoading -=1;
      if (pretendLoading < 0) pretendLoading = 0;
    } else {
      return (actuallyIsLoading || pretendLoading);
    }
  }

  function pageLoading (val) {
    if (val === true) {
      pageLoadings += 1;
    } else if (val === false) {
      pageLoadings -= 1;
      if (pageLoadings < 0) pageLoadings = 0;
    } else {
      return !!pageLoadings;
    }
  }

  angular.module('ngLoadingIndicators', [])
  .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
    function setIsLoading (data, headersGetter) {
      actuallyIsLoading += 1;
      return data;
    };
    $httpProvider.defaults.transformRequest.push(setIsLoading);
  }])
  .factory('myHttpInterceptor', ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
    if (typeof $rootScope.setIsLoading === 'undefined') {
      $realRootScope = $rootScope;
      $rootScope.loading = loading;
      $rootScope.pageLoading = pageLoading;
    }

    return function (promise) {
      return promise.then(function success(response) {
        actuallyIsLoading -= 1;
        if (actuallyIsLoading < 0) actuallyIsLoading = 0;
        return response;
      }, function error(response) {
        var errCode = response.status;
        // avoid recursion (error throwing error)
        // and only re-route if this was the main request (matches window.location) or 401, 403.
        // NOTE we silently skip 5xx and 404 responses because we do not want to alarm or mislead users
        // for ancillary objects that they are not requesting directly (as in search results, e.g.).
        //console.log("error " + errCode + " for path " + $location.path() + " for response", response);
        if (response && response.config) {
          var main_req = '/api' + $location.path();
          if (!$location.search().was && (response.config.url == main_req || !errCode.match(/^(404|5)/) ) ) {
            //console.log("redirect error " + errCode + " for response path " + response.config.url);
            $rootScope.errorLocation = response.config.url;
            $rootScope.prevLocation = $location.absUrl();
            $location.path('/error/' + errCode).search({was:$rootScope.prevLocation})
          }
        };
        actuallyIsLoading -= 1;
        if (actuallyIsLoading < 0) actuallyIsLoading = 0;
        return $q.reject(response);
      });
    };
  }])
  .factory('loading', function() {
    function maskedLoading (val) {
      return loading(val);
    }

    maskedLoading.page = function (val) {
      return pageLoading(val);
    }

    return maskedLoading;
  });
}());

<|endoftext|>


<commit_before>'use strict';

describe('main controller', function(){
  var $controller; // $controller ist der Angular-Service, der Controller erzeugt
  var scope; // Scope für zu instanziierenden Controller

  beforeEach(function() {
    module('lunchboxWebapp');
    inject(function(_$controller_) { $controller = _$controller_; });
    inject(function($rootScope) { scope = $rootScope.$new(); });
  });

  describe('instantiation', function() {
    beforeEach(function() {
      // main controller mit entsprechenden Parametern erzeugen
      $controller('MainCtrl', {
        $scope: scope,
        // _: {}, // TODO: Underscore als Util einbinden? ECMA6, RequireJS?
        LunchProviderStore: { query: function() {} }, // TODO: ngMock nutzen?!
        LunchOfferStore: { query: function() {} } // TODO: ngMock nutzen?!
      });
    });

    it('should default day to today', function() {
      var now = new Date();
      expect(scope.day).toBeDefined();
      expect(scope.day.getTime()).toBe(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
//      expect(angular.isArray(scope.awesomeThings)).toBeTruthy();
//      expect(scope.awesomeThings.length > 5).toBeTruthy();
    });

    it('should default location to Neubrandenburg', function() {
      expect(scope.location).toBe('Neubrandenburg');
    });

    it('should be loading data', function() {
      expect(scope.isLoading()).toBeTruthy();
      expect(scope.isLoadFinished()).toBeFalsy();
      expect(scope.isLoadFinishedWithNoVisibleOffers()).toBeFalsy();
      expect(scope.isLoadFailed()).toBeFalsy();
    });

    it('should default visibleOffers to {}', function() {
      expect(angular.equals(scope.visibleOffers, {})).toBeTruthy();
    });

  });
});
<commit_msg>WebApp: Unit-Tests verbessert<commit_after>'use strict';

describe('main controller', function(){
  var $controller; // $controller ist der Angular-Service, der Controller erzeugt
  var scope; // Scope für zu instanziierenden Controller

  beforeEach(function() {
    module('lunchboxWebapp');
    inject(function(_$controller_) { $controller = _$controller_; });
    inject(function($rootScope) { scope = $rootScope.$new(); });
  });

  describe('instantiation', function() {
    beforeEach(function() {
      // main controller mit entsprechenden Parametern erzeugen
      $controller('MainCtrl', {
        $scope: scope,
        // _: {}, // TODO: Underscore als Util einbinden? ECMA6, RequireJS?
        LunchProviderStore: { query: function() {} }, // TODO: ngMock nutzen?!
        LunchOfferStore: { query: function() {} } // TODO: ngMock nutzen?!
      });
    });

    it('should default day to today (in UTC)', function() {
      var now = new Date();
      expect(scope.day).toBeDefined();
      expect(scope.day.getTime()).toBe(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
//      expect(angular.isArray(scope.awesomeThings)).toBeTruthy();
//      expect(scope.awesomeThings.length > 5).toBeTruthy();
    });

    it('should default location to Neubrandenburg', function() {
      expect(scope.location).toBe('Neubrandenburg');
    });

    it('should be loading data', function() {
      expect(scope.isLoading()).toBeTruthy();
      expect(scope.isLoadFinished()).toBeFalsy();
      expect(scope.isLoadFinishedWithNoVisibleOffers()).toBeFalsy();
      expect(scope.isLoadFailed()).toBeFalsy();
    });

    it('should default visibleOffers to {}', function() {
      expect(angular.equals(scope.visibleOffers, {})).toBeTruthy();
      expect(scope.hasVisibleOffers()).toBeFalsy();
    });

  });
});
<|endoftext|>


<commit_before>/**
 * Jazzify adds helpers to vanilla JS and adds chaining functionality.
 *
 * @copyright Jakob Ploens 2016
 * @author    Jakob Ploens <jakob@2helden.com>
 * @version   1.3
 */

/**
 * -----------------------------------------------------------------------------
 * Object prototype functions
 * Use like object.addClass(), where object = document.querySelector('.elem')
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * addClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.addClass = function(className){
    if(this.classList){
        this.classList.add(className);
    } else {
        this.className += ' ' + className;
    }
};

/**
 * removeClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.removeClass = function(className){
    if (this.classList){
        this.classList.remove(className);
    } else {
        this.className = this.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
};

/**
 * hasClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.hasClass = function(className){
    if (this.classList){
        this.classList.contains(className);
    } else {
        new RegExp('(^| )' + className + '( |$)', 'gi').test(this.className);
    }
};

/**
 * toggleClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.toggleClass = function(className){
    if(this.classList){
        this.classList.toggle(className);

    } else {
        var classes = thus.className.split(' ');
        var existingIndex = classes.indexOf(className);

        if(existingIndex >= 0){
            classes.splice(existingIndex, 1);
        } else {
            classes.push(className);
        }
        this.className = classes.join(' ');
    }
};

/**
 * remove
 *
 * @return object
 * @since  1.1
 */
Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

/**
 * css
 *
 * @return object or css value
 * @since  1.1
 */
Object.prototype.css = function(name, value){
    if(value && value !== ""){
        this.style[name] = value;
    } else {
        return this.style[name];
    }
};

/**
 * data
 *
 * @return object or data value
 * @since  1.1
 */
Object.prototype.data = function(name, value){
    if(value && value !== ""){
        this.setAttribute('data-' + name) = value;
    } else {
        return this.getAttribute('data-' + name);
    }
};

/**
 * attr
 *
 * @return object or attr value
 * @since  1.2
 */
Object.prototype.attr = function(name, value){
    if(value && value !== ""){
        this.setAttribute(name) = value;
        return this;
    } else {
        return this.getAttribute(name);
    }
};

/**
 * each
 * Useable on NodeLists only
 *
 * @since  1.2
 */
Object.prototype.each = function(callback, scope){
    for(var i = 0; i < this.length; i++){
        callback.call(scope, i, this[i]);
    }
};

/**
 * on
 * Attaches event on object
 *
 * @since  1.3
 */
Object.prototype.on = function(e, callback, capture){
    if(this.addEventListener){
        this.addEventListener(e, callback, capture || false);
    } else if(this.attachEvent){
        this.attachEvent('on' + e, callback);
    }
};

/**
 * find
 * Returns nodelist or object
 *
 * @return object
 * @since  1.3
 */
Object.prototype.find = function(selector){
    var elements = this.querySelectorAll(selector);
    if(elements.length === 1) return elements[0];
    return elements;
};

/**
 * -----------------------------------------------------------------------------
 * Helper functions
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * Short function to merge two objects.
 *
 * @param  object (gets overwritten)
 * @param  object (overwrites)
 * @return object (merged)
 */
var merge = function(objectA, objectB){
    var result = {};
    for(var attr in objectA){
        result[attr] = objectA[attr];
    }
    for(var attr in objectB){
        result[attr] = objectB[attr];
    }
    return result;
};

/**
 * Shortcut for document.find()
 */
var $ = function(selector){
    return document.find(selector);
};<commit_msg>Added returns on every function for chaining<commit_after>/**
 * Jazzify adds helpers to vanilla JS and adds chaining functionality.
 *
 * @copyright Jakob Ploens 2016
 * @author    Jakob Ploens <jakob@2helden.com>
 * @version   1.3
 */

/**
 * -----------------------------------------------------------------------------
 * Object prototype functions
 * Use like object.addClass(), where object = document.querySelector('.elem')
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * addClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.addClass = function(className){
    if(this.classList){
        this.classList.add(className);
    } else {
        this.className += ' ' + className;
    }

    return this;
};

/**
 * removeClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.removeClass = function(className){
    if (this.classList){
        this.classList.remove(className);
    } else {
        this.className = this.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }

    return this;
};

/**
 * hasClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.hasClass = function(className){
    if (this.classList){
        return this.classList.contains(className);
    } else {
        return new RegExp('(^| )' + className + '( |$)', 'gi').test(this.className);
    }
};

/**
 * toggleClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.toggleClass = function(className){
    if(this.classList){
        this.classList.toggle(className);

    } else {
        var classes = thus.className.split(' ');
        var existingIndex = classes.indexOf(className);

        if(existingIndex >= 0){
            classes.splice(existingIndex, 1);
        } else {
            classes.push(className);
        }
        this.className = classes.join(' ');
    }

    return this;
};

/**
 * remove
 *
 * @return object
 * @since  1.1
 */
Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

/**
 * css
 *
 * @return object or css value
 * @since  1.1
 */
Object.prototype.css = function(name, value){
    if(value && value !== ""){
        this.style[name] = value;
        return this;
    } else {
        return this.style[name];
    }
};

/**
 * data
 *
 * @return object or data value
 * @since  1.1
 */
Object.prototype.data = function(name, value){
    if(value && value !== ""){
        this.setAttribute('data-' + name) = value;
        return this;
    } else {
        return this.getAttribute('data-' + name);
    }
};

/**
 * attr
 *
 * @return object or attr value
 * @since  1.2
 */
Object.prototype.attr = function(name, value){
    if(value && value !== ""){
        this.setAttribute(name) = value;
        return this;
    } else {
        return this.getAttribute(name);
    }
};

/**
 * each
 * Useable on NodeLists only
 *
 * @since  1.2
 */
Object.prototype.each = function(callback, scope){
    for(var i = 0; i < this.length; i++){
        callback.call(scope, i, this[i]);
    }
};

/**
 * on
 * Attaches event on object
 *
 * @since  1.3
 */
Object.prototype.on = function(e, callback, capture){
    if(this.addEventListener){
        this.addEventListener(e, callback, capture || false);
    } else if(this.attachEvent){
        this.attachEvent('on' + e, callback);
    }
    return this;
};

/**
 * find
 * Returns nodelist or object
 *
 * @return object
 * @since  1.3
 */
Object.prototype.find = function(selector){
    var elements = this.querySelectorAll(selector);
    if(elements.length === 1) return elements[0];
    return elements;
};

/**
 * -----------------------------------------------------------------------------
 * Helper functions
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * Short function to merge two objects.
 *
 * @param  object (gets overwritten)
 * @param  object (overwrites)
 * @return object (merged)
 */
var merge = function(objectA, objectB){
    var result = {};
    for(var attr in objectA){
        result[attr] = objectA[attr];
    }
    for(var attr in objectB){
        result[attr] = objectB[attr];
    }
    return result;
};

/**
 * Shortcut for document.find()
 */
var $ = function(selector){
    return document.find(selector);
};<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global jQuery */
(function ($) {
    "use strict";

    // Bootstrapper
    var InspectR = {
        // Static start function, called from main html/view to start all things up.
        start: function (config) {
            config = $.extend({}, InspectR.defaults, config);

            // main router, taking care of things
            var router = InspectR.Router = new Router(config),
                viewModel = InspectR.ViewModel = new InspectRViewModel(router, config);

            ko.applyBindings(viewModel, config.rootNode);

            // start the signalr connection
            // when the connection is successful, start the router
            $.connection.hub.logging = true;
            $.connection.hub.start({
                    waitForPageLoad: false,
                    transport: 'longPolling'
                }, function () {
                    router.trigger('connection:start');
                    Backbone.history.start({});
                });

            // TODO: this is a work-around for signalr erroring the longPolling connection when the user navigates away from the page.
            // abort the poll on page unload, so it doesn't error.
            window.onbeforeunload = function () {
                if ($.connection.hub.pollXhr) {
                    viewModel.ignoreConnectionErrors = true;
                }
            };
        },
        defaults: {
            // inspector: ''
            // rootNode:'#inspectr'
        }
    };

    // Backbone Router, takes care of history
    var Router = Backbone.Router.extend({
        routes: {
            "": "start",
            "*uniquekey": "loadInspector"
        }
    });

    // Main viewmodel
    var InspectRViewModel = function (router, options) {
        var self = this,
            hub = $.connection.inspectRHub,
            client = hub.client,
            server = hub.server;

        // mixin Events
        // _.extend(this, Backbone.Events);

        // public properties
        this.NewTitle = ko.observable();
        this.IsEditingTitle = ko.observable(false);
        this.UserProfile = ko.observable();
        this.Requests = ko.mapping.fromJS([]);
        this.Inspector = ko.observable();
        this.SupportedContentTypes = _.keys(CodeMirror.mimeModes).sort();
        this.Alerts = ko.observableArray([]);

        this.RequestList = ko.computed(function () {
            return self.Requests();
        });

        /** Routes */
        router.on('connection:start', function () { self.loadUserProfile(); });

        router.on('route:start', function () {
            self.loadInspector(options.inspector);
            // router.navigate(options.inspector, { trigger: true });
        });

        this.loadInspector = function (uniquekey) {
            // self.Inspector(null); // disable this to not flicker the screen
            self.Requests([]);
            if (self.Inspector()) {
                server.stopInspect(self.Inspector().Id());
            }
            server.startInspect(uniquekey)
                .done(function (result) {
                    if (result) {
                        self.Inspector(ko.mapping.fromJS(result));
                        self.loadRecentRequests();
                    }
                });
        };
        router.on('route:loadInspector', this.loadInspector);

        /** Methods */
        this.loadRecentRequests = function () {
            server.getRecentRequests(self.Inspector().UniqueKey())
                .done(function (result) {
                    if (result && result.length > 0) {
                        ko.mapping.fromJS(result, self.Requests);
                    }
                });
        };

        this.removeInspector = function (inspector) {
            if (self.Inspector().Id() == inspector.Id()) {
                throw "Cannot remove current inspector";
            }

            if (!confirm('Remove inspector: ' + inspector.UniqueKey())) {
                return;
            }

            server.removeInspectorFromUserProfile(inspector.Id())
                .done(function () {
                    self.UserProfile().Inspectors.remove(inspector);
                });
        };

        this.saveTitle = function () {
            server.setTitle(self.Inspector().Id(), self.NewTitle())
                .done(function () {
                    self.IsEditingTitle(false);
                    self.Inspector().Title(self.NewTitle());
                    self.loadUserProfile();
                });
        };

        this.loadUserProfile = function () {
            server.getUserProfile()
                .done(function (result) {
                    if (result) {
                        self.UserProfile(ko.mapping.fromJS(result));
                    }
                });
        };

        this.clearRecentRequests = function () {
            server.clearRecentRequests(self.Inspector().UniqueKey());
            self.Requests.removeAll();
        };

        /** Hub client functions */
        client.requestLogged = function (inspector, request) {
            if (inspector.Id != self.Inspector().Id()) {
                console.log('received request for non current inspector');
                return;
            }
            self.Requests.unshift(request);
        };

        /** Private functions */
        this.showAlert = function (title, content, type) {
            var alert = new Alert(title, content, type);
            alert.closed(function () {
                self.Alerts.remove(alert);
            });
            self.Alerts.push(alert);
            return alert;
        };

        this._connectionSlow = function () {
            self.showAlert('', 'The connection is having some issues. Try refreshing this page.', Alert.warning);
        };

        this._disconnected = function () {
            self.showAlert('', 'You are disconnected. Try refreshing this page.', Alert.error);
        };

        this._connectionError = function (data) {
            if (self.ignoreConnectionErrors) {
                return;
            }
            self.ignoreConnectionErrors = true;

            self.showAlert('', 'Errors occured in the connection. Try refreshing this page.', Alert.error)
                .closed(function () {
                    self.ignoreConnectionErrors = false;
                });
        };

        // Respond to connection errors
        $.connection.hub.connectionSlow(this._connectionSlow);
        $.connection.hub.disconnected(this._disconnected);
        $.connection.hub.error(this._connectionError);
    };

    // Alert model
    var Alert = function (title, content, type) {
        var self = this;
        this.Title = ko.observable(title || '');
        this.Content = ko.observable(content || '');
        this.Type = ko.observable(type ? type : '');

        this.close = function () {
            $(self).triggerHandler('close');
        };

        this.closed = function (callback) {
            $(self).bind('close', function (e) {
                callback.call(self);
            });
        };

        this.hideAfter = function (timeout) {
            setTimeout(this.close, timeout);
        };
    };
    Alert.warning = '';
    Alert.error = 'alert-error';
    Alert.success = 'alert-success';
    Alert.info = 'alert-info';

    $.inspectR = InspectR;
}(jQuery));
<commit_msg>don't show error notes on page unload<commit_after>/*jslint browser: true*/
/*global jQuery */
(function ($) {
    "use strict";

    // Bootstrapper
    var InspectR = {
        // Static start function, called from main html/view to start all things up.
        start: function (config) {
            config = $.extend({}, InspectR.defaults, config);

            // main router, taking care of things
            var router = InspectR.Router = new Router(config),
                viewModel = InspectR.ViewModel = new InspectRViewModel(router, config);

            ko.applyBindings(viewModel, config.rootNode);

            // start the signalr connection
            // when the connection is successful, start the router
            $.connection.hub.logging = true;
            $.connection.hub.start({
                    waitForPageLoad: false,
                    transport: 'longPolling'
                }, function () {
                    router.trigger('connection:start');
                    Backbone.history.start({});
                });

            // Don't show any errors because of page unload
            $(window).bind('beforeunload', function () {
                viewModel.ignoreConnectionErrors = true;
            });
        },
        defaults: {
            // inspector: ''
            // rootNode:'#inspectr'
        }
    };

    // Backbone Router, takes care of history
    var Router = Backbone.Router.extend({
        routes: {
            "": "start",
            "*uniquekey": "loadInspector"
        }
    });

    // Main viewmodel
    var InspectRViewModel = function (router, options) {
        var self = this,
            hub = $.connection.inspectRHub,
            client = hub.client,
            server = hub.server;

        // mixin Events
        // _.extend(this, Backbone.Events);

        // public properties
        this.NewTitle = ko.observable();
        this.IsEditingTitle = ko.observable(false);
        this.UserProfile = ko.observable();
        this.Requests = ko.mapping.fromJS([]);
        this.Inspector = ko.observable();
        this.SupportedContentTypes = _.keys(CodeMirror.mimeModes).sort();
        this.Alerts = ko.observableArray([]);

        this.RequestList = ko.computed(function () {
            return self.Requests();
        });

        /** Routes */
        router.on('connection:start', function () { self.loadUserProfile(); });

        router.on('route:start', function () {
            self.loadInspector(options.inspector);
            // router.navigate(options.inspector, { trigger: true });
        });

        this.loadInspector = function (uniquekey) {
            // self.Inspector(null); // disable this to not flicker the screen
            self.Requests([]);
            if (self.Inspector()) {
                server.stopInspect(self.Inspector().Id());
            }
            server.startInspect(uniquekey)
                .done(function (result) {
                    if (result) {
                        self.Inspector(ko.mapping.fromJS(result));
                        self.loadRecentRequests();
                    }
                });
        };
        router.on('route:loadInspector', this.loadInspector);

        /** Methods */
        this.loadRecentRequests = function () {
            server.getRecentRequests(self.Inspector().UniqueKey())
                .done(function (result) {
                    if (result && result.length > 0) {
                        ko.mapping.fromJS(result, self.Requests);
                    }
                });
        };

        this.removeInspector = function (inspector) {
            if (self.Inspector().Id() == inspector.Id()) {
                throw "Cannot remove current inspector";
            }

            if (!confirm('Remove inspector: ' + inspector.UniqueKey())) {
                return;
            }

            server.removeInspectorFromUserProfile(inspector.Id())
                .done(function () {
                    self.UserProfile().Inspectors.remove(inspector);
                });
        };

        this.saveTitle = function () {
            server.setTitle(self.Inspector().Id(), self.NewTitle())
                .done(function () {
                    self.IsEditingTitle(false);
                    self.Inspector().Title(self.NewTitle());
                    self.loadUserProfile();
                });
        };

        this.loadUserProfile = function () {
            server.getUserProfile()
                .done(function (result) {
                    if (result) {
                        self.UserProfile(ko.mapping.fromJS(result));
                    }
                });
        };

        this.clearRecentRequests = function () {
            server.clearRecentRequests(self.Inspector().UniqueKey());
            self.Requests.removeAll();
        };

        /** Hub client functions */
        client.requestLogged = function (inspector, request) {
            if (inspector.Id != self.Inspector().Id()) {
                console.log('received request for non current inspector');
                return;
            }
            self.Requests.unshift(request);
        };

        /** Private functions */
        this.showAlert = function (title, content, type) {
            var alert = new Alert(title, content, type);
            alert.closed(function () {
                self.Alerts.remove(alert);
            });
            self.Alerts.push(alert);
            return alert;
        };

        this._connectionSlow = function () {
            if (self.ignoreConnectionErrors) {
                return;
            }
            self.showAlert('', 'The connection is having some issues. Try refreshing this page.', Alert.warning);
        };

        this._disconnected = function () {
            if (self.ignoreConnectionErrors) {
                return;
            }
            self.showAlert('', 'You are disconnected. Try refreshing this page.', Alert.error);
        };

        this._connectionError = function (data) {
            if (self.ignoreConnectionErrors) {
                return;
            }
            self.ignoreConnectionErrors = true;

            self.showAlert('', 'Errors occured in the connection. Try refreshing this page.', Alert.error)
                .closed(function () {
                    self.ignoreConnectionErrors = false;
                });
        };

        // Respond to connection errors
        $.connection.hub.connectionSlow(this._connectionSlow);
        $.connection.hub.disconnected(this._disconnected);
        $.connection.hub.error(this._connectionError);
    };

    // Alert model
    var Alert = function (title, content, type) {
        var self = this;
        this.Title = ko.observable(title || '');
        this.Content = ko.observable(content || '');
        this.Type = ko.observable(type ? type : '');

        this.close = function () {
            $(self).triggerHandler('close');
        };

        this.closed = function (callback) {
            $(self).bind('close', function (e) {
                callback.call(self);
            });
        };

        this.hideAfter = function (timeout) {
            setTimeout(this.close, timeout);
        };
    };
    Alert.warning = '';
    Alert.error = 'alert-error';
    Alert.success = 'alert-success';
    Alert.info = 'alert-info';

    $.inspectR = InspectR;
}(jQuery));
<|endoftext|>


<commit_before>$(document).ready(function() {

  $('#upload_button').on('click', function(e) {
    form = $(this);
    $.ajax({
      url: form.attr('href'),
      method: "get",
      success: function(response) {
        $('#to_append_to').html(response);
      }
    })
  })

  $(document).on('submit', '#image-password-form', function(e) {
    form = $(this);
    $.ajax({
      url: form.attr('action'),
      method: form.attr('method'),
      data: form.serialize(),
      success: function(response) {
        $('#to_append_to').html(response);
      }
    })
  })

})<commit_msg>Can now show and hide upload form<commit_after>var showing = false

$(document).ready(function() {

  $('#upload_button').on('click', function(e) {
    form = $(this);
    if(showing) {
      $('#to_append_to').html('')
      showing = false
    } else {
      $.ajax({
        url: form.attr('href'),
        method: "get",
        success: function(response) {
          $('#to_append_to').html(response);
        }
      })
      showing = true
    }
  })

  $(document).on('submit', '#image-password-form', function(e) {
    form = $(this);
    if(showing) {
      $('#to_append_to').html('')
      showing = false
    } else {
      $.ajax({
        url: form.attr('action'),
        method: form.attr('method'),
        data: form.serialize(),
        success: function(response) {
          $('#to_append_to').html(response);
        }
      })
      showing = true
    }
  })

})<|endoftext|>


<commit_before>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var player = videojs('content_video');

var options = {
  id: 'content_video',
  //adTagUrl: 'https://googleads.g.doubleclick.net/pagead/ads?client=ca-video-pub-4631387039185633&slotname=5984306776&ad_type=standardvideo&description_url=http%3A%2F%2Fintoday.in&videoad_start_delay=0&type=all'
  adTagUrl: 'http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=xml_vmap1&unviewed_position_start=1&cust_params=sample_ar%3Dpremidpostpod%26deployment%3Dgmf-js&cmsid=496&vid=short_onecue&correlator='
};

player.ima(options);

// Remove controls from the player on iPad to stop native controls from stealing
// our click
var contentPlayer =  document.getElementById('content_video_html5_api');
if ((navigator.userAgent.match(/iPad/i) ||
      navigator.userAgent.match(/Android/i)) &&
    contentPlayer.hasAttribute('controls')) {
  contentPlayer.removeAttribute('controls');
}

// Initialize the ad container when the video player is clicked, but only the
// first time it's clicked.
var startEvent = 'click';
if (navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/Android/i)) {
  startEvent = 'tap';
}

player.one(startEvent, function() {
    player.ima.initializeAdDisplayContainer();
    player.ima.requestAds();
    player.play();
});
<commit_msg>sjhdjash<commit_after>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var player = videojs('content_video');

var options = {
  id: 'content_video',
  //IndiaToday>>>>
  //adTagUrl: 'https://googleads.g.doubleclick.net/pagead/ads?client=ca-video-pub-4631387039185633&slotname=5984306776&ad_type=standardvideo&description_url=http%3A%2F%2Fintoday.in&videoad_start_delay=0&type=all'
  //TestTag>>>>
  adTagUrl: 'http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=xml_vmap1&unviewed_position_start=1&cust_params=sample_ar%3Dpremidpostpod%26deployment%3Dgmf-js&cmsid=496&vid=short_onecue&correlator='
};

player.ima(options);

// Remove controls from the player on iPad to stop native controls from stealing
// our click
var contentPlayer =  document.getElementById('content_video_html5_api');
if ((navigator.userAgent.match(/iPad/i) ||
      navigator.userAgent.match(/Android/i)) &&
    contentPlayer.hasAttribute('controls')) {
  contentPlayer.removeAttribute('controls');
}

// Initialize the ad container when the video player is clicked, but only the
// first time it's clicked.
var startEvent = 'click';
if (navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/Android/i)) {
  startEvent = 'tap';
}

player.one(startEvent, function() {
    player.ima.initializeAdDisplayContainer();
    player.ima.requestAds();
    player.play();
});
<|endoftext|>


<commit_before>// jscs:disable
// jshint ignore: start

app.filter('readableTime', function() {
	return function(seconds) {
	  if(!seconds.isInteger()) { return 'TBD'; }
	  var day, format, hour, minute, month, week, year;
	  seconds = parseInt(seconds, 10);
	  minute = 60;
	  hour = minute * 60;
	  day = hour * 24;
	  week = day * 7;
	  year = day * 365;
	  month = year / 12;
	  format = function(number, string) {
	    string = number === 1 ? string : "" + string + "s";
	    return "" + number + " " + string;
	  };
	  switch (false) {
	    case !(seconds < minute):
	      return format(seconds, 'second');
	    case !(seconds < hour):
	      return format(Math.floor(seconds / minute), 'minute');
	    case !(seconds < day):
	      return format(Math.floor(seconds / hour), 'hour');
	    case !(seconds < week):
	      return format(Math.floor(seconds / day), 'day');
	    case !(seconds < month):
	      return format(Math.floor(seconds / week), 'week');
	    case !(seconds < year):
	      return format(Math.floor(seconds / month), 'month');
	    default:
	      return format(Math.floor(seconds / year), 'year');
	  }
	};
});

app.filter('readableTimeAbv', function() {
	return function(seconds) {
	  if(!seconds.isInteger()) { return 'TBD'; }
	  var day, format, hour, minute, month, week, year;
	  seconds = parseInt(seconds, 10);
	  minute = 60;
	  hour = minute * 60;
	  day = hour * 24;
	  week = day * 7;
	  year = day * 365;
	  month = year / 12;
	  format = function(number, string) {
	    string = number === 1 ? string : "" + string + "s";
	    return "" + number + " " + string;
	  };
	  switch (false) {
	    case !(seconds < minute):
	      return format(seconds, '');
	    case !(seconds < hour):
	      return format(Math.floor(seconds / minute), 'min');
	    case !(seconds < day):
	      return format(Math.floor(seconds / hour), 'hr');
	    case !(seconds < week):
	      return format(Math.floor(seconds / day), 'day');
	    case !(seconds < month):
	      return format(Math.floor(seconds / week), 'wk');
	    case !(seconds < year):
	      return format(Math.floor(seconds / month), 'mo');
	    default:
	      return format(Math.floor(seconds / year), 'yr');
	  }
	};
});<commit_msg>Tweak<commit_after>// jscs:disable
// jshint ignore: start

app.filter('readableTime', function() {
	return function(seconds) {
	  console.log(seconds);
	  if(seconds === null) { return 'TBD'; }
	  var day, format, hour, minute, month, week, year;
	  seconds = parseInt(seconds, 10);
	  minute = 60;
	  hour = minute * 60;
	  day = hour * 24;
	  week = day * 7;
	  year = day * 365;
	  month = year / 12;
	  format = function(number, string) {
	    string = number === 1 ? string : "" + string + "s";
	    return "" + number + " " + string;
	  };
	  switch (false) {
	    case !(seconds < minute):
	      return format(seconds, 'second');
	    case !(seconds < hour):
	      return format(Math.floor(seconds / minute), 'minute');
	    case !(seconds < day):
	      return format(Math.floor(seconds / hour), 'hour');
	    case !(seconds < week):
	      return format(Math.floor(seconds / day), 'day');
	    case !(seconds < month):
	      return format(Math.floor(seconds / week), 'week');
	    case !(seconds < year):
	      return format(Math.floor(seconds / month), 'month');
	    default:
	      return format(Math.floor(seconds / year), 'year');
	  }
	};
});

app.filter('readableTimeAbv', function() {
	return function(seconds) {
	  console.log(seconds);
	  if(seconds === null) { return 'TBD'; }
	  var day, format, hour, minute, month, week, year;
	  seconds = parseInt(seconds, 10);
	  minute = 60;
	  hour = minute * 60;
	  day = hour * 24;
	  week = day * 7;
	  year = day * 365;
	  month = year / 12;
	  format = function(number, string) {
	    string = number === 1 ? string : "" + string + "s";
	    return "" + number + " " + string;
	  };
	  switch (false) {
	    case !(seconds < minute):
	      return format(seconds, '');
	    case !(seconds < hour):
	      return format(Math.floor(seconds / minute), 'min');
	    case !(seconds < day):
	      return format(Math.floor(seconds / hour), 'hr');
	    case !(seconds < week):
	      return format(Math.floor(seconds / day), 'day');
	    case !(seconds < month):
	      return format(Math.floor(seconds / week), 'wk');
	    case !(seconds < year):
	      return format(Math.floor(seconds / month), 'mo');
	    default:
	      return format(Math.floor(seconds / year), 'yr');
	  }
	};
});<|endoftext|>


<commit_before>!function(e,t){"function"==typeof define&&define.amd?define(["efa"],t(e)):"object"==typeof exports?module.exports=t(require("efa")):e.eclipseFdnAdopters=t(e,e.efa)}(this,(function(e){"use strict";var t={},o=/<([^>]*?)>;(\s?[\w-]*?="(?:\\"|[^"])*";){0,}\s?rel="next"/,r={project_id:"",selector:".eclipsefdn-adopters",ul_classes:"",logo_white:!1,working_group:"",src_root:"https://api.eclipse.org/adopters",src_projects_prefix:"/projects"};function n(e){var t=JSON.parse(JSON.stringify(r));if(void 0!==e&&"object"==typeof e)for(var o in r)void 0===e[o]||"string"!=typeof e[o]&&"boolean"!=typeof e[o]||(t[o]=e[o]);return t}function i(e,t,r=[]){var n,s=new XMLHttpRequest;s.onreadystatechange=function(){if(4==this.readyState&&200==this.status){var n=JSON.parse(this.responseText);(Array.isArray(r)||r.length)&&(n=r.concat(n));var c=s.getResponseHeader("Link");if(null!==c){var a=c.match(o);null!==a?(e.next=a[1],i(e,t,n)):t(n)}else t(n)}else 4==this.readyState&&console.log("Error while retrieving adopters data, could not complete operation")},void 0!==e.next?n=e.next:(n=e.src_root+e.src_projects_prefix,void 0!==e.project_id&&""!==e.project_id.trim()&&(n+="/"+e.project_id),void 0!==e.working_group&&""!==e.working_group.trim()&&(n+="?working_group="+e.working_group)),s.open("GET",n,!0),s.send()}function s(e,t,o){const r=document.createElement("ul");if(void 0!==e)for(const o of e)if(t.project_id===o.project_id)for(const e of o.adopters){var n="";void 0!==e.homepage_url&&(n=e.homepage_url);var i="";void 0!==e.name&&(i=e.name);var s="";void 0!==e.logo&&(s=e.logo),!0===t.logo_white&&void 0!==e.logo_white&&(s=e.logo_white);let o=document.createElement("li"),c=document.createElement("a"),a=document.createElement("img");c.setAttribute("href",n),a.setAttribute("alt",i),a.setAttribute("src",t.src_root+"/assets/images/adopters/"+s),a.setAttribute("class","adopters-img"),c.appendChild(a),o.appendChild(c),r.appendChild(o)}for(var c=0;c<o.length;c++)""!==t.ul_classes&&r.setAttribute("class",t.ul_classes),o[c].append(r)}function c(){if(location.hash){var e=location.hash.replace("#","");document.getElementById(`${e}`).scrollIntoView()}}return t.getList=function(e){var t=n(e);i(t,(function(e){s(e,t,document.querySelectorAll(t.selector)),c()}))},t.getWGList=function(e){var t=n(e);i(t,(function(e){!function(e,t,o){for(const i of e){var r=JSON.parse(JSON.stringify(t));r.project_id=i.project_id;const c=document.createElement("h2");c.textContent=i.name,c.setAttribute("id",i.project_id);for(var n=0;n<o.length;n++)o[n].append(c);const a=document.createElement("a");a.setAttribute("class","btn btn-xs btn-secondary margin-left-10 uppercase"),a.setAttribute("href","https://projects.eclipse.org/projects/"+i.project_id),a.textContent=i.project_id,c.appendChild(a),s(e,r,o)}}(e,t,document.querySelectorAll(t.selector)),c()}))},t}));
<commit_msg>update adopters<commit_after>function _createForOfIteratorHelper(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var o=0,n=function(){};return{s:n,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,l=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return a=e.done,e},e:function(e){l=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(l)throw i}}}}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=new Array(t);r<t;r++)o[r]=e[r];return o}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var EclipseFdnAdopters=function(){function e(){_classCallCheck(this,e),_defineProperty(this,"precompiledRegex",/<([^>]*?)>;(\s?[\w-]*?="(?:\\"|[^"])*";){0,}\s?rel="next"/),_defineProperty(this,"default_options",{project_id:"",selector:".eclipsefdn-adopters",ul_classes:"",logo_white:!1,working_group:"",src_root:"https://api.eclipse.org/adopters",src_projects_prefix:"/projects"}),_defineProperty(this,"getList",(function(e){var t=this.getMergedOptions(e);this.fireCall(t,(function(e){this.createProjectList(e,t,document.querySelectorAll(t.selector)),this.scrollToAnchor()}))})),_defineProperty(this,"getWGList",(function(e){var t=this,r=this.getMergedOptions(e);this.fireCall(r,(function(e){t.createWGProjectsList(e,r,document.querySelectorAll(r.selector)),t.scrollToAnchor()}))}))}return _createClass(e,[{key:"getMergedOptions",value:function(e){var t=JSON.parse(JSON.stringify(this.default_options));if(void 0!==e&&"object"===_typeof(e))for(var r in this.default_options)void 0===e[r]||"string"!=typeof e[r]&&"boolean"!=typeof e[r]||(t[r]=e[r]);return t}},{key:"fireCall",value:function(e,t){var r,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=this,i=new XMLHttpRequest;i.onreadystatechange=function(){if(4==this.readyState&&200==this.status){var r=JSON.parse(this.responseText);(Array.isArray(o)||o.length)&&(r=o.concat(r));var a=i.getResponseHeader("Link");if(null!==a){var l=a.match(n.precompiledRegex);null!==l?(e.next=l[1],n.fireCall(e,t,r)):t(r)}else t(r)}else 4==this.readyState&&console.log("Error while retrieving adopters data, could not complete operation")},void 0!==e.next?r=e.next:(r=e.src_root+e.src_projects_prefix,void 0!==e.project_id&&""!==e.project_id.trim()&&(r+="/"+e.project_id),void 0!==e.working_group&&""!==e.working_group.trim()&&(r+="?working_group="+e.working_group)),i.open("GET",r,!0),i.send()}},{key:"createWGProjectsList",value:function(e,t,r){var o,n=_createForOfIteratorHelper(e);try{for(n.s();!(o=n.n()).done;){var i=o.value,a=JSON.parse(JSON.stringify(t));a.project_id=i.project_id;var l=document.createElement("h2");l.textContent=i.name,l.setAttribute("id",i.project_id);for(var s=0;s<r.length;s++)r[s].appendChild(l);var c=document.createElement("a");c.setAttribute("class","btn btn-xs btn-secondary margin-left-10 uppercase"),c.setAttribute("href","https://projects.eclipse.org/projects/"+i.project_id),c.textContent=i.project_id,l.appendChild(c),this.createProjectList(e,a,r)}}catch(e){n.e(e)}finally{n.f()}}},{key:"createProjectList",value:function(e,t,r){var o=document.createElement("ul");if(void 0!==e){var n,i=_createForOfIteratorHelper(e);try{for(i.s();!(n=i.n()).done;){var a=n.value;if(t.project_id===a.project_id){var l,s=_createForOfIteratorHelper(a.adopters);try{for(s.s();!(l=s.n()).done;){var c=l.value,p="";void 0!==c.homepage_url&&(p=c.homepage_url);var u="";void 0!==c.name&&(u=c.name);var f="";void 0!==c.logo&&(f=c.logo),!0===t.logo_white&&void 0!==c.logo_white&&(f=c.logo_white);var d=document.createElement("li"),y=document.createElement("a"),h=document.createElement("img");y.setAttribute("href",p),h.setAttribute("alt",u),h.setAttribute("src",t.src_root+"/assets/images/adopters/"+f),h.setAttribute("class","adopters-img"),y.appendChild(h),d.appendChild(y),o.appendChild(d)}}catch(e){s.e(e)}finally{s.f()}}}}catch(e){i.e(e)}finally{i.f()}}for(var _=0;_<r.length;_++)""!==t.ul_classes&&o.setAttribute("class",t.ul_classes),r[_].appendChild(o)}},{key:"scrollToAnchor",value:function(){if(location.hash){var e=location.hash.replace("#","");document.getElementById("".concat(e)).scrollIntoView()}}}]),e}(),eclipseFdnAdopters=new EclipseFdnAdopters;
<|endoftext|>


<commit_before>import moment from 'moment';
import React, { Component, PropTypes } from 'react';
import { Button } from 'react-bootstrap';
import { Link } from 'react-router';

import TimeRange from 'components/common/TimeRange';
import { getName } from 'utils/DataUtils';

class ReservationsTableRow extends Component {
  constructor(props) {
    super(props);
    this.handleDeleteClick = this.handleDeleteClick.bind(this);
    this.handleEditClick = this.handleEditClick.bind(this);
    this.renderButtons = this.renderButtons.bind(this);
  }

  handleDeleteClick() {
    const {
      openDeleteModal,
      reservation,
      selectReservationToDelete,
    } = this.props;

    selectReservationToDelete(reservation);
    openDeleteModal();
  }

  handleEditClick() {
    const {
      pushState,
      reservation,
      selectReservationToEdit,
    } = this.props;

    selectReservationToEdit(reservation);
    pushState(null, `/resources/${reservation.resource}/reservation`);
  }

  renderButtons() {
    if (moment() > moment(this.props.reservation.end)) {
      return null;
    }

    return (

        <Button
          bsSize="xsmall"
          bsStyle="primary"
          onClick={this.handleEditClick}
        >
          Muokkaa
        </Button>
        <Button
          bsSize="xsmall"
          bsStyle="danger"
          onClick={this.handleDeleteClick}
        >
          Poista
        </Button>

    );
  }

  render() {
    const {
      reservation,
      resource,
      unit,
    } = this.props;

    return (

          <Link to={`/resources/${resource.id}`}>
            {getName(resource)}
          </Link>

{getName(unit)}

          <Link
            to={`/resources/${resource.id}/reservation`}
            query={{ date: reservation.begin.split('T')[0] }}
          >
            <TimeRange
              begin={reservation.begin}
              end={reservation.end}
              lineBreaks
            />
        </Link>

          {this.renderButtons()}

    );
  }
}

ReservationsTableRow.propTypes = {
  openDeleteModal: PropTypes.func.isRequired,
  pushState: PropTypes.func.isRequired,
  reservation: PropTypes.object.isRequired,
  resource: PropTypes.object.isRequired,
  selectReservationToDelete: PropTypes.func.isRequired,
  selectReservationToEdit: PropTypes.func.isRequired,
  unit: PropTypes.object.isRequired,
};

export default ReservationsTableRow;
<commit_msg>Make my reservations edit links use correct date<commit_after>import moment from 'moment';
import React, { Component, PropTypes } from 'react';
import { Button } from 'react-bootstrap';
import { Link } from 'react-router';

import TimeRange from 'components/common/TimeRange';
import { getName } from 'utils/DataUtils';

class ReservationsTableRow extends Component {
  constructor(props) {
    super(props);
    this.handleDeleteClick = this.handleDeleteClick.bind(this);
    this.handleEditClick = this.handleEditClick.bind(this);
    this.renderButtons = this.renderButtons.bind(this);
  }

  handleDeleteClick() {
    const {
      openDeleteModal,
      reservation,
      selectReservationToDelete,
    } = this.props;

    selectReservationToDelete(reservation);
    openDeleteModal();
  }

  handleEditClick() {
    const {
      pushState,
      reservation,
      selectReservationToEdit,
    } = this.props;

    selectReservationToEdit(reservation);
    pushState(
      null,
      `/resources/${reservation.resource}/reservation`,
      { date: reservation.begin.split('T')[0] }
    );
  }

  renderButtons() {
    if (moment() > moment(this.props.reservation.end)) {
      return null;
    }

    return (

        <Button
          bsSize="xsmall"
          bsStyle="primary"
          onClick={this.handleEditClick}
        >
          Muokkaa
        </Button>
        <Button
          bsSize="xsmall"
          bsStyle="danger"
          onClick={this.handleDeleteClick}
        >
          Poista
        </Button>

    );
  }

  render() {
    const {
      reservation,
      resource,
      unit,
    } = this.props;

    return (

          <Link to={`/resources/${resource.id}`}>
            {getName(resource)}
          </Link>

{getName(unit)}

          <Link
            to={`/resources/${resource.id}/reservation`}
            query={{ date: reservation.begin.split('T')[0] }}
          >
            <TimeRange
              begin={reservation.begin}
              end={reservation.end}
              lineBreaks
            />
        </Link>

          {this.renderButtons()}

    );
  }
}

ReservationsTableRow.propTypes = {
  openDeleteModal: PropTypes.func.isRequired,
  pushState: PropTypes.func.isRequired,
  reservation: PropTypes.object.isRequired,
  resource: PropTypes.object.isRequired,
  selectReservationToDelete: PropTypes.func.isRequired,
  selectReservationToEdit: PropTypes.func.isRequired,
  unit: PropTypes.object.isRequired,
};

export default ReservationsTableRow;
<|endoftext|>


<commit_before>import escapeTextContentForBrowser from 'escape-html';
import emojify from '../../features/emoji/emoji';
import { unescapeHTML } from '../../utils/html';
import { expandSpoilers } from '../../initial_state';

const domParser = new DOMParser();

const makeEmojiMap = record => record.emojis.reduce((obj, emoji) => {
  obj[`:${emoji.shortcode}:`] = emoji;
  return obj;
}, {});

export function normalizeAccount(account) {
  account = { ...account };

  const emojiMap = makeEmojiMap(account);
  const displayName = account.display_name.trim().length === 0 ? account.username : account.display_name;

  account.display_name_html = emojify(escapeTextContentForBrowser(displayName), emojiMap);
  account.note_emojified = emojify(account.note, emojiMap);

  if (account.fields) {
    account.fields = account.fields.map(pair => ({
      ...pair,
      name_emojified: emojify(escapeTextContentForBrowser(pair.name)),
      value_emojified: emojify(pair.value, emojiMap),
      value_plain: unescapeHTML(pair.value),
    }));
  }

  if (account.moved) {
    account.moved = account.moved.id;
  }

  return account;
}

export function normalizeStatus(status, normalOldStatus) {
  const normalStatus   = { ...status };
  normalStatus.account = status.account.id;

  if (status.reblog && status.reblog.id) {
    normalStatus.reblog = status.reblog.id;
  }

  if (status.poll && status.poll.id) {
    normalStatus.poll = status.poll.id;
  }

  // Only calculate these values when status first encountered
  // Otherwise keep the ones already in the reducer
  if (normalOldStatus) {
    normalStatus.search_index = normalOldStatus.get('search_index');
    normalStatus.contentHtml = normalOldStatus.get('contentHtml');
    normalStatus.spoilerHtml = normalOldStatus.get('spoilerHtml');
    normalStatus.hidden = normalOldStatus.get('hidden');
  } else {
    const spoilerText   = normalStatus.spoiler_text || '';
    const searchContent = ([spoilerText, status.content].concat((status.poll && status.poll.options) ? status.poll.options.map(option => option.title) : [])).join('\n\n').replace(/<br\s*\/?>/g, '\n').replace(/<\/p><p>/g, '\n\n');
    const emojiMap      = makeEmojiMap(normalStatus);

    normalStatus.search_index = domParser.parseFromString(searchContent, 'text/html').documentElement.textContent;
    normalStatus.contentHtml  = emojify(normalStatus.content, emojiMap);
    normalStatus.spoilerHtml  = emojify(escapeTextContentForBrowser(spoilerText), emojiMap);
    normalStatus.hidden       = expandSpoilers ? false : spoilerText.length > 0 || normalStatus.sensitive;
  }

  return normalStatus;
}

export function normalizePoll(poll) {
  const normalPoll = { ...poll };

  const emojiMap = makeEmojiMap(normalPoll);

  normalPoll.options = poll.options.map(option => ({
    ...option,
    title_emojified: emojify(escapeTextContentForBrowser(option.title), emojiMap),
  }));

  return normalPoll;
}
<commit_msg>Display custom emoji in bio field names (#11350)<commit_after>import escapeTextContentForBrowser from 'escape-html';
import emojify from '../../features/emoji/emoji';
import { unescapeHTML } from '../../utils/html';
import { expandSpoilers } from '../../initial_state';

const domParser = new DOMParser();

const makeEmojiMap = record => record.emojis.reduce((obj, emoji) => {
  obj[`:${emoji.shortcode}:`] = emoji;
  return obj;
}, {});

export function normalizeAccount(account) {
  account = { ...account };

  const emojiMap = makeEmojiMap(account);
  const displayName = account.display_name.trim().length === 0 ? account.username : account.display_name;

  account.display_name_html = emojify(escapeTextContentForBrowser(displayName), emojiMap);
  account.note_emojified = emojify(account.note, emojiMap);

  if (account.fields) {
    account.fields = account.fields.map(pair => ({
      ...pair,
      name_emojified: emojify(escapeTextContentForBrowser(pair.name), emojiMap),
      value_emojified: emojify(pair.value, emojiMap),
      value_plain: unescapeHTML(pair.value),
    }));
  }

  if (account.moved) {
    account.moved = account.moved.id;
  }

  return account;
}

export function normalizeStatus(status, normalOldStatus) {
  const normalStatus   = { ...status };
  normalStatus.account = status.account.id;

  if (status.reblog && status.reblog.id) {
    normalStatus.reblog = status.reblog.id;
  }

  if (status.poll && status.poll.id) {
    normalStatus.poll = status.poll.id;
  }

  // Only calculate these values when status first encountered
  // Otherwise keep the ones already in the reducer
  if (normalOldStatus) {
    normalStatus.search_index = normalOldStatus.get('search_index');
    normalStatus.contentHtml = normalOldStatus.get('contentHtml');
    normalStatus.spoilerHtml = normalOldStatus.get('spoilerHtml');
    normalStatus.hidden = normalOldStatus.get('hidden');
  } else {
    const spoilerText   = normalStatus.spoiler_text || '';
    const searchContent = ([spoilerText, status.content].concat((status.poll && status.poll.options) ? status.poll.options.map(option => option.title) : [])).join('\n\n').replace(/<br\s*\/?>/g, '\n').replace(/<\/p><p>/g, '\n\n');
    const emojiMap      = makeEmojiMap(normalStatus);

    normalStatus.search_index = domParser.parseFromString(searchContent, 'text/html').documentElement.textContent;
    normalStatus.contentHtml  = emojify(normalStatus.content, emojiMap);
    normalStatus.spoilerHtml  = emojify(escapeTextContentForBrowser(spoilerText), emojiMap);
    normalStatus.hidden       = expandSpoilers ? false : spoilerText.length > 0 || normalStatus.sensitive;
  }

  return normalStatus;
}

export function normalizePoll(poll) {
  const normalPoll = { ...poll };

  const emojiMap = makeEmojiMap(normalPoll);

  normalPoll.options = poll.options.map(option => ({
    ...option,
    title_emojified: emojify(escapeTextContentForBrowser(option.title), emojiMap),
  }));

  return normalPoll;
}
<|endoftext|>


<commit_before>"use strict";

angular.module('arethusa.morph').directive('synchronizePostag', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var vars = scope.$eval(attrs.synchronizePostag);
      var form = scope[vars.form];
      var attr = scope[vars.attr];
      scope.$watch(vars.val, function(newVal, oldVal) {
        if (oldVal !== newVal) {
          scope.plugin.updatePostag(form, attr, newVal);
        }
      });
    }
  };
});
<commit_msg>Add comment to synchronizePostag<commit_after>"use strict";

// Don't like that this is practically the same as the fireEvent directive
// There has to be a better way.
angular.module('arethusa.morph').directive('synchronizePostag', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var vars = scope.$eval(attrs.synchronizePostag);
      var form = scope[vars.form];
      var attr = scope[vars.attr];
      scope.$watch(vars.val, function(newVal, oldVal) {
        if (oldVal !== newVal) {
          scope.plugin.updatePostag(form, attr, newVal);
        }
      });
    }
  };
});
<|endoftext|>


<commit_before>'use strict';

const config = require('./config');
const port = config.server.port;

module.exports = function (app) {

	app.listen(port, () => {
			console.log('Nitro listening on *:%s', port);
		})
		.on('error', (err) => {
			if (err.errno === 'EADDRINUSE') {
				console.error('Port *:%s already in use.', port);
			}
			else {
				console.error(err);
			}
			process.exit(1);
		});
};
<commit_msg>#84 add environment info to server start<commit_after>'use strict';

const config = require('./config');
const port = config.server.port;
const mode = config.server.production ? 'production': 'development';

module.exports = function (app) {

	app.listen(port, () => {
			console.log('Nitro listening on *:%s in %s mode', port, mode);
		})
		.on('error', (err) => {
			if (err.errno === 'EADDRINUSE') {
				console.error('Port *:%s already in use.', port);
			}
			else {
				console.error(err);
			}
			process.exit(1);
		});
};
<|endoftext|>


<commit_before>/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = [];

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        Kwf.callOnContentReady(document.body, { newRender: true });
    });
}

Kwf.callOnContentReady = function(el, options) {
    if (!options) options = {};
    if (Ext.Element && el instanceof Ext.Element) el = el.dom;
    if (jQuery && el instanceof jQuery) el = el.get();

    Kwf._readyHandlers.sort(function(a, b) {
        return (a.options.priority || 0) - (b.options.priority || 0);
    });
    for (var i = 0; i < Kwf._readyHandlers.length; i++) {
        var hndl = Kwf._readyHandlers[i];
        if (hndl.selector == null) {
            hndl.fn.call(hndl.scope || window, (el || document.body), options);
        } else {
            if (hndl.type == 'jquery') { // OnElementReady jQuery
                Kwf._callOnJElementReady(hndl, el);

            } else if (hndl.type == 'ext') { // OnElementReady ExtJS
                Kwf._callOnElementReady(hndl, el);
            }
        }
    }
};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function
 * @param scope for callback
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, scope, options) {
    Kwf._readyHandlers.push({
        selector: null,
        fn: fn,
        scope: scope,
        options: options || {}
    });
};
<commit_msg>add docs<commit_after>/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = [];

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        Kwf.callOnContentReady(document.body, { newRender: true });
    });
}

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(el, options) {
    if (!options) options = {};
    if (Ext.Element && el instanceof Ext.Element) el = el.dom;
    if (jQuery && el instanceof jQuery) el = el.get();

    Kwf._readyHandlers.sort(function(a, b) {
        return (a.options.priority || 0) - (b.options.priority || 0);
    });
    for (var i = 0; i < Kwf._readyHandlers.length; i++) {
        var hndl = Kwf._readyHandlers[i];
        if (hndl.selector == null) {
            hndl.fn.call(hndl.scope || window, (el || document.body), options);
        } else {
            if (hndl.type == 'jquery') { // OnElementReady jQuery
                Kwf._callOnJElementReady(hndl, el);

            } else if (hndl.type == 'ext') { // OnElementReady ExtJS
                Kwf._callOnElementReady(hndl, el);
            }
        }
    }
};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param scope for callback
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, scope, options) {
    Kwf._readyHandlers.push({
        selector: null,
        fn: fn,
        scope: scope,
        options: options || {}
    });
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        JR's Utils
// @namespace   http://openuserjs.org/users/zarjay/scripts
// @author      zarjay
// @version     1.4.0
// @description Library of functions runnable in the browser console.
// @match       http://*/*
// @match       https://*/*
// @license     MIT License; https://github.com/zarjay/userscripts/blob/master/LICENSE
// @updateURL   https://openuserjs.org/meta/zarjay/JRs_Utils.meta.js
// ==/UserScript==

const exec = fn => {
    const script = document.createElement('script');
    script.textContent = `(${fn})()`;
    document.head.appendChild(script);
};

const main = () => {
    // add CSS to the page
    function css(content) {
        const element = document.createElement('style');
        element.textContent = content;
        document.head.appendChild(element);
    }

    // copy JavaScript to the clipboard
    function copyJS(js) {
        copy(stringifyJS(js));
    }

    // copy JSON to the clipboard
    function copyJSON(js) {
        copy(stringifyJSON(js));
    }

    // make the page editable or non-editable
    function edit(canEdit = true) {
        document.designMode = canEdit ? 'on' : 'off';
    }

    // count occurrences of each value
    function frequency(...values) {
        return values.reduce((obj, val) => Object.assign(obj, { [val]: (obj[val] || 0) + 1 }), {});
    }

    // add HTML to the page
    function html(content, position = 'beforeend') {
        document.body.insertAdjacentHTML(position, content);
    }

    // include JS/CSS from URL or CDN
    function include(asset, type) {
        if (!asset.includes('/')) return includeFromCDN(asset);
        return includeFromURL(asset, type);
    }

    // include JS/CSS file from CDN
    function includeFromCDN(library) {
        return fetch(`https://api.cdnjs.com/libraries?search=${library}`)
            .then(response => response.json())
            .then(json => json.results[0].latest)
            .then(includeFromURL)
            .catch(error => console.error(`Couldn't load ${library}`, error))
    }

    // include JS/CSS file from URL
    function includeFromURL(url, type = url.split('.').pop().toLowerCase()) {
        return new Promise((resolve, reject) => {
            let element;

            if (type === 'css') {
                element = document.createElement('link');
                element.rel = 'stylesheet';
                element.href = url;
            } else if (type === 'js') {
                element = document.createElement('script');
                element.src = url;
                element.async = false;
            } else {
                throw new Error(`Failed to include ${url} due to unknown file type.`);
            }

            element.onload = resolve;
            element.onerror = reject;
            document.head.appendChild(element);
        }).then(() => console.log('Loaded', url));
    }

    // block bubble events with a capture event
    function intercept(target = document.documentElement, events) {
        events = events || [
            'contextmenu',
            'copy',
            'keydown',
            'keypress',
            'keyup',
            'mousedown',
            'mouseup',
            'selectstart'
        ];
        const stopEvents = event => event.stopPropagation();
        query(target).forEach(element =>
            events.forEach(event => element.addEventListener(event, stopEvents, true)));
    }

    // add JS to the page
    function js(content, isImmediate = false) {
        const script = document.createElement('script');
        script.textContent = isImmediate ? `(${content})()` : content;
        document.head.appendChild(script);
    }

    // calculate the mean
    function mean(...values) {
        return sum(...values) / values.length;
    }

    // calculate the median
    function median(...values) {
        values.sort((a, b) => a - b);
        const low = (values.length - 1) >> 1;
        const high = values.length >> 1;
        return (values[low] + values[high]) / 2;
    }

    // calculate the mode
    function mode(...values) {
        const counted = frequency(...values);
        const keys = unique(...values);
        const vals = keys.map(x => counted[x]);
        if (vals.every(x => x < 2)) return [];
        const max = Math.max(...vals);
        return keys.reduce((array, key) => counted[key] === max ? [...array, key] : array, []);
    }

    // pause audio/video (pause everything by default)
    function pause(target = 'audio, video') {
        const elements = query(target);
        elements.forEach(element => typeof element.pause === 'function' ? element.pause() : null);
    }

    // play audio/video (plays first found by default)
    function play(target = 'audio, video') {
        const element = query(target)[0];
        if (element && typeof element.play === 'function') element.play();
    }

    // kinda like jQuery's $()
    function query(target) {
        if (typeof target === 'string') return [...document.querySelectorAll(target)];
        if (target instanceof Node) return [target];
        return Array.from(target); // hopefully a NodeList, HTMLCollection, or Array
    }

    // format JS into a string
    function stringifyJS(js) {
        if (typeof js === 'function') {
            return js.toString();
        } else if (typeof js === 'object') {
            return stringifyJSON(js).replace(/"(\w+)":/g, '$1:').replace(/"/g, '\'');
        } else {
            return js;
        }
    }

    // format JSON into a string
    function stringifyJSON(js) {
        return JSON.stringify(js, null, '\t');
    }

    // calculate the sum
    function sum(...values) {
        return values.reduce((a, b) => a + b);
    }

    // filter out duplicate values
    function unique(...values){
        return values.filter((x, i) => values.indexOf(x) === i)
    }

    const jr = {
        css,
        copyJS,
        copyJSON,
        edit,
        frequency,
        html,
        include,
        intercept,
        js,
        mean,
        median,
        mode,
        pause,
        play,
        query,
        sum,
        unique
    };

    if (window.jr) {
        console.warn('Userscript: jr variable is taken.');
    } else {
        window.jr = jr;
        console.log('Userscript: jr is loaded.');
    }
};

exec(main);
<commit_msg>Update indentation<commit_after>// ==UserScript==
// @name        JR's Utils
// @namespace   http://openuserjs.org/users/zarjay/scripts
// @author      zarjay
// @version     1.4.0
// @description Library of functions runnable in the browser console.
// @match       http://*/*
// @match       https://*/*
// @license     MIT License; https://github.com/zarjay/userscripts/blob/master/LICENSE
// @updateURL   https://openuserjs.org/meta/zarjay/JRs_Utils.meta.js
// ==/UserScript==

const exec = fn => {
	const script = document.createElement('script');
	script.textContent = `(${fn})()`;
	document.head.appendChild(script);
};

const main = () => {
	// add CSS to the page
	function css(content) {
		const element = document.createElement('style');
		element.textContent = content;
		document.head.appendChild(element);
	}

	// copy JavaScript to the clipboard
	function copyJS(js) {
		copy(stringifyJS(js));
	}

	// copy JSON to the clipboard
	function copyJSON(js) {
		copy(stringifyJSON(js));
	}

	// make the page editable or non-editable
	function edit(canEdit = true) {
		document.designMode = canEdit ? 'on' : 'off';
	}

	// count occurrences of each value
	function frequency(...values) {
		return values.reduce((obj, val) => Object.assign(obj, { [val]: (obj[val] || 0) + 1 }), {});
	}

	// add HTML to the page
	function html(content, position = 'beforeend') {
		document.body.insertAdjacentHTML(position, content);
	}

	// include JS/CSS from URL or CDN
	function include(asset, type) {
		if (!asset.includes('/')) return includeFromCDN(asset);
		return includeFromURL(asset, type);
	}

	// include JS/CSS file from CDN
	function includeFromCDN(library) {
		return fetch(`https://api.cdnjs.com/libraries?search=${library}`)
			.then(response => response.json())
			.then(json => json.results[0].latest)
			.then(includeFromURL)
			.catch(error => console.error(`Couldn't load ${library}`, error))
	}

	// include JS/CSS file from URL
	function includeFromURL(url, type = url.split('.').pop().toLowerCase()) {
		return new Promise((resolve, reject) => {
			let element;

			if (type === 'css') {
				element = document.createElement('link');
				element.rel = 'stylesheet';
				element.href = url;
			} else if (type === 'js') {
				element = document.createElement('script');
				element.src = url;
				element.async = false;
			} else {
				throw new Error(`Failed to include ${url} due to unknown file type.`);
			}

			element.onload = resolve;
			element.onerror = reject;
			document.head.appendChild(element);
		}).then(() => console.log('Loaded', url));
	}

	// block bubble events with a capture event
	function intercept(target = document.documentElement, events) {
		events = events || [
				'contextmenu',
				'copy',
				'keydown',
				'keypress',
				'keyup',
				'mousedown',
				'mouseup',
				'selectstart'
			];
		const stopEvents = event => event.stopPropagation();
		query(target).forEach(element =>
			events.forEach(event => element.addEventListener(event, stopEvents, true)));
	}

	// add JS to the page
	function js(content, isImmediate = false) {
		const script = document.createElement('script');
		script.textContent = isImmediate ? `(${content})()` : content;
		document.head.appendChild(script);
	}

	// calculate the mean
	function mean(...values) {
		return sum(...values) / values.length;
	}

	// calculate the median
	function median(...values) {
		values.sort((a, b) => a - b);
		const low = (values.length - 1) >> 1;
		const high = values.length >> 1;
		return (values[low] + values[high]) / 2;
	}

	// calculate the mode
	function mode(...values) {
		const counted = frequency(...values);
		const keys = unique(...values);
		const vals = keys.map(x => counted[x]);
		if (vals.every(x => x < 2)) return [];
		const max = Math.max(...vals);
		return keys.reduce((array, key) => counted[key] === max ? [...array, key] : array, []);
	}

	// pause audio/video (pause everything by default)
	function pause(target = 'audio, video') {
		const elements = query(target);
		elements.forEach(element => typeof element.pause === 'function' ? element.pause() : null);
	}

	// play audio/video (plays first found by default)
	function play(target = 'audio, video') {
		const element = query(target)[0];
		if (element && typeof element.play === 'function') element.play();
	}

	// kinda like jQuery's $()
	function query(target) {
		if (typeof target === 'string') return [...document.querySelectorAll(target)];
		if (target instanceof Node) return [target];
		return Array.from(target); // hopefully a NodeList, HTMLCollection, or Array
	}

	// format JS into a string
	function stringifyJS(js) {
		if (typeof js === 'function') {
			return js.toString();
		} else if (typeof js === 'object') {
			return stringifyJSON(js).replace(/"(\w+)":/g, '$1:').replace(/"/g, '\'');
		} else {
			return js;
		}
	}

	// format JSON into a string
	function stringifyJSON(js) {
		return JSON.stringify(js, null, '\t');
	}

	// calculate the sum
	function sum(...values) {
		return values.reduce((a, b) => a + b);
	}

	// filter out duplicate values
	function unique(...values) {
		return values.filter((x, i) => values.indexOf(x) === i)
	}

	const jr = {
		css,
		copyJS,
		copyJSON,
		edit,
		frequency,
		html,
		include,
		intercept,
		js,
		mean,
		median,
		mode,
		pause,
		play,
		query,
		sum,
		unique
	};

	if (window.jr) {
		console.warn('Userscript: jr variable is taken.');
	} else {
		window.jr = jr;
		console.log('Userscript: jr is loaded.');
	}
};

exec(main);
<|endoftext|>


<commit_before>
var PolicyBarChartView = BaseChartView.extend({
  initialize : function() {
    this.initialize_defaults();
  },

  render : function() {
    this.clear_container();

    InitializePolicyBar(this.model.get("container"),
      this.result_serie1(),
      this.result_serie2(),
      this.ticks(),
      this.model.series.length,
      this.parsed_unit(),
      this.axis_scale(),
      this.model.colors(),
      this.model.labels());
  },

  result_serie1 : function() {
    return _.flatten(this.model.value_pairs());
  },

  result_serie2 : function() {
    return _.map(this.result_serie1(), function(r) {
      return 100 - r;
    });
  },

  ticks : function() {
    var ticks = [];
    this.model.series.each(function(serie) {
      // RD: when updating jqplot to version 720+ the ticks should not be in an array!
      ticks.push([ serie.result()[0][0] ]);
      ticks.push([ serie.result()[1][0] ]);
    });
    return ticks;
  }
});<commit_msg>updated policy bar to new jqplot version<commit_after>
var PolicyBarChartView = BaseChartView.extend({
  initialize : function() {
    this.initialize_defaults();
  },

  render : function() {
    this.clear_container();

    InitializePolicyBar(this.model.get("container"),
      this.result_serie1(),
      this.result_serie2(),
      this.ticks(),
      this.model.series.length,
      this.parsed_unit(),
      this.axis_scale(),
      this.model.colors(),
      this.model.labels());
  },

  result_serie1 : function() {
    return _.flatten(this.model.value_pairs());
  },

  result_serie2 : function() {
    return _.map(this.result_serie1(), function(r) {
      return 100 - r;
    });
  },

  ticks : function() {
    var ticks = [];
    this.model.series.each(function(serie) {
      ticks.push(serie.result()[0][0]);
      ticks.push(serie.result()[1][0]);
    });
    return ticks;
  }
});<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'backbone',
    'collections',
    'text!templates/sport-list.html'
], function ($, _, Backbone, Collections, sportListTemplate) {
    /*var SportItemView = Backbone.View.extend({
        render: function() {
            var data = this.model.toJSON()
            this.$el.html('
'+data.name+'	'+''+data.description+'
')
        }
    }) */
    var SportListView = Backbone.View.extend({
        el: $('#sport-list'),
        initialize: function() {
            this.collection = new Collections.Sports()
            this.collection.on('change', this.render, this);
        },

        render: function() {
            var data = {
                sports: this.collection.toJSON(),
                _: _
            };
            console.log(data.sports)
            var compiledTemplate = _.template(sportListTemplate)( data );
            this.$el.html(compiledTemplate);
        }
    })
    return SportListView;
});
<commit_msg>cleanup<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'collections',
    'text!templates/sport-list.html'
], function ($, _, Backbone, Collections, sportListTemplate) {
    /*var SportItemView = Backbone.View.extend({
        render: function() {
            var data = this.model.toJSON()
            this.$el.html('
'+data.name+'	'+''+data.description+'
')
        }
    }) */
    var SportListView = Backbone.View.extend({
        el: $('#sport-list'),
        initialize: function() {
            this.collection = new Collections.Sports()
            this.collection.on('change', this.render, this);
        },

        render: function() {
            var data = {
                sports: this.collection.toJSON(),
                _: _
            };
            var compiledTemplate = _.template(sportListTemplate)( data );
            this.$el.html(compiledTemplate);
        }
    })
    return SportListView;
});
<|endoftext|>