<commit_before>define([
    '/narrative/nbextensions/appCell2/appCell',
    'base/js/namespace',
    'common/semaphore',
    'testUtil',
    'narrativeMocks',
    'narrativeConfig',
    'json!/test/data/NarrativeTest.test_simple_inputs.spec.json',
], (AppCell, Jupyter, Semaphore, TestUtil, Mocks, Config, TestAppSpec) => {
    'use strict';

    describe('test the base AppCell2 module', () => {
        it('loads with expected functions', () => {
            ['make', 'isAppCell'].forEach((fn) => {
                expect(AppCell[fn]).toEqual(jasmine.any(Function));
            });
        });

        beforeEach(() => {
            const commSemaphore = Semaphore.make();
            commSemaphore.add('comm', false);
            commSemaphore.set('comm', 'ready');
            jasmine.Ajax.install();
            Jupyter.notebook = {
                writable: true,
            };
            Jupyter.narrative = {
                readonly: false,
                getAuthToken: () => 'fakeToken',
            };
        });

        afterEach(() => {
            TestUtil.clearRuntime();
            jasmine.Ajax.uninstall();
        });

        describe('create AppCell tests', () => {
            beforeEach(() => {
                // mock NMS.get_method_spec,
                Mocks.mockJsonRpc1Call({
                    url: Config.url('narrative_method_store'),
                    body: /get_method_spec/,
                    response: [TestAppSpec],
                });

                // mock NMS.get_method_full_info,
                Mocks.mockJsonRpc1Call({
                    url: Config.url('narrative_method_store'),
                    body: /get_method_full_info/,
                    response: [
                        Object.assign({}, TestAppSpec.info, {
                            description: 'test app',
                            suggestions: {
                                next_methods: [],
                                related_apps: [],
                                next_apps: [],
                                related_methods: [],
                            },
                            screenshots: [],
                            publications: [],
                            namespace: 'NarrativeTest',
                        }),
                    ],
                });

                // mock Catalog.get_exec_aggr_stats (not used here)
                Mocks.mockJsonRpc1Call({
                    url: Config.url('catalog'),
                    body: /get_exec_aggr_stats/,
                    response: [{}],
                });
            });

            it('makes an AppCell without starting it', () => {
                const fakeCell = Mocks.buildMockCell('code');
                const appCell = AppCell.make({ cell: fakeCell });
                ['setupCell', 'upgradeToAppCell'].forEach((fn) => {
                    expect(appCell[fn]).toEqual(jasmine.any(Function));
                });
            });

            it('makes a new AppCell from scratch', () => {
                const fakeCell = Mocks.buildMockCell('code');
                const appCell = AppCell.make({ cell: fakeCell });
                const appTag = 'release';
                const appType = 'app';
                expect(fakeCell.metadata).toBeDefined();

                const expectedMetadata = {
                    app: {
                        id: TestAppSpec.info.id,
                        gitCommitHash: TestAppSpec.info.git_commit_hash,
                        version: TestAppSpec.info.ver,
                        tag: appTag,
                        spec: TestAppSpec,
                    },
                    params: {
                        simple_string: '',
                    },
                    output: {
                        byJob: {},
                    },
                    'user-settings': {
                        showCodeInputArea: false,
                    },
                    executionStats: {},
                };

                return appCell.upgradeToAppCell(TestAppSpec, appTag, appType).then(() => {
                    expect(fakeCell.metadata.kbase.type).toEqual('app');
                    const appCellMeta = fakeCell.metadata.kbase.appCell;
                    expect(appCellMeta).toBeDefined();
                    expect(appCellMeta).toEqual(expectedMetadata);
                });
            });

            it('restores an existing AppCell', () => {
                const fakeAppCell = Mocks.buildMockCell('code', 'app');
                fakeAppCell.metadata.kbase.appCell = {
                    app: {
                        id: TestAppSpec.info.id,
                        spec: TestAppSpec,
                        tag: 'dev',
                        version: '0.0.0',
                    },
                    executionStats: {}, // provided from Catalog, not needed for mock
                    fsm: {
                        currentState: {
                            mode: 'editing',
                            params: 'incomplete',
                        },
                    },
                    output: {
                        byJob: {},
                    },
                    params: {
                        simple_string: null,
                    },
                    'user-settings': {
                        showCodeInputArea: false,
                    },
                };
                const appCell = AppCell.make({ cell: fakeAppCell });
                return appCell.setupCell().then(() => {
                    expect(appCell).toBeDefined();
                });
            });
        });

        describe('isAppCell tests', () => {
            const allowedCellTypes = ['app2', 'app', 'devapp'];
            allowedCellTypes.forEach((cellType) => {
                it(`returns true for a ${cellType} tagged cell`, () => {
                    const cell = {
                        cell_type: 'code',
                        metadata: {
                            kbase: {
                                type: cellType,
                            },
                        },
                    };
                    expect(AppCell.isAppCell(cell)).toBeTrue();
                });
            });

            const badCellCases = [
                {
                    cell: { cell_type: 'markdown' },
                    label: 'a markdown Jupyter type',
                },
                {
                    cell: { cell_type: 'code', metadata: {} },
                    label: 'no kbase metadata',
                },
                {
                    cell: { cell_type: 'code', metadata: { kbase: { type: 'foo' } } },
                    label: 'mismatched kbase type',
                },
            ];
            badCellCases.forEach((testCase) => {
                it(`returns false for a cell with ${testCase.label}`, () => {
                    expect(AppCell.isAppCell(testCase.cell)).toBeFalse();
                });
            });
        });
    });
});
<commit_msg>add better appcell setupCell expectation<commit_after>define([
    '/narrative/nbextensions/appCell2/appCell',
    'base/js/namespace',
    'common/semaphore',
    'testUtil',
    'narrativeMocks',
    'narrativeConfig',
    'json!/test/data/NarrativeTest.test_simple_inputs.spec.json',
], (AppCell, Jupyter, Semaphore, TestUtil, Mocks, Config, TestAppSpec) => {
    'use strict';

    fdescribe('test the base AppCell2 module', () => {
        it('loads with expected functions', () => {
            ['make', 'isAppCell'].forEach((fn) => {
                expect(AppCell[fn]).toEqual(jasmine.any(Function));
            });
        });

        beforeEach(() => {
            const commSemaphore = Semaphore.make();
            commSemaphore.add('comm', false);
            commSemaphore.set('comm', 'ready');
            jasmine.Ajax.install();
            Jupyter.notebook = {
                writable: true,
            };
            Jupyter.narrative = {
                readonly: false,
                getAuthToken: () => 'fakeToken',
            };
        });

        afterEach(() => {
            TestUtil.clearRuntime();
            jasmine.Ajax.uninstall();
        });

        describe('create AppCell tests', () => {
            beforeEach(() => {
                // mock NMS.get_method_spec,
                Mocks.mockJsonRpc1Call({
                    url: Config.url('narrative_method_store'),
                    body: /get_method_spec/,
                    response: [TestAppSpec],
                });

                // mock NMS.get_method_full_info,
                Mocks.mockJsonRpc1Call({
                    url: Config.url('narrative_method_store'),
                    body: /get_method_full_info/,
                    response: [
                        Object.assign({}, TestAppSpec.info, {
                            description: 'test app',
                            suggestions: {
                                next_methods: [],
                                related_apps: [],
                                next_apps: [],
                                related_methods: [],
                            },
                            screenshots: [],
                            publications: [],
                            namespace: 'NarrativeTest',
                        }),
                    ],
                });

                // mock Catalog.get_exec_aggr_stats (not used here)
                Mocks.mockJsonRpc1Call({
                    url: Config.url('catalog'),
                    body: /get_exec_aggr_stats/,
                    response: [{}],
                });
            });

            it('makes an AppCell without starting it', () => {
                const fakeCell = Mocks.buildMockCell('code');
                const appCell = AppCell.make({ cell: fakeCell });
                ['setupCell', 'upgradeToAppCell'].forEach((fn) => {
                    expect(appCell[fn]).toEqual(jasmine.any(Function));
                });
            });

            it('makes a new AppCell from scratch', () => {
                const fakeCell = Mocks.buildMockCell('code');
                const appCell = AppCell.make({ cell: fakeCell });
                const appTag = 'release';
                const appType = 'app';
                expect(fakeCell.metadata).toBeDefined();

                const expectedMetadata = {
                    app: {
                        id: TestAppSpec.info.id,
                        gitCommitHash: TestAppSpec.info.git_commit_hash,
                        version: TestAppSpec.info.ver,
                        tag: appTag,
                        spec: TestAppSpec,
                    },
                    params: {
                        simple_string: '',
                    },
                    output: {
                        byJob: {},
                    },
                    'user-settings': {
                        showCodeInputArea: false,
                    },
                    executionStats: {},
                };

                return appCell.upgradeToAppCell(TestAppSpec, appTag, appType).then(() => {
                    expect(fakeCell.metadata.kbase.type).toEqual('app');
                    const appCellMeta = fakeCell.metadata.kbase.appCell;
                    expect(appCellMeta).toBeDefined();
                    expect(appCellMeta).toEqual(expectedMetadata);
                });
            });

            it('start a pre-upgraded AppCell', () => {
                const fakeAppCell = Mocks.buildMockCell('code', 'app');
                fakeAppCell.metadata.kbase.appCell = {
                    app: {
                        id: TestAppSpec.info.id,
                        spec: TestAppSpec,
                        tag: 'dev',
                        version: '0.0.0',
                    },
                    executionStats: {}, // provided from Catalog, not needed for mock
                    fsm: {
                        currentState: {
                            mode: 'editing',
                            params: 'incomplete',
                        },
                    },
                    output: {
                        byJob: {},
                    },
                    params: {
                        simple_string: null,
                    },
                    'user-settings': {
                        showCodeInputArea: false,
                    },
                };
                const appCell = AppCell.make({ cell: fakeAppCell });
                return appCell.setupCell().then((ret) => {
                    expect(ret.widget).toBeDefined();
                    ['init', 'attach', 'start', 'stop', 'detach', 'run'].forEach((fn) => {
                        expect(ret.widget[fn]).toEqual(jasmine.any(Function));
                    });
                    expect(ret.bus).toBeDefined();
                    // really it should match a UUID, but close enough to ensure it's real?
                    expect(ret.bus.channelName).toEqual(jasmine.any(String));
                });
            });
        });

        describe('isAppCell tests', () => {
            const allowedCellTypes = ['app2', 'app', 'devapp'];
            allowedCellTypes.forEach((cellType) => {
                it(`returns true for a ${cellType} tagged cell`, () => {
                    const cell = {
                        cell_type: 'code',
                        metadata: {
                            kbase: {
                                type: cellType,
                            },
                        },
                    };
                    expect(AppCell.isAppCell(cell)).toBeTrue();
                });
            });

            const badCellCases = [
                {
                    cell: { cell_type: 'markdown' },
                    label: 'a markdown Jupyter type',
                },
                {
                    cell: { cell_type: 'code', metadata: {} },
                    label: 'no kbase metadata',
                },
                {
                    cell: { cell_type: 'code', metadata: { kbase: { type: 'foo' } } },
                    label: 'mismatched kbase type',
                },
            ];
            badCellCases.forEach((testCase) => {
                it(`returns false for a cell with ${testCase.label}`, () => {
                    expect(AppCell.isAppCell(testCase.cell)).toBeFalse();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>define(['widget-test-base', 'jquery', 'jquery-ui', 'src/widgets/select/pickList'], function () {

  describe('widget(pickList): callback:', function () {

    var fixture_list, element_list, original_list;
    var fixture_table, element_table, original_table;

    beforeEach(function () {
      var f = jasmine.getFixtures();
      f.load('test/widgets/select/pick-list/pick-list-source.html');

      var s = jasmine.getStyleFixtures();
      s.appendLoad('dist/assets/bootstrap/bootstrap.css');
      s.appendLoad('dist/assets/font-awesome/font-awesome.css');
      s.appendLoad('dist/assets/richwidgets/select/select-list.css');
      s.appendLoad('dist/assets/richwidgets/select/ordering-list.css');
      s.appendLoad('dist/assets/richwidgets/select/pick-list.css');

      fixture_list = $('#fixture-pick-list-list');
      original_list = fixture_list.clone();
      element_list = $('#list', fixture_list);
      fixture_table = $('#fixture-pick-list-table');
      original_table = fixture_table.clone();
      element_table = $('#table', fixture_table);
    });

    describe('lifecycle events: ', function () {
      it('create:', function () {
        function test(fixture, element) {
          // given
          var createCallback = jasmine.createSpy('createCallback');
          var destroyCallback = jasmine.createSpy('destroyCallback');
          var addDomElementsCallback = jasmine.createSpy('addDomElementsCallback');

          // when
          element.pickList({
            create: createCallback,
            destroy: destroyCallback,
            addDomElements: addDomElementsCallback
          });

          element.pickList('destroy');

          //then
          expect(createCallback).toHaveBeenCalled();
          expect(addDomElementsCallback).toHaveBeenCalled();
          expect(destroyCallback).toHaveBeenCalled();
        }

        test(fixture_list, element_list);
        test(fixture_table, element_table);
      });
    });

    describe('interaction events: ', function () {
      it('focus/blur:', function () {
        function test(fixture, element) {
          // given
          var focusCallback = jasmine.createSpy('focusCallback');
          var blurCallback = jasmine.createSpy('blurCallback');

          element.pickList({
            focus: focusCallback,
            blur: blurCallback
          });

          //when
          var firstItem = fixture.find('.source .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return firstItem.hasClass('ui-selected');
          }, "first item should be selected", 500);

          runs(function () {
            expect(focusCallback).toHaveBeenCalled();
            fixture.find('#blur').focus();
          });

          waitsFor(function () {
            return fixture.find('#blur').get(0) === document.activeElement;
          }, 'blur button has focus', 500);

          runs(function () {
            expect(blurCallback).toHaveBeenCalled();
          });
        }

        test(fixture_list, element_list);
        test(fixture_table, element_table);
      });

      describe('change by button click:', function () {
        it('btn-add:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-add');
          testChangeByButtonClick(fixture_table, element_table, 'btn-add');
        });

        it('btn-add-all:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-add-all');
          testChangeByButtonClick(fixture_table, element_table, 'btn-add-all');
        });

        it('btn-remove:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-remove');
          testChangeByButtonClick(fixture_table, element_table, 'btn-remove');
        });

        it('btn-remove:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-remove-all');
          testChangeByButtonClick(fixture_table, element_table, 'btn-remove-all');
        });

        function testChangeByButtonClick(fixture, element, buttonClass) {
          var changeCallback = jasmine.createSpy('changeCallback');

          element.pickList({ change: changeCallback });

          var list1 = buttonClass.indexOf('btn-add') === 0 ? ".source" : ".target";
          var list2 = buttonClass.indexOf('btn-add') === 0 ? ".target" : ".source";

          //when
          var firstItem = fixture.find(list1 + ' .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return firstItem.hasClass('ui-selected');
          }, "first item should be selected", 500);

          runs(function () {
            fixture.find('.button-column .' + buttonClass).first().click();
          });

          waitsFor(function () {
            return fixture.find(list2 + ' .ui-selectee').first().data('key') === firstItem.data('key');
          }, 'item should be moved to top of opposing list', 500);

          runs(function () {
            expect(changeCallback).toHaveBeenCalled();
          });
        };
      });

      describe('change by drag and drop:', function () {
        function test(fixture, element, dx, dy) {
          $('#container').width('800'); // set the container width so the mouse drags are repeatable across browsers
          var changeCallback = jasmine.createSpy('changeCallback');

          element.pickList({ change: changeCallback });

          var list1 = dx > 0 ? ".source" : ".target";
          var list2 = dx > 0 ? ".target" : ".source";

          //when
          var firstItem = fixture.find(list1 + ' .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.simulate('drag', {dx: dx, dy: dy});
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return fixture.find(list2 + ' .ui-selectee').first().data('key') === firstItem.data('key');
          }, 'item should be moved to top of opposing list', 500);

          runs(function () {
            expect(changeCallback).toHaveBeenCalled();
          });

        }

        var dx = 400;
        it('drag to target:', function () {
          test(fixture_list, element_list, dx, 0);
          test(fixture_table, element_table, dx, 20);
        });

        it('drag to source:', function () {
          test(fixture_list, element_list, -dx, 0);
          test(fixture_table, element_table, -dx, 20);
          debugger;
        });
      });
    });
  });
});<commit_msg>removing debugger instructions from pick-list-callbacks<commit_after>define(['widget-test-base', 'jquery', 'jquery-ui', 'src/widgets/select/pickList'], function () {

  describe('widget(pickList): callback:', function () {

    var fixture_list, element_list, original_list;
    var fixture_table, element_table, original_table;

    beforeEach(function () {
      var f = jasmine.getFixtures();
      f.load('test/widgets/select/pick-list/pick-list-source.html');

      var s = jasmine.getStyleFixtures();
      s.appendLoad('dist/assets/bootstrap/bootstrap.css');
      s.appendLoad('dist/assets/font-awesome/font-awesome.css');
      s.appendLoad('dist/assets/richwidgets/select/select-list.css');
      s.appendLoad('dist/assets/richwidgets/select/ordering-list.css');
      s.appendLoad('dist/assets/richwidgets/select/pick-list.css');

      fixture_list = $('#fixture-pick-list-list');
      original_list = fixture_list.clone();
      element_list = $('#list', fixture_list);
      fixture_table = $('#fixture-pick-list-table');
      original_table = fixture_table.clone();
      element_table = $('#table', fixture_table);
    });

    describe('lifecycle events: ', function () {
      it('create:', function () {
        function test(fixture, element) {
          // given
          var createCallback = jasmine.createSpy('createCallback');
          var destroyCallback = jasmine.createSpy('destroyCallback');
          var addDomElementsCallback = jasmine.createSpy('addDomElementsCallback');

          // when
          element.pickList({
            create: createCallback,
            destroy: destroyCallback,
            addDomElements: addDomElementsCallback
          });

          element.pickList('destroy');

          //then
          expect(createCallback).toHaveBeenCalled();
          expect(addDomElementsCallback).toHaveBeenCalled();
          expect(destroyCallback).toHaveBeenCalled();
        }

        test(fixture_list, element_list);
        test(fixture_table, element_table);
      });
    });

    describe('interaction events: ', function () {
      it('focus/blur:', function () {
        function test(fixture, element) {
          // given
          var focusCallback = jasmine.createSpy('focusCallback');
          var blurCallback = jasmine.createSpy('blurCallback');

          element.pickList({
            focus: focusCallback,
            blur: blurCallback
          });

          //when
          var firstItem = fixture.find('.source .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return firstItem.hasClass('ui-selected');
          }, "first item should be selected", 500);

          runs(function () {
            expect(focusCallback).toHaveBeenCalled();
            fixture.find('#blur').focus();
          });

          waitsFor(function () {
            return fixture.find('#blur').get(0) === document.activeElement;
          }, 'blur button has focus', 500);

          runs(function () {
            expect(blurCallback).toHaveBeenCalled();
          });
        }

        test(fixture_list, element_list);
        test(fixture_table, element_table);
      });

      describe('change by button click:', function () {
        it('btn-add:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-add');
          testChangeByButtonClick(fixture_table, element_table, 'btn-add');
        });

        it('btn-add-all:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-add-all');
          testChangeByButtonClick(fixture_table, element_table, 'btn-add-all');
        });

        it('btn-remove:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-remove');
          testChangeByButtonClick(fixture_table, element_table, 'btn-remove');
        });

        it('btn-remove:', function () {
          testChangeByButtonClick(fixture_list, element_list, 'btn-remove-all');
          testChangeByButtonClick(fixture_table, element_table, 'btn-remove-all');
        });

        function testChangeByButtonClick(fixture, element, buttonClass) {
          var changeCallback = jasmine.createSpy('changeCallback');

          element.pickList({ change: changeCallback });

          var list1 = buttonClass.indexOf('btn-add') === 0 ? ".source" : ".target";
          var list2 = buttonClass.indexOf('btn-add') === 0 ? ".target" : ".source";

          //when
          var firstItem = fixture.find(list1 + ' .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return firstItem.hasClass('ui-selected');
          }, "first item should be selected", 500);

          runs(function () {
            fixture.find('.button-column .' + buttonClass).first().click();
          });

          waitsFor(function () {
            return fixture.find(list2 + ' .ui-selectee').first().data('key') === firstItem.data('key');
          }, 'item should be moved to top of opposing list', 500);

          runs(function () {
            expect(changeCallback).toHaveBeenCalled();
          });
        };
      });

      describe('change by drag and drop:', function () {
        function test(fixture, element, dx, dy) {
          $('#container').width('800'); // set the container width so the mouse drags are repeatable across browsers
          var changeCallback = jasmine.createSpy('changeCallback');

          element.pickList({ change: changeCallback });

          var list1 = dx > 0 ? ".source" : ".target";
          var list2 = dx > 0 ? ".target" : ".source";

          //when
          var firstItem = fixture.find(list1 + ' .ui-selectee').first();

          //then
          runs(function () {
            firstItem.trigger('mousedown');
            firstItem.simulate('drag', {dx: dx, dy: dy});
            firstItem.trigger('mouseup');
          });

          waitsFor(function () {
            return fixture.find(list2 + ' .ui-selectee').first().data('key') === firstItem.data('key');
          }, 'item should be moved to top of opposing list', 500);

          runs(function () {
            expect(changeCallback).toHaveBeenCalled();
          });

        }

        var dx = 400;
        it('drag to target:', function () {
          test(fixture_list, element_list, dx, 0);
          test(fixture_table, element_table, dx, 20);
        });

        it('drag to source:', function () {
          test(fixture_list, element_list, -dx, 0);
          test(fixture_table, element_table, -dx, 20);
        });
      });
    });
  });
});<|endoftext|>


<commit_before>// Copyright The Workers Ltd. 2012 (theworkers.net)
// @author Ross Cairns
// @notes  Not suitable for heavy usage (i.e. particles) as produces
//         many object with in turn will cause big
//         garbage collections delays
(function () {

    var root = this;
    var W = root.W || {};
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = W;
        root.W = W;
    } else {
        root.W = W;
    }

    W.DisplayViewMixin = {
        version : 1,
        setPosition : function (x, y) { // or setXY(array) or setXY({x:y:})
            if (typeof x === "[object Array]") {
                this.x(x[0]);
                this.y(y[1]);
            } else if (typeof x === "number") {
                this.x(x);
                this.y(y);
            } else {
                this.x(x.x);
                this.y(x.y);
            }
            return this;
        },
        setSize : function (width, height) { // or setSize(Array) or setSize({width:height}) or setSize(DOMElement)
            if (!!width.tagName) {
                this.width($(width).width());
                this.height($(width).height());
            } else if (typeof width === "number") {
                this.width(width);
                this.height(height);
            } else if (typeof width === "height") {
                this.width(width[0]);
                this.height(width[1]);
            } else {
                this.width(_.isFunction(width.width) ? width.width() : width.width);
                this.height(_.isFunction(width.height) ? width.height() : width.height);
            }
        },
        x : function (x) {
            if (arguments.length > 0) { this._x = x; }
            if (typeof this._x === "undefined") { this._x = 0; }
            return this._x;
        },
        y : function (y) {
            if (arguments.length > 0) { this._y = y; }
            if (typeof this._y === "undefined") { this._y = 0; }
            return this._y;
        },
        width : function (width)  {
            if (arguments.length > 0) { this._width = width; }
            if (typeof this._width === "undefined") { this._width = 0; }
            return this._width;
        },
        height : function (height) {
            if (arguments.length > 0) { this._height = height; }
            if (typeof this._height === "undefined") { this._height = 0; }
            return this._height;
        }
    };

}());

<commit_msg>improved function arguments handling<commit_after>// Copyright The Workers Ltd. 2012 (theworkers.net)
// @author Ross Cairns
// @notes  Not suitable for heavy usage (i.e. particles) as produces
//         many object with in turn will cause big
//         garbage collections delays
(function () {

    var root = this;
    var W = root.W || {};
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = W;
        root.W = W;
    } else {
        root.W = W;
    }

    W.DisplayViewMixin = {
        version : 1,
        setPosition : function (x, y) { // or setXY(array) or setXY({x:y:})
            if (typeof x === "[object Array]") {
                this.x(x[0]);
                this.y(y[1]);
            } else if (typeof x === "number") {
                this.x(x);
                this.y(y);
            } else {
                this.x(x.x);
                this.y(x.y);
            }
            return this;
        },
        setSize : function (width, height) { // or setSize(Array) or setSize({width:height}) or setSize(DOMElement)
            if (!!width.tagName) {
                this.width($(width).width());
                this.height($(width).height());
            } else if (typeof width === "number") {
                this.width(width);
                this.height(height);
            } else if (typeof width === "array") {
                this.width(width[0]);
                this.height(width[1]);
            } else if (typeof(width) == 'function') {
                this.width(width());
                this.height(height());
            } else {
                var obj = width;
                this.width(typeof(obj.width) == 'function' ? obj.width() : obj.width);
                this.height(typeof(obj.height) == 'function' ? obj.height() : obj.height);
            }
            return this;
        },
        x : function (x) {
            if (arguments.length > 0) { this._x = x; }
            if (typeof this._x === "undefined") { this._x = 0; }
            return this._x;
        },
        y : function (y) {
            if (arguments.length > 0) { this._y = y; }
            if (typeof this._y === "undefined") { this._y = 0; }
            return this._y;
        },
        width : function (width)  {
            if (arguments.length > 0) { this._width = width; }
            if (typeof this._width === "undefined") { this._width = 0; }
            return this._width;
        },
        height : function (height) {
            if (arguments.length > 0) { this._height = height; }
            if (typeof this._height === "undefined") { this._height = 0; }
            return this._height;
        }
    };

}());

<|endoftext|>


<commit_before>"use strict";

var Cylon = require('cylon')
var tilted = false;
var talking = false;
var leds = {red:2,blue:3,green:4};
var color = "";
var whiteArray = {red:0,blue:0,green:0};
var blackArray = {red:0,blue:0,green:0};
var colorArray = {red:0,blue:0,green:0};
var avgArray = {red:0,blue:0,green:0};

require('shelljs/global');

Cylon.robot({
  connections: {
    edison: { adaptor: 'intel-iot' }
  },
  devices: {
    //outputs:
    laser: { driver: 'led', pin: 7 },
    redLed: { driver: 'led', pin: 4 },
    greenLed: { driver: 'led', pin: 5 },
    blueLed: { driver: 'led', pin: 6 },

    //inputs:
    tilt: { driver: 'button', pin: 3 },
    button: { driver: 'button', pin: 2 },
    ambient: { driver: 'analog-sensor', pin: 3, lowerLimit: 100, upperLimit: 900 },
    color_detector: { driver: 'analog-sensor', pin: 0, lowerLimit: 0, upperLimit: 1024 },

  },
  work: function(my) {
    my.button.on('push', function() {
      my.laser.toggle();
    console.log("laser toggled");

    });

    every((1).seconds(), function() {
    //   console.log("Hello, human!");
    });

    var output_sound= function(color) {
    console.log(color + " detected");
    if (!talking){
        if (color === "red"){
          exec('sh red.sh',{silent:true});
        }
        if (color === "green"){
            exec('sh green.sh',{silent:true});
        }
        if (color === "blue"){
            exec('sh blue.sh',{silent:true});
        }
    }
    };

      my.tilt.on('push', function() {
          console.log("Tilt Activated");
          tilted = true;
      });
      my.tilt.on('release', function() {
          console.log("Tilt Deactivated");
          tilted = false;
      });

      var setRed = function(){
          my.redLed.turnOn()
          my.greenLed.turnOff()
          my.blueLed.turnOff()
      };
      var setBlue = function(){
          my.redLed.turnOff()
          my.greenLed.turnOff()
          my.blueLed.turnOn()
      }
      var setGreen = function(){
          my.redLed.turnOff()
          my.greenLed.turnOn()
          my.blueLed.turnOff()
      }
      var setOff = function(){
          my.redLed.turnOff()
          my.greenLed.turnOff()
          my.blueLed.turnOff()
      }

    var calibrate = function(cb){
            setRed();
            after((0.1).seconds(), function() {
                getReading(5, function(avgRead){
                    whiteArray.red = avgRead;
                    // console.log("Set white red to "+avgRead);
                    setBlue();
                    after((0.1).seconds(), function() {
                        getReading(5, function(avgRead){
                            whiteArray.blue = avgRead;
                            // console.log("Set white blue to "+avgRead);
                            setGreen();
                            after((0.1).seconds(), function() {
                                getReading(5, function(avgRead){
                                    whiteArray.green = avgRead;
                                    // console.log("Set white green to "+avgRead);
                                    setOff();
                                    after((5).seconds(), function() {
                                        setRed();
                                        after((0.1).seconds(), function() {
                                            getReading(5, function(avgRead){
                                                blackArray.red = avgRead;
                                                // console.log("Set black red to "+avgRead);
                                                setBlue();
                                                after((0.1).seconds(), function() {
                                                    getReading(5, function(avgRead){
                                                        blackArray.blue = avgRead;
                                                        // console.log("Set black blue to "+avgRead);
                                                        setGreen();
                                                        after((0.1).seconds(), function() {
                                                            getReading(5, function(avgRead){
                                                                blackArray.green = avgRead;
                                                                // console.log("Set black green to "+avgRead);
                                                                after((0.1).seconds(), function() {
                                                                    cb();
                                                                });
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        };

    var getReading = function(times, cb, tally, count){
        if (count ===0){
            var avgRead = (tally) / times;
            return cb(avgRead);
        }
        if (!tally){
            tally=0;
        }
        if (!count){
            count=times;
        }

        var reading = my.ambient.analogRead();
        tally = reading + tally;
        after((0.01).seconds(), function() {
            getReading(times, cb, tally, count-1);
        });
    };

    after((5).seconds(), function() {
        calibrate(function(){
            every((1).seconds(), function() {
            //   console.log("Check color");
                    setRed();
                    after((0.01).seconds(), function() {
                        getReading(5, function(avgRead){
                            colorArray.red = avgRead;
                            console.log("Set colorArray red to "+avgRead);
                            var greyDiff = whiteArray.red - blackArray.red;
                            colorArray.red = (colorArray.red - blackArray.red) / (greyDiff) * 255;//the reading returned minus the lowest value divided by the possible range multiplied by 255 is a value roughly between 0-255 representing the value
                            //for the current reflectivity(for the color it is exposed to) of what is being scanned
                            avgArray.red = (avgArray.red + colorArray.red) / 2;

                            setBlue();
                            after((0.01).seconds(), function() {
                                getReading(5, function(avgRead){
                                    colorArray.blue = avgRead;
                                    console.log("Set colorArray blue to "+avgRead);
                                    var greyDiff = whiteArray.blue - blackArray.blue;
                                    colorArray.blue = (colorArray.blue - blackArray.blue) / (greyDiff) * 255;//the reading returned minus the lowest value divided by the possible range multiplied by 255 is a value roughly between 0-255 representing the value
                                    //for the current reflectivity(for the color it is exposed to) of what is being scanned
                                    avgArray.blue = (avgArray.blue + colorArray.blue) / 2;
                                    setGreen();
                                    after((0.01).seconds(), function() {
                                        getReading(5, function(avgRead){
                                            colorArray.green = avgRead;
                                            console.log("Set colorArray green to "+avgRead);
                                            var greyDiff = whiteArray.green - blackArray.green;
                                            colorArray.green = (colorArray.green - blackArray.green) / (greyDiff) * 255;//the reading returned minus the lowest value divided by the possible range multiplied by 255 is a value roughly between 0-255 representing the value
                                            //for the current reflectivity(for the color it is exposed to) of what is being scanned
                                            avgArray.green = (avgArray.green + colorArray.green) / 2;
                                            after((0.01).seconds(), function() {
                                                setOff();
                                                if(avgArray.red > avgArray.green && avgArray.red > avgArray.blue) {
                                                    console.log("Detected Red");
                                                    output_sound("red");
                                                }
                                                else if(avgArray.green > avgArray.red && avgArray.green > avgArray.blue) {
                                                    console.log("Detected Green");
                                                    output_sound("green");

                                                }
                                                else {
                                                    console.log("Detected Blue");
                                                    output_sound("blue");
                                                }

                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
              });
            });
        });

    } //end setup

}).start();
<commit_msg>Granularity<commit_after>"use strict";

var Cylon = require('cylon')
var tilted = false;
var talking = false;
var leds = {red:2,blue:3,green:4};
var color = "";
var whiteArray = {red:0,blue:0,green:0};
var blackArray = {red:0,blue:0,green:0};
var colorArray = {red:0,blue:0,green:0};
var avgArray = {red:0,blue:0,green:0};

require('shelljs/global');

Cylon.robot({
  connections: {
    edison: { adaptor: 'intel-iot' }
  },
  devices: {
    //outputs:
    laser: { driver: 'led', pin: 7 },
    redLed: { driver: 'led', pin: 4 },
    greenLed: { driver: 'led', pin: 5 },
    blueLed: { driver: 'led', pin: 6 },

    //inputs:
    tilt: { driver: 'button', pin: 3 },
    button: { driver: 'button', pin: 2 },
    ambient: { driver: 'analog-sensor', pin: 3, lowerLimit: 100, upperLimit: 900 },
    color_detector: { driver: 'analog-sensor', pin: 0, lowerLimit: 0, upperLimit: 1024 },

  },
  work: function(my) {
    my.button.on('push', function() {
      my.laser.toggle();
    console.log("laser toggled");

    });

    every((1).seconds(), function() {
    //   console.log("Hello, human!");
    });

    var output_sound= function(color) {
    console.log(color + " detected");
    if (!talking){
        if (color === "red"){
          exec('sh red.sh',{silent:true});
        }
        if (color === "green"){
            exec('sh green.sh',{silent:true});
        }
        if (color === "blue"){
            exec('sh blue.sh',{silent:true});
        }
    }
    };

      my.tilt.on('push', function() {
          console.log("Tilt Activated");
          tilted = true;
      });
      my.tilt.on('release', function() {
          console.log("Tilt Deactivated");
          tilted = false;
      });

      var setRed = function(){
          my.redLed.turnOn()
          my.greenLed.turnOff()
          my.blueLed.turnOff()
      };
      var setBlue = function(){
          my.redLed.turnOff()
          my.greenLed.turnOff()
          my.blueLed.turnOn()
      }
      var setGreen = function(){
          my.redLed.turnOff()
          my.greenLed.turnOn()
          my.blueLed.turnOff()
      }
      var setOff = function(){
          my.redLed.turnOff()
          my.greenLed.turnOff()
          my.blueLed.turnOff()
      }

    var calibrate = function(cb){
            setRed();
            after((0.1).seconds(), function() {
                getReading(5, function(avgRead){
                    whiteArray.red = avgRead;
                    // console.log("Set white red to "+avgRead);
                    setBlue();
                    after((0.1).seconds(), function() {
                        getReading(5, function(avgRead){
                            whiteArray.blue = avgRead;
                            // console.log("Set white blue to "+avgRead);
                            setGreen();
                            after((0.1).seconds(), function() {
                                getReading(5, function(avgRead){
                                    whiteArray.green = avgRead;
                                    // console.log("Set white green to "+avgRead);
                                    setOff();
                                    after((5).seconds(), function() {
                                        setRed();
                                        after((0.1).seconds(), function() {
                                            getReading(5, function(avgRead){
                                                blackArray.red = avgRead;
                                                // console.log("Set black red to "+avgRead);
                                                setBlue();
                                                after((0.1).seconds(), function() {
                                                    getReading(5, function(avgRead){
                                                        blackArray.blue = avgRead;
                                                        // console.log("Set black blue to "+avgRead);
                                                        setGreen();
                                                        after((0.1).seconds(), function() {
                                                            getReading(5, function(avgRead){
                                                                blackArray.green = avgRead;
                                                                // console.log("Set black green to "+avgRead);
                                                                after((0.1).seconds(), function() {
                                                                    cb();
                                                                });
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        };

    var getReading = function(times, cb, tally, count){
        if (count ===0){
            var avgRead = (tally) / times;
            return cb(avgRead);
        }
        if (!tally){
            tally=0;
        }
        if (!count){
            count=times;
        }

        var reading = my.ambient.analogRead();
        tally = reading + tally;
        after((0.01).seconds(), function() {
            getReading(times, cb, tally, count-1);
        });
    };

    after((5).seconds(), function() {
        calibrate(function(){
            every((1).seconds(), function() {
            //   console.log("Check color");
                    setRed();
                    after((0.01).seconds(), function() {
                        getReading(5, function(avgRead){
                            colorArray.red = avgRead;
                            console.log("Set colorArray red to "+avgRead);
                            var greyDiff = whiteArray.red - blackArray.red;
                            colorArray.red = (colorArray.red - blackArray.red) / (greyDiff) * 1024;//the reading returned minus the lowest value divided by the possible range multiplied by 1024 is a value roughly between 0-1024 representing the value
                            //for the current reflectivity(for the color it is exposed to) of what is being scanned
                            avgArray.red = (avgArray.red + colorArray.red) / 2;

                            setBlue();
                            after((0.01).seconds(), function() {
                                getReading(5, function(avgRead){
                                    colorArray.blue = avgRead;
                                    console.log("Set colorArray blue to "+avgRead);
                                    var greyDiff = whiteArray.blue - blackArray.blue;
                                    colorArray.blue = (colorArray.blue - blackArray.blue) / (greyDiff) * 1024;//the reading returned minus the lowest value divided by the possible range multiplied by 1024 is a value roughly between 0-1024 representing the value
                                    //for the current reflectivity(for the color it is exposed to) of what is being scanned
                                    avgArray.blue = (avgArray.blue + colorArray.blue) / 2;
                                    setGreen();
                                    after((0.01).seconds(), function() {
                                        getReading(5, function(avgRead){
                                            colorArray.green = avgRead;
                                            console.log("Set colorArray green to "+avgRead);
                                            var greyDiff = whiteArray.green - blackArray.green;
                                            colorArray.green = (colorArray.green - blackArray.green) / (greyDiff) * 1024;//the reading returned minus the lowest value divided by the possible range multiplied by 1024 is a value roughly between 0-1024 representing the value
                                            //for the current reflectivity(for the color it is exposed to) of what is being scanned
                                            avgArray.green = (avgArray.green + colorArray.green) / 2;
                                            after((0.01).seconds(), function() {
                                                setOff();
                                                if(avgArray.red > avgArray.green && avgArray.red > avgArray.blue) {
                                                    console.log("Detected Red");
                                                    output_sound("red");
                                                }
                                                else if(avgArray.green > avgArray.red && avgArray.green > avgArray.blue) {
                                                    console.log("Detected Green");
                                                    output_sound("green");

                                                }
                                                else {
                                                    console.log("Detected Blue");
                                                    output_sound("blue");
                                                }

                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
              });
            });
        });

    } //end setup

}).start();
<|endoftext|>


<commit_before>import React from 'react';

// firebase
var firebaseEndpoint = 'https://metaseq-6b779.firebaseio.com/';
var Rebase = require('re-base');
import Firebase from 'firebase';
var base = Rebase.createClass(firebaseEndpoint);
var firebaseRoot = new Firebase(firebaseEndpoint);

// Component imports
import AddDatasetForm from './AddDatasetForm';
import Header from './Header';

/*
  AddDataset
  AddDataset list on right side of page
*/

var AddDataset = React.createClass({
    getInitialState: function() {
        var datasetId = (new Date()).getTime();
        return {
          'dataset':{
            'owner': 'nb',
            'fields': {}
          },
          'datasetId':datasetId
        }
    },

    componentWillMount: function() {
        this.ref = base.syncState('/datasets/' + this.state.datasetId, {
            context: this,
            state: 'dataset'
        });
    },

    componentWillUnmount: function() {
      base.removeBinding(this.ref);
    },

    addDataset : function(dataset) {
      this.state.dataset.fields = dataset;
      this.state.dataset.owner = 'nb';
      this.setState({ 'dataset' : this.state.dataset});
      this.props.history.push('/dataset/' + this.state.datasetId);
    },

    render: function() {
        return (

Dataset

            <AddDatasetForm addDataset={this.addDataset} datasetId={this.state.datasetId}/>

        )
    }
});

export default AddDataset;
<commit_msg>Add Dataset page cleanup<commit_after>import React from 'react';

// Firebase imports / setup
import Rebase from 're-base';
import Firebase from 'firebase';

// Material Design imports
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

// My component imports
import AddDatasetForm from './AddDatasetForm';
import Header from './Header';

// Firebase setup
var firebaseEndpoint = 'https://metaseq-6b779.firebaseio.com/';
var base = Rebase.createClass(firebaseEndpoint);
var firebaseRoot = new Firebase(firebaseEndpoint);

var AddDataset = React.createClass({
    getInitialState: function() {
        return {
          'dataset':{
            'owner': 'nb',
            'fields': {}
          },
          'datasetId':0
        }
    },
    componentWillMount: function() {
        var datasetId = (new Date()).getTime();
        this.state.datasetId = datasetId;
        this.ref = base.syncState('/datasets/' + this.state.datasetId, {
            context: this,
            state: 'dataset'
        });
        this.setState({ 'dataset' : this.state.dataset});
    },
    componentWillUnmount: function() {
      base.removeBinding(this.ref);
    },
    addDataset : function(dataset) {
      this.state.dataset.fields = dataset;
      this.state.dataset.owner = 'nb';
      this.setState({ 'dataset' : this.state.dataset});
    },
    render: function() {
        return (

Contribute a dataset

              <AddDatasetForm addDataset={this.addDataset} datasetId={this.state.datasetId} history={this.props.history}/>

        )
    }
});

export default AddDataset;
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const SERVICES_APP_PATH_REGEX = /\/var\/lib\/app/g;
const SERVICES_ABSOLUTE_PATH = 'services';
const SERVICES_RELATIVE_PATH = 'services';
const excludedServices = [ 'core' ];

function getServices(srcpath, exclude) {
  return fs.readdirSync(srcpath)
    .filter(file =>
      fs.statSync(path.join(srcpath, file)).isDirectory() &&
      !exclude.includes(file)
    );
}

fs.mkdirSync('coverage');
fs.mkdirSync('coverage/unit');
fs.mkdirSync('coverage/functional');

getServices(SERVICES_RELATIVE_PATH, excludedServices).forEach(service => {
  const serviceRelativePath = `${SERVICES_RELATIVE_PATH}/${service}`;
  const unitCoverageFile = `${serviceRelativePath}/unit_coverage/lcov.info`;
  const functionalCoverageFile = `${serviceRelativePath}/functional_coverage/lcov.info`;
  const newAbsolutePath = `${SERVICES_ABSOLUTE_PATH}/${service}`;

  const hasUnitCoverage = fs.existsSync(unitCoverageFile);
  const hasFunctionalCoverage = fs.existsSync(functionalCoverageFile);

  if (hasUnitCoverage) {
    const file = fs.readFileSync(unitCoverageFile, 'utf8').replace(SERVICES_APP_PATH_REGEX, newAbsolutePath);

    fs.writeFileSync(`coverage/unit/${service}.info`, file);
  } else {
    console.log(`No unit coverage report found for ${service}`);
  }

  if (hasFunctionalCoverage) {
    const file = fs.readFileSync(functionalCoverageFile, 'utf8').replace(SERVICES_APP_PATH_REGEX, newAbsolutePath);

    fs.writeFileSync(`coverage/functional/${service}.info`, file);
  } else {
    console.log(`No functional coverage report found for ${service}`);
  }
});
<commit_msg>keep src in new absolute path for coverage reports<commit_after>const fs = require('fs');
const path = require('path');

const SERVICES_APP_PATH_REGEX = /\/var\/lib\/app/g;
const SERVICES_ABSOLUTE_PATH = 'services';
const SERVICES_RELATIVE_PATH = 'services';
const excludedServices = [ 'core' ];

function getServices(srcpath, exclude) {
  return fs.readdirSync(srcpath)
    .filter(file =>
      fs.statSync(path.join(srcpath, file)).isDirectory() &&
      !exclude.includes(file)
    );
}

fs.mkdirSync('coverage');
fs.mkdirSync('coverage/unit');
fs.mkdirSync('coverage/functional');

getServices(SERVICES_RELATIVE_PATH, excludedServices).forEach(service => {
  const serviceRelativePath = `${SERVICES_RELATIVE_PATH}/${service}`;
  const unitCoverageFile = `${serviceRelativePath}/unit_coverage/lcov.info`;
  const functionalCoverageFile = `${serviceRelativePath}/functional_coverage/lcov.info`;
  const newAbsolutePath = `${SERVICES_ABSOLUTE_PATH}/${service}/src`;

  const hasUnitCoverage = fs.existsSync(unitCoverageFile);
  const hasFunctionalCoverage = fs.existsSync(functionalCoverageFile);

  if (hasUnitCoverage) {
    const file = fs.readFileSync(unitCoverageFile, 'utf8').replace(SERVICES_APP_PATH_REGEX, newAbsolutePath);

    fs.writeFileSync(`coverage/unit/${service}.info`, file);
  } else {
    console.log(`No unit coverage report found for ${service}`);
  }

  if (hasFunctionalCoverage) {
    const file = fs.readFileSync(functionalCoverageFile, 'utf8').replace(SERVICES_APP_PATH_REGEX, newAbsolutePath);

    fs.writeFileSync(`coverage/functional/${service}.info`, file);
  } else {
    console.log(`No functional coverage report found for ${service}`);
  }
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /**
     * @ngdoc controller
     * @name data-prep.export.controller:ExportCtrl
     * @description Export controller.
     * @requires data-prep.services.preparation.service:PreparationService
     * @requires data-prep.services.recipe.service:RecipeService
     * @requires data-prep.services.utils.service:RestURLs
     * @requires data-prep.services.export.service:ExportService
     */
    function ExportCtrl($timeout, state, PreparationService, RecipeService, RestURLs, ExportService) {
        var vm = this;
        vm.state = state;
        vm.preparationService = PreparationService;
        vm.recipeService = RecipeService;
        vm.exportService = ExportService;

        /**
         * @ngdoc property
         * @name currentExportType
         * @propertyOf data-prep.export.controller:ExportCtrl
         * @description Current export type
         * @type {Object}
         */
        vm.currentExportType = null;

        /**
         * @ngdoc property
         * @name currentExportParameters
         * @propertyOf data-prep.export.controller:ExportCtrl
         * @description Current export parameters model, bound to form inputs
         * @type {Object}
         */
        vm.currentExportParameters = null;

        /**
         * @ngdoc method
         * @name resetCurrentParameters
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Reset current export parameters with the saved one from localStorage
         */
        vm.resetCurrentParameters = function resetCurrentParameters() {
            vm.currentExportParameters = ExportService.getParameters();
            vm.currentExportType = ExportService.getType(vm.currentExportParameters.exportType);
        };

        /**
         * @ngdoc method
         * @name changeTypeAndExport
         * @methodOf data-prep.export.controller:ExportCtrl
         * @param {object} exportType The export type
         * @description Change the export type and launch the export.
         * If the export type has parameters, we init the form and display a modal
         */
        vm.changeTypeAndExport = function (exportType) {
            var parameters = {exportType: exportType.id};
            vm.currentExportType = exportType;
            vm.currentExportParameters = parameters;

            if (exportType.parameters) {
                _.forEach(exportType.parameters, function(param) {
                    parameters['exportParameters.' + param.name] = param.defaultValue.value;
                    //hack for fileName as we don't know it with exportTypes parameters
                    //so if empty use the dataset.name
                    if (param.name === 'fileName'){
                        var allParameters = ExportService.getParameters();
                        if (allParameters && allParameters['exportParameters.fileName']){
                            parameters['exportParameters.' + param.name] = allParameters['exportParameters.fileName'];
                        } else {
                            parameters['exportParameters.' + param.name] = vm.state.playground.dataset.name;
                        }
                    }
                });
                vm.showModal = true;
            }
            else {
                ExportService.setParameters(parameters);
                $timeout(vm.export);
            }
        };

        /**
         * @ngdoc method
         * @name saveEditionAndExport
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Save the currently edited export parameters and launch the export
         */
        vm.saveEditionAndExport = function saveEditionAndExport() {
            ExportService.setParameters(vm.currentExportParameters);
            $timeout(vm.export);
        };

        /**
         * @ngdoc method
         * @name export
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Launch the export
         */
        vm.export = function () {
            vm.form.action = RestURLs.exportUrl;
            vm.form.submit();
        };

        // get types list
        ExportService.refreshTypes()
            .then(vm.resetCurrentParameters);
    }

    /**
     * @ngdoc property
     * @name stepId
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The current stepId
     * It is bound to {@link data-prep.services.recipe.service:RecipeService RecipeService}.getLastActiveStep()
     */
    Object.defineProperty(ExportCtrl.prototype,
        'stepId', {
            enumerable: true,
            configurable: false,
            get: function () {
                var step = this.recipeService.getLastActiveStep();
                return step ? step.transformation.stepId : '';
            }
        });

    /**
     * @ngdoc property
     * @name datasetId
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The current dataset id
     * It is bound to {@link data-prep.services.state.constant:state state} property
     */
    Object.defineProperty(ExportCtrl.prototype,
        'datasetId', {
            enumerable: true,
            configurable: false,
            get: function () {
                var dataset = this.state.playground.dataset;
                return dataset ? dataset.id : '';
            }
        });

    /**
     * @ngdoc property
     * @name exportTypes
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The export types list
     * It is bound to {@link data-prep.services.export.service:ExportService ExportService} property
     */
    Object.defineProperty(ExportCtrl.prototype,
        'exportTypes', {
            enumerable: true,
            configurable: false,
            get: function () {
                return this.exportService.exportTypes;
            }
        });

    angular.module('data-prep.export')
        .controller('ExportCtrl', ExportCtrl);
})();<commit_msg>[TDP-188] prefer preparation.name as default if any.<commit_after>(function () {
    'use strict';

    /**
     * @ngdoc controller
     * @name data-prep.export.controller:ExportCtrl
     * @description Export controller.
     * @requires data-prep.services.preparation.service:PreparationService
     * @requires data-prep.services.recipe.service:RecipeService
     * @requires data-prep.services.utils.service:RestURLs
     * @requires data-prep.services.export.service:ExportService
     */
    function ExportCtrl($timeout, state, PreparationService, RecipeService, RestURLs, ExportService) {
        var vm = this;
        vm.state = state;
        vm.preparationService = PreparationService;
        vm.recipeService = RecipeService;
        vm.exportService = ExportService;

        /**
         * @ngdoc property
         * @name currentExportType
         * @propertyOf data-prep.export.controller:ExportCtrl
         * @description Current export type
         * @type {Object}
         */
        vm.currentExportType = null;

        /**
         * @ngdoc property
         * @name currentExportParameters
         * @propertyOf data-prep.export.controller:ExportCtrl
         * @description Current export parameters model, bound to form inputs
         * @type {Object}
         */
        vm.currentExportParameters = null;

        /**
         * @ngdoc method
         * @name resetCurrentParameters
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Reset current export parameters with the saved one from localStorage
         */
        vm.resetCurrentParameters = function resetCurrentParameters() {
            vm.currentExportParameters = ExportService.getParameters();
            vm.currentExportType = ExportService.getType(vm.currentExportParameters.exportType);
        };

        /**
         * @ngdoc method
         * @name changeTypeAndExport
         * @methodOf data-prep.export.controller:ExportCtrl
         * @param {object} exportType The export type
         * @description Change the export type and launch the export.
         * If the export type has parameters, we init the form and display a modal
         */
        vm.changeTypeAndExport = function (exportType) {
            var parameters = {exportType: exportType.id};
            vm.currentExportType = exportType;
            vm.currentExportParameters = parameters;

            if (exportType.parameters) {
                _.forEach(exportType.parameters, function(param) {
                    parameters['exportParameters.' + param.name] = param.defaultValue.value;
                    //hack for fileName as we don't know it with exportTypes parameters
                    //so if empty use the dataset.name
                    if (param.name === 'fileName'){
                        var allParameters = ExportService.getParameters();
                        if (allParameters && allParameters['exportParameters.fileName']){
                            parameters['exportParameters.' + param.name] = allParameters['exportParameters.fileName'];
                        } else if (vm.state.playground.preparation && vm.state.playground.preparation.name) {
                            parameters['exportParameters.' + param.name] = vm.state.playground.preparation.name;
                        } else {
                            parameters['exportParameters.' + param.name] = vm.state.playground.dataset.name;
                        }
                    }
                });
                vm.showModal = true;
            }
            else {
                ExportService.setParameters(parameters);
                $timeout(vm.export);
            }
        };

        /**
         * @ngdoc method
         * @name saveEditionAndExport
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Save the currently edited export parameters and launch the export
         */
        vm.saveEditionAndExport = function saveEditionAndExport() {
            ExportService.setParameters(vm.currentExportParameters);
            $timeout(vm.export);
        };

        /**
         * @ngdoc method
         * @name export
         * @methodOf data-prep.export.controller:ExportCtrl
         * @description Launch the export
         */
        vm.export = function () {
            vm.form.action = RestURLs.exportUrl;
            vm.form.submit();
        };

        // get types list
        ExportService.refreshTypes()
            .then(vm.resetCurrentParameters);
    }

    /**
     * @ngdoc property
     * @name stepId
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The current stepId
     * It is bound to {@link data-prep.services.recipe.service:RecipeService RecipeService}.getLastActiveStep()
     */
    Object.defineProperty(ExportCtrl.prototype,
        'stepId', {
            enumerable: true,
            configurable: false,
            get: function () {
                var step = this.recipeService.getLastActiveStep();
                return step ? step.transformation.stepId : '';
            }
        });

    /**
     * @ngdoc property
     * @name datasetId
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The current dataset id
     * It is bound to {@link data-prep.services.state.constant:state state} property
     */
    Object.defineProperty(ExportCtrl.prototype,
        'datasetId', {
            enumerable: true,
            configurable: false,
            get: function () {
                var dataset = this.state.playground.dataset;
                return dataset ? dataset.id : '';
            }
        });

    /**
     * @ngdoc property
     * @name exportTypes
     * @propertyOf data-prep.export.controller:ExportCtrl
     * @description The export types list
     * It is bound to {@link data-prep.services.export.service:ExportService ExportService} property
     */
    Object.defineProperty(ExportCtrl.prototype,
        'exportTypes', {
            enumerable: true,
            configurable: false,
            get: function () {
                return this.exportService.exportTypes;
            }
        });

    angular.module('data-prep.export')
        .controller('ExportCtrl', ExportCtrl);
})();<|endoftext|>


<commit_before>function checkSignup(){

   var username1= document.getElementById("username").value;
   var username2=document.getElementById("username2").value;
   var psw1= document.getElementById("psw").value;
   var psw2=document.getElementById("psw2").value;
   if(username1==="" || username1 ===null)
   {
      document.getElementById("textUser1").innerHTML="username should not be empty";
      return false;
   }
  else{
    if(username2===""|| username2===null)
    {
      document.getElementById("textUser2").innerHTML="you should confirm your username";
      return false;
    }
    else if(username2!= username1)
    {
      document.getElementById("textUser2").innerHTML="";
      document.getElementById("textUser2").innerHTML="failed to confirm your username ";
      return false;
    }
    else if(psw==="" || psw===null)
    {
      document.getElementById("textPsw1").innerHTML="password should not be empty";
      return false;
    }
    else if(psw2==="" || psw2===null)
    {
      document.getElementById("textPsw2").innerHTML="you should confirm your password";
      return false;
    }
    else if(psw2!= psw1)
    {
      document.getElementById("textPsw2").innerHTML="";
      document.getElementById("textPsw2").innerHTML="failed to confirm your password ";
      return false;
    }
    else
    return true;

  }

}
// ajax function for sign up
$(document).ready(function() {

    //Stops the submit request
    $("#signupForm").submit(function(e){
           e.preventDefault();
    });
    //checks for the button click event
        $("#submit").click(function(e){

                //get the form data and then serialize that
                dataString = $("#signupForm").serialize();

                //get the form data using another method
                var username = $("input#username").val();
                //dataString =  username;

                alert(username);
                //make the AJAX request, dataType is set to json
                //meaning we are expecting JSON data in response from the server
                $.ajax({
                    type: "GET",
                    url: "/api/checkuser/:name",
                    data: username,
                    dataType: "json",

                    //if received a response from the server
                    success: function( data, textStatus, jqXHR) {
                        //our country code was correct so we have some information to display
                         if(data.success){
                            //  $("#ajaxResponse").html("");
                            //  $("#ajaxResponse").append("Country Code: " + data.countryInfo.code + "
");
                            //  $("#ajaxResponse").append("Country Name: " + data.countryInfo.name + "
");
                            //  $("#ajaxResponse").append("Continent: " + data.countryInfo.continent + "
");
                            //  $("#ajaxResponse").append("Region: " + data.countryInfo.region + "
");
                            //  $("#ajaxResponse").append("Life Expectancy: " + data.countryInfo.lifeExpectancy + "
");
                            //  $("#ajaxResponse").append("GNP: " + data.countryInfo.gnp + "
");
                         }
                         //display error message
                         else {
                             $("#ajaxResponse").html("
Country code in Invalid!
");
                         }
                    },

                    //If there was no resonse from the server
                    error: function(jqXHR, textStatus, errorThrown){
                         console.log("Something really bad happened " + textStatus);
                          $("#ajaxResponse").html(jqXHR.responseText);
                    },

                    //capture the request before it was sent to server
                    beforeSend: function(jqXHR, settings){
                        //adding some Dummy data to the request
                        settings.data += "&dummyData=whatever";
                        //disable the button until we get the response
                        $('#myButton').attr("disabled", true);
                    },

                    //this is called after the response or error functions are finsihed
                    //so that we can take some action
                    complete: function(jqXHR, textStatus){
                        //enable the button
                        $('#myButton').attr("disabled", false);
                    }

                });
        });

    });
<commit_msg>update<commit_after>function checkSignup(){

   var username1= document.getElementById("username").value;
   var username2=document.getElementById("username2").value;
   var psw1= document.getElementById("psw").value;
   var psw2=document.getElementById("psw2").value;
   if(username1==="" || username1 ===null)
   {
      document.getElementById("textUser1").innerHTML="username should not be empty";
      return false;
   }
  else{
    if(username2===""|| username2===null)
    {
      document.getElementById("textUser2").innerHTML="you should confirm your username";
      return false;
    }
    else if(username2!= username1)
    {
      document.getElementById("textUser2").innerHTML="";
      document.getElementById("textUser2").innerHTML="failed to confirm your username ";
      return false;
    }
    else if(psw==="" || psw===null)
    {
      document.getElementById("textPsw1").innerHTML="password should not be empty";
      return false;
    }
    else if(psw2==="" || psw2===null)
    {
      document.getElementById("textPsw2").innerHTML="you should confirm your password";
      return false;
    }
    else if(psw2!= psw1)
    {
      document.getElementById("textPsw2").innerHTML="";
      document.getElementById("textPsw2").innerHTML="failed to confirm your password ";
      return false;
    }
    else
    return true;

  }

}
// ajax function for sign up
$(document).ready(function() {

    //Stops the submit request
    $("#signupForm").submit(function(e){
           e.preventDefault();
    });
    //checks for the button click event
        $("#submit").click(function(e){

                //get the form data and then serialize that
                dataString = $("#signupForm").serialize();

                //get the form data using another method
                var username = $("input#username").val();
                //dataString =  username;
                console.log(username);
                alert(username);
                //make the AJAX request, dataType is set to json
                //meaning we are expecting JSON data in response from the server
                $.ajax({
                    type: "GET",
                    url: "/api/checkuser/:name",
                    data: username,
                    dataType: "json",

                    //if received a response from the server
                    success: function( data, textStatus, jqXHR) {
                        //our country code was correct so we have some information to display
                         if(data.success){
                            //  $("#ajaxResponse").html("");
                            //  $("#ajaxResponse").append("Country Code: " + data.countryInfo.code + "
");
                            //  $("#ajaxResponse").append("Country Name: " + data.countryInfo.name + "
");
                            //  $("#ajaxResponse").append("Continent: " + data.countryInfo.continent + "
");
                            //  $("#ajaxResponse").append("Region: " + data.countryInfo.region + "
");
                            //  $("#ajaxResponse").append("Life Expectancy: " + data.countryInfo.lifeExpectancy + "
");
                            //  $("#ajaxResponse").append("GNP: " + data.countryInfo.gnp + "
");
                         }
                         //display error message
                         else {
                             $("#ajaxResponse").html("
Country code in Invalid!
");
                         }
                    },

                    //If there was no resonse from the server
                    error: function(jqXHR, textStatus, errorThrown){
                         console.log("Something really bad happened " + textStatus);
                          $("#ajaxResponse").html(jqXHR.responseText);
                    },

                    //capture the request before it was sent to server
                    beforeSend: function(jqXHR, settings){
                        //adding some Dummy data to the request
                        settings.data += "&dummyData=whatever";
                        //disable the button until we get the response
                        $('#myButton').attr("disabled", true);
                    },

                    //this is called after the response or error functions are finsihed
                    //so that we can take some action
                    complete: function(jqXHR, textStatus){
                        //enable the button
                        $('#myButton').attr("disabled", false);
                    }

                });
        });

    });
<|endoftext|>


<commit_before>// features/step_definitions/stepDefinitions.js

var angularPage = require('../pages/homePage.js');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

module.exports = function() {
  this.Given(/^I go to "([^"]*)"$/, function(site) {
    //browser.get(site);
    angularPage.go(site);
  });

  this.When(/^I add "([^"]*)" in the task field$/, function(task) {
    //element(by.model('todoList.todoText')).sendKeys(task);
    angularPage.addTask(task);
  });

  this.When(/^I click the add button$/, function() {
    //var el = element(by.css('[value="add"]'));
    //el.click();
    angularPage.submitTask();
  });

  this.Then(/^I should see my new task in the list$/, function(callback) {
    var todoList = angularPage.angularHomepage.todoList;
    expect(todoList.count()).to.eventually.equal(3);
    expect(todoList.get(2).getText()).to.eventually.equal('Be Awesome')
      .and.notify(callback);
  });
};
<commit_msg>Update step def<commit_after>// features/step_definitions/stepDefinitions.js
var angularPage = require('../pages/homePage.js');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

module.exports = function() {
  this.Given(/^I go to "([^"]*)"$/, function(site, next) {
    //browser.get(site);
    angularPage.go(site);
    expect(browser.getTitle()).to.eventually.equal('AngularJS — Superheroic JavaScript MVW Framework').and.notify(next);
  });

  this.When(/^I add "([^"]*)" in the task field$/, function(task, next) {
    //element(by.model('todoList.todoText')).sendKeys(task);
    angularPage.addTask(task);
    next();
  });

  this.When(/^I click the add button$/, function(next) {
    //var el = element(by.css('[value="add"]'));
    //el.click();
    angularPage.submitTask();
    next();
  });

  this.Then(/^I should see my new task in the list$/, function(next) {
    var todoList = angularPage.angularHomepage.todoList;
    expect(todoList.count()).to.eventually.equal(3);
    expect(todoList.get(2).getText()).to.eventually.equal('Be Awesome')
      .and.notify(next);
  });
};
<|endoftext|>