text:
'use strict';
// These tests check the Installations functionality of the REST API.
// Ported from installation_collection_test.go

var auth = require('../src/Auth');
var cache = require('../src/cache');
var Config = require('../src/Config');
var DatabaseAdapter = require('../src/DatabaseAdapter');
var Parse = require('parse/node').Parse;
var rest = require('../src/rest');

var config = new Config('test');
let database = DatabaseAdapter.getDatabaseConnection('test', 'test_');

describe('Installations', () => {

  it('creates an android installation with ids', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var device = 'android';
    var input = {
      'installationId': installId,
      'deviceType': device
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.installationId).toEqual(installId);
      expect(obj.deviceType).toEqual(device);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('creates an ios installation with ids', (done) => {
    var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var device = 'ios';
    var input = {
      'deviceToken': t,
      'deviceType': device
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.deviceToken).toEqual(t);
      expect(obj.deviceType).toEqual(device);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('creates an embedded installation with ids', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var device = 'embedded';
    var input = {
      'installationId': installId,
      'deviceType': device
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.installationId).toEqual(installId);
      expect(obj.deviceType).toEqual(device);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('creates an android installation with all fields', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var device = 'android';
    var input = {
      'installationId': installId,
      'deviceType': device,
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.installationId).toEqual(installId);
      expect(obj.deviceType).toEqual(device);
      expect(typeof obj.channels).toEqual('object');
      expect(obj.channels.length).toEqual(2);
      expect(obj.channels[0]).toEqual('foo');
      expect(obj.channels[1]).toEqual('bar');
      done();
    }).catch((error) => { console.log(error); });
  });

  it('creates an ios installation with all fields', (done) => {
    var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var device = 'ios';
    var input = {
      'deviceToken': t,
      'deviceType': device,
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.deviceToken).toEqual(t);
      expect(obj.deviceType).toEqual(device);
      expect(typeof obj.channels).toEqual('object');
      expect(obj.channels.length).toEqual(2);
      expect(obj.channels[0]).toEqual('foo');
      expect(obj.channels[1]).toEqual('bar');
      done();
    }).catch((error) => { console.log(error); });
  });

  it('should properly fail queying installations', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var device = 'android';
    var input = {
      'installationId': installId,
      'deviceType': device
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      let query = new Parse.Query(Parse.Installation);
      return query.find()
    }).then((results) => {
      fail('Should not succeed!');
      done();
    }).catch((error) => {
      expect(error.code).toBe(119);
      expect(error.message).toBe('Clients aren\'t allowed to perform the find operation on the installation collection.')
      done();
    });
  });

  it('should properly queying installations with masterKey', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var device = 'android';
    var input = {
      'installationId': installId,
      'deviceType': device
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      let query = new Parse.Query(Parse.Installation);
      return query.find({useMasterKey: true});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0].toJSON();
      expect(obj.installationId).toEqual(installId);
      expect(obj.deviceType).toEqual(device);
      done();
    }).catch((error) => {
      fail('Should not fail');
      done();
    });
  });

  it('fails with missing ids', (done) => {
    var input = {
      'deviceType': 'android',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      fail('Should not have been able to create an Installation.');
      done();
    }).catch((error) => {
      expect(error.code).toEqual(135);
      done();
    });
  });

  it('fails for android with missing type', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var input = {
      'installationId': installId,
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      fail('Should not have been able to create an Installation.');
      done();
    }).catch((error) => {
      expect(error.code).toEqual(135);
      done();
    });
  });

  it('creates an object with custom fields', (done) => {
    var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var input = {
      'deviceToken': t,
      'deviceType': 'ios',
      'channels': ['foo', 'bar'],
      'custom': 'allowed'
    };
  rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var obj = results[0];
      expect(obj.custom).toEqual('allowed');
      done();
    }).catch((error) => { console.log(error); });
  });

  // Note: did not port test 'TestObjectIDForIdentifiers'

  it('merging when installationId already exists', (done) => {
    var installId1 = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var installId2 = '12345678-abcd-abcd-abcd-123456789abd';
    var input = {
      'deviceToken': t,
      'deviceType': 'ios',
      'installationId': installId1,
      'channels': ['foo', 'bar']
    };
    var firstObject;
    var secondObject;
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      firstObject = results[0];
      delete input.deviceToken;
      delete input.channels;
      input['foo'] = 'bar';
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      secondObject = results[0];
      expect(firstObject._id).toEqual(secondObject._id);
      expect(secondObject.channels.length).toEqual(2);
      expect(secondObject.foo).toEqual('bar');
      done();
    }).catch((error) => { console.log(error); });
  });

  it('merging when two objects both only have one id', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input1 = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    var input2 = {
      'deviceToken': t,
      'deviceType': 'ios'
    };
    var input3 = {
      'deviceToken': t,
      'installationId': installId,
      'deviceType': 'ios'
    };
    var firstObject;
    var secondObject;
    rest.create(config, auth.nobody(config), '_Installation', input1)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      firstObject = results[0];
      return rest.create(config, auth.nobody(config), '_Installation', input2);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(2);
      if (results[0]['_id'] == firstObject._id) {
        secondObject = results[1];
      } else {
        secondObject = results[0];
      }
      return rest.create(config, auth.nobody(config), '_Installation', input3);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0]['_id']).toEqual(secondObject._id);
      done();
    }).catch((error) => { console.log(error); });
  });

  notWorking('creating multiple devices with same device token works', (done) => {
    var installId1 = '11111111-abcd-abcd-abcd-123456789abc';
    var installId2 = '22222222-abcd-abcd-abcd-123456789abc';
    var installId3 = '33333333-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId1,
      'deviceType': 'ios',
      'deviceToken': t
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      input.installationId = installId2;
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      input.installationId = installId3;
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation',
                     {installationId: installId1}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      return database.mongoFind('_Installation',
                     {installationId: installId2}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      return database.mongoFind('_Installation',
                     {installationId: installId3}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('updating with new channels', (done) => {
    var input = {
      'installationId': '12345678-abcd-abcd-abcd-123456789abc',
      'deviceType': 'android',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      var id = results[0]['_id'];
      var update = {
        'channels': ['baz']
      };
      return rest.update(config, auth.nobody(config),
                         '_Installation', id, update);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].channels.length).toEqual(1);
      expect(results[0].channels[0]).toEqual('baz');
      done();
    }).catch((error) => { console.log(error); });
  });

  it('update android fails with new installation id', (done) => {
    var installId1 = '12345678-abcd-abcd-abcd-123456789abc';
    var installId2 = '87654321-abcd-abcd-abcd-123456789abc';
    var input = {
      'installationId': installId1,
      'deviceType': 'android',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'installationId': installId2
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      fail('Updating the installation should have failed.');
      done();
    }).catch((error) => {
      expect(error.code).toEqual(136);
      done();
    });
  });

  it('update ios fails with new deviceToken and no installationId', (done) => {
    var a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var input = {
      'deviceToken': a,
      'deviceType': 'ios',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'deviceToken': b
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      fail('Updating the installation should have failed.');
    }).catch((error) => {
      expect(error.code).toEqual(136);
      done();
    });
  });

  it('update ios updates device token', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
    var input = {
      'installationId': installId,
      'deviceType': 'ios',
      'deviceToken': t,
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'installationId': installId,
        'deviceToken': u,
        'deviceType': 'ios'
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].deviceToken).toEqual(u);
      done();
    });
  });

  it('update fails to change deviceType', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var input = {
      'installationId': installId,
      'deviceType': 'android',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'deviceType': 'ios'
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      fail('Should not have been able to update Installation.');
      done();
    }).catch((error) => {
      expect(error.code).toEqual(136);
      done();
    });
  });

  it('update android with custom field', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var input = {
      'installationId': installId,
      'deviceType': 'android',
      'channels': ['foo', 'bar']
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'custom': 'allowed'
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0]['custom']).toEqual('allowed');
      done();
    });
  });

  it('update android device token with duplicate device token', (done) => {
    var installId1 = '11111111-abcd-abcd-abcd-123456789abc';
    var installId2 = '22222222-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId1,
      'deviceToken': t,
      'deviceType': 'android'
    };
    var firstObject;
    var secondObject;
    rest.create(config, auth.nobody(config), '_Installation', input)
        .then(() => {
          input = {
            'installationId': installId2,
            'deviceType': 'android'
          };
          return rest.create(config, auth.nobody(config), '_Installation', input);
        }).then(() => {
      return database.mongoFind('_Installation',
          {installationId: installId1}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      firstObject = results[0];
      return database.mongoFind('_Installation',
          {installationId: installId2}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      secondObject = results[0];
      // Update second installation to conflict with first installation
      input = {
        'objectId': secondObject._id,
        'deviceToken': t
      };
      return rest.update(config, auth.nobody(config), '_Installation',
          secondObject._id, input);
    }).then(() => {
      // The first object should have been deleted
      return database.mongoFind('_Installation', {_id: firstObject._id}, {});
    }).then((results) => {
      expect(results.length).toEqual(0);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('update ios device token with duplicate device token', (done) => {
    var installId1 = '11111111-abcd-abcd-abcd-123456789abc';
    var installId2 = '22222222-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId1,
      'deviceToken': t,
      'deviceType': 'ios'
    };
    var firstObject;
    var secondObject;
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      input = {
        'installationId': installId2,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation',
                     {installationId: installId1}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      firstObject = results[0];
      return database.mongoFind('_Installation',
                     {installationId: installId2}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      secondObject = results[0];
      // Update second installation to conflict with first installation id
      input = {
        'installationId': installId2,
        'deviceToken': t
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         secondObject._id, input);
    }).then(() => {
      // The first object should have been deleted
      return database.mongoFind('_Installation', {_id: firstObject._id}, {});
    }).then((results) => {
      expect(results.length).toEqual(0);
      done();
    }).catch((error) => { console.log(error); });
  });

  notWorking('update ios device token with duplicate token different app', (done) => {
    var installId1 = '11111111-abcd-abcd-abcd-123456789abc';
    var installId2 = '22222222-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId1,
      'deviceToken': t,
      'deviceType': 'ios',
      'appIdentifier': 'foo'
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      input.installationId = installId2;
      input.appIdentifier = 'bar';
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      // The first object should have been deleted during merge
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId2);
      done();
    });
  });

  it('update ios token and channels', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'deviceToken': t,
        'channels': []
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId);
      expect(results[0].deviceToken).toEqual(t);
      expect(results[0].channels.length).toEqual(0);
      done();
    });
  });

  it('update ios linking two existing objects', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      input = {
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation',
                     {deviceToken: t}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'deviceToken': t,
        'installationId': installId,
        'deviceType': 'ios'
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId);
      expect(results[0].deviceToken).toEqual(t);
      expect(results[0].deviceType).toEqual('ios');
      done();
    });
  });

  it('update is linking two existing objects w/ increment', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      input = {
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation',
                     {deviceToken: t}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'deviceToken': t,
        'installationId': installId,
        'deviceType': 'ios',
        'score': {
          '__op': 'Increment',
          'amount': 1
        }
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         results[0]['_id'], input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId);
      expect(results[0].deviceToken).toEqual(t);
      expect(results[0].deviceType).toEqual('ios');
      expect(results[0].score).toEqual(1);
      done();
    });
  });

  it('update is linking two existing with installation id', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    var installObj;
    var tokenObj;
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      installObj = results[0];
      input = {
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation', {deviceToken: t}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      tokenObj = results[0];
      input = {
        'installationId': installId,
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         installObj._id, input);
    }).then(() => {
      return database.mongoFind('_Installation', {_id: tokenObj._id}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId);
      expect(results[0].deviceToken).toEqual(t);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('update is linking two existing with installation id w/ op', (done) => {
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var input = {
      'installationId': installId,
      'deviceType': 'ios'
    };
    var installObj;
    var tokenObj;
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      installObj = results[0];
      input = {
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation', {deviceToken: t}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      tokenObj = results[0];
      input = {
        'installationId': installId,
        'deviceToken': t,
        'deviceType': 'ios',
        'score': {
          '__op': 'Increment',
          'amount': 1
        }
      };
      return rest.update(config, auth.nobody(config), '_Installation',
                         installObj._id, input);
    }).then(() => {
      return database.mongoFind('_Installation', {_id: tokenObj._id}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].installationId).toEqual(installId);
      expect(results[0].deviceToken).toEqual(t);
      expect(results[0].score).toEqual(1);
      done();
    }).catch((error) => { console.log(error); });
  });

  it('ios merge existing same token no installation id', (done) => {
    // Test creating installation when there is an existing object with the
    // same device token but no installation ID.  This is possible when
    // developers import device tokens from another push provider; the import
    // process does not generate installation IDs. When they later integrate
    // the Parse SDK, their app is going to save the installation. This save
    // op will have a client-generated installation ID as well as a device
    // token. At this point, if the device token matches the originally-
    // imported installation, then we should reuse the existing installation
    // object in case the developer already added additional fields via Data
    // Browser or REST API (e.g. channel targeting info).
    var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
    var installId = '12345678-abcd-abcd-abcd-123456789abc';
    var input = {
      'deviceToken': t,
      'deviceType': 'ios'
    };
    rest.create(config, auth.nobody(config), '_Installation', input)
    .then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      input = {
        'installationId': installId,
        'deviceToken': t,
        'deviceType': 'ios'
      };
      return rest.create(config, auth.nobody(config), '_Installation', input);
    }).then(() => {
      return database.mongoFind('_Installation', {}, {});
    }).then((results) => {
      expect(results.length).toEqual(1);
      expect(results[0].deviceToken).toEqual(t);
      expect(results[0].installationId).toEqual(installId);
      done();
    });
  });

  // TODO: Look at additional tests from installation_collection_test.go:882
  // TODO: Do we need to support _tombstone disabling of installations?
  // TODO: Test deletion, badge increments

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~  Licensed to the Apache Software Foundation (ASF) under one
  ~  or more contributor license agreements.  See the NOTICE file
  ~  distributed with this work for additional information
  ~  regarding copyright ownership.  The ASF licenses this file
  ~  to you under the Apache License, Version 2.0 (the
  ~  "License"); you may not use this file except in compliance
  ~  with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing,
  ~  software distributed under the License is distributed on an
  ~   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~  KIND, either express or implied.  See the License for the
  ~  specific language governing permissions and limitations
  ~  under the License.
  -->

<!-- Action of dbreport and dblookup mediators together -->
<definitions xmlns="http://ws.apache.org/ns/synapse">

    <sequence name="main">
        <in>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>

        <out>
            <log level="custom">
                <property name="text" value="** Reporting to the Database **"/>
            </log>

            <dbreport>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>update company set price=? where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               expression="//m0:return/m0:last/child::text()" type="DOUBLE"/>
                    <parameter xmlns:m0="http://services.samples"
                               expression="//m0:return/m0:symbol/child::text()" type="VARCHAR"/>
                </statement>
            </dbreport>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>select * from company where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               expression="//m0:return/m0:symbol/child::text()" type="VARCHAR"/>
                    <result name="stock_price" column="price"/>
                </statement>
            </dblookup>
            <log level="custom">
                <property name="text"
                          expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
            </log>
            <send/>
        </out>
    </sequence>

</definitions>

redpajama_set_name: RedPajamaGithub


text:
package com.salesforce.phoenix.compile;

import java.sql.ParameterMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.salesforce.hbase.index.util.ImmutableBytesPtr;
import com.salesforce.phoenix.cache.ServerCacheClient.ServerCache;
import com.salesforce.phoenix.compile.GroupByCompiler.GroupBy;
import com.salesforce.phoenix.compile.OrderByCompiler.OrderBy;
import com.salesforce.phoenix.coprocessor.UngroupedAggregateRegionObserver;
import com.salesforce.phoenix.exception.SQLExceptionCode;
import com.salesforce.phoenix.exception.SQLExceptionInfo;
import com.salesforce.phoenix.execute.AggregatePlan;
import com.salesforce.phoenix.execute.MutationState;
import com.salesforce.phoenix.index.IndexMetaDataCacheClient;
import com.salesforce.phoenix.index.PhoenixIndexCodec;
import com.salesforce.phoenix.iterate.ResultIterator;
import com.salesforce.phoenix.jdbc.PhoenixConnection;
import com.salesforce.phoenix.jdbc.PhoenixResultSet;
import com.salesforce.phoenix.jdbc.PhoenixStatement;
import com.salesforce.phoenix.optimize.QueryOptimizer;
import com.salesforce.phoenix.parse.AliasedNode;
import com.salesforce.phoenix.parse.DeleteStatement;
import com.salesforce.phoenix.parse.HintNode;
import com.salesforce.phoenix.parse.HintNode.Hint;
import com.salesforce.phoenix.parse.ParseNode;
import com.salesforce.phoenix.parse.ParseNodeFactory;
import com.salesforce.phoenix.parse.SelectStatement;
import com.salesforce.phoenix.query.ConnectionQueryServices;
import com.salesforce.phoenix.query.QueryConstants;
import com.salesforce.phoenix.query.QueryServices;
import com.salesforce.phoenix.query.QueryServicesOptions;
import com.salesforce.phoenix.schema.ColumnModifier;
import com.salesforce.phoenix.schema.PColumn;
import com.salesforce.phoenix.schema.PDataType;
import com.salesforce.phoenix.schema.PRow;
import com.salesforce.phoenix.schema.PTable;
import com.salesforce.phoenix.schema.PTableType;
import com.salesforce.phoenix.schema.ReadOnlyTableException;
import com.salesforce.phoenix.schema.TableRef;
import com.salesforce.phoenix.schema.tuple.Tuple;
import com.salesforce.phoenix.util.IndexUtil;

public class DeleteCompiler {
    private static ParseNodeFactory FACTORY = new ParseNodeFactory();

    private final PhoenixStatement statement;

    public DeleteCompiler(PhoenixStatement statement) {
        this.statement = statement;
    }

    private static MutationState deleteRows(PhoenixStatement statement, TableRef tableRef, ResultIterator iterator, RowProjector projector) throws SQLException {
        PhoenixConnection connection = statement.getConnection();
        final boolean isAutoCommit = connection.getAutoCommit();
        ConnectionQueryServices services = connection.getQueryServices();
        final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
        final int batchSize = Math.min(connection.getMutateBatchSize(), maxSize);
        Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutations = Maps.newHashMapWithExpectedSize(batchSize);
        try {
            PTable table = tableRef.getTable();
            List<PColumn> pkColumns = table.getPKColumns();
            int offset = table.getBucketNum() == null ? 0 : 1; // Take into account salting
            byte[][] values = new byte[pkColumns.size()][];
            ResultSet rs = new PhoenixResultSet(iterator, projector, statement);
            int rowCount = 0;
            while (rs.next()) {
                for (int i = offset; i < values.length; i++) {
                    byte[] byteValue = rs.getBytes(i+1-offset);
                    // The ResultSet.getBytes() call will have inverted it - we need to invert it back.
                    // TODO: consider going under the hood and just getting the bytes
                    if (pkColumns.get(i).getColumnModifier() == ColumnModifier.SORT_DESC) {
                        byte[] tempByteValue = Arrays.copyOf(byteValue, byteValue.length);
                        byteValue = ColumnModifier.SORT_DESC.apply(byteValue, 0, tempByteValue, 0, byteValue.length);
                    }
                    values[i] = byteValue;
                }
                ImmutableBytesPtr ptr = new ImmutableBytesPtr();
                table.newKey(ptr, values);
                mutations.put(ptr, PRow.DELETE_MARKER);
                if (mutations.size() > maxSize) {
                    throw new IllegalArgumentException("MutationState size of " + mutations.size() + " is bigger than max allowed size of " + maxSize);
                }
                rowCount++;
                // Commit a batch if auto commit is true and we're at our batch size
                if (isAutoCommit && rowCount % batchSize == 0) {
                    MutationState state = new MutationState(tableRef, mutations, 0, maxSize, connection);
                    connection.getMutationState().join(state);
                    connection.commit();
                    mutations.clear();
                }
            }

            // If auto commit is true, this last batch will be committed upon return
            return new MutationState(tableRef, mutations, rowCount / batchSize * batchSize, maxSize, connection);
        } finally {
            iterator.close();
        }
    }

    private static class DeletingParallelIteratorFactory extends MutatingParallelIteratorFactory {
        private RowProjector projector;

        private DeletingParallelIteratorFactory(PhoenixConnection connection, TableRef tableRef) {
            super(connection, tableRef);
        }

        @Override
        protected MutationState mutate(PhoenixConnection connection, ResultIterator iterator) throws SQLException {
            PhoenixStatement statement = new PhoenixStatement(connection);
            return deleteRows(statement, tableRef, iterator, projector);
        }

        public void setRowProjector(RowProjector projector) {
            this.projector = projector;
        }

    }

    private boolean hasImmutableIndex(TableRef tableRef) {
        return tableRef.getTable().isImmutableRows() && !tableRef.getTable().getIndexes().isEmpty();
    }

    private boolean hasImmutableIndexWithKeyValueColumns(TableRef tableRef) {
        if (!hasImmutableIndex(tableRef)) {
            return false;
        }
        for (PTable index : tableRef.getTable().getIndexes()) {
            for (PColumn column : index.getPKColumns()) {
                if (!IndexUtil.isDataPKColumn(column)) {
                    return true;
                }
            }
        }
        return false;
    }

    public MutationPlan compile(DeleteStatement delete) throws SQLException {
        final PhoenixConnection connection = statement.getConnection();
        final boolean isAutoCommit = connection.getAutoCommit();
        final ConnectionQueryServices services = connection.getQueryServices();
        final ColumnResolver resolver = FromCompiler.getResolver(delete, connection);
        final TableRef tableRef = resolver.getTables().get(0);
        PTable table = tableRef.getTable();
        if (table.getType() == PTableType.VIEW && table.getViewType().isReadOnly()) {
            throw new ReadOnlyTableException(table.getSchemaName().getString(),table.getTableName().getString());
        }

        final boolean hasLimit = delete.getLimit() != null;
        boolean noQueryReqd = !hasLimit && !hasImmutableIndex(tableRef);
        boolean runOnServer = isAutoCommit && noQueryReqd;
        HintNode hint = delete.getHint();
        if (runOnServer && !delete.getHint().hasHint(Hint.USE_INDEX_OVER_DATA_TABLE)) {
            hint = HintNode.create(hint, Hint.USE_DATA_OVER_INDEX_TABLE);
        }

        List<AliasedNode> aliasedNodes = Lists.newArrayListWithExpectedSize(table.getPKColumns().size());
        boolean isSalted = table.getBucketNum() != null;
        boolean isMultiTenant = connection.getTenantId() != null && table.isMultiTenant();
        for (int i = (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0); i < table.getPKColumns().size(); i++) {
            PColumn column = table.getPKColumns().get(i);
            aliasedNodes.add(FACTORY.aliasedNode(null, FACTORY.column(null, '"' + column.getName().getString() + '"', null)));
        }
        SelectStatement select = FACTORY.select(
                Collections.singletonList(delete.getTable()),
                hint, false, aliasedNodes, delete.getWhere(),
                Collections.<ParseNode>emptyList(), null,
                delete.getOrderBy(), delete.getLimit(),
                delete.getBindCount(), false);
        DeletingParallelIteratorFactory parallelIteratorFactory = hasLimit ? null : new DeletingParallelIteratorFactory(connection, tableRef);
        final QueryPlan plan = new QueryOptimizer(services).optimize(select, statement, Collections.<PColumn>emptyList(), parallelIteratorFactory);
        if (!plan.getTableRef().equals(tableRef)) {
            runOnServer = false;
            noQueryReqd = false;
        }

        final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);

        if (hasImmutableIndexWithKeyValueColumns(tableRef)) {
            throw new SQLExceptionInfo.Builder(SQLExceptionCode.NO_DELETE_IF_IMMUTABLE_INDEX).setSchemaName(tableRef.getTable().getSchemaName().getString())
            .setTableName(tableRef.getTable().getTableName().getString()).build().buildException();
        }

        final StatementContext context = plan.getContext();
        // If we're doing a query for a single row with no where clause, then we don't need to contact the server at all.
        // A simple check of the none existence of a where clause in the parse node is not sufficient, as the where clause
        // may have been optimized out.
        if (noQueryReqd && context.isSingleRowScan()) {
            final ImmutableBytesPtr key = new ImmutableBytesPtr(context.getScan().getStartRow());
            return new MutationPlan() {

                @Override
                public ParameterMetaData getParameterMetaData() {
                    return context.getBindManager().getParameterMetaData();
                }

                @Override
                public MutationState execute() {
                    Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutation = Maps.newHashMapWithExpectedSize(1);
                    mutation.put(key, PRow.DELETE_MARKER);
                    return new MutationState(tableRef, mutation, 0, maxSize, connection);
                }

                @Override
                public ExplainPlan getExplainPlan() throws SQLException {
                    return new ExplainPlan(Collections.singletonList("DELETE SINGLE ROW"));
                }

                @Override
                public PhoenixConnection getConnection() {
                    return connection;
                }
            };
        } else if (runOnServer) {
            // TODO: better abstraction
            Scan scan = context.getScan();
            scan.setAttribute(UngroupedAggregateRegionObserver.DELETE_AGG, QueryConstants.TRUE);

            // Build an ungrouped aggregate query: select COUNT(*) from <table> where <where>
            // The coprocessor will delete each row returned from the scan
            // Ignoring ORDER BY, since with auto commit on and no limit makes no difference
            SelectStatement aggSelect = SelectStatement.create(SelectStatement.COUNT_ONE, delete.getHint());
            final RowProjector projector = ProjectionCompiler.compile(context, aggSelect, GroupBy.EMPTY_GROUP_BY);
            final QueryPlan aggPlan = new AggregatePlan(context, select, tableRef, projector, null, OrderBy.EMPTY_ORDER_BY, null, GroupBy.EMPTY_GROUP_BY, null);
            return new MutationPlan() {

                @Override
                public PhoenixConnection getConnection() {
                    return connection;
                }

                @Override
                public ParameterMetaData getParameterMetaData() {
                    return context.getBindManager().getParameterMetaData();
                }

                @Override
                public MutationState execute() throws SQLException {
                    // TODO: share this block of code with UPSERT SELECT
                    ImmutableBytesWritable ptr = context.getTempPtr();
                    tableRef.getTable().getIndexMaintainers(ptr);
                    ServerCache cache = null;
                    try {
                        if (ptr.getLength() > 0) {
                            IndexMetaDataCacheClient client = new IndexMetaDataCacheClient(connection, tableRef);
                            cache = client.addIndexMetadataCache(context.getScanRanges(), ptr);
                            byte[] uuidValue = cache.getId();
                            context.getScan().setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
                        }
                        ResultIterator iterator = aggPlan.iterator();
                        try {
                            Tuple row = iterator.next();
                            final long mutationCount = (Long)projector.getColumnProjector(0).getValue(row, PDataType.LONG, ptr);
                            return new MutationState(maxSize, connection) {
                                @Override
                                public long getUpdateCount() {
                                    return mutationCount;
                                }
                            };
                        } finally {
                            iterator.close();
                        }
                    } finally {
                        if (cache != null) {
                            cache.close();
                        }
                    }
                }

                @Override
                public ExplainPlan getExplainPlan() throws SQLException {
                    List<String> queryPlanSteps =  aggPlan.getExplainPlan().getPlanSteps();
                    List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
                    planSteps.add("DELETE ROWS");
                    planSteps.addAll(queryPlanSteps);
                    return new ExplainPlan(planSteps);
                }
            };
        } else {
            if (parallelIteratorFactory != null) {
                parallelIteratorFactory.setRowProjector(plan.getProjector());
            }
            return new MutationPlan() {

                @Override
                public PhoenixConnection getConnection() {
                    return connection;
                }

                @Override
                public ParameterMetaData getParameterMetaData() {
                    return context.getBindManager().getParameterMetaData();
                }

                @Override
                public MutationState execute() throws SQLException {
                    ResultIterator iterator = plan.iterator();
                    if (!hasLimit) {
                        Tuple tuple;
                        long totalRowCount = 0;
                        while ((tuple=iterator.next()) != null) {// Runs query
                            KeyValue kv = tuple.getValue(0);
                            totalRowCount += PDataType.LONG.getCodec().decodeLong(kv.getBuffer(), kv.getValueOffset(), null);
                        }
                        // Return total number of rows that have been delete. In the case of auto commit being off
                        // the mutations will all be in the mutation state of the current connection.
                        return new MutationState(maxSize, connection, totalRowCount);
                    } else {
                        return deleteRows(statement, tableRef, iterator, plan.getProjector());
                    }
                }

                @Override
                public ExplainPlan getExplainPlan() throws SQLException {
                    List<String> queryPlanSteps =  plan.getExplainPlan().getPlanSteps();
                    List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
                    planSteps.add("DELETE ROWS");
                    planSteps.addAll(queryPlanSteps);
                    return new ExplainPlan(planSteps);
                }
            };
        }

    }
}


text:
<?php namespace DMA\Friends\Classes\Notifications\Channels;

use Log;
use Event;
use Services_Twilio;
use DMA\Friends\Models\Settings;
use DMA\Friends\Classes\Notifications\Channels\Channel;
use DMA\Friends\Classes\Notifications\Channels\Listenable;
use DMA\Friends\Classes\Notifications\Channels\Webhook;
use DMA\Friends\Classes\Notifications\NotificationMessage;
use DMA\Friends\Classes\Notifications\IncomingMessage;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use Carbon\Carbon;

/**
 * Channel for sending SMS notification using Twilio as gateway
 * @author Carlos Arroyo
 *
 */
class ChannelSMS implements Channel, Listenable, Webhook
{
    private $client;
    private $fromNumber;

	public static function getKey()
	{
		return 'sms';
	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Channel::getDetails()
	 */
	public function getDetails()
	{
	    return [
	            'name'           => 'SMS',
	            'description'    => 'Send notifications by SMS using Twilio.'
	    ];
	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Channel::configChannel()
	 */
	public function configChannel()
	{
	    // TOOD : get this values for OctoberCMS settings
	    $accountSid = Settings::get('twilio_account_id');
	    $authToken  = Settings::get('twilio_auth_token');
	    $this->fromNumber = $this->cleanPhone(Settings::get('twilio_default_from_number'), false);

	    $this->client = new Services_Twilio($accountSid, $authToken);
	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Channel::settingFields()
	 */
	public function settingFields()
	{
		return [
            'twilio_account_id' => [
                'label' => 'Twilio account ID',
                'span'  => 'auto'
		    ],
		    'twilio_auth_token' => [
		         'label' => 'Twilio authentication token',
		         'span'  => 'auto'
		    ],
		    'twilio_default_from_number' => [
		         'label' => 'Twilio default from number',
		         'span'  => 'auto'
		    ],
		];

	}

	/**
	 * Clean phone number for Twilio
	 * @param string $phone
	 * @return string
	 */
	protected function cleanPhone($phone, $useTimezone=true)
	{
	    // if Phone number is not in E164 try to parse it
	    if(!preg_match('/^\+.\d+$/', $phone)){
	        if($useTimezone){
    	        $phoneUtil = PhoneNumberUtil::getInstance();
    	        try {
    	            // Get country code using configure timezone
    	            $tz = Carbon::now()->getTimezone();
    	            $country_code = array_get($tz->getLocation(), 'country_code', 'US');

    	            // Parse phone number
    	            $numberProto = $phoneUtil->parse($phone, $country_code);

    	            // Return phone
    	            return $phoneUtil->format($numberProto, PhoneNumberFormat::E164);

    	        } catch (\libphonenumber\NumberParseException $e) {
    	            // Invalid phone let twilio complain :D
    	            return '';
    	        }
	        }

	        // Just add missing plus sing

	        return '+' . $phone;

	    }else{
	        return $phone;
	    }
	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Channel::send()
	 */
	public function send(NotificationMessage $message)
	{

	    // TODO : add validation to control the size of the message.
	    $toUser  = $message->getTo();
	    $data    = $message->getData();
	    $txt     = strip_tags($message->getContent());

        $txt = $this->chunkLongText($txt);

        foreach($txt as $t) {
	        // Clean phone user
	        $toPhone = $this->cleanPhone($toUser->phone);
	        if (!empty($toPhone)) {
    	        $sms = $this->client->account->sms_messages->create(
    	    		$this->fromNumber, // From a Twilio number in your account
    	    		$toPhone, // Text any number
    	    		$t
    	        );
	        }
        }

	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Listenable::readChannel()
	 */
	public function read()
	{
        return [];
	}

	/**
	 * {@inheritDoc}
	 * @see \DMA\Friends\Classes\Notifications\Channels\Webhook::webhook()
	 */
	public function webhook(array $request)
	{
	    $httpCode = 200;
	    try
	    {
	        $msg = new IncomingMessage($this->getKey());
	        $msg->from($request['From']);
	        $msg->setContent($request['Body']);

	        // TODO : this should be reusable for other channels
	        $key = $this->getKey();
	        $event = strtolower("dma.channel.$key.incoming.data");
	        Event::fire($event, [[$msg]]);
	        Log::debug('Processed Twilio incoming SMS', $msg->getData());
	    }
	    catch(\Exception $e)
	    {
    	    Log::error('Processing Twilio webhook request', $request);
	        Log::error(sprintf('Processing Twilio webhook:  %s', $e));
	        $httpCode = 500;
	    }

	    // Response message was read ok
	    return \Response::make('<Response></Response>', $httpCode);
	}

    private function chunkLongText($longString, $maxLineLength = 60)
    {
        if (strlen($longString) <= $maxLineLength) {
            return [$longString];
        }

        $arrayOutput = [];
        $arrayWords = explode(' ', $longString);

        // Auxiliar counters, foreach will use them
        $currentLength = 0;
        $index = 0;

        foreach($arrayWords as $word)
        {
            // +1 because the word will receive back the space in the end that it loses in explode()
            $wordLength = strlen($word) + 1;
            $string = $word . ' ';

            if( ( $currentLength + $wordLength ) <= $maxLineLength )
            {

                if (isset($arrayOutput[$index])) {
                    $arrayOutput[$index] .= $string;
                } else {
                    $arrayOutput[$index] = $string;
                }

                $currentLength += $wordLength;
            }
            else
            {
                $index += 1;

                $currentLength = $wordLength;

                $arrayOutput[$index] = $string;
            }
        }

        return $arrayOutput;

    }

}


text:
package main.service.query;

import main.data.core.Result;
import main.data.core.Status;
import main.data.index.Id;
import main.data.rank.Score;
import main.service.file.FileDb;
import main.service.rank.RankDb;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import static main.service.query.Index.getIds;
import static main.service.rank.RankFunctions.isDocument;

public class Documents {
    private FileDb fileDb = new FileDb();
    private RankDb rankDb = new RankDb();

    /***
     *
     * @param query search terms
     * @return splits terms on white space
     */
    public String[] multiQuery(final String query) {
        return query.split("\\s");
    }

    /**
     *
     * @param query document name to search
     * @return Absolute path to document
     */
    public String top(Connection connection, final String query){
        List<Score> end = new ArrayList<Score>();
        String[] d = multiQuery(query);

        for (String word : d) {
            List<Score> scores = new ArrayList<Score>();
            List<Id> ids = getIds(connection,word);
            for (Id id : ids) {
                Result<Score> tmp = document(connection, id.id_file);
                if (tmp.statusOK() )
                    end.add(tmp.value());
            }
        }

        String r = "";
        Result<Score> q = top(end);
        if (q.statusOK())
            r = q.value().url;
        if (r.equals(""))
            return "No result's";
        else
            return r;
    }

    /**
     *
     * @param query document name to search
     * @return List of Absolute path to document
     */
    public List<String> list(Connection connection, final String query){
        List<String> end = new ArrayList<String>();
        String[] d = multiQuery(query);

        for (String word : d) {
            List<Score> scores = new ArrayList<Score>();
            List<Id> ids = getIds(connection,word);
            for (Id id : ids) {
                Result<Score> tmp = document(connection, id.id_file);
                if (tmp.statusOK() ) {
                    String url = tmp.value().url;
                    if (isDocument(url)){
                        if (!end.contains(url))
                            end.add(url);
                    }
                }
            }
        }

        if (!(end.size() > 0))
            end.add("No result's");
        return end;
    }

    /**
     *
     * @param query document name to search
     * @param size size of list to return
     * @return List of Absolute path to document
     */

    public List<String> list(Connection connection, final String query, final Integer size){
        List<Score> big = new ArrayList<Score>();
        List<String> end = new ArrayList<String>();
        String[] d = multiQuery(query);

        for (String word : d) {
            List<Score> scores = new ArrayList<Score>();

            List<Id> ids = getIds(connection,word);

            for (Id id : ids) {
                Result<Score> tmp = document(connection, id.id_file);
                if (tmp.statusOK() )  {
                    if (isDocument(tmp.value().url)){
                        if (!scores.contains(tmp.value()))
                            scores.add(tmp.value());
                    }
                }
            }
            big.addAll(scores);
        }

        if (!(big.size() > 0))
            end.add("No result's");
        if (big.size() <= size){
            for (Score score : big) {
                end.add(score.url);
            }
        } else if (big.size() > size){
            for (int i = 0; i < size; i++){
                Result<Score> r = top(big);
                if (r.statusOK()){
                    end.add(r.value().url);
                    big.remove(r.value());
                }
            }
        }
        return end;
    }

    /**
     *
     * @param input List of data.main.rank.Score
     * @return option of top score
     */
    private Result<Score> top(List<Score> input){
        Score re = null;
        Integer highrank = -1;
        for (Score data : input) {
            if (isDocument(data.url)){
                if (data.score > highrank){
                    re = data;
                    highrank = data.score;
                }
            }
        }
        if (highrank>-1)
            return Result.ok(re);
        return Result.notfound();
    }

    /**
     *
     * @param file File ID
     * @return Result of Score
     */
    private Result<Score> document(Connection connection, final Integer file){
        if ((rankDb.exists(connection, file) == Status.BAD_REQUEST) && (fileDb.exists(connection, file) == Status.BAD_REQUEST)){
            return Result.ok(new Score(file, fileDb.get(connection, file).url, rankDb.getScore(connection, file)));
        }
        return Result.notfound();
    }
}


text:
import os
import sys
import socket
sys.path.append('/usr/share/plc_api')
from sfa.util.config import Config as SfaConfig
from PLC.Config import Config as PlcConfig

sfa_config = SfaConfig()
plc_config = PlcConfig()
default_host = socket.gethostbyname(socket.gethostname())
all_vars = ['SFA_CONFIG_DIR', 'SFA_DATA_DIR', 'SFA_INTERFACE_HRN',
            'SFA_CM_SLICE_PREFIX', 'SFA_REGISTRY_HOST', 'SFA_REGISTRY_PORT',
            'SFA_AGGREGATE_HOST', 'SFA_AGGREGATE_PORT',
            'SFA_SM_HOST', 'SFA_SM_PORT',
            'SFA_CM_ENABLED', 'SFA_CM_HOST', 'SFA_CM_PORT', 'SFA_CM_TYPE', 'SFA_CM_SLICE_PREFIX',
            'SFA_API_LOGLEVEL']

defaults = {
    'SFA_CM_ENABLED': '1',
    'SFA_CM_HOST': 'localhost',
    'SFA_CM_PORT': '12346',
    'SFA_CM_SLICE_PREFIX': plc_config.PLC_SLICE_PREFIX,
    'SFA_CM_TYPE': 'pl',
    'SFA_API_LOGLEVEL': '0'
    }

host_defaults = {
    'SFA_REGISTRY_HOST': default_host,
    'SFA_AGGREGATE_HOST': default_host,
    'SFA_SM_HOST': default_host,
    }

const_dict = {}
for key in all_vars:
    value = ""

    if key in defaults:
        value = defaults[key]
    elif hasattr(sfa_config, key):
        value = getattr(sfa_config, key)
        # sfa_config may specify localhost instead of a resolvalbe host or ip
        # if so replace this with the host's address
        if key in host_defaults and value in ['localhost', '127.0.0.1']:
            value = host_defaults[key]
    const_dict[key] = value

filename = sfa_config.config_path + os.sep + 'sfa_component_config'
conffile = open(filename, 'w')
format='%s="%s"\n'

for var in all_vars:
    conffile.write(format % (var, const_dict[var]))

conffile.close()


text:
class Partner < ApplicationRecord
  belongs_to :location

  has_many :projects, dependent: :destroy
  has_many :images, dependent: :destroy

  validates :location, presence: :true
  validates :name, presence: :true
  # validates :name, presence: :true, length: { in: 2..128 }
  # validates :blurb, length: { maximum: 256 }, allow_nil: true
  # validates :description, length: { maximum: 10000 }, allow_nil: true
  # validates :news, length: { maximum: 10000 }, allow_nil: true
  # validates :volunteer, length: { maximum: 10000 }, allow_nil: true
end


text:
package proto

import (
	mproto "github.com/youtube/vitess/go/mysql/proto"
	"github.com/youtube/vitess/go/sqltypes"
)

// StreamEvent represents one event for the update stream.
type StreamEvent struct {
	// Category can be "DML", "DDL", "ERR" or "POS"
	Category string

	// TableName, PrimaryKeyFields and PrimaryKeyValues are set for DML
	TableName        string
	PrimaryKeyFields []mproto.Field
	PrimaryKeyValues [][]sqltypes.Value

	// Sql is set for DDL or ERR
	Sql string

	// Timestamp is set for DML, DDL or ERR
	Timestamp int64

	// TransactionID is set for POS
	TransactionID string
}

//go:generate bsongen -file $GOFILE -type StreamEvent -o stream_event_bson.go


text:
@implementation RestClient

+ (id)sharedInstance {
    static RestClient *sharedPiggate = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedPiggate = [[self alloc] init];
    });
    return sharedPiggate;
}

+ (NSString *)getAbsoluteURL: (NSString *) relativeUrl {
    return [NSString stringWithFormat:@"%@://%@:%@%@%@", PROTOCOL, HOST, PORT,BASE_RELATIVE_URL,relativeUrl];

}

- (id)init {
    if (self = [super init]) {
        _manager = [AFHTTPRequestOperationManager manager];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];

    }
    return self;
}
-(void)saveStoredCookies
{
    NSURL *httpUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@://%@",PROTOCOL, HOST ]];

    NSArray *httpCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];
    NSData *httpCookiesData = [NSKeyedArchiver archivedDataWithRootObject:httpCookies];
    [[NSUserDefaults standardUserDefaults] setObject:httpCookiesData forKey:@"PiggateSavedCookies"];

    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)readStoredCookies
{
    //clear, read and install stored cookies
    NSURL *httpUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@://%@",PROTOCOL, HOST ]];

    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];
    for (NSHTTPCookie *cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }

    NSData *httpCookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"PiggateSavedCookies"];

    if([httpCookiesData length]) {
        NSArray *savedCookies = [NSKeyedUnarchiver unarchiveObjectWithData:httpCookiesData];
        for (NSHTTPCookie *cookie in savedCookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }

}

-(void)clearStoredCookies
{
    NSURL *httpUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@://%@",PROTOCOL, HOST ]];

    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];

    for (NSHTTPCookie *cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }

}
- (void) get: (NSString *) url  params:(id)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [_manager GET:[RestClient getAbsoluteURL:url] parameters:params
          success:success failure:failure ];
}

- (void) post: (NSString *) url  params:(id)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [_manager POST:[RestClient getAbsoluteURL:url] parameters:params
          success:success failure:failure ];
}

- (void) put: (NSString *) url  params:(id)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [_manager PUT:[RestClient getAbsoluteURL:url] parameters:params
          success:success failure:failure ];
}

- (void) delete: (NSString *) url params:(id)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [_manager DELETE:[RestClient getAbsoluteURL:url] parameters:params
          success:success failure:failure ];
}

@end


text:
.class public Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;
.super Ljava/lang/Object;

# static fields
.field static synthetic class$com$sun$org$apache$xml$internal$security$utils$CachedXPathAPIHolder:Ljava/lang/Class;

.field static local:Ljava/lang/ThreadLocal;

.field static localDoc:Ljava/lang/ThreadLocal;

.field static log:Ljava/util/logging/Logger;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    sget-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->class$com$sun$org$apache$xml$internal$security$utils$CachedXPathAPIHolder:Ljava/lang/Class;

    if-eqz v0, :cond_0

    sget-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->class$com$sun$org$apache$xml$internal$security$utils$CachedXPathAPIHolder:Ljava/lang/Class;

    :goto_0
    invoke-virtual {v0}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Ljava/util/logging/Logger;->getLogger(Ljava/lang/String;)Ljava/util/logging/Logger;

    move-result-object v0

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->log:Ljava/util/logging/Logger;

    new-instance v0, Ljava/lang/ThreadLocal;

    invoke-direct {v0}, Ljava/lang/ThreadLocal;-><init>()V

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->local:Ljava/lang/ThreadLocal;

    new-instance v0, Ljava/lang/ThreadLocal;

    invoke-direct {v0}, Ljava/lang/ThreadLocal;-><init>()V

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->localDoc:Ljava/lang/ThreadLocal;

    return-void

    :cond_0
    const-string/jumbo v0, "com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder"

    invoke-static {v0}, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->class$(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->class$com$sun$org$apache$xml$internal$security$utils$CachedXPathAPIHolder:Ljava/lang/Class;

    goto :goto_0
.end method

.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method static synthetic class$(Ljava/lang/String;)Ljava/lang/Class;
    .locals 3

    :try_start_0
    invoke-static {p0}, Ljava/lang/Class;->forName(Ljava/lang/String;)Ljava/lang/Class;
    :try_end_0
    .catch Ljava/lang/ClassNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v1

    return-object v1

    :catch_0
    move-exception v0

    new-instance v1, Ljava/lang/NoClassDefFoundError;

    invoke-virtual {v0}, Ljava/lang/Throwable;->getMessage()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/lang/NoClassDefFoundError;-><init>(Ljava/lang/String;)V

    throw v1
.end method

.method public static getCachedXPathAPI()Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;
    .locals 3

    const/4 v2, 0x0

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->local:Ljava/lang/ThreadLocal;

    invoke-virtual {v1}, Ljava/lang/ThreadLocal;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;

    if-eqz v0, :cond_0

    :goto_0
    return-object v0

    :cond_0
    new-instance v0, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;

    invoke-direct {v0}, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;-><init>()V

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->local:Ljava/lang/ThreadLocal;

    invoke-virtual {v1, v0}, Ljava/lang/ThreadLocal;->set(Ljava/lang/Object;)V

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->localDoc:Ljava/lang/ThreadLocal;

    invoke-virtual {v1, v2}, Ljava/lang/ThreadLocal;->set(Ljava/lang/Object;)V

    goto :goto_0
.end method

.method public static setDoc(Lorg/w3c/dom/Document;)V
    .locals 2

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->localDoc:Ljava/lang/ThreadLocal;

    invoke-virtual {v1}, Ljava/lang/ThreadLocal;->get()Ljava/lang/Object;

    move-result-object v1

    if-ne v1, p0, :cond_0

    :goto_0
    return-void

    :cond_0
    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->local:Ljava/lang/ThreadLocal;

    invoke-virtual {v1}, Ljava/lang/ThreadLocal;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;

    if-eqz v0, :cond_1

    invoke-virtual {v0}, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;->getXPathContext()Lcom/sun/org/apache/xpath/internal/XPathContext;

    move-result-object v1

    invoke-virtual {v1}, Lcom/sun/org/apache/xpath/internal/XPathContext;->reset()V

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->localDoc:Ljava/lang/ThreadLocal;

    invoke-virtual {v1, p0}, Ljava/lang/ThreadLocal;->set(Ljava/lang/Object;)V

    goto :goto_0

    :cond_1
    new-instance v0, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;

    invoke-direct {v0}, Lcom/sun/org/apache/xpath/internal/CachedXPathAPI;-><init>()V

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->local:Ljava/lang/ThreadLocal;

    invoke-virtual {v1, v0}, Ljava/lang/ThreadLocal;->set(Ljava/lang/Object;)V

    sget-object v1, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->localDoc:Ljava/lang/ThreadLocal;

    invoke-virtual {v1, p0}, Ljava/lang/ThreadLocal;->set(Ljava/lang/Object;)V

    return-void
.end method


text:
using System;
using System.Collections.Generic;
using Mono.Cecil;

public class ConverterCache
{
    public ModuleWeaver ModuleWeaver;
    public ModuleDefinition ModuleDefinition;
    public DefaultStringComparisonFinder DefaultStringComparisonFinder;
    public void Execute()
    {
        Converters = new List<IConverter>();
        foreach (var type in ConverterTypes.Types)
        {
            var converter = (IConverter) Activator.CreateInstance(type);
            converter.ModuleWeaver = ModuleWeaver;
            converter.ModuleDefinition = ModuleDefinition;
            converter.StringComparisonConstant = DefaultStringComparisonFinder.StringComparisonConstant;
            if (converter is IEqualityConverter equality)
            {
                equality.UseOperatorForOrdinal = DefaultStringComparisonFinder.UseOperatorForOrdinal;
            }
            converter.Init();
            Converters.Add(converter);
        }
    }

    public List<IConverter> Converters;
}


text:
import java.io._

object GenerateInput {
    def main(args : Array[String]) {
        if (args.length != 3) {
            println("usage: GenerateInput output-dir n-output-files n-points-per-file")
            return;
        }

        val outputDir = args(0)
        val nOutputFiles = args(1).toInt
        val pointsPerFile = args(2).toInt
        val r = new scala.util.Random
        val range = 100.0

        for (f <- 0 until nOutputFiles) {
            val writer = new PrintWriter(new File(outputDir + "/input." + f))

            for (p <- 0 until pointsPerFile) {
                val curr = r.nextDouble * range
                writer.write(curr.toString + "\n")
            }
            writer.close
        }
    }
}


text:
import { IsString, IsNotEmpty, MinLength, IsEmail } from 'class-validator';
import { ApiModelProperty } from '@nestjs/swagger';

export class LoginPayload {
  // @ApiModelProperty({
  //   required: true,
  // })
  // @IsEmail()
  // user_email: string;

  @ApiModelProperty({
    required: true,
  })
  @IsString()
  readonly user_name: string;

  @ApiModelProperty({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  @MinLength(6)
  readonly user_pass: string;
}


text:
package tasty.mushrooms.finder.impl;

import tasty.mushrooms.finder.IContextSwitcher;

/**
 * 用于非混合型App
 *
 * @since 1.0.0
 */
public class SingleContextSwitcher implements IContextSwitcher {

	@Override
	public boolean support(String context) {
		return true;
	}

	@Override
	public void switchContext(String context) {
	}

}


text:
enum eMatrixMode
{
	MODELVIEW_MODE,
	PROJECTION_MODE
};

enum eGraphicsBuffer
{
	COLOR_BUFFER,
	DEPTH_BUFFER
};

enum eShapeMode
{
	QUADS
};

// Interface for platform-specific graphics systems.
// Subclass for each graphics platform (i.e. OpenGL, D3D),
// but use only through an interface pointer/reference.

class IRenderer
{
public:
	IRenderer(void) {}
	virtual ~IRenderer(void) {}

	///////////////////////////////
	// General functions
	///////////////////////////////

	// Call to resize the viewport when window size changes
	// Must call at least once when window is created BEFORE any other
	// functions
	virtual void ResizeViewport(int x, int y, int iWidth, int iHeight) = 0;

	// Call once after ResizeViewport() has been called the first time to
	// initialize the graphics system
	virtual void Inititialize() = 0;

	// Sets/gets current color, used by many other functions
	virtual void SetColor(const Color4F& color) = 0;
	virtual Color4F GetColor() = 0;

	// Call to clear color buffer (all values range from [0,1])
	virtual void ClearColorBuffer(const Color4F& color) = 0;

	// Call to clear the depth buffer (fDepth ranges from [0,1])
	virtual void ClearDepthBuffer(float fDepth) = 0;

	///////////////////////////////
	// General matrix functions
	///////////////////////////////

	// Call to change current matrix
	void MatrixMode(eMatrixMode mode, bool bLoadIdentity=true)
	{
		DoMatrixMode(mode);
		if ( bLoadIdentity )
			LoadIdentity();
	}
protected:
	virtual void DoMatrixMode(eMatrixMode mode) = 0;
public:

	// Call to load identity matrix in current matrix
	virtual void LoadIdentity() = 0;

	// Pushes current matrix
	virtual void PushMatrix() = 0;

	// Pops current matrix
	virtual void PopMatrix() = 0;

	///////////////////////////////
	// Modelview matrix functions
	///////////////////////////////

	// Translates to specified (x,y,z) offset from current position
	virtual void Translate(float x, float y, float z) = 0;

	// Translates to specified (x,y) offset from current position
	virtual void Translate(float x, float y) = 0;

	// Rotates angle amount in degrees around specified axis
	virtual void Rotate(const Angle& rAngle, float x, float y, float z) = 0;

	// Rotates angle amount in degrees around z-axis at current position
	virtual void Rotate(const Angle& rAngle) = 0;

	// Scales by input factors, which affects subsequent rendering
	virtual void Scale(float x, float y) = 0;

	///////////////////////////////
	// Projection matrix functions
	///////////////////////////////

	// Sets up orthographic projection
	virtual void Orthographic(float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar) = 0;

	// Sets up perspective projection where you define a frustrum
	virtual void Perspective(float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar) = 0;

	// Easier method to setup a perspective projection using field of view angle and aspect ratio
	virtual void Perspective(float fFieldOfViewAngle, float fAspectRatio, float fNear, float fFar) = 0;

	// Helper for 2D
	void Orthographic2D(float fLeft, float fRight, float fBottom, float fTop)
	{
		Orthographic(fLeft, fRight, fBottom, fTop, -1, 1);
	}

	///////////////////////////////
	// Texturing functions
	///////////////////////////////

	// Enables/disables texturing
	virtual void SetTexturing(bool bEnable) = 0;

	// Creates a 2d texture, retuning unique texture id and the texture's size in
	// the output parameter. Consecutive calls guarantee returning consecutive ids
	// (i.e. 3,4,5,etc.). The texture size might be larger if the image size is not
	// a power of two.
	virtual TextureId LoadTexture(const ImageData& rImageData, Size2d<float>& rTextureSize) = 0;

	// Overload that expects input image dimensions to be a power of two,
	// otherwise an exception is thrown.
	TextureId LoadTexture(const ImageData& rImageData)
	{
		if ( ImageFuncs::IsPowerOf2(rImageData.GetSize()) == false )
			throw std::logic_error("Input image dimensions must be a power of two");
		Size2d<float> useless;
		return LoadTexture(rImageData, useless);
	}

	// Unloads the texture data for the input texture id
	void FreeTexture(TextureId& rTexId)
	{
		if ( rTexId.IsFree() )
			return;
		DoFreeTexture(rTexId); // Forward call
		rTexId.Reset();
	}
protected:
	virtual void DoFreeTexture(TextureId& rTexId) = 0;
public:

	// Select/unselects the input texture
	virtual void SelectTexture(const TextureId& rTexId, bool bSelect=true) = 0;

	///////////////////////////////
	// Rendering functions
	///////////////////////////////

	virtual void BeginRender(eShapeMode mode) = 0;
	virtual void EndRender() = 0;
	virtual void Vertex(float x, float y) = 0;
	virtual void TexCoord(float s, float t) = 0;

	// Useful for debugging, renders the x-y-z axes
	// (x=red, y=blue, z=green)
	virtual void RenderXYZAxes(float fAxisSize=1.0f, float fAxisWidth=1.0f) = 0;

	//////////////////////////////////////
	// Blending/Transparency functions
	//////////////////////////////////////

	// If enabled, alpha channels are used to determine
	// which part of a texture to render.
	virtual void SetAlphaBlending(bool bEnable) = 0;
};

#endif // _IRENDERER_H_


text:
using System;
using Abp.Domain.Entities;

namespace Abp.NHibernate.Tests.Entities
{
    public class Hotel : Entity
    {
        public virtual string Name { get; set; }

        public virtual DateTime CreationDate { get; set; }

        public virtual DateTime? ModificationDate { get; set; }

        public virtual Location Headquarter { get; set; }
    }
}


text:
import threading = require('../threading');
import java_object = require('../java_object');
import logging = require('../logging');
import ClassData = require('../ClassData');
import gLong = require('../gLong');
import util = require('../util');
import methods = require('../methods');
import ConstantPool = require('../ConstantPool');
import enums = require('../enums');
import assert = require('../assert');
declare var registerNatives: (defs: any) => void;

class sun_reflect_ConstantPool {

  public static 'getSize0(Ljava/lang/Object;)I'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject): number {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return 0;
  }

  public static 'getClassAt0(Ljava/lang/Object;I)Ljava/lang/Class;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaClassObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getClassAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/Class;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaClassObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getMethodAt0(Ljava/lang/Object;I)Ljava/lang/reflect/Member;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getMethodAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/reflect/Member;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getFieldAt0(Ljava/lang/Object;I)Ljava/lang/reflect/Field;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getFieldAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/reflect/Field;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getMemberRefInfoAt0(Ljava/lang/Object;I)[Ljava/lang/String;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaArray {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getIntAt0(Ljava/lang/Object;I)I'(thread: threading.JVMThread, javaThis: java_object.JavaObject, cp: ConstantPool.ConstantPool, idx: number): number {
    return (<ConstantPool.ConstInt32> cp.get(idx)).value;
  }

  public static 'getLongAt0(Ljava/lang/Object;I)J'(thread: threading.JVMThread, javaThis: java_object.JavaObject, cpo: java_object.JavaObject, idx: number): gLong {
    var cp = <ConstantPool.ConstantPool> cpo.get_field(thread, 'Lsun/reflect/ConstantPool;constantPoolOop');
    return (<ConstantPool.ConstLong> cp.get(idx)).value;
  }

  public static 'getFloatAt0(Ljava/lang/Object;I)F'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): number {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return 0;
  }

  public static 'getDoubleAt0(Ljava/lang/Object;I)D'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): number {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return 0;
  }

  public static 'getStringAt0(Ljava/lang/Object;I)Ljava/lang/String;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, arg0: java_object.JavaObject, arg1: number): java_object.JavaObject {
    thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
    // Satisfy TypeScript return type.
    return null;
  }

  public static 'getUTF8At0(Ljava/lang/Object;I)Ljava/lang/String;'(thread: threading.JVMThread, javaThis: java_object.JavaObject, cp: ConstantPool.ConstantPool, idx: number): java_object.JavaObject {
    return java_object.initString(thread.getBsCl(), (<ConstantPool.ConstUTF8> cp.get(idx)).value);
  }

}

class sun_reflect_NativeConstructorAccessorImpl {

  public static 'newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;'(thread: threading.JVMThread, m: java_object.JavaObject, params: java_object.JavaArray): void {
    var cls = <java_object.JavaClassObject> m.get_field(thread, 'Ljava/lang/reflect/Constructor;clazz'),
      slot = m.get_field(thread, 'Ljava/lang/reflect/Constructor;slot');
    thread.setStatus(enums.ThreadStatus.ASYNC_WAITING);
    cls.$cls.initialize(thread, (cls_obj: ClassData.ReferenceClassData) => {
      if (cls_obj !== null) {
        var method: methods.Method = cls_obj.getMethodFromSlot(slot),
          obj = new java_object.JavaObject(cls_obj),
          args: any[] = [obj], i: number;

        if (slot === -1) {
          // HACK: Need to manually look up. :|
          method = cls_obj.methodLookup(thread, "<init>" + util.getDescriptorString(thread.getBsCl().getInitializedClass(thread, 'V').getClassObject(thread), m.get_field(thread, 'Ljava/lang/reflect/Constructor;parameterTypes')));
        }

        if (params !== null) {
          args = args.concat(params.array);
        }
        thread.runMethod(method, args, (e?, rv?) => {
          if (e) {
            // Wrap in a java.lang.reflect.InvocationTargetException
            thread.getBsCl().initializeClass(thread, 'Ljava/lang/reflect/InvocationTargetException;', (cdata: ClassData.ReferenceClassData) => {
              if (cdata !== null) {
                var wrappedE = new java_object.JavaObject(cdata);
                thread.runMethod(cdata.methodLookup(thread, '<init>(Ljava/lang/Throwable;)V'), [wrappedE, e], (e?, rv?) => {
                  thread.throwException(e ? e : wrappedE);
                });
              }
            });
          } else {
            // rv is not defined, since constructors do not return a value.
            // Return the object we passed to the constructor.
            thread.asyncReturn(obj);
          }
        });
      }
    }, true);
  }

}

class sun_reflect_NativeMethodAccessorImpl {

  /**
   * Invoke the specified method on the given object with the given parameters.
   * If the method is an interface method, perform a virtual method dispatch.
   */
  public static 'invoke0(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;'(thread: threading.JVMThread, mObj: java_object.JavaObject, obj: java_object.JavaObject, params: java_object.JavaArray): void {
    var cls = <ClassData.ReferenceClassData> (<java_object.JavaClassObject> mObj.get_field(thread, 'Ljava/lang/reflect/Method;clazz')).$cls,
      slot: number = mObj.get_field(thread, 'Ljava/lang/reflect/Method;slot'),
      ret_type = <java_object.JavaClassObject> mObj.get_field(thread, 'Ljava/lang/reflect/Method;returnType'),
      m: methods.Method = cls.getMethodFromSlot(slot),
      args: any[] = [], i: number;

    if (cls.accessFlags.isInterface()) {
      // It's an interface method. Look up the implementation in the object.
      m = obj.cls.methodLookup(thread, m.name + m.raw_descriptor);
      if (m == null) {
        // Method not found, exception thrown. Return.
        return;
      }
    }

    if (!m.accessFlags.isStatic()) {
      args.push(obj);
    }
    if (params != null) {
      // Unbox any primitives in the arguments array, and pad them if they are 64-bit.
      args = args.concat(util.unboxArguments(thread, m.param_types, params.array));
    }

    thread.setStatus(enums.ThreadStatus.ASYNC_WAITING);
    thread.runMethod(m, args, (e?, rv?) => {
      if (e) {
        // Wrap in a java.lang.reflect.InvocationTargetException
        thread.getBsCl().initializeClass(thread, 'Ljava/lang/reflect/InvocationTargetException;', (cdata: ClassData.ReferenceClassData) => {
          if (cdata !== null) {
            var wrappedE = new java_object.JavaObject(cdata);
            thread.runMethod(cdata.methodLookup(thread, '<init>(Ljava/lang/Throwable;)V'), [wrappedE, e], (e?, rv?) => {
              thread.throwException(e ? e : wrappedE);
            });
          }
        });
      } else {
        if (util.is_primitive_type(m.return_type)) {
          if (m.return_type === 'V') {
            // apparently the JVM returns NULL when there's a void return value,
            // rather than autoboxing a Void object. Go figure!
            thread.asyncReturn(null);
          } else {
            // wrap up primitives in their Object box
            thread.asyncReturn((<ClassData.PrimitiveClassData> ret_type.$cls).createWrapperObject(thread, rv));
          }
        } else {
          thread.asyncReturn(rv);
        }
      }
    });
  }

}

/**
 * From JDK documentation:
 *   Returns the class of the method realFramesToSkip frames up the stack
 *   (zero-based), ignoring frames associated with
 *   java.lang.reflect.Method.invoke() and its implementation. The first
 *   frame is that associated with this method, so getCallerClass(0) returns
 *   the Class object for sun.reflect.Reflection. Frames associated with
 *   java.lang.reflect.Method.invoke() and its implementation are completely
 *   ignored and do not count toward the number of "real" frames skipped.
 */
function get_caller_class(thread: threading.JVMThread, framesToSkip: number): java_object.JavaClassObject {
  var caller = thread.getStackTrace(),
    idx = caller.length - 1 - framesToSkip,
    frame: threading.IStackTraceFrame = caller[idx];
  while (frame.method.full_signature().indexOf('Ljava/lang/reflect/Method;::invoke') === 0) {
    if (idx === 0) {
      // No more stack to search!
      // XXX: What does the JDK do here, throw an exception?
      return null;
    }
    frame = caller[--idx];
  }

  return frame.method.cls.getClassObject(thread);
}

class sun_reflect_Reflection {

  public static 'getCallerClass()Ljava/lang/Class;'(thread: threading.JVMThread): java_object.JavaClassObject {
    // 0th item is Reflection class, 1st item is the class that called us,
    // and 2nd item is the caller of our caller, which is correct.
    return get_caller_class(thread, 2);
  }

  public static 'getCallerClass(I)Ljava/lang/Class;': (thread: threading.JVMThread, frames_to_skip: number) => java_object.JavaClassObject = get_caller_class;

  public static 'getClassAccessFlags(Ljava/lang/Class;)I'(thread: threading.JVMThread, class_obj: java_object.JavaClassObject): number {
    return (<ClassData.ReferenceClassData> class_obj.$cls).accessFlags.getRawByte();
  }

}

registerNatives({
  'sun/reflect/ConstantPool': sun_reflect_ConstantPool,
  'sun/reflect/NativeConstructorAccessorImpl': sun_reflect_NativeConstructorAccessorImpl,
  'sun/reflect/NativeMethodAccessorImpl': sun_reflect_NativeMethodAccessorImpl,
  'sun/reflect/Reflection': sun_reflect_Reflection
});


text:
class DataSource < ActiveRecord::Base
	self.primary_key = :id

	has_many :foods
	accepts_nested_attributes_for :foods
end


text:
@extends('template')

@section('content')

formolir edid: {!! $article->title !!}

    {!! Form::model($article, [
        'method' => 'PATCH',
        'action' => ['ArticlesController@update', $article->id]
    ]) !!}

    @include('errors.list');

    @include('articles._form', ['submitButtonText' => 'Update Article'])
    {!! Form::close() !!}
@stop


text:
DEVSTACK_ROOT=$1

source $DEVSTACK_ROOT/openrc admin admin
echo export OS_TENANT_NAME=$OS_TENANT_NAME
echo export OS_USERNAME=$OS_USERNAME
echo export OS_PASSWORD=$OS_PASSWORD
echo export OS_AUTH_URL=$OS_AUTH_URL


text:
#ifndef _PERF_UI_UTIL_H_
#define _PERF_UI_UTIL_H_ 1

#include <stdarg.h>

int ui__getch(int delay_secs);
int ui__popup_menu(int argc, char * const argv[]);
int ui__help_window(const char *text);
int ui__dialog_yesno(const char *msg);
int ui__question_window(const char *title, const char *text,
			const char *exit_msg, int delay_secs);

struct perf_error_ops {
	int (*error)(const char *format, va_list args);
	int (*warning)(const char *format, va_list args);
};

int perf_error__register(struct perf_error_ops *eops);
int perf_error__unregister(struct perf_error_ops *eops);

#endif /* _PERF_UI_UTIL_H_ */


text:
/**
 * controller
 **/

var controller = {
    loadVacations: function () {
        $.mobile.showPageLoadingMsg();
        model
            .getVacations()
            .done(view.showVacations)
            .fail(function (err) {
                alert("Page load failed: " + JSON.stringify(err, 0, 2));
            })
            .always($.mobile.hidePageLoadingMsg);
    },
    requestPTOs: function ( eventDate, endDate ) {
        $.mobile.showPageLoadingMsg();
        model
            //get the user info, so we can use his email.
            .getUser()
            //pipe the pto request
            .pipe(function (user) {
                return model.sendRequest(user.name, user.email, eventDate, endDate);
            })
            .done(function () {
                alert('Request was sent to approver!');
                view.cleanRequestForm();
                $.mobile.changePage("/");
            })
            .fail(function () {
                alert('Unable to send request.');
            })
            .always($.mobile.hidePageLoadingMsg);
    },
    loadDiscussion: function () {
        $.mobile.showPageLoadingMsg();
        model
            .getDiscussion()
            .done(view.showDiscussion)
            .always($.mobile.hidePageLoadingMsg);
    },

    reply: function(msg) {
        $.mobile.showPageLoadingMsg();
        model
            .sendReply(msg)
            .done(view.cleanReplyForm)
            .done(controller.loadDiscussion)
            .always($.mobile.hidePageLoadingMsg);
    }
};


text:
require 'tumblife/version'
require 'tumblife/error'
require 'tumblife/configuration'
require 'tumblife/client'

module Tumblife
  extend Configuration

  # Alias for Tumblife::Client.new
  #
  # @return [Tumblife::Client]
  def self.client(options = {})
    Tumblife::Client.new(options)
  end

  # Delegate to {Tumblife::Client}
  def self.method_missing(method_name, *args, &block)
    return super unless client.respond_to?(method_name)
    client.send(method_name, *args, &block)
  end

  # Delegate to {Tumblife::Client}
  def self.respond_to?(method_name, include_private = false)
    return client.respond_to?(method_name, include_private) || super
  end
end


text:
const normalize = require('./normalize');

module.exports = (keys, commands) => {
  return commands[normalize(keys)];
};