<commit_before>var Surface = require('@src/traces/surface');

describe('Test surface', function() {
    'use strict';

    describe('supplyDefaults', function() {
        var supplyDefaults = Surface.supplyDefaults;

        var defaultColor = '#444',
            layout = {};

        var traceIn, traceOut;

        beforeEach(function() {
            traceOut = {};
        });

        it('should set \'visible\' to false if \'z\' isn\'t provided', function() {
            traceIn = {};

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.visible).toBe(false);
        });

        it('should fill \'x\' and \'y\' if not provided', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]]
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.x).toEqual([0,1,2]);
            expect(traceOut.y).toEqual([0,1]);
        });

        it('should coerce \'project\' if contours or highlight lines are enabled', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                contours: {
                    x: { show: true }
                }
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.contours.x.project).toEqual({ x: false, y: false, z: false });
            expect(traceOut.contours.y).toEqual({ show: false, highlight: false });
            expect(traceOut.contours.z).toEqual({ show: false, highlight: false });
        });

        it('should coerce contour style attributes if contours lines are enabled', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                contours: {
                    x: { show: true }
                }
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.contours.x.color).toEqual('#000');
            expect(traceOut.contours.x.width).toEqual(2);
            expect(traceOut.contours.x.usecolormap).toEqual(false);

            ['y', 'z'].forEach(function(ax) {
                expect(traceOut.contours[ax].color).toBeUndefined();
                expect(traceOut.contours[ax].width).toBeUndefined();
                expect(traceOut.contours[ax].usecolormap).toBeUndefined();
            });
        });

        it('should coerce colorscale and colorbar attributes', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]]
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toBe(true);
            expect(traceOut.cmin).toBeUndefined();
            expect(traceOut.cmax).toBeUndefined();
            expect(traceOut.colorscale).toEqual([
                [0, 'rgb(5,10,172)'],
                [0.35, 'rgb(106,137,247)'],
                [0.5, 'rgb(190,190,190)'],
                [0.6, 'rgb(220,170,132)'],
                [0.7, 'rgb(230,145,90)'],
                [1, 'rgb(178,10,28)']
            ]);
            expect(traceOut.showscale).toBe(true);
            expect(traceOut.colorbar).toBeDefined();
        });

        it('should coerce \'c\' attributes with \'z\' if \'c\' isn\'t present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                zauto: false,
                zmin: 0,
                zmax: 10
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(false);
            expect(traceOut.cmin).toEqual(0);
            expect(traceOut.cmax).toEqual(10);
        });

        it('should coerce \'c\' attributes with \'c\' values regardless of `\'z\' if \'c\' is present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                zauto: false,
                zmin: 0,
                zmax: 10,
                cauto: true,
                cmin: -10,
                cmax: 20
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(true);
            expect(traceOut.cmin).toEqual(-10);
            expect(traceOut.cmax).toEqual(20);
        });

        it('should default \'c\' attributes with if \'surfacecolor\' is present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                surfacecolor: [[2,1,2], [1,2,3]],
                zauto: false,
                zmin: 0,
                zmax: 10
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(true);
            expect(traceOut.cmin).toBeUndefined();
            expect(traceOut.cmax).toBeUndefined();
        });
    });
});
<commit_msg>update surface defaults tests<commit_after>var Surface = require('@src/traces/surface');

var Lib = require('@src/lib');

describe('Test surface', function() {
    'use strict';

    describe('supplyDefaults', function() {
        var supplyDefaults = Surface.supplyDefaults;

        var defaultColor = '#444',
            layout = {};

        var traceIn, traceOut;

        beforeEach(function() {
            traceOut = {};
        });

        it('should set \'visible\' to false if \'z\' isn\'t provided', function() {
            traceIn = {};

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.visible).toBe(false);
        });

        it('should fill \'x\' and \'y\' if not provided', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]]
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.x).toEqual([0,1,2]);
            expect(traceOut.y).toEqual([0,1]);
        });

        it('should coerce \'project\' if contours or highlight lines are enabled', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                contours: {
                    x: {},
                    y: { show: true },
                    z: { show: false, highlight: false }
                }
            };

            var fullOpts = {
                show: false,
                highlight: true,
                project: { x: false, y: false, z: false },
                highlightcolor: '#444',
                highlightwidth: 2
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.contours.x).toEqual(fullOpts);
            expect(traceOut.contours.y).toEqual(Lib.extendDeep({}, fullOpts, {
                show: true,
                color: '#444',
                width: 2,
                usecolormap: false
            }));
            expect(traceOut.contours.z).toEqual({ show: false, highlight: false });
        });

        it('should coerce contour style attributes if contours lines are enabled', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                contours: {
                    x: { show: true }
                }
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.contours.x.color).toEqual('#444');
            expect(traceOut.contours.x.width).toEqual(2);
            expect(traceOut.contours.x.usecolormap).toEqual(false);

            ['y', 'z'].forEach(function(ax) {
                expect(traceOut.contours[ax].color).toBeUndefined();
                expect(traceOut.contours[ax].width).toBeUndefined();
                expect(traceOut.contours[ax].usecolormap).toBeUndefined();
            });
        });

        it('should coerce colorscale and colorbar attributes', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]]
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toBe(true);
            expect(traceOut.cmin).toBeUndefined();
            expect(traceOut.cmax).toBeUndefined();
            expect(traceOut.colorscale).toEqual([
                [0, 'rgb(5,10,172)'],
                [0.35, 'rgb(106,137,247)'],
                [0.5, 'rgb(190,190,190)'],
                [0.6, 'rgb(220,170,132)'],
                [0.7, 'rgb(230,145,90)'],
                [1, 'rgb(178,10,28)']
            ]);
            expect(traceOut.showscale).toBe(true);
            expect(traceOut.colorbar).toBeDefined();
        });

        it('should coerce \'c\' attributes with \'z\' if \'c\' isn\'t present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                zauto: false,
                zmin: 0,
                zmax: 10
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(false);
            expect(traceOut.cmin).toEqual(0);
            expect(traceOut.cmax).toEqual(10);
        });

        it('should coerce \'c\' attributes with \'c\' values regardless of `\'z\' if \'c\' is present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                zauto: false,
                zmin: 0,
                zmax: 10,
                cauto: true,
                cmin: -10,
                cmax: 20
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(true);
            expect(traceOut.cmin).toEqual(-10);
            expect(traceOut.cmax).toEqual(20);
        });

        it('should default \'c\' attributes with if \'surfacecolor\' is present', function() {
            traceIn = {
                z: [[1,2,3], [2,1,2]],
                surfacecolor: [[2,1,2], [1,2,3]],
                zauto: false,
                zmin: 0,
                zmax: 10
            };

            supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.cauto).toEqual(true);
            expect(traceOut.cmin).toBeUndefined();
            expect(traceOut.cmax).toBeUndefined();
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

const Post = require('../../models/Post');

const getPosts = async (req,res,next) => {

  try {
    req.posts = await Post.find({isRoot: true})
      .populate('_user')
      .collation({locale: 'en'})
      .sort({updatedAt: 'desc'})
      .limit(100);

    next();
  } catch(error) {
    next(error);
  }
};

module.exports = exports = getPosts;
<commit_msg>reduce posts limit<commit_after>'use strict';

const Post = require('../../models/Post');

const getPosts = async (req,res,next) => {

  try {
    req.posts = await Post.find({isRoot: true})
      .populate('_user')
      .collation({locale: 'en'})
      .sort({updatedAt: 'desc'})
      .limit(40);

    next();
  } catch(error) {
    next(error);
  }
};

module.exports = exports = getPosts;
<|endoftext|>


<commit_before>'use strict';

describe('ngTranslationProvider', function() {

  var loaderResult;

  //Provider
  function langsFiles(files) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.langsFiles(files);
    }
  }

  function addLangFile(file) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.addLangFile(file);
    }
  }

  function langsValues(values) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.langsValues(values);
    }
  }

  function setFilesSuffix(sfx) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.setFilesSuffix(sfx)
    }
  }

  function setBaseUrl(url) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.setBaseUrl(url);
    }
  }

  function setFallbackLanguage(name) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.fallbackLanguage(name);
    }
  }

  //Mocks
  function staticFilesLoaderMock($timeout, $q) {
    //mock the http request
    return {
      get: function(options) {
        var deferred = $q.defer();

        $timeout(function() {
          var object = {};

          object[options.key] = loaderResult[options.key];

          deferred.resolve(object);
        });
        return deferred.promise;
      }
    };
  }

  //Actions
  function setLoaderResult(result) {
    return loaderResult = result;
  }

  beforeEach(module('ng-translation.provider', function ($provide) {
    //Dependency as a mock
    $provide.factory('staticFilesLoader', staticFilesLoaderMock);
  }));

  describe('test setters', function() {

    //langsFiles
    it('should be able to set staticFiles', function() {
      var files = { login: '/login_page',  logout: '/logout_page' };
      module(langsFiles(files));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsFiles).toEqual(files);
      });
    });

    //addLangFile
    it('should able to add lang file', function() {
      var file = { foo: '/foo' };
      module(addLangFile(file));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsFiles).toEqual(file);
      });
    });

    //langsValues
    it('should be able to set langsValues', function() {
      var values = ['demo1', 'demo2', 'demo3'];
      module(langsValues(values));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsValues).toEqual(values);
      });
    });

    //setBaseUrl
    it('should add able to set base url', function() {
      var url = 'app/static';
      module(setBaseUrl(url));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.baseUrl).toEqual(url);
      });
    });

    //setDirectory
    it('should add able to use setDirectory to set baseUrl', function() {
      module(function(ngTranslationProvider) {
        ngTranslationProvider
          .setDirectory('/app/static');
      });
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.baseUrl).toEqual('/app/static');
      })
    });

    //setFilesSuffix
    it('should be able to set suffix for all files', function() {
      module(setFilesSuffix('.json'));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.suffix).toEqual('.json');
      });
    });

    //fallbackLanguage
    it('should be able to set fallback language', function() {
      module(setFallbackLanguage('en'));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.fallbackLanguage).toEqual('en');
      });
    });

  });

  //api object
  describe('api object', function() {

    var mockResult;

    beforeEach(function() {
      //module
      module(
        langsFiles({ login: '/login', logout: 'logout', en: 'en' }),
        setFilesSuffix('.json'),
        setBaseUrl('/app/static')
      );
      //inject
      inject(function(ngTranslation, $timeout) {
        mockResult = { login: { foo: 'bar' }, logout: { foo: 'baz' }, en: {} };
        setLoaderResult(mockResult);
        ngTranslation.init();

        $timeout.flush();
      });
    });

    it('should call staticFilesLoader', inject(function(ngTranslation, staticFilesLoader) {
      var spy = spyOn(staticFilesLoader, 'get');
      ngTranslation.init();

      expect(spy)
        .toHaveBeenCalledWith({ baseUrl : '/app/static', suffix : '.json', value : '/login', key : 'login' });
      expect(spy)
        .toHaveBeenCalledWith({ baseUrl : '/app/static', suffix : '.json', value : '/logout', key : 'logout' });
    }));

    it('should return the file if exist', inject(function(ngTranslation) {
      expect(ngTranslation.get('login')).toEqual(mockResult.login);
      expect(ngTranslation.get('login')).not.toEqual(mockResult.logout);
      expect(ngTranslation.get('logout')).toEqual(mockResult.logout);
      expect(ngTranslation.get('logout')).not.toEqual(mockResult.login);
    }));

    it('should return first file/default is the file not exist', inject(function(ngTranslation) {
      expect(ngTranslation.get('homepage')).toEqual(mockResult.login);
      expect(ngTranslation.get('api')).toEqual(mockResult.login);
    }));

    it('should return allFiles', inject(function(ngTranslation) {
      expect(ngTranslation.getAll()).toEqual(mockResult);
    }));

    it('should return the used language if exist', inject(function(ngTranslation) {
      expect(ngTranslation.getUsed()).toBeUndefined();
      ngTranslation.use('en');
      expect(ngTranslation.getUsed()).toEqual(mockResult.en)
    }));

  });

  //external behavior
  describe('external behavior', function() {

    it('should be friendly with files path', function() {
      module(langsFiles({ homepage: 'homepage.json' }));
      inject(function(ngTranslation, staticFilesLoader) {
        var spy = spyOn(staticFilesLoader, 'get');
        ngTranslation.init();
        expect(spy).toHaveBeenCalledWith({ baseUrl: '', value: '/homepage.json', key: 'homepage', suffix: undefined });
      });
    });

  });

  describe('load static values api', function() {
    var v1 = { foo: 'bar' }, v2 = { foo: 'baz' };

    //mock services and set static values in the providers phase
      beforeEach(module(function($provide) {
        $provide.value('value1', v1);
        $provide.value('value2', v2);
      }, langsValues([ 'value1', 'value2' ]))
    );

    it('should all values as a files', inject(function(ngTranslation) {
      ngTranslation.init();
      expect(ngTranslation.get('value1')).toEqual(v1);
      expect(ngTranslation.get('value2')).toEqual(v2);
      expect(ngTranslation.getAll()).toEqual({ value1: v1, value2: v2 });
    }));

  });

});
<commit_msg>test(ngTranslation): fallback language<commit_after>'use strict';

describe('ngTranslationProvider', function() {

  var loaderResult;

  //Provider
  function langsFiles(files) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.langsFiles(files);
    }
  }

  function addLangFile(file) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.addLangFile(file);
    }
  }

  function langsValues(values) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.langsValues(values);
    }
  }

  function setFilesSuffix(sfx) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.setFilesSuffix(sfx)
    }
  }

  function setBaseUrl(url) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.setBaseUrl(url);
    }
  }

  function setFallbackLanguage(name) {
    return function(ngTranslationProvider) {
      ngTranslationProvider.fallbackLanguage(name);
    }
  }

  //Mocks
  function staticFilesLoaderMock($timeout, $q) {
    //mock the http request
    return {
      get: function(options) {
        var deferred = $q.defer();

        $timeout(function() {
          var object = {};

          object[options.key] = loaderResult[options.key];

          deferred.resolve(object);
        });
        return deferred.promise;
      }
    };
  }

  //Actions
  function setLoaderResult(result) {
    return loaderResult = result;
  }

  beforeEach(module('ng-translation.provider', function ($provide) {
    //Dependency as a mock
    $provide.factory('staticFilesLoader', staticFilesLoaderMock);
  }));

  describe('test setters', function() {

    //langsFiles
    it('should be able to set staticFiles', function() {
      var files = { login: '/login_page',  logout: '/logout_page' };
      module(langsFiles(files));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsFiles).toEqual(files);
      });
    });

    //addLangFile
    it('should able to add lang file', function() {
      var file = { foo: '/foo' };
      module(addLangFile(file));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsFiles).toEqual(file);
      });
    });

    //langsValues
    it('should be able to set langsValues', function() {
      var values = ['demo1', 'demo2', 'demo3'];
      module(langsValues(values));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.langsValues).toEqual(values);
      });
    });

    //setBaseUrl
    it('should add able to set base url', function() {
      var url = 'app/static';
      module(setBaseUrl(url));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.baseUrl).toEqual(url);
      });
    });

    //setDirectory
    it('should add able to use setDirectory to set baseUrl', function() {
      module(function(ngTranslationProvider) {
        ngTranslationProvider
          .setDirectory('/app/static');
      });
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.baseUrl).toEqual('/app/static');
      })
    });

    //setFilesSuffix
    it('should be able to set suffix for all files', function() {
      module(setFilesSuffix('.json'));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.suffix).toEqual('.json');
      });
    });

    //fallbackLanguage
    it('should be able to set fallback language', function() {
      module(setFallbackLanguage('en'));
      inject(function(ngTranslation) {
        expect(ngTranslation.configuration.fallbackLanguage).toEqual('en');
      });
    });

  });

  //api object
  describe('api object', function() {

    var mockResult;

    beforeEach(function() {
      //module
      module(
        langsFiles({ login: '/login', logout: 'logout', en: 'en', de: 'de' }),
        setFilesSuffix('.json'),
        setBaseUrl('/app/static'),
        setFallbackLanguage('de')
      );
      //inject
      inject(function(ngTranslation, $timeout) {
        mockResult = { login: { foo: 'bar' }, logout: { foo: 'baz' }, en: {}, de: [] };
        setLoaderResult(mockResult);
        ngTranslation.init();

        $timeout.flush();
      });
    });

    it('should call staticFilesLoader', inject(function(ngTranslation, staticFilesLoader) {
      var spy = spyOn(staticFilesLoader, 'get');
      ngTranslation.init();

      expect(spy)
        .toHaveBeenCalledWith({ baseUrl : '/app/static', suffix : '.json', value : '/login', key : 'login' });
      expect(spy)
        .toHaveBeenCalledWith({ baseUrl : '/app/static', suffix : '.json', value : '/logout', key : 'logout' });
    }));

    it('should return the file if exist', inject(function(ngTranslation) {
      expect(ngTranslation.get('login')).toEqual(mockResult.login);
      expect(ngTranslation.get('login')).not.toEqual(mockResult.logout);
      expect(ngTranslation.get('logout')).toEqual(mockResult.logout);
      expect(ngTranslation.get('logout')).not.toEqual(mockResult.login);
    }));

    it('should return first file/default is the file not exist', inject(function(ngTranslation) {
      expect(ngTranslation.get('homepage')).toEqual(mockResult.login);
      expect(ngTranslation.get('api')).toEqual(mockResult.login);
    }));

    it('should return allFiles', inject(function(ngTranslation) {
      expect(ngTranslation.getAll()).toEqual(mockResult);
    }));

    it('should return the used language if exist', inject(function(ngTranslation) {
      expect(ngTranslation.getUsed()).toEqual(mockResult.de)
      ngTranslation.use('en');
      expect(ngTranslation.getUsed()).toEqual(mockResult.en)
    }));

    it('should return the fallback language if used not defined', inject(function(ngTranslation) {
        expect(ngTranslation.getUsed()).toEqual(mockResult.de)
    }));

  });

  //external behavior
  describe('external behavior', function() {

    it('should be friendly with files path', function() {
      module(langsFiles({ homepage: 'homepage.json' }));
      inject(function(ngTranslation, staticFilesLoader) {
        var spy = spyOn(staticFilesLoader, 'get');
        ngTranslation.init();
        expect(spy).toHaveBeenCalledWith({ baseUrl: '', value: '/homepage.json', key: 'homepage', suffix: undefined });
      });
    });

  });

  describe('load static values api', function() {
    var v1 = { foo: 'bar' }, v2 = { foo: 'baz' };

    //mock services and set static values in the providers phase
      beforeEach(module(function($provide) {
        $provide.value('value1', v1);
        $provide.value('value2', v2);
      }, langsValues([ 'value1', 'value2' ]))
    );

    it('should all values as a files', inject(function(ngTranslation) {
      ngTranslation.init();
      expect(ngTranslation.get('value1')).toEqual(v1);
      expect(ngTranslation.get('value2')).toEqual(v2);
      expect(ngTranslation.getAll()).toEqual({ value1: v1, value2: v2 });
    }));

  });

});
<|endoftext|>


<commit_before>const { hasStore } = require('../../server/lib/environment.js');

describe('hasStore', () => {

  test(`returns false when the DAV_ENV environment variable isn't set to 'simulated'`, () => {
    expect.assertions(1);
    if (process.env.DAV_ENV !== 'simulation') {
      expect(hasStore).toBe(false);
    }
  });

  test(`returns true when the DAV_ENV environment variable is set to 'simulated'`, () => {
    expect.assertions();
    if (process.env.DAV_ENV === 'simulation') {
      expect(hasStore).toBe(true);
    }
  });

});<commit_msg>removed second test<commit_after>const { hasStore } = require('../../server/lib/environment.js');

describe('hasStore', () => {

  test(`returns false when the DAV_ENV environment variable isn't set to 'simulated'`, () => {
    expect.assertions(1);
    if (process.env.DAV_ENV !== 'simulation') {
      expect(hasStore).toBe(false);
    }
  });
});<|endoftext|>


<commit_before>"use strict";

exports.generalInputToTestMultipleTestCases = {
    firstName: 'TIM',
    lastName:'DOE',
    middleName:'JOE',
    familyName:'',
    address:'',
    age:NaN,
    numbers:[],
    friends:[],
    groups:[1,2]
};

exports.templateToMapGeneralInput = {
    content: {
        firstName: {
            dataKey: 'firstName'
        },
        middleName: {
            dataKey: 'middleName'
        },
        lastName: {
            dataKey: 'lastName'
        },
        familyName: {
            dataKey: 'familyName'
        },
        address: {
            dataKey: 'address'
        },
        age: {
            dataKey: 'age'
        },
        numbers:{
            dataKey:'numbers'
        },
        friends:{
            dataKey:'friends'
        },
        groups:{
            dataKey:'groups'
        }
    }
};

exports.templateForDefaultValues={
    content: {
        firstName: {
            dataKey: 'firstName'
        },
        middleName: {
            dataKey: 'middleName'
        },
        lastName: {
            dataKey: 'lastName'
        },
        familyName: {
            dataKey: 'familyName',default: ""
        },
        address: {
            dataKey: 'address', default: ""
        },
        age: {
            dataKey: 'age',default:NaN
        },
        numbers:{
            dataKey:'numbers', default:[]
        },
        friends:{
            dataKey:'friends', default:[]
        },
        groups:{
            dataKey:'groups'
        }
    }
};

exports.outputForEmptyStringPresence =
{
    "address": "",
    "familyName": "",
    "firstName": "TIM",
    "groups": [1,2],
    "lastName": "DOE",
    "middleName": "JOE"
};
exports.outputForDefaultValues= {
    "address": "",
    "age": NaN,
    "familyName": "",
    "firstName": "TIM",
    "friends": [],
    "groups": [1,2],
    "lastName": "DOE",
    "middleName": "JOE",
    "numbers": []
};

exports.outputForNaNPresence={

    "age": NaN,
    "firstName": "TIM",
    "groups": [1,2],
    "lastName": "DOE",
    "middleName": "JOE"
};

exports.input = {
    a: {
        b: {
            c1: "i am key c1",
            c2: "",
            c3: undefined,
            c4: [],
            c5: NaN,
            c6:true,
            c7:false
        },
        d: NaN,
        e: "value a.e",
        f: [{
            firstName: "sampleFirstName",
            group: []
        },
            {
                firstName: "sampleFirstName",
                group: [1,3]
            },
            {
                firstName: "sampleFirstName",
                group: []
            }],
        g: {
            firstName: "sampleLastName",
            lastName: "",
            age: NaN,
            city: undefined,
            Numbers:[]
        },
        h:{
            firstName:"sampleFirstName",
            lastName: "",
            age: NaN,
            city: undefined,
            "h.a1":"I am Key with dot"
        },
        i:[{
            showWeather:true,
            weather:"sunny",
            temperature:"70F",
            city:"Dallas",
            days:["mon","tue","wed"]
        },
            {
                showWeather:true,
                weather:"",
                temperature:NaN,
                city:undefined,
                days:["thr","fri","sat"]
            },
            {
                showWeather:true,
                weather:"sunny",
                temperature:"70F",
                city:"Irving",
                days:[]
            },
            {
                showWeather:false,
                weather:"sunny",
                temperature:"70F",
                city:"Ft.Worth",
                days:[]
            }]

    }
};

var weatherTemplate = {
    existsWhen:function(data){
        return data.showWeather === true;
    },
    content: {
        weather: {dataKey: "weather"},
        temperature: {dataKey: "temperature"},
        city: {dataKey: "city"},
        days: {dataKey: "days"}
    }
};

exports.template = {
    content: {
        dest_a1: {
            dataKey: 'a.b.c1'
        },
        dest_a2: {
            dataKey: 'a.b.c2'
        },
        dest_a3: {
            dataKey: 'a.b.c3'
        },
        dest_a4: {
            dataKey: 'a.b.c4'
        },
        dest_a5: {
            dataKey: 'a.b.c5'
        },
        dest_a6: {
            dataKey: 'a.b.c6'
        },
        dest_a7: {
            dataKey: 'a.b.c7'
        },
        dest_b: {
            content: {
                dest_b0: {
                    value: function (data) {
                        return data.e;
                    }
                },
                dest_b1: {
                    dataKey: 'a.d',default:"I am Default for NaN"
                }
            },
            dataKey: 'a'
        },
        dest_d:{dataKey:"a.d"},
        dest_e:{dataKey:"a.e"},
        dest_f: {
            dataKey: "a.f",
            content: {
                firstName: {dataKey: "firstName"},
                group: {dataKey: "group"}
            }
        },
        dest_g:{
            dataKey:"a.g",
            content:{
                firstName:{dataKey:"firstName"},
                lastName: {dataKey:"lastName"},
                age: {dataKey:"age"},
                city: {dataKey:"city"},
                Numbers:{dataKey:"numbers",default:"1"},
                "dotValue":{dataKey:"h.a1"}
            }
        },
        dest_h:{
            ignoreDeep:true,
            content:{
                "dest.h1.firstName":{dataKey:"a.h.firstName"},
                "dest.h2.lastName":{dataKey:"a.h.lastName"}
            }
        },
        dest_i:{
            arrayContent:[{
                arrayContent :[ { dataKey:"a.i",value: weatherTemplate }],
                default : []
            }]
        }

    }
};

exports.expectedWithPruneOptions = {
    "dest_a1": "i am key c1",
    "dest_a6": true,
    "dest_a7": false,
    "dest_b": {
        "dest_b0": "value a.e",
        "dest_b1": "I am Default for NaN"
    },
    "dest_e": "value a.e",
    "dest_f": [{
        "firstName": "sampleFirstName"
    },
        {
            "firstName": "sampleFirstName",
            "group": [1,3]
        },
        {
            "firstName": "sampleFirstName"
        }],
    "dest_g": {
        "firstName": "sampleLastName",
        "Numbers": "1"
    },
    "dest_h": {
        "dest.h1.firstName": "sampleFirstName"
    },
    dest_i: [
        {
            "city": "Dallas",
            "temperature": "70F",
            "weather": "sunny",
            "days": [
                "mon",
                "tue",
                "wed"
            ]
        },
        {
            "days": [
                "thr",
                "fri",
                "sat"
            ]
        },
        {
            "city": "Irving",
            "temperature": "70F",
            "weather": "sunny"
        }
    ]
};

exports.expectedWithOutPruneOptions = {
    dest_a1: "i am key c1",
    dest_a2: "",
    dest_a4: [],
    dest_a5: NaN,
    dest_a6: true,
    dest_a7: false,
    dest_b: {
        dest_b0: "value a.e",
        dest_b1: "I am Default for NaN"
    },
    dest_d: NaN,
    dest_e: "value a.e",
    dest_f: [
        {
            firstName: "sampleFirstName",
            group: []
        },
        {
            firstName: "sampleFirstName",
            group: [1,3 ]
        },
        {
            firstName: "sampleFirstName",
            group: []
        }
    ],
    dest_g: {
        Numbers: "1",
        age: NaN,
        firstName: "sampleLastName",
        lastName: ""
    },
    dest_h: {
        "dest.h1.firstName": "sampleFirstName",
        "dest.h2.lastName": ""
    },
    "dest_i": [
        {
            "city": "Dallas",
            "days": [
                "mon",
                "tue",
                "wed"
            ],
            "temperature": "70F",
            "weather": "sunny"
        },
        {
            "days": [
                "thr",
                "fri",
                "sat"
            ],
            "temperature": NaN,
            "weather": ""
        },
        {
            "city": "Irving",
            "days": [],
            "temperature": "70F",
            "weather": "sunny"
        }
    ]
};

exports.expectedWithEmptyArrays = {
    "dest_a1": "i am key c1",
    "dest_a4": [],
    "dest_a6": true,
    "dest_a7": false,
    "dest_b": {
        "dest_b0": "value a.e",
        "dest_b1": "I am Default for NaN"
    },
    "dest_e": "value a.e",
    "dest_f": [{
        "firstName": "sampleFirstName",
        "group": []
    },
        {
            "firstName": "sampleFirstName",
            "group": [1,
                3]
        },
        {
            "firstName": "sampleFirstName",
            "group": []
        }],
    "dest_g": {
        "firstName": "sampleLastName",
        "Numbers": "1"
    },
    "dest_h": {
        "dest.h1.firstName": "sampleFirstName"
    },
    "dest_i": [
        {
            "city": "Dallas",
            "temperature": "70F",
            "weather": "sunny",
            "days": [
                "mon",
                "tue",
                "wed"
            ]
        },
        {
            "days": [
                "thr",
                "fri",
                "sat"
            ]
        },
        {
            "city": "Irving",
            "days": [],
            "temperature": "70F",
            "weather": "sunny"
        }
    ]
};<commit_msg>grunt code beautification changes<commit_after>"use strict";

exports.generalInputToTestMultipleTestCases = {
    firstName: 'TIM',
    lastName: 'DOE',
    middleName: 'JOE',
    familyName: '',
    address: '',
    age: NaN,
    numbers: [],
    friends: [],
    groups: [1, 2]
};

exports.templateToMapGeneralInput = {
    content: {
        firstName: {
            dataKey: 'firstName'
        },
        middleName: {
            dataKey: 'middleName'
        },
        lastName: {
            dataKey: 'lastName'
        },
        familyName: {
            dataKey: 'familyName'
        },
        address: {
            dataKey: 'address'
        },
        age: {
            dataKey: 'age'
        },
        numbers: {
            dataKey: 'numbers'
        },
        friends: {
            dataKey: 'friends'
        },
        groups: {
            dataKey: 'groups'
        }
    }
};

exports.templateForDefaultValues = {
    content: {
        firstName: {
            dataKey: 'firstName'
        },
        middleName: {
            dataKey: 'middleName'
        },
        lastName: {
            dataKey: 'lastName'
        },
        familyName: {
            dataKey: 'familyName',
            default: ""
        },
        address: {
            dataKey: 'address',
            default: ""
        },
        age: {
            dataKey: 'age',
            default: NaN
        },
        numbers: {
            dataKey: 'numbers',
            default: []
        },
        friends: {
            dataKey: 'friends',
            default: []
        },
        groups: {
            dataKey: 'groups'
        }
    }
};

exports.outputForEmptyStringPresence = {
    "address": "",
    "familyName": "",
    "firstName": "TIM",
    "groups": [1, 2],
    "lastName": "DOE",
    "middleName": "JOE"
};
exports.outputForDefaultValues = {
    "address": "",
    "age": NaN,
    "familyName": "",
    "firstName": "TIM",
    "friends": [],
    "groups": [1, 2],
    "lastName": "DOE",
    "middleName": "JOE",
    "numbers": []
};

exports.outputForNaNPresence = {

    "age": NaN,
    "firstName": "TIM",
    "groups": [1, 2],
    "lastName": "DOE",
    "middleName": "JOE"
};

exports.input = {
    a: {
        b: {
            c1: "i am key c1",
            c2: "",
            c3: undefined,
            c4: [],
            c5: NaN,
            c6: true,
            c7: false
        },
        d: NaN,
        e: "value a.e",
        f: [{
            firstName: "sampleFirstName",
            group: []
        }, {
            firstName: "sampleFirstName",
            group: [1, 3]
        }, {
            firstName: "sampleFirstName",
            group: []
        }],
        g: {
            firstName: "sampleLastName",
            lastName: "",
            age: NaN,
            city: undefined,
            Numbers: []
        },
        h: {
            firstName: "sampleFirstName",
            lastName: "",
            age: NaN,
            city: undefined,
            "h.a1": "I am Key with dot"
        },
        i: [{
            showWeather: true,
            weather: "sunny",
            temperature: "70F",
            city: "Dallas",
            days: ["mon", "tue", "wed"]
        }, {
            showWeather: true,
            weather: "",
            temperature: NaN,
            city: undefined,
            days: ["thr", "fri", "sat"]
        }, {
            showWeather: true,
            weather: "sunny",
            temperature: "70F",
            city: "Irving",
            days: []
        }, {
            showWeather: false,
            weather: "sunny",
            temperature: "70F",
            city: "Ft.Worth",
            days: []
        }]

    }
};

var weatherTemplate = {
    existsWhen: function (data) {
        return data.showWeather === true;
    },
    content: {
        weather: {
            dataKey: "weather"
        },
        temperature: {
            dataKey: "temperature"
        },
        city: {
            dataKey: "city"
        },
        days: {
            dataKey: "days"
        }
    }
};

exports.template = {
    content: {
        dest_a1: {
            dataKey: 'a.b.c1'
        },
        dest_a2: {
            dataKey: 'a.b.c2'
        },
        dest_a3: {
            dataKey: 'a.b.c3'
        },
        dest_a4: {
            dataKey: 'a.b.c4'
        },
        dest_a5: {
            dataKey: 'a.b.c5'
        },
        dest_a6: {
            dataKey: 'a.b.c6'
        },
        dest_a7: {
            dataKey: 'a.b.c7'
        },
        dest_b: {
            content: {
                dest_b0: {
                    value: function (data) {
                        return data.e;
                    }
                },
                dest_b1: {
                    dataKey: 'a.d',
                    default: "I am Default for NaN"
                }
            },
            dataKey: 'a'
        },
        dest_d: {
            dataKey: "a.d"
        },
        dest_e: {
            dataKey: "a.e"
        },
        dest_f: {
            dataKey: "a.f",
            content: {
                firstName: {
                    dataKey: "firstName"
                },
                group: {
                    dataKey: "group"
                }
            }
        },
        dest_g: {
            dataKey: "a.g",
            content: {
                firstName: {
                    dataKey: "firstName"
                },
                lastName: {
                    dataKey: "lastName"
                },
                age: {
                    dataKey: "age"
                },
                city: {
                    dataKey: "city"
                },
                Numbers: {
                    dataKey: "numbers",
                    default: "1"
                },
                "dotValue": {
                    dataKey: "h.a1"
                }
            }
        },
        dest_h: {
            ignoreDeep: true,
            content: {
                "dest.h1.firstName": {
                    dataKey: "a.h.firstName"
                },
                "dest.h2.lastName": {
                    dataKey: "a.h.lastName"
                }
            }
        },
        dest_i: {
            arrayContent: [{
                arrayContent: [{
                    dataKey: "a.i",
                    value: weatherTemplate
                }],
                default: []
            }]
        }

    }
};

exports.expectedWithPruneOptions = {
    "dest_a1": "i am key c1",
    "dest_a6": true,
    "dest_a7": false,
    "dest_b": {
        "dest_b0": "value a.e",
        "dest_b1": "I am Default for NaN"
    },
    "dest_e": "value a.e",
    "dest_f": [{
        "firstName": "sampleFirstName"
    }, {
        "firstName": "sampleFirstName",
        "group": [1, 3]
    }, {
        "firstName": "sampleFirstName"
    }],
    "dest_g": {
        "firstName": "sampleLastName",
        "Numbers": "1"
    },
    "dest_h": {
        "dest.h1.firstName": "sampleFirstName"
    },
    dest_i: [{
        "city": "Dallas",
        "temperature": "70F",
        "weather": "sunny",
        "days": [
            "mon",
            "tue",
            "wed"
        ]
    }, {
        "days": [
            "thr",
            "fri",
            "sat"
        ]
    }, {
        "city": "Irving",
        "temperature": "70F",
        "weather": "sunny"
    }]
};

exports.expectedWithOutPruneOptions = {
    dest_a1: "i am key c1",
    dest_a2: "",
    dest_a4: [],
    dest_a5: NaN,
    dest_a6: true,
    dest_a7: false,
    dest_b: {
        dest_b0: "value a.e",
        dest_b1: "I am Default for NaN"
    },
    dest_d: NaN,
    dest_e: "value a.e",
    dest_f: [{
        firstName: "sampleFirstName",
        group: []
    }, {
        firstName: "sampleFirstName",
        group: [1, 3]
    }, {
        firstName: "sampleFirstName",
        group: []
    }],
    dest_g: {
        Numbers: "1",
        age: NaN,
        firstName: "sampleLastName",
        lastName: ""
    },
    dest_h: {
        "dest.h1.firstName": "sampleFirstName",
        "dest.h2.lastName": ""
    },
    "dest_i": [{
        "city": "Dallas",
        "days": [
            "mon",
            "tue",
            "wed"
        ],
        "temperature": "70F",
        "weather": "sunny"
    }, {
        "days": [
            "thr",
            "fri",
            "sat"
        ],
        "temperature": NaN,
        "weather": ""
    }, {
        "city": "Irving",
        "days": [],
        "temperature": "70F",
        "weather": "sunny"
    }]
};

exports.expectedWithEmptyArrays = {
    "dest_a1": "i am key c1",
    "dest_a4": [],
    "dest_a6": true,
    "dest_a7": false,
    "dest_b": {
        "dest_b0": "value a.e",
        "dest_b1": "I am Default for NaN"
    },
    "dest_e": "value a.e",
    "dest_f": [{
        "firstName": "sampleFirstName",
        "group": []
    }, {
        "firstName": "sampleFirstName",
        "group": [1,
            3
        ]
    }, {
        "firstName": "sampleFirstName",
        "group": []
    }],
    "dest_g": {
        "firstName": "sampleLastName",
        "Numbers": "1"
    },
    "dest_h": {
        "dest.h1.firstName": "sampleFirstName"
    },
    "dest_i": [{
        "city": "Dallas",
        "temperature": "70F",
        "weather": "sunny",
        "days": [
            "mon",
            "tue",
            "wed"
        ]
    }, {
        "days": [
            "thr",
            "fri",
            "sat"
        ]
    }, {
        "city": "Irving",
        "days": [],
        "temperature": "70F",
        "weather": "sunny"
    }]
};
<|endoftext|>


<commit_before>var prefix = '';
var tests = {};

try {
  localStorage.test = 'test';
  localStorage.removeItem('test');
} catch (err) {
  if (err.code == 22) prefix = '// ';
}

function getLocalStorage(key) {
  return localStorage[key];
};

function setLocalStorage(key, val) {
  return localStorage[key] = val;
};

tests["setUp"] = function() {
  localStorage.clear();
};

tests["Should be able to set and get data against a key"] = function() {
  superstoreSync.set('keyOne', 'value1');
  var val = superstoreSync.get('keyOne');
  assert.equals('value1', val);
};

tests[prefix + "Should be able to read things (twice) from local storage"] = function() {
  setLocalStorage("keyTwo", 3884);
  assert.equals(getLocalStorage("keyTwo"), 3884);
  var val = superstoreSync.get('keyTwo');
  assert.equals(3884, val);
  var val2 = superstoreSync.get('keyTwo');
  assert.equals(3884, val2);
};

tests[prefix + "Should be able to unset things"] = function() {
  setLocalStorage("keyThree", "Hello");
  var val = superstoreSync.unset('keyThree');
  assert.equals(undefined, getLocalStorage("keyThree"));
};

tests["Getting an unset key should return a nully value"] = function() {
  var val = superstoreSync.get("keySixth");
  assert.equals(val, undefined);
};

tests[prefix + "Should json encode and decode objects"] = function() {
  var obj = {
    test: [1,4,6,7]
  };
  superstoreSync.set('keySeventh', obj);
  assert.equals(JSON.stringify(obj), getLocalStorage("keySeventh"));
};

tests[prefix + "#clear(something) clears only our namespaced data"] = function() {
  superstoreSync.set('other', '123');
  superstoreSync.set('prefixKeyTenth', 'A');
  superstoreSync.set('prefixKeyEleventh', 'B');
  superstoreSync.clear('prefixKey');

  assert.equals(undefined, getLocalStorage("prefixKeyTenth"));
  assert.equals(undefined, superstoreSync.get("prefixKeyTenth"));
  assert.equals(undefined, getLocalStorage("prefixKeyEleventh"));
  assert.equals(undefined, superstoreSync.get("prefixKeyEleventh"));
  assert.equals('"123"', getLocalStorage("other"));
  assert.equals('123', superstoreSync.get("other"));
};

tests[prefix + "#clear() clears all data"] = function() {
  superstoreSync.set('other', '123');
  superstoreSync.set('prefixKeyTwelth', 'C');
  superstoreSync.clear();

  assert.equals(undefined, getLocalStorage("prefixKeyTwelth"));
  assert.equals(undefined, getLocalStorage("other"));
};

tests["watch for changes in other processes"] = function() {
  superstoreSync.set('key13', 'A');

  var event = new CustomEvent("storage");
  event.key = "key13";
  event.newValue = "\"B\"";
  window.dispatchEvent(event);

  var val = superstoreSync.get('key13');
  assert.equals(val, 'B');
};

buster.testCase('superstore-sync', tests);
<commit_msg>Fix all tests for iOS private browsing mode<commit_after>var prefix = '';
var buggyLocalStorage = false;
var tests = {};

try {
  localStorage.test = 'test';
  localStorage.removeItem('test');
} catch (err) {
  if (err.code == 22) prefix = '// ';
  buggyLocalStorage = true;
}

function getLocalStorage(key) {
  return localStorage[key];
};

function setLocalStorage(key, val) {
  if (buggyLocalStorage) return localStorage[key] = val;
};

tests["setUp"] = function() {
  localStorage.clear();
};

tests["Removing a key before it's set should be harmless"] = function() {
  var exceptionThrown = false;
  try {
    superstoreSync.unset('keyUnset');
  } catch (e) {
    exceptionThrown = true;
  }
  assert.equals(false, exceptionThrown);
  assert.equals(undefined, getLocalStorage('keyUnset'));
};

tests["Should be able to set and get data against a key"] = function() {
  superstoreSync.set('keyOne', 'value1');
  var val = superstoreSync.get('keyOne');
  assert.equals('value1', val);
};

tests[prefix + "Should be able to read things (twice) from local storage"] = function() {
  setLocalStorage("keyTwo", 3884);
  assert.equals(getLocalStorage("keyTwo"), 3884);
  var val = superstoreSync.get('keyTwo');
  assert.equals(3884, val);
  var val2 = superstoreSync.get('keyTwo');
  assert.equals(3884, val2);
};

tests[prefix + "Should be able to unset things"] = function() {
  setLocalStorage("keyThree", "Hello");
  var val = superstoreSync.unset('keyThree');
  assert.equals(undefined, getLocalStorage("keyThree"));
};

tests["Getting an unset key should return a nully value"] = function() {
  var val = superstoreSync.get("keySixth");
  assert.equals(val, undefined);
};

tests[prefix + "Should json encode and decode objects"] = function() {
  var obj = {
    test: [1,4,6,7]
  };
  superstoreSync.set('keySeventh', obj);
  assert.equals(JSON.stringify(obj), getLocalStorage("keySeventh"));
};

tests["#clear(something) clears only our namespaced data"] = function() {
  superstoreSync.set('other', '123');
  superstoreSync.set('prefixKeyTenth', 'A');
  superstoreSync.set('prefixKeyEleventh', 'B');
  superstoreSync.clear('prefixKey');

  assert.equals(undefined, superstoreSync.get("prefixKeyTenth"));
  assert.equals(undefined, superstoreSync.get("prefixKeyEleventh"));
  assert.equals('123', superstoreSync.get("other"));

  if (!buggyLocalStorage) {
    assert.equals(undefined, getLocalStorage("prefixKeyEleventh"));
    assert.equals('"123"', getLocalStorage("other"));
    assert.equals(undefined, getLocalStorage("prefixKeyTenth"));
  }
};

tests["#clear() clears all data"] = function() {
  superstoreSync.set('other', '123');
  superstoreSync.set('prefixKeyTwelth', 'C');
  superstoreSync.clear();

  assert.equals(undefined, superstoreSync.get("prefixKeyTwelth"));
  assert.equals(undefined, superstoreSync.get("other"));

  if (!buggyLocalStorage) {
    assert.equals(undefined, getLocalStorage("prefixKeyTwelth"));
    assert.equals(undefined, getLocalStorage("other"));
  }
};

tests["watch for changes in other processes"] = function() {
  superstoreSync.set('key13', 'A');

  var event = new CustomEvent("storage");
  event.key = "key13";
  event.newValue = "\"B\"";
  window.dispatchEvent(event);

  var val = superstoreSync.get('key13');
  assert.equals(val, 'B');
};

buster.testCase('superstore-sync', tests);
<|endoftext|>


<commit_before>const { expect } = require('chai')

const translations = require('../../../app/js/translations')

describe('translations', function() {
  beforeEach(function() {
    this.translations = translations.setup({
      subdomainLang: {
        www: { lngCode: 'en', url: 'www.sharelatex.com' },
        fr: { lngCode: 'fr', url: 'fr.sharelatex.com' },
        da: { lngCode: 'da', url: 'da.sharelatex.com' }
      }
    })

    this.req = {
      originalUrl: "doesn'tmatter.sharelatex.com/login",
      headers: {
        'accept-language': ''
      }
    }
    this.res = {}
  })

  describe('setLangBasedOnDomainMiddlewear', function() {
    it('should set the lang to french if the domain is fr', function(done) {
      this.req.url = 'fr.sharelatex.com/login'
      this.req.headers.host = 'fr.sharelatex.com'
      this.translations.expressMiddlewear(this.req, this.req, () => {
        this.translations.setLangBasedOnDomainMiddlewear(
          this.req,
          this.res,
          () => {
            expect(this.req.lng).to.equal('fr')
            done()
          }
        )
      })
    })

    it('ignores domain if setLng query param is set', function(done) {
      this.req.originalUrl = 'fr.sharelatex.com/login?setLng=en'
      this.req.url = 'fr.sharelatex.com/login'
      this.req.headers.host = 'fr.sharelatex.com'
      this.translations.expressMiddlewear(this.req, this.req, () => {
        this.translations.setLangBasedOnDomainMiddlewear(
          this.req,
          this.res,
          () => {
            expect(this.req.lng).to.equal('en')
            done()
          }
        )
      })
    })

    describe('showUserOtherLng', function() {
      it('should set it to true if the language based on headers is different to lng', function(done) {
        this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
        this.req.url = 'fr.sharelatex.com/login'
        this.req.headers.host = 'fr.sharelatex.com'
        this.translations.expressMiddlewear(this.req, this.req, () => {
          this.translations.setLangBasedOnDomainMiddlewear(
            this.req,
            this.res,
            () => {
              expect(this.req.showUserOtherLng).to.equal('da')
              done()
            }
          )
        })
      })

      it('should not set prop', function(done) {
        this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
        this.req.url = 'da.sharelatex.com/login'
        this.req.headers.host = 'da.sharelatex.com'
        this.translations.expressMiddlewear(this.req, this.req, () => {
          this.translations.setLangBasedOnDomainMiddlewear(
            this.req,
            this.res,
            () => {
              expect(this.req.showUserOtherLng).to.not.exist
              done()
            }
          )
        })
      })
    })
  })
})
<commit_msg>Use fixed method names<commit_after>const { expect } = require('chai')

const translations = require('../../../app/js/translations')

describe('translations', function() {
  beforeEach(function() {
    this.translations = translations.setup({
      subdomainLang: {
        www: { lngCode: 'en', url: 'www.sharelatex.com' },
        fr: { lngCode: 'fr', url: 'fr.sharelatex.com' },
        da: { lngCode: 'da', url: 'da.sharelatex.com' }
      }
    })

    this.req = {
      originalUrl: "doesn'tmatter.sharelatex.com/login",
      headers: {
        'accept-language': ''
      }
    }
    this.res = {}
  })

  describe('setLangBasedOnDomainMiddleware', function() {
    it('should set the lang to french if the domain is fr', function(done) {
      this.req.url = 'fr.sharelatex.com/login'
      this.req.headers.host = 'fr.sharelatex.com'
      this.translations.expressMiddleware(this.req, this.req, () => {
        this.translations.setLangBasedOnDomainMiddleware(
          this.req,
          this.res,
          () => {
            expect(this.req.lng).to.equal('fr')
            done()
          }
        )
      })
    })

    it('ignores domain if setLng query param is set', function(done) {
      this.req.originalUrl = 'fr.sharelatex.com/login?setLng=en'
      this.req.url = 'fr.sharelatex.com/login'
      this.req.headers.host = 'fr.sharelatex.com'
      this.translations.expressMiddleware(this.req, this.req, () => {
        this.translations.setLangBasedOnDomainMiddleware(
          this.req,
          this.res,
          () => {
            expect(this.req.lng).to.equal('en')
            done()
          }
        )
      })
    })

    describe('showUserOtherLng', function() {
      it('should set it to true if the language based on headers is different to lng', function(done) {
        this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
        this.req.url = 'fr.sharelatex.com/login'
        this.req.headers.host = 'fr.sharelatex.com'
        this.translations.expressMiddleware(this.req, this.req, () => {
          this.translations.setLangBasedOnDomainMiddleware(
            this.req,
            this.res,
            () => {
              expect(this.req.showUserOtherLng).to.equal('da')
              done()
            }
          )
        })
      })

      it('should not set prop', function(done) {
        this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
        this.req.url = 'da.sharelatex.com/login'
        this.req.headers.host = 'da.sharelatex.com'
        this.translations.expressMiddleware(this.req, this.req, () => {
          this.translations.setLangBasedOnDomainMiddleware(
            this.req,
            this.res,
            () => {
              expect(this.req.showUserOtherLng).to.not.exist
              done()
            }
          )
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

require('../qunit_extensions');

var oo = require('../../../util/oo');
var Fragmenter = require('../../../model/Fragmenter');
// var DOMElement = require('../../../ui/DOMElement');

QUnit.module('model/Fragmenter');

// - nodes with lower level should be split less often
// - inline nodes must not be split at all
// - anchor nodes must never be split at all and should always be nested on the deepest
//   level
// - annotations with the same extension should be stacked

var TEXT = 'ABCDEFGHI';

function Anno(tagName, id, startOffset, endOffset, opts) {
  opts = opts || {};
  this.tagName = tagName;
  this.id = id;
  this.offset = startOffset;
  this.startOffset = startOffset;
  this.endOffset = endOffset;

  this._isAnchor = false;
  this._isInline = false;

  if (opts.anchor) {
    this.zeroWidth = true;
    this.offset = this.startOffset;
  }

  if (opts.hasOwnProperty('fragmentation')) {
    this.fragmentationHint = opts.fragmentation;
  }

  if (opts.hasOwnProperty('isAnchor')) {
    this._isAnchor = opts.isAnchor;
  }

  if (opts.hasOwnProperty('isInline')) {
    this._isInline = opts.isInline;
  }
}

Anno.Prototype = function() {

  // anchors are special annotations that have zero width
  this.isAnchor = function() {
    return this._isAnchor;
  };

  // inline nodes are implementated as annotations bound to a single character
  // I.e. the always have a length of 1
  this.isInline = function() {
    return this._isInline;
  };

};

oo.initClass(Anno);

var _render = function(text, annotations, opts) {
  opts = opts || {};
  var output = [];
  var fragmenter = new Fragmenter();
  fragmenter.onText = function(context, text) {
    output.push(text);
  };
  fragmenter.onEnter = function(fragment) {
    var node = fragment.node;
    if (opts.withId) {
      output.push('<' + node.tagName + ' id="' + node.id +'">');
    } else {
      output.push('<' + node.tagName + '>');
    }
  };
  fragmenter.onExit = function(fragment) {
    var node = fragment.node;
    output.push('</' + node.tagName + '>');
  };
  fragmenter.start(output, text, annotations);
  return output.join('');
};

// var _wrapped = function(html) {
//   return '
' + html + '
';
// };

QUnit.test("No annos.", function(assert) {
  var annos = [];
  var html = _render(TEXT, annos);
  assert.equal(html, TEXT);
});

QUnit.test("With one anno.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("With one anchor.", function(assert) {
  var annos = [new Anno('a', 'a1', 3, 3, {
    isAnchor: true
  })];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("With one inline.", function(assert) {
  var annos = [new Anno('i', 'i1', 3, 4)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("One nested anno.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 4, 5)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Overlapping annos.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 4, 8)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Equal annos.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 3, 6)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Overlapping with fragmentation hint.", function(assert) {
  var annos = [
    new Anno('b', 'b1', 3, 6),
    new Anno('a', 'link1', 4, 8, {
      fragmentation: Fragmenter.SHOULD_NOT_SPLIT
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Anchors should rendered as early as possible.", function(assert) {
  var annos = [
    new Anno('b', 'b1', 3, 6),
    new Anno('a', 'a1', 3, 3, {
      isAnchor: true
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Two subsequent inline nodes.", function(assert) {
  var annos = [
    new Anno('a', 'inline1', 3, 4, {
      isInline: true
    }),
    new Anno('b', 'inline2', 4, 5, {
      isInline: true
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});
<commit_msg>Added test revealing a Fragmenter issue with collapsed annotations/fragments.<commit_after>'use strict';

require('../qunit_extensions');

var oo = require('../../../util/oo');
var Fragmenter = require('../../../model/Fragmenter');
// var DOMElement = require('../../../ui/DOMElement');

QUnit.module('model/Fragmenter');

// - nodes with lower level should be split less often
// - inline nodes must not be split at all
// - anchor nodes must never be split at all and should always be nested on the deepest
//   level
// - annotations with the same extension should be stacked

var TEXT = 'ABCDEFGHI';

function Anno(tagName, id, startOffset, endOffset, opts) {
  opts = opts || {};
  this.tagName = tagName;
  this.id = id;
  this.offset = startOffset;
  this.startOffset = startOffset;
  this.endOffset = endOffset;

  this._isAnchor = false;
  this._isInline = false;

  if (opts.anchor) {
    this.zeroWidth = true;
    this.offset = this.startOffset;
  }

  if (opts.hasOwnProperty('fragmentation')) {
    this.fragmentationHint = opts.fragmentation;
  }

  if (opts.hasOwnProperty('isAnchor')) {
    this._isAnchor = opts.isAnchor;
  }

  if (opts.hasOwnProperty('isInline')) {
    this._isInline = opts.isInline;
  }
}

Anno.Prototype = function() {

  // anchors are special annotations that have zero width
  this.isAnchor = function() {
    return this._isAnchor;
  };

  // inline nodes are implementated as annotations bound to a single character
  // I.e. the always have a length of 1
  this.isInline = function() {
    return this._isInline;
  };

};

oo.initClass(Anno);

var _render = function(text, annotations, opts) {
  opts = opts || {};
  var output = [];
  var fragmenter = new Fragmenter();
  fragmenter.onText = function(context, text) {
    output.push(text);
  };
  fragmenter.onEnter = function(fragment) {
    var node = fragment.node;
    if (opts.withId) {
      output.push('<' + node.tagName + ' id="' + node.id +'">');
    } else {
      output.push('<' + node.tagName + '>');
    }
  };
  fragmenter.onExit = function(fragment) {
    var node = fragment.node;
    output.push('</' + node.tagName + '>');
  };
  fragmenter.start(output, text, annotations);
  return output.join('');
};

// var _wrapped = function(html) {
//   return '
' + html + '
';
// };

QUnit.test("No annos.", function(assert) {
  var annos = [];
  var html = _render(TEXT, annos);
  assert.equal(html, TEXT);
});

QUnit.test("With one anno.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("With one anchor.", function(assert) {
  var annos = [new Anno('a', 'a1', 3, 3, {
    isAnchor: true
  })];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("With one inline.", function(assert) {
  var annos = [new Anno('i', 'i1', 3, 4)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("One nested anno.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 4, 5)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Overlapping annos.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 4, 8)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Equal annos.", function(assert) {
  var annos = [new Anno('b', 'b1', 3, 6), new Anno('i', 'i1', 3, 6)];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Overlapping with fragmentation hint.", function(assert) {
  var annos = [
    new Anno('b', 'b1', 3, 6),
    new Anno('a', 'link1', 4, 8, {
      fragmentation: Fragmenter.SHOULD_NOT_SPLIT
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Anchors should rendered as early as possible.", function(assert) {
  var annos = [
    new Anno('b', 'b1', 3, 6),
    new Anno('a', 'a1', 3, 3, {
      isAnchor: true
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Two subsequent inline nodes.", function(assert) {
  var annos = [
    new Anno('a', 'inline1', 3, 4, {
      isInline: true
    }),
    new Anno('b', 'inline2', 4, 5, {
      isInline: true
    })
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});

QUnit.test("Collapsed annotation.", function(assert) {
  var annos = [
    new Anno('a', 'inline1', 0, 0, {
    }),
  ];
  var html = _render(TEXT, annos);
  assert.equal(html, 'ABCDEFGHI');
});
<|endoftext|>


<commit_before>var $$ = React.createElement;

var TYPE_LABELS = {
  "prison": "Prison",
  "toponym": "Toponym",
  "person": "Person",
  "definition": "Definition"
};

// Example of a sub view
// ----------------

var EntityView = React.createClass({
  displayName: "Entity",

  handleClick: function(e) {
    e.preventDefault();
    this.props.handleSelection(this.props.id);
  },

  render: function() {
    var className = ["entity", this.props.type];
    if (this.props.active) className.push("active");

    var props = [
      $$("div", {className: "type"}, TYPE_LABELS[this.props.type]),
      $$("div", {className: "name"}, this.props.name || this.props.title)
    ];

    if (this.props.synonyms) {
      props.push($$("div", {className: "synonyms"}, "Also known as: "+this.props.synonyms));
    }

    if (this.props.country) {
      props.push($$("div", {className: "country"}, "Country: "+this.props.country));
    }

    if (this.props.type == 'person') {
      var description = this.props.description;
      // Trim person description if it's too long
      if (description.length > 100) description = description.substring(0, 100) + '...';
      props.push($$("div", {className: "description"}, description));
    }

    return $$("div", {
      className: className.join(" "),
      onClick: this.handleClick
    }, props);
  }
});

// Entities Panel extension
// ----------------

var SelectEntityMixin = {

  contextTypes: {
    app: React.PropTypes.object.isRequired,
    backend: React.PropTypes.object.isRequired
  },

  handleCancel: function(e) {
    var app = this.context.app;
    e.preventDefault();
    console.log('props', this.props);
    if (this.props.entityReferenceId) {
      // Go back to show entities panel
      app.replaceState({
        contextId: "showEntityReference",
        entityReferenceId: this.props.entityReferenceId
      });
    } else {
      // Go to regular entities panel
      app.replaceState({
        contextId: "entities"
      });
    }
  },

  // Data loading methods
  // ------------

  loadEntities: function(searchString, type) {
    var self = this;
    var type = type || false;
    var backend = this.context.backend;

    backend.searchEntities(searchString, type, function(err, entities) {
      self.setState({
        state: entities.state,
        entities: entities.results
      });
    });
  },

  // State relevant things
  // ------------

  getInitialState: function() {
    return {
      searchString: this.props.searchString,
      entities: []
    };
  },

  // Events
  // ------------

  componentDidMount: function() {
    this.loadEntities(this.state.searchString);
  },

  handleSearchStringChange: function(e) {
    var searchString = e.target.value;
    var searchType = this.state.type || false;
    this.setState({searchString: searchString});
    this.loadEntities(searchString, searchType);
  },

  handleEntityFilterChange: function(e) {
    var searchType = e.currentTarget.value;
    this.setState({type: searchType});
    this.loadEntities(this.state.searchString, searchType);
  },

  handleRefreshClick: function() {
    var type = this.state.type || false;
    var searchString = this.state.searchString || '';
    this.loadEntities(searchString, type);
  },

  // Rendering
  // -------------------

  render: function() {
    var self = this;
    var entities = this.state.entities;
    var entityNodes;
    var stateMessage = this.state.state;

    if (entities.length > 0) {
      entityNodes = entities.map(function(entity) {
        entity.handleSelection = self.handleSelection;
        return $$(EntityView, entity);
      });
    } else {
      entityNodes = [$$('div', {className: "no-results", text: "Loading suggestions"})];
    }

    return $$("div", {className: "panel dialog tag-entity-panel-component"},
      $$('div', {className: "dialog-header"},
        $$('a', {
          href: "#",
          className: 'back',
          onClick: this.handleCancel,
          dangerouslySetInnerHTML: {__html: ''}
        }),
        $$('div', {className: 'label'}, "Select entity")
      ),

      $$('div', {className: "panel-content"},
        $$('div', {className: "search", html: ""},
          $$('input', {
            className: "search-str",
            type: "text",
            placeholder: "Type to search for entities",//,
            value: this.state.searchString,
            onChange: this.handleSearchStringChange
          }),
          $$('select', {
              className: "entity-type",
              onChange: this.handleEntityFilterChange
            },
            $$('option', {value: ""}, "All"),
            //$$('option', {value: "prison"}, "Prison"),
            //$$('option', {value: "toponym"}, "Toponym"),
            $$('option', {value: "location"}, "Location"),
            $$('option', {value: "person"}, "Person"),
            $$('option', {value: "definition"}, "Definition")
          ),
          $$('span', {
              className: "refresh",
              onClick: this.handleRefreshClick
            },
            $$('i', { className: "fa fa-refresh" }, "")
          )
        ),
        $$('div', {className: "search-result-state"},
          $$('span', { className: "state" }, stateMessage),
          $$('span', { className: "add-entity" },
            $$('span', { className: "label" }, "Add new: "),
            $$('a', { href: "/prisons/add", target: "_blank" },
              $$('i', { className: "fa fa-th" }, "")
            ),
            $$('a', { href: "/toponyms/add", target: "_blank" },
              $$('i', { className: "fa fa-globe" }, "")
            ),
            $$('a', { href: "/definitions/add", target: "_blank" },
              $$('i', { className: "fa fa-bookmark" }, "")
            ),
            $$('a', { href: "/persons/add", target: "_blank" },
              $$('i', { className: "fa fa-users" }, "")
            )
          )
        ),
        $$('div', {className: "entities"},
          entityNodes
        )
      )
    );
  }
};

module.exports = SelectEntityMixin;<commit_msg>fix undefined description<commit_after>var $$ = React.createElement;

var TYPE_LABELS = {
  "prison": "Prison",
  "toponym": "Toponym",
  "person": "Person",
  "definition": "Definition"
};

// Example of a sub view
// ----------------

var EntityView = React.createClass({
  displayName: "Entity",

  handleClick: function(e) {
    e.preventDefault();
    this.props.handleSelection(this.props.id);
  },

  render: function() {
    var className = ["entity", this.props.type];
    if (this.props.active) className.push("active");

    var props = [
      $$("div", {className: "type"}, TYPE_LABELS[this.props.type]),
      $$("div", {className: "name"}, this.props.name || this.props.title)
    ];

    if (this.props.synonyms) {
      props.push($$("div", {className: "synonyms"}, "Also known as: "+this.props.synonyms));
    }

    if (this.props.country) {
      props.push($$("div", {className: "country"}, "Country: "+this.props.country));
    }

    if (this.props.type == 'person') {
      var description = this.props.description || '';
      // Trim person description if it's too long
      if (description.length > 100) description = description.substring(0, 100) + '...';
      props.push($$("div", {className: "description"}, description));
    }

    return $$("div", {
      className: className.join(" "),
      onClick: this.handleClick
    }, props);
  }
});

// Entities Panel extension
// ----------------

var SelectEntityMixin = {

  contextTypes: {
    app: React.PropTypes.object.isRequired,
    backend: React.PropTypes.object.isRequired
  },

  handleCancel: function(e) {
    var app = this.context.app;
    e.preventDefault();
    console.log('props', this.props);
    if (this.props.entityReferenceId) {
      // Go back to show entities panel
      app.replaceState({
        contextId: "showEntityReference",
        entityReferenceId: this.props.entityReferenceId
      });
    } else {
      // Go to regular entities panel
      app.replaceState({
        contextId: "entities"
      });
    }
  },

  // Data loading methods
  // ------------

  loadEntities: function(searchString, type) {
    var self = this;
    var type = type || false;
    var backend = this.context.backend;

    backend.searchEntities(searchString, type, function(err, entities) {
      self.setState({
        state: entities.state,
        entities: entities.results
      });
    });
  },

  // State relevant things
  // ------------

  getInitialState: function() {
    return {
      searchString: this.props.searchString,
      entities: []
    };
  },

  // Events
  // ------------

  componentDidMount: function() {
    this.loadEntities(this.state.searchString);
  },

  handleSearchStringChange: function(e) {
    var searchString = e.target.value;
    var searchType = this.state.type || false;
    this.setState({searchString: searchString});
    this.loadEntities(searchString, searchType);
  },

  handleEntityFilterChange: function(e) {
    var searchType = e.currentTarget.value;
    this.setState({type: searchType});
    this.loadEntities(this.state.searchString, searchType);
  },

  handleRefreshClick: function() {
    var type = this.state.type || false;
    var searchString = this.state.searchString || '';
    this.loadEntities(searchString, type);
  },

  // Rendering
  // -------------------

  render: function() {
    var self = this;
    var entities = this.state.entities;
    var entityNodes;
    var stateMessage = this.state.state;

    if (entities.length > 0) {
      entityNodes = entities.map(function(entity) {
        entity.handleSelection = self.handleSelection;
        return $$(EntityView, entity);
      });
    } else {
      entityNodes = [$$('div', {className: "no-results", text: "Loading suggestions"})];
    }

    return $$("div", {className: "panel dialog tag-entity-panel-component"},
      $$('div', {className: "dialog-header"},
        $$('a', {
          href: "#",
          className: 'back',
          onClick: this.handleCancel,
          dangerouslySetInnerHTML: {__html: ''}
        }),
        $$('div', {className: 'label'}, "Select entity")
      ),

      $$('div', {className: "panel-content"},
        $$('div', {className: "search", html: ""},
          $$('input', {
            className: "search-str",
            type: "text",
            placeholder: "Type to search for entities",//,
            value: this.state.searchString,
            onChange: this.handleSearchStringChange
          }),
          $$('select', {
              className: "entity-type",
              onChange: this.handleEntityFilterChange
            },
            $$('option', {value: ""}, "All"),
            //$$('option', {value: "prison"}, "Prison"),
            //$$('option', {value: "toponym"}, "Toponym"),
            $$('option', {value: "location"}, "Location"),
            $$('option', {value: "person"}, "Person"),
            $$('option', {value: "definition"}, "Definition")
          ),
          $$('span', {
              className: "refresh",
              onClick: this.handleRefreshClick
            },
            $$('i', { className: "fa fa-refresh" }, "")
          )
        ),
        $$('div', {className: "search-result-state"},
          $$('span', { className: "state" }, stateMessage),
          $$('span', { className: "add-entity" },
            $$('span', { className: "label" }, "Add new: "),
            $$('a', { href: "/prisons/add", target: "_blank" },
              $$('i', { className: "fa fa-th" }, "")
            ),
            $$('a', { href: "/toponyms/add", target: "_blank" },
              $$('i', { className: "fa fa-globe" }, "")
            ),
            $$('a', { href: "/definitions/add", target: "_blank" },
              $$('i', { className: "fa fa-bookmark" }, "")
            ),
            $$('a', { href: "/persons/add", target: "_blank" },
              $$('i', { className: "fa fa-users" }, "")
            )
          )
        ),
        $$('div', {className: "entities"},
          entityNodes
        )
      )
    );
  }
};

module.exports = SelectEntityMixin;<|endoftext|>


<commit_before>var map;
var hasInit = false;
var markers;

/**
 * The load article control will load article markers onto the map
 */

function ArticleControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map.
  controlDiv.style.padding = '5px';

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Load articles when you click the button';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Load Articles';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  google.maps.event.addDomListener(controlUI, 'click', addMarker);
}

function initialize() {
	if (!hasInit) {
		var mapOptions = {
		  center: new google.maps.LatLng(40.714623,-74.006605 ),
		  zoom: 12,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		map = new google.maps.Map(document.getElementById("map-canvas"),
	    mapOptions);

		hasInit = true;
	}
    //addMarker();
    // Create the DIV to hold the control and call the ArticleControl() constructor
	// passing in this DIV.
	var articleControlDiv = document.createElement('div');
	var articleControl = new ArticleControl(articleControlDiv, map);

	articleControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(articleControlDiv);
}

function addMarker() {
	var myLatlng = new google.maps.LatLng(40.714623,-74.006605);
	var marker = new google.maps.Marker({
	  position: myLatlng,
	  map: map,
	  title: 'Hello World!'
	});
}
google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>added infowindow to map marker<commit_after>var map;
var hasInit = false;
var markers;

/**
 * The load article control will load article markers onto the map
 */

function ArticleControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map.
  controlDiv.style.padding = '5px';

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Load articles when you click the button';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Load Articles';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  google.maps.event.addDomListener(controlUI, 'click', addMarker);
}

function initialize() {
	if (!hasInit) {
		var mapOptions = {
		  center: new google.maps.LatLng(40.714623,-74.006605 ),
		  zoom: 12,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		map = new google.maps.Map(document.getElementById("map-canvas"),
	    mapOptions);

		hasInit = true;
	}
    //addMarker();
    // Create the DIV to hold the control and call the ArticleControl() constructor
	// passing in this DIV.
	var articleControlDiv = document.createElement('div');
	var articleControl = new ArticleControl(articleControlDiv, map);

	articleControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(articleControlDiv);
}

function addMarker() {
        var infowindow = new google.maps.InfoWindow({
              content: "Hello World"
          });
	var myLatlng = new google.maps.LatLng(40.714623,-74.006605);
	var marker = new google.maps.Marker({
	  position: myLatlng,
	  map: map,
	  title: 'Hello World!'
	});
        google.maps.event.addListener(marker, 'click', function() {
                  infowindow.open(map,marker);
                });
}
google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>var map;
var hasInit = false;
var markers;

/**
 * The load article control will load article markers onto the map
 */

function ArticleControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map.
  controlDiv.style.padding = '5px';

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Load articles when you click the button';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Load Articles';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  google.maps.event.addDomListener(controlUI, 'click', addMarker);
}

function initialize() {
	if (!hasInit) {
		var mapOptions = {
		  center: new google.maps.LatLng(40.714623,-74.006605 ),
		  zoom: 12,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		map = new google.maps.Map(document.getElementById("map-canvas"),
	    mapOptions);

		hasInit = true;
	}
    //addMarker();
    // Create the DIV to hold the control and call the ArticleControl() constructor
	// passing in this DIV.
	var articleControlDiv = document.createElement('div');
	var articleControl = new ArticleControl(articleControlDiv, map);

	articleControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(articleControlDiv);
}

// Adds marker to specfic lat lng
function addMarker(JSONObj) {
    var infowindow = new google.maps.InfoWindow({
        content: JSONObj.Blurb;
 	});
	var myLatlng = new google.maps.LatLng(JSONObj.lat, JSONObj.lng);
	var marker = new google.maps.Marker({
	  position: myLatlng,
	  map: map,
	  title: JSONObj.headline
	});

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.open(map,marker);
  });
  google.maps.event.addListener(marker, 'mouseout', function() {
    infowindow.close();
  });

}

// Passes in lat lng from center of map and returns relevant articles. We then build markers on the map.
function loadArticles() {
  //Get lat lng for center
  var currentLatLng = map.getCenter();
  var lat = currentLatLng.lat;
  var lng = currentLatLng.lng;

  //Get region radius
  var bounds = map.getBounds();
  var swPoint = bounds.getSouthWest();
  var proximitymeter = google.maps.geometry.spherical.computeDistanceBetween(swPoint, currentLatLng);
  var proximitymiles = proximitymeter * 0.000621371192;

  //call Gabe's interface to get a bunch of articles

  //loop through relevant articles and get address
  //var JSONObj = gabeFunction(lat, lng, proximitymiles);
  for(var i = 0; i < JSONObj.length; i++) {
    console.log("Plotting headline " + JSONObj[i].headline + "at " + JSONObj[i].lat + " " + JSONObj[i].lng);
    addMarker(JSONObj[i]);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>wired addArticle method to addArticle button<commit_after>var map;
var hasInit = false;
var markers;

/**
 * The load article control will load article markers onto the map
 */

function ArticleControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map.
  controlDiv.style.padding = '5px';

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Load articles when you click the button';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Load Articles';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  google.maps.event.addDomListener(controlUI, 'click', loadArticles);
}

function initialize() {
	if (!hasInit) {
		var mapOptions = {
		  center: new google.maps.LatLng(40.714623,-74.006605 ),
		  zoom: 12,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		map = new google.maps.Map(document.getElementById("map-canvas"),
	    mapOptions);

		hasInit = true;
	}
    //addMarker();
    // Create the DIV to hold the control and call the ArticleControl() constructor
	// passing in this DIV.
	var articleControlDiv = document.createElement('div');
	var articleControl = new ArticleControl(articleControlDiv, map);

	articleControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(articleControlDiv);
}

// Adds marker to specfic lat lng
function addMarker(JSONObj) {
    var infowindow = new google.maps.InfoWindow({
        content: JSONObj.Blurb;
 	});
	var myLatlng = new google.maps.LatLng(JSONObj.lat, JSONObj.lng);
	var marker = new google.maps.Marker({
	  position: myLatlng,
	  map: map,
	  title: JSONObj.headline
	});

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.open(map,marker);
  });
  google.maps.event.addListener(marker, 'mouseout', function() {
    infowindow.close();
  });

}

// Passes in lat lng from center of map and returns relevant articles. We then build markers on the map.
function loadArticles() {
  //Get lat lng for center
  var currentLatLng = map.getCenter();
  var lat = currentLatLng.lat;
  var lng = currentLatLng.lng;

  //Get region radius
  var bounds = map.getBounds();
  var swPoint = bounds.getSouthWest();
  var proximitymeter = google.maps.geometry.spherical.computeDistanceBetween(swPoint, currentLatLng);
  var proximitymiles = proximitymeter * 0.000621371192;

  //call Gabe's interface to get a bunch of articles

  //loop through relevant articles and get address
  //var JSONObj = gabeFunction(lat, lng, proximitymiles);
  for(var i = 0; i < JSONObj.length; i++) {
    console.log("Plotting headline " + JSONObj[i].headline + "at " + JSONObj[i].lat + " " + JSONObj[i].lng);
    addMarker(JSONObj[i]);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>"use strict";

const _ = require('lodash'),
      express = require('express'),
      bodyParser = require('body-parser'),
      logger = require('winston'),
      fs = require('fs-extra'),
      nocache = require('nocache'),
      passport = require('passport'),
      config = require('./config'),
      routes = require('./routes'),
      filters = require('./filters'),
      utils = require('./utils'),

      DEF_LOGGER_LEVEL = 'info',
      DEF_LOGGER_SILENT = false;

/* Logging system */

function initLogging(conf) {
    logger.setLevels({
        error: 0,
        warn: 1,
        info: 2,
        verbose: 3,
        debug: 4,
        silly: 5
    });
    logger.addColors({
        debug: 'green',
        info: 'cyan',
        silly: 'magenta',
        warn: 'yellow',
        error: 'red'
    });

    logger.remove(logger.transports.Console);
    logger.add(logger.transports.Console, {
        level: conf.level || DEF_LOGGER_LEVEL,
        silent: conf.silent || DEF_LOGGER_SILENT,
        colorize: true,
        timestamp: true
    });
}

/* Termination & Errors handling */

function initExitHandling(server) {
    const onExit = () => {
        server.close(() => {
            logger.info('Manet server stopped');
            process.exit(0);
        });
    }
    process.on('SIGTERM', onExit);
    process.on('SIGINT', onExit);
}

/* Init FS services */

function cleanupFsStorage(conf) {
    if (conf.cleanupStartup) {
        const storagePath = conf.storage,
              files = fs.readdirSync(storagePath);

        files.forEach((file) => {
            try {
                const filePath = utils.filePath(file, storagePath);
                fs.removeSync(filePath, {force: true});
            } catch (err) {}
        });
    }
}

function initFsWatchdog(conf) {
    const timeout = conf.cache * 1000,
          dir = conf.storage;

    utils.runFsWatchdog(dir, timeout, (file) => {
        fs.unlink(file, (err) => {
            if (err) {
                logger.debug('Can not delete file "%s": %s', file, err);
            } else {
                logger.info('Deleted file "%s"', file);
            }
        });
    });
}

function initFsStorage(conf) {
    cleanupFsStorage(conf);
    initFsWatchdog(conf);
}

/* Web application */

function createWebApplication(conf) {
    const app = express(),
          index = routes.index(conf),
          urlencoded = bodyParser.urlencoded({ extended: false }),
          json = bodyParser.json(),
          noCache = nocache(),
          basic = filters.basic(conf),
          usage = filters.usage(conf),
          merge = filters.merge,
          notNull = (f) => _.without(f, null);

    filters.configureWebSecurity(conf);

    app.use(express.static(utils.filePath('../public')));
    app.use(passport.initialize());

    app.get('/', notNull([noCache, basic, merge, usage]), index);
    app.post('/', notNull([noCache, basic, urlencoded, json, merge, usage]), index);

    return app;
}

function runWebServer(conf, onStart) {
    const app = createWebApplication(conf),
          host = conf.host,
          port = conf.port,
          server = app.listen(port, host, () => {
              if (onStart) {
                  onStart(server);
              }
          });

    logger.info('Manet server started on %s:%d', host, port);

    initExitHandling(server);
}

/* Initialize and run server */

function main(onStart) {
    const conf = config.read();

    initLogging(conf);
    initFsStorage(conf);

    logger.debug('Default configuration file: %s', conf.path);
    logger.debug('Configuration parameters: %s', JSON.stringify(conf));

    runWebServer(conf, onStart);
}

/* Exported functions */

module.exports = {
    main: main
};
<commit_msg>Make linter happy<commit_after>"use strict";

const _ = require('lodash'),
      express = require('express'),
      bodyParser = require('body-parser'),
      logger = require('winston'),
      fs = require('fs-extra'),
      nocache = require('nocache'),
      passport = require('passport'),
      config = require('./config'),
      routes = require('./routes'),
      filters = require('./filters'),
      utils = require('./utils'),

      DEF_LOGGER_LEVEL = 'info',
      DEF_LOGGER_SILENT = false;

/* Logging system */

function initLogging(conf) {
    logger.setLevels({
        error: 0,
        warn: 1,
        info: 2,
        verbose: 3,
        debug: 4,
        silly: 5
    });
    logger.addColors({
        debug: 'green',
        info: 'cyan',
        silly: 'magenta',
        warn: 'yellow',
        error: 'red'
    });

    logger.remove(logger.transports.Console);
    logger.add(logger.transports.Console, {
        level: conf.level || DEF_LOGGER_LEVEL,
        silent: conf.silent || DEF_LOGGER_SILENT,
        colorize: true,
        timestamp: true
    });
}

/* Termination & Errors handling */

function initExitHandling(server) {
    const onExit = () => {
        server.close(() => {
            logger.info('Manet server stopped');
            process.exit(0);
        });
    };

    process.on('SIGTERM', onExit);
    process.on('SIGINT', onExit);
}

/* Init FS services */

function cleanupFsStorage(conf) {
    if (conf.cleanupStartup) {
        const storagePath = conf.storage,
              files = fs.readdirSync(storagePath);

        files.forEach((file) => {
            try {
                const filePath = utils.filePath(file, storagePath);
                fs.removeSync(filePath, {force: true});
            } catch (err) {}
        });
    }
}

function initFsWatchdog(conf) {
    const timeout = conf.cache * 1000,
          dir = conf.storage;

    utils.runFsWatchdog(dir, timeout, (file) => {
        fs.unlink(file, (err) => {
            if (err) {
                logger.debug('Can not delete file "%s": %s', file, err);
            } else {
                logger.info('Deleted file "%s"', file);
            }
        });
    });
}

function initFsStorage(conf) {
    cleanupFsStorage(conf);
    initFsWatchdog(conf);
}

/* Web application */

function createWebApplication(conf) {
    const app = express(),
          index = routes.index(conf),
          urlencoded = bodyParser.urlencoded({ extended: false }),
          json = bodyParser.json(),
          noCache = nocache(),
          basic = filters.basic(conf),
          usage = filters.usage(conf),
          merge = filters.merge,
          notNull = (f) => _.without(f, null);

    filters.configureWebSecurity(conf);

    app.use(express.static(utils.filePath('../public')));
    app.use(passport.initialize());

    app.get('/', notNull([noCache, basic, merge, usage]), index);
    app.post('/', notNull([noCache, basic, urlencoded, json, merge, usage]), index);

    return app;
}

function runWebServer(conf, onStart) {
    const app = createWebApplication(conf),
          host = conf.host,
          port = conf.port,
          server = app.listen(port, host, () => {
              if (onStart) {
                  onStart(server);
              }
          });

    logger.info('Manet server started on %s:%d', host, port);

    initExitHandling(server);
}

/* Initialize and run server */

function main(onStart) {
    const conf = config.read();

    initLogging(conf);
    initFsStorage(conf);

    logger.debug('Default configuration file: %s', conf.path);
    logger.debug('Configuration parameters: %s', JSON.stringify(conf));

    runWebServer(conf, onStart);
}

/* Exported functions */

module.exports = {
    main: main
};
<|endoftext|>