text:
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import spies from 'chai-spies';
import * as jp from '../../dist/index.js';

chai.should();
chai.use(spies);
chai.use(chaiAsPromised);

describe('Schema', function () {
  describe('validators', function () {
    describe('type', function () {
      it('should validate a null value', async function () {
        const schema = await jp.create(
          {
            type: 'null',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(null).should.eventually.equal(null);
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate a boolean value', async function () {
        const schema = await jp.create(
          {
            type: 'boolean',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(true).should.eventually.equal(true);
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate an array value', async function () {
        const schema = await jp.create(
          {
            type: 'array',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate([]).should.eventually.deep.equal([]);
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate a number value', async function () {
        const schema = await jp.create(
          {
            type: 'number',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(10).should.eventually.equal(10);
        await schema.validate(10.5).should.eventually.equal(10.5);
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate a integer value', async function () {
        const schema = await jp.create(
          {
            type: 'integer',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(10).should.eventually.equal(10);
        await schema.validate(10.5).should.be.rejectedWith(jp.ValidationError, 'type');
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate a string value', async function () {
        const schema = await jp.create(
          {
            type: 'string',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('test').should.eventually.equal('test');
        await schema.validate('').should.eventually.equal('');
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate an object value', async function () {
        const schema = await jp.create(
          {
            type: 'object',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({}).should.eventually.deep.equal({});
        return schema.validate('test').should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should validate with an array of types', async function () {
        const schema = await jp.create(
          {
            type: ['string', 'number'],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('test').should.eventually.equal('test');
        await schema.validate(10).should.eventually.equal(10);
        return schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'type');
      });
      it('should fail to validate an unknown type', async function () {
        const schema = await jp.create(
          {
            type: 'foo',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({}).should.be.rejectedWith(jp.SchemaError, 'type');
      });
    });
    describe('enum', async function () {
      it('should fail with an invalid enum', async function () {
        const schema1 = await jp.create(
          {
            enum: true,
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate(true).should.be.rejectedWith(jp.SchemaError, 'enum');
        const schema2 = await jp.create(
          {
            enum: [],
          },
          { scope: 'http://example.com' }
        );
        return schema2.validate(true).should.be.rejectedWith(jp.SchemaError, 'enum');
      });
      it('should validate with enum', async function () {
        const schema = await jp.create(
          {
            enum: ['test', 10],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('test').should.eventually.equal('test');
        await schema.validate(10).should.eventually.equal(10);
        return schema.validate(11).should.be.rejectedWith(jp.ValidationError, 'enum');
      });
    });
    describe('const', async function () {
      it('should fail with an invalid const', async function () {
        const schema = await jp.create(
          {
            const: undefined,
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(true).should.be.rejectedWith(jp.SchemaError, 'const');
      });
      it('should validate with const', async function () {
        const schema = await jp.create(
          {
            const: 10,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(10).should.eventually.equal(10);
        return schema.validate(11).should.be.rejectedWith(jp.ValidationError, 'const');
      });
    });
    describe('multipleOf', async function () {
      it('should fail with an invalid multipleOf', async function () {
        const schema = await jp.create(
          {
            multipleOf: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(10).should.be.rejectedWith(jp.SchemaError, 'multipleOf');
      });
      it('should validate with multipleOf', async function () {
        const schema = await jp.create(
          {
            multipleOf: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(15).should.eventually.equal(15);
        await schema.validate('15').should.eventually.equal('15');
        return schema.validate(11).should.be.rejectedWith(jp.ValidationError, 'multipleOf');
      });
    });
    describe('maximum', async function () {
      it('should fail with an invalid maximum', async function () {
        const schema = await jp.create(
          {
            maximum: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(10).should.be.rejectedWith(jp.SchemaError, 'maximum');
      });
      it('should validate with maximum', async function () {
        const schema = await jp.create(
          {
            maximum: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(2).should.eventually.equal(2);
        await schema.validate(3).should.eventually.equal(3);
        return schema.validate(4).should.be.rejectedWith(jp.ValidationError, 'maximum');
      });
    });
    describe('exclusiveMaximum', async function () {
      it('should fail with an invalid exclusiveMaximum', async function () {
        const schema = await jp.create(
          {
            exclusiveMaximum: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(10).should.be.rejectedWith(jp.SchemaError, 'exclusiveMaximum');
      });
      it('should validate with exclusiveMaximum', async function () {
        const schema = await jp.create(
          {
            exclusiveMaximum: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(2).should.eventually.equal(2);
        await schema.validate('2').should.eventually.equal('2');
        await schema.validate(3).should.be.rejectedWith(jp.ValidationError, 'exclusiveMaximum');
        return schema.validate(4).should.be.rejectedWith(jp.ValidationError, 'exclusiveMaximum');
      });
    });
    describe('minimum', async function () {
      it('should fail with an invalid minimum', async function () {
        const schema = await jp.create(
          {
            minimum: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(10).should.be.rejectedWith(jp.SchemaError, 'minimum');
      });
      it('should validate with minimum', async function () {
        const schema = await jp.create(
          {
            minimum: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(4).should.eventually.equal(4);
        await schema.validate(3).should.eventually.equal(3);
        await schema.validate('4').should.eventually.equal('4');
        return schema.validate(2).should.be.rejectedWith(jp.ValidationError, 'minimum');
      });
    });
    describe('exclusiveMinimum', async function () {
      it('should fail with an invalid exclusiveMinimum', async function () {
        const schema = await jp.create(
          {
            exclusiveMinimum: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(10).should.be.rejectedWith(jp.SchemaError, 'exclusiveMinimum');
      });
      it('should validate with exclusiveMinimum', async function () {
        const schema = await jp.create(
          {
            exclusiveMinimum: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(4).should.eventually.equal(4);
        await schema.validate('4').should.eventually.equal('4');
        await schema.validate(3).should.be.rejectedWith(jp.ValidationError, 'exclusiveMinimum');
        return schema.validate(2).should.be.rejectedWith(jp.ValidationError, 'exclusiveMinimum');
      });
    });
    describe('maxLength', async function () {
      it('should fail with an invalid maxLength', async function () {
        const schema = await jp.create(
          {
            maxLength: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate('abc').should.be.rejectedWith(jp.SchemaError, 'maxLength');
      });
      it('should validate with maxLength', async function () {
        const schema = await jp.create(
          {
            maxLength: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('abc').should.eventually.equal('abc');
        return schema.validate('abcd').should.be.rejectedWith(jp.ValidationError, 'maxLength');
      });
    });
    describe('minLength', async function () {
      it('should fail with an invalid minLength', async function () {
        const schema = await jp.create(
          {
            minLength: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate('abc').should.be.rejectedWith(jp.SchemaError, 'minLength');
      });
      it('should validate with minLength', async function () {
        const schema = await jp.create(
          {
            minLength: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('abc').should.eventually.equal('abc');
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate('ab').should.be.rejectedWith(jp.ValidationError, 'minLength');
      });
    });
    describe('pattern', async function () {
      it('should fail with an invalid pattern', async function () {
        const schema = await jp.create(
          {
            pattern: 10,
          },
          { scope: 'http://example.com' }
        );
        return schema.validate('abc').should.be.rejectedWith(jp.SchemaError, 'pattern');
      });
      it('should validate with pattern', async function () {
        const schema = await jp.create(
          {
            pattern: '^a.*b$',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('a_b').should.eventually.equal('a_b');
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate('abc').should.be.rejectedWith(jp.ValidationError, 'pattern');
      });
      it('should validate a Date with pattern', async function () {
        const schema = await jp.create(
          {
            pattern: '^202[12]',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(new Date('2021-01-01')).should.eventually.equal('2021-01-01T00:00:00.000Z');
        return schema.validate(new Date('2020-01-01')).should.be.rejectedWith(jp.ValidationError, 'pattern');
      });
    });
    describe('format', async function () {
      it('should fail with an invalid format', async function () {
        const schema = await jp.create(
          {
            format: 10,
          },
          { scope: 'http://example.com' }
        );
        return schema.validate('abc').should.be.rejectedWith(jp.SchemaError, 'format');
      });
      it('should validate a valid date with a date-time format', async function () {
        const schema = await jp.create(
          {
            format: 'date-time',
          },
          { scope: 'http://example.com' }
        );

        await schema.validate('2022-03-29T00:00:00Z').should.eventually.be.a('Date');
        debugger;
        await schema.validate(new Date('2022-03-29T10:10:10Z')).should.eventually.be.a('Date');
      });
      it('should fail with an invalid date with a date-time format', async function () {
        const schema = await jp.create(
          {
            format: 'date-time',
          },
          { scope: 'http://example.com' }
        );

        await schema.validate('aaaaa').should.be.rejectedWith(jp.SchemaError, 'format');
      });
      it('should validate a valid date with a date format', async function () {
        const schema = await jp.create(
          {
            format: 'date',
          },
          { scope: 'http://example.com' }
        );

        await schema.validate('2022-03-29').should.eventually.be.a('Date');
        debugger;
        await schema.validate(new Date('2022-03-29')).should.eventually.be.a('Date');
      });
      it('should fail with an invalid date with a date format', async function () {
        const schema = await jp.create(
          {
            format: 'date',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('2022-03-32').should.be.rejectedWith(jp.SchemaError, 'format');
        await schema.validate('2022-03-29T00:00:00Z').should.be.rejectedWith(jp.SchemaError, 'format');
      });
      it('should validate a valid time with a time format', async function () {
        const schema = await jp.create(
          {
            format: 'time',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('12:32:10').should.eventually.equal('12:32:10');
        await schema.validate('12:32:10.333').should.eventually.equal('12:32:10.333');
      });
      it('should fail with an invalid time with a time format', async function () {
        const schema = await jp.create(
          {
            format: 'time',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('aaaa').should.be.rejectedWith(jp.SchemaError, 'format');
        await schema.validate('26:12:99').should.be.rejectedWith(jp.SchemaError, 'format');
      });
      it('should validate a valid email with a email format', async function () {
        const schema = await jp.create(
          {
            format: 'email',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('joe@example.com').should.eventually.equal('joe@example.com');
      });
      it('should fail with an invalid email with a email format', async function () {
        const schema = await jp.create(
          {
            format: 'email',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('aaaa').should.be.rejectedWith(jp.SchemaError, 'format');
      });
      it('should validate other valid formats', async function () {
        let schema = await jp.create(
          {
            format: 'hostname',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('example.com').should.eventually.equal('example.com');
        await schema.validate('a b c').should.be.rejectedWith(jp.SchemaError, 'format');
        schema = await jp.create(
          {
            format: 'ipv4',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('1.2.3.4').should.eventually.equal('1.2.3.4');
        await schema.validate('300.2').should.be.rejectedWith(jp.SchemaError, 'format');
        schema = await jp.create(
          {
            format: 'uri',
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('http://a.b.c').should.eventually.equal('http://a.b.c');
      });
    });
    describe('items', async function () {
      it('should validate with an empty array', async function () {
        const schema = await jp.create(
          {
            items: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        return schema.validate([]).should.eventually.deep.equal([]);
      });
      it('should validate with a single schema', async function () {
        const schema = await jp.create(
          {
            items: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['test', 'other']).should.eventually.deep.equal(['test', 'other']);
        return schema.validate([10]).should.be.rejectedWith(jp.ValidationError, 'items');
      });
      it('should validate with a multiple schemas', async function () {
        const schema = await jp.create(
          {
            items: [
              {
                type: 'string',
              },
              {
                type: 'boolean',
              },
              {
                type: 'integer',
              },
            ],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['test', true, 10]).should.eventually.deep.equal(['test', true, 10]);
        const p = schema.validate([1, true, 10.2]);
        const err = await p.should.be.rejectedWith(jp.ValidationError, 'items');
        err.errors.length.should.equal(2);

        const schema2 = await jp.create(
          {
            items: [
              {
                type: 'string',
              },
              undefined,
            ],
          },
          { scope: 'http://example.com' }
        );
        await schema2.validate([0, true]).should.be.rejectedWith(jp.ValidationError, 'items');
      });
    });
    describe('additionalItems', async function () {
      it('should ignore additionalItems if items is not an array', async function () {
        const schema1 = await jp.create(
          {
            additionalItems: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate([5, 10, 12.5]).should.eventually.deep.equal([5, 10, 12.5]);
        const schema2 = await jp.create(
          {
            items: {
              type: 'number',
            },
            additionalItems: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema2.validate([5, 10, 12.5]).should.eventually.deep.equal([5, 10, 12.5]);
      });
      it('should validate with additionalItems', async function () {
        const schema = await jp.create(
          {
            items: [
              {
                type: 'string',
              },
              {
                type: 'boolean',
              },
              {
                type: 'integer',
              },
            ],
            additionalItems: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['test', true, 12, 'aaa', 'bbb', 'ccc']).should.be.fulfilled;
        const p = schema.validate(['test', true, 12, true, null, 'ccc']);
        const err = await p.should.be.rejectedWith(jp.ValidationError, 'additionalItems');
        err.errors.length.should.equal(2);
      });
    });
    describe('maxItems', async function () {
      it('should fail with an invalid maxItems', async function () {
        const schema = await jp.create(
          {
            maxItems: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(['abc']).should.be.rejectedWith(jp.SchemaError, 'maxItems');
      });
      it('should validate with maxItems', async function () {
        const schema = await jp.create(
          {
            maxItems: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['a', 'b']).should.be.fulfilled;
        await schema.validate(['a', 'b', 'c']).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate(['a', 'b', 'c', 'd']).should.be.rejectedWith(jp.ValidationError, 'maxItems');
      });
    });
    describe('minItems', async function () {
      it('should fail with an invalid minItems', async function () {
        const schema = await jp.create(
          {
            minItems: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(['abc']).should.be.rejectedWith(jp.SchemaError, 'minItems');
      });
      it('should validate with minItems', async function () {
        const schema = await jp.create(
          {
            minItems: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['a', 'b', 'c', 'd']).should.be.fulfilled;
        await schema.validate(['a', 'b', 'c']).should.be.fulfilled;
        return schema.validate(['a', 'b']).should.be.rejectedWith(jp.ValidationError, 'minItems');
      });
    });
    describe('uniqueItems', async function () {
      it('should fail with an invalid uniqueItems', async function () {
        const schema = await jp.create(
          {
            uniqueItems: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate(['abc']).should.be.rejectedWith(jp.SchemaError, 'uniqueItems');
      });
      it('should validate with uniqueItems', async function () {
        const schema = await jp.create(
          {
            uniqueItems: true,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['a', 'b', 'c', 'd']).should.be.fulfilled;
        return schema.validate(['a', 'b', 'a', 'd']).should.be.rejectedWith(jp.ValidationError, 'uniqueItems');
      });
    });
    describe('contains', async function () {
      it('should validate a contains', async function () {
        const schema = await jp.create(
          {
            contains: {
              type: 'number',
              maximum: 3,
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(['a', 'b', 7, 3]).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate(['a', 'b', 7]).should.be.rejectedWith(jp.ValidationError, 'contains');
      });
    });
    describe('maxProperties', async function () {
      it('should fail with an invalid maxProperties', async function () {
        const schema = await jp.create(
          {
            maxProperties: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'maxProperties');
      });
      it('should validate with maxProperties', async function () {
        const schema = await jp.create(
          {
            maxProperties: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: 1, b: 2 }).should.be.fulfilled;
        await schema.validate({ a: 1, b: 2, c: 3 }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate({ a: 1, b: 2, c: 3, d: 4 }).should.be.rejectedWith(jp.ValidationError, 'maxProperties');
      });
    });
    describe('minProperties', async function () {
      it('should fail with an invalid minProperties', async function () {
        const schema = await jp.create(
          {
            minProperties: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'minProperties');
      });
      it('should validate with minProperties', async function () {
        const schema = await jp.create(
          {
            minProperties: 3,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: 1, b: 2, c: 3, d: 4 }).should.be.fulfilled;
        await schema.validate({ a: 1, b: 2, c: 3 }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate({ a: 1, b: 2 }).should.be.rejectedWith(jp.ValidationError, 'minProperties');
      });
    });
    describe('required', async function () {
      it('should fail with an invalid required', async function () {
        const schema1 = await jp.create(
          {
            required: 'test',
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'required');
        const schema2 = await jp.create(
          {
            required: [1],
          },
          { scope: 'http://example.com' }
        );
        return schema2.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'required');
      });
      it('should validate with required', async function () {
        const schema = await jp.create(
          {
            required: ['a', 'b', 'c'],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: 1, b: 2, c: 3, d: 4 }).should.be.fulfilled;
        await schema.validate({ a: 1, b: 2, c: 3 }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate({ a: 1, b: 2 }).should.be.rejectedWith(jp.ValidationError, 'required');
      });
      it('should handle validation of required properties that have readOnly flag', async function () {
        const schema = await jp.create(
          {
            type: 'object',
            required: ['a', 'b'],
            properties: {
              a: {
                type: 'string',
                readOnly: true,
              },
              b: {
                type: 'number',
              },
            },
          },
          { scope: 'http://example.com' }
        );

        await schema.validate({ b: 1 }).should.be.rejectedWith(jp.ValidationError, 'required');
        await schema.validate({ b: 1 }, { context: 'write' }).should.be.fulfilled;
        await schema.validate({ a: 1 }, { context: 'write' }).should.be.rejectedWith(jp.ValidationError, 'required');
        await schema.validate({ b: 1 }, { context: 'read' }).should.be.rejectedWith(jp.ValidationError, 'required');
        await schema.validate({}).should.be.rejectedWith(jp.ValidationError, 'required');
      });
      it('should handle validation of required properties that have writeOnly flag', async function () {
        const schema = await jp.create(
          {
            type: 'object',
            required: ['a', 'b'],
            properties: {
              a: {
                type: 'string',
                writeOnly: true,
              },
              b: {
                type: 'number',
              },
            },
          },
          { scope: 'http://example.com' }
        );

        await schema.validate({ b: 5 }).should.be.rejectedWith(jp.ValidationError, 'required');
        await schema.validate({ b: 5 }, { context: 'read' }).should.be.fulfilled;
      });
    });
    describe('properties', async function () {
      it('should fail with an invalid properties', async function () {
        const schema1 = await jp.create(
          {
            properties: 'test',
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'properties');
        const schema2 = await jp.create(
          {
            properties: [1],
          },
          { scope: 'http://example.com' }
        );
        return schema2.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'properties');
      });
      it('should validate with properties', async function () {
        const schema = await jp.create(
          {
            properties: {
              a: {
                type: 'number',
              },
              c: {
                type: 'string',
              },
            },
          },
          { scope: 'http://example.com' }
        );

        await schema.validate({ a: 1, b: true, c: 'test', d: 4 }).should.be.fulfilled;
        await schema.validate({}, { setDefault: true }).should.be.fulfilled;
        const p = schema.validate({ a: 1, b: 2, c: 3 });
        const err = await p.should.be.rejectedWith(jp.ValidationError, 'properties');
        err.errors.length.should.equal(1);
        err.errors[0].message.should.equal('type');
        await schema.validate(1).should.eventually.equal(1);
      });
      it('should purge out-of-context properties', async function () {
        const schema = await jp.create(
          {
            properties: {
              a: {
                type: 'number',
                readOnly: true,
              },
              c: {
                type: 'string',
                writeOnly: true,
              },
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: 1, b: true, c: 'test', d: 4 }, { context: 'read' }).should.eventually.deep.equal({ a: 1, b: true, d: 4 });
        return schema.validate({ a: 1, b: true, c: 'test', d: 4 }, { context: 'write' }).should.eventually.deep.equal({ b: true, c: 'test', d: 4 });
      });
    });
    describe('patternProperties', async function () {
      it('should fail with an invalid patternProperties', async function () {
        const schema1 = await jp.create(
          {
            patternProperties: 'test',
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'patternProperties');
        const schema2 = await jp.create(
          {
            patternProperties: [1],
          },
          { scope: 'http://example.com' }
        );
        return schema2.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'patternProperties');
      });
      it('should validate with patternProperties', async function () {
        const schema = await jp.create(
          {
            patternProperties: {
              '^a': {
                type: 'number',
              },
              b: {
                maxLength: 2,
                maximum: 6,
              },
              c$: {
                type: 'string',
              },
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ aaa: 1, b1: true, b2: 'tt', cc: 'aaa' }).should.be.fulfilled;
        await schema.validate({ aaa: true, b1: true }).should.be.rejectedWith(jp.ValidationError, 'patternProperties');
        await schema.validate({ aaa: 1, b1: 7 }).should.be.rejectedWith(jp.ValidationError, 'patternProperties');
        await schema.validate({ aba: 8 }).should.be.rejectedWith(jp.ValidationError, 'patternProperties');
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate({ bbc: 'aaa' }).should.be.rejectedWith(jp.ValidationError, 'patternProperties');
      });
      it('should purge out-of-context patternProperties', async function () {
        const schema = await jp.create(
          {
            patternProperties: {
              '^a': {
                type: 'number',
                readOnly: true,
              },
              b: {
                maxLength: 2,
                maximum: 6,
              },
              c$: {
                type: 'string',
                writeOnly: true,
              },
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ aaa: 1, b1: true, b2: 'tt', cc: 'aaa' }, { context: 'read' }).should.eventually.deep.equal({ aaa: 1, b1: true, b2: 'tt' });
        return schema.validate({ aaa: 1, b1: true, b2: 'tt', cc: 'aaa' }, { context: 'write' }).should.eventually.deep.equal({ b1: true, b2: 'tt', cc: 'aaa' });
      });
    });
    describe('additionalProperties', async function () {
      it('should validate with a schema additionalProperties', async function () {
        const schema = await jp.create(
          {
            properties: {
              b: {
                type: 'string',
              },
            },
            patternProperties: {
              '^a': {
                type: 'number',
              },
            },
            additionalProperties: {
              type: 'boolean',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ aaa: 1, b: 'x', c: true }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        return schema.validate({ bbc: 'aaa' }).should.be.rejectedWith(jp.ValidationError, 'additionalProperties');
      });
      it('should validate with a boolean additionalProperties', async function () {
        const schema = await jp.create(
          {
            properties: {
              b: {
                type: 'string',
              },
            },
            patternProperties: {
              '^a': {
                type: 'number',
              },
            },
            additionalProperties: false,
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ aaa: 1, b: 'x' }).should.be.fulfilled;
        return schema.validate({ bbc: 'aaa' }).should.be.rejectedWith(jp.ValidationError, 'additionalProperties');
      });
      it('should purge additionalProperties, when the option is set', async function () {
        const schema = await jp.create(
          {
            properties: {
              b: {
                type: 'string',
              },
            },
            patternProperties: {
              '^a': {
                type: 'number',
              },
            },
            additionalProperties: false,
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ b: 'x', bbc: 'aaa' }, { removeAdditional: true }).should.eventually.deep.equal({ b: 'x' });
      });
      it('should purge out-of-context additionalProperties', async function () {
        const schema1 = await jp.create(
          {
            additionalProperties: {
              type: 'string',
              readOnly: true,
            },
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate({ b: 'x' }, { context: 'read' }).should.eventually.deep.equal({ b: 'x' });
        await schema1.validate({ b: 'x' }, { context: 'write' }).should.eventually.deep.equal({});
        const schema2 = await jp.create(
          {
            additionalProperties: {
              type: 'string',
              writeOnly: true,
            },
          },
          { scope: 'http://example.com' }
        );
        await schema2.validate({ b: 'x' }, { context: 'read' }).should.eventually.deep.equal({});
        return schema2.validate({ b: 'x' }, { context: 'write' }).should.eventually.deep.equal({ b: 'x' });
      });
    });
    describe('dependencies', async function () {
      it('should fail with an invalid dependencies', async function () {
        const schema1 = await jp.create(
          {
            dependencies: 'test',
          },
          { scope: 'http://example.com' }
        );
        await schema1.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'dependencies');
        const schema2 = await jp.create(
          {
            dependencies: [1],
          },
          { scope: 'http://example.com' }
        );
        await schema2.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'dependencies');
        const schema3 = await jp.create(
          {
            dependencies: { a: [true] },
          },
          { scope: 'http://example.com' }
        );
        return schema3.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'dependencies');
      });
      it('should validate with dependencies', async function () {
        const schema = await jp.create(
          {
            dependencies: {
              a: ['b', 'c'],
              b: ['d'],
              d: {
                minProperties: 4,
              },
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ b: true, d: 'aaa', e: 1, f: 2 }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        await schema.validate({ a: 1 }).should.be.rejectedWith(jp.ValidationError, 'dependencies');
        await schema.validate({ d: 'aaa' }).should.be.rejectedWith(jp.ValidationError, 'dependencies');
        return schema.validate({ b: true }).should.be.rejectedWith(jp.ValidationError, 'dependencies');
      });
    });
    describe('propertyNames', async function () {
      it('should validate with propertyNames', async function () {
        const schema = await jp.create(
          {
            propertyNames: {
              minLength: 3,
              pattern: '^x-',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ 'x-a': 3, 'x-b': true }).should.be.fulfilled;
        await schema.validate(1).should.eventually.equal(1);
        await schema.validate({ a: 1 }).should.be.rejectedWith(jp.ValidationError, 'propertyNames');
        return schema.validate({ 'x-': true }).should.be.rejectedWith(jp.ValidationError, 'propertyNames');
      });
    });
    describe('if', async function () {
      it('should validate with if (when then and else are absent)', async function () {
        const schema = await jp.create(
          {
            if: {
              properties: {
                a: {
                  type: 'boolean',
                },
              },
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: true }).should.be.fulfilled;
        return schema.validate({ a: 1 }).should.be.fulfilled;
      });
      it('should validate with if (true branch)', async function () {
        const schema = await jp.create(
          {
            if: {
              properties: {
                a: {
                  type: 'boolean',
                },
              },
            },
            then: {
              required: ['b'],
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: true, b: 1 }).should.be.fulfilled;
        return schema.validate({ a: true }).should.be.rejectedWith(jp.ValidationError, 'required');
      });
      it('should validate with if (false branch)', async function () {
        const schema = await jp.create(
          {
            if: {
              properties: {
                a: {
                  type: 'boolean',
                },
              },
            },
            else: {
              required: ['c'],
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: true }).should.be.fulfilled;
        await schema.validate({ a: 1, c: true }).should.be.fulfilled;
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.ValidationError, 'required');
      });
    });
    describe('allOf', async function () {
      it('should fail with an invalid allOf', async function () {
        const schema = await jp.create(
          {
            allOf: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'allOf');
      });
      it('should validate with allOf', async function () {
        const schema = await jp.create(
          {
            allOf: [
              {
                type: 'string',
              },
              {
                maxLength: 3,
              },
            ],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('aaa').should.be.fulfilled;
        await schema.validate(true).should.be.rejectedWith(jp.ValidationError, 'allOf');
        return schema.validate('aaaa').should.be.rejectedWith(jp.ValidationError, 'allOf');
      });
    });
    describe('anyOf', async function () {
      it('should fail with an invalid anyOf', async function () {
        const schema = await jp.create(
          {
            anyOf: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'anyOf');
      });
      it('should validate with anyOf', async function () {
        const schema = await jp.create(
          {
            anyOf: [
              {
                type: 'string',
              },
              {
                maximum: 3,
              },
            ],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate('aaa').should.be.fulfilled;
        await schema.validate(2).should.be.fulfilled;
        await schema.validate(true).should.be.fulfilled;
        return schema.validate(5).should.be.rejectedWith(jp.ValidationError, 'anyOf');
      });
    });
    describe('oneOf', async function () {
      it('should fail with an invalid oneOf', async function () {
        const schema = await jp.create(
          {
            oneOf: 'test',
          },
          { scope: 'http://example.com' }
        );
        return schema.validate({ a: 1 }).should.be.rejectedWith(jp.SchemaError, 'oneOf');
      });
      it('should validate with oneOf', async function () {
        const schema = await jp.create(
          {
            oneOf: [
              {
                properties: {
                  a: true,
                  b: true,
                },
                additionalProperties: false,
              },
              {
                properties: {
                  b: true,
                  c: true,
                },
                additionalProperties: false,
              },
            ],
          },
          { scope: 'http://example.com' }
        );
        await schema.validate({ a: 1 }).should.be.fulfilled;
        await schema.validate({ c: 1 }).should.be.fulfilled;
        return schema.validate({ b: 1 }).should.be.rejectedWith(jp.ValidationError, 'oneOf');
      });
      it('should validate with oneOf which includes an array type', async function () {
        const schema = await jp.create(
          {
            oneOf: [
              {
                type: 'object',
                properties: {
                  a: true,
                  b: true,
                },
                additionalProperties: false,
              },
              {
                type: 'array',
                items: {
                  type: 'object',
                  properties: {
                    a: true,
                    b: true,
                  },
                  additionalProperties: false,
                },
              },
            ],
          },
          { scope: 'http://example.com' }
        );
        schema.validate({ a: 1 }).should.be.fulfilled;
        schema.validate({ b: 1 }).should.be.fulfilled;
        schema.validate({ c: 1 }).should.be.rejected;
        return schema.validate([{ a: 1 }]).should.be.fulfilled;
      });
    });
    describe('not', async function () {
      it('should validate with not', async function () {
        const schema = await jp.create(
          {
            not: {
              type: 'string',
            },
          },
          { scope: 'http://example.com' }
        );
        await schema.validate(true).should.be.fulfilled;
        await schema.validate(1).should.be.fulfilled;
        return schema.validate('test').should.be.rejectedWith(jp.ValidationError, 'not');
      });
    });
  });

  describe('default', function () {
    it('should not add default values if the option is not set', async function () {
      const schema = await jp.create(
        {
          default: 5,
        },
        { scope: 'http://example.com' }
      );
      await schema.validate(null).should.eventually.equal(null);
      await schema.validate(undefined).should.eventually.equal(undefined);
    });
    it('should return the default value if the option is set', async function () {
      const schema = await jp.create(
        {
          default: 5,
        },
        { scope: 'http://example.com' }
      );
      await schema.validate(null, { setDefault: true }).should.eventually.equal(null);
      await schema.validate(undefined, { setDefault: true }).should.eventually.equal(5);
    });
    it('should return the first default value when multiple schemas are validated', async function () {
      const schema = await jp.create(
        {
          type: 'object',
          properties: {
            a: {
              default: 1,
            },
            b: {
              default: 2,
            },
            d: {
              default: undefined,
            },
          },
          allOf: [
            {
              properties: {
                a: {
                  default: 3,
                },
                c: {
                  default: 4,
                },
              },
            },
            {
              properties: {
                c: {
                  default: 5,
                },
              },
            },
          ],
        },
        { scope: 'http://example.com' }
      );
      const res = await schema.validate({}, { setDefault: true });
      res.a.should.equal(1);
      res.b.should.equal(2);
      res.c.should.equal(4);
    });
    it('should ignore clauses not relevant for a type', async function () {
      const schema = await jp.create(
        {
          type: 'object',
          properties: {
            a: {
              type: 'string',
              multipleOf: 1,
              maximum: 1,
              minimum: 1,
              exclusiveMinimum: 1,
              exclusiveMaximum: 1,
            },
            b: {
              type: 'number',
              maxLength: 1,
              minLength: 1,
              pattern: 'a',
              format: 'uri',
              maxItems: 1,
              contains: {},
              maxProperties: 1,
              minProperties: 1,
              required: ['c'],
              properties: {},
              patternProperties: {},
              additionalProperties: {},
              propertyNames: {},
              dependencies: {},
            },
          },
        },
        { scope: 'http://example.com' }
      );
      return schema.validate({ a: 'test', b: 0 });
    });
  });
});


text:
namespace gl {

ScopedCGLSetCurrentContext::ScopedCGLSetCurrentContext(CGLContextObj context) {
  CGLContextObj previous_context = CGLGetCurrentContext();
  // It is possible for the previous context to have a zero reference count,
  // because making a context current does not increment the reference count.
  // In that case, do not restore the previous context.
  if (previous_context && CGLGetContextRetainCount(previous_context)) {
    previous_context_.reset(previous_context, base::scoped_policy::RETAIN);
  }
  CGLError error = CGLSetCurrentContext(context);
  DCHECK_EQ(error, kCGLNoError) << "CGLSetCurrentContext should never fail";
}

ScopedCGLSetCurrentContext::~ScopedCGLSetCurrentContext() {
  CGLError error = CGLSetCurrentContext(previous_context_);
  DCHECK_EQ(error, kCGLNoError) << "CGLSetCurrentContext should never fail";
}

}  // namespace gl

redpajama_set_name: RedPajamaGithub


text:
"""Test Z-Wave JS (value notification) events."""
from zwave_js_server.event import Event

from tests.common import async_capture_events

async def test_scenes(hass, hank_binary_switch, integration, client):
    """Test scene events."""
    # just pick a random node to fake the value notification events
    node = hank_binary_switch
    events = async_capture_events(hass, "zwave_js_event")

    # Publish fake Basic Set value notification
    event = Event(
        type="value notification",
        data={
            "source": "node",
            "event": "value notification",
            "nodeId": 32,
            "args": {
                "commandClassName": "Basic",
                "commandClass": 32,
                "endpoint": 0,
                "property": "event",
                "propertyName": "event",
                "value": 255,
                "metadata": {
                    "type": "number",
                    "readable": True,
                    "writeable": False,
                    "min": 0,
                    "max": 255,
                    "label": "Event value",
                },
                "ccVersion": 1,
            },
        },
    )
    node.receive_event(event)
    # wait for the event
    await hass.async_block_till_done()
    assert len(events) == 1
    assert events[0].data["home_id"] == client.driver.controller.home_id
    assert events[0].data["node_id"] == 32
    assert events[0].data["endpoint"] == 0
    assert events[0].data["command_class"] == 32
    assert events[0].data["command_class_name"] == "Basic"
    assert events[0].data["label"] == "Event value"
    assert events[0].data["value"] == 255

    # Publish fake Scene Activation value notification
    event = Event(
        type="value notification",
        data={
            "source": "node",
            "event": "value notification",
            "nodeId": 32,
            "args": {
                "commandClassName": "Scene Activation",
                "commandClass": 43,
                "endpoint": 0,
                "property": "SceneID",
                "propertyName": "SceneID",
                "value": 16,
                "metadata": {
                    "type": "number",
                    "readable": True,
                    "writeable": False,
                    "min": 0,
                    "max": 255,
                    "label": "Scene ID",
                },
                "ccVersion": 3,
            },
        },
    )
    node.receive_event(event)
    # wait for the event
    await hass.async_block_till_done()
    assert len(events) == 2
    assert events[1].data["command_class"] == 43
    assert events[1].data["command_class_name"] == "Scene Activation"
    assert events[1].data["label"] == "Scene ID"
    assert events[1].data["value"] == 16

    # Publish fake Central Scene value notification
    event = Event(
        type="value notification",
        data={
            "source": "node",
            "event": "value notification",
            "nodeId": 32,
            "args": {
                "commandClassName": "Central Scene",
                "commandClass": 91,
                "endpoint": 0,
                "property": "scene",
                "propertyKey": "001",
                "propertyName": "scene",
                "propertyKeyName": "001",
                "value": 4,
                "metadata": {
                    "type": "number",
                    "readable": True,
                    "writeable": False,
                    "min": 0,
                    "max": 255,
                    "label": "Scene 001",
                    "states": {
                        "0": "KeyPressed",
                        "1": "KeyReleased",
                        "2": "KeyHeldDown",
                        "3": "KeyPressed2x",
                        "4": "KeyPressed3x",
                        "5": "KeyPressed4x",
                        "6": "KeyPressed5x",
                    },
                },
                "ccVersion": 3,
            },
        },
    )
    node.receive_event(event)
    # wait for the event
    await hass.async_block_till_done()
    assert len(events) == 3
    assert events[2].data["command_class"] == 91
    assert events[2].data["command_class_name"] == "Central Scene"
    assert events[2].data["label"] == "Scene 001"
    assert events[2].data["value"] == "KeyPressed3x"

async def test_notifications(hass, hank_binary_switch, integration, client):
    """Test notification events."""
    # just pick a random node to fake the value notification events
    node = hank_binary_switch
    events = async_capture_events(hass, "zwave_js_event")

    # Publish fake Basic Set value notification
    event = Event(
        type="notification",
        data={
            "source": "node",
            "event": "notification",
            "nodeId": 23,
            "notificationLabel": "Keypad lock operation",
            "parameters": {"userId": 1},
        },
    )
    node.receive_event(event)
    # wait for the event
    await hass.async_block_till_done()
    assert len(events) == 1
    assert events[0].data["type"] == "notification"
    assert events[0].data["home_id"] == client.driver.controller.home_id
    assert events[0].data["node_id"] == 32
    assert events[0].data["label"] == "Keypad lock operation"
    assert events[0].data["parameters"]["userId"] == 1


text:
<?php

namespace Cpliakas\DynamoDb\ODM\Test;

use Cpliakas\DynamoDb\ODM\Events;

class DummyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A dummy test that calls a beacon method ensuring the class is autolaoded.
     *
     * @see https://github.com/cpliakas/php-project-starter/issues/19
     * @see https://github.com/cpliakas/php-project-starter/issues/21
     */
    public function testAutoload()
    {
        $class = new Events();
        $this->assertTrue((bool) $class);
    }
}


text:
<?php namespace Tequilarapido\Database;

use Illuminate\Database\Capsule\Manager as Capsule;

class Database
{

    /**
     * Initialize Illuminate Database connection
     *
     * @param $dbConfig
     */
    public function connect($dbConfig)
    {
        $capsule = new Capsule;
        $capsule->addConnection($dbConfig);
        $capsule->bootEloquent();
        $capsule->setAsGlobal();
    }

    public function size($database)
    {
        $query = '';
        $query .= 'SELECT table_schema, Sum(data_length + index_length) as size ';
        $query .= 'FROM   information_schema.tables ';
        $query .= 'WHERE table_schema = ? ';
        $query .= 'GROUP BY table_schema';

        $res = static::select($query, array($database));
        if (!empty($res[0]['size'])) {
            return round($res[0]['size'] / 1024 / 1024);
        }

        return false;
    }

    //
    // Helpers
    //

    public static function select($query, $bindings = array())
    {
        return Capsule::connection()->select($query, $bindings);
    }

    public static function update($query, $bindings = array())
    {
        return Capsule::connection()->update($query, $bindings);
    }

    public static function statement($query, $bindings = array())
    {
        return Capsule::connection()->statement($query, $bindings);
    }

    public static function enableQueryLog()
    {
        Capsule::connection()->enableQueryLog();
    }

    public static function getLastQuery()
    {
        $queries = Capsule::connection()->getQueryLog();
        return end($queries);
    }

    public static function connection()
    {
        return Capsule::connection();
    }

    public static function schema()
    {
        return Capsule::schema();
    }

    public static function table($table)
    {
        return Capsule::table($table);
    }

    public static function beginTransaction()
    {
        return Capsule::connection()->beginTransaction();
    }

    public static function commit()
    {
        return Capsule::connection()->commit();
    }

    public static function rollback()
    {
        return Capsule::connection()->rollBack();
    }

}


text:
import collections
import copy
import logging
import sys
import traceback

from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six

import oslo_messaging
from oslo_messaging._i18n import _
from oslo_messaging._i18n import _LE
from oslo_messaging import _utils as utils

LOG = logging.getLogger(__name__)

_EXCEPTIONS_MODULE = 'exceptions' if six.PY2 else 'builtins'
_EXCEPTIONS_MODULES = ['exceptions', 'builtins']

'''RPC Envelope Version.

This version number applies to the top level structure of messages sent out.
It does *not* apply to the message payload, which must be versioned
independently.  For example, when using rpc APIs, a version number is applied
for changes to the API being exposed over rpc.  This version number is handled
in the rpc proxy and dispatcher modules.

This version number applies to the message envelope that is used in the
serialization done inside the rpc layer.  See serialize_msg() and
deserialize_msg().

The current message format (version 2.0) is very simple.  It is:

    {
        'oslo.version': <RPC Envelope Version as a String>,
        'oslo.message': <Application Message Payload, JSON encoded>
    }

Message format version '1.0' is just considered to be the messages we sent
without a message envelope.

So, the current message envelope just includes the envelope version.  It may
eventually contain additional information, such as a signature for the message
payload.

We will JSON encode the application message payload.  The message envelope,
which includes the JSON encoded application message body, will be passed down
to the messaging libraries as a dict.
'''
_RPC_ENVELOPE_VERSION = '2.0'

_VERSION_KEY = 'oslo.version'
_MESSAGE_KEY = 'oslo.message'

_REMOTE_POSTFIX = '_Remote'

class RPCException(Exception):
    msg_fmt = _("An unknown RPC related exception occurred.")

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if not message:
            try:
                message = self.msg_fmt % kwargs

            except Exception:
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception(_LE('Exception in string format operation, '
                                  'kwargs are:'))
                for name, value in kwargs.items():
                    LOG.error("%s: %s", name, value)
                # at least get the core message out if something happened
                message = self.msg_fmt

        super(RPCException, self).__init__(message)

class Timeout(RPCException):
    """Signifies that a timeout has occurred.

    This exception is raised if the rpc_response_timeout is reached while
    waiting for a response from the remote side.
    """
    msg_fmt = _('Timeout while waiting on RPC response - '
                'topic: "%(topic)s", RPC method: "%(method)s" '
                'info: "%(info)s"')

    def __init__(self, info=None, topic=None, method=None):
        """Initiates Timeout object.

        :param info: Extra info to convey to the user
        :param topic: The topic that the rpc call was sent to
        :param method: The name of the rpc method being
                                called
        """
        self.info = info
        self.topic = topic
        self.method = method
        super(Timeout, self).__init__(
            None,
            info=info or _('<unknown>'),
            topic=topic or _('<unknown>'),
            method=method or _('<unknown>'))

class DuplicateMessageError(RPCException):
    msg_fmt = _("Found duplicate message(%(msg_id)s). Skipping it.")

class InvalidRPCConnectionReuse(RPCException):
    msg_fmt = _("Invalid reuse of an RPC connection.")

class UnsupportedRpcVersion(RPCException):
    msg_fmt = _("Specified RPC version, %(version)s, not supported by "
                "this endpoint.")

class UnsupportedRpcEnvelopeVersion(RPCException):
    msg_fmt = _("Specified RPC envelope version, %(version)s, "
                "not supported by this endpoint.")

class RpcVersionCapError(RPCException):
    msg_fmt = _("Specified RPC version cap, %(version_cap)s, is too low")

class Connection(object):
    """A connection, returned by rpc.create_connection().

    This class represents a connection to the message bus used for rpc.
    An instance of this class should never be created by users of the rpc API.
    Use rpc.create_connection() instead.
    """
    def close(self):
        """Close the connection.

        This method must be called when the connection will no longer be used.
        It will ensure that any resources associated with the connection, such
        as a network connection, and cleaned up.
        """
        raise NotImplementedError()

def serialize_remote_exception(failure_info):
    """Prepares exception data to be sent over rpc.

    Failure_info should be a sys.exc_info() tuple.

    """
    tb = traceback.format_exception(*failure_info)

    failure = failure_info[1]

    kwargs = {}
    if hasattr(failure, 'kwargs'):
        kwargs = failure.kwargs

    # NOTE(matiu): With cells, it's possible to re-raise remote, remote
    # exceptions. Lets turn it back into the original exception type.
    cls_name = six.text_type(failure.__class__.__name__)
    mod_name = six.text_type(failure.__class__.__module__)
    if (cls_name.endswith(_REMOTE_POSTFIX) and
            mod_name.endswith(_REMOTE_POSTFIX)):
        cls_name = cls_name[:-len(_REMOTE_POSTFIX)]
        mod_name = mod_name[:-len(_REMOTE_POSTFIX)]

    data = {
        'class': cls_name,
        'module': mod_name,
        'message': six.text_type(failure),
        'tb': tb,
        'args': failure.args,
        'kwargs': kwargs
    }

    json_data = jsonutils.dumps(data)

    return json_data

def deserialize_remote_exception(data, allowed_remote_exmods):
    failure = jsonutils.loads(six.text_type(data))

    trace = failure.get('tb', [])
    message = failure.get('message', "") + "\n" + "\n".join(trace)
    name = failure.get('class')
    module = failure.get('module')

    # the remote service which raised the given exception might have a
    # different python version than the caller. For example, the caller might
    # run python 2.7, while the remote service might run python 3.4. Thus,
    # the exception module will be "builtins" instead of "exceptions".
    if module in _EXCEPTIONS_MODULES:
        module = _EXCEPTIONS_MODULE

    # NOTE(ameade): We DO NOT want to allow just any module to be imported, in
    # order to prevent arbitrary code execution.
    if module != _EXCEPTIONS_MODULE and module not in allowed_remote_exmods:
        return oslo_messaging.RemoteError(name, failure.get('message'), trace)

    try:
        __import__(module)
        mod = sys.modules[module]
        klass = getattr(mod, name)
        if not issubclass(klass, Exception):
            raise TypeError("Can only deserialize Exceptions")

        failure = klass(*failure.get('args', []), **failure.get('kwargs', {}))
    except (AttributeError, TypeError, ImportError):
        return oslo_messaging.RemoteError(name, failure.get('message'), trace)

    ex_type = type(failure)
    str_override = lambda self: message
    new_ex_type = type(ex_type.__name__ + _REMOTE_POSTFIX, (ex_type,),
                       {'__str__': str_override, '__unicode__': str_override})
    new_ex_type.__module__ = '%s%s' % (module, _REMOTE_POSTFIX)
    try:
        # NOTE(ameade): Dynamically create a new exception type and swap it in
        # as the new type for the exception. This only works on user defined
        # Exceptions and not core Python exceptions. This is important because
        # we cannot necessarily change an exception message so we must override
        # the __str__ method.
        failure.__class__ = new_ex_type
    except TypeError:
        # NOTE(ameade): If a core exception then just add the traceback to the
        # first exception argument.
        failure.args = (message,) + failure.args[1:]
    return failure

class CommonRpcContext(object):
    def __init__(self, **kwargs):
        self.values = kwargs

    def __getattr__(self, key):
        try:
            return self.values[key]
        except KeyError:
            raise AttributeError(key)

    def to_dict(self):
        return copy.deepcopy(self.values)

    @classmethod
    def from_dict(cls, values):
        return cls(**values)

    def deepcopy(self):
        return self.from_dict(self.to_dict())

    def update_store(self):
        # local.store.context = self
        pass

class ClientException(Exception):
    """Encapsulates actual exception expected to be hit by a RPC proxy object.

    Merely instantiating it records the current exception information, which
    will be passed back to the RPC client without exceptional logging.
    """
    def __init__(self):
        self._exc_info = sys.exc_info()

def serialize_msg(raw_msg):
    # NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more
    # information about this format.
    msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION,
           _MESSAGE_KEY: jsonutils.dumps(raw_msg)}

    return msg

def deserialize_msg(msg):
    # NOTE(russellb): Hang on to your hats, this road is about to
    # get a little bumpy.
    #
    # Robustness Principle:
    #    "Be strict in what you send, liberal in what you accept."
    #
    # At this point we have to do a bit of guessing about what it
    # is we just received.  Here is the set of possibilities:
    #
    # 1) We received a dict.  This could be 2 things:
    #
    #   a) Inspect it to see if it looks like a standard message envelope.
    #      If so, great!
    #
    #   b) If it doesn't look like a standard message envelope, it could either
    #      be a notification, or a message from before we added a message
    #      envelope (referred to as version 1.0).
    #      Just return the message as-is.
    #
    # 2) It's any other non-dict type.  Just return it and hope for the best.
    #    This case covers return values from rpc.call() from before message
    #    envelopes were used.  (messages to call a method were always a dict)

    if not isinstance(msg, dict):
        # See #2 above.
        return msg

    base_envelope_keys = (_VERSION_KEY, _MESSAGE_KEY)
    if not all(map(lambda key: key in msg, base_envelope_keys)):
        #  See #1.b above.
        return msg

    # At this point we think we have the message envelope
    # format we were expecting. (#1.a above)

    if not utils.version_is_compatible(_RPC_ENVELOPE_VERSION,
                                       msg[_VERSION_KEY]):
        raise UnsupportedRpcEnvelopeVersion(version=msg[_VERSION_KEY])

    raw_msg = jsonutils.loads(msg[_MESSAGE_KEY])

    return raw_msg

class DecayingTimer(object):
    def __init__(self, duration=None):
        self._watch = timeutils.StopWatch(duration=duration)

    def start(self):
        self._watch.start()

    def check_return(self, timeout_callback=None, *args, **kwargs):
        maximum = kwargs.pop('maximum', None)
        left = self._watch.leftover(return_none=True)
        if left is None:
            return maximum
        if left <= 0 and timeout_callback is not None:
            timeout_callback(*args, **kwargs)
        return left if maximum is None else min(left, maximum)

# NOTE(sileht): Even if rabbit has only one Connection class,
# this connection can be used for two purposes:
# * wait and receive amqp messages (only do read stuffs on the socket)
# * send messages to the broker (only do write stuffs on the socket)
# The code inside a connection class is not concurrency safe.
# Using one Connection class instance for doing both, will result
# of eventlet complaining of multiple greenthreads that read/write the
# same fd concurrently... because 'send' and 'listen' run in different
# greenthread.
# So, a connection cannot be shared between thread/greenthread and
# this two variables permit to define the purpose of the connection
# to allow drivers to add special handling if needed (like heatbeat).
# amqp drivers create 3 kind of connections:
# * driver.listen*(): each call create a new 'PURPOSE_LISTEN' connection
# * driver.send*(): a pool of 'PURPOSE_SEND' connections is used
# * driver internally have another 'PURPOSE_LISTEN' connection dedicated
#   to wait replies of rpc call
PURPOSE_LISTEN = 'listen'
PURPOSE_SEND = 'send'

class ConnectionContext(Connection):
    """The class that is actually returned to the create_connection() caller.

    This is essentially a wrapper around Connection that supports 'with'.
    It can also return a new Connection, or one from a pool.

    The function will also catch when an instance of this class is to be
    deleted.  With that we can return Connections to the pool on exceptions
    and so forth without making the caller be responsible for catching them.
    If possible the function makes sure to return a connection to the pool.
    """

    def __init__(self, connection_pool, purpose):
        """Create a new connection, or get one from the pool."""
        self.connection = None
        self.connection_pool = connection_pool
        pooled = purpose == PURPOSE_SEND
        if pooled:
            self.connection = connection_pool.get()
        else:
            # a non-pooled connection is requested, so create a new connection
            self.connection = connection_pool.create(purpose)
        self.pooled = pooled
        self.connection.pooled = pooled

    def __enter__(self):
        """When with ConnectionContext() is used, return self."""
        return self

    def _done(self):
        """If the connection came from a pool, clean it up and put it back.
        If it did not come from a pool, close it.
        """
        if self.connection:
            if self.pooled:
                # Reset the connection so it's ready for the next caller
                # to grab from the pool
                try:
                    self.connection.reset()
                except Exception:
                    LOG.exception(_LE("Fail to reset the connection, drop it"))
                    try:
                        self.connection.close()
                    except Exception:
                        pass
                    self.connection = self.connection_pool.create()
                finally:
                    self.connection_pool.put(self.connection)
            else:
                try:
                    self.connection.close()
                except Exception:
                    pass
            self.connection = None

    def __exit__(self, exc_type, exc_value, tb):
        """End of 'with' statement.  We're done here."""
        self._done()

    def __del__(self):
        """Caller is done with this connection.  Make sure we cleaned up."""
        self._done()

    def close(self):
        """Caller is done with this connection."""
        self._done()

    def __getattr__(self, key):
        """Proxy all other calls to the Connection instance."""
        if self.connection:
            return getattr(self.connection, key)
        else:
            raise InvalidRPCConnectionReuse()

class ConfigOptsProxy(collections.Mapping):
    """Proxy for oslo_config.cfg.ConfigOpts.

    Values from the query part of the transport url (if they are both present
    and valid) override corresponding values from the configuration.
    """

    def __init__(self, conf, url):
        self._conf = conf
        self._url = url

    def __getattr__(self, name):
        value = getattr(self._conf, name)
        if isinstance(value, self._conf.GroupAttr):
            return self.GroupAttrProxy(self._conf, name, value, self._url)
        return value

    def __getitem__(self, name):
        return self.__getattr__(name)

    def __contains__(self, name):
        return name in self._conf

    def __iter__(self):
        return iter(self._conf)

    def __len__(self):
        return len(self._conf)

    class GroupAttrProxy(collections.Mapping):
        """Internal helper proxy for oslo_config.cfg.ConfigOpts.GroupAttr."""

        _VOID_MARKER = object()

        def __init__(self, conf, group_name, group, url):
            self._conf = conf
            self._group_name = group_name
            self._group = group
            self._url = url

        def __getattr__(self, opt_name):
            # Make sure that the group has this specific option
            opt_value_conf = getattr(self._group, opt_name)
            # If the option is also present in the url and has a valid
            # (i.e. convertible) value type, then try to override it
            opt_value_url = self._url.query.get(opt_name, self._VOID_MARKER)
            if opt_value_url is self._VOID_MARKER:
                return opt_value_conf
            opt_info = self._conf._get_opt_info(opt_name, self._group_name)
            return opt_info['opt'].type(opt_value_url)

        def __getitem__(self, opt_name):
            return self.__getattr__(opt_name)

        def __contains__(self, opt_name):
            return opt_name in self._group

        def __iter__(self):
            return iter(self._group)

        def __len__(self):
            return len(self._group)


text:
package com.dutproject.coffee360.model.bean;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="integer")
public class XmlInteger {
	private int value;

	public int getValue() {
		return value;
	}

	@XmlElement
	public void setValue(int value) {
		this.value = value;
	}

}


text:
drop table if exists person;
create table person (id int, nr_department int);

insert into person (id,  nr_department)
values (1, 1);

drop table if exists productattribute;
create table productattribute (nr_id int);

insert into productattribute(nr_id)
values (1);

drop table if exists department;
create table department (nr_id int,nr_attribute int,person int);

insert into department(nr_id,nr_attribute,person)
values (1,1,1);


text:
<?php

// +----------------------------------------------------------------------
// | date: 2015-12-11
// +----------------------------------------------------------------------
// | LocationEvent.php: 后端处理顶级当前位置缓存事件
// +----------------------------------------------------------------------
// | Author: yangyifan <yangyifanphp@gmail.com>
// +----------------------------------------------------------------------

namespace App\Events\Admin\Cache;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use App\Commands\Admin\Cache\LocationCommand;

class LocationEvent extends Event
{

	use SerializesModels;

	/**
	 * Create a new event instance.
	 *
	 * @return void
	 * @author yangyifan <yangyifanphp@gmail.com>
	 */
	public function __construct()
	{

	}

	/**
	 * 处理事件
	 *
	 * @return bool
	 * @author yangyifan <yangyifanphp@gmail.com>
	 */
	public function handle()
	{
		\Bus::dispatch(
			new LocationCommand()
		);
		return true;
	}

}


text:
//
//  AXDecayAnimation.h
//  AXAnimationChain
//
//  Created by devedbox on 2017/3/31.
//  Copyright © 2017年 devedbox. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

#import <QuartzCore/QuartzCore.h>

#ifndef AXDecayAnimationUnavailable
#define AXDecayAnimationUnavailable(AXDecayAnimationClass)\
@interface AXDecayAnimationClass (Unavailable)\
- (void)setTimingFunction:(CAMediaTimingFunction *)timingFunction __attribute__((unavailable));\
- (void)setValues:(NSArray *)values __attribute__((unavailable));\
- (void)setPath:(CGPathRef)path __attribute__((unavailable));\
- (void)setKeyTimes:(NSArray<NSNumber *> *)keyTimes __attribute__((unavailable));\
- (void)setTimingFunctions:(NSArray<CAMediaTimingFunction *> *)timingFunctions __attribute__((unavailable));\
- (void)setCalculationMode:(NSString *)calculationMode __attribute__((unavailable));\
- (void)setTensionValues:(NSArray<NSNumber *> *)tensionValues __attribute__((unavailable));\
- (void)setContinuityValues:(NSArray<NSNumber *> *)continuityValues __attribute__((unavailable));\
- (void)setBiasValues:(NSArray<NSNumber *> *)biasValues __attribute__((unavailable));\
- (void)setRotationMode:(NSString *)rotationMode __attribute__((unavailable));\
@end
#endif

NS_ASSUME_NONNULL_BEGIN
@interface AXDecayAnimation : CAKeyframeAnimation
/* The initial velocity of the object attached to the spring. Defaults
 * to zero, which represents an unmoving object. Negative values
 * represent the object moving away from the spring attachment point,
 * positive values represent the object moving towards the spring
 * attachment point. */
@property(assign, nonatomic) CGFloat velocity;
/**
 @abstract The deceleration factor.
 @discussion Values specifies should be in the range [0, 1]. Lower values results in faster deceleration. Defaults to 0.998.
 */
@property(assign, nonatomic) CGFloat deceleration;
/**
 @abstract The expected duration.
 @discussion Derived based on input velocity and deceleration values.
 */
@property(readonly, nonatomic) CFTimeInterval settlingDuration;

@property(nullable, strong, nonatomic) id fromValue;
@end

AXDecayAnimationUnavailable(AXDecayAnimation)
NS_ASSUME_NONNULL_END


text:
package com.jajja.arachne.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.IDN;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jajja.arachne.exceptions.MalformedDomainException;

/**
 * A class for parsing Internet domains and optionally matching them against the
 * "Public Suffix List" (http://publicsuffix.org/).
 *
 * This class accurately implements the public suffix specification, but also
 * provides support for identifying "subleased" domains, such as dyndns.org.
 *
 * To support subleased domains, the provided copy of the public suffix list
 * has been split into multiple files; one "ICANN registered" part, and one
 * "subleased" part. In addition to this, the list has been extended by several
 * private records (such as *.wordpress.com), and even some ICANN entries that
 * appear to be missing from the public suffix list (such as com.tp).
 *
 * For reference check out: http://publicsuffix.org
 *
 * @author Martin Korinth <martin.korinth@jajja.com>
 */
public class Domain extends Host {

    private final static Pattern deprefixHostPattern = Pattern.compile("^(www|ftp|smtp|mail|pop)[0-9]*\\.", Pattern.CASE_INSENSITIVE);
    private static Log log = LogFactory.getLog(Domain.class);
    private static Map<String, List<Rule>> icannRules = Rule.loadIcann();
    private static Map<String, List<Rule>> privateRules = Rule.loadPrivate();

    private String[] labels;
    private boolean isMatched = false;

    private String fqdn;
    private String tld;
    private Record _icannRegisteredRecord;
    private Record _subleasedRecord;
    private String _publicSuffix;

    /**
     * Creates a domain.
     *
     * @param name
     *            the domain name
     * @throws MalformedDomainException
     *             when the domain name can not be parsed as a domain
     */
    public Domain(String name) throws MalformedDomainException {
        super(IDN.toASCII(name));
        parse();
    }

    /**
     * Provides the fully qualified domain name of the domain, in lowercase.
     *
     * @return the fully qualified domain name
     */
    public String getFqdn() {
        return fqdn;
    }

    /**
     * Provides the top level part of the domain in lowercase, e.g.
     * "uk" for "www.foo.stwilfrids.devon.sch.uk".
     *
     *
     * @return the top level domain
     */
    public String getTld() {
        return tld;
    }

    /**
     * Provides the ICANN registered record of the domain if such exists.
     *
     * @return the registered record if such exists, otherwise null
     */
    public Record getIcannRegisteredRecord() {
        match();
        return _icannRegisteredRecord;
    }

    /**
     * Provides the ICANN registered part of the domain.
     * e.g. "foo.co.uk" for "baz.bar.foo.co.uk", null for "co.uk" (can not be registered).
     *
     * @return the ICANN registered part of the domain, or null if not an ICANN registered domain
     */
    public String getIcannRegistered() {
        Record record = getIcannRegisteredRecord();
        return record != null ? record.getEntry() : null;
    }

    /**
     * Provides the suffix for the ICANN registered part of the domain.
     * e.g. "co.uk" for "baz.bar.foo.co.uk", null for "co.uk" (can not be registered).
     *
     * @return the suffix for the ICANN registered part of the domain, or null if not an ICANN registered domain
     */
    public String getIcannRegisteredSuffix() {
        Record record = getIcannRegisteredRecord();
        return record != null ? record.getSuffix() : null;
    }

    /**
     * Provides the rule matching the ICANN registered domain.
     *
     * @return the rule matching the ICANN registered domain, or null if not an ICANN registered domain
     */
    public String getIcannRegisteredRule() {
        Record record = getIcannRegisteredRecord();
        return record != null ? record.getRule() : null;
    }

    /**
     * Tells whether the domain is an ICANN domain or not.
     *
     * @return true if the domain is an ICANN registered domain, false otherwise
     */
    public boolean isIcannRegistered() {
        return getRegisteredRecord() != null;
    }

    /**
     * Provides the subleased record of the domain if such exists.
     *
     * @return the subleased record if such exists, otherwise null
     */
    public Record getSubleasedRecord() {
        match();
        return _subleasedRecord;
    }

    /**
     * Provides the subleased part of the domain.
     *
     * e.g. "foo.dyndns.org" for "baz.bar.foo.dyndns.org", null for "dyndns.org".
     *
     * @return the subleased part of the domain, or null
     */
    public String getSubleased() {
        Record record = getSubleasedRecord();
        return record != null ? record.getEntry() : null;
    }

    /**
     * Provides the suffix for the subleased part of the domain.
     *
     * e.g. "dyndns.org" for "baz.bar.dyndns.org", null for "dyndns.org".
     *
     * @return the suffix for the subleased part of the domain, or null
     */
    public String getSubleasedSuffix() {
        Record record = getSubleasedRecord();
        return record != null ? record.getSuffix() : null;
    }

    /**
     * Provides the rule matching the subleased domain.
     *
     * @return the rule matching the subleased domain, or null
     */
    public String getSubleasedRule() {
        Record record = getSubleasedRecord();
        return record != null ? record.getRule() : null;
    }

    /**
     * Tells whether the domain is subleased or not.
     *
     * @return true if the domain is subleased, false otherwise
     */
    public boolean isSubleased() {
        return getSubleasedRecord() != null;
    }

    /**
     * Provides the registered record, or null.
     *
     * @return the registered record, or null
     */
    public Record getRegisteredRecord() {
        return isSubleased() ? getSubleasedRecord() : getIcannRegisteredRecord();
    }

    /**
     * Provides the registered domain, or null.
     *
     * @return the registered domain, or null
     */
    public String getRegistered() {
        Record record = getRegisteredRecord();
        return record != null ? record.getEntry() : null;
    }

    /**
     * Provides the suffix of the registered domain, or null.
     *
     * @return the suffix of the registered domain, or null
     */
    public String getRegisteredSuffix() {
        Record record = getRegisteredRecord();
        return record != null ? record.getSuffix() : null;
    }

    /**
     * Provides the rule matching the registered domain, or null.
     *
     * @return the rule matching the registered domain, or null
     */
    public String getRegisteredRule() {
        Record record = getRegisteredRecord();
        return record != null ? record.getRule() : null;
    }

    /**
     * Tells whether the domain is a registered or not.
     *
     * @return true if the domain is registered, false otherwise
     */
    public boolean isRegistered() {
        return getRegisteredRecord() != null;
    }

    /**
     * Provides the matched public suffix in the ICANN part of the list,
     * regardless of whether a record was matched or not.
     *
     * @return the matched public suffix, or null for no matched public suffix
     */
    public String getPublicSuffix() {   // XXX wtf is this for?
        match();
        return _publicSuffix;
    }

    public String getDeprefixed() {
        String registered = getRegistered();
        // Don't remove www from "www.com", etc
        if (registered == null || registered.equalsIgnoreCase(string)) {
            return string.toLowerCase();
        }
        Matcher m = deprefixHostPattern.matcher(string);
        return m.replaceFirst("");
    }

    private void parse() throws MalformedDomainException {
        fqdn = string.toLowerCase();
        if (fqdn.isEmpty())
            throw new MalformedDomainException(string, "Empty domain!");
        labels = fqdn.split("\\."); // TODO: implement proper string split for performance
        if (253 < fqdn.length())
            throw new MalformedDomainException(string, "Too many characters in fully qualified domain name!");
        if (127 < labels.length)
            throw new MalformedDomainException(string, "Too many labels in fully qualified domain name!");
        for (String label : labels) {
            if (63 < label.length())
                throw new MalformedDomainException(string, "Too many characters in domain name!");
            if (!label.matches("[0-9a-z-]+")) // TODO: compile this statically or search manually for performance
                throw new MalformedDomainException(string, "Invalid charcters in domain name!");
        }
        tld = labels[labels.length - 1];
    }

    private void match() {
        if (!isMatched) {
            _icannRegisteredRecord = getRecord(labels, true);
            if (_icannRegisteredRecord != null) {
                Record record = getRecord(labels, false);
                if (record != null && !record.getEntry().equals("www." + _icannRegisteredRecord.getEntry())) {
                    _subleasedRecord = record;
                }
            }
            isMatched = true;
        }
    }

    private Record getRecord(String[] labels, boolean isPublic) {
        Record record = null;
        List<Rule> rules = isPublic ? icannRules.get(tld) : privateRules.get(tld);
        if (rules != null) {
            for (Rule rule : rules) {
                record = rule.match(labels);
                if (record != null) {
                    if (isPublic) {
                        this._publicSuffix = record.getRule();
                    }
                    if (record.getEntry().isEmpty()) {
                        record = null;
                    }
                    break;
                }
            }
        }
        return record;
    }

    public static void main(String[] args) {
        try {
//            System.out.println(new Domain("peat.se"));
//            System.out.println(new Domain("peat.wordpress.se"));
//            System.out.println(new Domain("peat.wordpress.com"));
//            System.out.println(new Domain("peat.co.uk"));
//            System.out.println(new Domain("peat.co.se"));
//            System.out.println(new Domain("pEaT.sE"));
//            System.out.println(new Domain("peat.local"));
//            System.out.println(new Domain("local"));
            System.out.println(new Domain("lol.lol.mil.no"));
            System.out.println(new Domain("lol.mil.no"));
            System.out.println(new Domain("mil.no"));
        } catch (MalformedDomainException e) {
            e.printStackTrace();
        }
    }

    private static class Rule implements Comparable<Rule> {

        private String rule;

        private boolean isException;

        private boolean isExact;

        private String[] patterns;

        private Rule(String rule) {
            this.rule = rule;
            isException = rule.startsWith("!");
            isExact = rule.startsWith("?");
            isException = isException || isExact;
            patterns = IDN.toASCII(rule.replaceAll("[!?]", "")).split("\\.");
        }

        Record match(String[] labels) {
            String entry = "";
            for (int i = 0; i < Math.min(patterns.length, labels.length); i++) {
                String pattern = patterns[patterns.length - (i + 1)];
                String label = labels[labels.length - (i + 1)];
                if ("*".equals(pattern) || label.equals(pattern)) {
                    entry = label + (entry.isEmpty() ? "" : '.') + entry;
                } else {
                    return null;
                }
            }
            String suffix = null;
            if (isException) {
                if (labels.length < patterns.length) {
                    return null;
                } else {
                    if (isExact && labels.length != patterns.length) {
                        return null;
                    }
                    suffix = isExact ? entry.substring(Math.max(0, entry.indexOf('.') + 1)) : entry;
                }
            } else {
                if (patterns.length < labels.length) {
                    suffix = entry;
                    entry = labels[labels.length - (patterns.length + 1)] + '.' + entry;
                } else {
                    entry = "";
                }
            }
            Record record = new Record();
            record.setEntry(entry);
            record.setSuffix(suffix);
            record.setRule(rule);
            return record;
        }

        private String getTld() {
            return patterns[patterns.length - 1];
        }

        private int weight() {
            return patterns.length + (isException ? 255 : 0) + (isExact ? 255 : 0);
        }

        static Map<String, List<Rule>> loadIcann() {
            Map<String, List<Rule>> map = new HashMap<String, List<Rule>>();
            add("/suffix/icann_effective_tld_names.dat", map);
            add("/suffix/icann_patch_tld_names.dat", map);
            for (String tld : map.keySet()) {
                Collections.sort(map.get(tld));
            }
            return map;
        }

        static Map<String, List<Rule>> loadPrivate() {
            Map<String, List<Rule>> map = new HashMap<String, List<Rule>>();
            add("/suffix/private_effective_tld_names.dat", map);
            add("/suffix/private_patch_tld_names.dat", map);
            for (String tld : map.keySet()) {
                Collections.sort(map.get(tld));
            }
            return map;
        }

        private static void add(String file,  Map<String, List<Rule>> map) {
            for (Rule rule : read(file)) {
                List<Rule> rules = map.get(rule.getTld());
                if (rules == null) {
                    rules = new LinkedList<Rule>();
                    map.put(rule.getTld(), rules);
                }
                rules.add(rule);
            }
        }

        private static List<Rule> read(String file) {
            List<Rule> rules = null;
            try {
                log.info("Trying file resource for " + file);
                rules = read(new FileInputStream(new File("/usr/share/arachne" + file)));
            } catch (Exception e) {
                log.info("Trying class path resource for effective TLD names " + file);
                rules = read(Rule.class.getResourceAsStream(file));
            }
            return rules != null ? rules : new LinkedList<Rule>();
        }

        private static List<Rule> read(InputStream inputStream) {
            BufferedReader bufferedReader = null;
            List<Rule> rules = new LinkedList<Rule>();
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    if (!line.matches("(\\s+.*)|(/+.*)") && !line.isEmpty()) {
                        try {
                            rules.add(new Rule(line.trim()));
                        } catch (Exception e) {
                            log.error("Failed to parse public domain suffix rule from line: " + line, e);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("Failed to read line", e);
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        log.warn("Failed to close reader", e);
                    }
                }
            }
            return rules;
        }

        @Override
        public int compareTo(Rule rule) {
            return rule.weight() - weight();
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("[ definition => ");
            builder.append(rule);
            builder.append(", labels => ");
            builder.append(Arrays.asList(patterns));
            builder.append(", isException => ");
            builder.append(isException);
            builder.append(" ]");
            return builder.toString();
        }

    }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

/**
 * Customization class that allows per-component type handling of various SCS editor functionality.
 */
class ISCSEditorCustomization
{
public:
	virtual ~ISCSEditorCustomization() {}

	/**
	 * Process click in the viewport.
	 * @param	InViewportClient	The viewport client receiving the click
	 * @param	InView				The scene view receiving the click
	 * @param	InHitProxy			The hit proxy that was clicked
	 * @param	InKey				The key that was pressed
	 * @param	InEvent				The input event that occurred
	 * @param	InHitX				The X location of the click
	 * @param	InHitY				The Y location of the click
	 * @return true if the operation was handled.
	 */
	virtual bool HandleViewportClick(const TSharedRef<FEditorViewportClient>& InViewportClient, class FSceneView& InView, class HHitProxy* InHitProxy, FKey InKey, EInputEvent InEvent, uint32 InHitX, uint32 InHitY) = 0;

	/**
	 * Handle drag in the viewport
	 * @param	InSceneComponent		The scene component being dragged
	 * @param	InComponentTemplate		The template corresponding to the scene component
	 * @param	InDeltaTranslation		The delta translation being applied
	 * @param	InDeltaRotation			The delta rotation being applied
	 * @param	InDeltaScale			The delta scale being applied
	 * @param	InPivot					The povot point for any transformations
	 * @return true if the operation was handled.
	 */
	virtual bool HandleViewportDrag(class USceneComponent* InSceneComponent, class USceneComponent* InComponentTemplate, const FVector& InDeltaTranslation, const FRotator& InDeltaRotation, const FVector& InDeltaScale, const FVector& InPivot) = 0;

	/**
	 * Get the widget location for this scene component
	 * @param	InSceneComponent		The scene component to get location for
	 * @param	OutWidgetLocation		The output widget location
	 * @return true if the operation was handled.
	 */
	virtual bool HandleGetWidgetLocation(class USceneComponent* InSceneComponent, FVector& OutWidgetLocation) = 0;

	/**
	 * Get the widget transform for this scene component
	 * @param	InSceneComponent		The scene component to get transform for
	 * @param	OutWidgetLocation		The output widget transform
	 * @return true if the operation was handled.
	 */
	virtual bool HandleGetWidgetTransform(class USceneComponent* InSceneComponent, FMatrix& OutWidgetTransform) = 0;
};


text:
from flask import Blueprint

auth = Blueprint('auth', __name__)
from . import routes