text:
var Domain = require('domain');
var Path = require('path');
var Lab = require('lab');
var Hapi = require('..');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var before = lab.before;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Lab.expect;

describe('Pack', function () {

    var routesList = function (server) {

        var routes = server._router.routes['get'];
        var list = [];
        for (var i = 0, il = routes.length; i < il; ++i) {
            var route = routes[i];
            list.push(route.path);
        }

        return list;
    };

    it('registers plugins', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['s1', 'a', 'b'] });
        pack.server({ labels: ['s2', 'a', 'c'] });
        pack.server({ labels: ['s3', 'a', 'b', 'd'] });
        pack.server({ labels: ['s4', 'b', 'x'] });

        var server2 = pack._servers[2];

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                var a = plugin.select('a');
                var ab = a.select('b');
                var memoryx = plugin.select('x', 's4');
                var sodd = plugin.select(['s2', 's4']);

                expect(plugin.length).to.equal(4);
                expect(a.length).to.equal(3);
                expect(ab.length).to.equal(2);
                expect(memoryx.length).to.equal(1);
                expect(sodd.length).to.equal(2);

                plugin.route({ method: 'GET', path: '/all', handler: function (request, reply) { reply('all'); } });
                a.route({ method: 'GET', path: '/a', handler: function (request, reply) { reply('a'); } });
                ab.route([{ method: 'GET', path: '/ab', handler: function (request, reply) { reply('ab'); } }]);
                memoryx.route({ method: 'GET', path: '/memoryx', handler: function (request, reply) { reply('memoryx'); } });
                sodd.route({ method: 'GET', path: '/sodd', handler: function (request, reply) { reply('sodd'); } });

                memoryx.state('sid', { encoding: 'base64' });
                plugin.method({
                    name: 'testMethod', fn: function (next) {

                        return next(null, '123');
                    }, options: { cache: { expiresIn: 1000 } }
                });

                server2.methods.testMethod(function (err, result) {

                    expect(result).to.equal('123');

                    plugin.methods.testMethod(function (err, result) {

                        expect(result).to.equal('123');
                        return next();
                    });
                });
            }
        };

        pack.register(plugin, function (err) {

            expect(err).to.not.exist;

            expect(routesList(pack._servers[0])).to.deep.equal(['/a', '/ab', '/all']);
            expect(routesList(pack._servers[1])).to.deep.equal(['/a', '/all', '/sodd']);
            expect(routesList(pack._servers[2])).to.deep.equal(['/a', '/ab', '/all']);
            expect(routesList(pack._servers[3])).to.deep.equal(['/all', '/sodd', '/memoryx']);
            done();
        });
    });

    it('registers plugin with options', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['a', 'b'] });

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                expect(options.something).to.be.true;
                return next();
            },
            options: { something: true }
        };

        pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('throws when register is missing a callback function', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['a', 'b'] });

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                return next();
            },
            options: { something: true }
        };

        expect(function () {

            pack.register(plugin);
        }).to.throw('A callback function is required to register a plugin');
        done();
    });

    it('registers plugin via server pack interface', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                expect(options.something).to.be.true;
                return next();
            },
            options: { something: true }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('returns plugin error', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                return next(new Error('from plugin'));
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.exist;
            expect(err.message).to.equal('from plugin');
            done();
        });
    });

    it('throws when plugin missing register', function (done) {

        var plugin = {
            name: 'test'
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('One of plugin or register required but cannot include both');
        done();
    });

    it('throws when register is not a function', function (done) {

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register({ register: 'x' }, function (err) { });
        }).to.throw('Plugin register must be a function or a required plugin module');
        done();
    });

    it('throws when pack server contains cache configuration', function (done) {

        expect(function () {

            var pack = new Hapi.Pack();
            pack.server({ cache: require('catbox-memory'), labels: ['a', 'b', 'c'] });
        }).to.throw('Cannot configure server cache in a pack member');
        done();
    });

    it('throws when plugin contains non object plugin property', function (done) {

        var plugin = {
            name: 'test',
            plugin: 5
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('Plugin register must be a function or a required plugin module');
        done();
    });

    it('throws when plugin contains an object plugin property with invalid register', function (done) {

        var plugin = {
            name: 'test',
            plugin: {
                register: 5
            }
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('Plugin register must be a function or a required plugin module');
        done();
    });

    it('throws when plugin contains a pkg attribute without a name', function (done) {

        var plugin = {
            register: function () { }
        };

        plugin.register.attributes = {
            pkg: {

            }
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('Missing plugin name');
        done();
    });

    it('sets version to 0.0.0 if missing', function (done) {

        var plugin = {
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/', handler: function (request, reply) { reply(plugin.version); } });
                return next();
            }
        };

        plugin.register.attributes = {
            pkg: {
                name: '--steve'
            }
        };

        var server = new Hapi.Server();

        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(server._registrations['--steve'].version).to.equal('0.0.0');
            server.inject('/', function (res) {

                expect(res.result).to.equal(Hapi.version);
                done();
            });
        });
    });

    it('throws when plugin sets undefined path', function (done) {

        var plugin = {
            name: '--steve',
            register: function (plugin, options, next) {

                plugin.path();
                return next();
            }
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('path must be a non-empty string');
        done();
    });

    it('registers plugin with exposed api', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['s1', 'a', 'b'] });
        pack.server({ labels: ['s2', 'a', 'test'] });
        pack.server({ labels: ['s3', 'a', 'b', 'd', 'cache'] });
        pack.server({ labels: ['s4', 'b', 'test', 'cache'] });

        pack.register(require('./pack/--test1'), function (err) {

            expect(err).to.not.exist;

            expect(pack._servers[0]._router.routes['get']).to.not.exist;
            expect(routesList(pack._servers[1])).to.deep.equal(['/test1']);
            expect(pack._servers[2]._router.routes['get']).to.not.exist;
            expect(routesList(pack._servers[3])).to.deep.equal(['/test1']);

            expect(pack._servers[0].plugins['--test1'].add(1, 3)).to.equal(4);
            expect(pack._servers[0].plugins['--test1'].glue('1', '3')).to.equal('13');

            done();
        });
    });

    it('prevents plugin from multiple registrations', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/a', handler: function (request, reply) { reply('a'); } });
                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(function () {

                server.pack.register(plugin, function (err) { });
            }).to.throw('Plugin test already registered in: ' + server.info.uri);

            done();
        });
    });

    it('allows plugin multiple registrations (attributes)', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.app.x = plugin.app.x ? plugin.app.x + 1 : 1;
                return next();
            }
        };

        plugin.register.attributes = { multiple: true };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                expect(server.pack.app.x).to.equal(2);
                done();
            });
        });
    });

    it('allows plugin multiple registrations (property)', function (done) {

        var plugin = {
            name: 'test',
            multiple: true,
            register: function (plugin, options, next) {

                plugin.app.x = plugin.app.x ? plugin.app.x + 1 : 1;
                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                expect(server.pack.app.x).to.equal(2);
                done();
            });
        });
    });

    it('registers multiple plugins', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        var log = null;
        server.pack.events.once('log', function (event, tags) {

            log = [event, tags];
        });

        server.pack.register([require('./pack/--test1'), require('./pack/--test2')], function (err) {

            expect(err).to.not.exist;
            expect(routesList(server)).to.deep.equal(['/test1', '/test2']);
            expect(log[1].test).to.equal(true);
            expect(log[0].data).to.equal('abc');
            done();
        });
    });

    it('registers multiple plugins (verbose)', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        var log = null;
        server.pack.events.once('log', function (event, tags) {

            log = [event, tags];
        });

        server.pack.register([{ plugin: require('./pack/--test1') }, { plugin: require('./pack/--test2') }], function (err) {

            expect(err).to.not.exist;
            expect(routesList(server)).to.deep.equal(['/test1', '/test2']);
            expect(log[1].test).to.equal(true);
            expect(log[0].data).to.equal('abc');
            done();
        });
    });

    it('requires plugin with views', function (done) {

        var server = new Hapi.Server();
        server.pack.register({ plugin: require('./pack/--views'), options: { message: 'viewing it' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/view', function (res) {

                expect(res.result).to.equal('
viewing it
');

                server.inject('/file', function (res) {

                    expect(res.result).to.equal('
{{message}}
');

                    server.inject('/ext', function (res) {

                        expect(res.result).to.equal('
grabbed
');
                        done();
                    });
                });
            });
        });
    });

    it('requires plugin with views with specific basePath', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.views({
                    engines: { 'html': require('handlebars') },
                    basePath: __dirname + '/pack/--views',
                    path: './templates'
                });

                plugin.route([
                    {
                        path: '/view', method: 'GET', handler: function (request, reply) {

                            return reply.view('test', { message: 'steve' });
                        }
                    }
                ]);

                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server.inject('/view', function (res) {

                expect(res.result).to.equal('
steve
');
                done();
            });
        });
    });

    it('registers a child plugin', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(require('./pack/--child'), function (err) {

            expect(err).to.not.exist;
            server.inject('/test1', function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a plugin with route path prefix', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(require('./pack/--test1'), { route: { prefix: '/xyz' } }, function (err) {

            expect(server.plugins['--test1'].prefix).to.equal('/xyz');
            expect(err).to.not.exist;
            server.inject('/xyz/test1', function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a plugin with route path prefix and plugin root route', function (done) {

        var a = {
            name: 'a',
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('ok'); } });
                return next();
            }
        };

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(a, { route: { prefix: '/xyz' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/xyz', function (res) {

                expect(res.result).to.equal('ok');
                done();
            });
        });
    });

    it('ignores the type of the plugin value', function (done) {

        var a = function () { };
        a.register = function (plugin, options, next) {

            plugin.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('ok'); } });
            return next();
        };

        a.register.attributes = { name: 'a' };

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register({ plugin: a }, { route: { prefix: '/xyz' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/xyz', function (res) {

                expect(res.result).to.equal('ok');
                done();
            });
        });
    });

    it('registers a child plugin with parent route path prefix', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(require('./pack/--child'), { route: { prefix: '/xyz' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/xyz/test1', function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a child plugin with parent route vhost prefix', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(require('./pack/--child'), { route: { vhost: 'example.com' } }, function (err) {

            expect(err).to.not.exist;
            server.inject({ url: '/test1', headers: { host: 'example.com' } }, function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a child plugin with parent route path prefix and inner register prefix', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register({ plugin: require('./pack/--child'), options: { route: { prefix: '/inner' } } }, { route: { prefix: '/xyz' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/xyz/inner/test1', function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a child plugin with parent route vhost prefix and inner register vhost', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register({ plugin: require('./pack/--child'), options: { route: { vhost: 'example.net' } } }, { route: { vhost: 'example.com' } }, function (err) {

            expect(err).to.not.exist;
            server.inject({ url: '/test1', headers: { host: 'example.com' } }, function (res) {

                expect(res.result).to.equal('testing123');
                done();
            });
        });
    });

    it('registers a plugin with route vhost', function (done) {

        var server = new Hapi.Server({ labels: 'test' });
        server.pack.register(require('./pack/--test1'), { route: { vhost: 'example.com' } }, function (err) {

            expect(err).to.not.exist;
            server.inject('/test1', function (res) {

                expect(res.statusCode).to.equal(404);

                server.inject({ url: '/test1', headers: { host: 'example.com' } }, function (res) {

                    expect(res.result).to.equal('testing123');
                    done();
                });
            });
        });
    });

    it('registers a plugin on selection inside a plugin', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['a'] });
        pack.server({ labels: ['b'] });
        pack.server({ labels: ['c'] });

        var server1 = pack._servers[0];
        var server2 = pack._servers[1];
        var server3 = pack._servers[2];

        var child = {
            name: 'child',
            register: function (plugin, options, next) {

                plugin.expose('key2', 2);
                return next();
            }
        };

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.expose('key1', 1);
                plugin.select('a').register(child, next);
            }
        };

        pack.register(plugin, { select: ['a', 'b'] }, function (err) {

            expect(err).to.not.exist;
            expect(server1.plugins.test.key1).to.equal(1);
            expect(server1.plugins.child.key2).to.equal(2);
            expect(server2.plugins.test.key1).to.equal(1);
            expect(server2.plugins.child).to.not.exist;
            expect(server3.plugins.test).to.not.exist;
            expect(server3.plugins.child).to.not.exist;
            done();
        });
    });

    it('starts and stops', function (done) {

        var pack = new Hapi.Pack();
        pack.server(0, { labels: ['s1', 'a', 'b'] });
        pack.server(0, { labels: ['s2', 'a', 'test'] });
        pack.server(0, { labels: ['s3', 'a', 'b', 'd', 'cache'] });
        pack.server(0, { labels: ['s4', 'b', 'test', 'cache'] });

        var started = 0;
        var stopped = 0;

        pack.events.on('start', function () { ++started; });
        pack.events.on('stop', function () { ++stopped; });

        pack.start(function () {

            pack._servers.forEach(function (server) {

                expect(server._started).to.equal(true);
            });

            pack.stop(function () {

                pack._servers.forEach(function (server) {

                    expect(server._started).to.equal(false);
                });

                expect(started).to.equal(1);
                expect(stopped).to.equal(1);
                done();
            });
        });
    });

    it('fails to register a bad plugin', function (done) {

        var pack = new Hapi.Pack();
        expect(function () {

            pack.register({ register: function (plugin, options, next) { return next(); } }, function (err) { });
        }).to.throw('Missing plugin name');

        done();
    });

    it('extends onRequest point', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/b', handler: function (request, reply) { reply('b'); } });
                plugin.ext('onRequest', function (request, cont) {

                    request.setUrl('/b');
                    cont();
                });

                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(routesList(server)).to.deep.equal(['/b']);

            server.inject('/a', function (res) {

                expect(res.result).to.equal('b');
                done();
            });
        });
    });

    it('adds multiple ext functions with dependencies', function (done) {

        var pack = new Hapi.Pack();
        pack.server(0, { labels: ['a', 'b'] });
        pack.server(0, { labels: ['a', 'c'] });
        pack.server(0, { labels: ['c', 'b'] });

        var handler = function (request, reply) {

            return reply(request.app.deps);
        };

        pack._servers[0].route({ method: 'GET', path: '/', handler: handler });
        pack._servers[1].route({ method: 'GET', path: '/', handler: handler });
        pack._servers[2].route({ method: 'GET', path: '/', handler: handler });

        pack.register([require('./pack/--deps1'), require('./pack/--deps2'), require('./pack/--deps3')], function (err) {

            expect(err).to.not.exist;

            pack.start(function (err) {

                expect(err).to.not.exist;
                expect(pack.plugins['--deps1'].breaking).to.equal('bad');

                pack._servers[0].inject('/', function (res) {

                    expect(res.result).to.equal('|2|1|');

                    pack._servers[1].inject('/', function (res) {

                        expect(res.result).to.equal('|3|1|');

                        pack._servers[2].inject('/', function (res) {

                            expect(res.result).to.equal('|3|2|');
                            done();
                        });
                    });
                });
            });
        });
    });

    it('fails to require single plugin with dependencies', function (done) {

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(require('./pack/--deps1'), function (err) { });
        }).to.throw('Plugin --deps1 missing dependency --deps2 in server: ' + server.info.uri);
        done();
    });

    it('fails to register single plugin with dependencies', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.dependency('none');
                return next();
            }
        };

        var server = new Hapi.Server();
        expect(function () {

            server.pack.register(plugin, function (err) { });
        }).to.throw('Plugin test missing dependency none in server: ' + server.info.uri);
        done();
    });

    it('fails to require multiple plugins with dependencies', function (done) {

        var server = new Hapi.Server();

        var domain = Domain.create();
        domain.on('error', function (err) {

            expect(err.message).to.equal('Plugin --deps1 missing dependency --deps2 in server: ' + server.info.uri);
            done();
        });

        domain.run(function () {

            server.pack.register([require('./pack/--deps1'), require('./pack/--deps3')], function (err) { });
        });
    });

    it('recognizes dependencies from peer plugins', function (done) {

        var a = {
            name: 'a',
            register: function (plugin, options, next) {

                plugin.register(b, next);
            }
        };

        var b = {
            name: 'b',
            register: function (plugin, options, next) {

                return next();
            }
        };

        var c = {
            name: 'c',
            register: function (plugin, options, next) {

                plugin.dependency('b');
                return next();
            }
        };

        var server = new Hapi.Server(0);
        server.pack.register([a, c], function (err) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('errors when missing inner dependencies', function (done) {

        var a = {
            name: 'a',
            register: function (plugin, options, next) {

                plugin.register(b, next);
            }
        };

        var b = {
            name: 'b',
            register: function (plugin, options, next) {

                plugin.dependency('c');
                return next();
            }
        };

        var domain = Domain.create();
        domain.on('error', function (err) {

            expect(err.message).to.equal('Plugin b missing dependency c in server: ' + server.info.uri);
            done();
        });

        var server = new Hapi.Server();

        domain.run(function () {

            server.pack.register(a, function (err) { });
        });
    });

    it('fails to start server when after method fails', function (done) {

        var server = new Hapi.Server();
        server.pack.register(require('./pack/--afterErr'), function (err) {

            expect(err).to.not.exist;
            server.start(function (err) {

                expect(err).to.exist;
                done();
            });
        });
    });

    it('uses plugin cache interface', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                var cache = plugin.cache({ expiresIn: 10 });
                plugin.expose({
                    get: function (key, callback) {
                        cache.get(key, function (err, value) {

                            callback(err, value && value.item);
                        });
                    },
                    set: function (key, value, callback) {
                        cache.set(key, value, 0, callback);
                    }
                });

                return next();
            }
        };

        var server = new Hapi.Server(0);
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server.start(function () {

                server.plugins.test.set('a', '1', function (err) {

                    expect(err).to.not.exist;
                    server.plugins.test.get('a', function (err, value) {

                        expect(err).to.not.exist;
                        expect(value).to.equal('1');
                        setTimeout(function () {

                            server.plugins.test.get('a', function (err, value) {

                                expect(err).to.not.exist;
                                expect(value).to.equal(null);
                                done();
                            });
                        }, 11);
                    });
                });
            });
        });
    });

    it('adds auth strategy via plugin', function (done) {

        var server = new Hapi.Server();
        server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('authenticated!'); } });

        server.pack.register(require('./pack/--auth'), function (err) {

            expect(err).to.not.exist;

            server.inject('/', function (res) {

                expect(res.statusCode).to.equal(401);
                server.inject({ method: 'GET', url: '/', headers: { authorization: 'Basic ' + (new Buffer('john:12345', 'utf8')).toString('base64') } }, function (res) {

                    expect(res.statusCode).to.equal(200);
                    expect(res.result).to.equal('authenticated!');
                    done();
                });
            });
        });
    });

    it('adds auth strategy via plugin to multiple servers', function (done) {

        var pack = new Hapi.Pack();
        pack.server(0, { labels: 'a' });
        pack.server(0, { labels: 'b' });

        pack.register(require('./pack/--auth'), function (err) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('sets plugin context', function (done) {

        var server = new Hapi.Server();
        server.pack.register(require('./pack/--context'), function (err) {

            expect(err).to.not.exist;
            server.inject('/', function (res) {

                expect(res.result).to.equal('in context throughout');
                done();
            });
        });
    });

    it('plugin event handlers receive more than 2 arguments when they exist', function (done) {

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.events.once('request', function (request, event, tags) {

                    expect(tags).to.exist;
                    done();
                });

                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server.inject({ url: '/' }, function () { });
        });
    });

    it('returns a reference to the new server when adding one to the pack', function (done) {

        var pack = new Hapi.Pack();
        var server = pack.server();

        expect(server).to.exist;
        server.inject({ url: '/' }, function (res) {

            expect(res.statusCode).to.equal(404);
            done();
        });
    });

    it('sets directory route handler', function (done) {

        var server = new Hapi.Server({ files: { relativeTo: __dirname } });
        server.pack.register(require('./pack/--handler'), function (err) {

            expect(err).to.not.exist;
            server.inject('/handler/package.json', function (res) {

                expect(res.statusCode).to.equal(200);
                expect(JSON.parse(res.result).name).to.equal('--handler');
                done();
            });
        });
    });

    it('errors on bad cache start', function (done) {

        var cache = {
            engine: {
                start: function (callback) {

                    return callback(new Error('oops'));
                }
            }
        };

        var server = new Hapi.Server(0, { cache: cache });
        server.start(function (err) {

            expect(err.message).to.equal('oops');
            done();
        });
    });

    describe('#log', { parallel: false }, function () {

        it('outputs log data to debug console', function (done) {

            var server = new Hapi.Server();

            var orig = console.error;
            console.error = function () {

                console.error = orig;
                expect(arguments[0]).to.equal('Debug:');
                expect(arguments[1]).to.equal('implementation');
                expect(arguments[2]).to.equal('\n    {"data":1}');
                done();
            };

            server.pack.log(['implementation'], { data: 1 });
        });

        it('outputs log error data to debug console', function (done) {

            var server = new Hapi.Server();

            var orig = console.error;
            console.error = function () {

                console.error = orig;
                expect(arguments[0]).to.equal('Debug:');
                expect(arguments[1]).to.equal('implementation');
                expect(arguments[2]).to.contain('\n    Error: test\n    at');
                done();
            };

            server.pack.log(['implementation'], new Error('test'));
        });

        it('outputs log data to debug console without data', function (done) {

            var server = new Hapi.Server();

            var orig = console.error;
            console.error = function () {

                console.error = orig;
                expect(arguments[0]).to.equal('Debug:');
                expect(arguments[1]).to.equal('implementation');
                expect(arguments[2]).to.equal('');
                done();
            };

            server.pack.log(['implementation']);
        });

        it('does not output events when debug disabled', function (done) {

            var server = new Hapi.Server({ debug: false });

            var i = 0;
            var orig = console.error;
            console.error = function () {

                ++i;
            };

            server.pack.log(['implementation']);
            console.error('nothing');
            expect(i).to.equal(1);
            console.error = orig;
            done();
        });

        it('does not output events when debug.request disabled', function (done) {

            var server = new Hapi.Server({ debug: { request: false } });

            var i = 0;
            var orig = console.error;
            console.error = function () {

                ++i;
            };

            server.pack.log(['implementation']);
            console.error('nothing');
            expect(i).to.equal(1);
            console.error = orig;
            done();
        });

        it('does not output non-implementation events by default', function (done) {

            var server = new Hapi.Server();

            var i = 0;
            var orig = console.error;
            console.error = function () {

                ++i;
            };

            server.pack.log(['xyz']);
            console.error('nothing');
            expect(i).to.equal(1);
            console.error = orig;
            done();
        });

        it('emits server log events once', function (done) {

            var pc = 0;

            var plugin = {
                name: 'test',
                register: function (plugin, options, next) {

                    plugin.events.on('log', function (event, tags) {

                        ++pc;
                    });

                    next();
                }
            };

            var server = new Hapi.Server();

            var sc = 0;
            server.on('log', function (event, tags) {

                ++sc;
            });

            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                server.log('test');
                expect(sc).to.equal(1);
                expect(pc).to.equal(1);
                done();
            });
        })
    });

    it('adds server method using arguments', function (done) {

        var pack = new Hapi.Pack();
        pack.server();

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.method('log', function () { });
                return next();
            }
        };

        pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('adds server method with plugin bind', function (done) {

        var server = new Hapi.Server();

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.bind({ x: 1 });
                plugin.method('log', function () { return this.x; });
                return next();
            }
        };

        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(server.methods.log()).to.equal(1);
            done();
        });
    });

    it('adds server method with method bind', function (done) {

        var server = new Hapi.Server();

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.method('log', function () { return this.x; }, { bind: { x: 2 } });
                return next();
            }
        };

        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(server.methods.log()).to.equal(2);
            done();
        });
    });

    it('adds server method with method and ext bind', function (done) {

        var server = new Hapi.Server();

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.bind({ x: 1 });
                plugin.method('log', function () { return this.x; }, { bind: { x: 2 } });
                return next();
            }
        };

        server.pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            expect(server.methods.log()).to.equal(2);
            done();
        });
    });

    it('sets multiple dependencies in one statement', function (done) {

        var a = {
            name: 'a',
            register: function (plugin, options, next) {

                plugin.dependency(['b', 'c']);
                return next();
            }
        };

        var b = {
            name: 'b',
            register: function (plugin, options, next) {

                return next();
            }
        };

        var c = {
            name: 'c',
            register: function (plugin, options, next) {

                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(b, function (err) {

            server.pack.register(c, function (err) {

                server.pack.register(a, function (err) {

                    done();
                });
            });
        });
    });

    it('sets multiple dependencies in multiple statements', function (done) {

        var a = {
            name: 'a',
            register: function (plugin, options, next) {

                plugin.dependency('b');
                plugin.dependency('c');
                return next();
            }
        };

        var b = {
            name: 'b',
            register: function (plugin, options, next) {

                return next();
            }
        };

        var c = {
            name: 'c',
            register: function (plugin, options, next) {

                return next();
            }
        };

        var server = new Hapi.Server();
        server.pack.register(b, function (err) {

            server.pack.register(c, function (err) {

                server.pack.register(a, function (err) {

                    done();
                });
            });
        });
    });

    it('starts a pack without callback', function (done) {

        var pack = new Hapi.Pack();
        pack.server(0);
        pack.register(require('./pack/--afterErr'), function (err) {

            pack.start();
            setTimeout(function () {

                pack.stop();
                done();
            }, 10);
        });
    });

    it('registers plugins with pre-selected label', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['a'] });
        pack.server({ labels: ['b'] });

        var server1 = pack._servers[0];
        var server2 = pack._servers[1];

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('ok'); } });
                return next();
            }
        };

        pack.register(plugin, { select: 'a' }, function (err) {

            expect(err).to.not.exist;
            server1.inject('/', function (res) {

                expect(res.statusCode).to.equal(200);
                server2.inject('/', function (res) {

                    expect(res.statusCode).to.equal(404);
                    done();
                });
            });
        });
    });

    it('registers plugins with pre-selected labels', function (done) {

        var pack = new Hapi.Pack();
        pack.server({ labels: ['a'] });
        pack.server({ labels: ['b'] });
        pack.server({ labels: ['c'] });

        var server1 = pack._servers[0];
        var server2 = pack._servers[1];
        var server3 = pack._servers[2];

        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('ok'); } });
                plugin.expose('super', 'trooper');
                return next();
            }
        };

        pack.register(plugin, { select: ['a', 'c'] }, function (err) {

            expect(err).to.not.exist;
            expect(pack.plugins.test).to.not.exist;
            expect(server1.plugins.test.super).to.equal('trooper');
            expect(server2.plugins.test).to.not.exist;
            expect(server3.plugins.test.super).to.equal('trooper');

            server1.inject('/', function (res) {

                expect(res.statusCode).to.equal(200);
                server2.inject('/', function (res) {

                    expect(res.statusCode).to.equal(404);
                    server3.inject('/', function (res) {

                        expect(res.statusCode).to.equal(200);
                        done();
                    });
                });
            });
        });
    });

    it('listens to events on selected servers', function (done) {

        var pack = new Hapi.Pack();
        pack.server(0, { labels: ['a'] });
        pack.server(0, { labels: ['b'] });
        pack.server(0, { labels: ['c'] });

        var server1 = pack._servers[0];
        var server2 = pack._servers[1];
        var server3 = pack._servers[2];

        var counter = 0;
        var plugin = {
            name: 'test',
            register: function (plugin, options, next) {

                plugin.select(['a', 'b']).events.on('test', function () {

                    ++counter;
                });

                plugin.select(['a']).events.on('start', function () {

                    ++counter;
                });

                return next();
            }
        };

        pack.register(plugin, function (err) {

            expect(err).to.not.exist;
            server1.emit('test');
            server2.emit('test');
            server3.emit('test');

            pack.start(function () {

                pack.stop(function () {

                    expect(counter).to.equal(3);
                    done();
                });
            });
        });
    });

    describe('#_provisionCache ', function () {

        it('throws when missing options', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache();
            }).to.throw('Invalid cache policy options');
            done();
        });

        it('throws when creating method cache with invalid segment', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'method', 'steve', 'bad');
            }).to.throw('Server method cache segment must start with \'##\'');
            done();
        });

        it('throws when creating plugin cache with invalid segment', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'plugin', 'steve', 'bad');
            }).to.throw('Plugin cache segment must start with \'!!\'');
            done();
        });

        it('uses custom method cache segment', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'method', 'steve', '##method');
            }).to.not.throw();
            done();
        });

        it('uses custom plugin cache segment', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'plugin', 'steve', '!!plugin');
            }).to.not.throw();
            done();
        });

        it('throws when creating the same cache twice', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'plugin', 'steve', '!!plugin');
                server.pack._provisionCache({ expiresIn: 1000 }, 'plugin', 'steve', '!!plugin');
            }).to.throw('Cannot provision the same cache segment more than once');
            done();
        });

        it('allows creating the same cache twice via cache options', function (done) {

            var server = new Hapi.Server();
            expect(function () {

                server.pack._provisionCache({ expiresIn: 1000 }, 'plugin', 'steve', '!!plugin');
                server.pack._provisionCache({ expiresIn: 1000, shared: true }, 'plugin', 'steve', '!!plugin');
            }).to.not.throw();
            done();
        });
    });

    describe('#handler', function () {

        it('add new handler', function (done) {

            var server = new Hapi.Server();
            var plugin = {
                name: 'foo',
                register: function (plugin, options, next) {

                    plugin.handler('bar', function (route, options) {

                        return function (request, reply) {

                            reply('success');
                        };
                    });
                    return next();
                }
            };

            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                server.route({
                    method: 'GET',
                    path: '/',
                    handler: {
                        bar: {}
                    }
                });
                server.inject('/', function (res) {
                    expect(res.payload).to.equal('success');
                    done();
                });
            });
        });
    });

    describe('#compose', function () {

        it('composes pack', function (done) {

            var manifest = {
                pack: {
                    cache: '../node_modules/catbox-memory',
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['api', 'nasty', 'test'],
                            views: {
                                engines: { html: 'handlebars' }
                            }
                        }
                    },
                    {
                        host: 'localhost',
                        port: 0,
                        options: {
                            labels: ['api', 'nice']
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--test1': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop(function () {

                        pack._servers[0].inject('/test1', function (res) {

                            expect(res.result).to.equal('testing123special-value');
                            done();
                        });
                    });
                });
            });
        });

        it('composes pack (cache.engine)', function (done) {

            var manifest = {
                pack: {
                    cache: {
                        engine: '../node_modules/catbox-memory'
                    },
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['api', 'nasty', 'test']
                        }
                    },
                    {
                        host: 'localhost',
                        port: 0,
                        options: {
                            labels: ['api', 'nice']
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--test1': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop(function () {

                        pack._servers[0].inject('/test1', function (res) {

                            expect(res.result).to.equal('testing123special-value');
                            done();
                        });
                    });
                });
            });
        });

        it('composes pack (cache array)', function (done) {

            var manifest = {
                pack: {
                    cache: [{
                        engine: '../node_modules/catbox-memory'
                    }],
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['api', 'nasty', 'test']
                        }
                    },
                    {
                        host: 'localhost',
                        port: 0,
                        options: {
                            labels: ['api', 'nice']
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--test1': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop(function () {

                        pack._servers[0].inject('/test1', function (res) {

                            expect(res.result).to.equal('testing123special-value');
                            done();
                        });
                    });
                });
            });
        });

        it('composes pack (engine function)', function (done) {

            var manifest = {
                pack: {
                    cache: {
                        engine: require('catbox-memory')
                    },
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['api', 'nasty', 'test']
                        }
                    },
                    {
                        host: 'localhost',
                        port: 0,
                        options: {
                            labels: ['api', 'nice'],
                            views: {
                                engines: { html: require('handlebars') }
                            }
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--test1': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop(function () {

                        pack._servers[0].inject('/test1', function (res) {

                            expect(res.result).to.equal('testing123special-value');
                            done();
                        });
                    });
                });
            });
        });

        it('composes pack (env)', function (done) {

            var manifest = {
                servers: [
                    {
                        port: '$env.hapi_port',
                        options: {
                            labels: ['api', 'nasty', 'test']
                        }
                    },
                    {
                        host: '$env.hapi_host',
                        port: 0,
                        options: {
                            labels: ['api', 'nice']
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--test1': {}
                }
            };

            process.env.hapi_port = '0';
            process.env.hapi_host = 'localhost';

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop();

                    pack._servers[0].inject('/test1', function (res) {

                        expect(res.result).to.equal('testing123');
                        done();
                    });
                });
            });
        });

        it('composes pack (relative and absolute paths)', function (done) {

            var manifest = {
                pack: {
                    cache: {
                        engine: '../../node_modules/catbox-memory'
                    },
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['api', 'nasty', 'test']
                        }
                    },
                    {
                        host: 'localhost',
                        port: 0,
                        options: {
                            labels: ['api', 'nice'],
                            views: {
                                engines: { html: '../../node_modules/handlebars' }
                            }
                        }
                    }
                ],
                plugins: {
                    './--test2': null
                }
            };

            manifest.plugins[__dirname + '/pack/--test1'] = null;

            Hapi.Pack.compose(manifest, { relativeTo: __dirname + '/pack' }, function (err, pack) {

                expect(err).to.not.exist;
                pack.start(function (err) {

                    expect(err).to.not.exist;
                    pack.stop(function () {

                        pack._servers[0].inject('/test1', function (res) {

                            expect(res.result).to.equal('testing123special-value');
                            done();
                        });
                    });
                });
            });
        });

        it('composes pack with ports', function (done) {

            var manifest = {
                servers: [
                    {
                        port: 8000
                    },
                    {
                        port: '8001',
                    }
                ],
                plugins: {}
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('validates server config after defaults applied', function (done) {

            var manifest = {
                servers: [
                    {
                        options: {
                            timeout: {

                            }
                        }
                    }
                ],
                plugins: {}
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('composes pack with plugin registration options', function (done) {

            var manifest = {
                pack: {
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                    {
                        port: 0,
                        options: {
                            labels: ['a', 'b']
                        }
                    },
                    {
                        port: 0,
                        options: {
                            labels: ['b', 'c']
                        }
                    }
                ],
                plugins: {
                    '../test/pack/--custom': [
                        {
                            options: {
                                path: '/'
                            }
                        },
                        {
                            select: 'a',
                            options: {
                                path: '/a'
                            }
                        },
                        {
                            select: 'b',
                            options: {
                                path: '/b'
                            }
                        },
                        {
                            route: {
                                prefix: '/steve'
                            },
                            options: {
                                path: '/a'
                            }
                        }
                    ]
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;

                var server1 = pack._servers[0];
                var server2 = pack._servers[1];

                server1.inject('/', function (res) {

                    expect(res.statusCode).to.equal(200);
                    expect(res.result).to.equal('/');

                    server2.inject('/', function (res) {

                        expect(res.statusCode).to.equal(200);
                        expect(res.result).to.equal('/');

                        server1.inject('/a', function (res) {

                            expect(res.statusCode).to.equal(200);
                            expect(res.result).to.equal('/a');

                            server2.inject('/a', function (res) {

                                expect(res.statusCode).to.equal(404);

                                server1.inject('/b', function (res) {

                                    expect(res.statusCode).to.equal(200);
                                    expect(res.result).to.equal('/b');

                                    server2.inject('/b', function (res) {

                                        expect(res.statusCode).to.equal(200);
                                        expect(res.result).to.equal('/b');

                                        server1.inject('/steve/a', function (res) {

                                            expect(res.statusCode).to.equal(200);
                                            expect(res.result).to.equal('/a');

                                            server2.inject('/steve/a', function (res) {

                                                expect(res.statusCode).to.equal(200);
                                                expect(res.result).to.equal('/a');
                                                done();
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        it('composes pack with inner deps', function (done) {

            var manifest = {
                servers: [{}],
                plugins: {
                    '../test/pack/--deps1': null,
                    '../test/pack/--deps2': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('errors on invalid plugin', function (done) {

            var manifest = {
                servers: [{}],
                plugins: {
                    '../test/pack/--fail': null
                }
            };

            Hapi.Pack.compose(manifest, function (err, pack) {

                expect(err).to.exist;
                done();
            });
        });

        it('throws on pack with missing inner deps', function (done) {

            var manifest = {
                servers: [{ host: 'localhost' }],
                plugins: {
                    '../test/pack/--deps1': null
                }
            };

            var domain = Domain.create();
            domain.on('error', function (err) {

                expect(err.message).to.equal('Plugin --deps1 missing dependency --deps2 in server: http://localhost:80');
                done();
            });

            domain.run(function () {

                Hapi.Pack.compose(manifest, function (err, pack) {});
            });
        });

        it('throws on invalid manifest options', function (done) {

            var manifest = {
                pack: {
                    app: {
                        my: 'special-value'
                    }
                },
                servers: [
                ],
                plugins: {
                    './--loaded': {}
                }
            };

            expect(function() {

                Hapi.Pack.compose(manifest, function () {});
            }).to.throw('Invalid manifest options');
            done();
        });
    });

    describe('#render', function () {

        it('renders view', function (done) {

            var plugin = {
                name: 'test',
                register: function (plugin, options, next) {

                    plugin.views({
                        engines: { 'html': require('handlebars') },
                        basePath: __dirname + '/pack/--views',
                        path: './templates'
                    });

                    var view = plugin.render('test', { message: 'steve' }, function (err, rendered, config) {

                        plugin.route([
                            {
                                path: '/view', method: 'GET', handler: function (request, reply) {

                                    return reply(rendered);
                                }
                            }
                        ]);

                        return next();
                    });
                }
            };

            var server = new Hapi.Server();
            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                server.inject('/view', function (res) {

                    expect(res.result).to.equal('
steve
');
                    done();
                });
            });
        });

        it('renders view (with options)', function (done) {

            var plugin = {
                name: 'test',
                register: function (plugin, options, next) {

                    plugin.views({
                        engines: { 'html': require('handlebars') }
                    });

                    var view = plugin.render('test', { message: 'steve' }, { basePath: __dirname + '/pack/--views', path: './templates' }, function (err, rendered, config) {

                        plugin.route([
                            {
                                path: '/view', method: 'GET', handler: function (request, reply) {

                                    return reply(rendered);
                                }
                            }
                        ]);

                        return next();
                    });
                }
            };

            var server = new Hapi.Server();
            server.pack.register(plugin, function (err) {

                expect(err).to.not.exist;
                server.inject('/view', function (res) {

                    expect(res.result).to.equal('
steve
');
                    done();
                });
            });
        });
    });
});


text:
/**
 * https://oj.leetcode.com/problems/longest-palindromic-substring/
 * Given a string S, find the longest palindromic substring in S.
 * You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
 */
public class LongestPalindromicSubstring {
    public static void main(String[] args) {
        System.out.println(new LongestPalindromicSubstring().truncate("1301 Ave FLR31, WA 98021", 13));
    }

    public String truncate(String str, int k) {
        int len = str == null ? 0 : str.length();
        if (k < 1 || len < k) {
            throw new IllegalArgumentException("");
        }
        if (len == k) {
            return str;
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (res.length() >= k) {
                if (isNumber(c)) {
                    replace(res, c);
                }
            } else {
                res.append(c);
            }
        }
        return res.toString();
    }

    private void replace(StringBuilder res, char c) {
        int i = res.length() - 1;
        while (i >= 0) {
            char tmp = res.charAt(i);
            if (!isNumber(tmp)) {
                res.deleteCharAt(i);
                break;
            }
            i--;
        }
        res.append(c);
    }

    private boolean isNumber(char c) {
        return c >= '0' && c <= '9';
    }
}

redpajama_set_name: RedPajamaGithub


text:
CREATE TABLE IF NOT EXISTS `ipdb` (
  `id` int(11) NOT NULL,
  `range` varchar(50) NOT NULL,
  `location` varchar(200) NOT NULL,
  `type` varchar(100) NOT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `ipdb`
  ADD PRIMARY KEY (`id`);


text:
package ru.javavlad.array;

import java.util.Arrays;

/**
 * ArrayDuplicate class.
 * @author Vladislav4er
 * @version 1.00
 * @since 04.04.2018
 */

public class ArrayDuplicate {

    /**
     * Duplicate in array remove method.
     * @param array - input array with duplicates
     * @return array without duplicates
     */

    public String[] remove(String[] array) {
        int unique = array.length;
        for (int out = 0; out < unique; out++) {
            for (int in = out + 1; in < unique; in++) {
                if (array[out].equals(array[in])) {
                    array[in] = array[unique - 1];
                    unique--;
                    in--;
                }
            }
        }
        return Arrays.copyOf(array, unique);
    }
}


text:
import {expect} from 'chai';
// import jsdom from 'jsdom';
// import fs from 'fs';
describe('Our first test', () =>{
  it('should pass', () =>{
    expect(true).to.equal(true);
  });
});

// describe('index.html', ()=>{
//   "use strict";
//   it('should say hello', (done) =>{
//     const index = fs.readFileSync('./src/index.html', "utf-8");

//     new jsdom(index, function (err, window) {
//       const h1 = window.document.getElementsByTagName('h1')[0];
//       expect(h1.innerHTML).to.equal('Hello World!');
//       done();
//       window.close();
//     });
//   });
// });


text:
<?xml version="1.0" encoding="UTF-8"?>
<images animationDelay="4">
	<image src="assets/1.jpg" link="http://www.google.de"/>
	<image src="assets/2.jpg" />
	<image src="assets/trv4_eng2.swf"/>
	<image src="assets/4.jpg" link="http://www.heise.de"/>
	<image src="assets/3.jpg" link="http://www.wetter.de"/>
</images>


text:
<?php

declare(strict_types=1);

namespace Sentry\Serializer;

/**
 * Serializes a value into a representation that should reasonably suggest
 * both the type and value, and be serializable into JSON.
 */
interface RepresentationSerializerInterface
{
    /**
     * Serialize an object (recursively) into something safe to be sent as a stacktrace frame argument.
     *
     * The main difference with the {@link SerializerInterface} is the fact that even basic types
     * (bool, int, float) are converted into strings, to avoid misrepresentations on the server side.
     *
     * @param mixed $value
     *
     * @return mixed[]|string|null
     */
    public function representationSerialize($value);
}


text:
/**
 * @file entity_browser.modal_selection.js
 *
 * Propagates selected entities from modal display.
 */

(function (drupalSettings) {

  'use strict';

  // We need to access parent window, get it's jquery and find correct modal
  // element to trigger event on.
  parent.jQuery(parent.document)
    .find(':input[data-uuid*=' + drupalSettings.entity_browser.modal.uuid + ']')
    .trigger('entities-selected', [drupalSettings.entity_browser.modal.uuid, drupalSettings.entity_browser.modal.entities])
    .unbind('entities-selected').show();

  // This is a silly solution, but works fo now. We should close the modal
  // via ajax commands.
  parent.jQuery(parent.document).find('.entity-browser-modal-iframe').parents('.ui-dialog').eq(0).find('.ui-dialog-titlebar-close').click();

}(drupalSettings));


text:
package enrich

import (
	"fmt"
	"github.com/spf13/viper"
	"github.com/fsnotify/fsnotify"
	"log"
)

func init() {

	viper.AutomaticEnv()
	viper.SetConfigName("enrich-service")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("/etc/numeralti/")
	viper.AddConfigPath("$HOME/.numeralti")
	viper.AddConfigPath(".")

	viper.SetDefault("listenOn", ":8083")
	viper.SetDefault("serviceName", ":enrich")

	err := viper.ReadInConfig()
	if err != nil {
		log.Println("Could not read config file, using defaults" + err.Error())
	}

	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})
}


text:
namespace Google.Cloud.AIPlatform.V1.Snippets
{
    // [START aiplatform_v1_generated_TensorboardService_BatchReadTensorboardTimeSeriesData_async_flattened_resourceNames]
    using Google.Cloud.AIPlatform.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedTensorboardServiceClientSnippets
    {
        /// <summary>Snippet for BatchReadTensorboardTimeSeriesDataAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task BatchReadTensorboardTimeSeriesDataResourceNamesAsync()
        {
            // Create client
            TensorboardServiceClient tensorboardServiceClient = await TensorboardServiceClient.CreateAsync();
            // Initialize request argument(s)
            TensorboardName tensorboard = TensorboardName.FromProjectLocationTensorboard("[PROJECT]", "[LOCATION]", "[TENSORBOARD]");
            // Make the request
            BatchReadTensorboardTimeSeriesDataResponse response = await tensorboardServiceClient.BatchReadTensorboardTimeSeriesDataAsync(tensorboard);
        }
    }
    // [END aiplatform_v1_generated_TensorboardService_BatchReadTensorboardTimeSeriesData_async_flattened_resourceNames]
}


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace NGnono.FMNote.Datas.Models.Mapping
{
    public partial class AdminAccessRightEntityMap : EntityTypeConfiguration<AdminAccessRightEntity>
    {
        public AdminAccessRightEntityMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(100);

            this.Property(t => t.Description)
                .HasMaxLength(200);

            this.Property(t => t.ControllName)
                .IsRequired()
                .HasMaxLength(50);

            this.Property(t => t.ActionName)
                .HasMaxLength(50);

            // Table & Column Mappings
            this.ToTable("AdminAccessRight");
            this.Property(t => t.Id).HasColumnName("Id");
            this.Property(t => t.Name).HasColumnName("Name");
            this.Property(t => t.Description).HasColumnName("Description");
            this.Property(t => t.ControllName).HasColumnName("ControllName");
            this.Property(t => t.ActionName).HasColumnName("ActionName");
            this.Property(t => t.Status).HasColumnName("Status");
            this.Property(t => t.InDate).HasColumnName("InDate");
            this.Property(t => t.InUser).HasColumnName("InUser");
			LastInit();
        }

		partial void LastInit();
    }
}


text:
<!DOCTYPE html>
<link rel="help" href="https://drafts.csswg.org/css-tables-3/#height-distribution-algorithm">
<link rel="match" href="td-different-subpixel-padding-in-same-row-ref.html">
Passes if there is an unbroken rectangular border.


text:
import errno
import json
import os
import re

from os_brick.remotefs import remotefs
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import units

from cinder import exception
from cinder.i18n import _, _LI
from cinder.image import image_utils
from cinder import utils
from cinder.volume.drivers import remotefs as remotefs_drv

VERSION = '1.0'

LOG = logging.getLogger(__name__)

vzstorage_opts = [
    cfg.StrOpt('vzstorage_shares_config',
               default='/etc/cinder/vzstorage_shares',
               help='File with the list of available vzstorage shares.'),
    cfg.BoolOpt('vzstorage_sparsed_volumes',
                default=True,
                help=('Create volumes as sparsed files which take no space '
                      'rather than regular files when using raw format, '
                      'in which case volume creation takes lot of time.')),
    cfg.FloatOpt('vzstorage_used_ratio',
                 default=0.95,
                 help=('Percent of ACTUAL usage of the underlying volume '
                       'before no new volumes can be allocated to the volume '
                       'destination.')),
    cfg.StrOpt('vzstorage_mount_point_base',
               default='$state_path/mnt',
               help=('Base dir containing mount points for '
                     'vzstorage shares.')),
    cfg.ListOpt('vzstorage_mount_options',
                default=None,
                help=('Mount options passed to the vzstorage client. '
                      'See section of the pstorage-mount man page '
                      'for details.')),
]

CONF = cfg.CONF
CONF.register_opts(vzstorage_opts)

class VZStorageDriver(remotefs_drv.RemoteFSSnapDriver):
    """Cinder driver for Virtuozzo Storage.

    Creates volumes as files on the mounted vzstorage cluster.

    Version history:
        1.0     - Initial driver.
    """
    driver_volume_type = 'vzstorage'
    driver_prefix = 'vzstorage'
    volume_backend_name = 'Virtuozzo_Storage'
    VERSION = VERSION
    SHARE_FORMAT_REGEX = r'(?:(\S+):\/)?([a-zA-Z0-9_-]+)(?::(\S+))?'

    def __init__(self, execute=putils.execute, *args, **kwargs):
        self._remotefsclient = None
        super(VZStorageDriver, self).__init__(*args, **kwargs)
        self.configuration.append_config_values(vzstorage_opts)
        self._execute_as_root = False
        root_helper = utils.get_root_helper()
        # base bound to instance is used in RemoteFsConnector.
        self.base = getattr(self.configuration,
                            'vzstorage_mount_point_base',
                            CONF.vzstorage_mount_point_base)
        opts = getattr(self.configuration,
                       'vzstorage_mount_options',
                       CONF.vzstorage_mount_options)

        self._remotefsclient = remotefs.RemoteFsClient(
            'vzstorage', root_helper, execute=execute,
            vzstorage_mount_point_base=self.base,
            vzstorage_mount_options=opts)

    def _qemu_img_info(self, path, volume_name):
        return super(VZStorageDriver, self)._qemu_img_info_base(
            path, volume_name, self.configuration.vzstorage_mount_point_base)

    @remotefs_drv.locked_volume_id_operation
    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info.

        :param volume: volume reference
        :param connector: connector reference
        """
        # Find active image
        active_file = self.get_active_image_from_info(volume)
        active_file_path = os.path.join(self._local_volume_dir(volume),
                                        active_file)
        info = self._qemu_img_info(active_file_path, volume['name'])
        fmt = info.file_format

        data = {'export': volume['provider_location'],
                'format': fmt,
                'name': active_file,
                }

        return {
            'driver_volume_type': self.driver_volume_type,
            'data': data,
            'mount_point_base': self._get_mount_point_base(),
        }

    def do_setup(self, context):
        """Any initialization the volume driver does while starting."""
        super(VZStorageDriver, self).do_setup(context)

        config = self.configuration.vzstorage_shares_config
        if not os.path.exists(config):
            msg = (_("VzStorage config file at %(config)s doesn't exist.") %
                   {'config': config})
            LOG.error(msg)
            raise exception.VzStorageException(msg)

        if not os.path.isabs(self.base):
            msg = _("Invalid mount point base: %s.") % self.base
            LOG.error(msg)
            raise exception.VzStorageException(msg)

        used_ratio = self.configuration.vzstorage_used_ratio
        if not ((used_ratio > 0) and (used_ratio <= 1)):
            msg = _("VzStorage config 'vzstorage_used_ratio' invalid. "
                    "Must be > 0 and <= 1.0: %s.") % used_ratio
            LOG.error(msg)
            raise exception.VzStorageException(msg)

        self.shares = {}

        # Check if mount.fuse.pstorage is installed on this system;
        # note that we don't need to be root to see if the package
        # is installed.
        package = 'mount.fuse.pstorage'
        try:
            self._execute(package, check_exit_code=False,
                          run_as_root=False)
        except OSError as exc:
            if exc.errno == errno.ENOENT:
                msg = _('%s is not installed.') % package
                raise exception.VzStorageException(msg)
            else:
                raise

        self.configuration.nas_secure_file_operations = 'true'
        self.configuration.nas_secure_file_permissions = 'true'

    def _ensure_share_mounted(self, share):
        m = re.search(self.SHARE_FORMAT_REGEX, share)
        if not m:
            msg = (_("Invalid Virtuozzo Storage share specification: %r. "
                     "Must be: [MDS1[,MDS2],...:/]<CLUSTER NAME>[:PASSWORD].")
                   % share)
            raise exception.VzStorageException(msg)
        cluster_name = m.group(2)

        # set up logging to non-default path, so that it will
        # be possible to mount the same cluster to another mount
        # point by hand with default options.
        mnt_flags = ['-l', '/var/log/pstorage/%s-cinder.log.gz' % cluster_name]
        if self.shares.get(share) is not None:
            extra_flags = json.loads(self.shares[share])
            mnt_flags.extend(extra_flags)
        self._remotefsclient.mount(share, mnt_flags)

    def _find_share(self, volume_size_in_gib):
        """Choose VzStorage share among available ones for given volume size.

        For instances with more than one share that meets the criteria, the
        first suitable share will be selected.

        :param volume_size_in_gib: int size in GB
        """

        if not self._mounted_shares:
            raise exception.VzStorageNoSharesMounted()

        for share in self._mounted_shares:
            if self._is_share_eligible(share, volume_size_in_gib):
                break
        else:
            raise exception.VzStorageNoSuitableShareFound(
                volume_size=volume_size_in_gib)

        LOG.debug('Selected %s as target VzStorage share.', share)

        return share

    def _is_share_eligible(self, vz_share, volume_size_in_gib):
        """Verifies VzStorage share is eligible to host volume with given size.

        :param vz_share: vzstorage share
        :param volume_size_in_gib: int size in GB
        """

        used_ratio = self.configuration.vzstorage_used_ratio
        volume_size = volume_size_in_gib * units.Gi

        total_size, available, allocated = self._get_capacity_info(vz_share)

        if (allocated + volume_size) / total_size > used_ratio:
            LOG.debug('_is_share_eligible: %s is above '
                      'vzstorage_used_ratio.', vz_share)
            return False

        return True

    @remotefs_drv.locked_volume_id_operation
    def extend_volume(self, volume, size_gb):
        LOG.info(_LI('Extending volume %s.'), volume['id'])
        self._extend_volume(volume, size_gb)

    def _extend_volume(self, volume, size_gb):
        volume_path = self.local_path(volume)

        self._check_extend_volume_support(volume, size_gb)
        LOG.info(_LI('Resizing file to %sG...'), size_gb)

        self._do_extend_volume(volume_path, size_gb)

    def _do_extend_volume(self, volume_path, size_gb):
        image_utils.resize_image(volume_path, size_gb)

        if not self._is_file_size_equal(volume_path, size_gb):
            raise exception.ExtendVolumeError(
                reason='Resizing image file failed.')

    def _check_extend_volume_support(self, volume, size_gb):
        volume_path = self.local_path(volume)
        active_file = self.get_active_image_from_info(volume)
        active_file_path = os.path.join(self._local_volume_dir(volume),
                                        active_file)

        if active_file_path != volume_path:
            msg = _('Extend volume is only supported for this '
                    'driver when no snapshots exist.')
            raise exception.InvalidVolume(msg)

        extend_by = int(size_gb) - volume['size']
        if not self._is_share_eligible(volume['provider_location'],
                                       extend_by):
            raise exception.ExtendVolumeError(reason='Insufficient space to '
                                              'extend volume %s to %sG.'
                                              % (volume['id'], size_gb))

    def _is_file_size_equal(self, path, size):
        """Checks if file size at path is equal to size."""
        data = image_utils.qemu_img_info(path)
        virt_size = data.virtual_size / units.Gi
        return virt_size == size

    def _copy_volume_from_snapshot(self, snapshot, volume, volume_size):
        """Copy data from snapshot to destination volume.

        This is done with a qemu-img convert to raw/qcow2 from the snapshot
        qcow2.
        """

        LOG.debug("_copy_volume_from_snapshot: snapshot: %(snap)s, "
                  "volume: %(vol)s, volume_size: %(size)s.",
                  {'snap': snapshot['id'],
                   'vol': volume['id'],
                   'size': volume_size,
                   })

        info_path = self._local_path_volume_info(snapshot['volume'])
        snap_info = self._read_info_file(info_path)
        vol_dir = self._local_volume_dir(snapshot['volume'])
        out_format = "raw"

        forward_file = snap_info[snapshot['id']]
        forward_path = os.path.join(vol_dir, forward_file)

        # Find the file which backs this file, which represents the point
        # when this snapshot was created.
        img_info = self._qemu_img_info(forward_path,
                                       snapshot['volume']['name'])
        path_to_snap_img = os.path.join(vol_dir, img_info.backing_file)

        LOG.debug("_copy_volume_from_snapshot: will copy "
                  "from snapshot at %s.", path_to_snap_img)

        image_utils.convert_image(path_to_snap_img,
                                  self.local_path(volume),
                                  out_format)
        self._extend_volume(volume, volume_size)

    @remotefs_drv.locked_volume_id_operation
    def delete_volume(self, volume):
        """Deletes a logical volume."""
        if not volume['provider_location']:
            msg = (_('Volume %s does not have provider_location '
                     'specified, skipping.') % volume['name'])
            LOG.error(msg)
            raise exception.VzStorageException(msg)

        self._ensure_share_mounted(volume['provider_location'])
        volume_dir = self._local_volume_dir(volume)
        mounted_path = os.path.join(volume_dir,
                                    self.get_active_image_from_info(volume))
        if os.path.exists(mounted_path):
            self._delete(mounted_path)
        else:
            LOG.info(_LI("Skipping deletion of volume %s "
                         "as it does not exist."), mounted_path)

        info_path = self._local_path_volume_info(volume)
        self._delete(info_path)


text:
KUploadFile *KUploadFile::d = 0;

KUploadFile::KUploadFile(QObject *parent)
    :QObject(parent)
{
//    QFileDialog dialog(this);
//    filename = dialog.getOpenFileName(0, "/");

    _uploadManager = new QNetworkAccessManager(this);
    connect(_uploadManager,SIGNAL(finished(QNetworkReply*)),SLOT(replyFinished(QNetworkReply*)));
    m_buf = NULL;
}

KUploadFile::~KUploadFile()
{
    if( m_buf != NULL ) delete[] m_buf;
}

KUploadFile * KUploadFile::getInstance()
{
    if (d == 0)
        d = new KUploadFile;
    return d;
}

void KUploadFile::uploadFile(QString uploadFilename)
{
    QFile file(uploadFilename);
    file.open(QIODevice::ReadOnly);
    int  file_len = file.size();

    QDataStream in(&file);
    m_buf = new char[file_len];
    in.readRawData( m_buf, file_len);
    file.close();

    QUrl url = QString("http://10.0.1.77:8080/TrainService/Uploadfile");
    QNetworkRequest request( url );

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    request.setRawHeader("filename", uploadFilename.section('/', -1, -1).toUtf8() );

    QByteArray arr = QByteArray( m_buf, file_len );
    _reply = _uploadManager->post( request , arr );

    connect(_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(upLoadError(QNetworkReply::NetworkError)));
    connect(_reply, SIGNAL(uploadProgress ( qint64 ,qint64 )), this, SLOT( OnUploadProgress(qint64 ,qint64 )));

}

void KUploadFile::replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<"no error.....";
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        qDebug()<<result;
    }
    else{
        qDebug() << "replyFinished:  " << reply->error() << " " <<reply->errorString();
    }

    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<status_code;
}

void KUploadFile::upLoadError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "upLoadError  errorCode: " << (int)errorCode;
}

void KUploadFile::OnUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
    qDebug() << "bytesSent: " << bytesSent << "  bytesTotal: "<< bytesTotal;
}


text:
extern bool touch_forward;
extern bool touch_jump;

extern long touch_active;
extern long touch_clientX;
extern long touch_clientY;

void init_touch_callbacks(GLFWwindow *window);


text:
from setuptools import setup, find_packages
import os

version = '2.4.2'

requires = [
    'setuptools',
    'openprocurement.api>=2.4',
]
test_requires = requires + [
    'webtest',
    'python-coveralls',
]
docs_requires = requires + [
    'sphinxcontrib-httpdomain',
]

entry_points = {
    'openprocurement.api.plugins': [
        'planning = openprocurement.planning.api:includeme'
    ],
    'openprocurement.api.migrations': [
        'plans = openprocurement.planning.api.migration:migrate_data'
    ]
}

setup(name='openprocurement.planning.api',
      version=version,
      description="",
      long_description=open("README.rst").read() + "\n" +
                       open(os.path.join("docs", "HISTORY.txt")).read(),
      classifiers=[
        "Programming Language :: Python",
        ],
      keywords='',
      author='Quintagroup, Ltd.',
      author_email='info@quintagroup.com',
      license='Apache License 2.0',
      url='https://github.com/gorserg/openprocurement.planning.api',
      packages=find_packages(exclude=['ez_setup']),
      namespace_packages=['openprocurement', 'openprocurement.planning'],
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=test_requires,
      extras_require={'test': test_requires, 'docs': docs_requires},
      test_suite="openprocurement.planning.api.tests.main.suite",
      entry_points=entry_points,
      )


text:
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Threading;

using IBM.Data.Informix;

namespace BLToolkit.Data.DataProvider
{
	using Sql.SqlProvider;

	class InformixDataProvider :  DataProviderBase
	{
		public override IDbConnection CreateConnectionObject () { return new IfxConnection      ();     }
		public override DbDataAdapter CreateDataAdapterObject() { return new IfxDataAdapter     ();     }
		public override ISqlProvider  CreateSqlProvider      () { return new InformixSqlProvider(this); }

		public override Type   ConnectionType { get { return typeof(IfxConnection);              } }
		public override string Name           { get { return DataProvider.ProviderName.Informix; } }
		public override string EndOfSql       { get { return ";"; } }

		public override bool DeriveParameters(IDbCommand command)
		{
			if (command is IfxCommand)
			{
				IfxCommandBuilder.DeriveParameters((IfxCommand)command);
				return true;
			}

			return false;
		}

		public override object Convert(object value, ConvertType convertType)
		{
			switch (convertType)
			{
				case ConvertType.NameToQueryParameter:
					return "?";

				case ConvertType.NameToCommandParameter:
				case ConvertType.NameToSprocParameter:
					return ":" + value;

				case ConvertType.SprocParameterToName:
					if (value != null)
					{
						var str = value.ToString();
						return (str.Length > 0 && str[0] == ':')? str.Substring(1): str;
					}

					break;

				case ConvertType.ExceptionToErrorNumber:
					if (value is IfxException)
					{
						var ex = (IfxException)value;

						foreach (IfxError error in ex.Errors)
							return error.NativeError;

						return 0;
					}

					break;
			}

			return value;
		}

		public override void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters)
		{
			base.PrepareCommand(ref commandType, ref commandText, ref commandParameters);

			if (commandParameters != null) foreach (var p in commandParameters)
			{
				if (p.Value is Guid)
				{
					var value = p.Value.ToString();
					p.DbType = DbType.AnsiStringFixedLength;
					p.Value  = value;
					p.Size   = value.Length;
				}
				//else if (p.DbType == DbType.Binary)
				//{
				//	var ip = (IfxParameter)p;

				//	ip.IfxType = IfxType.Blob;
				//}
			}
		}

		#region GetDataReader

		public override IDataReader GetDataReader(Mapping.MappingSchema schema, IDataReader dataReader)
		{
			return dataReader is IfxDataReader?
				new InformixDataReaderEx((IfxDataReader)dataReader):
				base.GetDataReader(schema, dataReader);
		}

		class InformixDataReaderEx : DataReaderBase<IfxDataReader>, IDataReader
		{
			public InformixDataReaderEx(IfxDataReader rd): base(rd)
			{
			}

			public new float GetFloat(int i)
			{
				var current = Thread.CurrentThread.CurrentCulture;

				if (Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

				var value = DataReader.GetFloat(i);

				if (current != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = current;

				return value;
			}

			public new double GetDouble(int i)
			{
				var current = Thread.CurrentThread.CurrentCulture;

				if (Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

				var value = DataReader.GetDouble(i);

				if (current != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = current;

				return value;
			}

			public new decimal GetDecimal(int i)
			{
				var current = Thread.CurrentThread.CurrentCulture;

				if (Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

				var value = DataReader.GetDecimal     (i);

				if (current != CultureInfo.InvariantCulture)
					Thread.CurrentThread.CurrentCulture = current;

				return value;
			}
		}

		#endregion
	}
}


text:
'''
Created on Mar 4, 2014

@author: kylerogers
'''

class PageHelper:

    @staticmethod
    def get_request_count(request, default_count_per_page, max_count_per_page):
        '''
        Finds the requested number of brothers and corrects it if there are any issues
        If the number is invalid, it will return standard_brothers_per_page
        '''
        brothers_count = request.GET.get('count',str(default_count_per_page))
        try:
            brothers_count = int(brothers_count)
            if brothers_count > max_count_per_page:
                brothers_count = max_count_per_page
        except:
            brothers_count = default_count_per_page
        return brothers_count

    @staticmethod
    def get_page_number(request):
        '''
        Finds the page number and corrects it if there are any issues
        If the page number is invalid, it will return 1
        '''
        page_number = request.GET.get('page','1')
        try:
            page_number = int(page_number)
            if page_number < 1:
                page_number = 1
        except:
            page_number = 1
        return page_number

    @staticmethod
    def calculate_page_range(total_pages, page_number, max_pages_listed_on_screen):
        '''
        This determines which page numbers to show at the bottom of the brothers list pages.
        It returns a list of integers that should be displayed on the page based on the total
        number of pages and the current page number.
        '''
        if total_pages == 1: # If there is only the one page, there is no need to display page numbers
            return []
        elif total_pages <= max_pages_listed_on_screen: # In this case, just display all of the available pages
            min_page_number_displayed = 1
            max_page_number_displayed = total_pages + 1
        elif page_number - max_pages_listed_on_screen / 2 <= 1: # We are near the beginning. In this case, display from page 1 to max_pages_listed_on_screen
            min_page_number_displayed = 1
            max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen
        elif page_number + max_pages_listed_on_screen / 2 >= total_pages: # We are near the end. In this case, display from (end - max_pages_listed_on_screen) to end
            max_page_number_displayed = total_pages + 1
            min_page_number_displayed = max_page_number_displayed - max_pages_listed_on_screen
        else: # We are somewhere in the middle. In this case, just display some pages on either side
            min_page_number_displayed = page_number - max_pages_listed_on_screen / 2
            max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen

        page_numbers_list = range(min_page_number_displayed,max_page_number_displayed)
        return page_numbers_list