text:
import * as chai from 'chai';
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
const chaiThings = require('chai-things');
const awsMock = require('aws-sdk-mock');
const AWS = require('aws-sdk');
import * as sinon from 'sinon';
import * as sinonAsPromised from 'sinon-as-promised';
import { Model } from '../src/models/model';
import Joi from 'joi';
import base64url from 'base64-url';
import omitEmpty from 'omit-empty';

chai.use(chaiThings);
chai.use(chaiAsPromised);

describe('Model', () => {
  let db;
  const validTable = 'valid-table';
  const retryableTable = 'retriable-table';
  const invalidModel = {};
  const validModel = { attr1: 'attr1', attr2: 'attr2' };

  before(() => {
    awsMock.mock('DynamoDB.DocumentClient', 'put', (params, cb) => {
      if (params.hasOwnProperty('TableName')) {
        cb(null, {});
      } else {
        cb('Invalid params');
      }
    });
    awsMock.mock('DynamoDB.DocumentClient', 'batchWrite', (params, cb) => {
      if (params.RequestItems.hasOwnProperty(validTable)) {
        cb(null, {});
      } else if (params.RequestItems.hasOwnProperty(retryableTable)) {
        const result = { UnprocessedItems: {} };
        result.UnprocessedItems[retryableTable] = [{ id: 'some-id' }];
        cb(null, result);
      } else {
        cb('Invalid params');
      }
    });
    db = new AWS.DynamoDB.DocumentClient();
    sinon.stub(Model, '_db').returns(db);
  });

  describe('#_client()', () => {
    it('calls the DynamoDB specified method and passes the params', (done) => {
      const method = 'put';
      const params = { TableName: 'my-table', Item: { id: '123' } };
      Model._client(method, params).then(() => {
        const dbMethod = db[method];
        const dbArgs = dbMethod.lastCall.args;
        expect(dbMethod).to.have.been.called;
        expect(dbArgs[0]).to.have.property('TableName');
        done();
      });
    });

    context('withouth TableName', () => {
      it('rejects the promise', (done) => {
        const clientPromise = Model._client('put', {});
        expect(clientPromise).to.be.rejected.and.notify(done);
      });
    });

    let clientSpy = null;
    let retryDelayStub = null;

    context('when there are unprocessed items', () => {
      before(() => {
        clientSpy = sinon.spy(Model, '_client');
        retryDelayStub = sinon.stub(Model, 'retryDelay', { get: () => 1.005 });
      });

      it('retries the function up to maxRetries', (done) => {
        const params = { RequestItems: {} };
        params.RequestItems[retryableTable] = {};
        Model._client('batchWrite', params).then((res) => {
          expect(Model._client.callCount).to.equal(Model.maxRetries + 1);
          const secondCallParams = Model._client.secondCall.args[1];
          expect(secondCallParams.RequestItems).to.deep.equal(res.UnprocessedItems);
          done();
        });
      });

      after(() => {
        clientSpy.restore();
        retryDelayStub.restore();
      });
    });

    context('when there aren\'t unprocessed items', () => {
      before(() => {
        clientSpy = sinon.spy(Model, '_client');
      });

      it('retries the function up to maxRetries', (done) => {
        const params = { RequestItems: {} };
        params.RequestItems[validTable] = {};
        Model._client('batchWrite', params).then((res) => {
          expect(Model._client).to.be.calledOnce;
          expect(res).to.deep.equal({});
          done();
        })
          .catch(done);
      });

      after(() => {
        clientSpy.restore();
      });
    });
  });

  context('stub client', () => {
    const tableName = 'my-table';
    const hashKey = 'myKey';
    const rangeKey = 'myRange';
    const hashValue = 'some hash value';
    const rangeValue = 'some range value';
    const item = { myKey: 1, myRange: 2, anAttribute: 'its value', someAttribute: 'some_value', anotherAttribute: 'value', another: 'value' };
    const lastEvaluatedKey = { myKey: 1, myRange: 2 };
    const nextPage = base64url.encode(JSON.stringify(lastEvaluatedKey));
    const items = Array(5).fill().map(() => item);
    let tNameStub;
    let hashStub;
    let rangeStub;
    let clientStub;
    let schemaStub;

    before(() => {
      clientStub = sinon.stub(Model, '_client');
      clientStub.resolves('ok');
      clientStub.withArgs('query').resolves({ Items: items, LastEvaluatedKey: lastEvaluatedKey });
      clientStub.withArgs('get').resolves({ Item: item });
      tNameStub = sinon.stub(Model, 'tableName', { get: () => tableName });
      hashStub = sinon.stub(Model, 'hashKey', { get: () => hashKey });
      rangeStub = sinon.stub(Model, 'rangeKey', { get: () => rangeKey });
    });

    describe('#get', () => {
      context('only hash key was provided', () => {
        it('calls the DynamoDB get method with correct params', (done) => {
          Model.get(hashValue).then((result) => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('get');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.deep.property(`Key.${hashKey}`, hashValue);
            expect(result).to.deep.equal(item);
            done();
          });
        });
      });

      context('range key was provided', () => {
        it('calls the DynamoDB get method with correct params', (done) => {
          Model.get(hashValue, rangeValue).then(() => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('get');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.deep.property(`Key.${hashKey}`, hashValue);
            expect(args[1]).to.have.deep.property(`Key.${rangeKey}`, rangeValue);
            done();
          });
        });
      });

      context('fields filter was provided and include_fields is true', () => {
        it('calls the DynamoDB get method with correct params', (done) => {
          const fields = ['attr1', 'attr2'];
          const options = { fields: fields.join(','), include_fields: true };
          Model.get(hashValue, rangeValue, options).then(() => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('get');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.deep.property(`Key.${hashKey}`, hashValue);
            expect(args[1]).to.have.deep.property(`Key.${rangeKey}`, rangeValue);
            const dbOptions = Model._buildOptions(options);
            for (let key in dbOptions) {
              expect(args[1][key]).to.deep.equal(dbOptions[key]);
            }
            done();
          });
        });
      });

      context('fields filter was provided and include_fields is false', () => {
        it('calls the DynamoDB get method with correct params', done => {
          const field = 'someAttribute';
          const options = { fields: field, include_fields: false };
          Model.get(hashValue, rangeValue, options).then(result => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('get');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.deep.property(`Key.${hashKey}`, hashValue);
            expect(args[1]).to.have.deep.property(`Key.${rangeKey}`, rangeValue);
            expect(result).not.to.have.property(field);
            done();
          });
        });
      });
    });

    describe('#allBy', () => {
      const value = 'value';

      it('calls the DynamoDB query method with correct params', (done) => {
        Model.allBy(null, value).then((result) => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('query');
          expect(args[1]).to.have.property('TableName', tableName);
          expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue');
          expect(args[1]).not.to.have.property('IndexName');
          expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
          expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:hvalue', value);
          expect(result).to.have.property('items');
          expect(result).to.have.property('nextPage', nextPage);
          done();
        }).catch(done);
      });

      context('when the nexPage param was provided', () => {
        it('includes the ExclusiveStartKey in the query', (done) => {
          const page = nextPage;
          Model.allBy(null, value, { page }).then(() => {
            const args = Model._client.lastCall.args;
            expect(args[1].ExclusiveStartKey).to.deep.equal(lastEvaluatedKey);
            done();
          });
        });
      });

      context('fields filter was provided and include_fields is true', () => {
        it('calls the DynamoDB get method with correct params', (done) => {
          const attributes = ['attr1', 'attr2'];
          const options = { fields: attributes.join(','), include_fields: true };
          Model.allBy(null, value, options).then(result => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('query');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue');
            expect(args[1]).not.to.have.property('IndexName');
            expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
            expect(result).to.have.property('items');
            const dbOptions = Model._buildOptions(options);
            for (let key in dbOptions) {
              expect(args[1][key]).to.deep.contain(dbOptions[key]);
            }
            done();
          });
        });
      });

      context('fields filter was provided and include_fields is false', () => {
        it('filters the result', done => {
          const fields = ['anAttribute', 'anotherAttribute'];
          const options = { fields: fields.join(','), include_fields: false };
          Model.allBy(null, value, options).then(result => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('query');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue');
            expect(args[1]).not.to.have.property('IndexName');
            expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
            expect(result).to.have.property('items');
            result.items.forEach(item => {
              fields.forEach(field => expect(item).not.to.have.property(field));
            });
            done();
          })
            .catch(err => done(err));
        });
      });

      context('when range key filter was provided', () => {
        const rkey = 'anotherAttribute';
        const rvalue = 'value';
        const options = { range: { gt: {} } };
        options.range.gt[rkey] = rvalue;

        it('calls the DynamoDB query method with correct params', (done) => {
          Model.allBy(null, value, options).then((result) => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('query');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue AND #rkey > :rvalue');
            expect(args[1]).not.to.have.property('IndexName');
            expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
            expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#rkey', rkey);
            expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:hvalue', value);
            expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:rvalue', rvalue);
            expect(result).to.have.property('items');
            done();
          }).catch(done);
        });

        it('should build next key for the given range key', done => {
          Model.allBy(null, value, options).then((result) => {
            const lastKey = Model.lastEvaluatedKey(result.nextPage);
            expect(lastKey).to.have.property(rkey, item[rkey])
            expect(lastKey).to.have.property(Model.hashKey)
            expect(lastKey).to.have.property(Model.rangeKey)
            done();
          }).catch(done);
        });
      });

      context('when index name was provided', () => {
        it('calls the DynamoDB query method with correct params', (done) => {
          const indexName = 'my-index';
          const options = { indexName };
          Model.allBy(null, value, options).then(() => {
            const args = Model._client.lastCall.args;
            expect(args[0]).to.equal('query');
            expect(args[1]).to.have.property('TableName', tableName);
            expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue');
            expect(args[1]).to.have.property('IndexName', indexName);
            expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
            expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:hvalue', value);
            done();
          }).catch(done);
        });
      });

      context('when recusrive option was provided', () => {
          const firstResult = {
            items: [{ id: 'myKey1', attr: 1 }, { id: 'myKey2', attr: 2 }],
            nextPage: '2'
          };

          const secondResult = {
            items: [{ id: 'myKey3', attr: 3 }, { id: 'myKey4', attr: 4 }],
            nextPage: '3'
          };

          const lastResult = {
            items: [{ id: 'myKey5', attr: 5 }, { id: 'myKey6', attr: 6 }]
          };

          beforeEach(() => {
            sinon.stub(Model, '_allBy')
              .onFirstCall()
              .resolves(firstResult)
              .onSecondCall()
              .resolves(secondResult)
              .onThirdCall()
              .resolves(lastResult);
          });

          it('iterates recursively over the pages', (done) => {
            Model.allBy(null, value, { recursive: true }).then((results) => {
              expect(Model._allBy).to.have.been.calledThrice;
              expect(results).to.have.property('items');
              expect(results.items.length).to.equal(6);
              done();
            }).catch(err => done(err));
          });

          it('iterates recursively over the pages respecting the limit', (done) => {
            Model.allBy(null, value, { recursive: true, limit: 5 }).then((results) => {
              expect(Model._allBy).to.have.been.calledThrice;
              expect(results).to.have.property('items');
              expect(results.items.length).to.equal(5);
              done();
            }).catch(err => done(err));
          });

          afterEach(() => {
            Model._allBy.restore();
          });
      });
    });

    describe('#allBetween', () => {
      it('calls the DynamoDB query method with correct params', (done) => {
        const keyValue = 'id';
        const start = 1;
        const end = 2;
        Model.allBetween(keyValue, start, end).then((result) => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('query');
          expect(args[1]).to.have.property('TableName', tableName);
          expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue AND #rkey BETWEEN :start AND :end');
          expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', Model.hashKey);
          expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#rkey', Model.rangeKey);
          expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:hvalue', keyValue);
          expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:start', start);
          expect(args[1]).to.have.deep.property('ExpressionAttributeValues.:end', end);
          expect(result).to.have.property('items');
          done();
        }).catch(done);
      });
    });

    describe('#countBy', () => {
      const key = 'key';
      const value = 'value';
      it('calls the DynamoDB query method with correct params', (done) => {
        Model.countBy(key, value).then((result) => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('query');
          expect(args[1]).to.have.property('TableName', tableName);
          expect(args[1]).to.have.property('KeyConditionExpression', '#hkey = :hvalue');
          expect(args[1]).to.have.deep.property('ExpressionAttributeNames.#hkey', key);
          expect(args[1]).to.have.property('Select', 'COUNT');
          done();
        });
      });
    });

    describe('#save', () => {
      it('calls the DynamoDB put method with correct params', (done) => {
        let params = { id: 'key' };
        Model.save(params).then(() => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('put');
          expect(args[1]).to.have.property('TableName', tableName);
          expect(args[1].Item).to.deep.contain(params);
          expect(args[1].Item).to.have.property('createdAt');
          done();
        });
      });
    });

    describe('#saveAll', () => {
      it('calls the DynamoDB batchWrite method with correct params', (done) => {
        const items = [{ id: 'key', some: { nonEmpty: 1 } }, { id: 'key2', some: { attribute: '', nonEmpty: 1 } }];
        const nItems = items.map((i) => omitEmpty(i));
        Model.saveAll(items).then(() => {
          const args = Model._client.lastCall.args;
          const method = args[0];
          const params = args[1];
          expect(method).to.equal('batchWrite');
          expect(params).to.have.deep.property(`RequestItems.${tableName}`);

          for (let item of params.RequestItems[tableName]) {
            expect(item).to.have.deep.property('PutRequest.Item');
            expect(nItems).to.include.something.that.deep.equals(item.PutRequest.Item);
          }
          done();
        });
      });
    });

    describe('#deleteAll', () => {
      it('calls the DynamoDB batchWrite method with correct params', (done) => {
        const itemsKeys = [['key1'], ['key2']];
        Model.deleteAll(itemsKeys).then(() => {
          const args = Model._client.lastCall.args;
          const method = args[0];
          const params = args[1];
          expect(method).to.equal('batchWrite');
          expect(params).to.have.deep.property(`RequestItems.${tableName}`);
          for (let request of params.RequestItems[tableName]) {
            expect(request).to.have.deep.property(`DeleteRequest.Key.${Model.hashKey}`);
          }
          done();
        });
      });
    });

    describe('#update', () => {
      it('calls the DynamoDB update method with correct params', (done) => {
        const params = { att: 'value', att2: 'value 2' };
        Model.update(params, hashValue, rangeValue).then(() => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('update');
          expect(args[1]).to.have.property('TableName');
          expect(args[1]).to.have.property('Key');
          expect(args[1].AttributeUpdates).to.deep.equal(Model._buildAttributeUpdates(params));
          done();
        });
      });
    });

    describe('#increment', () => {
      it('calls the DynamoDB update method with correct params', (done) => {
        const count = 2;
        const countAttribute = 'someCount';
        Model.increment(countAttribute, count, hashValue, rangeValue).then(() => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('update');
          expect(args[1]).to.have.property('TableName');
          expect(args[1]).to.have.property('Key');
          expect(args[1]).to.have.deep.property(`AttributeUpdates.${countAttribute}.Action`, 'ADD');
          expect(args[1]).to.have.deep.property(`AttributeUpdates.${countAttribute}.Value`, count);
          done();
        });
      });
    });

    describe('#incrementAll', () => {
      it('calls the DynamoDB update method with correct params', (done) => {
        const attrValue = {
          attr1: 1,
          attr2: -2
        };
        Model.incrementAll(hashValue, rangeValue, attrValue).then(() => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('update');
          expect(args[1]).to.have.property('TableName');
          expect(args[1]).to.have.property('Key');
          expect(args[1]).to.have.deep.property('AttributeUpdates.attr1.Action', 'ADD');
          expect(args[1]).to.have.deep.property('AttributeUpdates.attr1.Value', 1);
          expect(args[1]).to.have.deep.property('AttributeUpdates.attr2.Action', 'ADD');
          expect(args[1]).to.have.deep.property('AttributeUpdates.attr2.Value', -2);
          done();
        });
      });
    });

    describe('#delete', () => {
      it('calls the DynamoDB delete method with correct params', (done) => {
        Model.delete(hashValue, rangeValue).then(() => {
          const args = Model._client.lastCall.args;
          expect(args[0]).to.equal('delete');
          expect(args[1]).to.have.property('TableName');
          expect(args[1].Key).to.deep.equal(Model._buildKey(hashValue, rangeValue));
          done();
        });
      });
    });

    describe('#isValid', () => {
      context('when using validation', () => {
        before(() => {
          const schema = Joi.object({
            attr1: Joi.string().required(),
            attr2: Joi.string().required()
          });
          schemaStub = sinon.stub(Model, 'schema', { get: () => schema });
        });

        it('succeeds if all required fields are valid', () => {
          expect(Model.isValid(validModel)).to.be.true;
        });

        it('fails if required fields are missing', () => {
          expect(Model.isValid(invalidModel)).to.be.false;
        });

        after(() => {
          schemaStub.restore();
        });
      });

      context('when not using validation', () => {
        before(() => {
          schemaStub = sinon.stub(Model, 'schema', { get: () => null });
        });

        it('succeeds if no validation schema is defined', () => {
          expect(Model.isValid({ some: 'object' })).to.be.true;
        });

        after(() => {
          schemaStub.restore();
        });
      });
    });

    after(() => {
      Model._client.restore();
      tNameStub.restore();
      hashStub.restore();
      rangeStub.restore();
    });
  });

  describe('#_buildAttributeUpdates()', () => {
    it('returns a correct AttributeUpdates object', () => {
      const params = { someAttribute: 'some value', anotherAttribute: 'another value' };
      params[Model.hashKey] = 'some value';
      params[Model.rangeKey] = 'some value';
      const attributeUpdates = Model._buildAttributeUpdates(params);
      for (let key in params) {
        if (key === Model.hashKey || key === Model.rangeKey) {
          expect(attributeUpdates).not.to.have.property(key);
        } else {
          expect(attributeUpdates).to.have.deep.property(`${key}.Action`, 'PUT');
          expect(attributeUpdates).to.have.deep.property(`${key}.Value`, params[key]);
        }
      }
    });
  });

  describe('#_buildOptions', () => {
    context('when fields are provided and include_fields is true', () => {
      it('returns the correct project expression and attribute names', done => {
        const fields = ['attr1', 'attr2'];
        const options = { fields: fields.join(','), include_fields: true };
        const dbOptions = Model._buildOptions(options);
        const projExpression = fields.map(attr => `#${attr}`).join(',');
        expect(dbOptions).to.have.property('ProjectionExpression', projExpression);
        expect(dbOptions).to.have.deep.property(`ExpressionAttributeNames.#${fields[0]}`, fields[0]);
        expect(dbOptions).to.have.deep.property(`ExpressionAttributeNames.#${fields[1]}`, fields[1]);
        done();
      });
    });

    context('when filter params are provided', () => {
      it('returns the correct filter expression and attribute names', done => {
        const status = 'subscribed';
        const name = 'david';
        const email = 'da';
        const options = { filters: { status: { eq: status }, name: { ne: name }, email: { bw: email } } };
        const dbOptions = Model._buildOptions(options);
        const filterExpression = '#status = :status AND #name <> :name AND begins_with(#email, :email)';
        expect(dbOptions).to.have.property('FilterExpression', filterExpression);
        expect(dbOptions).to.have.deep.property('ExpressionAttributeNames.#status', 'status');
        expect(dbOptions).to.have.deep.property('ExpressionAttributeNames.#name', 'name');
        expect(dbOptions).to.have.deep.property('ExpressionAttributeNames.#email', 'email');
        expect(dbOptions).to.have.deep.property('ExpressionAttributeValues.:status', status);
        expect(dbOptions).to.have.deep.property('ExpressionAttributeValues.:name', name);
        expect(dbOptions).to.have.deep.property('ExpressionAttributeValues.:email', email);
        done();
      });
    });
  });

  describe('#_refineItem', () => {
    context('when fields are provided and include_fields is false', () => {
      it('filters the specified fields', done => {
        const field1 = 'field1';
        const field2 = 'field2';
        const field3 = 'field3';
        const item = { field1, field2, field3 };
        const options = { fields: `${field1},${field2}`, include_fields: false };
        const refinedResult = Model._refineItem(item, options);
        expect(refinedResult).to.have.property(field3, field3);
        expect(refinedResult).not.to.have.property(field1);
        expect(refinedResult).and.not.to.have.property(field2);
        done();
      });
    });
  });

  describe('#_refineItems', () => {
    context('when fields are provided and include_fields is false', () => {
      it('filters the specified fields in all items', done => {
        const field1 = 'field1';
        const field2 = 'field2';
        const field3 = 'field3';
        const item = { field1, field2, field3 };
        const items = Array(5).fill().map(() => item);
        const options = { fields: `${field1},${field2}`, include_fields: false };
        const refinedResult = Model._refineItems(items, options);
        refinedResult.forEach(refinedItem => {
          expect(refinedItem).not.to.have.property(field1);
          expect(refinedItem).not.to.have.property(field2);
        });
        done();
      });
    });
  });

  after(() => {
    awsMock.restore('DynamoDB.DocumentClient');
  });
});


text:
from __future__ import print_function
import time

import numpy as np
import tables

N = 144000
#N = 144

def timed(func, *args, **kwargs):
    start = time.time()
    res = func(*args, **kwargs)
    print("%fs elapsed." % (time.time() - start))
    return res

def create_table(output_path):
    print("creating array...", end=' ')
    dt = np.dtype([('field%d' % i, int) for i in range(320)])
    a = np.zeros(N, dtype=dt)
    print("done.")

    output_file = tables.open_file(output_path, mode="w")
    table = output_file.create_table("/", "test", dt)  # , filters=blosc4)
    print("appending data...", end=' ')
    table.append(a)
    print("flushing...", end=' ')
    table.flush()
    print("done.")
    output_file.close()

def copy1(input_path, output_path):
    print("copying data from %s to %s..." % (input_path, output_path))
    input_file = tables.open_file(input_path, mode="r")
    output_file = tables.open_file(output_path, mode="w")

    # copy nodes as a batch
    input_file.copy_node("/", output_file.root, recursive=True)
    output_file.close()
    input_file.close()

def copy2(input_path, output_path):
    print("copying data from %s to %s..." % (input_path, output_path))
    input_file = tables.open_file(input_path, mode="r")
    input_file.copy_file(output_path, overwrite=True)
    input_file.close()

def copy3(input_path, output_path):
    print("copying data from %s to %s..." % (input_path, output_path))
    input_file = tables.open_file(input_path, mode="r")
    output_file = tables.open_file(output_path, mode="w")
    table = input_file.root.test
    table.copy(output_file.root)
    output_file.close()
    input_file.close()

def copy4(input_path, output_path, complib='zlib', complevel=0):
    print("copying data from %s to %s..." % (input_path, output_path))
    input_file = tables.open_file(input_path, mode="r")
    output_file = tables.open_file(output_path, mode="w")

    input_table = input_file.root.test
    print("reading data...", end=' ')
    data = input_file.root.test.read()
    print("done.")

    filter = tables.Filters(complevel=complevel, complib=complib)
    output_table = output_file.create_table("/", "test", input_table.dtype,
                                            filters=filter)
    print("appending data...", end=' ')
    output_table.append(data)
    print("flushing...", end=' ')
    output_table.flush()
    print("done.")

    input_file.close()
    output_file.close()

def copy5(input_path, output_path, complib='zlib', complevel=0):
    print("copying data from %s to %s..." % (input_path, output_path))
    input_file = tables.open_file(input_path, mode="r")
    output_file = tables.open_file(output_path, mode="w")

    input_table = input_file.root.test

    filter = tables.Filters(complevel=complevel, complib=complib)
    output_table = output_file.create_table("/", "test", input_table.dtype,
                                            filters=filter)
    chunksize = 10000
    rowsleft = len(input_table)
    start = 0
    for chunk in range((len(input_table) / chunksize) + 1):
        stop = start + min(chunksize, rowsleft)
        data = input_table.read(start, stop)
        output_table.append(data)
        output_table.flush()
        rowsleft -= chunksize
        start = stop

    input_file.close()
    output_file.close()

if __name__ == '__main__':
    timed(create_table, 'tmp.h5')
#    timed(copy1, 'tmp.h5', 'test1.h5')
    timed(copy2, 'tmp.h5', 'test2.h5')
#    timed(copy3, 'tmp.h5', 'test3.h5')
    timed(copy4, 'tmp.h5', 'test4.h5')
    timed(copy5, 'tmp.h5', 'test5.h5')

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using GraphQL.Introspection;

namespace GraphQL.Types
{
    public class GraphTypesLookup
    {
        private readonly Dictionary<string, GraphType> _types = new Dictionary<string, GraphType>();

        public GraphTypesLookup()
        {
            AddType<StringGraphType>();
            AddType<BooleanGraphType>();
            AddType<FloatGraphType>();
            AddType<IntGraphType>();
            AddType<IdGraphType>();
            AddType<DateGraphType>();
            AddType<DecimalGraphType>();

            AddType<NonNullGraphType<StringGraphType>>();
            AddType<NonNullGraphType<BooleanGraphType>>();
            AddType<NonNullGraphType<FloatGraphType>>();
            AddType<NonNullGraphType<IntGraphType>>();
            AddType<NonNullGraphType<IdGraphType>>();
            AddType<NonNullGraphType<DateGraphType>>();
            AddType<NonNullGraphType<DecimalGraphType>>();

            AddType<__Schema>();
            AddType<__Type>();
            AddType<__Field>();
            AddType<__EnumValue>();
            AddType<__InputValue>();
            AddType<__TypeKind>();
            AddType<__Directive>();
        }

        public static GraphTypesLookup Create(IEnumerable<GraphType> types, Func<Type, GraphType> resolveType)
        {
            var lookup = new GraphTypesLookup();

            var ctx = new TypeCollectionContext(resolveType, (name, graphType, context) =>
            {
                if (lookup[name] == null)
                {
                    lookup.AddType(graphType, context);
                }
            });

            types.Apply(type =>
            {
                lookup.AddType(type, ctx);
            });

            return lookup;
        }

        public void Clear()
        {
            _types.Clear();
        }

        public IEnumerable<GraphType> All()
        {
            return _types.Values;
        }

        public GraphType this[string typeName]
        {
            get
            {
                GraphType result;
                _types.TryGetValue(typeName, out result);
                return result;
            }
            set { _types[typeName] = value; }
        }

        public GraphType this[Type type]
        {
            get
            {
                var result = _types.FirstOrDefault(x => x.Value.GetType() == type);
                return result.Value;
            }
        }

        public IEnumerable<GraphType> FindImplemenationsOf(Type type)
        {
            return _types
                .Values
                .Where(t => t is ObjectGraphType && t.As<ObjectGraphType>().Interfaces.Any(i => i == type))
                .Select(x => x)
                .ToList();
        }

        public void AddType<TType>()
            where TType : GraphType, new()
        {
            var context = new TypeCollectionContext(
                type => (GraphType) Activator.CreateInstance(type),
                (name, type, _) =>
                {
                    _types[name] = type;
                    _?.AddType(name, type, null);
                });

            AddType<TType>(context);
        }

        public void AddType<TType>(TypeCollectionContext context)
            where TType : GraphType
        {
            var instance = context.ResolveType(typeof (TType));
            AddType(instance, context);
        }

        public void AddType(GraphType type, TypeCollectionContext context)
        {
            if (type == null)
            {
                return;
            }

            var name = type.CollectTypes(context);
            _types[name] = type;

            type.Fields.Apply(field =>
            {
                AddTypeIfNotRegistered(field.Type, context);

                field.Arguments?.Apply(arg =>
                {
                    AddTypeIfNotRegistered(arg.Type, context);
                });
            });

            if (type is ObjectGraphType)
            {
                var obj = (ObjectGraphType) type;
                obj.Interfaces.Apply(objectInterface =>
                {
                    AddTypeIfNotRegistered(objectInterface, context);

                    var interfaceInstance = this[objectInterface] as InterfaceGraphType;
                    if (interfaceInstance != null)
                    {
                        interfaceInstance.AddPossibleType(obj);

                        if (interfaceInstance.ResolveType == null && obj.IsTypeOf == null)
                        {
                            throw new ExecutionError((
                                "Interface type {0} does not provide a \"resolveType\" function" +
                                "and possible Type \"{1}\" does not provide a \"isTypeOf\" function.  " +
                                "There is no way to resolve this possible type during execution.")
                                .ToFormat(interfaceInstance, obj));
                        }
                    }
                });
            }

            if (type is UnionGraphType)
            {
                var union = (UnionGraphType) type;

                if (!union.Types.Any())
                {
                    throw new ExecutionError("Must provide types for Union {0}.".ToFormat(union));
                }

                union.Types.Apply(unionedType =>
                {
                    AddTypeIfNotRegistered(unionedType, context);

                    var objType = this[unionedType] as ObjectGraphType;

                    if (union.ResolveType == null && objType != null && objType.IsTypeOf == null)
                    {
                        throw new ExecutionError((
                            "Union type {0} does not provide a \"resolveType\" function" +
                            "and possible Type \"{1}\" does not provide a \"isTypeOf\" function.  " +
                            "There is no way to resolve this possible type during execution.")
                            .ToFormat(union, objType));
                    }

                    union.AddPossibleType(objType);
                });
            }
        }

        private void AddTypeIfNotRegistered(Type type, TypeCollectionContext context)
        {
            var foundType = this[type];
            if (foundType == null)
            {
                AddType(context.ResolveType(type), context);
            }
        }
    }
}


text:
from chainer.training import extension
from chainer.training import trainer
from chainer.training import trigger
from chainer.training import updater

Extension = extension.Extension
make_extension = extension.make_extension
PRIORITY_WRITER = extension.PRIORITY_WRITER
PRIORITY_EDITOR = extension.PRIORITY_EDITOR
PRIORITY_READER = extension.PRIORITY_READER

Trainer = trainer.Trainer

IntervalTrigger = trigger.IntervalTrigger
get_trigger = trigger.get_trigger

Updater = updater.Updater
StandardUpdater = updater.StandardUpdater
ParallelUpdater = updater.ParallelUpdater


text:
module MootoolsPlus
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end


text:
[TOC]

## Debugging

[Linux Debugging](linux_debugging.md) has some emacs-specific debugging tips.

## Blink Style (WebKit)

Chrome and Blink/WebKit style differ. You can use
[directory-local variables](http://www.gnu.org/software/emacs/manual/html_node/emacs/Directory-Variables.html)
to make the tab key do the right thing. E.g., in `third_party/WebKit`, add a
`.dir-locals.el` that contains

```el
((nil . ((indent-tabs-mode . nil)
         (c-basic-offset . 4)
         (fill-column . 120))))
```

This turns off tabs, sets your indent to four spaces, and makes `M-q` wrap at
120 columns (WebKit doesn't define a wrap column, but there's a soft limit
somewhere in that area for comments. Some reviewers do enforce the no wrap
limit, which Emacs can deal with gracefully; see below.)

Be sure to `echo .dir-locals.el >> .git/info/exclude` so `git clean` doesn't
delete your file.

It can be useful to set up a WebKit specific indent style. It's not too much
different so it's easy to base off of the core Google style. Somewhere after
you've loaded google.el (most likely in your .emacs file), add:

```el
(c-add-style "WebKit" '("Google"
                        (c-basic-offset . 4)
                        (c-offsets-alist . ((innamespace . 0)
                                            (access-label . -)
                                            (case-label . 0)
                                            (member-init-intro . +)
                                            (topmost-intro . 0)
                                            (arglist-cont-nonempty . +)))))
```

then you can add

```el
(c-mode . ((c-file-style . "WebKit")))
(c++-mode . ((c-file-style . "WebKit"))))
```

to the end of the .dir-locals.el file you created above. Note that this style
may not yet be complete, but it covers the most common differences.

Now that you have a WebKit specific style being applied, and assuming you have
font locking and it's default jit locking turned on, you can also get Emacs 23
to wrap long lines more intelligently by adding the following to your .emacs
file:

```el
;; For dealing with WebKit long lines and word wrapping.
(defun c-mode-adaptive-indent (beg end)
  "Set the wrap-prefix for the the region between BEG and END with adaptive filling."
  (goto-char beg)
  (while
      (let ((lbp (line-beginning-position))
            (lep (line-end-position)))
        (put-text-property lbp lep 'wrap-prefix (concat (fill-context-prefix lbp lep) (make-string c-basic-offset ? )))
        (search-forward "\n" end t))))

(define-minor-mode c-adaptive-wrap-mode
  "Wrap the buffer text with adaptive filling for c-mode."
  :lighter ""
  (save-excursion
    (save-restriction
      (widen)
      (let ((buffer-undo-list t)
            (inhibit-read-only t)
            (mod (buffer-modified-p)))
        (if c-adaptive-wrap-mode
            (jit-lock-register 'c-mode-adaptive-indent)
          (jit-lock-unregister 'c-mode-adaptive-indent)
          (remove-text-properties (point-min) (point-max) '(wrap-prefix pref)))
        (restore-buffer-modified-p mod)))))

(defun c-adaptive-wrap-mode-for-webkit ()
  "Turn on visual line mode and adaptive wrapping for WebKit source files."
  (if (or (string-equal "webkit" c-indentation-style)
          (string-equal "WebKit" c-indentation-style))
      (progn
        (visual-line-mode t)
        (c-adaptive-wrap-mode t))))

(add-hook 'c-mode-common-hook 'c-adaptive-wrap-mode-for-webkit)
(add-hook 'hack-local-variables-hook 'c-adaptive-wrap-mode-for-webkit)
```

This turns on visual wrap mode for files using the WebKit c style, and sets up a
hook to dynamically set the indent on the wrapped lines. It's not quite as
intelligent as it could be (e.g., what would the wrap be if there really were a
newline there?), but it's very fast. It makes dealing with long code lines
anywhere much more tolerable (not just in WebKit).

## Syntax-error Highlighting

[Ninja](ninja_build.md) users get in-line highlighting of syntax errors using
`flymake.el` on each buffer-save:

    (load-file "src/tools/emacs/flymake-chromium.el")

## [ycmd](https://github.com/Valloric/ycmd) (YouCompleteMe) + flycheck

[emacs-ycmd](https://github.com/abingham/emacs-ycmd) in combination with
flycheck provides:

*   advanced code completion
*   syntax checking
*   navigation to declarations and definitions (using `ycmd-goto`) based on
    on-the-fly processing using clang. A quick demo video showing code
    completion and flycheck highlighting a missing semicolon syntax error:

[![video preview][img]][video]

[img]: http://img.youtube.com/vi/a0zMbm4jACk/0.jpg
[video]: http://www.youtube.com/watch?feature=player_embedded&v=a0zMbm4jACk

### Requirements

  * Your build system is set up for building with clang or wrapper+clang

### Setup

1.  Clone, update external git repositories and build.sh ycmd from
    https://github.com/Valloric/ycmd into a directory, e.g. `~/dev/ycmd`
1.  Test `ycmd` by running `~/dev/ycmd$ python ycmd/__main__.py` You should see
    `KeyError: 'hmac_secret'`
1.  Install the following packages to emacs, for example from melpa:
    *   `ycmd`
    *   `company-ycmd`
    *   `flycheck-ycmd`
1.  [More info on configuring emacs-ycmd](https://github.com/abingham/emacs-ycmd#quickstart)
    1.  Assuming your checkout of Chromium is in `~/dev/blink`, i.e. this is the
        directory in which you find the `src`folder, create a symbolic link as
        follows:

        ```shell
        cd ~/dev/blink
        ln -s src/tools/vim/chromium.ycm_extra_conf.py .ycm_extra_conf.py
        ```

    1.  Add something like the following to your `init.el`

```el
;; ycmd

;;; Googlers can replace a lot of this with (require 'google-ycmd).

(require 'ycmd)
(require 'company-ycmd)
(require 'flycheck-ycmd)

(company-ycmd-setup)
(flycheck-ycmd-setup)

;; Show completions after 0.15 seconds
(setq company-idle-delay 0.15)

;; Activate for editing C++ files
(add-hook 'c++-mode-hook 'ycmd-mode)
(add-hook 'c++-mode-hook 'company-mode)
(add-hook 'c++-mode-hook 'flycheck-mode)

;; Replace the directory information with where you downloaded ycmd to
(set-variable 'ycmd-server-command (list "python" (substitute-in-file-name "$HOME/dev/ycmd/ycmd/__main__.py")))

;; Edit according to where you have your Chromium/Blink checkout
(add-to-list 'ycmd-extra-conf-whitelist (substitute-in-file-name "$HOME/dev/blink/.ycm_extra_conf.py"))

;; Show flycheck errors in idle-mode as well
(setq ycmd-parse-conditions '(save new-line mode-enabled idle-change))

;; Makes emacs-ycmd less verbose
(setq url-show-status nil)
```

### Troubleshooting

*   If no completions show up or emacs reports errors, you can check the
    `*ycmd-server*` buffer for errors. See the next bullet point for how to
    handle "OS Error: No such file or directory"
*   Launching emacs from an OS menu might result in a different environment so
    that `ycmd` does not find ninja. In that case, you can use a package like
    [exec-path from shell](https://github.com/purcell/exec-path-from-shell) and
    add the following to your `init.el`:

```el
(require 'exec-path-from-shell)
(when (memq window-system '(mac ns x))
    (exec-path-from-shell-initialize))
```

## ff-get-other-file

There's a builtin function called `ff-get-other-file` which will get the "other
file" based on file extension. I have this bound to C-o in c-mode
(`(local-set-key "\C-o" 'ff-get-other-file)`). While "other file" is per-mode
defined, in c-like languages it means jumping between the header and the source
file. So I switch back and forth between the header and the source with C-o. If
we had separate include/ and src/ directories, this would be a pain to setup,
but this might just work out of the box for you. See the documentation for the
variable `cc-other-file-alist` for more information.

One drawback of ff-get-other-file is that it will always switch to a matching
buffer, even if the other file is in a different directory, so if you have
A.cc,A.h,A.cc(2) then ff-get-other-file will switch to A.h from A.cc(2) rather
than load A.h(2) from the appropriate directory. If you prefer something (C
specific) that always finds, try this:

```el
(defun cc-other-file()
  "Toggles source/header file"
  (interactive)
  (let ((buf (current-buffer))
        (name (file-name-sans-extension (buffer-file-name)))
	(other-extens
	 (cadr (assoc (concat "\\."
			      (file-name-extension (buffer-file-name))
			      "\\'")
		      cc-other-file-alist))))
    (dolist (e other-extens)
      (if (let ((f (concat name e)))
	    (and (file-exists-p f) (find-file f)))
	  (return)))
    )
  )
```

_Note: if you know an easy way to change the ff-get-other-file behavior, please
replace this hack with that solution! - stevenjb@chromium.org_

## Use Google's C++ style!

We have an emacs module,
[google-c-style.el](http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el),
which adds c-mode formatting. Then add to your .emacs:

```el
(load "/<path/to/chromium>/src/buildtools/clang_format/script/clang-format.el")
(add-hook 'c-mode-common-hook
    (function (lambda () (local-set-key (kbd "TAB") 'clang-format-region))))
```

Now, you can use the

<Tab>

key to format the current line (even a long line) or region.

## Highlight long lines

One nice way to highlight long lines and other style issues:

```el
(require 'whitespace)
(setq whitespace-style '(face indentation trailing empty lines-tail))
(setq whitespace-line-column nil)
(set-face-attribute 'whitespace-line nil
                    :background "purple"
                    :foreground "white"
                    :weight 'bold)
(global-whitespace-mode 1)
```

Note: You might need to grab the latest version of
[whitespace.el](http://www.emacswiki.org/emacs-en/download/whitespace.el).

## gyp

### `gyp` style
There is a gyp mode that provides basic indentation and font-lock (syntax
highlighting) support. The mode derives from python.el (bundled with newer
emacsen).

You can find it in /src/tools/gyp/tools/emacs

See the README file there for installation instructions.

**Important**: the mode is only tested with `python.el` (bundled with newer
emacsen), not with `python-mode.el` (outdated and less maintained these days).

### deep nesting

A couple of helpers that show a summary of where you are; the first by tracing
the indentation hierarchy upwards, the second by only showing `#if`s and
`#else`s that are relevant to the current line:

```el
(defun ami-summarize-indentation-at-point ()
  "Echo a summary of how one gets from the left-most column to
  POINT in terms of indentation changes."
  (interactive)
  (save-excursion
    (let ((cur-indent most-positive-fixnum)
          (trace '()))
      (while (not (bobp))
        (let ((current-line (buffer-substring (line-beginning-position)
                                              (line-end-position))))
          (when (and (not (string-match "^\\s-*$" current-line))
                     (< (current-indentation) cur-indent))
            (setq cur-indent (current-indentation))
            (setq trace (cons current-line trace))
            (if (or (string-match "^\\s-*}" current-line)
                    (string-match "^\\s-*else " current-line)
                    (string-match "^\\s-*elif " current-line))
                (setq cur-indent (1+ cur-indent)))))
        (forward-line -1))
      (message "%s" (mapconcat 'identity trace "\n")))))

(require 'cl)
  (defun ami-summarize-preprocessor-branches-at-point ()
    "Summarize the C preprocessor branches needed to get to point."
    (interactive)
    (flet ((current-line-text ()
              (buffer-substring (line-beginning-position) (line-end-position))))
      (save-excursion
        (let ((eol (or (end-of-line) (point)))
              deactivate-mark directives-stack)
          (goto-char (point-min))
          (while (re-search-forward "^#\\(if\\|else\\|endif\\)" eol t)
            (if (or (string-prefix-p "#if" (match-string 0))
                    (string-prefix-p "#else" (match-string 0)))
                (push (current-line-text) directives-stack)
            (if (string-prefix-p "#endif" (match-string 0))
                 (while (string-prefix-p "#else" (pop directives-stack)) t))))
          (message "%s" (mapconcat 'identity (reverse directives-stack) "\n"))))))
```

## find-things-fast

erg wrote a suite of tools that do common operations from the root of your
repository, called
[Find Things Fast](https://github.com/eglaysher/find-things-fast). It contains
ido completion over `git ls-files` (or the svn find equivalent) and `grepsource`
that only git greps files with extensions we care about (or the equivalent the
`find | xargs grep` statement in non-git repos.)

## vc-mode and find-file performance

When you first open a file under git control, vc mode kicks in and does a high
level stat of your git repo. For huge repos, especially WebKit and Chromium,
this makes opening a file take literally seconds. This snippet disables VC git
for chrome directories:

```el
; Turn off VC git for chrome
(when (locate-library "vc")
(defadvice vc-registered (around nochrome-vc-registered (file))
(message (format "nochrome-vc-registered %s" file))
(if (string-match ".*chrome/src.*" file)
(progn
(message (format "Skipping VC mode for %s" % file))
(setq ad-return-value nil)
)
ad-do-it)
)
(ad-activate 'vc-registered)
)
```

## git tools

We're collecting Chrome-specific tools under `tools/emacs`. See the files there
for details.

*   `trybot.el`: import Windows trybot output into a `compilation-mode` buffer.

## ERC for IRC

See [ErcIrc][erc_irc.md].

## TODO

*   Figure out how to make `M-x compile` default to
    `cd /path/to/chrome/root; make -r chrome`.


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["reduxLogger"] = factory();
	else
		root["reduxLogger"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	__webpack_require__(2);
	module.exports = __webpack_require__(2);

/***/ },
/* 1 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	var repeat = exports.repeat = function repeat(str, times) {
	  return new Array(times + 1).join(str);
	};

	var pad = exports.pad = function pad(num, maxLength) {
	  return repeat("0", maxLength - num.toString().length) + num;
	};

	var formatTime = exports.formatTime = function formatTime(time) {
	  return pad(time.getHours(), 2) + ":" + pad(time.getMinutes(), 2) + ":" + pad(time.getSeconds(), 2) + "." + pad(time.getMilliseconds(), 3);
	};

	// Use performance API if it's available in order to get better precision
	var timer = exports.timer = typeof performance !== "undefined" && performance !== null && typeof performance.now === "function" ? performance : Date;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.logger = exports.defaults = undefined;

	var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

	var _core = __webpack_require__(3);

	var _helpers = __webpack_require__(1);

	var _defaults = __webpack_require__(4);

	var _defaults2 = _interopRequireDefault(_defaults);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	/**
	 * Creates logger with following options
	 *
	 * @namespace
	 * @param {object} options - options for logger
	 * @param {string | function | object} options.level - console[level]
	 * @param {boolean} options.duration - print duration of each action?
	 * @param {boolean} options.timestamp - print timestamp with each action?
	 * @param {object} options.colors - custom colors
	 * @param {object} options.logger - implementation of the `console` API
	 * @param {boolean} options.logErrors - should errors in action execution be caught, logged, and re-thrown?
	 * @param {boolean} options.collapsed - is group collapsed?
	 * @param {boolean} options.predicate - condition which resolves logger behavior
	 * @param {function} options.stateTransformer - transform state before print
	 * @param {function} options.actionTransformer - transform action before print
	 * @param {function} options.errorTransformer - transform error before print
	 *
	 * @returns {function} logger middleware
	 */
	function createLogger() {
	  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

	  var loggerOptions = _extends({}, _defaults2.default, options);

	  var logger = loggerOptions.logger,
	      transformer = loggerOptions.transformer,
	      stateTransformer = loggerOptions.stateTransformer,
	      errorTransformer = loggerOptions.errorTransformer,
	      predicate = loggerOptions.predicate,
	      logErrors = loggerOptions.logErrors,
	      diffPredicate = loggerOptions.diffPredicate;

	  // Return if 'console' object is not defined

	  if (typeof logger === 'undefined') {
	    return function () {
	      return function (next) {
	        return function (action) {
	          return next(action);
	        };
	      };
	    };
	  }

	  if (transformer) {
	    console.error('Option \'transformer\' is deprecated, use \'stateTransformer\' instead!'); // eslint-disable-line no-console
	  }

	  // Detect if 'createLogger' was passed directly to 'applyMiddleware'.
	  if (options.getState && options.dispatch) {
	    // eslint-disable-next-line no-console
	    console.error('[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware:\n\n// Logger with default options\nimport { logger } from \'redux-logger\'\nconst store = createStore(\n  reducer,\n  applyMiddleware(logger)\n)\n\n\n// Or you can create your own logger with custom options http://bit.ly/redux-logger-options\nimport createLogger from \'redux-logger\'\n\nconst logger = createLogger({\n  // ...options\n});\n\nconst store = createStore(\n  reducer,\n  applyMiddleware(logger)\n)\n');

	    return function () {
	      return function (next) {
	        return function (action) {
	          return next(action);
	        };
	      };
	    };
	  }

	  var logBuffer = [];

	  return function (_ref) {
	    var getState = _ref.getState;
	    return function (next) {
	      return function (action) {
	        // Exit early if predicate function returns 'false'
	        if (typeof predicate === 'function' && !predicate(getState, action)) {
	          return next(action);
	        }

	        var logEntry = {};
	        logBuffer.push(logEntry);

	        logEntry.started = _helpers.timer.now();
	        logEntry.startedTime = new Date();
	        logEntry.prevState = stateTransformer(getState());
	        logEntry.action = action;

	        var returnedValue = void 0;
	        if (logErrors) {
	          try {
	            returnedValue = next(action);
	          } catch (e) {
	            logEntry.error = errorTransformer(e);
	          }
	        } else {
	          returnedValue = next(action);
	        }

	        logEntry.took = _helpers.timer.now() - logEntry.started;
	        logEntry.nextState = stateTransformer(getState());

	        var diff = loggerOptions.diff && typeof diffPredicate === 'function' ? diffPredicate(getState, action) : loggerOptions.diff;

	        (0, _core.printBuffer)(logBuffer, _extends({}, loggerOptions, { diff: diff }));
	        logBuffer.length = 0;

	        if (logEntry.error) throw logEntry.error;
	        return returnedValue;
	      };
	    };
	  };
	}

	var defaultLogger = createLogger();

	exports.defaults = _defaults2.default;
	exports.logger = defaultLogger;
	exports.default = createLogger;

/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

	exports.printBuffer = printBuffer;

	var _helpers = __webpack_require__(1);

	var _diff = __webpack_require__(5);

	var _diff2 = _interopRequireDefault(_diff);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

	/**
	 * Get log level string based on supplied params
	 *
	 * @param {string | function | object} level - console[level]
	 * @param {object} action - selected action
	 * @param {array} payload - selected payload
	 * @param {string} type - log entry type
	 *
	 * @returns {string} level
	 */
	function getLogLevel(level, action, payload, type) {
	  switch (typeof level === 'undefined' ? 'undefined' : _typeof(level)) {
	    case 'object':
	      return typeof level[type] === 'function' ? level[type].apply(level, _toConsumableArray(payload)) : level[type];
	    case 'function':
	      return level(action);
	    default:
	      return level;
	  }
	}

	function defaultTitleFormatter(options) {
	  var timestamp = options.timestamp,
	      duration = options.duration;

	  return function (action, time, took) {
	    var parts = ['action'];

	    parts.push('%c' + String(action.type));
	    if (timestamp) parts.push('%c@ ' + time);
	    if (duration) parts.push('%c(in ' + took.toFixed(2) + ' ms)');

	    return parts.join(' ');
	  };
	}

	function printBuffer(buffer, options) {
	  var logger = options.logger,
	      actionTransformer = options.actionTransformer,
	      _options$titleFormatt = options.titleFormatter,
	      titleFormatter = _options$titleFormatt === undefined ? defaultTitleFormatter(options) : _options$titleFormatt,
	      collapsed = options.collapsed,
	      colors = options.colors,
	      level = options.level,
	      diff = options.diff;

	  buffer.forEach(function (logEntry, key) {
	    var started = logEntry.started,
	        startedTime = logEntry.startedTime,
	        action = logEntry.action,
	        prevState = logEntry.prevState,
	        error = logEntry.error;
	    var took = logEntry.took,
	        nextState = logEntry.nextState;

	    var nextEntry = buffer[key + 1];

	    if (nextEntry) {
	      nextState = nextEntry.prevState;
	      took = nextEntry.started - started;
	    }

	    // Message
	    var formattedAction = actionTransformer(action);
	    var isCollapsed = typeof collapsed === 'function' ? collapsed(function () {
	      return nextState;
	    }, action, logEntry) : collapsed;

	    var formattedTime = (0, _helpers.formatTime)(startedTime);
	    var titleCSS = colors.title ? 'color: ' + colors.title(formattedAction) + ';' : '';
	    var headerCSS = ['color: gray; font-weight: lighter;'];
	    headerCSS.push(titleCSS);
	    if (options.timestamp) headerCSS.push('color: gray; font-weight: lighter;');
	    if (options.duration) headerCSS.push('color: gray; font-weight: lighter;');
	    var title = titleFormatter(formattedAction, formattedTime, took);

	    // Render
	    try {
	      if (isCollapsed) {
	        if (colors.title) logger.groupCollapsed.apply(logger, ['%c ' + title].concat(headerCSS));else logger.groupCollapsed(title);
	      } else {
	        if (colors.title) logger.group.apply(logger, ['%c ' + title].concat(headerCSS));else logger.group(title);
	      }
	    } catch (e) {
	      logger.log(title);
	    }

	    var prevStateLevel = getLogLevel(level, formattedAction, [prevState], 'prevState');
	    var actionLevel = getLogLevel(level, formattedAction, [formattedAction], 'action');
	    var errorLevel = getLogLevel(level, formattedAction, [error, prevState], 'error');
	    var nextStateLevel = getLogLevel(level, formattedAction, [nextState], 'nextState');

	    if (prevStateLevel) {
	      if (colors.prevState) logger[prevStateLevel]('%c prev state', 'color: ' + colors.prevState(prevState) + '; font-weight: bold', prevState);else logger[prevStateLevel]('prev state', prevState);
	    }

	    if (actionLevel) {
	      if (colors.action) logger[actionLevel]('%c action    ', 'color: ' + colors.action(formattedAction) + '; font-weight: bold', formattedAction);else logger[actionLevel]('action    ', formattedAction);
	    }

	    if (error && errorLevel) {
	      if (colors.error) logger[errorLevel]('%c error     ', 'color: ' + colors.error(error, prevState) + '; font-weight: bold;', error);else logger[errorLevel]('error     ', error);
	    }

	    if (nextStateLevel) {
	      if (colors.nextState) logger[nextStateLevel]('%c next state', 'color: ' + colors.nextState(nextState) + '; font-weight: bold', nextState);else logger[nextStateLevel]('next state', nextState);
	    }

	    if (diff) {
	      (0, _diff2.default)(prevState, nextState, logger, isCollapsed);
	    }

	    try {
	      logger.groupEnd();
	    } catch (e) {
	      logger.log('\u2014\u2014 log end \u2014\u2014');
	    }
	  });
	}

/***/ },
/* 4 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.default = {
	  level: "log",
	  logger: console,
	  logErrors: true,
	  collapsed: undefined,
	  predicate: undefined,
	  duration: false,
	  timestamp: true,
	  stateTransformer: function stateTransformer(state) {
	    return state;
	  },
	  actionTransformer: function actionTransformer(action) {
	    return action;
	  },
	  errorTransformer: function errorTransformer(error) {
	    return error;
	  },
	  colors: {
	    title: function title() {
	      return "inherit";
	    },
	    prevState: function prevState() {
	      return "#9E9E9E";
	    },
	    action: function action() {
	      return "#03A9F4";
	    },
	    nextState: function nextState() {
	      return "#4CAF50";
	    },
	    error: function error() {
	      return "#F20404";
	    }
	  },
	  diff: false,
	  diffPredicate: undefined,

	  // Deprecated options
	  transformer: undefined
	};
	module.exports = exports["default"];

/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.default = diffLogger;

	var _deepDiff = __webpack_require__(6);

	var _deepDiff2 = _interopRequireDefault(_deepDiff);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

	// https://github.com/flitbit/diff#differences
	var dictionary = {
	  'E': {
	    color: '#2196F3',
	    text: 'CHANGED:'
	  },
	  'N': {
	    color: '#4CAF50',
	    text: 'ADDED:'
	  },
	  'D': {
	    color: '#F44336',
	    text: 'DELETED:'
	  },
	  'A': {
	    color: '#2196F3',
	    text: 'ARRAY:'
	  }
	};

	function style(kind) {
	  return 'color: ' + dictionary[kind].color + '; font-weight: bold';
	}

	function render(diff) {
	  var kind = diff.kind,
	      path = diff.path,
	      lhs = diff.lhs,
	      rhs = diff.rhs,
	      index = diff.index,
	      item = diff.item;

	  switch (kind) {
	    case 'E':
	      return [path.join('.'), lhs, '\u2192', rhs];
	    case 'N':
	      return [path.join('.'), rhs];
	    case 'D':
	      return [path.join('.')];
	    case 'A':
	      return [path.join('.') + '[' + index + ']', item];
	    default:
	      return [];
	  }
	}

	function diffLogger(prevState, newState, logger, isCollapsed) {
	  var diff = (0, _deepDiff2.default)(prevState, newState);

	  try {
	    if (isCollapsed) {
	      logger.groupCollapsed('diff');
	    } else {
	      logger.group('diff');
	    }
	  } catch (e) {
	    logger.log('diff');
	  }

	  if (diff) {
	    diff.forEach(function (elem) {
	      var kind = elem.kind;

	      var output = render(elem);

	      logger.log.apply(logger, ['%c ' + dictionary[kind].text, style(kind)].concat(_toConsumableArray(output)));
	    });
	  } else {
	    logger.log('\u2014\u2014 no diff \u2014\u2014');
	  }

	  try {
	    logger.groupEnd();
	  } catch (e) {
	    logger.log('\u2014\u2014 diff end \u2014\u2014 ');
	  }
	}
	module.exports = exports['default'];

/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {

	var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global) {/*!
	 * deep-diff.
	 * Licensed under the MIT License.
	 */
	;(function(root, factory) {
	  'use strict';
	  if (true) {
	    // AMD. Register as an anonymous module.
	    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
	      return factory();
	    }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	  } else if (typeof exports === 'object') {
	    // Node. Does not work with strict CommonJS, but
	    // only CommonJS-like environments that support module.exports,
	    // like Node.
	    module.exports = factory();
	  } else {
	    // Browser globals (root is window)
	    root.DeepDiff = factory();
	  }
	}(this, function(undefined) {
	  'use strict';

	  var $scope, conflict, conflictResolution = [];
	  if (typeof global === 'object' && global) {
	    $scope = global;
	  } else if (typeof window !== 'undefined') {
	    $scope = window;
	  } else {
	    $scope = {};
	  }
	  conflict = $scope.DeepDiff;
	  if (conflict) {
	    conflictResolution.push(
	      function() {
	        if ('undefined' !== typeof conflict && $scope.DeepDiff === accumulateDiff) {
	          $scope.DeepDiff = conflict;
	          conflict = undefined;
	        }
	      });
	  }

	  // nodejs compatible on server side and in the browser.
	  function inherits(ctor, superCtor) {
	    ctor.super_ = superCtor;
	    ctor.prototype = Object.create(superCtor.prototype, {
	      constructor: {
	        value: ctor,
	        enumerable: false,
	        writable: true,
	        configurable: true
	      }
	    });
	  }

	  function Diff(kind, path) {
	    Object.defineProperty(this, 'kind', {
	      value: kind,
	      enumerable: true
	    });
	    if (path && path.length) {
	      Object.defineProperty(this, 'path', {
	        value: path,
	        enumerable: true
	      });
	    }
	  }

	  function DiffEdit(path, origin, value) {
	    DiffEdit.super_.call(this, 'E', path);
	    Object.defineProperty(this, 'lhs', {
	      value: origin,
	      enumerable: true
	    });
	    Object.defineProperty(this, 'rhs', {
	      value: value,
	      enumerable: true
	    });
	  }
	  inherits(DiffEdit, Diff);

	  function DiffNew(path, value) {
	    DiffNew.super_.call(this, 'N', path);
	    Object.defineProperty(this, 'rhs', {
	      value: value,
	      enumerable: true
	    });
	  }
	  inherits(DiffNew, Diff);

	  function DiffDeleted(path, value) {
	    DiffDeleted.super_.call(this, 'D', path);
	    Object.defineProperty(this, 'lhs', {
	      value: value,
	      enumerable: true
	    });
	  }
	  inherits(DiffDeleted, Diff);

	  function DiffArray(path, index, item) {
	    DiffArray.super_.call(this, 'A', path);
	    Object.defineProperty(this, 'index', {
	      value: index,
	      enumerable: true
	    });
	    Object.defineProperty(this, 'item', {
	      value: item,
	      enumerable: true
	    });
	  }
	  inherits(DiffArray, Diff);

	  function arrayRemove(arr, from, to) {
	    var rest = arr.slice((to || from) + 1 || arr.length);
	    arr.length = from < 0 ? arr.length + from : from;
	    arr.push.apply(arr, rest);
	    return arr;
	  }

	  function realTypeOf(subject) {
	    var type = typeof subject;
	    if (type !== 'object') {
	      return type;
	    }

	    if (subject === Math) {
	      return 'math';
	    } else if (subject === null) {
	      return 'null';
	    } else if (Array.isArray(subject)) {
	      return 'array';
	    } else if (Object.prototype.toString.call(subject) === '[object Date]') {
	      return 'date';
	    } else if (typeof subject.toString !== 'undefined' && /^\/.*\//.test(subject.toString())) {
	      return 'regexp';
	    }
	    return 'object';
	  }

	  function deepDiff(lhs, rhs, changes, prefilter, path, key, stack) {
	    path = path || [];
	    var currentPath = path.slice(0);
	    if (typeof key !== 'undefined') {
	      if (prefilter) {
	        if (typeof(prefilter) === 'function' && prefilter(currentPath, key)) { return; }
	        else if (typeof(prefilter) === 'object') {
	          if (prefilter.prefilter && prefilter.prefilter(currentPath, key)) { return; }
	          if (prefilter.normalize) {
	            var alt = prefilter.normalize(currentPath, key, lhs, rhs);
	            if (alt) {
	              lhs = alt[0];
	              rhs = alt[1];
	            }
	          }
	        }
	      }
	      currentPath.push(key);
	    }

	    // Use string comparison for regexes
	    if (realTypeOf(lhs) === 'regexp' && realTypeOf(rhs) === 'regexp') {
	      lhs = lhs.toString();
	      rhs = rhs.toString();
	    }

	    var ltype = typeof lhs;
	    var rtype = typeof rhs;
	    if (ltype === 'undefined') {
	      if (rtype !== 'undefined') {
	        changes(new DiffNew(currentPath, rhs));
	      }
	    } else if (rtype === 'undefined') {
	      changes(new DiffDeleted(currentPath, lhs));
	    } else if (realTypeOf(lhs) !== realTypeOf(rhs)) {
	      changes(new DiffEdit(currentPath, lhs, rhs));
	    } else if (Object.prototype.toString.call(lhs) === '[object Date]' && Object.prototype.toString.call(rhs) === '[object Date]' && ((lhs - rhs) !== 0)) {
	      changes(new DiffEdit(currentPath, lhs, rhs));
	    } else if (ltype === 'object' && lhs !== null && rhs !== null) {
	      stack = stack || [];
	      if (stack.indexOf(lhs) < 0) {
	        stack.push(lhs);
	        if (Array.isArray(lhs)) {
	          var i, len = lhs.length;
	          for (i = 0; i < lhs.length; i++) {
	            if (i >= rhs.length) {
	              changes(new DiffArray(currentPath, i, new DiffDeleted(undefined, lhs[i])));
	            } else {
	              deepDiff(lhs[i], rhs[i], changes, prefilter, currentPath, i, stack);
	            }
	          }
	          while (i < rhs.length) {
	            changes(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i++])));
	          }
	        } else {
	          var akeys = Object.keys(lhs);
	          var pkeys = Object.keys(rhs);
	          akeys.forEach(function(k, i) {
	            var other = pkeys.indexOf(k);
	            if (other >= 0) {
	              deepDiff(lhs[k], rhs[k], changes, prefilter, currentPath, k, stack);
	              pkeys = arrayRemove(pkeys, other);
	            } else {
	              deepDiff(lhs[k], undefined, changes, prefilter, currentPath, k, stack);
	            }
	          });
	          pkeys.forEach(function(k) {
	            deepDiff(undefined, rhs[k], changes, prefilter, currentPath, k, stack);
	          });
	        }
	        stack.length = stack.length - 1;
	      }
	    } else if (lhs !== rhs) {
	      if (!(ltype === 'number' && isNaN(lhs) && isNaN(rhs))) {
	        changes(new DiffEdit(currentPath, lhs, rhs));
	      }
	    }
	  }

	  function accumulateDiff(lhs, rhs, prefilter, accum) {
	    accum = accum || [];
	    deepDiff(lhs, rhs,
	      function(diff) {
	        if (diff) {
	          accum.push(diff);
	        }
	      },
	      prefilter);
	    return (accum.length) ? accum : undefined;
	  }

	  function applyArrayChange(arr, index, change) {
	    if (change.path && change.path.length) {
	      var it = arr[index],
	          i, u = change.path.length - 1;
	      for (i = 0; i < u; i++) {
	        it = it[change.path[i]];
	      }
	      switch (change.kind) {
	        case 'A':
	          applyArrayChange(it[change.path[i]], change.index, change.item);
	          break;
	        case 'D':
	          delete it[change.path[i]];
	          break;
	        case 'E':
	        case 'N':
	          it[change.path[i]] = change.rhs;
	          break;
	      }
	    } else {
	      switch (change.kind) {
	        case 'A':
	          applyArrayChange(arr[index], change.index, change.item);
	          break;
	        case 'D':
	          arr = arrayRemove(arr, index);
	          break;
	        case 'E':
	        case 'N':
	          arr[index] = change.rhs;
	          break;
	      }
	    }
	    return arr;
	  }

	  function applyChange(target, source, change) {
	    if (target && source && change && change.kind) {
	      var it = target,
	          i = -1,
	          last = change.path ? change.path.length - 1 : 0;
	      while (++i < last) {
	        if (typeof it[change.path[i]] === 'undefined') {
	          it[change.path[i]] = (typeof change.path[i] === 'number') ? [] : {};
	        }
	        it = it[change.path[i]];
	      }
	      switch (change.kind) {
	        case 'A':
	          applyArrayChange(change.path ? it[change.path[i]] : it, change.index, change.item);
	          break;
	        case 'D':
	          delete it[change.path[i]];
	          break;
	        case 'E':
	        case 'N':
	          it[change.path[i]] = change.rhs;
	          break;
	      }
	    }
	  }

	  function revertArrayChange(arr, index, change) {
	    if (change.path && change.path.length) {
	      // the structure of the object at the index has changed...
	      var it = arr[index],
	          i, u = change.path.length - 1;
	      for (i = 0; i < u; i++) {
	        it = it[change.path[i]];
	      }
	      switch (change.kind) {
	        case 'A':
	          revertArrayChange(it[change.path[i]], change.index, change.item);
	          break;
	        case 'D':
	          it[change.path[i]] = change.lhs;
	          break;
	        case 'E':
	          it[change.path[i]] = change.lhs;
	          break;
	        case 'N':
	          delete it[change.path[i]];
	          break;
	      }
	    } else {
	      // the array item is different...
	      switch (change.kind) {
	        case 'A':
	          revertArrayChange(arr[index], change.index, change.item);
	          break;
	        case 'D':
	          arr[index] = change.lhs;
	          break;
	        case 'E':
	          arr[index] = change.lhs;
	          break;
	        case 'N':
	          arr = arrayRemove(arr, index);
	          break;
	      }
	    }
	    return arr;
	  }

	  function revertChange(target, source, change) {
	    if (target && source && change && change.kind) {
	      var it = target,
	          i, u;
	      u = change.path.length - 1;
	      for (i = 0; i < u; i++) {
	        if (typeof it[change.path[i]] === 'undefined') {
	          it[change.path[i]] = {};
	        }
	        it = it[change.path[i]];
	      }
	      switch (change.kind) {
	        case 'A':
	          // Array was modified...
	          // it will be an array...
	          revertArrayChange(it[change.path[i]], change.index, change.item);
	          break;
	        case 'D':
	          // Item was deleted...
	          it[change.path[i]] = change.lhs;
	          break;
	        case 'E':
	          // Item was edited...
	          it[change.path[i]] = change.lhs;
	          break;
	        case 'N':
	          // Item is new...
	          delete it[change.path[i]];
	          break;
	      }
	    }
	  }

	  function applyDiff(target, source, filter) {
	    if (target && source) {
	      var onChange = function(change) {
	        if (!filter || filter(target, source, change)) {
	          applyChange(target, source, change);
	        }
	      };
	      deepDiff(target, source, onChange);
	    }
	  }

	  Object.defineProperties(accumulateDiff, {

	    diff: {
	      value: accumulateDiff,
	      enumerable: true
	    },
	    observableDiff: {
	      value: deepDiff,
	      enumerable: true
	    },
	    applyDiff: {
	      value: applyDiff,
	      enumerable: true
	    },
	    applyChange: {
	      value: applyChange,
	      enumerable: true
	    },
	    revertChange: {
	      value: revertChange,
	      enumerable: true
	    },
	    isConflict: {
	      value: function() {
	        return 'undefined' !== typeof conflict;
	      },
	      enumerable: true
	    },
	    noConflict: {
	      value: function() {
	        if (conflictResolution) {
	          conflictResolution.forEach(function(it) {
	            it();
	          });
	          conflictResolution = null;
	        }
	        return accumulateDiff;
	      },
	      enumerable: true
	    }
	  });

	  return accumulateDiff;
	}));

	/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))

/***/ }
/******/ ])
});
;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Sida Bot. Misc. 23:167. 2002

#### Original name
null

### Remarks
null


text:
package reuse.util;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PairTest {

	@Before
	public void setUp() throws Exception {
		System.err.println("setup");
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testHashCode() {
//		fail("Not yet implemented");
	}
//
//	@Test
//	public void testEqualsObject() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testPairLR() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testPair() {
//		fail("Not yet implemented");
//	}

}


text:
<?php

class SchedulerRemoveTaskProcessor extends modObjectRemoveProcessor {
    public $classKey = 'sTaskRun';
    public $objectType = 'scheduler.staskrun';
    public $languageTopics = array('scheduler:default');
}

return 'SchedulerRemoveTaskProcessor';


text:
#include <stdio.h>

int main() {
	int average, grades[3];
		/*I
	 * ts an array containing the list of same kind of variables.
	 * In C an array contain same data types.
	 * 3 denotes number of items in array
	 */
	grades[0] = 80;
	grades[1] = 85;
	grades[2] = 90;
	average = (grades[0] + grades[1] + grades[2]) / 3;
  printf("The average of the 3 grades is: %d", average);

  return 0;
}


text:
#ifndef GUCEF_CORE_CIOACCESSTOIOSTREAM_H
#define GUCEF_CORE_CIOACCESSTOIOSTREAM_H

/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#include <stdio.h>
#include <iostream>

#ifndef GUCEF_CORE_CSTRING_H
#include "gucefCORE_CString.h"
#define GUCEF_CORE_CSTRING_H
#endif /* GUCEF_CORE_CSTRING_H ? */

#ifndef GUCEF_CORE_CIOACCESS_H
#include "CIOAccess.h"        /* base class for all media manipulators */
#define GUCEF_CORE_CIOACCESS_H
#endif /* GUCEF_CORE_CIOACCESS_H ? */

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

namespace GUCEF {
namespace CORE {

/*-------------------------------------------------------------------------//
//                                                                         //
//      CLASSES                                                            //
//                                                                         //
//-------------------------------------------------------------------------*/

template< typename char_type, typename traits_type = std::char_traits< char_type > >
class TIOAccessToStreambuff : public std::basic_streambuf< char_type, traits_type >
{
    private:

    CIOAccess* m_access;

    public:

    using Base = std::basic_streambuf< char_type, traits_type >;
    using int_type = typename Base::int_type;
    using pos_type = typename traits_type::pos_type;
    using off_type = typename traits_type::off_type;
    using streamsize = typename std::streamsize;

    TIOAccessToStreambuff( CIOAccess& access )
        : Base()
        , m_access( &access )
    {
    }

    virtual ~TIOAccessToStreambuff()
    {
        m_access = GUCEF_NULL;
    }

    virtual int_type overflow( int_type c ) override
    {
        if ( GUCEF_NULL != m_access )
        {
            if ( 1 == m_access->Write( &c, sizeof(int_type), 1 ) )
                return traits_type::not_eof( c );
        }
        return traits_type::eof();
    }

    virtual int_type underflow() override
    {
        if ( GUCEF_NULL != m_access )
        {
            char_type c;
            if ( 1 == m_access->Read( &c, sizeof(c), 1 ) )
                return traits_type::to_int_type( c );
        }
        return traits_type::eof();
    }

    virtual int sync() override
    {
        if ( GUCEF_NULL != m_access )
        {
            m_access->Flush();
        }
        return 0;
    }

    virtual pos_type seekoff( off_type offset, std::ios_base::seekdir origin, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ) override
    {
        // change position by offset, according to way and mode
        if ( GUCEF_NULL != m_access )
        {
            Int32 fOrigin = -1;
            switch ( origin )
            {
                case std::ios_base::beg: fOrigin = SEEK_SET; break;
                case std::ios_base::cur: fOrigin = SEEK_CUR; break;
                case std::ios_base::end: fOrigin = SEEK_END; break;
                default: return pos_type(off_type(-1));
            }

            if ( 0 == m_access->Seek( (Int32) offset, fOrigin ) )
                return (pos_type) m_access->Tell();
        }
        return pos_type(off_type(-1));
    }

    virtual pos_type seekpos( pos_type pos, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ) override
    {
        // change to specified position, according to mode
        if ( GUCEF_NULL != m_access )
        {
            if ( 0 == m_access->Setpos( (UInt32) pos ) )
                return (pos_type) m_access->Tell();
        }
        return pos_type(off_type(-1));
    }

    virtual streamsize xsgetn( char_type* outBuffer, streamsize charsToRead )
    {
        if ( GUCEF_NULL != m_access )
        {
            UInt32 elementsRead = m_access->Read( outBuffer, sizeof(char_type), (UInt32)charsToRead );
            return (streamsize) elementsRead;
        }
        return traits_type::eof();
    }
};

/*-------------------------------------------------------------------------*/

/**
 *  Basic and simplistic wrapper for IOAccess to STL style std iostream style data access.
 */
class GUCEF_CORE_PUBLIC_CPP CIOAccessToIOStream : public std::iostream
{
    public:

    typedef TIOAccessToStreambuff< char > ByteStreambuffFromIOAccess;

    CIOAccessToIOStream( CIOAccess& access );

    virtual ~CIOAccessToIOStream();

    private:

    CIOAccessToIOStream( void );                                       /**< not implemented */
    CIOAccessToIOStream( const CIOAccessToIOStream& src );             /**< not implemented */
    CIOAccessToIOStream& operator=( const CIOAccessToIOStream& src );  /**< not implemented */

    private:

    CIOAccess* m_access;
    ByteStreambuffFromIOAccess m_stlAdapter;
};

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

}; /* namespace CORE */
}; /* namespace GUCEF */

/*-------------------------------------------------------------------------*/

#endif /* GUCEF_CORE_CIOACCESSTOIOSTREAM_H ? */

/*-------------------------------------------------------------------------//
//                                                                         //
//      Info & Changes                                                     //
//                                                                         //
//-------------------------------------------------------------------------//

- 26-07-2006 :
        - Dinand: Designed and implemented this class.

-----------------------------------------------------------------------------*/


text:
document.querySelector('button').onclick = function(){
  var area = document.querySelector('textarea').value;
  var grafo = document.createElement('p');
  var br = document.createElement('br');
  grafo.innerText = area;
  grafo.setAttribute("class","p1");
  var bot = document.createElement('p');
  var falabot = ["Como vai você ?","HA     HA    HA","Você se hidrata?","Ata meu","FON","ENTROSA NÃO","Beijinhos, rsrs"];
  bot.innerText = falabot[(parseInt(Math.random()*7))];
  bot.setAttribute("class","p2");
  document.querySelector('textarea').value = '';
  if (area==="") {

  }else {
    postagens.appendChild(grafo);
    postagens.appendChild(br);
    postagens.appendChild(bot)
  }
}


text:
require 'spec_helper'

describe ::UserSkillRate::RateWithinRangeValidator do
  describe 'ensures proper range' do
    context 'when within range' do
      let(:content) { build(:user_skill_rate_content, :with_boolean_rate_type, rate: 1) }

      it 'pass validation' do
        described_class.new.validate(content)

        result = content.errors.count
        expect(result).to eq(0)
      end
    end

    context 'when out of range' do
      let(:content) { build(:user_skill_rate_content, :with_boolean_rate_type, rate: 99) }

      it 'fails validation' do
        described_class.new.validate(content)

        result = content.errors.full_messages
        expect(result).to include('Skill is not included in the list')
      end
    end
  end
end


text:
package com.dianping.cat.report.task.alert.summary;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.unidal.dal.jdbc.DalException;
import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.Cat;
import com.dianping.cat.home.dal.report.Alteration;
import com.dianping.cat.home.dal.report.AlterationDao;
import com.dianping.cat.home.dal.report.AlterationEntity;

public class AlterationSummaryContentGenerator extends SummaryContentGenerator {

	@Inject
	private AlterationDao m_alterationDao;

	public static final String ID = "AlterationSummaryContentGenerator";

	@Override
	public Map<Object, Object> generateModel(String domain, Date date) {
		Map<Object, Object> dataMap = new HashMap<Object, Object>();

		try {
			List<Alteration> alterations = m_alterationDao.findByDomainAndTime(getStartDate(date), date, domain,
			      AlterationEntity.READSET_FULL);

			dataMap.put("count", alterations.size());
			dataMap.put("items", alterations);
		} catch (DalException e) {
			Cat.logError(e);
		}
		return dataMap;
	}

	@Override
	public String getID() {
		return ID;
	}

	private Date getStartDate(Date date) {
		return new Date(date.getTime() - AlertSummaryExecutor.ALTERATION_DURATION);
	}

	@Override
	protected String getTemplateAddress() {
		return "alterationInfo.ftl";
	}

}


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "C:/SPlisHSPlasH/extern/install/PositionBasedDynamics")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "Release")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()


text:
<?php

/**
 * MQTT Client
 */

namespace Server\Asyn\MQTT\Message;

use Server\Asyn\MQTT\Debug;
use Server\Asyn\MQTT\Exception;
use Server\Asyn\MQTT\IMqtt;
use Server\Asyn\MQTT\Message;
use Server\Asyn\MQTT\Utility;

/**
 * Base class for MQTT Messages
 */
abstract class Base
{
    /**
     * Message with Fixed Header ONLY
     *
     * CONNECT, CONNACK, PINGREQ, PINGRESP, DISCONNECT
     */
    const FIXED_ONLY     = 0x01;

    /**
     * Message with Variable Header
     * Fixed Header + Variable Header
     *
     */
    const WITH_VARIABLE  = 0x02;
    /**
     * Message with Payload
     * Fixed Header + Variable Header + Payload
     *
     */
    const WITH_PAYLOAD   = 0x03;
    /**
     * Protocol Type
     * Constants FIXED_ONLY, WITH_VARIABLE, WITH_PAYLOAD
     *
     * @var int
     */
    protected $protocol_type = self::FIXED_ONLY;

    /**
     * @var IMqtt
     */
    public $mqtt;

    /**
     * Bytes to read
     *
     * @var int
     */
    protected $read_bytes = 0;

    /**
     * @var header\Base
     */
    public $header = null;

    /**
     * Control Packet Type
     *
     * @var int
     */
    protected $message_type = 0;

    public function __construct(IMqtt $mqtt)
    {
        $this->mqtt = $mqtt;

        $header_class = __NAMESPACE__ . '\\Header\\' . Message::$name[$this->message_type];

        $this->header = new $header_class($this);
    }

    final public function decode($packet_data, $remaining_length)
    {
        $payload_pos = 0;

        $this->header->decode($packet_data, $remaining_length, $payload_pos);
        return $this->decodePayload($packet_data, $payload_pos);
    }

    protected function decodePayload(& $packet_data, & $payload_pos)
    {
        return true;
    }

    /**
     * Get Control Packet Type
     *
     * @return int
     */
    public function getMessageType()
    {
        return $this->message_type;
    }

    /**
     * Get Protocol Type
     *
     * @return int
     */
    public function getProtocolType()
    {
        return $this->protocol_type;
    }

    /**
     * Set Packet Identifier
     *
     * @param int $msgid
     */
    public function setMsgID($msgid)
    {
        $this->header->setMsgID($msgid);
    }

    /**
     * Get Packet Identifier
     *
     * @return int
     */
    public function getMsgID()
    {
        return $this->header->getMsgID();
    }

    /**
     * Build packet data
     *
     * @param int & $length
     * @return string
     * @throws Exception
     */
    final public function build(&$length=0)
    {
        if ($this->protocol_type == self::FIXED_ONLY) {
            $payload = $this->payload();
        } else if ($this->protocol_type == self::WITH_VARIABLE) {
            $payload = $this->payload();
        } else if ($this->protocol_type == self::WITH_PAYLOAD) {
            $payload = $this->payload();
        } else {
            throw new Exception('Invalid protocol type');
        }

        $length = strlen($payload);
        $this->header->setPayloadLength($length);

        $length = $this->header->getFullLength();
        Debug::Log(Debug::DEBUG, 'Message Build: total length='.$length);

        return $this->header->build() . $payload;
    }

    protected $payload = '';

    /**
     * Prepare Payload
     * Empty payload by default
     *
     * @return string
     */
    protected function payload()
    {
        return $this->payload;
    }

    /**
     * Process packet with Fixed Header + Message Identifier only
     *
     * @param string $message
     * @return array|bool
     */
    final protected function processReadFixedHeaderWithMsgID($message)
    {
        $packet_length = 4;
        $name = Message::$name[$this->message_type];

        if (!isset($message[$packet_length - 1])) {
            # error
            Debug::Log(Debug::DEBUG, "Message {$name}: error on reading");
            return false;
        }

        $packet = unpack('Ccmd/Clength/nmsgid', $message);

        $packet['cmd'] = Utility::UnpackCommand($packet['cmd']);

        if ($packet['cmd']['message_type'] != $this->getMessageType()) {
            Debug::Log(Debug::DEBUG, "Message {$name}: type mismatch");
            return false;
        } else {
            Debug::Log(Debug::DEBUG, "Message {$name}: success");
            return $packet;
        }
    }

    protected function readUTF($messages)
    {
        $arr = [];
        while (strlen($messages) != 0) {
            $length = unpack("n", $messages)[1];
            $message = substr($messages, 2, $length);
            $arr[] = $message;
            $messages = substr($messages, 2 + $length);
        }
        return $arr;
    }
}

# EOF


text:
<ti-light state="component._state"
          toggle="panel.callActorService(component, 'toggleLight', $event)"
          dimmerChange="panel.callActorService(component, 'dimmerChange', $event)"
          options="{lightState: true, dimmer: true, scene: false, fieldMappings: {dimmerLevel: 'brightness' }}"></ti-light>


text:
function capitalize(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

// #####splitName
// split "event1 event2" into an
// array of event names
function splitName(names, context) {
  // get result of name if defined as a function
  var events = result(names, context);

  // split by spaces if result isn't an array
  // always returns an array
  return _.isArray(events) ? events : events && events.split(' ');
}

// #####result
// returns get result of an expression
function result(expr, context) {
  return _.isFunction(expr) ? expr.apply(context) : expr;
}

function firstDef() {
  return _.find(arguments, function(arg) {
    return !_.isUndefined(arg);
  });
}