<commit_before>/*jslint nomen: true*/
/*global require, module, __dirname, process, console*/
(function () {
    'use strict';

    /**
     * Module dependencies.
     */
    var fs = require('fs'),
        http = require('http'),
        https = require('https'),
        express = require('express'),
        morgan = require('morgan'),
        bodyParser = require('body-parser'),
        session = require('express-session'),
        compress = require('compression'),
        methodOverride = require('method-override'),
        cookieParser = require('cookie-parser'),
        helmet = require('helmet'),
        passport = require('passport'),
        mongoStore = require('connect-mongo')({
            session: session
        }),
        flash = require('connect-flash'),
        config = require('./config'),
        consolidate = require('consolidate'),
        path = require('path');

    module.exports = function (db) {
        // Initialize express app
        var app = express();
        // Globbing model files
        config.getGlobbedFiles('./app/models/**/*.js').forEach(function (modelPath) {
            require(path.resolve(modelPath));
        });

        // Setting application local variables
        app.locals.title = config.app.title;
        app.locals.description = config.app.description;
        app.locals.keywords = config.app.keywords;
        app.locals.facebookAppId = config.facebook.clientID;
        app.locals.jsFiles = config.getJavaScriptAssets();
        app.locals.cssFiles = config.getCSSAssets();
        app.locals.messageChannelName = config.getMessageChannelName();
        app.locals.appVersion = config.getAppVersion();

        // Passing the request url to environment locals
        app.use(function (req, res, next) {
            res.locals.url = req.protocol + '://' + req.headers.host + req.url;
            next();
        });

        // Should be placed before express.static
        app.use(compress({
            filter: function (req, res) {
                return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
            },
            level: 9
        }));

        // Showing stack errors
        app.set('showStackError', true);

        // Set swig as the template engine
        app.engine('server.view.html', consolidate[config.templateEngine]);

        // Set views path and view engine
        app.set('view engine', 'server.view.html');
        app.set('views', './app/views');

        // Environment dependent middleware
        if (process.env.NODE_ENV === 'development') {
            // Enable logger (morgan)
            app.use(morgan('dev'));

            // Disable views cache
            app.set('view cache', false);
        } else if (process.env.NODE_ENV === 'production') {
            app.locals.cache = 'memory';
        }

        app.use(bodyParser({limit: '50mb'}));
        // Request body parsing middleware should be above methodOverride
        app.use(bodyParser.urlencoded({
            extended: true
        }));
        app.use(bodyParser.json());
        app.use(methodOverride());

        // CookieParser should be above session
        app.use(cookieParser());

        // Express MongoDB session storage
        app.use(session({
            saveUninitialized: true,
            resave: true,
            secret: config.sessionSecret,
            store: new mongoStore({
                db: db.connection.db,
                collection: config.sessionCollection
            })
        }));

        // use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        // connect flash for flash messages
        app.use(flash());

        // Use helmet to secure Express headers
        app.use(helmet.xframe());
        app.use(helmet.xssFilter());
        app.use(helmet.nosniff());
        app.use(helmet.ienoopen());
        app.disable('x-powered-by');

        // Setting the app router and static folder
        app.use(express.static(path.resolve('./public')));
        app.use(express.static(path.resolve('./config/shared')));

        // Globbing routing files
        config.getGlobbedFiles('./app/routes/**/*.js').forEach(function (routePath) {
            require(path.resolve(routePath))(app);
        });

        // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
        app.use(function (err, req, res, next) {
            // If the error object doesn't exists
            if (!err) {
                return next();
            }

            // Log it
            console.error(err.stack);

            // Error page
            res.status(500).render('500', {
                error: err.stack
            });
        });

        // Assume 404 since no middleware responded
        app.use(function (req, res) {
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not Found'
            });
        });

        if (process.env.NODE_ENV === 'secure') {
            // Log SSL usage
            console.log('Securely using https protocol');

            // Load SSL key and certificate
            var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'),
                certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'),
                httpsServer = https.createServer({
                    key: privateKey,
                    cert: certificate
                }, app);

            // Return HTTPS server instance
            return httpsServer;
        }

        var messageHandler = require('../app/services/messaging/messageHandler');
        messageHandler.init();
        // Return Express server instance
        return app;
    };
}());
<commit_msg>moved the static publisher middleware before session creation in order to increase the priority<commit_after>/*jslint nomen: true*/
/*global require, module, __dirname, process, console*/
(function () {
    'use strict';

    /**
     * Module dependencies.
     */
    var fs = require('fs'),
        http = require('http'),
        https = require('https'),
        express = require('express'),
        morgan = require('morgan'),
        bodyParser = require('body-parser'),
        session = require('express-session'),
        compress = require('compression'),
        methodOverride = require('method-override'),
        cookieParser = require('cookie-parser'),
        helmet = require('helmet'),
        passport = require('passport'),
        mongoStore = require('connect-mongo')({
            session: session
        }),
        flash = require('connect-flash'),
        config = require('./config'),
        consolidate = require('consolidate'),
        path = require('path');

    module.exports = function (db) {
        // Initialize express app
        var app = express();
        // Globbing model files
        config.getGlobbedFiles('./app/models/**/*.js').forEach(function (modelPath) {
            require(path.resolve(modelPath));
        });

        // Setting application local variables
        app.locals.title = config.app.title;
        app.locals.description = config.app.description;
        app.locals.keywords = config.app.keywords;
        app.locals.facebookAppId = config.facebook.clientID;
        app.locals.jsFiles = config.getJavaScriptAssets();
        app.locals.cssFiles = config.getCSSAssets();
        app.locals.messageChannelName = config.getMessageChannelName();
        app.locals.appVersion = config.getAppVersion();

        // Passing the request url to environment locals
        app.use(function (req, res, next) {
            res.locals.url = req.protocol + '://' + req.headers.host + req.url;
            next();
        });

        // Should be placed before express.static
        app.use(compress({
            filter: function (req, res) {
                return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
            },
            level: 9
        }));

        // Showing stack errors
        app.set('showStackError', true);

        // Set swig as the template engine
        app.engine('server.view.html', consolidate[config.templateEngine]);

        // Set views path and view engine
        app.set('view engine', 'server.view.html');
        app.set('views', './app/views');

        // Environment dependent middleware
        if (process.env.NODE_ENV === 'development') {
            // Enable logger (morgan)
            app.use(morgan('dev'));

            // Disable views cache
            app.set('view cache', false);
        } else if (process.env.NODE_ENV === 'production') {
            app.locals.cache = 'memory';
        }

        app.use(bodyParser({limit: '50mb'}));
        // Request body parsing middleware should be above methodOverride
        app.use(bodyParser.urlencoded({
            extended: true
        }));
        app.use(bodyParser.json());
        app.use(methodOverride());

        // CookieParser should be above session
        app.use(cookieParser());

        // Setting the app router and static folder
        app.use(express.static(path.resolve('./public')));
        app.use(express.static(path.resolve('./config/shared')));

        // Express MongoDB session storage
        app.use(session({
            saveUninitialized: true,
            resave: true,
            secret: config.sessionSecret,
            store: new mongoStore({
                db: db.connection.db,
                collection: config.sessionCollection
            })
        }));

        // use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        // connect flash for flash messages
        app.use(flash());

        // Use helmet to secure Express headers
        app.use(helmet.xframe());
        app.use(helmet.xssFilter());
        app.use(helmet.nosniff());
        app.use(helmet.ienoopen());
        app.disable('x-powered-by');

        // Globbing routing files
        config.getGlobbedFiles('./app/routes/**/*.js').forEach(function (routePath) {
            require(path.resolve(routePath))(app);
        });

        // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
        app.use(function (err, req, res, next) {
            // If the error object doesn't exists
            if (!err) {
                return next();
            }

            // Log it
            console.error(err.stack);

            // Error page
            res.status(500).render('500', {
                error: err.stack
            });
        });

        // Assume 404 since no middleware responded
        app.use(function (req, res) {
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not Found'
            });
        });

        if (process.env.NODE_ENV === 'secure') {
            // Log SSL usage
            console.log('Securely using https protocol');

            // Load SSL key and certificate
            var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'),
                certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'),
                httpsServer = https.createServer({
                    key: privateKey,
                    cert: certificate
                }, app);

            // Return HTTPS server instance
            return httpsServer;
        }

        var messageHandler = require('../app/services/messaging/messageHandler');
        messageHandler.init();
        // Return Express server instance
        return app;
    };
}());
<|endoftext|>


<commit_before>"use strict";

var themesSupported = [],
    languagesSupported = [],
    express = require( 'express' ),
    path = require( 'path' ),
    bodyParser = require( 'body-parser' ),
    cookieParser = require( 'cookie-parser' ),
    fs = require( 'fs' ),
    favicon = require( 'serve-favicon' ),
    config = require( '../app/models/config-model' ).server,
    logger = require( 'morgan' ),
    i18n = require( 'i18next' ),
    compression = require( 'compression' ),
    errorHandler = require( '../app/controllers/error-handler' ),
    controllersPath = path.join( __dirname, '../app/controllers' ),
    app = express(),
    debug = require( 'debug' )( 'express' );

// general
for ( var item in config ) {
    app.set( item, app.get( item ) || config[ item ] );
}
app.set( 'port', process.env.PORT || app.get( "port" ) || 3000 );
app.set( 'env', process.env.NODE_ENV || 'production' );
app.set( 'authentication cookie name', '__enketo' );

// views
app.set( 'views', path.resolve( __dirname, '../app/views' ) );
app.set( 'view engine', 'jade' );

// pretty json API responses
app.set( 'json spaces', 4 );

// setup i18next
i18n.init( {
    // don't bother with these routes
    ignoreRoutes: [ 'css/', 'fonts/', 'images/', 'js/', 'lib/' ],
    // only attemp to translate the supported languages
    supportedLngs: app.get( 'languages supported' ),
    // allow query string lang override
    detectLngQS: 'lang',
    // fallback language
    fallbackLng: 'en',
    // don't use cookies, always detect
    useCookie: false
} );
// make i18n apphelper available in jade templates
i18n.registerAppHelper( app );

// middleware
app.use( compression() );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( {
    extended: true
} ) );
app.use( cookieParser( app.get( 'encryption key' ) ) );
app.use( i18n.handle );
app.use( favicon( path.resolve( __dirname, '../public/images/favicon.ico' ) ) );
app.use( express.static( path.resolve( __dirname, '../public' ) ) );
app.use( '/locales', express.static( path.resolve( __dirname, '../locales' ) ) );

// set variables that should be accessible in all view templates
app.use( function( req, res, next ) {
    res.locals.livereload = req.app.get( 'env' ) === 'development';
    res.locals.environment = req.app.get( 'env' );
    res.locals.tracking = req.app.get( 'google' ).analytics.ua ? req.app.get( 'google' ).analytics.ua : false;
    res.locals.trackingDomain = req.app.get( 'google' ).analytics.domain || 'auto';
    res.locals.logo = req.app.get( 'logo' );
    res.locals.defaultTheme = req.app.get( 'default theme' ).replace( 'theme-', '' ) || 'kobo';
    res.locals.title = req.app.get( 'app name' );
    res.locals.offline = req.app.get( 'offline enabled' ); // temporary to show 'Experimental' warning
    res.locals.directionality = function(){
        return /^(ar|he)/.test(i18n.lng()) ? 'rtl' : 'ltr';
    };
    next();
} );

// load controllers (including routers)
fs.readdirSync( controllersPath ).forEach( function( file ) {
    if ( file.indexOf( '-controller.js' ) >= 0 ) {
        debug( 'loading', file );
        require( controllersPath + '/' + file )( app );
    }
} );

// logging
app.use( logger( ( app.get( 'env' ) === 'development' ? 'dev' : 'tiny' ) ) );

// error handlers
app.use( errorHandler[ "404" ] );
if ( app.get( 'env' ) === 'development' ) {
    app.use( errorHandler.development );
}
app.use( errorHandler.production );

module.exports = app;
<commit_msg>changed: jsbeautified<commit_after>"use strict";

var themesSupported = [],
    languagesSupported = [],
    express = require( 'express' ),
    path = require( 'path' ),
    bodyParser = require( 'body-parser' ),
    cookieParser = require( 'cookie-parser' ),
    fs = require( 'fs' ),
    favicon = require( 'serve-favicon' ),
    config = require( '../app/models/config-model' ).server,
    logger = require( 'morgan' ),
    i18n = require( 'i18next' ),
    compression = require( 'compression' ),
    errorHandler = require( '../app/controllers/error-handler' ),
    controllersPath = path.join( __dirname, '../app/controllers' ),
    app = express(),
    debug = require( 'debug' )( 'express' );

// general
for ( var item in config ) {
    app.set( item, app.get( item ) || config[ item ] );
}
app.set( 'port', process.env.PORT || app.get( "port" ) || 3000 );
app.set( 'env', process.env.NODE_ENV || 'production' );
app.set( 'authentication cookie name', '__enketo' );

// views
app.set( 'views', path.resolve( __dirname, '../app/views' ) );
app.set( 'view engine', 'jade' );

// pretty json API responses
app.set( 'json spaces', 4 );

// setup i18next
i18n.init( {
    // don't bother with these routes
    ignoreRoutes: [ 'css/', 'fonts/', 'images/', 'js/', 'lib/' ],
    // only attemp to translate the supported languages
    supportedLngs: app.get( 'languages supported' ),
    // allow query string lang override
    detectLngQS: 'lang',
    // fallback language
    fallbackLng: 'en',
    // don't use cookies, always detect
    useCookie: false
} );
// make i18n apphelper available in jade templates
i18n.registerAppHelper( app );

// middleware
app.use( compression() );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( {
    extended: true
} ) );
app.use( cookieParser( app.get( 'encryption key' ) ) );
app.use( i18n.handle );
app.use( favicon( path.resolve( __dirname, '../public/images/favicon.ico' ) ) );
app.use( express.static( path.resolve( __dirname, '../public' ) ) );
app.use( '/locales', express.static( path.resolve( __dirname, '../locales' ) ) );

// set variables that should be accessible in all view templates
app.use( function( req, res, next ) {
    res.locals.livereload = req.app.get( 'env' ) === 'development';
    res.locals.environment = req.app.get( 'env' );
    res.locals.tracking = req.app.get( 'google' ).analytics.ua ? req.app.get( 'google' ).analytics.ua : false;
    res.locals.trackingDomain = req.app.get( 'google' ).analytics.domain || 'auto';
    res.locals.logo = req.app.get( 'logo' );
    res.locals.defaultTheme = req.app.get( 'default theme' ).replace( 'theme-', '' ) || 'kobo';
    res.locals.title = req.app.get( 'app name' );
    res.locals.offline = req.app.get( 'offline enabled' ); // temporary to show 'Experimental' warning
    res.locals.directionality = function() {
        return /^(ar|he)/.test( i18n.lng() ) ? 'rtl' : 'ltr';
    };
    next();
} );

// load controllers (including routers)
fs.readdirSync( controllersPath ).forEach( function( file ) {
    if ( file.indexOf( '-controller.js' ) >= 0 ) {
        debug( 'loading', file );
        require( controllersPath + '/' + file )( app );
    }
} );

// logging
app.use( logger( ( app.get( 'env' ) === 'development' ? 'dev' : 'tiny' ) ) );

// error handlers
app.use( errorHandler[ "404" ] );
if ( app.get( 'env' ) === 'development' ) {
    app.use( errorHandler.development );
}
app.use( errorHandler.production );

module.exports = app;
<|endoftext|>


<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "bootstrap",
], function(widget, $){

    var BoxView = widget.DOMWidgetView.extend({
        initialize: function(){
            // Public constructor
            BoxView.__super__.initialize.apply(this, arguments);
            this.model.on('change:children', function(model, value) {
                this.update_children(model.previous('children'), value);
            }, this);
        },

        render: function(){
            // Called when view is rendered.
            this.$box = this.$el;
            this.$box.addClass('widget-box');
            this.update_children([], this.model.get('children'));
        },

        update_children: function(old_list, new_list) {
            // Called when the children list changes.
            this.do_diff(old_list, new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a model is removed from the children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a model is added to the children list.
            var view = this.create_child_view(model);
            this.$box.append(view.$el);

            // Trigger the displayed event of the child view.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },
    });

    var FlexBoxView = BoxView.extend({
        render: function(){
            FlexBoxView.__super__.render.apply(this);
            this.model.on('change:orientation', this.update_orientation, this);
            this.model.on('change:flex', this._flex_changed, this);
            this.model.on('change:pack', this._pack_changed, this);
            this.model.on('change:align', this._align_changed, this);
            this._flex_changed();
            this._pack_changed();
            this._align_changed();
            that.update_orientation();
        },

        update_orientation: function(){
            var orientation = this.model.get("orientation");
            if (orientation == "vertical") {
                this.$box.removeClass("hbox").addClass("vbox");
            } else {
                this.$box.removeClass("vbox").addClass("hbox");
            }
        },

        _flex_changed: function(){
            if (this.model.previous('flex')) {
                this.$box.removeClass('box-flex' + this.model.previous('flex'));
            }
            this.$box.addClass('box-flex' + this.model.get('flex'));
        },

        _pack_changed: function(){
            if (this.model.previous('pack')) {
                this.$box.removeClass(this.model.previous('pack'));
            }
            this.$box.addClass(this.model.get('pack'));
        },

        _align_changed: function(){
            if (this.model.previous('align')) {
                this.$box.removeClass('align-' + this.model.previous('align'));
            }
            this.$box.addClass('align-' + this.model.get('align'));
        },
    });

    var PopupView = BoxView.extend({

        render: function(){
            // Called when view is rendered.
            var that = this;

            this.$el.on("remove", function(){
                    that.$backdrop.remove();
                });
            this.$backdrop = $('<div />')
                .appendTo($('#notebook-container'))
                .addClass('modal-dialog')
                .css('position', 'absolute')
                .css('left', '0px')
                .css('top', '0px');
            this.$window = $('<div />')
                .appendTo(this.$backdrop)
                .addClass('modal-content widget-modal')
                .mousedown(function(){
                    that.bring_to_front();
                });

            // Set the elements array since the this.$window element is not child
            // of this.$el and the parent widget manager or other widgets may
            // need to know about all of the top-level widgets.  The IPython
            // widget manager uses this to register the elements with the
            // keyboard manager.
            this.additional_elements = [this.$window];

            this.$title_bar = $('<div />')
                .addClass('popover-title')
                .appendTo(this.$window)
                .mousedown(function(){
                    that.bring_to_front();
                });
            this.$close = $('<button />')
                .addClass('close fa fa-remove')
                .css('margin-left', '5px')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.hide();
                    event.stopPropagation();
                });
            this.$minimize = $('<button />')
                .addClass('close fa fa-arrow-down')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.popped_out = !that.popped_out;
                    if (!that.popped_out) {
                        that.$minimize
                            .removeClass('fa fa-arrow-down')
                            .addClass('fa fa-arrow-up');

                        that.$window
                            .draggable('destroy')
                            .resizable('destroy')
                            .removeClass('widget-modal modal-content')
                            .addClass('docked-widget-modal')
                            .detach()
                            .insertBefore(that.$show_button);
                        that.$show_button.hide();
                        that.$close.hide();
                    } else {
                        that.$minimize
                            .addClass('fa fa-arrow-down')
                            .removeClass('fa fa-arrow-up');

                        that.$window
                            .removeClass('docked-widget-modal')
                            .addClass('widget-modal modal-content')
                            .detach()
                            .appendTo(that.$backdrop)
                            .draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'})
                            .resizable()
                            .children('.ui-resizable-handle').show();
                        that.show();
                        that.$show_button.show();
                        that.$close.show();
                    }
                    event.stopPropagation();
                });
            this.$title = $('<div />')
                .addClass('widget-modal-title')
                .html(" ")
                .appendTo(this.$title_bar);
            this.$box = $('<div />')
                .addClass('modal-body')
                .addClass('widget-modal-body')
                .addClass('widget-box')
                .addClass('vbox')
                .appendTo(this.$window);

            this.$show_button = $('<button />')
                .html(" ")
                .addClass('btn btn-info widget-modal-show')
                .appendTo(this.$el)
                .click(function(){
                    that.show();
                });

            this.$window.draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'});
            this.$window.resizable();
            this.$window.on('resize', function(){
                that.$box.outerHeight(that.$window.innerHeight() - that.$title_bar.outerHeight());
            });

            this._shown_once = false;
            this.popped_out = true;

            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value) {
                this.update_children(model.previous('children'), value);
            }, this);
        },

        hide: function() {
            // Called when the modal hide button is clicked.
            this.$window.hide();
            this.$show_button.removeClass('btn-info');
        },

        show: function() {
            // Called when the modal show button is clicked.
            this.$show_button.addClass('btn-info');
            this.$window.show();
            if (this.popped_out) {
                this.$window.css("positon", "absolute");
                this.$window.css("top", "0px");
                this.$window.css("left", Math.max(0, (($('body').outerWidth() - this.$window.outerWidth()) / 2) +
                    $(window).scrollLeft()) + "px");
                this.bring_to_front();
            }
        },

        bring_to_front: function() {
            // Make the modal top-most, z-ordered about the other modals.
            var $widget_modals = $(".widget-modal");
            var max_zindex = 0;
            $widget_modals.each(function (index, el){
                var zindex = parseInt($(el).css('z-index'));
                if (!isNaN(zindex)) {
                    max_zindex = Math.max(max_zindex, zindex);
                }
            });

            // Start z-index of widget modals at 2000
            max_zindex = Math.max(max_zindex, 2000);

            $widget_modals.each(function (index, el){
                $el = $(el);
                if (max_zindex == parseInt($el.css('z-index'))) {
                    $el.css('z-index', max_zindex - 1);
                }
            });
            this.$window.css('z-index', max_zindex);
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var description = this.model.get('description');
            if (description.trim().length === 0) {
                this.$title.html(" "); // Preserve title height
            } else {
                this.$title.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$title.get(0)]);
            }

            var button_text = this.model.get('button_text');
            if (button_text.trim().length === 0) {
                this.$show_button.html(" "); // Preserve button height
            } else {
                this.$show_button.text(button_text);
            }

            if (!this._shown_once) {
                this._shown_once = true;
                this.show();
            }

            return PopupView.__super__.update.apply(this);
        },

        _get_selector_element: function(selector) {
            // Get an element view a 'special' jquery selector.  (see widget.js)
            //
            // Since the modal actually isn't within the $el in the DOM, we need to extend
            // the selector logic to allow the user to set css on the modal if need be.
            // The convention used is:
            // "modal" - select the modal div
            // "modal [selector]" - select element(s) within the modal div.
            // "[selector]" - select elements within $el
            // "" - select the $el
            if (selector.substring(0, 5) == 'modal') {
                if (selector == 'modal') {
                    return this.$window;
                } else {
                    return this.$window.find(selector.substring(6));
                }
            } else {
                return PopupView.__super__._get_selector_element.apply(this, [selector]);
            }
        },
    });

    return {
        'BoxView': BoxView,
        'PopupView': PopupView,
        'FlexBoxView': FlexBoxView,
    };
});
<commit_msg>s/that/this bug<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "bootstrap",
], function(widget, $){

    var BoxView = widget.DOMWidgetView.extend({
        initialize: function(){
            // Public constructor
            BoxView.__super__.initialize.apply(this, arguments);
            this.model.on('change:children', function(model, value) {
                this.update_children(model.previous('children'), value);
            }, this);
        },

        render: function(){
            // Called when view is rendered.
            this.$box = this.$el;
            this.$box.addClass('widget-box');
            this.update_children([], this.model.get('children'));
        },

        update_children: function(old_list, new_list) {
            // Called when the children list changes.
            this.do_diff(old_list, new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a model is removed from the children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a model is added to the children list.
            var view = this.create_child_view(model);
            this.$box.append(view.$el);

            // Trigger the displayed event of the child view.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },
    });

    var FlexBoxView = BoxView.extend({
        render: function(){
            FlexBoxView.__super__.render.apply(this);
            this.model.on('change:orientation', this.update_orientation, this);
            this.model.on('change:flex', this._flex_changed, this);
            this.model.on('change:pack', this._pack_changed, this);
            this.model.on('change:align', this._align_changed, this);
            this._flex_changed();
            this._pack_changed();
            this._align_changed();
            this.update_orientation();
        },

        update_orientation: function(){
            var orientation = this.model.get("orientation");
            if (orientation == "vertical") {
                this.$box.removeClass("hbox").addClass("vbox");
            } else {
                this.$box.removeClass("vbox").addClass("hbox");
            }
        },

        _flex_changed: function(){
            if (this.model.previous('flex')) {
                this.$box.removeClass('box-flex' + this.model.previous('flex'));
            }
            this.$box.addClass('box-flex' + this.model.get('flex'));
        },

        _pack_changed: function(){
            if (this.model.previous('pack')) {
                this.$box.removeClass(this.model.previous('pack'));
            }
            this.$box.addClass(this.model.get('pack'));
        },

        _align_changed: function(){
            if (this.model.previous('align')) {
                this.$box.removeClass('align-' + this.model.previous('align'));
            }
            this.$box.addClass('align-' + this.model.get('align'));
        },
    });

    var PopupView = BoxView.extend({

        render: function(){
            // Called when view is rendered.
            var that = this;

            this.$el.on("remove", function(){
                    that.$backdrop.remove();
                });
            this.$backdrop = $('<div />')
                .appendTo($('#notebook-container'))
                .addClass('modal-dialog')
                .css('position', 'absolute')
                .css('left', '0px')
                .css('top', '0px');
            this.$window = $('<div />')
                .appendTo(this.$backdrop)
                .addClass('modal-content widget-modal')
                .mousedown(function(){
                    that.bring_to_front();
                });

            // Set the elements array since the this.$window element is not child
            // of this.$el and the parent widget manager or other widgets may
            // need to know about all of the top-level widgets.  The IPython
            // widget manager uses this to register the elements with the
            // keyboard manager.
            this.additional_elements = [this.$window];

            this.$title_bar = $('<div />')
                .addClass('popover-title')
                .appendTo(this.$window)
                .mousedown(function(){
                    that.bring_to_front();
                });
            this.$close = $('<button />')
                .addClass('close fa fa-remove')
                .css('margin-left', '5px')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.hide();
                    event.stopPropagation();
                });
            this.$minimize = $('<button />')
                .addClass('close fa fa-arrow-down')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.popped_out = !that.popped_out;
                    if (!that.popped_out) {
                        that.$minimize
                            .removeClass('fa fa-arrow-down')
                            .addClass('fa fa-arrow-up');

                        that.$window
                            .draggable('destroy')
                            .resizable('destroy')
                            .removeClass('widget-modal modal-content')
                            .addClass('docked-widget-modal')
                            .detach()
                            .insertBefore(that.$show_button);
                        that.$show_button.hide();
                        that.$close.hide();
                    } else {
                        that.$minimize
                            .addClass('fa fa-arrow-down')
                            .removeClass('fa fa-arrow-up');

                        that.$window
                            .removeClass('docked-widget-modal')
                            .addClass('widget-modal modal-content')
                            .detach()
                            .appendTo(that.$backdrop)
                            .draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'})
                            .resizable()
                            .children('.ui-resizable-handle').show();
                        that.show();
                        that.$show_button.show();
                        that.$close.show();
                    }
                    event.stopPropagation();
                });
            this.$title = $('<div />')
                .addClass('widget-modal-title')
                .html(" ")
                .appendTo(this.$title_bar);
            this.$box = $('<div />')
                .addClass('modal-body')
                .addClass('widget-modal-body')
                .addClass('widget-box')
                .addClass('vbox')
                .appendTo(this.$window);

            this.$show_button = $('<button />')
                .html(" ")
                .addClass('btn btn-info widget-modal-show')
                .appendTo(this.$el)
                .click(function(){
                    that.show();
                });

            this.$window.draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'});
            this.$window.resizable();
            this.$window.on('resize', function(){
                that.$box.outerHeight(that.$window.innerHeight() - that.$title_bar.outerHeight());
            });

            this._shown_once = false;
            this.popped_out = true;

            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value) {
                this.update_children(model.previous('children'), value);
            }, this);
        },

        hide: function() {
            // Called when the modal hide button is clicked.
            this.$window.hide();
            this.$show_button.removeClass('btn-info');
        },

        show: function() {
            // Called when the modal show button is clicked.
            this.$show_button.addClass('btn-info');
            this.$window.show();
            if (this.popped_out) {
                this.$window.css("positon", "absolute");
                this.$window.css("top", "0px");
                this.$window.css("left", Math.max(0, (($('body').outerWidth() - this.$window.outerWidth()) / 2) +
                    $(window).scrollLeft()) + "px");
                this.bring_to_front();
            }
        },

        bring_to_front: function() {
            // Make the modal top-most, z-ordered about the other modals.
            var $widget_modals = $(".widget-modal");
            var max_zindex = 0;
            $widget_modals.each(function (index, el){
                var zindex = parseInt($(el).css('z-index'));
                if (!isNaN(zindex)) {
                    max_zindex = Math.max(max_zindex, zindex);
                }
            });

            // Start z-index of widget modals at 2000
            max_zindex = Math.max(max_zindex, 2000);

            $widget_modals.each(function (index, el){
                $el = $(el);
                if (max_zindex == parseInt($el.css('z-index'))) {
                    $el.css('z-index', max_zindex - 1);
                }
            });
            this.$window.css('z-index', max_zindex);
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var description = this.model.get('description');
            if (description.trim().length === 0) {
                this.$title.html(" "); // Preserve title height
            } else {
                this.$title.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$title.get(0)]);
            }

            var button_text = this.model.get('button_text');
            if (button_text.trim().length === 0) {
                this.$show_button.html(" "); // Preserve button height
            } else {
                this.$show_button.text(button_text);
            }

            if (!this._shown_once) {
                this._shown_once = true;
                this.show();
            }

            return PopupView.__super__.update.apply(this);
        },

        _get_selector_element: function(selector) {
            // Get an element view a 'special' jquery selector.  (see widget.js)
            //
            // Since the modal actually isn't within the $el in the DOM, we need to extend
            // the selector logic to allow the user to set css on the modal if need be.
            // The convention used is:
            // "modal" - select the modal div
            // "modal [selector]" - select element(s) within the modal div.
            // "[selector]" - select elements within $el
            // "" - select the $el
            if (selector.substring(0, 5) == 'modal') {
                if (selector == 'modal') {
                    return this.$window;
                } else {
                    return this.$window.find(selector.substring(6));
                }
            } else {
                return PopupView.__super__._get_selector_element.apply(this, [selector]);
            }
        },
    });

    return {
        'BoxView': BoxView,
        'PopupView': PopupView,
        'FlexBoxView': FlexBoxView,
    };
});
<|endoftext|>


<commit_before>/*
 * MediaWiki article feedback tool
 */
jQuery(function($){
	var F = {ui:{}, page:{}};
	var PD=function(e){ // preventDefault shorthand
		if(e && 'preventDefault' in e && 'call' in e.preventDefault)
			e.preventDefault()
	};

	F.page.name = wgPageName.replace(/_/g, ' ');

	F.opts = {
		'watch': true,
		'triggers': [['section', 'Feedback']]
	};
	$('#feedback-opts').each(function(i,e){
		try {
			$.extend(F.opts, JSON.parse($(e).text()||'{}'));
		}
		catch(e) {}
	});

	F.enabled = !!$('#feedback-enable').length;

	F.log = function(){
		args = [].slice.call(arguments);
		args.unshift('Feedback reporter:');
		if ('console' in window && 'log' in console) {
			console.log.apply(console, args);
		}
	};

	F.setup = function(){
		if (!F.enabled) {
			return false;
		}
		$.each(F.opts.triggers, function(i, trigger){
			switch (trigger[0].toLowerCase()) {
				case 'section':
					$('body').on('click', 'a[href=#'+trigger[1]+']', F.init);
					break;
				case 'tab':
					F.ui.tab.show();
					break;
				default:
					F.log('Unknown trigger type:', trigger[0])
			}
		});
		return true;
	};

	F.init = function(e){PD(e);
		if (!F.enabled) {
			return false;
		}
		F.ui.show();
		return true;
	};

	F.reset = function(e){PD(e);
		F.ui.form.find('input[type=text], textarea').val('');
	};

	F.exit = function(e){PD(e);
		if (!F.exit.enabled) {
			return false;
		}
		F.ui.hide();
		return true;
	};
	F.exit.enabled = true;

	F.save = function(e, captcha){PD(e);
		F.ui.error.fadeOut(200);
		var text = F.ui.f_text.val();
		if (!text) {
			return F.save_error('Feedback is required!');
		}
		// Remove trailing whitespace
		text = text.replace(/\s+$/, '') + ' --~~~~';
		text = ('
$1
\n'.replace(/\$1/g,
			Number(F.ui.f_section.val()) ? 'Section: ' + F.ui.f_section.find(':selected').text() : 'No section specified'
		)) + text;
		F.ui.form.hide();
		F.ui.close_link.hide();
		F.ui.progress.show();
		F.exit.enabled = false;
		F.ui.screen.animate({height: '15%'}, 400);

		var edit_token = mw.user.tokens.values.editToken,
			watch_token = mw.user.tokens.values.watchToken,
			title = (F.ui.f_title.val() ?
				 'Feedback: '+F.ui.f_title.val() :
				 'Feedback from '+(window.wgUserName||'anonymous user')),
			api_path = wgScriptPath + '/api.php',
			query = {
				action: 'edit',
				format: 'json',
				section: 'new',
				text: text,
				summary: title,
				token: edit_token
			},
			p = F.ui.progress.html('
Submitting feedback...
');
		$.extend(query, captcha);
		if (F.opts.watch) {
			query.watch = 1;
		}
		// Obtain talk page title
		$.get(api_path, {action:'parse', format:'json', title:wgPageName,
		      text:'{{TALKPAGENAME}}'}, function(d){
			query.title = $('').html(d.parse.text['*']).text().replace(/\n/g, '');
			$.post(api_path, query, function(d){
				if ('captcha' in d.edit) {
					F.save_captcha(query, d);
					return;
				}
				p.html('
Thank you!
');
				F.exit.enabled = true;
				setTimeout(F.exit, 500);
				F.reset();
			});
		});
		return true;
	};

	F.save_captcha = function(q, d){
		if (!('captcha' in d.edit)) {
			return false;
		}
		F.ui.screen.stop().animate({height: '50%'}, 400);
		F.exit.enabled = true;
		switch (d.edit.captcha.type) {
			case 'recaptcha':
				$('
').appendTo(F.ui.progress)
				.html('To prevent spam, please type the words you see in the box below.');				$('
').appendTo(F.ui.progress);
				Recaptcha.create(d.edit.captcha.key, 'F-recaptcha');
				$('Cancel').appendTo(F.ui.progress);
				$('OK').click(function(e){PD(e);
					F.exit.enabled = false;
					F.ui.screen.animate({height: '15%'}, 400);
					F.save(0, {
						captchaid: $('#recaptcha_challenge_field').val(),
						captchaword: $('#recaptcha_response_field').val()
					});
				}).appendTo(F.ui.progress).css('padding-left', '1em');
				break;
			default:
				return false;
		}
		return true;
	};

	F.save_error = function(err){
		F.ui.error.text(err).fadeIn(200);
		return false;
	};

	F.ui.show = function(e){PD(e);
		F.ui.overlay.fadeIn(300);
		F.ui.screen.fadeIn(300).css({height: '50%'});
		F.ui.tab.addClass('selected');
		F.ui.form.show();
		F.ui.close_link.show();
		F.ui.progress.hide();
		F.exit.enabled = true;
	};

	F.ui.hide = function(e){PD(e);
		F.ui.overlay
		.add(F.ui.screen)
		.add(F.ui.error)
		.fadeOut(300);
		F.ui.tab.removeClass('selected');
	};

	F.ui.tab = $('
').html('Feedback')
		.insertAfter('#left-navigation ul:nth(0) li:last').hide();

	F.ui.overlay = $('
').css({
		top:0, left:0, width:'100%', height:'100%', position:'fixed',
		'z-index': 1000, 'background-color': 'rgba(128,128,128,0.5)'
	}).hide().appendTo('body').click(F.exit);

	F.ui.screen = $('
').css({
		top:'25%', left:'25%', width:'50%', height:'50%',
		position:'fixed', 'z-index': 1000, 'background-color':'white',
		'border-radius': 4, padding: '1em'
	}).hide().appendTo('body');

	F.ui.close_link = $('').attr('href','#F-exit').text('Close').css({
		color:'red', 'float':'right'
	}).appendTo(F.ui.screen);

	$('body').on('click', 'a[href=#F-init]', F.init);
	$('body').on('click', 'a[href=#F-exit]', F.exit);

	F.ui.screen.append('
Feedback
');
	F.ui.form = $('
').appendTo(F.ui.screen).css({height:'100%'});
	F.ui.progress = $('
').appendTo(F.ui.screen).css({height:'100%'}).hide()
		.css({'text-align':'center'});

	F.ui.f_title = $('<input>').attr({type:'text', placeholder:'Title', title:'Title'})
	.appendTo(F.ui.form).css({
		'font-size': '1.2em'
	});
	F.ui.f_text = $('<textarea>').appendTo(F.ui.form).css({
		height:'50%',
		'font-size': '1em'
	}).attr({placeholder:'Feedback (required)', title:'Feedback (required)'});
	F.ui.f_section = $('<select>').insertBefore(F.ui.f_title).css({
		'float': 'left'
	}).attr('id', 'F-section');
	F.ui.f_section.append($('<option>').text('(No section)').attr({value:0}));
	$('#mw-content-text').children('h1,h2,h3,h4,h5,h6').each(function(i, e){
		F.ui.f_section.append($('<option>').text($(e).find('.mw-headline').text()).attr({value:1}));
	});

	F.ui.f_text.add(F.ui.f_title).css({
		width: '95%',
		border: '1px solid #ccc',
		'border-radius': 2,
		color: '#333',
		margin: 6,
		'padding': 5,
		'font-family': 'sans-serif'
	});

	$('
').css('clear','both').insertAfter(F.ui.f_text);

	F.ui.watch = $('<input>').attr({type:'checkbox', id:'F-watch'}).appendTo(F.ui.form)
	.css({
		'float':'left'
	}).prop('checked', F.opts.watch);
	F.ui.watch_label = $('').text('Watch for changes')
	.insertAfter(F.ui.watch);
	if (!wgUserName) {
		F.ui.watch.hide();
		F.ui.watch_label.hide();
		F.opts.watch = false;
	}
	F.ui.b_submit = $('<button>').text('Submit feedback').appendTo(F.ui.form).click(F.save);
	F.ui.b_cancel = $('<button>').text('Cancel').appendTo(F.ui.form).click(F.exit);
	F.ui.b_cancel.add(F.ui.b_submit).css({
		'float': 'right',
		'background-color': '#ddd',
		cursor: 'pointer',
	}).add(F.ui.f_section).css({
		border: '1px solid #ddd',
		color: '#333',
		'border-radius': 2,
		'margin-right': 5,
		'font-size': '1em',
	});
	F.ui.error = $('
').css({color:'red', 'clear':'both'}).hide().appendTo(F.ui.form);

	F.setup();
	window.Feedback = F;
});
<commit_msg>Add section feedback links<commit_after>/*
 * MediaWiki article feedback tool
 */
jQuery(function($){
	var F = {ui:{}, page:{}};
	var PD=function(e){ // preventDefault shorthand
		if(e && 'preventDefault' in e && 'call' in e.preventDefault)
			e.preventDefault()
	};

	F.page.name = wgPageName.replace(/_/g, ' ');

	F.opts = {
		'watch': true,
		'triggers': [['section', 'Feedback']]
	};
	$('#feedback-opts').each(function(i,e){
		try {
			$.extend(F.opts, JSON.parse($(e).text()||'{}'));
		}
		catch(e) {}
	});

	F.enabled = !!$('#feedback-enable').length;

	F.log = function(){
		args = [].slice.call(arguments);
		args.unshift('Feedback reporter:');
		if ('console' in window && 'log' in console) {
			console.log.apply(console, args);
		}
	};

	F.setup = function(){
		if (!F.enabled) {
			return false;
		}
		$.each(F.opts.triggers, function(i, trigger){
			switch (trigger[0].toLowerCase()) {
				case 'section':
					$('body').on('click', 'a[href=#'+trigger[1]+']', F.init);
					break;
				case 'tab':
					F.ui.tab.show();
					break;
				case 'sectionlink':
					$('.F-section-link').show();
					break;
				default:
					F.log('Unknown trigger type:', trigger[0])
			}
		});
		return true;
	};

	F.init = function(e){PD(e);
		if (!F.enabled) {
			return false;
		}
		F.ui.show();
		var section = $(this).data('section')
		if (section) {
			F.ui.f_section.find('option').filter(function(i, e){
				return $(e).text() == section
			}).prop('selected', true);
		}
		return true;
	};

	F.reset = function(e){PD(e);
		F.ui.form.find('input[type=text], textarea').val('');
	};

	F.exit = function(e){PD(e);
		if (!F.exit.enabled) {
			return false;
		}
		F.ui.hide();
		return true;
	};
	F.exit.enabled = true;

	F.save = function(e, captcha){PD(e);
		F.ui.error.fadeOut(200);
		var text = F.ui.f_text.val();
		if (!text) {
			return F.save_error('Feedback is required!');
		}
		// Remove trailing whitespace
		text = text.replace(/\s+$/, '') + ' --~~~~';
		text = ('
$1
\n'.replace(/\$1/g,
			Number(F.ui.f_section.val()) ? 'Section: ' + F.ui.f_section.find(':selected').text() : 'No section specified'
		)) + text;
		F.ui.form.hide();
		F.ui.close_link.hide();
		F.ui.progress.show();
		F.exit.enabled = false;
		F.ui.screen.animate({height: '15%'}, 400);

		var edit_token = mw.user.tokens.values.editToken,
			watch_token = mw.user.tokens.values.watchToken,
			title = (F.ui.f_title.val() ?
				 'Feedback: '+F.ui.f_title.val() :
				 'Feedback from '+(window.wgUserName||'anonymous user')),
			api_path = wgScriptPath + '/api.php',
			query = {
				action: 'edit',
				format: 'json',
				section: 'new',
				text: text,
				summary: title,
				token: edit_token
			},
			p = F.ui.progress.html('
Submitting feedback...
');
		$.extend(query, captcha);
		if (F.opts.watch) {
			query.watch = 1;
		}
		// Obtain talk page title
		$.get(api_path, {action:'parse', format:'json', title:wgPageName,
		      text:'{{TALKPAGENAME}}'}, function(d){
			query.title = $('').html(d.parse.text['*']).text().replace(/\n/g, '');
			$.post(api_path, query, function(d){
				if ('captcha' in d.edit) {
					F.save_captcha(query, d);
					return;
				}
				p.html('
Thank you!
');
				F.exit.enabled = true;
				setTimeout(F.exit, 500);
				F.reset();
			});
		});
		return true;
	};

	F.save_captcha = function(q, d){
		if (!('captcha' in d.edit)) {
			return false;
		}
		F.ui.screen.stop().animate({height: '50%'}, 400);
		F.exit.enabled = true;
		switch (d.edit.captcha.type) {
			case 'recaptcha':
				$('
').appendTo(F.ui.progress)
				.html('To prevent spam, please type the words you see in the box below.');				$('
').appendTo(F.ui.progress);
				Recaptcha.create(d.edit.captcha.key, 'F-recaptcha');
				$('Cancel').appendTo(F.ui.progress);
				$('OK').click(function(e){PD(e);
					F.exit.enabled = false;
					F.ui.screen.animate({height: '15%'}, 400);
					F.save(0, {
						captchaid: $('#recaptcha_challenge_field').val(),
						captchaword: $('#recaptcha_response_field').val()
					});
				}).appendTo(F.ui.progress).css('padding-left', '1em');
				break;
			default:
				return false;
		}
		return true;
	};

	F.save_error = function(err){
		F.ui.error.text(err).fadeIn(200);
		return false;
	};

	F.ui.show = function(e){PD(e);
		F.ui.overlay.fadeIn(300);
		F.ui.screen.fadeIn(300).css({height: '50%'});
		F.ui.tab.addClass('selected');
		F.ui.form.show();
		F.ui.close_link.show();
		F.ui.progress.hide();
		F.exit.enabled = true;
	};

	F.ui.hide = function(e){PD(e);
		F.ui.overlay
		.add(F.ui.screen)
		.add(F.ui.error)
		.fadeOut(300);
		F.ui.tab.removeClass('selected');
	};

	F.ui.tab = $('
').html('Feedback')
		.insertAfter('#left-navigation ul:nth(0) li:last').hide();

	F.ui.overlay = $('
').css({
		top:0, left:0, width:'100%', height:'100%', position:'fixed',
		'z-index': 1000, 'background-color': 'rgba(128,128,128,0.5)'
	}).hide().appendTo('body').click(F.exit);

	F.ui.screen = $('
').css({
		top:'25%', left:'25%', width:'50%', height:'50%',
		position:'fixed', 'z-index': 1000, 'background-color':'white',
		'border-radius': 4, padding: '1em'
	}).hide().appendTo('body');

	F.ui.close_link = $('').attr('href','#F-exit').text('Close').css({
		color:'red', 'float':'right'
	}).appendTo(F.ui.screen);

	$('body').on('click', 'a[href=#F-init]', F.init);
	$('body').on('click', 'a[href=#F-exit]', F.exit);

	F.ui.screen.append('
Feedback
');
	F.ui.form = $('
').appendTo(F.ui.screen).css({height:'100%'});
	F.ui.progress = $('
').appendTo(F.ui.screen).css({height:'100%'}).hide()
		.css({'text-align':'center'});

	F.ui.f_title = $('<input>').attr({type:'text', placeholder:'Title', title:'Title'})
	.appendTo(F.ui.form).css({
		'font-size': '1.2em'
	});
	F.ui.f_text = $('<textarea>').appendTo(F.ui.form).css({
		height:'50%',
		'font-size': '1em'
	}).attr({placeholder:'Feedback (required)', title:'Feedback (required)'});
	F.ui.f_section = $('<select>').insertBefore(F.ui.f_title).css({
		'float': 'left'
	}).attr('id', 'F-section');
	F.ui.f_section.append($('<option>').text('(No section)').attr({value:0}));

	$('#mw-content-text').children('h1,h2,h3,h4,h5,h6').each(function(i, e){
		var section = $(e).find('.mw-headline').text();
		F.ui.f_section.append($('<option>').text(section).attr({value:1}));
		$(e).find('.editsection').prepend(
			$('').text('[').append(
				$('').attr('href','#F-init').text('Leave feedback').data({section:section})
			).append('] ').addClass('F-section-link').hide()
		)
	});

	F.ui.f_text.add(F.ui.f_title).css({
		width: '95%',
		border: '1px solid #ccc',
		'border-radius': 2,
		color: '#333',
		margin: 6,
		'padding': 5,
		'font-family': 'sans-serif'
	});

	$('
').css('clear','both').insertAfter(F.ui.f_text);

	F.ui.watch = $('<input>').attr({type:'checkbox', id:'F-watch'}).appendTo(F.ui.form)
	.css({
		'float':'left'
	}).prop('checked', F.opts.watch);
	F.ui.watch_label = $('').text('Watch for changes')
	.insertAfter(F.ui.watch);
	if (!wgUserName) {
		F.ui.watch.hide();
		F.ui.watch_label.hide();
		F.opts.watch = false;
	}
	F.ui.b_submit = $('<button>').text('Submit feedback').appendTo(F.ui.form).click(F.save);
	F.ui.b_cancel = $('<button>').text('Cancel').appendTo(F.ui.form).click(F.exit);
	F.ui.b_cancel.add(F.ui.b_submit).css({
		'float': 'right',
		'background-color': '#ddd',
		cursor: 'pointer',
	}).add(F.ui.f_section).css({
		border: '1px solid #ddd',
		color: '#333',
		'border-radius': 2,
		'margin-right': 5,
		'font-size': '1em',
	});
	F.ui.error = $('
').css({color:'red', 'clear':'both'}).hide().appendTo(F.ui.form);

	F.setup();
	window.Feedback = F;
});
<|endoftext|>


<commit_before>(function() {

var KasuariImage = function(ix, iy, iz, url) {
    this.ix = ix;
    this.iy = iy;
    this.iz = iz;
    this.scale = Math.pow(2, iz);
    this.loaded = false;
    this.url = url;
    this.img = new Image();
    this.onload = undefined;

    this.id = ix + '-' + iy + '-' + iz;

    var self = this;
    this.img.onload = function() {
        self.loaded = true;
        if (self.onload != undefined) {
            self.onload(self);
        }
    };
};

KasuariImage.prototype = {
    init: function() {
        this.img.src = this.url;
    },

    draw: function(ctx, scale) {
        if (!this.loaded) { return; }
        var s = scale * this.scale;
        var dim = 256 * s;
        var x = Math.ceil(this.ix * dim);
        var y = Math.ceil(this.iy * dim);
        var w = Math.ceil(this.img.width * s);
        var h = Math.ceil(this.img.height * s);
        try {
            ctx.drawImage(this.img, x, y, w, h);
        }
        catch (err) {
            // image is removed when this image is about to be rendered
        }
    }
};

var RedrawBucket = function(kasuari) {
    var self = this;
    this.timer = setInterval(function() { self.redraw(); }, 250);
    this.items = [];
    this.kasuari = kasuari;
};

RedrawBucket.prototype = {
    add: function(img) {
        this.items.push(img);
    },

    redraw: function() {
        var items = this.items.slice(0);
        this.items = []; // racing condition possibility

        var level = this.kasuari.zoomLevel;
        var len = items.length;
        for (var i=0; i<len; i++) {
            var img = items[i];
            if (img.iz == level) {
                var key = img.ix+','+img.iy;
                this.kasuari.images[level][key] = img;
            }
        }

        this.kasuari.redraw();
    },
};

var Kasuari = function(canvas, config) {
    this.canvas = canvas.get(0);
    this.cw = canvas.width();
    this.ch = canvas.height();
    this.canvas.width = this.cw;
    this.canvas.height = this.ch;
    this.ctx = this.canvas.getContext('2d');

    this.dir = config.imgdir;
    this.ext = config.ext;
    this.zoomLevel = config.zoom;
    this.oldZoomLevel = this.zoomlevel;
    this.w = config.w;
    this.h = config.h;

    this.scale = Math.pow(0.5, this.zoomLevel);
    this.tx = 0;
    this.ty = 0;

    this.drag = {x: 0, y: 0, dx: 0, dy: 0, enabled: false};
    this.zooming = {x: 0, y: 0, scale: 0,
                    dx: 0, dy: 0, dscale: 0,
                    tx: 0, ty: 0, tscale: 0,
                    duration: 250,
                    interval: 20,
                    start: new Date(),
                    enabled: false};

    this.clickZoomStep = 2.0;
    this.wheelZoomStep = 2.0;

    this.images = [];

    this.redrawBucket = new RedrawBucket(this);
};

Kasuari.prototype = {
    getURL: function(ix, iy, iz) {
        return this.dir + '/img-z' + iz + '.x' + ix + '.y' + iy + this.ext;
    },

    start: function() {
        this.initEventHandlers();
        this.updateImages();
    },

    addImage: function(ix, iy, iz) {
        var url = this.getURL(ix, iy, iz);
        var img = new KasuariImage(ix, iy, iz, url);
        var self = this;
        img.onload = function(img) {
            if (self.images[iz] == undefined) {
                self.images[iz] = {};
            }
            self.redrawBucket.add(img);
            // self.images[iz][ix+','+iy] = img;
            // self.redraw();
        }
        return img;
    },

    redraw: function() {

        this.ctx.clearRect(0, 0, this.cw, this.ch);

        this.ctx.save();
        this.ctx.translate(this.tx, this.ty);

        var len = this.images.length;
        for (var i=len-1; i>=0; i--) {
            var images = this.images[i];
            if ((images != undefined) && (i >= this.zoomLevel)) {
                for (var key in images) {
                    images[key].draw(this.ctx, this.scale);
                }
            }
        }

        this.ctx.restore();
    },

    updateZoomLevel: function() {
        var zoomLevel = Math.floor(Math.log(1/this.scale) / Math.log(2));
        if (zoomLevel < 0) { zoomLevel = 0; }
        this.zoomLevel = zoomLevel;
    },

    getVisibleImages: function(level) {
        var tx = this.tx / this.scale;
        var ty = this.ty / this.scale;
        var cw = this.cw / this.scale;
        var ch = this.ch / this.scale;
        var size = 256 * Math.pow(2, level);

        var x0 = Math.floor(-tx / size) - 1;
        var y0 = Math.floor(-ty / size) - 1;
        var x1 = Math.ceil((-tx + cw) / size) + 1;
        var y1 = Math.ceil((-ty + ch) / size) + 1;

        var items = {};

        var x, y;
        for (x=x0; x<=x1; x++) {
            for (y=y0; y<=y1; y++) {
                if ((x >= 0) && (y >= 0)) {
                    items[x+','+y] = [x, y];
                }
            }
        }

        return items;
    },

    updateVisibleImages: function(level, add) {
        var items = this.getVisibleImages(level);

        if (this.images[level] == undefined) {
            this.images[level] = {};
        }

        // delete unused image
        for (var key in this.images[level]) {
            if (!(key in items)) {
                delete this.images[level][key];
            }
        }

        // add new image
        if ((add == undefined) || add) {
            var images = this.images[level];
            for (var key in items) {
                var data = items[key];
                if (!(data in images)) {
                    this.addImage(data[0], data[1], level).init();
                }
            }
        }
    },

    updateImages: function() {
        var len = this.images.length;
        for (var i=0; i<len; i++) {
            if (i != this.zoomLevel) {
                this.updateVisibleImages(i, false);
            }
        }
        this.updateVisibleImages(this.zoomLevel);
    },

    /* Event handlers */

    initEventHandlers: function() {
        var canvas = $(this.canvas);
        var self = this;
        canvas.mousedown(function(e) {
            self._mousedown(e);
        });
        canvas.mousemove(function(e) {
            self._mousemove(e);
        });
        canvas.mouseup(function(e) {
            self._mouseup(e);
        });
        canvas.dblclick(function(e) {
            self._dblclick(e);
        });
        canvas.mousewheel(function(e, d) {
            self._mousewheel(e, d);
        });
    },
    _mousedown: function(e) {
        this.drag.x = e.clientX;
        this.drag.y = e.clientY;
        this.drag.dx = 0;
        this.drag.dy = 0;
        this.drag.enabled = true;
    },
    _mouseup: function(e) {
        this.drag.enabled = false;
    },
    _mousemove: function(e) {
        if (this.drag.enabled) {
            var x = e.clientX;
            var y = e.clientY;
            this.drag.dx = x - this.drag.x;
            this.drag.dy = y - this.drag.y;
            this.drag.x = x;
            this.drag.y = y;

            this.tx += this.drag.dx;
            this.ty += this.drag.dy;
            this.updateImages();
            this.redraw();
        };
    },
    _dblclick: function(e) {
        var canvas = $(this.canvas);
        var pos = canvas.offset();
        var x = e.pageX - pos.left;
        var y = e.pageY - pos.top;
        this.zoom(x, y, this.clickZoomStep);
    },
    _mousewheel: function(e, d) {
        var pos = $(this.canvas).offset();
        var x = e.pageX - pos.left;
        var y = e.pageY - pos.top;
        if (d > 0) {
            this.zoom(x, y, this.wheelZoomStep);
        }
        else {
            this.zoom(x, y, 1/this.wheelZoomStep);
        }
        return false;
    },

    /* Navigation */

    zoom: function(x, y, scale) {
        if (this.zooming.enabled) { return; }
        this.zooming.enabled = true;

        this.zooming.x = this.tx;
        this.zooming.y = this.ty;
        this.zooming.scale = this.scale;

        this.zooming.tx = Math.floor(x - (x - this.tx) * scale);
        this.zooming.ty = Math.floor(y - (y - this.ty) * scale);
        this.zooming.tscale = this.scale * scale;

        this.zooming.dx = this.zooming.tx - this.zooming.x;
        this.zooming.dy = this.zooming.ty - this.zooming.y;
        this.zooming.dscale = this.zooming.tscale - this.zooming.scale;

        this.zooming.start = new Date();
        var self = this;
        setTimeout(function() { self._zoomStep(); },
                    this.zooming.interval);
    },

    _zoomStep: function() {
        var tnow = new Date();
        var tdelta = tnow - this.zooming.start;
        var now = tdelta / this.zooming.duration;

        this.tx = this.zooming.x + this.zooming.dx * now;
        this.ty = this.zooming.y + this.zooming.dy * now;
        this.scale = this.zooming.scale + this.zooming.dscale * now;

        var a = this.tx;
        if (now >= 1.0) {
            this.tx = this.zooming.tx;
            this.ty = this.zooming.ty;
            this.scale = this.zooming.tscale;
        }
        var b = this.tx;

        if (now < 1.0) {
            this.redraw();
            var self = this;
            setTimeout(function() { self._zoomStep(); },
                       this.zooming.interval);
        }
        else {
            this.zooming.enabled = false;
            this.updateZoomLevel();
            this.updateImages();
            this.redraw();
        }
    },
};

this.Kasuari = Kasuari;

})();
<commit_msg>Always use updateImages()<commit_after>(function() {

var KasuariImage = function(ix, iy, iz, url) {
    this.ix = ix;
    this.iy = iy;
    this.iz = iz;
    this.scale = Math.pow(2, iz);
    this.loaded = false;
    this.url = url;
    this.img = new Image();
    this.onload = undefined;

    this.id = ix + '-' + iy + '-' + iz;

    var self = this;
    this.img.onload = function() {
        self.loaded = true;
        if (self.onload != undefined) {
            self.onload(self);
        }
    };
};

KasuariImage.prototype = {
    init: function() {
        this.img.src = this.url;
    },

    draw: function(ctx, scale) {
        if (!this.loaded) { return; }
        var s = scale * this.scale;
        var dim = 256 * s;
        var x = Math.ceil(this.ix * dim);
        var y = Math.ceil(this.iy * dim);
        var w = Math.ceil(this.img.width * s);
        var h = Math.ceil(this.img.height * s);
        try {
            ctx.drawImage(this.img, x, y, w, h);
        }
        catch (err) {
            // image is removed when this image is about to be rendered
        }
    }
};

var RedrawBucket = function(kasuari) {
    var self = this;
    this.timer = setInterval(function() { self.redraw(); }, 250);
    this.items = [];
    this.kasuari = kasuari;
};

RedrawBucket.prototype = {
    add: function(img) {
        this.items.push(img);
    },

    redraw: function() {
        var items = this.items.slice(0);
        this.items = []; // racing condition possibility

        var level = this.kasuari.zoomLevel;
        var len = items.length;
        for (var i=0; i<len; i++) {
            var img = items[i];
            if (img.iz == level) {
                var key = img.ix+','+img.iy;
                this.kasuari.images[level][key] = img;
            }
        }

        this.kasuari.redraw();
    },
};

var Kasuari = function(canvas, config) {
    this.canvas = canvas.get(0);
    this.cw = canvas.width();
    this.ch = canvas.height();
    this.canvas.width = this.cw;
    this.canvas.height = this.ch;
    this.ctx = this.canvas.getContext('2d');

    this.dir = config.imgdir;
    this.ext = config.ext;
    this.zoomLevel = config.zoom;
    this.oldZoomLevel = this.zoomlevel;
    this.w = config.w;
    this.h = config.h;

    this.scale = Math.pow(0.5, this.zoomLevel);
    this.tx = 0;
    this.ty = 0;

    this.drag = {x: 0, y: 0, dx: 0, dy: 0, enabled: false};
    this.zooming = {x: 0, y: 0, scale: 0,
                    dx: 0, dy: 0, dscale: 0,
                    tx: 0, ty: 0, tscale: 0,
                    duration: 250,
                    interval: 20,
                    start: new Date(),
                    enabled: false};

    this.clickZoomStep = 2.0;
    this.wheelZoomStep = 2.0;

    this.images = [];

    this.redrawBucket = new RedrawBucket(this);
};

Kasuari.prototype = {
    getURL: function(ix, iy, iz) {
        return this.dir + '/img-z' + iz + '.x' + ix + '.y' + iy + this.ext;
    },

    start: function() {
        this.initEventHandlers();
        this.updateImages();
    },

    addImage: function(ix, iy, iz) {
        var url = this.getURL(ix, iy, iz);
        var img = new KasuariImage(ix, iy, iz, url);
        var self = this;
        img.onload = function(img) {
            if (self.images[iz] == undefined) {
                self.images[iz] = {};
            }
            self.redrawBucket.add(img);
            // self.images[iz][ix+','+iy] = img;
            // self.redraw();
        }
        return img;
    },

    redraw: function() {

        this.ctx.clearRect(0, 0, this.cw, this.ch);

        this.ctx.save();
        this.ctx.translate(this.tx, this.ty);

        var len = this.images.length;
        for (var i=len-1; i>=0; i--) {
            var images = this.images[i];
            if ((images != undefined) && (i >= this.zoomLevel)) {
                for (var key in images) {
                    images[key].draw(this.ctx, this.scale);
                }
            }
        }

        this.ctx.restore();
    },

    updateZoomLevel: function() {
        var zoomLevel = Math.floor(Math.log(1/this.scale) / Math.log(2));
        if (zoomLevel < 0) { zoomLevel = 0; }
        this.zoomLevel = zoomLevel;
    },

    getVisibleImages: function(level) {
        var tx = this.tx / this.scale;
        var ty = this.ty / this.scale;
        var cw = this.cw / this.scale;
        var ch = this.ch / this.scale;
        var size = 256 * Math.pow(2, level);

        var x0 = Math.floor(-tx / size) - 1;
        var y0 = Math.floor(-ty / size) - 1;
        var x1 = Math.ceil((-tx + cw) / size) + 1;
        var y1 = Math.ceil((-ty + ch) / size) + 1;

        var items = {};

        var x, y;
        for (x=x0; x<=x1; x++) {
            for (y=y0; y<=y1; y++) {
                if ((x >= 0) && (y >= 0)) {
                    items[x+','+y] = [x, y];
                }
            }
        }

        return items;
    },

    updateVisibleImages: function(level, add) {
        var items = this.getVisibleImages(level);

        if (this.images[level] == undefined) {
            this.images[level] = {};
        }

        // delete unused image
        for (var key in this.images[level]) {
            if (!(key in items)) {
                delete this.images[level][key];
            }
        }

        // add new image
        if ((add == undefined) || add) {
            var images = this.images[level];
            for (var key in items) {
                var data = items[key];
                if (!(data in images)) {
                    this.addImage(data[0], data[1], level).init();
                }
            }
        }
    },

    updateImages: function() {
        var len = this.images.length;
        for (var i=0; i<len; i++) {
            if (i != this.zoomLevel) {
                this.updateVisibleImages(i, false);
            }
        }
        this.updateVisibleImages(this.zoomLevel);
    },

    /* Event handlers */

    initEventHandlers: function() {
        var canvas = $(this.canvas);
        var self = this;
        canvas.mousedown(function(e) {
            self._mousedown(e);
        });
        canvas.mousemove(function(e) {
            self._mousemove(e);
        });
        canvas.mouseup(function(e) {
            self._mouseup(e);
        });
        canvas.dblclick(function(e) {
            self._dblclick(e);
        });
        canvas.mousewheel(function(e, d) {
            self._mousewheel(e, d);
        });
    },
    _mousedown: function(e) {
        this.drag.x = e.clientX;
        this.drag.y = e.clientY;
        this.drag.dx = 0;
        this.drag.dy = 0;
        this.drag.enabled = true;
    },
    _mouseup: function(e) {
        this.drag.enabled = false;
    },
    _mousemove: function(e) {
        if (this.drag.enabled) {
            var x = e.clientX;
            var y = e.clientY;
            this.drag.dx = x - this.drag.x;
            this.drag.dy = y - this.drag.y;
            this.drag.x = x;
            this.drag.y = y;

            this.tx += this.drag.dx;
            this.ty += this.drag.dy;
            // this.updateVisibleImages(this.zoomLevel);
            this.updateImages();
            this.redraw();
        };
    },
    _dblclick: function(e) {
        var canvas = $(this.canvas);
        var pos = canvas.offset();
        var x = e.pageX - pos.left;
        var y = e.pageY - pos.top;
        this.zoom(x, y, this.clickZoomStep);
    },
    _mousewheel: function(e, d) {
        var pos = $(this.canvas).offset();
        var x = e.pageX - pos.left;
        var y = e.pageY - pos.top;
        if (d > 0) {
            this.zoom(x, y, this.wheelZoomStep);
        }
        else {
            this.zoom(x, y, 1/this.wheelZoomStep);
        }
        return false;
    },

    /* Navigation */

    zoom: function(x, y, scale) {
        if (this.zooming.enabled) { return; }
        this.zooming.enabled = true;

        this.zooming.x = this.tx;
        this.zooming.y = this.ty;
        this.zooming.scale = this.scale;

        this.zooming.tx = Math.floor(x - (x - this.tx) * scale);
        this.zooming.ty = Math.floor(y - (y - this.ty) * scale);
        this.zooming.tscale = this.scale * scale;

        this.zooming.dx = this.zooming.tx - this.zooming.x;
        this.zooming.dy = this.zooming.ty - this.zooming.y;
        this.zooming.dscale = this.zooming.tscale - this.zooming.scale;

        this.zooming.start = new Date();
        var self = this;
        setTimeout(function() { self._zoomStep(); },
                    this.zooming.interval);
    },

    _zoomStep: function() {
        var tnow = new Date();
        var tdelta = tnow - this.zooming.start;
        var now = tdelta / this.zooming.duration;

        this.tx = this.zooming.x + this.zooming.dx * now;
        this.ty = this.zooming.y + this.zooming.dy * now;
        this.scale = this.zooming.scale + this.zooming.dscale * now;

        var a = this.tx;
        if (now >= 1.0) {
            this.tx = this.zooming.tx;
            this.ty = this.zooming.ty;
            this.scale = this.zooming.tscale;
        }
        var b = this.tx;

        if (now < 1.0) {
            this.redraw();
            var self = this;
            setTimeout(function() { self._zoomStep(); },
                       this.zooming.interval);
        }
        else {
            this.zooming.enabled = false;
            this.updateZoomLevel();
            this.updateImages();
            this.redraw();
        }
    },
};

this.Kasuari = Kasuari;

})();
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Vehicle Schema
 */
var VehicleSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Vehicle registration name',
		trim: true
	},
  type: {
      type: String,
      default: '',
      required: 'Please fill the Vehicle Type',
      trim: true
  },
  year: {
      type: Number,
      required: 'Please fill in the Vehicle Year',
      trim: true
  },
  make: {
      type: String,
      required: 'Please fill in the Vehicle Make',
      trim: true
  },
  model: {
      type: String,
      required: 'Please fill in the Vehicle Model',
      trim: true
  },
  mods: {
      type: String,
      required: 'Please fill in the Vehicle Mods'
  },
  class: {
      type: String,
      required: 'Please choose a Vehicle Class'
  },
  hasPaid: {
      type: Boolean
  },
  registrationNumber: {
    type: Number,
    unique: true
  },
  preRegistered: {
    type: Boolean
  },
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Vehicle', VehicleSchema);
<commit_msg>vehicle schema<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Vehicle Schema
 */
var VehicleSchema = new Schema({
	name: {
		type: String,
		default: '',
		//required: 'Please fill Vehicle registration name',
		trim: true
	},
  type: {
      type: String,
      default: '',
      //required: 'Please fill the Vehicle Type',
      trim: true
  },
  year: {
      type: Number,
      //required: 'Please fill in the Vehicle Year',
      trim: true
  },
  make: {
      type: String,
      //required: 'Please fill in the Vehicle Make',
      trim: true
  },
  model: {
      type: String,
      //required: 'Please fill in the Vehicle Model',
      trim: true
  },
  mods: {
      type: String,
      //required: 'Please fill in the Vehicle Mods'
  },
  class: {
      type: String,
      //required: 'Please choose a Vehicle Class'
  },
  hasPaid: {
      type: Boolean
  },
  registrationNumber: {
    type: Number,
    //unique: true
  },
  preRegistered: {
    type: Boolean
  },
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Vehicle', VehicleSchema);
<|endoftext|>


<commit_before>//**
(function(){
var
    defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    defineProperties = Cesium.defineProperties,
    loadText = Cesium.loadText,
    throttleRequestByServer = Cesium.throttleRequestByServer,
    Event = Cesium.Event,
    Credit = Cesium.Credit,
    WebMercatorTilingScheme = Cesium.WebMercatorTilingScheme,
    HeightmapTerrainData = Cesium.HeightmapTerrainData,
    TerrainProvider = Cesium.TerrainProvider,
    when = Cesium.when;
/**/
    "use strict";

    var trailingSlashRegex = /\/$/;
    var defaultCredit = new Credit('国土地理院');
    var GSI_MAX_TERRAIN_LEVEL = 15;

    var JapanGSITerrainProvider = function JapanGSITerrainProvider(options) {
        options = defaultValue(options, {});

        var url = defaultValue(options.url, '//cyberjapandata.gsi.go.jp/xyz/dem');

/*
        if (!trailingSlashRegex.test(url)) {
            url = url + '/';
        }
*/

        this._url = url;
        this._proxy = options.proxy;
        this._heightPower = defaultValue(options.heightPower , 1);

        this._tilingScheme = new WebMercatorTilingScheme({numberOfLevelZeroTilesX:2});

        this._heightmapWidth = 32;
        this._demDataWidth   = 256;

        this._terrainDataStructure = {
            heightScale:       1,
            heightOffset:      0,
            elementsPerHeight: 1,
            stride:            1,
            elementMultiplier: 256
        };

        this._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(this._tilingScheme.ellipsoid, this._heightmapWidth, this._tilingScheme.getNumberOfXTilesAtLevel(0));

        this._errorEvent = new Event();

        var credit = defaultValue(options.credit, defaultCredit);
        if (typeof credit === 'string') {
            credit = new Credit(credit);
        }
        this._credit = credit;
    };

    JapanGSITerrainProvider.prototype.requestTileGeometry = function(x, y, level, throttleRequests) {
        var orgx = x;
        var orgy = y;
        var shift = 0;
        if (level > GSI_MAX_TERRAIN_LEVEL) {
            shift = level - GSI_MAX_TERRAIN_LEVEL;
            level = GSI_MAX_TERRAIN_LEVEL;
        }

        x >>= shift+1;
        y >>= shift;
        var shiftx = (orgx % Math.pow(2, shift + 1)) / Math.pow(2, shift + 1);
        var shifty = (orgy % Math.pow(2, shift)) / Math.pow(2, shift);

        var url = this._url + (level == 15 ? '5a' : '') +
          '/' + level + '/' + x + '/' + y + '.txt';

        var proxy = this._proxy;
        if (defined(proxy)) {
            url = proxy.getURL(url);
        }

        var promise;

        throttleRequests = defaultValue(throttleRequests, true);
        if (throttleRequests) {
            promise = throttleRequestByServer(url, loadText);
            if (!defined(promise)) {
                return undefined;
            }
        } else {
            promise = loadText(url);
        }

        var self = this;
        return when(promise, function(data) {
            var heightCSV = [];
            var LF = String.fromCharCode(10);
            var lines = data.split(LF);
            for (var i=0; i<lines.length; i++){
                var heights = lines[i].split(",");
                for (var j=0; j<heights.length; j++){
                    if (heights[j] == "e") heights[j] = 0;
                }
                heightCSV[i] = heights;
            }

            var whm = self._heightmapWidth;
            var wim = self._demDataWidth;
            var hmp = new Int16Array(whm*whm);

            for(var y = 0; y < whm; ++y){
                for(var x = 0; x < whm; ++x){
                    var py = Math.round( ( y / Math.pow(2, shift) / ( whm - 1 ) + shifty ) * ( wim - 1 ) );
                    var px = Math.round( ( x / Math.pow(2, shift + 1) / ( whm - 1 ) + shiftx ) * ( wim - 1 ) );

                    hmp[y*whm + x] = Math.round(heightCSV[py][px] * self._heightPower);
                }
            }

            return new HeightmapTerrainData({
                buffer:        hmp,
                width:         self._heightmapWidth,
                height:        self._heightmapWidth,
                structure:     self._terrainDataStructure,
                childTileMask: GSI_MAX_TERRAIN_LEVEL
            });
        });
    };

    JapanGSITerrainProvider.prototype.getLevelMaximumGeometricError = function(level) {
        return this._levelZeroMaximumGeometricError / (1 << level);
    };
    JapanGSITerrainProvider.prototype.hasWaterMask = function() {
        return !true;
    };
    JapanGSITerrainProvider.prototype.getTileDataAvailable = function(x, y, level) {
        return true;
    };

    defineProperties(JapanGSITerrainProvider.prototype, {
        errorEvent : {
            get : function() {
                return this._errorEvent;
            }
        },

        credit : {
            get : function() {
                return this._credit;
            }
        },

        tilingScheme : {
            get : function() {
                return this._tilingScheme;
            }
        },

        ready : {
            get : function() {
                return true;
            }
        }
    });

    Cesium.JapanGSITerrainProvider = JapanGSITerrainProvider;
})();
<commit_msg>CESIUM >1.35 obsolutes throttleRequestByServer<commit_after>//**
(function(){
var
    defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    defineProperties = Cesium.defineProperties,
    loadText = Cesium.loadText,
    throttleRequestByServer = Cesium.throttleRequestByServer,
    Event = Cesium.Event,
    Credit = Cesium.Credit,
    WebMercatorTilingScheme = Cesium.WebMercatorTilingScheme,
    HeightmapTerrainData = Cesium.HeightmapTerrainData,
    TerrainProvider = Cesium.TerrainProvider,
    when = Cesium.when;
/**/
    "use strict";

    var trailingSlashRegex = /\/$/;
    var defaultCredit = new Credit('国土地理院');
    var GSI_MAX_TERRAIN_LEVEL = 15;

    var JapanGSITerrainProvider = function JapanGSITerrainProvider(options) {
        options = defaultValue(options, {});

        var url = defaultValue(options.url, '//cyberjapandata.gsi.go.jp/xyz/dem');

/*
        if (!trailingSlashRegex.test(url)) {
            url = url + '/';
        }
*/

        this._url = url;
        this._proxy = options.proxy;
        this._heightPower = defaultValue(options.heightPower , 1);

        this._tilingScheme = new WebMercatorTilingScheme({numberOfLevelZeroTilesX:2});

        this._heightmapWidth = 32;
        this._demDataWidth   = 256;

        this._terrainDataStructure = {
            heightScale:       1,
            heightOffset:      0,
            elementsPerHeight: 1,
            stride:            1,
            elementMultiplier: 256
        };

        this._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(this._tilingScheme.ellipsoid, this._heightmapWidth, this._tilingScheme.getNumberOfXTilesAtLevel(0));

        this._errorEvent = new Event();

        var credit = defaultValue(options.credit, defaultCredit);
        if (typeof credit === 'string') {
            credit = new Credit(credit);
        }
        this._credit = credit;
    };

    JapanGSITerrainProvider.prototype.requestTileGeometry = function(x, y, level, throttleRequests) {
        var orgx = x;
        var orgy = y;
        var shift = 0;
        if (level > GSI_MAX_TERRAIN_LEVEL) {
            shift = level - GSI_MAX_TERRAIN_LEVEL;
            level = GSI_MAX_TERRAIN_LEVEL;
        }

        x >>= shift+1;
        y >>= shift;
        var shiftx = (orgx % Math.pow(2, shift + 1)) / Math.pow(2, shift + 1);
        var shifty = (orgy % Math.pow(2, shift)) / Math.pow(2, shift);

        var url = this._url + (level == 15 ? '5a' : '') +
          '/' + level + '/' + x + '/' + y + '.txt';

        var proxy = this._proxy;
        if (defined(proxy)) {
            url = proxy.getURL(url);
        }

        var promise;

        throttleRequests = defaultValue(throttleRequests, true);
        if ( throttleRequestByServer ){ // Patch for > CESIUM1.35
            if (throttleRequests) {
                promise = throttleRequestByServer(url, loadText);
                if (!defined(promise)) {
                    return undefined;
                }
            } else {
                promise = loadText(url);
            }
        } else {
            promise = loadText(url);
        }

        var self = this;
        return when(promise, function(data) {
            var heightCSV = [];
            var LF = String.fromCharCode(10);
            var lines = data.split(LF);
            for (var i=0; i<lines.length; i++){
                var heights = lines[i].split(",");
                for (var j=0; j<heights.length; j++){
                    if (heights[j] == "e") heights[j] = 0;
                }
                heightCSV[i] = heights;
            }

            var whm = self._heightmapWidth;
            var wim = self._demDataWidth;
            var hmp = new Int16Array(whm*whm);

            for(var y = 0; y < whm; ++y){
                for(var x = 0; x < whm; ++x){
                    var py = Math.round( ( y / Math.pow(2, shift) / ( whm - 1 ) + shifty ) * ( wim - 1 ) );
                    var px = Math.round( ( x / Math.pow(2, shift + 1) / ( whm - 1 ) + shiftx ) * ( wim - 1 ) );

                    hmp[y*whm + x] = Math.round(heightCSV[py][px] * self._heightPower);
                }
            }

            return new HeightmapTerrainData({
                buffer:        hmp,
                width:         self._heightmapWidth,
                height:        self._heightmapWidth,
                structure:     self._terrainDataStructure,
                childTileMask: GSI_MAX_TERRAIN_LEVEL
            });
        });
    };

    JapanGSITerrainProvider.prototype.getLevelMaximumGeometricError = function(level) {
        return this._levelZeroMaximumGeometricError / (1 << level);
    };
    JapanGSITerrainProvider.prototype.hasWaterMask = function() {
        return !true;
    };
    JapanGSITerrainProvider.prototype.getTileDataAvailable = function(x, y, level) {
        return true;
    };

    defineProperties(JapanGSITerrainProvider.prototype, {
        errorEvent : {
            get : function() {
                return this._errorEvent;
            }
        },

        credit : {
            get : function() {
                return this._credit;
            }
        },

        tilingScheme : {
            get : function() {
                return this._tilingScheme;
            }
        },

        ready : {
            get : function() {
                return true;
            }
        }
    });

    Cesium.JapanGSITerrainProvider = JapanGSITerrainProvider;
})();
<|endoftext|>


<commit_before>(function ($, rho, rhoUtil) {
    'use strict';

    var moduleNS = 'Rho.Application';
    var apiReq = rhoUtil.apiReqFor(moduleNS);
    var App = {};

    // At this moment we unable to extend target namespace with property proxies defined in a local namespace.
    // So defining (overwriting) them right in the target namespace.
    rhoUtil.createPropsProxy( Rho.Application, [
        { propName: 'defaultNativeMenu', propAccess: 'r', customGet: function(){
            return [
                {'label':'Home', 'action': 'home'},
                {'label':'Refresh', 'action': 'refresh'},
                {'label':'Sync', 'action': 'sync'},
                {'label':'Settings', 'action': 'options'},
                {'label':'Log', 'action': 'log'},
                {'label':'separator', 'action': ''},
                {'label':'Exit', 'action': 'close'}
            ];
        } }
    ], apiReq);

    function processApplicationEvent(event) {
        applicationEvent = event.applicationEvent;
        eventData = event.eventData;

        // UICreated
        if (applicationEvent == Rho.Application.APP_EVENT_UICREATED) {
            console.log("AppEvent: "+ applicationEvent);
            start_url = Rho.Application.startURI;
            if (!start_url){
                start_url = "";
            }
            if (Rho.System.platform != Rho.System.PLATFORM_WP8) {
              invalid_security_token_start_path = Rho.Application.invalidSecurityTokenStartPath;

              if (Rho.Application.securityTokenNotPassed) {
                if (invalid_security_token_start_path && invalid_security_token_start_path.length() > 0) {
                  start_url = invalid_security_token_start_path;
                } else {
                  // exit from application - old way
                  Rho.Log.fatalError('processApplicationEvent: security_token is not passed - application will closed','EROOR');
                  Rho.System.exit();
                }
              }
            }
            console.log("on_ui_created.navigate to start url: "+ start_url);
            Rho.WebView.navigate(start_url);
        }
        // UIDestroyed
        else if (applicationEvent==Rho.Application.APP_EVENT_UIDESTROYED) {
            console.log("AppEvent: "+ applicationEvent);
        }
        else if (applicationEvent==Rho.Application.APP_EVENT_CONFIGCONFLICT) {
            console.log("AppEvent: "+ applicationEvent);
        }
        //
        else if (applicationEvent==Rho.Application.APP_EVENT_DBMIGRATESOURCE) {
            console.log("AppEvent: "+ applicationEvent);
            console.log( "default on_migrate_source - do nothing; old_version :"+eventData.old_version+"; new_src : "+eventData.new_src);
            //if new_src['schema']
            //    db = ::Rho::RHO.get_src_db(new_src['name'])
            //    db.delete_table(new_src['name'])
            //    return false  #create new table
            //end
            return true
        }
        //
        else if (applicationEvent==Rho.Application.APP_EVENT_SYNCUSERCHANGED) {
            Rho.ORM.databaseFullReset(false, false)
            //::Rho::RHO.get_user_db().execute_sql("UPDATE client_info SET client_id=?", "")
        }
    }

    var App = {
        processApplicationEvent : function(event) {
            processApplicationEvent(event);
        }
    };

    rhoUtil.namespace(moduleNS, App, true);

    function setAppEventsHandler()
    {
        Rho.Application.setApplicationNotify(processApplicationEvent);
    }

    $(document).ready( setAppEventsHandler );

})(Rho.jQuery, Rho, Rho.util);
<commit_msg>rhodes js: do not use event handler<commit_after>(function ($, rho, rhoUtil) {
    'use strict';

    var moduleNS = 'Rho.Application';
    var apiReq = rhoUtil.apiReqFor(moduleNS);
    var App = {};

    // At this moment we unable to extend target namespace with property proxies defined in a local namespace.
    // So defining (overwriting) them right in the target namespace.
    rhoUtil.createPropsProxy( Rho.Application, [
        { propName: 'defaultNativeMenu', propAccess: 'r', customGet: function(){
            return [
                {'label':'Home', 'action': 'home'},
                {'label':'Refresh', 'action': 'refresh'},
                {'label':'Sync', 'action': 'sync'},
                {'label':'Settings', 'action': 'options'},
                {'label':'Log', 'action': 'log'},
                {'label':'separator', 'action': ''},
                {'label':'Exit', 'action': 'close'}
            ];
        } }
    ], apiReq);

    function processApplicationEvent(event) {
        applicationEvent = event.applicationEvent;
        eventData = event.eventData;

        // UICreated
        if (applicationEvent == Rho.Application.APP_EVENT_UICREATED) {
            console.log("AppEvent: "+ applicationEvent);
            start_url = Rho.Application.startURI;
            if (!start_url){
                start_url = "";
            }
            if (Rho.System.platform != Rho.System.PLATFORM_WP8) {
              invalid_security_token_start_path = Rho.Application.invalidSecurityTokenStartPath;

              if (Rho.Application.securityTokenNotPassed) {
                if (invalid_security_token_start_path && invalid_security_token_start_path.length() > 0) {
                  start_url = invalid_security_token_start_path;
                } else {
                  // exit from application - old way
                  Rho.Log.fatalError('processApplicationEvent: security_token is not passed - application will closed','EROOR');
                  Rho.System.exit();
                }
              }
            }
            console.log("on_ui_created.navigate to start url: "+ start_url);
            Rho.WebView.navigate(start_url);
        }
        // UIDestroyed
        else if (applicationEvent==Rho.Application.APP_EVENT_UIDESTROYED) {
            console.log("AppEvent: "+ applicationEvent);
        }
        else if (applicationEvent==Rho.Application.APP_EVENT_CONFIGCONFLICT) {
            console.log("AppEvent: "+ applicationEvent);
        }
        //
        else if (applicationEvent==Rho.Application.APP_EVENT_DBMIGRATESOURCE) {
            console.log("AppEvent: "+ applicationEvent);
            console.log( "default on_migrate_source - do nothing; old_version :"+eventData.old_version+"; new_src : "+eventData.new_src);
            //if new_src['schema']
            //    db = ::Rho::RHO.get_src_db(new_src['name'])
            //    db.delete_table(new_src['name'])
            //    return false  #create new table
            //end
            return true
        }
        //
        else if (applicationEvent==Rho.Application.APP_EVENT_SYNCUSERCHANGED) {
            Rho.ORM.databaseFullReset(false, false)
            //::Rho::RHO.get_user_db().execute_sql("UPDATE client_info SET client_id=?", "")
        }
    }

    var App = {
        processApplicationEvent : function(event) {
            processApplicationEvent(event);
        }
    };

    rhoUtil.namespace(moduleNS, App, true);

    // function setAppEventsHandler()
    // {
    //     Rho.Application.setApplicationNotify(processApplicationEvent);
    // }

    // $(document).ready( setAppEventsHandler );

})(Rho.jQuery, Rho, Rho.util);
<|endoftext|>


<commit_before>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/api';
import $ from 'jquery';

$.fn.extend({
  taxonMoveUp() {
    const element = this;

    element.api({
      method: 'PUT',
      on: 'click',
      beforeSend(settings) {
        /* eslint-disable-next-line no-param-reassign */
        settings.data = {
          position: element.data('position') - 1,
        };

        return settings;
      },
      onSuccess() {
        window.location.reload();
      },
    });
  },

  taxonMoveDown() {
    const element = this;

    element.api({
      method: 'PUT',
      on: 'click',
      beforeSend(settings) {
        /* eslint-disable-next-line no-param-reassign */
        settings.data = {
          position: element.data('position') + 1,
        };

        return settings;
      },
      onSuccess() {
        window.location.reload();
      },
    });
  },
});
<commit_msg>bug #10054 [Admin] Taxon order : fix element(data) always returns 0 (pierre-H, pamil)<commit_after>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/api';
import $ from 'jquery';

$.fn.extend({
  taxonMoveUp() {
    const element = this;

    element.api({
      method: 'PUT',
      on: 'click',
      beforeSend(settings) {
        /* eslint-disable-next-line no-param-reassign */
        settings.data = {
          position: $(this).data('position') - 1,
        };

        return settings;
      },
      onSuccess() {
        window.location.reload();
      },
    });
  },

  taxonMoveDown() {
    const element = this;

    element.api({
      method: 'PUT',
      on: 'click',
      beforeSend(settings) {
        /* eslint-disable-next-line no-param-reassign */
        settings.data = {
          position: $(this).data('position') + 1,
        };

        return settings;
      },
      onSuccess() {
        window.location.reload();
      },
    });
  },
});
<|endoftext|>