text:
<!DOCTYPE html>
<!--
@license
Copyright (C) 2018 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-diff</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>

<link rel="import" href="gr-diff-host.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-diff-host></gr-diff-host>
  </template>
</test-fixture>

<script>
  suite('gr-diff-host tests', () => {
    let element;
    let sandbox;

    setup(() => {
      sandbox = sinon.sandbox.create();
      element = fixture('basic');
    });

    teardown(() => {
      sandbox.restore();
    });

    test('reload() cancels before network resolves', () => {
      const cancelStub = sandbox.stub(element.$.diff, 'cancel');

      // Stub the network calls into requests that never resolve.
      sandbox.stub(element, '_getDiff', () => new Promise(() => {}));

      element.reload();
      assert.isTrue(cancelStub.called);
    });

    suite('not logged in', () => {
      setup(() => {
        const getLoggedInPromise = Promise.resolve(false);
        stub('gr-rest-api-interface', {
          getLoggedIn() { return getLoggedInPromise; },
        });
        element = fixture('basic');
        return getLoggedInPromise;
      });

      test('reload() loads files weblinks', () => {
        const weblinksStub = sandbox.stub(Gerrit.Nav, '_generateWeblinks')
            .returns({name: 'stubb', url: '#s'});
        sandbox.stub(element.$.restAPI, 'getDiff').returns(Promise.resolve({
          content: [],
        }));
        element.projectName = 'test-project';
        element.path = 'test-path';
        element.commitRange = {baseCommit: 'test-base', commit: 'test-commit'};
        element.patchRange = {};
        return element.reload().then(() => {
          assert.isTrue(weblinksStub.calledTwice);
          assert.isTrue(weblinksStub.firstCall.calledWith({
            commit: 'test-base',
            file: 'test-path',
            options: {
              weblinks: undefined,
            },
            repo: 'test-project',
            type: Gerrit.Nav.WeblinkType.FILE}));
          assert.isTrue(weblinksStub.secondCall.calledWith({
            commit: 'test-commit',
            file: 'test-path',
            options: {
              weblinks: undefined,
            },
            repo: 'test-project',
            type: Gerrit.Nav.WeblinkType.FILE}));
          assert.deepEqual(element.filesWeblinks, {
            meta_a: [{name: 'stubb', url: '#s'}],
            meta_b: [{name: 'stubb', url: '#s'}],
          });
        });
      });

      test('_getDiff handles null diff responses', done => {
        stub('gr-rest-api-interface', {
          getDiff() { return Promise.resolve(null); },
        });
        element.changeNum = 123;
        element.patchRange = {basePatchNum: 1, patchNum: 2};
        element.path = 'file.txt';
        element._getDiff().then(done);
      });

      test('reload resolves on error', () => {
        const onErrStub = sandbox.stub(element, '_handleGetDiffError');
        const error = {ok: false, status: 500};
        sandbox.stub(element.$.restAPI, 'getDiff',
            (changeNum, basePatchNum, patchNum, path, onErr) => {
              onErr(error);
            });
        return element.reload().then(() => {
          assert.isTrue(onErrStub.calledOnce);
        });
      });

      suite('_handleGetDiffError', () => {
        let serverErrorStub;
        let pageErrorStub;

        setup(() => {
          serverErrorStub = sinon.stub();
          element.addEventListener('server-error', serverErrorStub);
          pageErrorStub = sinon.stub();
          element.addEventListener('page-error', pageErrorStub);
        });

        test('page error on HTTP-409', () => {
          element._handleGetDiffError({status: 409});
          assert.isTrue(serverErrorStub.calledOnce);
          assert.isFalse(pageErrorStub.called);
          assert.isNotOk(element._errorMessage);
        });

        test('server error on non-HTTP-409', () => {
          element._handleGetDiffError({status: 500});
          assert.isFalse(serverErrorStub.called);
          assert.isTrue(pageErrorStub.calledOnce);
          assert.isNotOk(element._errorMessage);
        });

        test('error message if showLoadFailure', () => {
          element.showLoadFailure = true;
          element._handleGetDiffError({status: 500, statusText: 'Failure!'});
          assert.isFalse(serverErrorStub.called);
          assert.isFalse(pageErrorStub.called);
          assert.equal(element._errorMessage,
              'Encountered error when loading the diff: 500 Failure!');
        });
      });

      suite('image diffs', () => {
        let mockFile1;
        let mockFile2;
        setup(() => {
          mockFile1 = {
            body: 'Qk06AAAAAAAAADYAAAAoAAAAAQAAAP////8BACAAAAAAAAAAAAATCwAAE' +
            'wsAAAAAAAAAAAAAAAAA/w==',
            type: 'image/bmp',
          };
          mockFile2 = {
            body: 'Qk06AAAAAAAAADYAAAAoAAAAAQAAAP////8BACAAAAAAAAAAAAATCwAAE' +
            'wsAAAAAAAAAAAAA/////w==',
            type: 'image/bmp',
          };
          sandbox.stub(element.$.restAPI,
              'getB64FileContents',
              (changeId, patchNum, path, opt_parentIndex) => {
                return Promise.resolve(opt_parentIndex === 1 ? mockFile1 :
                  mockFile2);
              });

          element.patchRange = {basePatchNum: 'PARENT', patchNum: 1};
          element.comments = {left: [], right: []};
        });

        test('renders image diffs with same file name', done => {
          const mockDiff = {
            meta_a: {name: 'carrot.jpg', content_type: 'image/jpeg', lines: 66},
            meta_b: {name: 'carrot.jpg', content_type: 'image/jpeg',
              lines: 560},
            intraline_status: 'OK',
            change_type: 'MODIFIED',
            diff_header: [
              'diff --git a/carrot.jpg b/carrot.jpg',
              'index 2adc47d..f9c2f2c 100644',
              '--- a/carrot.jpg',
              '+++ b/carrot.jpg',
              'Binary files differ',
            ],
            content: [{skip: 66}],
            binary: true,
          };
          sandbox.stub(element.$.restAPI, 'getDiff')
              .returns(Promise.resolve(mockDiff));

          const rendered = () => {
            // Recognizes that it should be an image diff.
            assert.isTrue(element.isImageDiff);
            assert.instanceOf(
                element.$.diff.$.diffBuilder._builder, GrDiffBuilderImage);

            // Left image rendered with the parent commit's version of the file.
            const leftImage =
                element.$.diff.$.diffTable.querySelector('td.left img');
            const leftLabel =
                element.$.diff.$.diffTable.querySelector('td.left label');
            const leftLabelContent = leftLabel.querySelector('.label');
            const leftLabelName = leftLabel.querySelector('.name');

            const rightImage =
                element.$.diff.$.diffTable.querySelector('td.right img');
            const rightLabel = element.$.diff.$.diffTable.querySelector(
                'td.right label');
            const rightLabelContent = rightLabel.querySelector('.label');
            const rightLabelName = rightLabel.querySelector('.name');

            assert.isNotOk(rightLabelName);
            assert.isNotOk(leftLabelName);

            let leftLoaded = false;
            let rightLoaded = false;

            leftImage.addEventListener('load', () => {
              assert.isOk(leftImage);
              assert.equal(leftImage.getAttribute('src'),
                  'data:image/bmp;base64, ' + mockFile1.body);
              assert.equal(leftLabelContent.textContent, '1×1 image/bmp');
              leftLoaded = true;
              if (rightLoaded) {
                element.removeEventListener('render', rendered);
                done();
              }
            });

            rightImage.addEventListener('load', () => {
              assert.isOk(rightImage);
              assert.equal(rightImage.getAttribute('src'),
                  'data:image/bmp;base64, ' + mockFile2.body);
              assert.equal(rightLabelContent.textContent, '1×1 image/bmp');

              rightLoaded = true;
              if (leftLoaded) {
                element.removeEventListener('render', rendered);
                done();
              }
            });
          };

          element.addEventListener('render', rendered);

          element.$.restAPI.getDiffPreferences().then(prefs => {
            element.prefs = prefs;
            element.reload();
          });
        });

        test('renders image diffs with a different file name', done => {
          const mockDiff = {
            meta_a: {name: 'carrot.jpg', content_type: 'image/jpeg', lines: 66},
            meta_b: {name: 'carrot2.jpg', content_type: 'image/jpeg',
              lines: 560},
            intraline_status: 'OK',
            change_type: 'MODIFIED',
            diff_header: [
              'diff --git a/carrot.jpg b/carrot2.jpg',
              'index 2adc47d..f9c2f2c 100644',
              '--- a/carrot.jpg',
              '+++ b/carrot2.jpg',
              'Binary files differ',
            ],
            content: [{skip: 66}],
            binary: true,
          };
          sandbox.stub(element.$.restAPI, 'getDiff')
              .returns(Promise.resolve(mockDiff));

          const rendered = () => {
            // Recognizes that it should be an image diff.
            assert.isTrue(element.isImageDiff);
            assert.instanceOf(
                element.$.diff.$.diffBuilder._builder, GrDiffBuilderImage);

            // Left image rendered with the parent commit's version of the file.
            const leftImage =
                element.$.diff.$.diffTable.querySelector('td.left img');
            const leftLabel =
                element.$.diff.$.diffTable.querySelector('td.left label');
            const leftLabelContent = leftLabel.querySelector('.label');
            const leftLabelName = leftLabel.querySelector('.name');

            const rightImage =
                element.$.diff.$.diffTable.querySelector('td.right img');
            const rightLabel = element.$.diff.$.diffTable.querySelector(
                'td.right label');
            const rightLabelContent = rightLabel.querySelector('.label');
            const rightLabelName = rightLabel.querySelector('.name');

            assert.isOk(rightLabelName);
            assert.isOk(leftLabelName);
            assert.equal(leftLabelName.textContent, mockDiff.meta_a.name);
            assert.equal(rightLabelName.textContent, mockDiff.meta_b.name);

            let leftLoaded = false;
            let rightLoaded = false;

            leftImage.addEventListener('load', () => {
              assert.isOk(leftImage);
              assert.equal(leftImage.getAttribute('src'),
                  'data:image/bmp;base64, ' + mockFile1.body);
              assert.equal(leftLabelContent.textContent, '1×1 image/bmp');
              leftLoaded = true;
              if (rightLoaded) {
                element.removeEventListener('render', rendered);
                done();
              }
            });

            rightImage.addEventListener('load', () => {
              assert.isOk(rightImage);
              assert.equal(rightImage.getAttribute('src'),
                  'data:image/bmp;base64, ' + mockFile2.body);
              assert.equal(rightLabelContent.textContent, '1×1 image/bmp');

              rightLoaded = true;
              if (leftLoaded) {
                element.removeEventListener('render', rendered);
                done();
              }
            });
          };

          element.addEventListener('render', rendered);

          element.$.restAPI.getDiffPreferences().then(prefs => {
            element.prefs = prefs;
            element.reload();
          });
        });

        test('renders added image', done => {
          const mockDiff = {
            meta_b: {name: 'carrot.jpg', content_type: 'image/jpeg',
              lines: 560},
            intraline_status: 'OK',
            change_type: 'ADDED',
            diff_header: [
              'diff --git a/carrot.jpg b/carrot.jpg',
              'index 0000000..f9c2f2c 100644',
              '--- /dev/null',
              '+++ b/carrot.jpg',
              'Binary files differ',
            ],
            content: [{skip: 66}],
            binary: true,
          };
          sandbox.stub(element.$.restAPI, 'getDiff')
              .returns(Promise.resolve(mockDiff));

          element.addEventListener('render', () => {
            // Recognizes that it should be an image diff.
            assert.isTrue(element.isImageDiff);
            assert.instanceOf(
                element.$.diff.$.diffBuilder._builder, GrDiffBuilderImage);

            const leftImage =
                element.$.diff.$.diffTable.querySelector('td.left img');
            const rightImage =
                element.$.diff.$.diffTable.querySelector('td.right img');

            assert.isNotOk(leftImage);
            assert.isOk(rightImage);
            done();
          });

          element.$.restAPI.getDiffPreferences().then(prefs => {
            element.prefs = prefs;
            element.reload();
          });
        });

        test('renders removed image', done => {
          const mockDiff = {
            meta_a: {name: 'carrot.jpg', content_type: 'image/jpeg',
              lines: 560},
            intraline_status: 'OK',
            change_type: 'DELETED',
            diff_header: [
              'diff --git a/carrot.jpg b/carrot.jpg',
              'index f9c2f2c..0000000 100644',
              '--- a/carrot.jpg',
              '+++ /dev/null',
              'Binary files differ',
            ],
            content: [{skip: 66}],
            binary: true,
          };
          sandbox.stub(element.$.restAPI, 'getDiff')
              .returns(Promise.resolve(mockDiff));

          element.addEventListener('render', () => {
            // Recognizes that it should be an image diff.
            assert.isTrue(element.isImageDiff);
            assert.instanceOf(
                element.$.diff.$.diffBuilder._builder, GrDiffBuilderImage);

            const leftImage =
                element.$.diff.$.diffTable.querySelector('td.left img');
            const rightImage =
                element.$.diff.$.diffTable.querySelector('td.right img');

            assert.isOk(leftImage);
            assert.isNotOk(rightImage);
            done();
          });

          element.$.restAPI.getDiffPreferences().then(prefs => {
            element.prefs = prefs;
            element.reload();
          });
        });

        test('does not render disallowed image type', done => {
          const mockDiff = {
            meta_a: {name: 'carrot.jpg', content_type: 'image/jpeg-evil',
              lines: 560},
            intraline_status: 'OK',
            change_type: 'DELETED',
            diff_header: [
              'diff --git a/carrot.jpg b/carrot.jpg',
              'index f9c2f2c..0000000 100644',
              '--- a/carrot.jpg',
              '+++ /dev/null',
              'Binary files differ',
            ],
            content: [{skip: 66}],
            binary: true,
          };
          mockFile1.type = 'image/jpeg-evil';

          sandbox.stub(element.$.restAPI, 'getDiff')
              .returns(Promise.resolve(mockDiff));

          element.addEventListener('render', () => {
            // Recognizes that it should be an image diff.
            assert.isTrue(element.isImageDiff);
            assert.instanceOf(
                element.$.diff.$.diffBuilder._builder, GrDiffBuilderImage);
            const leftImage =
                element.$.diff.$.diffTable.querySelector('td.left img');
            assert.isNotOk(leftImage);
            done();
          });

          element.$.restAPI.getDiffPreferences().then(prefs => {
            element.prefs = prefs;
            element.reload();
          });
        });
      });
    });

    test('delegates cancel()', () => {
      const stub = sandbox.stub(element.$.diff, 'cancel');
      element.reload();
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('delegates getCursorStops()', () => {
      const returnValue = [document.createElement('b')];
      const stub = sandbox.stub(element.$.diff, 'getCursorStops')
          .returns(returnValue);
      assert.equal(element.getCursorStops(), returnValue);
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('delegates isRangeSelected()', () => {
      const returnValue = true;
      const stub = sandbox.stub(element.$.diff, 'isRangeSelected')
          .returns(returnValue);
      assert.equal(element.isRangeSelected(), returnValue);
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('delegates toggleLeftDiff()', () => {
      const stub = sandbox.stub(element.$.diff, 'toggleLeftDiff');
      element.toggleLeftDiff();
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    suite('blame', () => {
      setup(() => {
        element = fixture('basic');
      });

      test('clearBlame', () => {
        element._blame = [];
        const setBlameSpy = sandbox.spy(element.$.diff.$.diffBuilder, 'setBlame');
        element.clearBlame();
        assert.isNull(element._blame);
        assert.isTrue(setBlameSpy.calledWithExactly(null));
        assert.equal(element.isBlameLoaded, false);
      });

      test('loadBlame', () => {
        const mockBlame = [{id: 'commit id', ranges: [{start: 1, end: 2}]}];
        const showAlertStub = sinon.stub();
        element.addEventListener('show-alert', showAlertStub);
        const getBlameStub = sandbox.stub(element.$.restAPI, 'getBlame')
            .returns(Promise.resolve(mockBlame));
        element.changeNum = 42;
        element.patchRange = {patchNum: 5, basePatchNum: 4};
        element.path = 'foo/bar.baz';
        return element.loadBlame().then(() => {
          assert.isTrue(getBlameStub.calledWithExactly(
              42, 5, 'foo/bar.baz', true));
          assert.isFalse(showAlertStub.called);
          assert.equal(element._blame, mockBlame);
          assert.equal(element.isBlameLoaded, true);
        });
      });

      test('loadBlame empty', () => {
        const mockBlame = [];
        const showAlertStub = sinon.stub();
        element.addEventListener('show-alert', showAlertStub);
        sandbox.stub(element.$.restAPI, 'getBlame')
            .returns(Promise.resolve(mockBlame));
        element.changeNum = 42;
        element.patchRange = {patchNum: 5, basePatchNum: 4};
        element.path = 'foo/bar.baz';
        return element.loadBlame()
            .then(() => {
              assert.isTrue(false, 'Promise should not resolve');
            })
            .catch(() => {
              assert.isTrue(showAlertStub.calledOnce);
              assert.isNull(element._blame);
              assert.equal(element.isBlameLoaded, false);
            });
      });
    });

    test('delegates getThreadEls()', () => {
      const returnValue = [document.createElement('b')];
      const stub = sandbox.stub(element.$.diff, 'getThreadEls')
          .returns(returnValue);
      assert.equal(element.getThreadEls(), returnValue);
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('delegates addDraftAtLine(el)', () => {
      const param0 = document.createElement('b');
      const stub = sandbox.stub(element.$.diff, 'addDraftAtLine');
      element.addDraftAtLine(param0);
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 1);
      assert.equal(stub.lastCall.args[0], param0);
    });

    test('delegates clearDiffContent()', () => {
      const stub = sandbox.stub(element.$.diff, 'clearDiffContent');
      element.clearDiffContent();
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('delegates expandAllContext()', () => {
      const stub = sandbox.stub(element.$.diff, 'expandAllContext');
      element.expandAllContext();
      assert.isTrue(stub.calledOnce);
      assert.equal(stub.lastCall.args.length, 0);
    });

    test('passes in changeNum', () => {
      const value = '12345';
      element.changeNum = value;
      assert.equal(element.$.diff.changeNum, value);
    });

    test('passes in noAutoRender', () => {
      const value = true;
      element.noAutoRender = value;
      assert.equal(element.$.diff.noAutoRender, value);
    });

    test('passes in patchRange', () => {
      const value = {patchNum: 'foo', basePatchNum: 'bar'};
      element.patchRange = value;
      assert.equal(element.$.diff.patchRange, value);
    });

    test('passes in path', () => {
      const value = 'some/file/path';
      element.path = value;
      assert.equal(element.$.diff.path, value);
    });

    test('passes in prefs', () => {
      const value = {};
      element.prefs = value;
      assert.equal(element.$.diff.prefs, value);
    });

    test('passes in projectConfig', () => {
      const value = {};
      element.projectConfig = value;
      assert.equal(element.$.diff.projectConfig, value);
    });

    test('passes in changeNum', () => {
      const value = '12345';
      element.changeNum = value;
      assert.equal(element.$.diff.changeNum, value);
    });

    test('passes in projectName', () => {
      const value = 'Gerrit';
      element.projectName = value;
      assert.equal(element.$.diff.projectName, value);
    });

    test('passes in displayLine', () => {
      const value = true;
      element.displayLine = value;
      assert.equal(element.$.diff.displayLine, value);
    });

    test('passes in commitRange', () => {
      const value = {};
      element.commitRange = value;
      assert.equal(element.$.diff.commitRange, value);
    });

    test('passes in hidden', () => {
      const value = true;
      element.hidden = value;
      assert.equal(element.$.diff.hidden, value);
      assert.isNotNull(element.getAttribute('hidden'));
    });

    test('passes in noRenderOnPrefsChange', () => {
      const value = true;
      element.noRenderOnPrefsChange = value;
      assert.equal(element.$.diff.noRenderOnPrefsChange, value);
    });

    test('passes in comments', () => {
      const value = {left: [], right: []};
      element.comments = value;
      assert.equal(element.$.diff.comments, value);
    });

    test('passes in lineWrapping', () => {
      const value = true;
      element.lineWrapping = value;
      assert.equal(element.$.diff.lineWrapping, value);
    });

    test('passes in viewMode', () => {
      const value = 'SIDE_BY_SIDE';
      element.viewMode = value;
      assert.equal(element.$.diff.viewMode, value);
    });

    test('passes in lineOfInterest', () => {
      const value = {number: 123, leftSide: true};
      element.lineOfInterest = value;
      assert.equal(element.$.diff.lineOfInterest, value);
    });

    suite('_reportDiff', () => {
      let reportStub;

      setup(() => {
        element = fixture('basic');
        element.patchRange = {basePatchNum: 1};
        reportStub = sandbox.stub(element.$.reporting, 'reportInteraction');
      });

      test('null and content-less', () => {
        element._reportDiff(null);
        assert.isFalse(reportStub.called);

        element._reportDiff({});
        assert.isFalse(reportStub.called);
      });

      test('diff w/ no delta', () => {
        const diff = {
          content: [
            {ab: ['foo', 'bar']},
            {ab: ['baz', 'foo']},
          ],
        };
        element._reportDiff(diff);
        assert.isTrue(reportStub.calledOnce);
        assert.equal(reportStub.lastCall.args[0], 'rebase-percent-zero');
        assert.isUndefined(reportStub.lastCall.args[1]);
      });

      test('diff w/ no rebase delta', () => {
        const diff = {
          content: [
            {ab: ['foo', 'bar']},
            {a: ['baz', 'foo']},
            {ab: ['foo', 'bar']},
            {a: ['baz', 'foo'], b: ['bar', 'baz']},
            {ab: ['foo', 'bar']},
            {b: ['baz', 'foo']},
            {ab: ['foo', 'bar']},
          ],
        };
        element._reportDiff(diff);
        assert.isTrue(reportStub.calledOnce);
        assert.equal(reportStub.lastCall.args[0], 'rebase-percent-zero');
        assert.isUndefined(reportStub.lastCall.args[1]);
      });

      test('diff w/ some rebase delta', () => {
        const diff = {
          content: [
            {ab: ['foo', 'bar']},
            {a: ['baz', 'foo'], due_to_rebase: true},
            {ab: ['foo', 'bar']},
            {a: ['baz', 'foo'], b: ['bar', 'baz']},
            {ab: ['foo', 'bar']},
            {b: ['baz', 'foo'], due_to_rebase: true},
            {ab: ['foo', 'bar']},
            {a: ['baz', 'foo']},
          ],
        };
        element._reportDiff(diff);
        assert.isTrue(reportStub.calledOnce);
        assert.equal(reportStub.lastCall.args[0], 'rebase-percent-nonzero');
        assert.strictEqual(reportStub.lastCall.args[1], 50);
      });

      test('diff w/ all rebase delta', () => {
        const diff = {content: [{
          a: ['foo', 'bar'],
          b: ['baz', 'foo'],
          due_to_rebase: true,
        }]};
        element._reportDiff(diff);
        assert.isTrue(reportStub.calledOnce);
        assert.equal(reportStub.lastCall.args[0], 'rebase-percent-nonzero');
        assert.strictEqual(reportStub.lastCall.args[1], 100);
      });

      test('diff against parent event', () => {
        element.patchRange.basePatchNum = 'PARENT';
        const diff = {content: [{
          a: ['foo', 'bar'],
          b: ['baz', 'foo'],
        }]};
        element._reportDiff(diff);
        assert.isTrue(reportStub.calledOnce);
        assert.equal(reportStub.lastCall.args[0], 'diff-against-parent');
        assert.isUndefined(reportStub.lastCall.args[1]);
      });
    });

    suite('_translateChunksToIgnore', () => {
      let content;

      setup(() => {
        content = [
          {ab: ['one', 'two']},
          {a: ['three'], b: ['different three']},
          {b: ['four']},
          {ab: ['five', 'six']},
          {a: ['seven']},
          {ab: ['eight', 'nine']},
        ];
      });

      test('does nothing to unmarked diff', () => {
        assert.deepEqual(element._translateChunksToIgnore({content}),
            {content});
      });

      test('merges marked delta chunk', () => {
        content[1].common = true;
        assert.deepEqual(element._translateChunksToIgnore({content}), {
          content: [
            {ab: ['one', 'two', 'different three']},
            {b: ['four']},
            {ab: ['five', 'six']},
            {a: ['seven']},
            {ab: ['eight', 'nine']},
          ],
        });
      });

      test('merges marked addition chunk', () => {
        content[2].common = true;
        assert.deepEqual(element._translateChunksToIgnore({content}), {
          content: [
            {ab: ['one', 'two']},
            {a: ['three'], b: ['different three']},
            {ab: ['four', 'five', 'six']},
            {a: ['seven']},
            {ab: ['eight', 'nine']},
          ],
        });
      });

      test('merges multiple marked delta', () => {
        content[1].common = true;
        content[2].common = true;
        assert.deepEqual(element._translateChunksToIgnore({content}), {
          content: [
            {ab: ['one', 'two', 'different three', 'four', 'five', 'six']},
            {a: ['seven']},
            {ab: ['eight', 'nine']},
          ],
        });
      });

      test('marked deletion chunks are omitted', () => {
        content[4].common = true;
        assert.deepEqual(element._translateChunksToIgnore({content}), {
          content: [
            {ab: ['one', 'two']},
            {a: ['three'], b: ['different three']},
            {b: ['four']},
            {ab: ['five', 'six', 'eight', 'nine']},
          ],
        });
      });

      test('marked deltas can start shared chunks', () => {
        content[0] = {a: ['one'], b: ['two'], common: true};
        assert.deepEqual(element._translateChunksToIgnore({content}), {
          content: [
            {ab: ['two']},
            {a: ['three'], b: ['different three']},
            {b: ['four']},
            {ab: ['five', 'six']},
            {a: ['seven']},
            {ab: ['eight', 'nine']},
          ],
        });
      });
    });
  });
</script>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.igniterealtime.spark.plugins</groupId>
        <artifactId>plugin</artifactId>
        <version>3.0.1-SNAPSHOT</version>
        <relativePath>../plugin/pom.xml</relativePath>
    </parent>

    <artifactId>fastpath</artifactId>
    <version>3.5.1</version>

    <name>Fastpath</name>
    <description>Provides FastPath Agent functionality.</description>

    <contributors>
        <contributor>
            <organization>Jive Software</organization>
            <email>spark@jivesoftware.com</email>
            <roles>
                <role>Author</role>
            </roles>
        </contributor>
    </contributors>
</project>

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jdbi.v3.core.statement;

import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Optional;

import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.argument.Argument;
import org.jdbi.v3.core.argument.ArgumentFactory;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.rule.DatabaseRule;
import org.jdbi.v3.core.rule.SqliteDatabaseRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class TestSqlLoggerToString {
    private static final String INSERT_POSITIONAL = "insert into foo(bar) values(?)";
    private static final String INSERT_NAMED = "insert into foo(bar) values(:x)";
    private static final String NAME = "x";

    @Rule
    public DatabaseRule db = new SqliteDatabaseRule();

    private Handle handle;
    private String positional = null;
    private String named = null;

    @Before
    public void before() {
        handle = db.getJdbi().open();

        handle.execute("create table foo(bar binary)");

        handle.setSqlLogger(new SqlLogger() {
            @Override
            public void logBeforeExecution(StatementContext context) {
                context.getBinding().findForPosition(0).ifPresent(value -> positional = Objects.toString(value));
                context.getBinding().findForName(NAME, context).ifPresent(value -> named = Objects.toString(value));
            }
        });
    }

    // basic types

    @Test
    public void testInt() {
        handle.createUpdate(INSERT_POSITIONAL).bind(0, 1).execute();

        assertThat(positional).isEqualTo("1");
    }

    @Test
    public void testString() {
        handle.createUpdate(INSERT_POSITIONAL).bind(0, "herp").execute();

        assertThat(positional).isEqualTo("herp");
    }

    @Test
    public void testBean() {
        handle.createUpdate(INSERT_NAMED).bindBean(new StringBean("herp")).execute();

        assertThat(named).isEqualTo("herp");
    }

    // Arguments

    @Test
    public void testArgumentWithoutToString() {
        handle.createUpdate(INSERT_POSITIONAL).bind(0, (position, statement, ctx) -> statement.setString(1, "derp")).execute();

        assertThat(positional).isNotEqualTo("derp");
    }

    @Test
    public void testArgumentWithToString() {
        handle.createUpdate(INSERT_POSITIONAL).bind(0, new Argument() {
            @Override
            public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
                statement.setString(1, "derp");
            }

            @Override
            public String toString() {
                return "toString for derp";
            }
        }).execute();

        assertThat(positional).isEqualTo("toString for derp");
    }

    // factories

    @Test
    public void testNeitherHasToString() {
        handle.registerArgument(new FooArgumentFactory());

        handle.createUpdate(INSERT_POSITIONAL).bind(0, new Foo()).execute();

        assertThat(positional).containsPattern("@[0-9a-f]{1,8}$");
    }

    @Test
    public void testObjectHasToString() {
        handle.registerArgument(new FooArgumentFactory());

        handle.createUpdate(INSERT_POSITIONAL).bind(0, new ToStringFoo()).execute();

        assertThat(positional).isEqualTo("I'm a Foo");
    }

    @Test
    public void testArgumentHasToString() {
        handle.registerArgument(new ToStringFooArgumentFactory());

        handle.createUpdate(INSERT_POSITIONAL).bind(0, new Foo()).execute();

        assertThat(positional).isEqualTo("this is a Foo");
    }

    @Test
    public void testBothHaveToStringAndArgumentWins() {
        handle.registerArgument(new ToStringFooArgumentFactory());

        handle.createUpdate(INSERT_POSITIONAL).bind(0, new ToStringFoo()).execute();

        assertThat(positional).isEqualTo("this is a Foo");
    }

    public static class StringBean {
        private final String x;

        private StringBean(String x) {
            this.x = x;
        }

        public String getX() {
            return x;
        }
    }

    private static class Foo {}

    private static class ToStringFoo extends Foo {
        @Override
        public String toString() {
            return "I'm a Foo";
        }
    }

    private static class FooArgumentFactory implements ArgumentFactory {
        @Override
        public Optional<Argument> build(Type type, Object value, ConfigRegistry config) {
            if (value instanceof Foo) {
                return Optional.of((position, statement, ctx) -> statement.setObject(1, value));
            } else {
                return Optional.empty();
            }
        }
    }

    private static class ToStringFooArgumentFactory implements ArgumentFactory {
        @Override
        public Optional<Argument> build(Type type, Object value, ConfigRegistry config) {
            if (value instanceof Foo) {
                return Optional.of(new Argument() {
                    @Override
                    public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
                        statement.setObject(1, value);
                    }

                    @Override
                    public String toString() {
                        return "this is a Foo";
                    }
                });
            } else {
                return Optional.empty();
            }
        }
    }
}


text:
package org.gdg.frisbee.android;

import android.text.format.DateUtils;

import org.joda.time.DateTime;

/**
 * Created with IntelliJ IDEA.
 * User: maui
 * Date: 20.04.13
 * Time: 12:19
 */
public class Const {

    private Const() {
    }

    //GitHub
    public static final String GITHUB_ORGA = "gdg-x";
    public static final String GITHUB_REPO = "frisbee";

    //Special Events
    public static final String EXTRA_TAGGED_EVENT = "org.gdg.frisbee.TAGGED_EVENT";
    public static final String EXTRA_TAGGED_EVENT_CACHEKEY = "org.gdg.frisbee.TAGGED_EVENT_CACHEKEY";
    //Special Events Dates
    public static final DateTime START_TIME_DEVFEST =       new DateTime(2015, 9, 1, 0, 0);
    public static final DateTime START_TIME_WTM =           new DateTime(2015, 2, 1, 0, 0);
    public static final DateTime START_TIME_STUDY_JAMS =    new DateTime(2015, 2, 1, 0, 0);
    public static final DateTime START_TIME_IOEXTENDED =    new DateTime(2015, 5, 1, 0, 0);

    public static final DateTime END_TIME_DEVFEST =      new DateTime(2016, 1, 1, 0, 0);
    public static final DateTime END_TIME_WTM =             new DateTime(2015, 4, 1, 0, 0);
    public static final DateTime END_TIME_STUDY_JAMS =      new DateTime(2015, 5, 1, 0, 0);
    public static final DateTime END_TIME_IOEXTENDED =      new DateTime(2015, 6, 1, 0, 0);

    public static final String EXTRA_PLUS_ID = "plus_id";

    //Navigation Drawer
    public static final int DRAWER_HOME = 0;
    public static final int DRAWER_PULSE = 2;
    public static final int DRAWER_ACHIEVEMENTS = 4;
    public static final int DRAWER_GDE = 5;
    public static final int DRAWER_ARROW = 99;
    public static final int DRAWER_SETTINGS = 100;
    public static final int DRAWER_HELP = 101;
    public static final int DRAWER_FEEDBACK = 102;
    public static final int DRAWER_ABOUT = 103;
    public static final int DRAWER_SUBMENU_GAMES = 1000;

    // Drawer Special Event Items
    public static final int DRAWER_DEVFEST = 30;
    public static final int DRAWER_WTM = 31;
    public static final int DRAWER_STUDY_JAM = 32;
    public static final int DRAWER_IO_EXTENDED = 33;

    //Arrow
    public static final String QR_MSG_PREFIX = "gdgx://arrow?m=";
    public static final String PREF_ORGANIZER_CHECK_TIME = "pref_organizer_check_time";
    public static final String PREF_ORGANIZER_CHECK_ID = "pref_organizer_check_id";
    public static final String PREF_ORGANIZER_STATE = "pref_organizer_state";
    public static final long ORGANIZER_CHECK_MAX_TIME = DateUtils.WEEK_IN_MILLIS;
    public static final String ARROW_MIME = "application/vnd.org.gdgx.frisbee.arrow";
    public static final String ARROW_LB = "CgkIh5yNxL8MEAIQBw";
    public static final String ARROW_K = "XXXX111122223333";
    public static final int ARROW_STATE_KEY = 1;

    public static final int ARROW_DONE_STATE_KEY = 2;

    public static final String EXTRA_EVENT_ID = "EXTRA_EVENT_ID";
    public static final String EXTRA_SECTION = "EXTRA_SECTION";
    public static final String URL_DEVELOPERS_GOOGLE_COM = "https://developers.google.com";
    public static final String URL_HELP = "https://support.google.com/developergroups";
    public static final String URL_GDG_RESOURCE_FOLDER = "https://drive.google.com/drive/#folders/0B55wxScz_BJtWW9aUnk2LUlNdEk";
    public static final String URL_GDG_WISDOM_BOOK = "http://gdg-wisdom.gitbooks.io/gdg-wisdom-2015/content/";
    public static final String URL_GDG_LEADS_GPLUS_COMMUNITY = "https://plus.google.com/communities/101119632372181012379";

    //Keys
    public static final String EXTRA_CHAPTER_ID = "org.gdg.frisbee.CHAPTER";
    public static final String CACHE_KEY_CHAPTER_LIST_HUB = "chapter_list_hub";
    public static final String CACHE_KEY_PULSE_GLOBAL = "pulse_global";
    public static final String CACHE_KEY_GDE_LIST = "gde_list";
    public static final String CACHE_KEY_FRISBEE_CONTRIBUTORS = "frisbee_contributor_list";
    public static final String CACHE_KEY_PERSON = "person_";
    public static final String CACHE_KEY_NEWS = "news_";
    public static final String CACHE_KEY_PULSE = "pulse_";

    public static final String GOOGLE_DEVELOPERS_YT_ID = "UC_x5XG1OV2P6uZZ5FSM9Ttw";
    public static final String ANDROID_DEVELOPERS_YT_ID = "UCVHFbqXqoYvEWM1Ddxl0QDg";
    public static final String YOUTUBE_DEVELOPERS_YT_ID = "UCtVd0c0tGXuTSbU5d8cSBUg";

    public static final String TRUSTSTORE_PW = "VU%&ibkr45pnq39v53x";
}


text:
package com.twitter.scalding

import cascading.tuple.{Tuple => CTuple}

/** Typeclass roughly equivalent to a Lens, which allows getting items out of a tuple.
 * This is useful because cascading has type coercion (string to int, for instance) that
 * users expect in the fields API.  This code is not used in the typesafe API, which
 * does not allow suc silent coercion.
 * See the generated TupleConverters for an example of where this is used
 */
trait TupleGetter[@specialized(Int,Long,Float,Double)T] extends java.io.Serializable {
  def get(tup: CTuple, i: Int): T
}

trait LowPriorityTupleGetter extends java.io.Serializable {
  implicit def castingGetter[T]: TupleGetter[T] = new TupleGetter[T] {
    def get(tup: CTuple, i: Int) = tup.getObject(i).asInstanceOf[T]
  }
}

object TupleGetter extends LowPriorityTupleGetter {

  def get[T](tup: CTuple, i: Int)(implicit tg: TupleGetter[T]): T = tg.get(tup, i)
  def of[T](implicit tg: TupleGetter[T]): TupleGetter[T] = tg

  implicit object UnitGetter extends TupleGetter[Unit] {
    override def get(tup : CTuple, i : Int) = ()
  }

  implicit object BooleanGetter extends TupleGetter[Boolean] {
    override def get(tup : CTuple, i : Int) = tup.getBoolean(i)
  }

  implicit object ShortGetter extends TupleGetter[Short] {
    override def get(tup : CTuple, i : Int) = tup.getShort(i)
  }

  implicit object IntGetter extends TupleGetter[Int] {
    override def get(tup : CTuple, i : Int) = tup.getInteger(i)
  }

  implicit object LongGetter extends TupleGetter[Long] {
    override def get(tup : CTuple, i : Int) = tup.getLong(i)
  }

  implicit object FloatGetter extends TupleGetter[Float] {
    override def get(tup : CTuple, i : Int) = tup.getFloat(i)
  }

  implicit object DoubleGetter extends TupleGetter[Double] {
    override def get(tup : CTuple, i : Int) = tup.getDouble(i)
  }

  implicit object StringGetter extends TupleGetter[String] {
    override def get(tup : CTuple, i : Int) = tup.getString(i)
  }
}


text:
<?php

/* TallerGageBundle:Alumno:new.html.twig */
class __TwigTemplate_d66eaf02fcf4d47a470fc137e796df310ab6f56aea8b1549b034fb18765b2cc8 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
Alumno creation

    ";
        // line 6
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form');
        echo "

        env->getExtension('routing')->getPath("alumno");
        echo "\">
            Back to the list

";
    }

    public function getTemplateName()
    {
        return "TallerGageBundle:Alumno:new.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  42 => 10,  35 => 6,  31 => 4,  28 => 3,);
    }
}


text:
var del = require('del');
var projectConfig = require('../project.config');

var paths = del.sync([
    'coverage',
    projectConfig.srcDir +'/**/*.css',
    '!'+ projectConfig.srcClientDir +'/assets/fonts/**/*.css',
    projectConfig.srcDir +'/**/*.js',
    '!'+ projectConfig.srcDir +'/**/libs/**/*',
    projectConfig.srcDir +'/**/*.map',
    projectConfig.testDir+"/**/*.js",
    projectConfig.testDir +'/**/*.map',
    projectConfig.distDir,'temp',"reporters"]);

console.log('Deleted files/folders:\n', paths.join('\n'));


text:
from django import template

register = template.Library()

@register.simple_tag
def next_in_gallery(photo, gallery):
    next = photo.get_next_in_gallery(gallery)
    if next:
        return '' % (next.title, next.get_absolute_url(), next.thumbnail.url)
    return ""

@register.simple_tag
def previous_in_gallery(photo, gallery):
    prev = photo.get_previous_in_gallery(gallery)
    if prev:
        return '' % (prev.title, prev.get_absolute_url(), prev.thumbnail.url)
    return ""


text:
package org.apache.hadoop.mapreduce.task.reduce;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.IOUtils;

import org.apache.hadoop.mapred.IFileInputStream;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.MapOutputFile;

import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.CryptoUtils;
import org.apache.hadoop.mapreduce.task.reduce.MergeManagerImpl.CompressAwarePath;

import com.google.common.annotations.VisibleForTesting;

@InterfaceAudience.Private
@InterfaceStability.Unstable
class OnDiskMapOutput<K, V> extends IFileWrappedMapOutput<K, V> {
  private static final Logger LOG =
      LoggerFactory.getLogger(OnDiskMapOutput.class);
  private final FileSystem fs;
  private final Path tmpOutputPath;
  private final Path outputPath;
  private final OutputStream disk;
  private long compressedSize;

  @Deprecated
  public OnDiskMapOutput(TaskAttemptID mapId, TaskAttemptID reduceId,
                         MergeManagerImpl<K,V> merger, long size,
                         JobConf conf,
                         MapOutputFile mapOutputFile,
                         int fetcher, boolean primaryMapOutput)
      throws IOException {
    this(mapId, merger, size, conf, fetcher,
        primaryMapOutput, FileSystem.getLocal(conf).getRaw(),
        mapOutputFile.getInputFileForWrite(mapId.getTaskID(), size));
  }

  @Deprecated
  OnDiskMapOutput(TaskAttemptID mapId, TaskAttemptID reduceId,
                         MergeManagerImpl<K,V> merger, long size,
                         JobConf conf,
                         MapOutputFile mapOutputFile,
                         int fetcher, boolean primaryMapOutput,
                         FileSystem fs, Path outputPath) throws IOException {
    this(mapId, merger, size, conf, fetcher, primaryMapOutput, fs, outputPath);
  }

  OnDiskMapOutput(TaskAttemptID mapId,
                  MergeManagerImpl<K, V> merger, long size,
                  JobConf conf,
                  int fetcher, boolean primaryMapOutput,
                  FileSystem fs, Path outputPath) throws IOException {
    super(conf, merger, mapId, size, primaryMapOutput);
    this.fs = fs;
    this.outputPath = outputPath;
    tmpOutputPath = getTempPath(outputPath, fetcher);
    disk = CryptoUtils.wrapIfNecessary(conf, fs.create(tmpOutputPath));
  }

  @VisibleForTesting
  static Path getTempPath(Path outPath, int fetcher) {
    return outPath.suffix(String.valueOf(fetcher));
  }

  @Override
  protected void doShuffle(MapHost host, IFileInputStream input,
                      long compressedLength, long decompressedLength,
                      ShuffleClientMetrics metrics,
                      Reporter reporter) throws IOException {
    // Copy data to local-disk
    long bytesLeft = compressedLength;
    try {
      final int BYTES_TO_READ = 64 * 1024;
      byte[] buf = new byte[BYTES_TO_READ];
      while (bytesLeft > 0) {
        int n = input.readWithChecksum(buf, 0,
                                      (int) Math.min(bytesLeft, BYTES_TO_READ));
        if (n < 0) {
          throw new IOException("read past end of stream reading " +
                                getMapId());
        }
        disk.write(buf, 0, n);
        bytesLeft -= n;
        metrics.inputBytes(n);
        reporter.progress();
      }

      LOG.info("Read " + (compressedLength - bytesLeft) +
               " bytes from map-output for " + getMapId());

      disk.close();
    } catch (IOException ioe) {
      // Close the streams
      IOUtils.cleanupWithLogger(LOG, disk);

      // Re-throw
      throw ioe;
    }

    // Sanity check
    if (bytesLeft != 0) {
      throw new IOException("Incomplete map output received for " +
                            getMapId() + " from " +
                            host.getHostName() + " (" +
                            bytesLeft + " bytes missing of " +
                            compressedLength + ")");
    }
    this.compressedSize = compressedLength;
  }

  @Override
  public void commit() throws IOException {
    fs.rename(tmpOutputPath, outputPath);
    CompressAwarePath compressAwarePath = new CompressAwarePath(outputPath,
        getSize(), this.compressedSize);
    getMerger().closeOnDiskFile(compressAwarePath);
  }

  @Override
  public void abort() {
    try {
      fs.delete(tmpOutputPath, false);
    } catch (IOException ie) {
      LOG.info("failure to clean up " + tmpOutputPath, ie);
    }
  }

  @Override
  public String getDescription() {
    return "DISK";
  }

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataGridControlFactory.cs" company="PropertyTools">
//   Copyright (c) 2014 PropertyTools contributors
// </copyright>
// <summary>
//   Creates display and edit controls for the DataGrid.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace PropertyTools.Wpf
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Data;
    using System.Windows.Media;
    using System.Windows.Shapes;

    /// <summary>
    /// Creates display and edit controls for the DataGrid.
    /// </summary>
    public class DataGridControlFactory : IDataGridControlFactory
    {
        /// <summary>
        /// Creates the display control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// The control.
        /// </returns>
        public virtual FrameworkElement CreateDisplayControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var propertyType = propertyDefinition.PropertyType;
            if (propertyType.Is(typeof(bool)))
            {
                return this.CreateCheckBoxControl(propertyDefinition, bindingPath);
            }

            if (propertyType.Is(typeof(Color)))
            {
                return this.CreateColorPreviewControl(propertyDefinition, bindingPath);
            }

            return this.CreateTextBlockControl(propertyDefinition, bindingPath);
        }

        /// <summary>
        /// Creates the edit control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// The control.
        /// </returns>
        public virtual FrameworkElement CreateEditControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var propertyType = propertyDefinition.PropertyType;
            if (propertyDefinition.ItemsSourceProperty != null || propertyDefinition.ItemsSource != null)
            {
                return this.CreateComboBox(propertyDefinition, bindingPath);
            }

            if (propertyType == typeof(bool))
            {
                return null;
            }

            if (propertyType != null && propertyType.Is(typeof(Color)))
            {
                return this.CreateColorPickerControl(propertyDefinition, bindingPath);
            }

            return this.CreateTextBox(propertyDefinition, bindingPath);
        }

        /// <summary>
        /// Creates a check box control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// A CheckBox.
        /// </returns>
        protected virtual FrameworkElement CreateCheckBoxControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            if (propertyDefinition.IsReadOnly)
            {
                var cm = new CheckMark
                             {
                                 VerticalAlignment = VerticalAlignment.Center,
                                 HorizontalAlignment = propertyDefinition.HorizontalAlignment
                             };
                cm.SetBinding(CheckMark.IsCheckedProperty, propertyDefinition.CreateBinding(bindingPath));
                return cm;
            }

            var c = new CheckBox
                        {
                            VerticalAlignment = VerticalAlignment.Center,
                            HorizontalAlignment = propertyDefinition.HorizontalAlignment,
                            IsEnabled = !propertyDefinition.IsReadOnly
                        };
            c.SetBinding(ToggleButton.IsCheckedProperty, propertyDefinition.CreateBinding(bindingPath));
            return c;
        }

        /// <summary>
        /// Creates a color picker control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// A color picker.
        /// </returns>
        protected virtual FrameworkElement CreateColorPickerControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var c = new ColorPicker
                {
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    Focusable = false
                };
            c.SetBinding(ColorPicker.SelectedColorProperty, propertyDefinition.CreateBinding(bindingPath));
            return c;
        }

        /// <summary>
        /// Creates a color preview control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// A preview control.
        /// </returns>
        protected virtual FrameworkElement CreateColorPreviewControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var c = new Rectangle
                        {
                            Stroke = Brushes.Black,
                            StrokeThickness = 1,
                            Width = 12,
                            Height = 12,
                            VerticalAlignment = VerticalAlignment.Center,
                            HorizontalAlignment = HorizontalAlignment.Center
                        };

            var binding = propertyDefinition.CreateBinding(bindingPath);
            binding.Converter = new ColorToBrushConverter();
            c.SetBinding(Shape.FillProperty, binding);
            return c;
        }

        /// <summary>
        /// Creates a combo box with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// A ComboBox.
        /// </returns>
        protected virtual FrameworkElement CreateComboBox(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var c = new ComboBox { IsEditable = propertyDefinition.IsEditable, Focusable = false, Margin = new Thickness(0, 0, -1, -1) };
            if (propertyDefinition.ItemsSource != null)
            {
                c.ItemsSource = propertyDefinition.ItemsSource;
            }
            else
            {
                if (propertyDefinition.ItemsSourceProperty != null)
                {
                    var itemsSourceBinding = new Binding(propertyDefinition.ItemsSourceProperty);
                    c.SetBinding(ItemsControl.ItemsSourceProperty, itemsSourceBinding);
                }
            }

            c.DropDownClosed += (s, e) => FocusParentDataGrid(c);
            var binding = propertyDefinition.CreateBinding(bindingPath);
            binding.NotifyOnSourceUpdated = true;
            c.SetBinding(propertyDefinition.IsEditable ? ComboBox.TextProperty : Selector.SelectedValueProperty, binding);

            return c;
        }

        /// <summary>
        /// Creates a text block control with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>
        /// A TextBlock.
        /// </returns>
        protected virtual FrameworkElement CreateTextBlockControl(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var tb = new TextBlock
            {
                HorizontalAlignment = propertyDefinition.HorizontalAlignment,
                VerticalAlignment = VerticalAlignment.Center,
                Padding = new Thickness(4, 0, 4, 0)
            };

            tb.SetBinding(TextBlock.TextProperty, propertyDefinition.CreateOneWayBinding(bindingPath));
            return tb;
        }

        /// <summary>
        /// Creates a text box with data binding.
        /// </summary>
        /// <param name="propertyDefinition">The property definition.</param>
        /// <param name="bindingPath">The binding path.</param>
        /// <returns>A TextBox.</returns>
        protected virtual FrameworkElement CreateTextBox(PropertyDefinition propertyDefinition, string bindingPath)
        {
            var tb = new TextBox
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                HorizontalContentAlignment = propertyDefinition.HorizontalAlignment,
                MaxLength = propertyDefinition.MaxLength,
                BorderThickness = new Thickness(0),
                Margin = new Thickness(1, 1, 0, 0)
            };

            tb.SetBinding(TextBox.TextProperty, propertyDefinition.CreateBinding(bindingPath));
            return tb;
        }

        /// <summary>
        /// Focuses on the parent data grid.
        /// </summary>
        /// <param name="obj">The <see cref="DependencyObject" />.</param>
        private static void FocusParentDataGrid(DependencyObject obj)
        {
            var parent = VisualTreeHelper.GetParent(obj);
            while (parent != null && !(parent is DataGrid))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }

            var u = parent as UIElement;
            if (u != null)
            {
                u.Focus();
            }
        }
    }
}


text:
package Lucy::Index::DocReader;
use Lucy;
our $VERSION = '0.004000';
$VERSION = eval $VERSION;

1;

__END__


text:
package com.lucafontanili.designpatterns.example.java.db.dto;

import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
@Table(name = "SESSION")
public class Session extends ADTO {

	private static final long serialVersionUID = -8682770625960628620L;

	@Column(name = DB_EMPLOYEEID)
	private UUID employeeId;
	@Column(name = DB_CREATIONDATE)
	private Date creationDate;
	@Column(name = DB_VALID)
	private Boolean valid;

	public static final String DB_EMPLOYEEID = "employeeId";
	public static final String DB_CREATIONDATE = "creationDate";
	public static final String DB_VALID = "valid";

	@JsonProperty(DB_EMPLOYEEID)
	public String getEmployeeId() {
		if (this.employeeId == null) {
			return null;
		}
		return this.employeeId.toString();
	}

	@JsonProperty(DB_EMPLOYEEID)
	public void setEmployeeId(String userId) {
		if (userId == null || userId.isEmpty()) {
			this.employeeId = null;
		} else {
			this.employeeId = UUID.fromString(userId);
		}
	}

	@JsonProperty(DB_CREATIONDATE)
	public Date getCreationDate() {
		return this.creationDate;
	}

	@JsonProperty(DB_CREATIONDATE)
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}

	@JsonProperty(DB_VALID)
	public Boolean getValid() {
		return this.valid;
	}

	@JsonProperty(DB_VALID)
	public void setValid(Boolean valid) {
		this.valid = valid;
	}

	public Session() {
		super();
		setEmployeeId("");
		setCreationDate(new Date());
		setValid(true);
	}
}


text:
using System.ServiceProcess;
using System.Threading;
using FFmpegFarm.Worker;

namespace FFmpegFarm.WindowsService
{
    public partial class Service : ServiceBase
    {
        private readonly CancellationTokenSource _cancellationTokenSource;
        private readonly ILogger _logger;
        private readonly FFmpegClient _client;

        public Service()
        {
            InitializeComponent();
            _logger = new EventLogger(eventLog);
            _cancellationTokenSource = new CancellationTokenSource();
            _client = new FFmpegClient(_logger, _cancellationTokenSource);
        }

        protected override void OnStart(string[] args)
        {
            _client.Start();
        }

        protected override void OnStop()
        {
            _client.Stop();
        }
    }
}


text:
package kushrestaurant.interfaces;

import java.util.ArrayList;

import kushrestaurant.CashierRole.Bill;

public interface Cashier {

	public abstract void msgProduceCheck(Customer c, String choice, Waiter w);
	public abstract void msgHereIsPayment(Customer c, double check, double cash);
	public abstract void msgHereIsBill(Market m, int bill);
	public abstract double getBill();
	public abstract double getMoney();
	public abstract ArrayList<Bill> getListOfBills();
}


text:
package org.nfunk.jep.function;

import java.util.*;
import org.nfunk.jep.*;
import org.nfunk.jep.type.*;

/**
 * Argument of a complex number
 * @author Rich Morris
 * Created on 20-Nov-2003
 */
public class Arg extends PostfixMathCommand
{
	private static final Double ONE = new Double(1.0);
	public Arg()
	{
		numberOfParameters = 1;
	}

	public void run(Stack inStack)
		throws ParseException
	{
		checkStack(inStack);// check the stack
		Object param = inStack.pop();
		inStack.push(arg(param));//push the result on the inStack
		return;
	}

	public Number arg(Object param) throws ParseException {
		if (param instanceof Complex) {
					return new Double(((Complex)param).arg());
				}
		else if (param instanceof Number) {
			return (ONE);
		}
		throw new ParseException("Invalid parameter type");
	}

}


text:
package com.weygo.weygophone.pages.classifyDetail.adapter;

import android.content.Context;
import android.graphics.Point;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.weygo.common.base.JHBaseViewHolder;
import com.weygo.common.base.JHLinearLayout;
import com.weygo.common.base.JHRecyclerViewAdapter;
import com.weygo.common.base.JHRelativeLayout;
import com.weygo.weygophone.R;
import com.weygo.weygophone.pages.classifyDetail.model.WGClassifyDetail;
import com.weygo.weygophone.pages.classifyDetail.model.WGHomeRotation;
import com.weygo.weygophone.pages.classifyDetail.widget.WGClassifyDetailFilterView;
import com.weygo.weygophone.pages.collection.widget.WGGoodListView;
import com.weygo.weygophone.pages.tabs.home.adapter.WGHomeFragmentAdapter;
import com.weygo.weygophone.pages.tabs.home.model.WGHomeFloorBaseContentItem;
import com.weygo.weygophone.pages.tabs.home.model.WGHomeFloorContentGoodItem;
import com.weygo.weygophone.pages.tabs.home.model.WGHomeFloorContentItem;
import com.weygo.weygophone.pages.tabs.home.widget.WGHomeContentFloorGoodsGridCellView;

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

/**
 * Created by muma on 2017/8/2.
 */

public class WGClassifyDetailContentAdapter extends JHRecyclerViewAdapter {

    public interface OnItemClickListener extends OnBaseItemClickListener {
        void onSort(View view);
        void onFilter(View view);
        void onGrid(View view);
        void onGoodItem(WGHomeFloorContentGoodItem item);
        void onShopCart(WGHomeFloorContentGoodItem item, View view, Point point);
    }

    public WGClassifyDetailContentAdapter(Context context, WGClassifyDetail data) {
        this.mContext = context;
        setData(data);
    }

    WGClassifyDetail mData;
    public void setData(WGClassifyDetail data) {
        mData = data;
        mPostionValueMap.clear();
        if (mData == null) {
            notifyDataSetChanged();
            return;
        }
        int key = 0;
        if (mData.hasCarousel()) {
            List list = new ArrayList();
            list.add(mData.carouselFigureItem.pictureURL);
            WGHomeRotation model = new WGHomeRotation();
            model.mList = list;
            model.time = mData.snappedUpExpiredTime;
            CellData cellData = new CellData(Item_Type.ITEM_TYPE_CarouselFigures,
                    model);
            mPostionValueMap.put(key, cellData);
            key++;
        }
        if (mData.hasRecommendedArray()) {
            for (WGHomeFloorContentGoodItem item : mData.recommendedArray) {
                CellData cellData = new CellData(Item_Type.ITEM_TYPE_GoodListItem,
                        item);
                mPostionValueMap.put(key, cellData);
                key++;
            }
        }
        CellData cellData = new CellData(Item_Type.ITEM_TYPE_GoodFilter,
                mData);
        mPostionValueMap.put(key, cellData);
        key++;
        if (mData.hasGoods()) {
            if (mData.isGrid()) {
                List<WGHomeFloorContentGoodItem> goodArray = mData.goodArray;
                int count = goodArray.size();
                for (int num = 0; num < Math.ceil(count/2.0); ++num) {
                    List list = new ArrayList();
                    WGHomeFloorContentGoodItem goodItem = null;
                    if (count > 2 * num) {
                        goodItem = goodArray.get(2 * num);
                        list.add(goodItem);
                    }
                    if (count > 2 * num + 1) {
                        goodItem = goodArray.get(2 * num + 1);
                        list.add(goodItem);
                    }
                    WGClassifyDetailContentAdapter.CellData value = new WGClassifyDetailContentAdapter.
                            CellData(Item_Type.ITEM_TYPE_GoodGridItem, list);
                    mPostionValueMap.put(key, value);
                    key++;
                }
            }
            else {
                for (WGHomeFloorContentGoodItem item : mData.goodArray) {
                    CellData cellData1 = new CellData(Item_Type.ITEM_TYPE_GoodListItem,
                            item);
                    mPostionValueMap.put(key, cellData1);
                    key++;
                }
            }
        }
        notifyDataSetChanged();
    }

    public enum Item_Type {
        ITEM_TYPE_None,
        ITEM_TYPE_CarouselFigures,
        ITEM_TYPE_GoodFilter,
        ITEM_TYPE_GoodListItem,
        ITEM_TYPE_GoodGridItem
    }

    class CellData extends Object {

        public Item_Type mType;

        public Object mObject;

        public CellData(Item_Type type, Object object) {
            mType = type;
            mObject = object;
        }
    }

    Map<Integer, CellData> mPostionValueMap = new HashMap<>();

    void handleGoodItem(WGHomeFloorContentGoodItem item) {
        if (mOnItemClickListener != null) {
            OnItemClickListener temp = (OnItemClickListener)mOnItemClickListener;
            if (temp != null) {
                temp.onGoodItem(item);
            }
        }
    }

    void handleShopCart(WGHomeFloorContentGoodItem item, View view, Point fromPoint) {
        if (mOnItemClickListener != null) {
            OnItemClickListener temp = (OnItemClickListener)mOnItemClickListener;
            if (temp != null) {
                temp.onShopCart(item, view, fromPoint);
            }
        }
    }

    @Override
    public JHBaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        int resourceId = 0;
        View view = null;
        if (viewType == WGClassifyDetailContentAdapter.Item_Type.ITEM_TYPE_CarouselFigures.ordinal()) {
            resourceId = R.layout.wghome_content_rotation;
            view = LayoutInflater.from(
                    mContext).inflate(resourceId, parent,
                    false);
        }
        else if (viewType == WGClassifyDetailContentAdapter.Item_Type.
                        ITEM_TYPE_GoodListItem.ordinal()) {
            resourceId = R.layout.wggood_list_item;
            WGGoodListView temp = (WGGoodListView)LayoutInflater.from(
                    mContext).inflate(resourceId, parent,
                    false);
            temp.setListener(new WGGoodListView.GoodListItemOnListener() {
                @Override
                public void onTouchShopCart(WGHomeFloorContentGoodItem item, View view, Point point) {
                    handleShopCart(item, view, point);
                }

                @Override
                public void onTouchItem(WGHomeFloorContentGoodItem item) {
                    handleGoodItem(item);
                }
            });
            view = temp;
        }
        else if (viewType == WGClassifyDetailContentAdapter.Item_Type.
                ITEM_TYPE_GoodGridItem.ordinal()) {
            resourceId = R.layout.wghome_content_floor_good_grid_cell;
            WGHomeContentFloorGoodsGridCellView temp = (WGHomeContentFloorGoodsGridCellView)LayoutInflater.from(
                    mContext).inflate(resourceId, parent,
                    false);
            temp.setListener(new WGHomeContentFloorGoodsGridCellView.OnPurchaseListener() {
                @Override
                public void onPurchase(WGHomeFloorContentGoodItem item, View view, Point point) {
                    handleShopCart(item, view, point);
                }

                @Override
                public void onGoodDetail(WGHomeFloorContentGoodItem item) {
                    handleGoodItem(item);
                }
            });
            view = temp;
        }
        else if (viewType == Item_Type.ITEM_TYPE_GoodFilter.ordinal()) {
            resourceId = R.layout.classifydetail_filter_view;
            final WGClassifyDetailFilterView filter = (WGClassifyDetailFilterView)LayoutInflater.from(
                    mContext).inflate(resourceId, parent,
                    false);
            filter.setListener(new WGClassifyDetailFilterView.OnItemClickListener() {
                @Override
                public void onSort(View view) {
                    if (mOnItemClickListener != null) {
                        ((OnItemClickListener)mOnItemClickListener).onSort(filter);
                    }
                }

                @Override
                public void onFilter(View view) {
                    if (mOnItemClickListener != null) {
                        ((OnItemClickListener)mOnItemClickListener).onFilter(filter);
                    }
                }

                @Override
                public void onVista(View view) {
                    if (mOnItemClickListener != null) {
                        ((OnItemClickListener)mOnItemClickListener).onGrid(filter);
                    }
                }
            });
            view = filter;
        }
        HomeViewHolder holder = new HomeViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(JHBaseViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        CellData item = mPostionValueMap.get(position);
        holder.showWithData(item.mObject);
    }

    @Override
    public int getItemCount() {
        if (mData == null) {
            return 0;
        }
        int count = 1;  //筛选
        if (mData.hasCarousel()) {
            count += 1;
        }
        if (mData.hasRecommendedArray()) {
            count += mData.recommendedArray.size();
        }
        if (mData.hasGoods()) {
            if (mData.isGrid()) {
                count += (mData.goodArray.size() + 1)/2;
            }
            else {
                count += mData.goodArray.size();
            }
        }
        return count;
    }

    @Override
    public int getItemViewType(int position) {
        if (mPostionValueMap != null && mPostionValueMap.size() > position) {
            CellData data = mPostionValueMap.get(position);
            return data.mType.ordinal();
        }
        return Item_Type.ITEM_TYPE_None.ordinal();
    }

    //Classify
    class HomeViewHolder extends JHBaseViewHolder {

        View mView;

        public HomeViewHolder(View view) {
            super(view);
            mView = view;
        }

        @Override
        public void showWithData(Object object) {
            super.showWithData(object);
            if (mView instanceof JHRelativeLayout) {
                JHRelativeLayout layout = (JHRelativeLayout) mView;
                if (object instanceof List) {
                    layout.showWithArray((List) object);
                }
                else {
                    layout.showWithData(object);
                }
            }
            else if (mView instanceof JHLinearLayout) {
                JHLinearLayout layout = (JHLinearLayout) mView;
                if (object instanceof List) {
                    layout.showWithArray((List) object);
                }
                else {
                    layout.showWithData(object);
                }
            }
        }
    }
}


text:
> A jQuery/Zepto.js plugin for creating a slider for any kind of content.

## Development
The current beta/unstable version can be found in the "develop" branch. Not recommended for production sites.

Please send all pull requests to the "develop" branch as well.

### Building AnySlider
To build and automatically minify and run JSHint on the code you'll need the latest [Node.js/npm](http://nodejs.org/) and [Git](http://git-scm.com/).
Please refer to their respective home pages for installation instructions.

Then install the [grunt-cli](http://gruntjs.com/getting-started#installing-the-cli) package globally (if not done already):

```bash
npm install -g grunt-cli
```

Then install the Node dependencies:

```bash
cd AnySlider && npm install
```

Now, to get a minified and linted version of AnySlider run:

```bash
grunt
```

If all goes well and your code passes the lint a file called "jquery.anyslider.min.js" will be created in the "dist" directory.

## Features
* Continuous autoplay.
* Custom easings.
* Fade or slide transition.
* Highly customizable appearance and lots of options.
* Keyboard navigation.
* Multiple sliders on one page supported.
* Navigation bullets.
* No CSS or HTML-structure enforced, you're 100% in charge.
* Slide any content or using any element. HTML, images and YouTube clips. Or mix
s, s, and
s. AnySlider doesn't care.
* Small, 1.5 kB minified and gzipped (3.5 kB minified).
* Supported in all major browsers.
* Touch support (Android, iOS, and Windows 8).

## Options
* afterChange (Default function ()) function A function to call after each slide change.
* afterSetup (Default function ()) function A function to call after the slider has been setup.
* animation (Default slide") string Transition, one of the following:
    * fade Fades between slides.
    * slide A sliding aniamtion between slides.
* beforeChange (Default function ()) function A function to call before each slide change.
* easing (Default "swing") string Name of a custom easing. For example via the jQuery Easing plugin. Only used when "animation" is "slide".
* interval (Default 5000) integer Number of milliseconds to pause on each slide. Setting this option to 0 will disable autoplay.
* keyboard (Default true) boolean Allow for keyboard navigation using the left and right arrow keys.
* nextLabel (Default "Next slide") string Label for the next button.
* pauseOnHover (Default true) boolean Pause the autoplay on hover?
* prevLabel (Default "Previous slide") string Label for the previous button.
* reverse (Default false) boolean Whether to slide right-to-left instead of left-to-right when autoplay is enabled.
* showBullets (Default true) boolean Whether or not to display navigation bullets. Setting this to false will prevent the bullets from being drawn at all.
* showControls (Default true) boolean Show/hide controls. Setting this to false will prevent the controls from being drawn at all.
* speed (Default 400) int The animation time in milliseconds. Setting this option to 0 will disable animation.
* startSlide (Default 1) int Number of the starting slide. Starting from 1.
* touch (Default true) boolean Whether to enable the ability to swipe between slides.

## Requirements
* jQuery 1.7.0 (or later).
* Or Zepto 1.1.0 (or later) with the following modules:
    * zepto
    * data
    * event
    * fx
    * fx_methods
    * ie (Optional, if IE10+ support is wanted)

## License
Free to use and abuse under the [MIT license](http://www.opensource.org/licenses/mit-license.php).


text:
import * as React from "react";
import * as ReactDOM from "react-dom";
import {browserHistory} from "react-router";
import Navbar from "../../components/navbar/navbar";
import sessionStore, {PermissionLevel} from "../../../stores/sessionStore";
import companyStore from "../../../stores/companyStore";
import {EmptyChecker} from "../../../utils/checker";
import ErrorMessage from "../../components/errorMessageComponent";
import companyActionCreator, {ICompany}
    from "../../../actions/companyActionCreator";

/**
 *
IUpdateCompanyState defines an interface
 * to store the token of the user

 */
export interface IUpdateCompanyState {
    token : string;
    company : ICompany;
    message : string;
}

/**
 *
IUpdateCompanyProps defines an interface
 * which stores the params (the company_id passed through the URI)

 */
export interface IUpdateCompanyProps {
    params : ReactRouter.Params
}

/**
 *
UpdateCompany is a react component that renders
 * the update company component.
 *

 *
 * @history
 * | Author           | Action Performed    | Data       |
 * |------------------|---------------------|------------|
 * | Emanuele Carraro |  create class       | 2/06/2015  |
 *
 * @author Emanuele Carraro
 * @license MIT
 */
class UpdateCompany extends React.Component<IUpdateCompanyProps,
                                            IUpdateCompanyState> {

    /**
     * @description ID of the company.
     */
    private company_id : string = this.props.params["company_id"];

    /**
     * @description Default constructor.
     * @return {UpdateCompany}
     */
    constructor(props : IUpdateCompanyProps) {
        super(props);
        this.state = {
            token : sessionStore.getAccessToken(),
            company : companyStore.getCompany(this.company_id),
            message : ""
        };

        this._onChange = this._onChange.bind(this);
    }

    /**
     * @description
     *
Render method of the component.
     * It renders the UpdateCompanies component.

     * @return {JSX.Element}
     */
    public render() : JSX.Element {

        /* tslint:disable: max-line-length */
        return(

                <Navbar />

Company

{this.state.company.name}

                        <ErrorMessage error={this.state.message} />
                        <form className="col s12">

                                    <input id="companyName" type="text" className="validate" ref="companyName"/>
                                    Name of the company

                                    done
                                    Update Company

                        </form>

        );
        /* tslint:enable: max-line-length */
    }

    /**
     * @description
     *
This method is call when the user click
     * on the update Company button.

     */
    private updateCompany() : void {
        let companyName : string =
            ReactDOM.
            findDOMNode<HTMLInputElement>(this.refs["companyName"]).value;
        let emptyChecker : EmptyChecker = new EmptyChecker(companyName);
        if (!emptyChecker.check()) {
            this.setState({
                token : sessionStore.getAccessToken(),
                company : companyStore.getCompany(this.company_id),
                message : "Empty name field"
            });
        } else {
            companyActionCreator.updateCompany(
                {
                    name : companyName,
                },
                this.state.token,
                this.state.company._id
            );
        }
    }

    /**
     * @description This method is called when the component mount.
     */
    private componentDidMount() : void {
        if (!(sessionStore.checkPermission(PermissionLevel.SUPERADMIN))) {
            browserHistory.push("/Error403")
        }
        companyStore.addChangeListener(this._onChange);
    }

    /**
     * @description This method is called when the component will unmount.
     */
    private componentWillUnmount() : void {
        companyStore.removeChangeListener(this._onChange);
    }

    /**
     * @description This method is called every time the store change.
     */
    private _onChange() : void {
        let errorMessage : string = "";
        if (companyStore.updateCompanyError()) {
            errorMessage = companyStore.getUpdateCompanyError()
        } else {
            browserHistory.push("/SuperAdmin/ShowCompanies");
        }
        this.setState({
            token : sessionStore.getAccessToken(),
            company : companyStore.getCompany(this.company_id),
            message : errorMessage
        });
    }

}

export default UpdateCompany;


text:
<?php

namespace leinonen\Yii2Monolog\Factories;

class ProcessorFactory
{
    /**
     * @var GenericStrategyBasedFactory
     */
    private $genericFactory;

    /**
     * Initializes a new ProcessorFactory.
     *
     * @param GenericStrategyBasedFactory $genericFactory
     */
    public function __construct(GenericStrategyBasedFactory $genericFactory)
    {
        $this->genericFactory = $genericFactory;
    }

    /**
     * Makes a new Processor from the given processor class and config.
     *
     * @param string $processorClass
     * @param array $config
     *
     * @return callable
     *
     * @throws \InvalidArgumentException
     * @throws \yii\base\InvalidConfigException
     */
    public function make(string $processorClass, array $config = []): callable
    {
        $this->validateProcessorClass($processorClass);

        return $this->genericFactory->makeWithStrategy($processorClass, $config);
    }

    /**
     * Validates the given processor class.
     *
     * @param $processorClass
     *
     * @throws \InvalidArgumentException
     */
    private function validateProcessorClass(string $processorClass)
    {
        if (! (new \ReflectionClass($processorClass))->hasMethod('__invoke')) {
            throw new \InvalidArgumentException("{$processorClass} isn't callable. All processor classes must implement the __invoke method.");
        }
    }
}