text:
'use strict';

const chai = require('chai'),
  sinon = require('sinon'),
  expect = chai.expect,
  Support = require('../support'),
  DataTypes = require('../../../lib/data-types'),
  Sequelize = require('../../../index'),
  current = Support.sequelize,
  dialect = Support.getTestDialect();

describe(Support.getTestDialectTeaser('BelongsTo'), () => {
  describe('Model.associations', () => {
    it('should store all associations when associating to the same table multiple times', function() {
      const User = this.sequelize.define('User', {}),
        Group = this.sequelize.define('Group', {});

      Group.belongsTo(User);
      Group.belongsTo(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' });
      Group.belongsTo(User, { foreignKey: 'secondaryGroupId', as: 'secondaryUsers' });

      expect(
        Object.keys(Group.associations)
      ).to.deep.equal(['User', 'primaryUsers', 'secondaryUsers']);
    });
  });

  describe('get', () => {
    describe('multiple', () => {
      it('should fetch associations for multiple instances', async function() {
        const User = this.sequelize.define('User', {}),
          Task = this.sequelize.define('Task', {});

        Task.User = Task.belongsTo(User, { as: 'user' });

        await this.sequelize.sync({ force: true });

        const tasks = await Promise.all([Task.create({
          id: 1,
          user: { id: 1 }
        }, {
          include: [Task.User]
        }), Task.create({
          id: 2,
          user: { id: 2 }
        }, {
          include: [Task.User]
        }), Task.create({
          id: 3
        })]);

        const result = await Task.User.get(tasks);
        expect(result[tasks[0].id].id).to.equal(tasks[0].user.id);
        expect(result[tasks[1].id].id).to.equal(tasks[1].user.id);
        expect(result[tasks[2].id]).to.be.undefined;
      });
    });
  });

  describe('getAssociation', () => {
    if (current.dialect.supports.transactions) {
      it('supports transactions', async function() {
        const sequelize = await Support.prepareTransactionTest(this.sequelize);
        const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
          Group = sequelize.define('Group', { name: Support.Sequelize.STRING });

        Group.belongsTo(User);

        await sequelize.sync({ force: true });
        const user = await User.create({ username: 'foo' });
        const group = await Group.create({ name: 'bar' });
        const t = await sequelize.transaction();
        await group.setUser(user, { transaction: t });
        const groups = await Group.findAll();
        const associatedUser = await groups[0].getUser();
        expect(associatedUser).to.be.null;
        const groups0 = await Group.findAll({ transaction: t });
        const associatedUser0 = await groups0[0].getUser({ transaction: t });
        expect(associatedUser0).to.be.not.null;
        await t.rollback();
      });
    }

    it('should be able to handle a where object that\'s a first class citizen.', async function() {
      const User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING, gender: Sequelize.STRING }),
        Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING, status: Sequelize.STRING });

      Task.belongsTo(User);

      await User.sync({ force: true });
      // Can't use Promise.all cause of foreign key references
      await Task.sync({ force: true });

      const [userA, , task] = await Promise.all([
        User.create({ username: 'foo', gender: 'male' }),
        User.create({ username: 'bar', gender: 'female' }),
        Task.create({ title: 'task', status: 'inactive' })
      ]);

      await task.setUserXYZ(userA);
      const user = await task.getUserXYZ({ where: { gender: 'female' } });
      expect(user).to.be.null;
    });

    it('supports schemas', async function() {
      const User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING, gender: Sequelize.STRING }).schema('archive'),
        Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING, status: Sequelize.STRING }).schema('archive');

      Task.belongsTo(User);

      await Support.dropTestSchemas(this.sequelize);
      await this.sequelize.createSchema('archive');
      await User.sync({ force: true });
      await Task.sync({ force: true });

      const [user0, task] = await Promise.all([
        User.create({ username: 'foo', gender: 'male' }),
        Task.create({ title: 'task', status: 'inactive' })
      ]);

      await task.setUserXYZ(user0);
      const user = await task.getUserXYZ();
      expect(user).to.be.ok;
      await this.sequelize.dropSchema('archive');
      const schemas = await this.sequelize.showAllSchemas();
      if (dialect === 'postgres' || dialect === 'mssql' || dialect === 'mariadb') {
        expect(schemas).to.not.have.property('archive');
      }
    });

    it('supports schemas when defining custom foreign key attribute #9029', async function() {
      const User = this.sequelize.define('UserXYZ', {
          uid: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false
          }
        }).schema('archive'),
        Task = this.sequelize.define('TaskXYZ', {
          user_id: {
            type: Sequelize.INTEGER,
            references: { model: User, key: 'uid' }
          }
        }).schema('archive');

      Task.belongsTo(User, { foreignKey: 'user_id' });

      await Support.dropTestSchemas(this.sequelize);
      await this.sequelize.createSchema('archive');
      await User.sync({ force: true });
      await Task.sync({ force: true });
      const user0 = await User.create({});
      const task = await Task.create({});
      await task.setUserXYZ(user0);
      const user = await task.getUserXYZ();
      expect(user).to.be.ok;

      await this.sequelize.dropSchema('archive');
    });
  });

  describe('setAssociation', () => {

    if (current.dialect.supports.transactions) {
      it('supports transactions', async function() {
        const sequelize = await Support.prepareTransactionTest(this.sequelize);
        const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
          Group = sequelize.define('Group', { name: Support.Sequelize.STRING });

        Group.belongsTo(User);

        await sequelize.sync({ force: true });
        const user = await User.create({ username: 'foo' });
        const group = await Group.create({ name: 'bar' });
        const t = await sequelize.transaction();
        await group.setUser(user, { transaction: t });
        const groups = await Group.findAll();
        const associatedUser = await groups[0].getUser();
        expect(associatedUser).to.be.null;
        await t.rollback();
      });
    }

    it('can set the association with declared primary keys...', async function() {
      const User = this.sequelize.define('UserXYZ', { user_id: { type: DataTypes.INTEGER, primaryKey: true }, username: DataTypes.STRING }),
        Task = this.sequelize.define('TaskXYZ', { task_id: { type: DataTypes.INTEGER, primaryKey: true }, title: DataTypes.STRING });

      Task.belongsTo(User, { foreignKey: 'user_id' });

      await this.sequelize.sync({ force: true });
      const user = await User.create({ user_id: 1, username: 'foo' });
      const task = await Task.create({ task_id: 1, title: 'task' });
      await task.setUserXYZ(user);
      const user1 = await task.getUserXYZ();
      expect(user1).not.to.be.null;

      await task.setUserXYZ(null);
      const user0 = await task.getUserXYZ();
      expect(user0).to.be.null;
    });

    it('clears the association if null is passed', async function() {
      const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
        Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });

      Task.belongsTo(User);

      await this.sequelize.sync({ force: true });
      const user = await User.create({ username: 'foo' });
      const task = await Task.create({ title: 'task' });
      await task.setUserXYZ(user);
      const user1 = await task.getUserXYZ();
      expect(user1).not.to.be.null;

      await task.setUserXYZ(null);
      const user0 = await task.getUserXYZ();
      expect(user0).to.be.null;
    });

    it('should throw a ForeignKeyConstraintError if the associated record does not exist', async function() {
      const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
        Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });

      Task.belongsTo(User);

      await this.sequelize.sync({ force: true });
      await expect(Task.create({ title: 'task', UserXYZId: 5 })).to.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
      const task = await Task.create({ title: 'task' });

      await expect(Task.update({ title: 'taskUpdate', UserXYZId: 5 }, { where: { id: task.id } })).to.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
    });

    it('supports passing the primary key instead of an object', async function() {
      const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
        Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });

      Task.belongsTo(User);

      await this.sequelize.sync({ force: true });
      const user = await User.create({ id: 15, username: 'jansemand' });
      const task = await Task.create({});
      await task.setUserXYZ(user.id);
      const user0 = await task.getUserXYZ();
      expect(user0.username).to.equal('jansemand');
    });

    it('should support logging', async function() {
      const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
        Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING }),
        spy = sinon.spy();

      Task.belongsTo(User);

      await this.sequelize.sync({ force: true });
      const user = await User.create();
      const task = await Task.create({});
      await task.setUserXYZ(user, { logging: spy });
      expect(spy.called).to.be.ok;
    });

    it('should not clobber atributes', async function() {
      const Comment = this.sequelize.define('comment', {
        text: DataTypes.STRING
      });

      const Post = this.sequelize.define('post', {
        title: DataTypes.STRING
      });

      Post.hasOne(Comment);
      Comment.belongsTo(Post);

      await this.sequelize.sync();

      const post = await Post.create({
        title: 'Post title'
      });

      const comment = await Comment.create({
        text: 'OLD VALUE'
      });

      comment.text = 'UPDATED VALUE';
      await comment.setPost(post);
      expect(comment.text).to.equal('UPDATED VALUE');
    });

    it('should set the foreign key value without saving when using save: false', async function() {
      const Comment = this.sequelize.define('comment', {
        text: DataTypes.STRING
      });

      const Post = this.sequelize.define('post', {
        title: DataTypes.STRING
      });

      Post.hasMany(Comment, { foreignKey: 'post_id' });
      Comment.belongsTo(Post, { foreignKey: 'post_id' });

      await this.sequelize.sync({ force: true });
      const [post, comment] = await Promise.all([Post.create(), Comment.create()]);
      expect(comment.get('post_id')).not.to.be.ok;

      const setter = await comment.setPost(post, { save: false });

      expect(setter).to.be.undefined;
      expect(comment.get('post_id')).to.equal(post.get('id'));
      expect(comment.changed('post_id')).to.be.true;
    });

    it('supports setting same association twice', async function() {
      const Home = this.sequelize.define('home', {});
      const User = this.sequelize.define('user');

      Home.belongsTo(User);

      await this.sequelize.sync({ force: true });
      const [home, user] = await Promise.all([
        Home.create(),
        User.create()
      ]);
      await home.setUser(user);
      expect(await home.getUser()).to.have.property('id', user.id);
    });
  });

  describe('createAssociation', () => {
    it('creates an associated model instance', async function() {
      const User = this.sequelize.define('User', { username: DataTypes.STRING }),
        Task = this.sequelize.define('Task', { title: DataTypes.STRING });

      Task.belongsTo(User);

      await this.sequelize.sync({ force: true });
      const task = await Task.create({ title: 'task' });
      const user = await task.createUser({ username: 'bob' });
      expect(user).not.to.be.null;
      expect(user.username).to.equal('bob');
    });

    if (current.dialect.supports.transactions) {
      it('supports transactions', async function() {
        const sequelize = await Support.prepareTransactionTest(this.sequelize);
        const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
          Group = sequelize.define('Group', { name: Support.Sequelize.STRING });

        Group.belongsTo(User);

        await sequelize.sync({ force: true });
        const group = await Group.create({ name: 'bar' });
        const t = await sequelize.transaction();
        await group.createUser({ username: 'foo' }, { transaction: t });
        const user = await group.getUser();
        expect(user).to.be.null;

        const user0 = await group.getUser({ transaction: t });
        expect(user0).not.to.be.null;

        await t.rollback();
      });
    }
  });

  describe('foreign key', () => {
    it('should setup underscored field with foreign keys when using underscored', function() {
      const User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: true }),
        Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: true });

      User.belongsTo(Account);

      expect(User.rawAttributes.AccountId).to.exist;
      expect(User.rawAttributes.AccountId.field).to.equal('account_id');
    });

    it('should use model name when using camelcase', function() {
      const User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: false }),
        Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: false });

      User.belongsTo(Account);

      expect(User.rawAttributes.AccountId).to.exist;
      expect(User.rawAttributes.AccountId.field).to.equal('AccountId');
    });

    it('should support specifying the field of a foreign key', async function() {
      const User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: false }),
        Account = this.sequelize.define('Account', { title: Sequelize.STRING }, { underscored: false });

      User.belongsTo(Account, {
        foreignKey: {
          name: 'AccountId',
          field: 'account_id'
        }
      });

      expect(User.rawAttributes.AccountId).to.exist;
      expect(User.rawAttributes.AccountId.field).to.equal('account_id');

      await Account.sync({ force: true });
      // Can't use Promise.all cause of foreign key references
      await User.sync({ force: true });

      const [user1, account] = await Promise.all([
        User.create({ username: 'foo' }),
        Account.create({ title: 'pepsico' })
      ]);

      await user1.setAccount(account);
      const user0 = await user1.getAccount();
      expect(user0).to.not.be.null;

      const user = await User.findOne({
        where: { username: 'foo' },
        include: [Account]
      });

      // the sql query should correctly look at account_id instead of AccountId
      expect(user.Account).to.exist;
    });

    it('should set foreignKey on foreign table', async function() {
      const Mail = this.sequelize.define('mail', {}, { timestamps: false });
      const Entry = this.sequelize.define('entry', {}, { timestamps: false });
      const User = this.sequelize.define('user', {}, { timestamps: false });

      Entry.belongsTo(User, {
        as: 'owner',
        foreignKey: {
          name: 'ownerId',
          allowNull: false
        }
      });
      Entry.belongsTo(Mail, {
        as: 'mail',
        foreignKey: {
          name: 'mailId',
          allowNull: false
        }
      });
      Mail.belongsToMany(User, {
        as: 'recipients',
        through: 'MailRecipients',
        otherKey: {
          name: 'recipientId',
          allowNull: false
        },
        foreignKey: {
          name: 'mailId',
          allowNull: false
        },
        timestamps: false
      });
      Mail.hasMany(Entry, {
        as: 'entries',
        foreignKey: {
          name: 'mailId',
          allowNull: false
        }
      });
      User.hasMany(Entry, {
        as: 'entries',
        foreignKey: {
          name: 'ownerId',
          allowNull: false
        }
      });

      await this.sequelize.sync({ force: true });
      await User.create({});
      const mail = await Mail.create({});
      await Entry.create({ mailId: mail.id, ownerId: 1 });
      await Entry.create({ mailId: mail.id, ownerId: 1 });
      // set recipients
      await mail.setRecipients([1]);

      const result = await Entry.findAndCountAll({
        offset: 0,
        limit: 10,
        order: [['id', 'DESC']],
        include: [
          {
            association: Entry.associations.mail,
            include: [
              {
                association: Mail.associations.recipients,
                through: {
                  where: {
                    recipientId: 1
                  }
                },
                required: true
              }
            ],
            required: true
          }
        ]
      });

      expect(result.count).to.equal(2);
      expect(result.rows[0].get({ plain: true })).to.deep.equal(
        {
          id: 2,
          ownerId: 1,
          mailId: 1,
          mail: {
            id: 1,
            recipients: [{
              id: 1,
              MailRecipients: {
                mailId: 1,
                recipientId: 1
              }
            }]
          }
        }
      );
    });
  });

  describe('foreign key constraints', () => {
    it('are enabled by default', async function() {
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
        User = this.sequelize.define('User', { username: DataTypes.STRING });

      Task.belongsTo(User); // defaults to SET NULL

      await this.sequelize.sync({ force: true });

      const user = await User.create({ username: 'foo' });
      const task = await Task.create({ title: 'task' });
      await task.setUser(user);
      await user.destroy();
      await task.reload();
      expect(task.UserId).to.equal(null);
    });

    it('sets to NO ACTION if allowNull: false', async function() {
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
        User = this.sequelize.define('User', { username: DataTypes.STRING });

      Task.belongsTo(User, { foreignKey: { allowNull: false } }); // defaults to NO ACTION

      await this.sequelize.sync({ force: true });

      const user = await User.create({ username: 'foo' });
      await Task.create({ title: 'task', UserId: user.id });
      await expect(user.destroy()).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
      const tasks = await Task.findAll();
      expect(tasks).to.have.length(1);
    });

    it('should be possible to disable them', async function() {
      const Task = this.sequelize.define('Task', { title: Sequelize.STRING }),
        User = this.sequelize.define('User', { username: Sequelize.STRING });

      Task.belongsTo(User, { constraints: false });

      await this.sequelize.sync({ force: true });
      const user = await User.create({ username: 'foo' });
      const task = await Task.create({ title: 'task' });
      await task.setUser(user);
      await user.destroy();
      await task.reload();
      expect(task.UserId).to.equal(user.id);
    });

    it('can cascade deletes', async function() {
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
        User = this.sequelize.define('User', { username: DataTypes.STRING });

      Task.belongsTo(User, { onDelete: 'cascade' });

      await this.sequelize.sync({ force: true });
      const user = await User.create({ username: 'foo' });
      const task = await Task.create({ title: 'task' });
      await task.setUser(user);
      await user.destroy();
      const tasks = await Task.findAll();
      expect(tasks).to.have.length(0);
    });

    if (current.dialect.supports.constraints.restrict) {
      it('can restrict deletes', async function() {
        const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
          User = this.sequelize.define('User', { username: DataTypes.STRING });

        Task.belongsTo(User, { onDelete: 'restrict' });

        await this.sequelize.sync({ force: true });
        const user = await User.create({ username: 'foo' });
        const task = await Task.create({ title: 'task' });
        await task.setUser(user);
        await expect(user.destroy()).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
        const tasks = await Task.findAll();
        expect(tasks).to.have.length(1);
      });

      it('can restrict updates', async function() {
        const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
          User = this.sequelize.define('User', { username: DataTypes.STRING });

        Task.belongsTo(User, { onUpdate: 'restrict' });

        await this.sequelize.sync({ force: true });
        const user = await User.create({ username: 'foo' });
        const task = await Task.create({ title: 'task' });
        await task.setUser(user);

        // Changing the id of a DAO requires a little dance since
        // the `UPDATE` query generated by `save()` uses `id` in the
        // `WHERE` clause

        const tableName = user.sequelize.getQueryInterface().queryGenerator.addSchema(user.constructor);

        await expect(
          user.sequelize.getQueryInterface().update(user, tableName, { id: 999 }, { id: user.id })
        ).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);

        // Should fail due to FK restriction
        const tasks = await Task.findAll();

        expect(tasks).to.have.length(1);
      });
    }

    // NOTE: mssql does not support changing an autoincrement primary key
    if (Support.getTestDialect() !== 'mssql') {
      it('can cascade updates', async function() {
        const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
          User = this.sequelize.define('User', { username: DataTypes.STRING });

        Task.belongsTo(User, { onUpdate: 'cascade' });

        await this.sequelize.sync({ force: true });
        const user = await User.create({ username: 'foo' });
        const task = await Task.create({ title: 'task' });
        await task.setUser(user);

        // Changing the id of a DAO requires a little dance since
        // the `UPDATE` query generated by `save()` uses `id` in the
        // `WHERE` clause

        const tableName = user.sequelize.getQueryInterface().queryGenerator.addSchema(user.constructor);
        await user.sequelize.getQueryInterface().update(user, tableName, { id: 999 }, { id: user.id });
        const tasks = await Task.findAll();
        expect(tasks).to.have.length(1);
        expect(tasks[0].UserId).to.equal(999);
      });
    }
  });

  describe('association column', () => {
    it('has correct type and name for non-id primary keys with non-integer type', async function() {
      const User = this.sequelize.define('UserPKBT', {
        username: {
          type: DataTypes.STRING
        }
      });

      const Group = this.sequelize.define('GroupPKBT', {
        name: {
          type: DataTypes.STRING,
          primaryKey: true
        }
      });

      User.belongsTo(Group);

      await this.sequelize.sync({ force: true });
      expect(User.rawAttributes.GroupPKBTName.type).to.an.instanceof(DataTypes.STRING);
    });

    it('should support a non-primary key as the association column on a target without a primary key', async function() {
      const User = this.sequelize.define('User', { username: { type: DataTypes.STRING, unique: true } });
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING });

      User.removeAttribute('id');
      Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });

      await this.sequelize.sync({ force: true });
      const newUser = await User.create({ username: 'bob' });
      const newTask = await Task.create({ title: 'some task' });
      await newTask.setUser(newUser);
      const foundTask = await Task.findOne({ where: { title: 'some task' } });
      const foundUser = await foundTask.getUser();
      await expect(foundUser.username).to.equal('bob');
      const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
      expect(foreignKeysDescriptions[0]).to.includes({
        referencedColumnName: 'username',
        referencedTableName: 'Users',
        columnName: 'user_name'
      });
    });

    it('should support a non-primary unique key as the association column', async function() {
      const User = this.sequelize.define('User', {
        username: {
          type: DataTypes.STRING,
          field: 'user_name',
          unique: true
        }
      });
      const Task = this.sequelize.define('Task', {
        title: DataTypes.STRING
      });

      Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });

      await this.sequelize.sync({ force: true });
      const newUser = await User.create({ username: 'bob' });
      const newTask = await Task.create({ title: 'some task' });
      await newTask.setUser(newUser);
      const foundTask = await Task.findOne({ where: { title: 'some task' } });
      const foundUser = await foundTask.getUser();
      await expect(foundUser.username).to.equal('bob');
      const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
      expect(foreignKeysDescriptions[0]).to.includes({
        referencedColumnName: 'user_name',
        referencedTableName: 'Users',
        columnName: 'user_name'
      });
    });

    it('should support a non-primary key as the association column with a field option', async function() {
      const User = this.sequelize.define('User', {
        username: {
          type: DataTypes.STRING,
          field: 'the_user_name_field',
          unique: true
        }
      });
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING });

      User.removeAttribute('id');
      Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });

      await this.sequelize.sync({ force: true });
      const newUser = await User.create({ username: 'bob' });
      const newTask = await Task.create({ title: 'some task' });
      await newTask.setUser(newUser);
      const foundTask = await Task.findOne({ where: { title: 'some task' } });
      const foundUser = await foundTask.getUser();
      await expect(foundUser.username).to.equal('bob');
      const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
      expect(foreignKeysDescriptions[0]).to.includes({
        referencedColumnName: 'the_user_name_field',
        referencedTableName: 'Users',
        columnName: 'user_name'
      });
    });

    it('should support a non-primary key as the association column in a table with a composite primary key', async function() {
      const User = this.sequelize.define('User', {
        username: {
          type: DataTypes.STRING,
          field: 'the_user_name_field',
          unique: true
        },
        age: {
          type: DataTypes.INTEGER,
          field: 'the_user_age_field',
          primaryKey: true
        },
        weight: {
          type: DataTypes.INTEGER,
          field: 'the_user_weight_field',
          primaryKey: true
        }
      });
      const Task = this.sequelize.define('Task', { title: DataTypes.STRING });

      Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });

      await this.sequelize.sync({ force: true });
      const newUser = await User.create({ username: 'bob', age: 18, weight: 40 });
      const newTask = await Task.create({ title: 'some task' });
      await newTask.setUser(newUser);
      const foundTask = await Task.findOne({ where: { title: 'some task' } });
      const foundUser = await foundTask.getUser();
      await expect(foundUser.username).to.equal('bob');
      const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
      expect(foreignKeysDescriptions[0]).to.includes({
        referencedColumnName: 'the_user_name_field',
        referencedTableName: 'Users',
        columnName: 'user_name'
      });
    });
  });

  describe('association options', () => {
    it('can specify data type for auto-generated relational keys', async function() {
      const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
        dataTypes = [DataTypes.INTEGER, DataTypes.BIGINT, DataTypes.STRING],
        Tasks = {};

      dataTypes.forEach(dataType => {
        const tableName = `TaskXYZ_${dataType.key}`;
        Tasks[dataType] = this.sequelize.define(tableName, { title: DataTypes.STRING });
        Tasks[dataType].belongsTo(User, { foreignKey: 'userId', keyType: dataType, constraints: false });
      });

      await this.sequelize.sync({ force: true });
      dataTypes.forEach(dataType => {
        expect(Tasks[dataType].rawAttributes.userId.type).to.be.an.instanceof(dataType);
      });
    });

    describe('allows the user to provide an attribute definition object as foreignKey', () => {
      it('works with a column that hasnt been defined before', function() {
        const Task = this.sequelize.define('task', {}),
          User = this.sequelize.define('user', {});

        Task.belongsTo(User, {
          foreignKey: {
            allowNull: false,
            name: 'uid'
          }
        });

        expect(Task.rawAttributes.uid).to.be.ok;
        expect(Task.rawAttributes.uid.allowNull).to.be.false;
        expect(Task.rawAttributes.uid.references.model).to.equal(User.getTableName());
        expect(Task.rawAttributes.uid.references.key).to.equal('id');
      });

      it('works when taking a column directly from the object', function() {
        const User = this.sequelize.define('user', {
            uid: {
              type: Sequelize.INTEGER,
              primaryKey: true
            }
          }),
          Profile = this.sequelize.define('project', {
            user_id: {
              type: Sequelize.INTEGER,
              allowNull: false
            }
          });

        Profile.belongsTo(User, { foreignKey: Profile.rawAttributes.user_id });

        expect(Profile.rawAttributes.user_id).to.be.ok;
        expect(Profile.rawAttributes.user_id.references.model).to.equal(User.getTableName());
        expect(Profile.rawAttributes.user_id.references.key).to.equal('uid');
        expect(Profile.rawAttributes.user_id.allowNull).to.be.false;
      });

      it('works when merging with an existing definition', function() {
        const Task = this.sequelize.define('task', {
            projectId: {
              defaultValue: 42,
              type: Sequelize.INTEGER
            }
          }),
          Project = this.sequelize.define('project', {});

        Task.belongsTo(Project, { foreignKey: { allowNull: true } });

        expect(Task.rawAttributes.projectId).to.be.ok;
        expect(Task.rawAttributes.projectId.defaultValue).to.equal(42);
        expect(Task.rawAttributes.projectId.allowNull).to.be.ok;
      });
    });

    it('should throw an error if foreignKey and as result in a name clash', function() {
      const Person = this.sequelize.define('person', {}),
        Car = this.sequelize.define('car', {});

      expect(Car.belongsTo.bind(Car, Person, { foreignKey: 'person' })).to
        .throw('Naming collision between attribute \'person\' and association \'person\' on model car. To remedy this, change either foreignKey or as in your association definition');
    });

    it('should throw an error if an association clashes with the name of an already define attribute', function() {
      const Person = this.sequelize.define('person', {}),
        Car = this.sequelize.define('car', {
          person: Sequelize.INTEGER
        });

      expect(Car.belongsTo.bind(Car, Person, { as: 'person' })).to
        .throw('Naming collision between attribute \'person\' and association \'person\' on model car. To remedy this, change either foreignKey or as in your association definition');
    });
  });

  describe('Eager loading', () => {
    beforeEach(function() {
      this.Individual = this.sequelize.define('individual', {
        name: Sequelize.STRING
      });
      this.Hat = this.sequelize.define('hat', {
        name: Sequelize.STRING
      });
      this.Individual.belongsTo(this.Hat, {
        as: 'personwearinghat'
      });
    });

    it('should load with an alias', async function() {
      await this.sequelize.sync({ force: true });

      const [individual1, hat] = await Promise.all([
        this.Individual.create({ name: 'Foo Bar' }),
        this.Hat.create({ name: 'Baz' })
      ]);

      await individual1.setPersonwearinghat(hat);

      const individual0 = await this.Individual.findOne({
        where: { name: 'Foo Bar' },
        include: [{ model: this.Hat, as: 'personwearinghat' }]
      });

      expect(individual0.name).to.equal('Foo Bar');
      expect(individual0.personwearinghat.name).to.equal('Baz');

      const individual = await this.Individual.findOne({
        where: { name: 'Foo Bar' },
        include: [{
          model: this.Hat,
          as: { singular: 'personwearinghat' }
        }]
      });

      expect(individual.name).to.equal('Foo Bar');
      expect(individual.personwearinghat.name).to.equal('Baz');
    });

    it('should load all', async function() {
      await this.sequelize.sync({ force: true });

      const [individual0, hat] = await Promise.all([
        this.Individual.create({ name: 'Foo Bar' }),
        this.Hat.create({ name: 'Baz' })
      ]);

      await individual0.setPersonwearinghat(hat);

      const individual = await this.Individual.findOne({
        where: { name: 'Foo Bar' },
        include: [{ all: true }]
      });

      expect(individual.name).to.equal('Foo Bar');
      expect(individual.personwearinghat.name).to.equal('Baz');
    });
  });
});


text:
#include <aws/gamelift/model/SearchGameSessionsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

SearchGameSessionsRequest::SearchGameSessionsRequest() :
    m_fleetIdHasBeenSet(false),
    m_aliasIdHasBeenSet(false),
    m_filterExpressionHasBeenSet(false),
    m_sortExpressionHasBeenSet(false),
    m_limit(0),
    m_limitHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String SearchGameSessionsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_fleetIdHasBeenSet)
  {
   payload.WithString("FleetId", m_fleetId);

  }

  if(m_aliasIdHasBeenSet)
  {
   payload.WithString("AliasId", m_aliasId);

  }

  if(m_filterExpressionHasBeenSet)
  {
   payload.WithString("FilterExpression", m_filterExpression);

  }

  if(m_sortExpressionHasBeenSet)
  {
   payload.WithString("SortExpression", m_sortExpression);

  }

  if(m_limitHasBeenSet)
  {
   payload.WithInteger("Limit", m_limit);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection SearchGameSessionsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.SearchGameSessions"));
  return headers;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ZfrLightspeedRetailTest;

use PHPUnit\Framework\TestCase;
use ZfrLightspeedRetail\Filter;

/**
 * @author Daniel Gimenes
 */
final class FilterTest extends TestCase
{
    public function testNormalizesEmptyCollection()
    {
        $this->assertSame([], Filter::normalizeCollection([]));
    }

    public function testNormalizesCollectionWithASingleItem()
    {
        $this->assertSame([
            ['foo' => 'bar'],
        ], Filter::normalizeCollection([
            'foo' => 'bar',
        ]));
    }

    public function testNormalizesCollectionWithMultipleItems()
    {
        $this->assertSame([
            ['foo' => 'bar'],
            ['baz' => 'bat'],
        ], Filter::normalizeCollection([
            ['foo' => 'bar'],
            ['baz' => 'bat'],
        ]));
    }
}


text:
package net.sf.relish.web;

import static org.junit.Assert.*;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HttpRequestDataTest {

	@Test
	public void assertAllPublicMethodsSynchronized() {

		for (Method method : HttpRequestData.class.getMethods()) {
			if (method.getDeclaringClass() != Object.class) {
				assertTrue("Method is not synchronized: " + method, Modifier.isSynchronized(method.getModifiers()));
			}
		}
	}
}


text:
/**
 * Created by qbl on 2015/10/9.
 */
require(['app'],function(app){
    app.constant("provinceURL","/city/province");
    app.constant("tubeURL","../JSON/attribute.json");
    app.constant("propURL","../JSON/prop.json");
    app.constant("type2","../JSON/areali_1.json");
    app.constant("type4","../JSON/areali_2.json");
    app.constant("type6","../JSON/areali_3.json");
    app.constant("type1","../JSON/areawen_1.json");
    app.constant("type3","../JSON/areawen_2.json");
    app.constant("type5","../JSON/areawen_3.json");
    app.constant("type8","../JSON/areagl_1.json");
    app.constant("type7","../JSON/areagw_1.json");
    app.controller("wishTabCtr-attr",['$rootScope','$scope',"$timeout",'$location',"ZYBinfoDATA","provinceURL","propURL","AJAX","tubeURL","loadClickEvent","loadDblclickEvent","loadClickAll","loadClickCancle","loadCancleAll",'type1','type2','type3','type4','type5','type6','type7','type8',function($rootScope,$scope,$timeout,$location,ZYBinfoDATA,provinceURL,propURL,AJAX,tubeURL,loadClickEvent,loadDblclickEvent,loadClickAll,loadClickCancle,loadCancleAll,type1,type2,type3,type4,type5,type6,type7,type8){

            $scope.attr = ZYBinfoDATA;
            $scope.area = "";
            $scope.areaArr = [];
            $scope.style = "";
            $scope.attribute = "";
            $scope.belongs = "";
            $scope.tube = "";
            $scope.isShowProperty = false;
            $scope.screening = true;
            $scope.btnStyle = true;
            $scope.isClick = 0;
            $scope.zyb = {
                city_name: [],//优先地区名称
                style_name: [],//院校分类
                attr_name: [],//办学性质
                belongs_name: [],//属管,
                prop_name: [],//院校特色
            };

            init();

            function init(){
                var num = $location.$$search.type == true ? 1 :$location.$$search.type;
                var url = "";

                if(num == 1){
                    url = type1;
                }else if (num == 2){
                    url = type2;
                }else if (num == 3){
                    url = type3;
                }else if (num == 4){
                    url = type4;
                }else if(num == 5){
                    url = type5;
                }else if (num == 6){
                    url = type6;
                }else if (num == 7){
                    url = type7;
                }else {
                    url = type8;
                }

                AJAX.getRequest(url,'GET',"")
                    .success(function(data,status){
                        $scope.area = data;
                    });

                AJAX.getRequest(propURL,'GET',"")
                    .success(function(data,status){
                        var list = data.response;
                        var arr_style = [],arr_attr=[],attr_belongs=[];
                        for (var i = 0; i < list.length; i++) {
                            if(list[i].type == 0){
                                arr_style.push(list[i]);
                            }else if(list[i].type == 2){
                                arr_attr.push(list[i]);
                            }else if(list[i].type == 1){
                                attr_belongs.push(list[i]);
                            }
                        }
                        arr_style.join(',');
                        arr_attr.join(',');
                        attr_belongs.join(',')
                        $scope.style = arr_style;
                        $scope.attribute = arr_attr;
                        $scope.belongs = attr_belongs;
                    });

                AJAX.getRequest(tubeURL,'GET',"")
                    .success(function(data,status){
                        var list = data.response;
                        var tube_list = [];
                        for(var i = 0; i< list.length;i++){
                            if($scope.attr.u_level == 3){
                                if(list[i].type == 2){
                                    tube_list.push(list[i]);
                                }
                            }else{
                                if(list[i].type == 1){
                                    tube_list.push(list[i]);
                                }
                            }

                        }
                        tube_list.join(',');
                        $scope.tube = tube_list ;
                    });

                //TODO new  加载内容 二期

                $scope.clickScreen = function(isTrue){
                    $scope.screening = isTrue;
                }
            }

            var TimeFn = null;

            /**
             * 1同意
             * 0取消
             * 2取消拒绝
             * */
            $scope.clickCity = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                TimeFn = $timeout(function(){
                    var target = $event.target,
                        state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                    $scope.isClick = 1;

                    loadClickEvent.clickEvent(target,state,then,id,$scope.attr.city_ignore,$scope.attr.city_prefer,$scope.zyb.city_name);
                },400);
            }

            $scope.clickStyle = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                TimeFn = $timeout(function(){
                    var target = $event.target,
                        state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');
                    loadClickEvent.clickEvent(target,state,then,id,$scope.attr.style_ignore,$scope.attr.style_prefer,$scope.zyb.style_name);
                },400);
            }

            $scope.clickAttr = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                TimeFn = $timeout(function(){
                    var target = $event.target,
                        state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');
                    loadClickEvent.clickEvent(target,state,then,id,$scope.attr.attr_ignore,$scope.attr.attr_prefer,$scope.zyb.attr_name);
                },400);
            }

            $scope.clickBelongs = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                TimeFn = $timeout(function(){
                    var target = $event.target,
                        state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');
                    loadClickEvent.clickEvent(target,state,then,id,$scope.attr.belongs_ignore,$scope.attr.belongs_prefer,$scope.zyb.belongs_name);
                },400);
            }

            $scope.clickProp = function($event,id,type){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                TimeFn = $timeout(function(){
                    var target = $event.target,
                        state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                    if(state == 2){
                        propState(false,id,type);
                        $scope.zyb.prop_name.splice($.inArray(then,$scope.zyb.prop_name),1);
                        $(target).attr('state',0).removeClass().addClass("btn btn-sm btn-default");
                    }else if (state == 1){
                        propState(false,id,type);
                        $scope.zyb.prop_name.splice($.inArray(then,$scope.zyb.prop_name),1);
                        $(target).attr('state',0).removeClass().addClass("btn btn-sm btn-default");
                    }else {
                        propState(true,id,type);
                        $scope.zyb.prop_name.push(then);
                        $(target).attr('state',1).removeClass().addClass("btn btn-sm btn-success");
                    }
                },400);
            }

            /**
             * 修改prop状态
             * ture or false
             * */
            function propState(isTrue,id,type){
                if (type == 1) {
                    if (id == 0) {
                        $scope.attr.prop7 = isTrue;
                    } else if (id == 1) {
                        $scope.attr.prop3 = isTrue;
                    } else if (id == 2) {
                        $scope.attr.prop4 = isTrue;
                    } else if (id == 24) {
                        $scope.attr.prop8 = isTrue;
                    }
                } else {
                    if (id == 1) {
                        $scope.attr.level1 = isTrue;
                    } else if (id == 2) {
                        $scope.attr.level2 = isTrue;
                    }
                }
            }

            /**
             * 2拒绝
             **/
            $scope.dblclickCity = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                var target = $event.target,
                    state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                loadDblclickEvent.dblclickEvent(target,state,then,id,$scope.attr.city_ignore,$scope.attr.city_prefer,$scope.zyb.city_name);
            }

            $scope.dblclickStyle = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                var target = $event.target,
                    state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                loadDblclickEvent.dblclickEvent(target,state,then,id,$scope.attr.style_ignore,$scope.attr.style_prefer,$scope.zyb.style_name);

            }

            $scope.dblclickAttr = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                var target = $event.target,
                    state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                loadDblclickEvent.dblclickEvent(target,state,then,id,$scope.attr.attr_ignore,$scope.attr.attr_prefer,$scope.zyb.attr_name);

            }

            $scope.dblclickBelongs = function($event,id){
                var then = this.list.name;
                $timeout.cancel(TimeFn);
                var target = $event.target,
                    state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                loadDblclickEvent.dblclickEvent(target,state,then,id,$scope.attr.belongs_ignore,$scope.attr.belongs_prefer,$scope.zyb.belongs_name);

            }

            $scope.dblclickProp = function($event,id,type){
                var then = this.list.name;
                $timeout.cancel(TimeFn);

                var target = $event.target,
                    state = $(target).attr('state') == undefined ? 0 : $(target).attr('state');

                if(state == 2){
                    propState(false,id,type);
                    $(target).attr('state',0).removeClass().addClass("btn btn-sm btn-default");
                }else if (state == 1){
                    propState(false,id,type);
                    $scope.zyb.prop_name.splice($.inArray(then,$scope.zyb.prop_name),1);
                    $(target).attr('state',2).removeClass().addClass("btn btn-sm btn-danger");
                }else {
                    propState(false,id,type);
                    $(target).attr('state',2).removeClass().addClass("btn btn-sm btn-danger");
                }

            }

            $scope.allCity = function(provinceId){
                var arr = $("button[province="+provinceId+"]");
                loadClickAll.all(arr,$scope.attr.city_prefer,'city',$scope.zyb.city_name);
            }

            $scope.allStyle = function(){
                var arr = $('button[style]');
                loadClickAll.all(arr,$scope.attr.style_prefer,'style',$scope.zyb.style_name)
            }

            $scope.allAttr = function(){
                var arr = $('button[attr]');
                loadClickAll.all(arr,$scope.attr.attr_prefer,'attr',$scope.zyb.attr_name)
            }

            $scope.allBelongs = function(){
                var arr = $('button[belongs]');
                loadClickAll.all(arr,$scope.attr.attr_prefer,'belongs',$scope.zyb.attr_name)
            }

            $scope.allProp = function(){
                var arr = $('button[prop]');
                loadClickAll.all(arr,"",'prop',$scope.zyb.prop_name,1);
            }

            function all(arr,prefer,name,type){
                if(type ==undefined){
                    for(var i = 0; i< arr.length;i++){
                        if(arr.eq(i).attr('state')!=1){
                            arr.eq(i).attr('state',1).removeClass().addClass("btn btn-sm btn-success");
                            prefer.push(arr.eq(i).attr('city'));
                            name.push(arr.eq(i).html());
                        }
                    }
                }else{
                    for(var i = 0; i< arr.length;i++){
                        if(arr.eq(i).attr('state')!=1){
                            arr.eq(i).attr('state',1).removeClass().addClass("btn btn-sm btn-success");
                            if(arr.eq(i).attr('prop') == "prop3"){
                                $scope.attr.prop3 = true;
                            }else if(arr.eq(i).attr('prop') == "prop4"){
                                $scope.attr.prop4 = true;
                            }else if(arr.eq(i).attr('prop') == "prop7"){
                                $scope.attr.prop7 = true;
                            }else if (arr.eq(i).attr('prop') == "prop8"){
                                $scope.attr.prop8 = true;
                            }else if (arr.eq(i).attr('prop') == "level1"){
                                $scope.attr.level1 = true;
                            }else if (arr.eq(i).attr('prop') == "level2"){
                                $scope.attr.level2 = true;
                            }
                            name.push(arr.eq(i).html());
                        }
                    }
                }

            }

            $scope.cancleCity = function(provinceId){
                var arr = $("button[province="+provinceId+"]");
                loadClickCancle.reject(arr,$scope.attr.city_ignore,$scope.attr.city_prefer,'city',$scope.zyb.city_name);
            }

            $scope.cancleStyle = function(){
                var arr = $('button[style]');
                loadClickCancle.reject(arr,$scope.attr.style_ignore,$scope.attr.style_prefer,'style',$scope.zyb.style_name);
            }

            $scope.cancleAttr = function(){
                var arr = $('button[attr]');
                loadClickCancle.reject(arr,$scope.attr.attr_ignore,$scope.attr.attr_prefer,'attr',$scope.zyb.attr_name);
            }

            $scope.cancleBelongs = function(){
                var arr = $('button[Belongs]');
                loadClickCancle.reject(arr,$scope.attr.belongs_ignore,$scope.attr.belongs_prefer,'belongs',$scope.zyb.attr_name);
            }

            $scope.cancleProp = function(){
                var arr = $('button[economy]');
                loadClickCancle.reject(arr,"","",'economy',$scope.zyb.prop_name,1);
            }

            $scope.cancleAll = function(){
                loadCancleAll.cancleAll($scope.attr.city_prefer,$scope.attr.city_ignore,$scope.area,'city')
            }

        }]);
})


text:
package com.gdn.x.beirut.dto.request;

import com.gdn.common.web.base.BaseRequest;

public class CandidatesPositionDTOWrapper extends BaseRequest {

  private static final long serialVersionUID = 1188398673210252295L;
  // HAPUS
}


text:
"""Definition of various recurrent neural network layers."""
from __future__ import print_function

from ... import ndarray
from ..nn import Block
from . import rnn_cell

class _RNNLayer(Block):
    """Implementation of recurrent layers."""
    def __init__(self, hidden_size, num_layers, layout,
                 dropout, bidirectional, input_size,
                 i2h_weight_initializer, h2h_weight_initializer,
                 i2h_bias_initializer, h2h_bias_initializer,
                 mode, **kwargs):
        super(_RNNLayer, self).__init__(**kwargs)
        assert layout == 'TNC' or layout == 'NTC', \
            "Invalid layout %s; must be one of ['TNC' or 'NTC']"%layout
        self._hidden_size = hidden_size
        self._num_layers = num_layers
        self._mode = mode
        self._layout = layout
        self._dropout = dropout
        self._dir = 2 if bidirectional else 1
        self._input_size = input_size
        self._i2h_weight_initializer = i2h_weight_initializer
        self._h2h_weight_initializer = h2h_weight_initializer
        self._i2h_bias_initializer = i2h_bias_initializer
        self._h2h_bias_initializer = h2h_bias_initializer

        self._gates = {'rnn_relu': 1, 'rnn_tanh': 1, 'lstm': 4, 'gru': 3}[mode]

        self.i2h_weight = []
        self.h2h_weight = []
        self.i2h_bias = []
        self.h2h_bias = []

        ng, ni, nh = self._gates, input_size, hidden_size
        for i in range(num_layers):
            for j in (['l', 'r'] if self._dir == 2 else ['l']):
                self.i2h_weight.append(
                    self.params.get('%s%d_i2h_weight'%(j, i), shape=(ng*nh, ni),
                                    init=i2h_weight_initializer,
                                    allow_deferred_init=True))
                self.h2h_weight.append(
                    self.params.get('%s%d_h2h_weight'%(j, i), shape=(ng*nh, nh),
                                    init=h2h_weight_initializer,
                                    allow_deferred_init=True))
                self.i2h_bias.append(
                    self.params.get('%s%d_i2h_bias'%(j, i), shape=(ng*nh,),
                                    init=i2h_bias_initializer,
                                    allow_deferred_init=True))
                self.h2h_bias.append(
                    self.params.get('%s%d_h2h_bias'%(j, i), shape=(ng*nh,),
                                    init=h2h_bias_initializer,
                                    allow_deferred_init=True))
            ni = nh * self._dir

        self._unfused = self._unfuse()

    def __repr__(self):
        s = '{name}({mapping}, {_layout}'
        if self._num_layers != 1:
            s += ', num_layers={_num_layers}'
        if self._dropout != 0:
            s += ', dropout={_dropout}'
        if self._dir == 2:
            s += ', bidirectional'
        s += ')'
        mapping = ('{_input_size} -> {_hidden_size}'.format(**self.__dict__) if self._input_size
                   else self._hidden_size)
        return s.format(name=self.__class__.__name__,
                        mapping=mapping,
                        **self.__dict__)

    def state_info(self, batch_size=0):
        raise NotImplementedError

    def _unfuse(self):
        """Unfuses the fused RNN in to a stack of rnn cells."""
        get_cell = {'rnn_relu': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size,
                                                                  activation='relu',
                                                                  **kwargs),
                    'rnn_tanh': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size,
                                                                  activation='tanh',
                                                                  **kwargs),
                    'lstm': lambda **kwargs: rnn_cell.LSTMCell(self._hidden_size,
                                                               **kwargs),
                    'gru': lambda **kwargs: rnn_cell.GRUCell(self._hidden_size,
                                                             **kwargs)}[self._mode]

        stack = rnn_cell.SequentialRNNCell(prefix=self.prefix, params=self.params)
        with stack.name_scope():
            ni = self._input_size
            for i in range(self._num_layers):
                kwargs = {'input_size': ni,
                          'i2h_weight_initializer': self._i2h_weight_initializer,
                          'h2h_weight_initializer': self._h2h_weight_initializer,
                          'i2h_bias_initializer': self._i2h_bias_initializer,
                          'h2h_bias_initializer': self._h2h_bias_initializer}
                if self._dir == 2:
                    stack.add(rnn_cell.BidirectionalCell(
                        get_cell(prefix='l%d_'%i, **kwargs),
                        get_cell(prefix='r%d_'%i, **kwargs)))
                else:
                    stack.add(get_cell(prefix='l%d_'%i, **kwargs))

                if self._dropout > 0 and i != self._num_layers - 1:
                    stack.add(rnn_cell.DropoutCell(self._dropout))

                ni = self._hidden_size * self._dir

        return stack

    def begin_state(self, batch_size=0, func=ndarray.zeros, **kwargs):
        """Initial state for this cell.

        Parameters
        ----------
        batch_size: int
            Only required for `NDArray` API. Size of the batch ('N' in layout).
            Dimension of the input.
        func : callable, default `symbol.zeros`
            Function for creating initial state.

            For Symbol API, func can be `symbol.zeros`, `symbol.uniform`,
            `symbol.var` etc. Use `symbol.var` if you want to directly
            feed input as states.

            For NDArray API, func can be `ndarray.zeros`, `ndarray.ones`, etc.

        **kwargs :
            Additional keyword arguments passed to func. For example
            `mean`, `std`, `dtype`, etc.

        Returns
        -------
        states : nested list of Symbol
            Starting states for the first RNN step.
        """
        states = []
        for i, info in enumerate(self.state_info(batch_size)):
            if info is not None:
                info.update(kwargs)
            else:
                info = kwargs
            states.append(func(name='%sh0_%d'%(self.prefix, i), **info))
        return states

    def forward(self, inputs, states):
        if isinstance(states, ndarray.NDArray):
            states = [states]
        batch_size = states[0].shape[self._layout.find('N')]
        for state, info in zip(states, self.state_info(batch_size)):
            if state.shape != info['shape']:
                raise ValueError(
                    "Invalid recurrent state shape. Expecting %s, got %s."%(
                        str(info['shape']), str(state.shape)))
        if self._input_size == 0:
            for i in range(self._dir):
                self.i2h_weight[i].shape = (self._gates*self._hidden_size, inputs.shape[2])
                self.i2h_weight[i]._finish_deferred_init()
        if inputs.context.device_type == 'gpu':
            return self._forward_gpu(inputs, states)
        return self._forward_cpu(inputs, states)

    def _forward_cpu(self, inputs, states):
        ns = len(states)
        axis = self._layout.find('T')
        states = sum(zip(*((j for j in i) for i in states)), ())
        outputs, states = self._unfused.unroll(
            inputs.shape[axis], inputs, states,
            layout=self._layout, merge_outputs=True)
        new_states = []
        for i in range(ns):
            state = ndarray.concat(*(j.reshape((1,)+j.shape) for j in states[i::ns]), dim=0)
            new_states.append(state)

        return outputs, new_states

    def _forward_gpu(self, inputs, states):
        if self._layout == 'NTC':
            inputs = ndarray.swapaxes(inputs, dim1=0, dim2=1)
        ctx = inputs.context
        params = sum(zip(self.i2h_weight, self.h2h_weight), ())
        params += sum(zip(self.i2h_bias, self.h2h_bias), ())
        params = (i.data(ctx).reshape((-1,)) for i in params)
        params = ndarray.concat(*params, dim=0)

        rnn = ndarray.RNN(inputs, params, *states, state_size=self._hidden_size,
                          num_layers=self._num_layers, bidirectional=self._dir == 2,
                          p=self._dropout, state_outputs=True, mode=self._mode)

        if self._mode == 'lstm':
            outputs, states = rnn[0], [rnn[1], rnn[2]]
        else:
            outputs, states = rnn[0], [rnn[1]]

        if self._layout == 'NTC':
            outputs = ndarray.swapaxes(outputs, dim1=0, dim2=1)

        return outputs, states

class RNN(_RNNLayer):
    r"""Applies a multi-layer Elman RNN with `tanh` or `ReLU` non-linearity to an input sequence.

    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        h_t = \tanh(w_{ih} * x_t + b_{ih}  +  w_{hh} * h_{(t-1)} + b_{hh})

    where :math:`h_t` is the hidden state at time `t`, and :math:`x_t` is the hidden
    state of the previous layer at time `t` or :math:`input_t` for the first layer.
    If nonlinearity='relu', then `ReLU` is used instead of `tanh`.

    Parameters
    ----------
    hidden_size: int
        The number of features in the hidden state h.
    num_layers: int, default 1
        Number of recurrent layers.
    activation: {'relu' or 'tanh'}, default 'tanh'
        The activation function to use.
    layout : str, default 'TNC'
        The format of input and output tensors. T, N and C stand for
        sequence length, batch size, and feature dimensions respectively.
    dropout: float, default 0
        If non-zero, introduces a dropout layer on the outputs of each
        RNN layer except the last layer.
    bidirectional: bool, default False
        If `True`, becomes a bidirectional RNN.
    i2h_weight_initializer : str or Initializer
        Initializer for the input weights matrix, used for the linear
        transformation of the inputs.
    h2h_weight_initializer : str or Initializer
        Initializer for the recurrent weights matrix, used for the linear
        transformation of the recurrent state.
    i2h_bias_initializer : str or Initializer
        Initializer for the bias vector.
    h2h_bias_initializer : str or Initializer
        Initializer for the bias vector.
    input_size: int, default 0
        The number of expected features in the input x.
        If not specified, it will be inferred from input.
    prefix : str or None
        Prefix of this `Block`.
    params : ParameterDict or None
        Shared Parameters for this `Block`.

    Input shapes:
        The input shape depends on `layout`. For `layout='TNC'`, the
        input has shape `(sequence_length, batch_size, input_size)`

    Output shape:
        The output shape depends on `layout`. For `layout='TNC'`, the
        output has shape `(sequence_length, batch_size, num_hidden)`.
        If `bidirectional` is True, output shape will instead be
        `(sequence_length, batch_size, 2*num_hidden)`

    Recurrent state shape:
        The recurrent state's shape is `(num_layers, batch_size, num_hidden)`.
        If `bidirectional` is True, state shape will instead be
        `(num_layers, batch_size, 2*num_hidden)`

    Examples
    --------
    >>> layer = mx.gluon.rnn.RNN(100, 3)
    >>> layer.initialize()
    >>> input = mx.nd.random_uniform(shape=(5, 3, 10))
    >>> h0 = mx.nd.random_uniform(shape=(3, 3, 100))
    >>> output, hn = layer(input, h0)
    """
    def __init__(self, hidden_size, num_layers=1, activation='relu',
                 layout='TNC', dropout=0, bidirectional=False,
                 i2h_weight_initializer=None, h2h_weight_initializer=None,
                 i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
                 input_size=0, **kwargs):
        super(RNN, self).__init__(hidden_size, num_layers, layout,
                                  dropout, bidirectional, input_size,
                                  i2h_weight_initializer, h2h_weight_initializer,
                                  i2h_bias_initializer, h2h_bias_initializer,
                                  'rnn_'+activation, **kwargs)

    def state_info(self, batch_size=0):
        return [{'shape': (self._num_layers * self._dir, batch_size, self._hidden_size),
                 '__layout__': 'LNC'}]

class LSTM(_RNNLayer):
    r"""Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence.

    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        \begin{array}{ll}
        i_t = sigmoid(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\
        f_t = sigmoid(W_{if} x_t + b_{if} + W_{hf} h_{(t-1)} + b_{hf}) \\
        g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hc} h_{(t-1)} + b_{hg}) \\
        o_t = sigmoid(W_{io} x_t + b_{io} + W_{ho} h_{(t-1)} + b_{ho}) \\
        c_t = f_t * c_{(t-1)} + i_t * g_t \\
        h_t = o_t * \tanh(c_t)
        \end{array}

    where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the
    cell state at time `t`, :math:`x_t` is the hidden state of the previous
    layer at time `t` or :math:`input_t` for the first layer, and :math:`i_t`,
    :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and
    out gates, respectively.

    Parameters
    ----------
    hidden_size: int
        The number of features in the hidden state h.
    num_layers: int, default 1
        Number of recurrent layers.
    layout : str, default 'TNC'
        The format of input and output tensors. T, N and C stand for
        sequence length, batch size, and feature dimensions respectively.
    dropout: float, default 0
        If non-zero, introduces a dropout layer on the outputs of each
        RNN layer except the last layer.
    bidirectional: bool, default False
        If `True`, becomes a bidirectional RNN.
    i2h_weight_initializer : str or Initializer
        Initializer for the input weights matrix, used for the linear
        transformation of the inputs.
    h2h_weight_initializer : str or Initializer
        Initializer for the recurrent weights matrix, used for the linear
        transformation of the recurrent state.
    i2h_bias_initializer : str or Initializer, default 'lstmbias'
        Initializer for the bias vector. By default, bias for the forget
        gate is initialized to 1 while all other biases are initialized
        to zero.
    h2h_bias_initializer : str or Initializer
        Initializer for the bias vector.
    input_size: int, default 0
        The number of expected features in the input x.
        If not specified, it will be inferred from input.
    prefix : str or None
        Prefix of this `Block`.
    params : `ParameterDict` or `None`
        Shared Parameters for this `Block`.

    Input shapes:
        The input shape depends on `layout`. For `layout='TNC'`, the
        input has shape `(sequence_length, batch_size, input_size)`

    Output shape:
        The output shape depends on `layout`. For `layout='TNC'`, the
        output has shape `(sequence_length, batch_size, num_hidden)`.
        If `bidirectional` is True, output shape will instead be
        `(sequence_length, batch_size, 2*num_hidden)`

    Recurrent state shape:
        The recurrent state is a list of two NDArrays. Both has shape
        `(num_layers, batch_size, num_hidden)`.
        If `bidirectional` is True, state shape will instead be
        `(num_layers, batch_size, 2*num_hidden)`.

    Examples
    --------
    >>> layer = mx.gluon.rnn.LSTM(100, 3)
    >>> layer.initialize()
    >>> input = mx.nd.random_uniform(shape=(5, 3, 10))
    >>> h0 = mx.nd.random_uniform(shape=(3, 3, 100))
    >>> c0 = mx.nd.random_uniform(shape=(3, 3, 100))
    >>> output, hn = layer(input, [h0, c0])
    """
    def __init__(self, hidden_size, num_layers=1, layout='TNC',
                 dropout=0, bidirectional=False, input_size=0,
                 i2h_weight_initializer=None, h2h_weight_initializer=None,
                 i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
                 **kwargs):
        super(LSTM, self).__init__(hidden_size, num_layers, layout,
                                   dropout, bidirectional, input_size,
                                   i2h_weight_initializer, h2h_weight_initializer,
                                   i2h_bias_initializer, h2h_bias_initializer,
                                   'lstm', **kwargs)

    def state_info(self, batch_size=0):
        return [{'shape': (self._num_layers * self._dir, batch_size, self._hidden_size),
                 '__layout__': 'LNC'},
                {'shape': (self._num_layers * self._dir, batch_size, self._hidden_size),
                 '__layout__': 'LNC'}]

class GRU(_RNNLayer):
    r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.

    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        \begin{array}{ll}
        r_t = sigmoid(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
        i_t = sigmoid(W_{ii} x_t + b_{ii} + W_hi h_{(t-1)} + b_{hi}) \\
        n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
        h_t = (1 - i_t) * n_t + i_t * h_{(t-1)} \\
        \end{array}

    where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the hidden
    state of the previous layer at time `t` or :math:`input_t` for the first layer,
    and :math:`r_t`, :math:`i_t`, :math:`n_t` are the reset, input, and new gates, respectively.

    Parameters
    ----------
    hidden_size: int
        The number of features in the hidden state h
    num_layers: int, default 1
        Number of recurrent layers.
    layout : str, default 'TNC'
        The format of input and output tensors. T, N and C stand for
        sequence length, batch size, and feature dimensions respectively.
    dropout: float, default 0
        If non-zero, introduces a dropout layer on the outputs of each
        RNN layer except the last layer
    bidirectional: bool, default False
        If True, becomes a bidirectional RNN.
    i2h_weight_initializer : str or Initializer
        Initializer for the input weights matrix, used for the linear
        transformation of the inputs.
    h2h_weight_initializer : str or Initializer
        Initializer for the recurrent weights matrix, used for the linear
        transformation of the recurrent state.
    i2h_bias_initializer : str or Initializer
        Initializer for the bias vector.
    h2h_bias_initializer : str or Initializer
        Initializer for the bias vector.
    input_size: int, default 0
        The number of expected features in the input x.
        If not specified, it will be inferred from input.
    prefix : str or None
        Prefix of this `Block`.
    params : ParameterDict or None
        Shared Parameters for this `Block`.

    Input shapes:
        The input shape depends on `layout`. For `layout='TNC'`, the
        input has shape `(sequence_length, batch_size, input_size)`

    Output shape:
        The output shape depends on `layout`. For `layout='TNC'`, the
        output has shape `(sequence_length, batch_size, num_hidden)`.
        If `bidirectional` is True, output shape will instead be
        `(sequence_length, batch_size, 2*num_hidden)`

    Recurrent state shape:
        The recurrent state's shape is `(num_layers, batch_size, num_hidden)`.
        If `bidirectional` is True, state shape will instead be
        `(num_layers, batch_size, 2*num_hidden)`

    Examples
    --------
    >>> layer = mx.gluon.rnn.GRU(100, 3)
    >>> layer.initialize()
    >>> input = mx.nd.random_uniform(shape=(5, 3, 10))
    >>> h0 = mx.nd.random_uniform(shape=(3, 3, 100))
    >>> output, hn = layer(input, h0)
    """
    def __init__(self, hidden_size, num_layers=1, layout='TNC',
                 dropout=0, bidirectional=False, input_size=0,
                 i2h_weight_initializer=None, h2h_weight_initializer=None,
                 i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
                 **kwargs):
        super(GRU, self).__init__(hidden_size, num_layers, layout,
                                  dropout, bidirectional, input_size,
                                  i2h_weight_initializer, h2h_weight_initializer,
                                  i2h_bias_initializer, h2h_bias_initializer,
                                  'gru', **kwargs)

    def state_info(self, batch_size=0):
        return [{'shape': (self._num_layers * self._dir, batch_size, self._hidden_size),
                 '__layout__': 'LNC'}]


text:
import { Endpoint } from '../../application/common/endpoint';
import { injectable } from "inversify";
import { listen as doListen, Logger, ConsoleLogger } from "vscode-ws-jsonrpc";
import { ConnectionHandler, JsonRpcProxyFactory } from "../common";
const ReconnectingWebSocket = require('reconnecting-websocket');

export interface WebSocketOptions {
    /**
     * True by default.
     */
    reconnecting?: boolean;
}

@injectable()
export class WebSocketConnectionProvider {

    /**
     * Create a proxy object to remote interface of T type
     * over a web socket connection for the given path.
     *
     * An optional target can be provided to handle
     * notifications and requests from a remote side.
     */
    createProxy<T extends object>(path: string, target?: object, options?: WebSocketOptions): T {
        const factory = new JsonRpcProxyFactory<T>(path, target);
        this.listen(factory, options);
        return factory.createProxy();
    }

    /**
     * Install a connection handler for the given path.
     */
    listen(handler: ConnectionHandler, options?: WebSocketOptions): void {
        const url = this.createWebSocketUrl(handler.path);
        const webSocket = this.createWebSocket(url, options);

        const logger = this.createLogger();
        webSocket.onerror = function (error: Event) {
            logger.error('' + error)
            return;
        }
        doListen({
            webSocket,
            onConnection: handler.onConnection.bind(handler),
            logger
        });
    }

    protected createLogger(): Logger {
        return new ConsoleLogger();
    }

    /**
     * Creates a websocket URL to the current location
     */
    createWebSocketUrl(path: string): string {
        const endpoint = new Endpoint({ path })
        return endpoint.getWebSocketUrl().toString()
    }

    /**
     * Creates a web socket for the given url
     */
    createWebSocket(url: string, options?: WebSocketOptions): WebSocket {
        if (options === undefined || options.reconnecting) {
            const socketOptions = {
                maxReconnectionDelay: 10000,
                minReconnectionDelay: 1000,
                reconnectionDelayGrowFactor: 1.3,
                connectionTimeout: 10000,
                maxRetries: Infinity,
                debug: false
            };
            return new ReconnectingWebSocket(url, undefined, socketOptions);
        }
        return new WebSocket(url);
    }

}


text:
<!-- author: TestAuthor -->
<!-- title: TestTitle -->
<!-- tags: tag1, tag2, tag3 -->
<!-- testtag: test -->

# Test_Headline

Test-Text


text:
package org.apache.ignite.internal.processors.cache.persistence.freelist;

import java.util.Collection;
import org.apache.ignite.internal.processors.cache.persistence.AbstractCorruptedPersistenceException;
import org.apache.ignite.internal.util.typedef.T2;
import org.jetbrains.annotations.Nullable;

/**
 * Exception to distinguish {@link AbstractFreeList} broken invariants.
 */
public class CorruptedFreeListException extends AbstractCorruptedPersistenceException {
    /** */
    private static final long serialVersionUID = 0L;

    /**
     * @param msg Message.
     * @param cause Cause.
     * @param grpId Group id.
     * @param pageIds Ids of pages that are possibly corrupted.
     */
    public CorruptedFreeListException(String msg, @Nullable Throwable cause, int grpId, Collection<Long> pageIds) {
        this(msg, cause, grpId, pageIds.stream().mapToLong(Long::longValue).toArray());
    }

    /**
     * @param msg Message.
     * @param cause Cause.
     * @param grpId Group id.
     * @param pageIds Ids of pages that are possibly corrupted.
     */
    public CorruptedFreeListException(String msg, @Nullable Throwable cause, int grpId, long... pageIds) {
        this(msg, cause, toPagesArray(grpId, pageIds));
    }

    /**
     * @param msg Message.
     * @param cause Cause.
     * @param pages (groupId, pageId) pairs for pages that might be corrupted.
     */
    public CorruptedFreeListException(String msg,
        @Nullable Throwable cause,
        T2<Integer, Long>[] pages
    ) {
        super(msg, cause, pages);
    }
}


text:
namespace base {
namespace cef_internal {

// Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
// for the existence of AddRef() and Release() functions of the correct
// signature.
//
// http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
// http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
// http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
//
// The last link in particular show the method used below.
//
// For SFINAE to work with inherited methods, we need to pull some extra tricks
// with multiple inheritance.  In the more standard formulation, the overloads
// of Check would be:
//
//   template <typename C>
//   Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
//
//   template <typename C>
//   No NotTheCheckWeWant(...);
//
//   static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
//
// The problem here is that template resolution will not match
// C::TargetFunc if TargetFunc does not exist directly in C.  That is, if
// TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
// |value| will be false.  This formulation only checks for whether or
// not TargetFunc exist directly in the class being introspected.
//
// To get around this, we play a dirty trick with multiple inheritance.
// First, We create a class BaseMixin that declares each function that we
// want to probe for.  Then we create a class Base that inherits from both T
// (the class we wish to probe) and BaseMixin.  Note that the function
// signature in BaseMixin does not need to match the signature of the function
// we are probing for; thus it's easiest to just use void(void).
//
// Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
// ambiguous resolution between BaseMixin and T.  This lets us write the
// following:
//
//   template <typename C>
//   No GoodCheck(Helper<&C::TargetFunc>*);
//
//   template <typename C>
//   Yes GoodCheck(...);
//
//   static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
//
// Notice here that the variadic version of GoodCheck() returns Yes here
// instead of No like the previous one. Also notice that we calculate |value|
// by specializing GoodCheck() on Base instead of T.
//
// We've reversed the roles of the variadic, and Helper overloads.
// GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
// substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
// to the variadic version if T has TargetFunc.  If T::TargetFunc does not
// exist, then &C::TargetFunc is not ambiguous, and the overload resolution
// will prefer GoodCheck(Helper<&C::TargetFunc>*).
//
// This method of SFINAE will correctly probe for inherited names, but it cannot
// typecheck those names.  It's still a good enough sanity check though.
//
// Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
//
// TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted
// this works well.
//
// TODO(ajwong): Make this check for Release() as well.
// See http://crbug.com/82038.
template <typename T>
class SupportsAddRefAndRelease {
  typedef char Yes[1];
  typedef char No[2];

  struct BaseMixin {
    void AddRef();
  };

// MSVC warns when you try to use Base if T has a private destructor, the
// common pattern for refcounted types. It does this even though no attempt to
// instantiate Base is made.  We disable the warning for this definition.
#if defined(OS_WIN)
#pragma warning(push)
#pragma warning(disable:4624)
#endif
  struct Base : public T, public BaseMixin {
  };
#if defined(OS_WIN)
#pragma warning(pop)
#endif

  template <void(BaseMixin::*)(void)> struct Helper {};

  template <typename C>
  static No& Check(Helper<&C::AddRef>*);

  template <typename >
  static Yes& Check(...);

 public:
  static const bool value = sizeof(Check<Base>(0)) == sizeof(Yes);
};

// Helpers to assert that arguments of a recounted type are bound with a
// scoped_refptr.
template <bool IsClasstype, typename T>
struct UnsafeBindtoRefCountedArgHelper : false_type {
};

template <typename T>
struct UnsafeBindtoRefCountedArgHelper<true, T>
    : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
};

template <typename T>
struct UnsafeBindtoRefCountedArg : false_type {
};

template <typename T>
struct UnsafeBindtoRefCountedArg<T*>
    : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
};

template <typename T>
class HasIsMethodTag {
  typedef char Yes[1];
  typedef char No[2];

  template <typename U>
  static Yes& Check(typename U::IsMethod*);

  template <typename U>
  static No& Check(...);

 public:
  static const bool value = sizeof(Check<T>(0)) == sizeof(Yes);
};

template <typename T>
class UnretainedWrapper {
 public:
  explicit UnretainedWrapper(T* o) : ptr_(o) {}
  T* get() const { return ptr_; }
 private:
  T* ptr_;
};

template <typename T>
class ConstRefWrapper {
 public:
  explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
  const T& get() const { return *ptr_; }
 private:
  const T* ptr_;
};

template <typename T>
struct IgnoreResultHelper {
  explicit IgnoreResultHelper(T functor) : functor_(functor) {}

  T functor_;
};

template <typename T>
struct IgnoreResultHelper<Callback<T> > {
  explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {}

  const Callback<T>& functor_;
};

// An alternate implementation is to avoid the destructive copy, and instead
// specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
// a class that is essentially a scoped_ptr<>.
//
// The current implementation has the benefit though of leaving ParamTraits<>
// fully in callback_internal.h as well as avoiding type conversions during
// storage.
template <typename T>
class OwnedWrapper {
 public:
  explicit OwnedWrapper(T* o) : ptr_(o) {}
  ~OwnedWrapper() { delete ptr_; }
  T* get() const { return ptr_; }
  OwnedWrapper(const OwnedWrapper& other) {
    ptr_ = other.ptr_;
    other.ptr_ = NULL;
  }

 private:
  mutable T* ptr_;
};

// PassedWrapper is a copyable adapter for a scoper that ignores const.
//
// It is needed to get around the fact that Bind() takes a const reference to
// all its arguments.  Because Bind() takes a const reference to avoid
// unnecessary copies, it is incompatible with movable-but-not-copyable
// types; doing a destructive "move" of the type into Bind() would violate
// the const correctness.
//
// This conundrum cannot be solved without either C++11 rvalue references or
// a O(2^n) blowup of Bind() templates to handle each combination of regular
// types and movable-but-not-copyable types.  Thus we introduce a wrapper type
// that is copyable to transmit the correct type information down into
// BindState<>. Ignoring const in this type makes sense because it is only
// created when we are explicitly trying to do a destructive move.
//
// Two notes:
//  1) PassedWrapper supports any type that has a "Pass()" function.
//     This is intentional. The whitelisting of which specific types we
//     support is maintained by CallbackParamTraits<>.
//  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
//     scoper to a Callback and allow the Callback to execute once.
template <typename T>
class PassedWrapper {
 public:
  explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {}
  PassedWrapper(const PassedWrapper& other)
      : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) {
  }
  T Pass() const {
    CHECK(is_valid_);
    is_valid_ = false;
    return scoper_.Pass();
  }

 private:
  mutable bool is_valid_;
  mutable T scoper_;
};

// Unwrap the stored parameters for the wrappers above.
template <typename T>
struct UnwrapTraits {
  typedef const T& ForwardType;
  static ForwardType Unwrap(const T& o) { return o; }
};

template <typename T>
struct UnwrapTraits<UnretainedWrapper<T> > {
  typedef T* ForwardType;
  static ForwardType Unwrap(UnretainedWrapper<T> unretained) {
    return unretained.get();
  }
};

template <typename T>
struct UnwrapTraits<ConstRefWrapper<T> > {
  typedef const T& ForwardType;
  static ForwardType Unwrap(ConstRefWrapper<T> const_ref) {
    return const_ref.get();
  }
};

template <typename T>
struct UnwrapTraits<scoped_refptr<T> > {
  typedef T* ForwardType;
  static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); }
};

template <typename T>
struct UnwrapTraits<WeakPtr<T> > {
  typedef const WeakPtr<T>& ForwardType;
  static ForwardType Unwrap(const WeakPtr<T>& o) { return o; }
};

template <typename T>
struct UnwrapTraits<OwnedWrapper<T> > {
  typedef T* ForwardType;
  static ForwardType Unwrap(const OwnedWrapper<T>& o) {
    return o.get();
  }
};

template <typename T>
struct UnwrapTraits<PassedWrapper<T> > {
  typedef T ForwardType;
  static T Unwrap(PassedWrapper<T>& o) {
    return o.Pass();
  }
};

// Utility for handling different refcounting semantics in the Bind()
// function.
template <bool is_method, typename T>
struct MaybeRefcount;

template <typename T>
struct MaybeRefcount<false, T> {
  static void AddRef(const T&) {}
  static void Release(const T&) {}
};

template <typename T, size_t n>
struct MaybeRefcount<false, T[n]> {
  static void AddRef(const T*) {}
  static void Release(const T*) {}
};

template <typename T>
struct MaybeRefcount<true, T> {
  static void AddRef(const T&) {}
  static void Release(const T&) {}
};

template <typename T>
struct MaybeRefcount<true, T*> {
  static void AddRef(T* o) { o->AddRef(); }
  static void Release(T* o) { o->Release(); }
};

// No need to additionally AddRef() and Release() since we are storing a
// scoped_refptr<> inside the storage object already.
template <typename T>
struct MaybeRefcount<true, scoped_refptr<T> > {
  static void AddRef(const scoped_refptr<T>& o) {}
  static void Release(const scoped_refptr<T>& o) {}
};

template <typename T>
struct MaybeRefcount<true, const T*> {
  static void AddRef(const T* o) { o->AddRef(); }
  static void Release(const T* o) { o->Release(); }
};

// IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
// method.  It is used internally by Bind() to select the correct
// InvokeHelper that will no-op itself in the event the WeakPtr<> for
// the target object is invalidated.
//
// P1 should be the type of the object that will be received of the method.
template <bool IsMethod, typename P1>
struct IsWeakMethod : public false_type {};

template <typename T>
struct IsWeakMethod<true, WeakPtr<T> > : public true_type {};

template <typename T>
struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T> > > : public true_type {};

}  // namespace cef_internal

template <typename T>
static inline cef_internal::UnretainedWrapper<T> Unretained(T* o) {
  return cef_internal::UnretainedWrapper<T>(o);
}

template <typename T>
static inline cef_internal::ConstRefWrapper<T> ConstRef(const T& o) {
  return cef_internal::ConstRefWrapper<T>(o);
}

template <typename T>
static inline cef_internal::OwnedWrapper<T> Owned(T* o) {
  return cef_internal::OwnedWrapper<T>(o);
}

// We offer 2 syntaxes for calling Passed().  The first takes a temporary and
// is best suited for use with the return value of a function. The second
// takes a pointer to the scoper and is just syntactic sugar to avoid having
// to write Passed(scoper.Pass()).
template <typename T>
static inline cef_internal::PassedWrapper<T> Passed(T scoper) {
  return cef_internal::PassedWrapper<T>(scoper.Pass());
}
template <typename T>
static inline cef_internal::PassedWrapper<T> Passed(T* scoper) {
  return cef_internal::PassedWrapper<T>(scoper->Pass());
}

template <typename T>
static inline cef_internal::IgnoreResultHelper<T> IgnoreResult(T data) {
  return cef_internal::IgnoreResultHelper<T>(data);
}

template <typename T>
static inline cef_internal::IgnoreResultHelper<Callback<T> >
IgnoreResult(const Callback<T>& data) {
  return cef_internal::IgnoreResultHelper<Callback<T> >(data);
}

void DoNothing();

template<typename T>
void DeletePointer(T* obj) {
  delete obj;
}

}  // namespace base

#endif  // !BUILDING_CEF_SHARED

#endif  // CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_


text:
package org.nkjmlab.util.javax.servlet;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.nkjmlab.util.java.lang.ParameterizedStringFormat;
import org.nkjmlab.util.java.lang.SystemPropertyUtils;

public class WebJarsUtils {

  static String findWebJarVersionFromClassPath(String libName) {
    String regex = "^" + libName + "-(.*).jar";

    List<String> versions =
        SystemPropertyUtils.findClassPathElements(regex).stream().map(classPath -> {
          Pattern pattern = Pattern.compile(regex);
          Matcher m = pattern.matcher(new File(classPath).getName());
          if (m.find()) {
            return m.group(1);
          } else {
            Object[] params = {regex, SystemPropertyUtils.getClassPathElements()};
            throw new IllegalStateException(
                ParameterizedStringFormat.DEFAULT.format("{} should be one in classpath ({})", params));
          }
        }).collect(Collectors.toList());

    if (versions.size() == 0) {
      Object[] params = {regex, SystemPropertyUtils.getClassPathElements()};
      throw new IllegalStateException(ParameterizedStringFormat.DEFAULT.format("{} should be one in classpath ({})", params));
    } else if (versions.size() == 1) {
      return versions.get(0);
    } else {
      Object[] params = {regex, SystemPropertyUtils.getClassPathElements()};
      return versions.stream().filter(
          v -> v.toLowerCase().matches("([0-9]|\\.|-|beta|alpha|stable|release|stable|snapshot)*"))
          .findAny()
          .orElseThrow(() -> new IllegalStateException(
              ParameterizedStringFormat.DEFAULT.format("{} should be one in classpath ({})", params)));
    }
  }

  public static Map<String, String> findWebJarVersionsFromClassPath(String... libNames) {
    return Stream.of(libNames)
        .collect(Collectors.toMap(lib -> lib.replace(".", "_").replace("-", "_"),
            lib -> findWebJarVersionFromClassPath(lib)));
  }

}