<commit_before>define([
  'jquery',
  'backbone',
  'handlebars',
  'underscore',
  'mps',
  'validate',
  'jquery_fileupload',

], function($, Backbone, Handlebars, _, mps, validate, jquery_fileupload) {

  'use strict';

  var MAXFILESIZE = 2000000000;
  var TIMEOUT = 3600000;

  var constraints = {
    'data_format': {
      presence: true,
    },
    'data_show': {
      presence: true,
    },
    'data_email': {
      presence: true,
      email: true,
    },
    'data_agree': {
      presence: true,
      inclusion: {
        within: [true],
      }
    },
    'data_terms': {
      presence: true,
      inclusion: {
        within: [true],
      }
    },
    'data_uploaded': {
      presence: true
    },
    'metadata_title': {
      presence: true
    },
    'metadata_function': {
      presence: true
    },
    'metadata_geographic_coverage': {
      presence: true
    },
    'metadata_source': {
      presence: true
    },
    'metadata_date_of_content': {
      presence: true
    },
    'metadata_cautions': {
      presence: true
    },
  };

  var ContributeDataView = Backbone.View.extend({
    el: '#contributeDataView',

    model: new (Backbone.Model.extend({
      urlRoot: window.gfw.config.GFW_API_HOST_NEW_API + '/contribution-data/',
    })),

    events: {
      'change .js-radio-fieldset' : 'onChangeFieldset',
      'change input,textarea,select' : 'onChangeInput',
      'click .js-upload-file' : 'onClickFileUpload',
      'submit #new-contribution': 'onSubmitContribution',
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }
      this.cache();
      this.listeners();
      this.setUploadField();
    },

    listeners: function() {
    },

    cache: function() {
      this.$form = this.$el.find('#new-contribution');
      this.$fieldsets = this.$el.find('.-js-fieldset');
      this.$fieldSubmit = this.$el.find('#submit');
      this.$fieldFileUpload = this.$el.find('#fileupload');
      this.$fieldFileUploaded = this.$el.find('#fileuploaded');
      this.$fieldFileName = this.$el.find('#fileupload-name');
      this.$fieldFileBtn = this.$el.find('#fileupload-btn');
    },

    setUploadField: function() {
      var that = this;

      this.$fieldFileUpload.fileupload({
        url: '/data/upload',
        dataType: 'json',
        autoUpload: true,
        maxFileSize: MAXFILESIZE, // 10 MB
        timeout: TIMEOUT,
      })

      .on('fileuploadadd', function (e, data) {
        console.log(data);
        _.each(data.files, function(file) {
          if (file && file.size > MAXFILESIZE) {
            mps.publish('Notification/open', ['notification-limit-exceed']);
            return;
          } else {
            // Set upload spinner
            that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', true);
            // Set submit button
            that.$fieldSubmit.toggleClass('disabled', true);
            that.$fieldSubmit.prop('disabled', true);
            that.$fieldSubmit.val('Please wait...');
          }
        });
      })

      .on('fileuploaddone', function (e, data) {
        mps.publish('Notification/open', ['contribution-limit-exceed']);
        // Set 'data_uploaded' val and trigger the change
        that.$fieldFileUploaded.val(data.result.url).trigger("change");
        // Set upload spinner
        that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', false);
        // Set name of file
        that.$fieldFileName.text(data.files[0].name);
        // Set submit button
        that.$fieldSubmit.toggleClass('disabled', false);
        that.$fieldSubmit.prop('disabled', false);
        that.$fieldSubmit.val('Submit data');

      })

      .on('fileuploadfail', function (e, data){
        mps.publish('Notification/open', ['notification-upload-error-server']);
        // Set 'data_uploaded' val and trigger the change
        that.$fieldFileUploaded.val(null);
        // Set upload spinner
        that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', false);
        // Set name of file
        that.$fieldFileName.text('No file chosen');
        // Set submit button
        that.$fieldSubmit.toggleClass('disabled', false);
        that.$fieldSubmit.prop('disabled', false);
        that.$fieldSubmit.val('Submit data');
      });
    },

    /**
     * VALIDATIONS && FORM UPDATE
     * - validate
     * - validateInput
     */
    validate: function(attributesFromForm) {
      // Validate form, if is valid the response will be undefined
      this.errors = validate(attributesFromForm, constraints);
      return ! !!this.errors;
    },

    // TO-DO: validate checkbox
    validateInput: function(name, value) {
      let errors = validate.single(value, constraints[name]);
      if (!!errors) {
        this.errors[name] = errors[0];
      } else {
        this.errors && this.errors[name] && delete this.errors[name];
      }
    },

    updateForm: function() {
      this.$form.find('input, textarea, select').removeClass('-error');
      this.$form.find('[for]').removeClass('-error');
      for (var key in this.errors) {
        var $input = this.$form.find('[name='+key+']');
        var $label = this.$form.find('[for='+key+']');
        $input.addClass('-error');
        $label.addClass('-error');
      }
    },

    /**
     * UI EVENTS
     * - onChangeFieldset
     * - onChangeInput
     * - onSubmitContribution
     */
    onChangeFieldset: function(e) {
      var fieldset = this.$form.find('input[name="data_show"]:checked').data('fieldset');
      this.$fieldsets.toggleClass('-active', false);
      this.$fieldsets.filter('#fieldset-'+fieldset).toggleClass('-active', true);
    },

    onChangeInput: function(e) {
      var name = e.currentTarget.name,
          value = (e.currentTarget.value == 'on') ? true : e.currentTarget.value;

      this.validateInput(name, value);
      this.updateForm();
    },

    onClickFileUpload: function(e) {
      e && e.preventDefault();
      this.$fieldFileUpload.trigger('click');
    },

    onSubmitContribution: function(e) {
      e && e.preventDefault();
      var attributesFromForm = validate.collectFormValues(this.$form);

      if (this.validate(attributesFromForm)) {
        this.model.set(attributesFromForm).save()
          .then(function(){
            mps.publish('Notification/open', ['contribution-new-form-success']);
            $(document).scrollTop(0);
            setTimeout(function(){ window.location.reload(); }, 1000);
          })
          .fail(function(){
            mps.publish('Notification/open', ['contribution-new-form-error']);
          })

      } else {
        this.updateForm();
        mps.publish('Notification/open', ['contribution-new-form-error']);
        $(document).scrollTop(0);
      }
    }
  });

  return ContributeDataView;

});
<commit_msg>Contribute data: cleaning<commit_after>define([
  'jquery',
  'backbone',
  'handlebars',
  'underscore',
  'mps',
  'validate',
  'jquery_fileupload',

], function($, Backbone, Handlebars, _, mps, validate, jquery_fileupload) {

  'use strict';

  var MAXFILESIZE = 2000000000;
  var TIMEOUT = 3600000;

  var constraints = {
    'data_format': {
      presence: true,
    },
    'data_show': {
      presence: true,
    },
    'data_email': {
      presence: true,
      email: true,
    },
    'data_agree': {
      presence: true,
      inclusion: {
        within: [true],
      }
    },
    'data_terms': {
      presence: true,
      inclusion: {
        within: [true],
      }
    },
    'data_uploaded': {
      presence: true
    },
    'metadata_title': {
      presence: true
    },
    'metadata_function': {
      presence: true
    },
    'metadata_geographic_coverage': {
      presence: true
    },
    'metadata_source': {
      presence: true
    },
    'metadata_date_of_content': {
      presence: true
    },
    'metadata_cautions': {
      presence: true
    },
  };

  var ContributeDataView = Backbone.View.extend({
    el: '#contributeDataView',

    model: new (Backbone.Model.extend({
      urlRoot: window.gfw.config.GFW_API_HOST_NEW_API + '/contribution-data/',
    })),

    events: {
      'change .js-radio-fieldset' : 'onChangeFieldset',
      'change input,textarea,select' : 'onChangeInput',
      'click .js-upload-file' : 'onClickFileUpload',
      'submit #new-contribution': 'onSubmitContribution',
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }
      this.cache();
      this.listeners();
      this.setUploadField();
    },

    listeners: function() {
    },

    cache: function() {
      this.$form = this.$el.find('#new-contribution');
      this.$fieldsets = this.$el.find('.-js-fieldset');
      this.$fieldSubmit = this.$el.find('#submit');
      this.$fieldFileUpload = this.$el.find('#fileupload');
      this.$fieldFileUploaded = this.$el.find('#fileuploaded');
      this.$fieldFileName = this.$el.find('#fileupload-name');
      this.$fieldFileBtn = this.$el.find('#fileupload-btn');
    },

    setUploadField: function() {
      var that = this;

      this.$fieldFileUpload.fileupload({
        url: '/data/upload',
        dataType: 'json',
        autoUpload: true,
        maxFileSize: MAXFILESIZE, // 10 MB
        timeout: TIMEOUT,
      })

      .on('fileuploadadd', function (e, data) {
        _.each(data.files, function(file) {
          if (file && file.size > MAXFILESIZE) {
            mps.publish('Notification/open', ['notification-limit-exceed']);
            return;
          } else {
            // Set upload spinner
            that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', true);
            // Set submit button
            that.$fieldSubmit.toggleClass('disabled', true);
            that.$fieldSubmit.prop('disabled', true);
            that.$fieldSubmit.val('Please wait...');
          }
        });
      })

      .on('fileuploaddone', function (e, data) {
        mps.publish('Notification/open', ['notification-upload-success-server']);
        // Set 'data_uploaded' val and trigger the change
        that.$fieldFileUploaded.val(data.result.url).trigger("change");
        // Set upload spinner
        that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', false);
        // Set name of file
        that.$fieldFileName.text(data.files[0].name);
        // Set submit button
        that.$fieldSubmit.toggleClass('disabled', false);
        that.$fieldSubmit.prop('disabled', false);
        that.$fieldSubmit.val('Submit data');

      })

      .on('fileuploadfail', function (e, data){
        mps.publish('Notification/open', ['notification-upload-error-server']);
        // Set 'data_uploaded' val and trigger the change
        that.$fieldFileUploaded.val(null);
        // Set upload spinner
        that.$fieldFileBtn.find('.m-spinner').toggleClass('-start', false);
        // Set name of file
        that.$fieldFileName.text('No file chosen');
        // Set submit button
        that.$fieldSubmit.toggleClass('disabled', false);
        that.$fieldSubmit.prop('disabled', false);
        that.$fieldSubmit.val('Submit data');
      });
    },

    /**
     * VALIDATIONS && FORM UPDATE
     * - validate
     * - validateInput
     */
    validate: function(attributesFromForm) {
      // Validate form, if is valid the response will be undefined
      this.errors = validate(attributesFromForm, constraints);
      return ! !!this.errors;
    },

    // TO-DO: validate checkbox
    validateInput: function(name, value) {
      let errors = validate.single(value, constraints[name]);
      if (!!errors) {
        this.errors[name] = errors[0];
      } else {
        this.errors && this.errors[name] && delete this.errors[name];
      }
    },

    updateForm: function() {
      this.$form.find('input, textarea, select').removeClass('-error');
      this.$form.find('[for]').removeClass('-error');
      for (var key in this.errors) {
        var $input = this.$form.find('[name='+key+']');
        var $label = this.$form.find('[for='+key+']');
        $input.addClass('-error');
        $label.addClass('-error');
      }
    },

    /**
     * UI EVENTS
     * - onChangeFieldset
     * - onChangeInput
     * - onSubmitContribution
     */
    onChangeFieldset: function(e) {
      var fieldset = this.$form.find('input[name="data_show"]:checked').data('fieldset');
      this.$fieldsets.toggleClass('-active', false);
      this.$fieldsets.filter('#fieldset-'+fieldset).toggleClass('-active', true);
    },

    onChangeInput: function(e) {
      var name = e.currentTarget.name,
          value = (e.currentTarget.value == 'on') ? true : e.currentTarget.value;

      this.validateInput(name, value);
      this.updateForm();
    },

    onClickFileUpload: function(e) {
      e && e.preventDefault();
      this.$fieldFileUpload.trigger('click');
    },

    onSubmitContribution: function(e) {
      e && e.preventDefault();
      var attributesFromForm = validate.collectFormValues(this.$form);

      if (this.validate(attributesFromForm)) {
        this.model.set(attributesFromForm).save()
          .then(function(){
            mps.publish('Notification/open', ['contribution-new-form-success']);
            $(document).scrollTop(0);
            setTimeout(function(){ window.location.reload(); }, 1000);
          })
          .fail(function(){
            mps.publish('Notification/open', ['contribution-new-form-error']);
          })

      } else {
        this.updateForm();
        mps.publish('Notification/open', ['contribution-new-form-error']);
        $(document).scrollTop(0);
      }
    }
  });

  return ContributeDataView;

});
<|endoftext|>


<commit_before>var fs = require('fs');
var util = require('util');
var Carmen = require('..');
var tilelive = require('tilelive');
var context = require('../lib/context');
var UPDATE = process.env.UPDATE;
var test = require('tape');
var zlib = require('zlib');
var path = require('path');
var mapnik = require('mapnik');
var mem = require('../lib/api-mem');
var feature = require('../lib/util/feature');
var index = require('../lib/index');

mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'ogr.input'));

// limit_verify 1 implies that the correct result must be the very top
// result prior to context verification. It means even with a long list
// of competing results the correct candidate is sorted to the top.

// limit_verify 2 implies that there is some ambiguity prior to context
// verification (e.g. new york (city) vs new york (province)) that is sorted
// into the correct order after context verification occurs.

(function() {
    var conf = { address: new mem({geocoder_address: 1, maxzoom: 14, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('Index Cluster', function(t) {
        var vtile = new mapnik.VectorTile(14,3640,5670);
        var address = {
            _id:1,
            _geometry: {
                    type: "LineString",
                    coordinates: [[ -100.00605583190918,48.36314970496242],[-100.00185012817383,48.36640011246755]]
                },
            _text:'fake street',
            _center: [-100.00605583190918,48.36314970496242],
            _cluster: {
                9: { type: "Point", coordinates: [-100.00605583190918,48.36314970496242] },
                10: { type: "Point", coordinates: [-100.00185012817383,48.36640011246755] }
            }
        };
        vtile.addGeoJSON(JSON.stringify(address._geometry), "address");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.address.putTile(14,3640,5670, buffer, function() {
                index.update(conf.address, [address], 14, t.end);
            });
        });
    });

    test('contextVector reverse Cluster', function (t) {
        c.geocode('-100.00185012817383,48.36640011246755', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEquals(res, { features: [ { address: '10', center: [ -100.00185012817383, 48.36640011246755 ], geometry: { coordinates: [ -100.00185012817383, 48.36640011246755 ], type: 'Point' }, id: 'address.1', place_name: '10 fake street', properties: {}, relevance: 1, text: 'fake street', type: 'Feature' } ], query: [ -100.00185012817383, 48.36640011246755 ], type: 'FeatureCollection' }, 'Outputs address pt');
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

(function() {
    var conf = { postcode: new mem({maxzoom: 1, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('Index Poly & Point', function(t) {
        var vtile = new mapnik.VectorTile(1,0,0);
        var postcodePoly = {
            _id:1,
            _geometry: {
                type: "Polygon",
                coordinates: [[[-134.296875,44.08758502824516],[-134.296875,70.37785394109224],[-59.765625,70.37785394109224],[-59.765625,44.08758502824516],[-134.296875,44.08758502824516]]]
            },
            _center: [-97.03125, 57.2327194846687],
            _text:'fake polygon'
        };
        var postcodePoint = {
            _id: 2,
            _geometry: {
                type: "Point",
                coordinates: [-99.492,58.263]
            },
            _center: [-99.492,58.263],
            _text: "fake point"
        };
        vtile.addGeoJSON(JSON.stringify(postcodePoly._geometry), "address");
        vtile.addGeoJSON(JSON.stringify(postcodePoint._geometry), "address");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.postcode.putTile(1,0,0, buffer, function() {
                index.update(conf.postcode, [postcodePoint], 1, function() {
                    index.update(conf.postcode, [postcodePoly], 1, t.end);
                });
            });
        });
    });

    test('Ensure allFeatures', function(t) {
        feature.getAllFeatures(conf.postcode, function(err, feats) {
            t.ifError(err, 'no feature err');
            t.equals(feats.length, 2);
            t.end();
        });
    });

    test('contextVector reverse polygon', function (t) {
        c.geocode('-125.5078125,64.47279382008166', { limit_verify:1 }, function(err, res) {
            t.ifError(err, 'no geocode err');
            t.equal(res.features[0].text, 'fake polygon', 'returns polygon');
            t.end();
        });
    });

    test('contextVector reverse exact point - return polygon', function (t) {
        c.geocode('-99.492,58.263', { limit_verify:1 }, function(err, res) {
            t.ifError(err, 'no geocode err');
            t.equal(res.features[0].text, 'fake polygon', 'returns polygon');
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

//If the layer does not have geocoder_address do not take house number into account
(function() {
    var conf = { address: new mem({maxzoom: 1}, function() {}) };
    var c = new Carmen(conf);
    var vtile = new mapnik.VectorTile(1,0,0);

    test('index address', function(t) {
        var address = {
            _id:1,
            _text:'fake street',
            _center:[-97.031, 57.232],
            _geometry: {
                type: "Point",
                coordinates: [-97.031, 57.232]
              }
        };
        vtile.addGeoJSON(JSON.stringify(address._geometry), "address");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.address.putTile(1,0,0, buffer, function() {
                index.update(conf.address, [address], 1, function() {
                    index.update(conf.address, [address], 1, t.end);
                });
            });
        });
    });

    test('test address without geocoder_address', function(t) {
        c.geocode('9 fake street', { limit_verify: 1 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features[0].relevance, 0.6666666666666666);
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

(function() {
    var conf = { address: new mem({maxzoom: 1, geocoder_address: 1}, function() {}) };
    var c = new Carmen(conf);
    var vtile = new mapnik.VectorTile(1,0,0);

    test('index address', function(t) {
        var address = {
            _id: 1,
            _text:'beach street',
            _geometry: {
                type: "LineString",
                coordinates: [[-133.59375,58.07787626787517],[-79.453125,68.91100484562020]]
            },
            _center:[-133.59375,58.07787626787517],
            _rangetype:'tiger',
            _lfromhn: '23-100',
            _ltohn: '23-500'
        };
        vtile.addGeoJSON(JSON.stringify(address._geometry), "address");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.address.putTile(1,0,0, buffer, function() {
                index.update(conf.address, [address], 1, t.end);
            });
        });
    });

    test('test hyphenated address query with address range', function(t) {
        c.geocode('23-414 beach street', { limit_verify: 1 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features[0].place_name, '23-414 beach street', 'found 23-414 beach street');
            t.equals(res.features[0].relevance, 1);
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

// spatialmatch test to ensure the highest relev for a stacked zxy cell
// is used, disallowing a lower scoring cell from overwriting a previous
// entry.
(function() {
    var conf = {
        place: new mem({maxzoom: 1}, function() {}),
        address: new mem({maxzoom: 1, geocoder_address: 1}, function() {})
    };
    var c = new Carmen(conf);

    test('index place', function(t) {
        var vtile = new mapnik.VectorTile(1,0,0);
        var place = {
            _id:1,
            _text:'fakecity',
            _geometry: {
                type:"Polygon",
                coordinates:[[[-124.8046875,53.12040528310657],[-124.8046875,66.23145747862573],[-96.6796875,66.23145747862573],[-96.6796875,53.12040528310657],[-124.8046875,53.12040528310657]]]
            },
            _center:[-110.039,59.712],
        };
        vtile.addGeoJSON(JSON.stringify(place._geometry), "place");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.place.putTile(1,0,0, buffer, function() {
                index.update(conf.place, [place], 1, t.end);
            });
        });
    });

    test('index matching address', function(t) {
        var vtile = new mapnik.VectorTile(1,0,0);
        var featureOne = {
            _id: 2,
            _text:'fake street',
            _geometry: {
                type: "Point",
                coordinates: [-119.179,64.774]
            },
            _center:[-119.179,64.774],
            _cluster: {
                '1': { type: "Point", coordinates: [-119.179,64.774] }
            }
        };
        var featureTwo = {
            _id: 3,
            _text:'fake street',
            _geometry: {
                type: "Point",
                coordinates: [-100.546,57.891]
            },
            _center: [-100.546,57.891],
            _cluster: {
                '2': { type: "Point", coordinates: [-100.546,57.891] }
            }
        };
        vtile.addGeoJSON(JSON.stringify(featureOne._geometry), "address");
        vtile.addGeoJSON(JSON.stringify(featureTwo._geometry), "address");
        zlib.gzip(vtile.getData(), function(err, buffer) {
            t.ifError(err, 'vtile gzip success');
            conf.place.putTile(1,0,0, buffer, function() {
                index.update(conf.place, [place], 1, function() {
                    index.update(conf.place, [place], 1, t.end);
                });
            });
        });
    });

    test('test spatialmatch relev', function(t) {
        c.geocode('1 fake street fakecity', { limit_verify: 2 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features.length, 1);
            t.equals(res.features[0].relevance, 1);
            t.equals(res.features[0].id, 'address.2');
            t.end();
        });
    });
})();
<commit_msg>Add tile helper function<commit_after>var fs = require('fs');
var util = require('util');
var Carmen = require('..');
var tilelive = require('tilelive');
var context = require('../lib/context');
var UPDATE = process.env.UPDATE;
var test = require('tape');
var zlib = require('zlib');
var path = require('path');
var mapnik = require('mapnik');
var mem = require('../lib/api-mem');
var feature = require('../lib/util/feature');
var index = require('../lib/index');
var queue = require('queue-async');

mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'ogr.input'));

// limit_verify 1 implies that the correct result must be the very top
// result prior to context verification. It means even with a long list
// of competing results the correct candidate is sorted to the top.

// limit_verify 2 implies that there is some ambiguity prior to context
// verification (e.g. new york (city) vs new york (province)) that is sorted
// into the correct order after context verification occurs.

(function() {
    var conf = { address: new mem({geocoder_address: 1, maxzoom: 14, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('Index Cluster', function(t) {
        addFeature(conf, [14,3640,5670], [{
            properties: {
                _id:1,
                _text:'fake street',
                _center: [-100.00605583190918,48.36314970496242],
                _cluster: {
                    9: { type: "Point", coordinates: [-100.00605583190918,48.36314970496242] },
                    10: { type: "Point", coordinates: [-100.00185012817383,48.36640011246755] }
                }
            },
            geometry: {
                type: "LineString",
                coordinates: [[ -100.00605583190918,48.36314970496242],[-100.00185012817383,48.36640011246755]]
            }
        }], "address", t);
    });

    test('contextVector reverse Cluster', function (t) {
        c.geocode('-100.00185012817383,48.36640011246755', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEquals(res, { features: [ { address: '10', center: [ -100.00185012817383, 48.36640011246755 ], geometry: { coordinates: [ -100.00185012817383, 48.36640011246755 ], type: 'Point' }, id: 'address.1', place_name: '10 fake street', properties: {}, relevance: 1, text: 'fake street', type: 'Feature' } ], query: [ -100.00185012817383, 48.36640011246755 ], type: 'FeatureCollection' }, 'Outputs address pt');
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

(function() {
    var conf = { postcode: new mem({maxzoom: 1, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('Index Poly & Point', function(t) {
        addFeature(conf, [1,0,0], [{
            properties: {
                _id:1,
                _center: [-97.03125, 57.2327194846687],
                _text:'fake polygon'
            },
            geometry: {
                type: "Polygon",
                coordinates: [[[-134.296875,44.08758502824516],[-134.296875,70.37785394109224],[-59.765625,70.37785394109224],[-59.765625,44.08758502824516],[-134.296875,44.08758502824516]]]
            }
        },{
            properties: {
                _id: 2,
                _center: [-99.492,58.263],
                _text: "fake point"
            },
            geometry: {
                type: "Point",
                coordinates: [-99.492,58.263]
            }
        }], "postcode", t);
    });

    test('Ensure allFeatures', function(t) {
        feature.getAllFeatures(conf.postcode, function(err, feats) {
            t.ifError(err, 'no feature err');
            t.equals(feats.length, 2);
            t.end();
        });
    });

    test('contextVector reverse polygon', function (t) {
        c.geocode('-125.5078125,64.47279382008166', { limit_verify:1 }, function(err, res) {
            t.ifError(err, 'no geocode err');
            t.equal(res.features[0].text, 'fake polygon', 'returns polygon');
            t.end();
        });
    });

    test('contextVector reverse exact point - return polygon', function (t) {
        c.geocode('-99.492,58.263', { limit_verify:1 }, function(err, res) {
            t.ifError(err, 'no geocode err');
            t.equal(res.features[0].text, 'fake polygon', 'returns polygon');
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

//If the layer does not have geocoder_address do not take house number into account
(function() {
    var conf = { address: new mem({maxzoom: 1, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('index address', function(t) {
        addFeature(conf, [1,0,0], [{
            properties: {
                _id:1,
                _text:'fake street',
                _center:[-97.031, 57.232],
            },
            geometry: {
                type: "Point",
                coordinates: [-97.031, 57.232]
            }
        }], "address", t);
    });

    test('test address without geocoder_address', function(t) {
        c.geocode('9 fake street', { limit_verify: 1 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features[0].relevance, 0.6666666666666666);
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

(function() {
    var conf = { address: new mem({maxzoom: 1, geocoder_address: 1, format: 'pbf'}, function() {}) };
    var c = new Carmen(conf);

    test('index address', function(t) {
        addFeature(conf, [1,0,0], [{
            properties: {
                _id: 1,
                _text:'beach street',
                _center:[-133.59375,58.07787626787517],
                _rangetype:'tiger',
                _lfromhn: '23-100',
                _ltohn: '23-500'
            },
            geometry: {
                type: "LineString",
                coordinates: [[-133.59375,58.07787626787517],[-79.453125,68.91100484562020]]
            }
        }], "address", t);
    });

    test('test hyphenated address query with address range', function(t) {
        c.geocode('23-414 beach street', { limit_verify: 1 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features[0].place_name, '23-414 beach street', 'found 23-414 beach street');
            t.equals(res.features[0].relevance, 1);
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

// spatialmatch test to ensure the highest relev for a stacked zxy cell
// is used, disallowing a lower scoring cell from overwriting a previous
// entry.
(function() {
    var conf = {
        place: new mem({maxzoom: 1, format: 'pbf'}, function() {}),
        address: new mem({maxzoom: 1, geocoder_address: 1, format: 'pbf'}, function() {})
    };
    var c = new Carmen(conf);

    test('index place', function(t) {
        addFeature(conf, [1,0,0], [{
            properties: {
                _id:1,
                _text:'fakecity',
                _center:[-110.039,59.712],
            },
            geometry: {
                type:"Polygon",
                coordinates:[[[-124.8046875,53.12040528310657],[-124.8046875,66.23145747862573],[-96.6796875,66.23145747862573],[-96.6796875,53.12040528310657],[-124.8046875,53.12040528310657]]]
            }
        }], "place", t);
    });

    test('index matching address', function(t) {
        addFeature(conf, [1,0,0], [{
            properties: {
                _id: 2,
                _text:'fake street',
                _center:[-110.039,59.712],
                _cluster: {
                    '1': { type: "Point", coordinates: [-110.039,59.712] }
                }
            },
            geometry: {
                type: "Point",
                coordinates: [-110.039,59.712]
            },
        }, {
            properties: {
                _id: 3,
                _text:'fake street',
                _center: [-110.039,59.712],
                _cluster: {
                    '2': { type: "Point", coordinates: [-110.039,59.712] }
                }
            },
            geometry: {
                type: "Point",
                coordinates: [-110.039,59.712]
            }
        }], "address", t);
    });

    test('test spatialmatch relev', function(t) {
        c.geocode('1 fake street fakecity', { limit_verify: 2 }, function (err, res) {
            t.ifError(err);
            t.equals(res.features.length, 1);
            t.equals(res.features[0].relevance, 1);
            t.equals(res.features[0].id, 'address.2');
            t.end();
        });
    });

    test('index teardown', function(t){
        index.teardown();
        t.end();
    });
})();

function addFeature(conf, zxy, features, layer, t) {
    var vtile = new mapnik.VectorTile(zxy[0],zxy[1],zxy[2]);
    features.forEach(function(feature) {
        feature = JSON.parse(JSON.stringify(feature));
        feature.geometry.properties = feature.properties;
        vtile.addGeoJSON(JSON.stringify(feature.geometry), layer);
    });

    zlib.gzip(vtile.getData(), function(err, buffer) {
        t.ifError(err, 'vtile gzip success');
        conf[layer].putTile(zxy[0],zxy[1],zxy[2], buffer, function() {
            q = new queue(1);
            features.forEach(function(feature) {
                feature.properties._geometry = feature.geometry;
                q.defer(index.update, conf[layer], [feature.properties], zxy[0]);
            });
            q.awaitAll(function(err, res) {
                t.ifError(err);
                t.end();
            });
        });
    });
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('commander');
var fs = require('fs');
var rm = require('rimraf');
var inquirer = require('inquirer');
var glob = require('glob');
var project = require('./package.json');

program
    .version(project.version)
    .parse(process.argv);

function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
}

// Initialisation prompt questions
var questions = [{
    name: 'name',
    message: 'Project name:',
    validate: function(input) {
        return input !== '' ? true : 'You must enter a valid name.';
    }
}, {
    name: 'templates',
    type: 'confirm',
    message: 'Include VTT templates?',
    default: true
}, {
    name: 'version',
    message: 'Project version:',
    default: '0.0.1',
    validate: function(input) {
        return input !== '' ? true : 'You must enter a valid version.';
    }
}, {
    name: 'description',
    message: 'Project description:'
}, {
    name: 'keywords',
    message: 'Project keywords:'
}, {
    name: 'url',
    message: 'Project url:',
    default: 'http://127.0.0.1:3000'
}, {
    name: 'repository',
    message: 'Project git repository:'
}];

// Prompt user for project informations
inquirer.prompt(questions, function(answers) {
    // Update project values
    project.name = answers.name;
    project.version = answers.version;
    project.description = answers.description;
    project.keywords = answers.keywords;
    project.url = answers.url;
    project.repository = answers.repository;
    project.jsname = answers.jsname;
    project.templates = answers.templates;

    // Save new project values
    fs.writeFile('./package.json', JSON.stringify(project, null, 2), function(error) {
        if (error) return console.log(error);
    });

    // Save new project values
    glob('./src/js/**/*.js', function(error, files) {
        if (error) return console.log(error);

        for (var i = 0, t = files.length; i < t; i++) {
            (function(i) {
                var file = files[i];

                // Replace module name inside template file
                fs.readFile(file, 'utf8', function(error, data) {
                    if (error) return console.log(error);

                    data = replaceAll('PROJECT_NAME', answers.jsname, data);

                    fs.writeFile(file, data, 'utf8', function(error) {
                        if (error) return console.log(error);
                    });
                });
            })(i);
        }
    });

    // Remove templates files
    if (!answers.templates) {
        rm('./src/twig/templates/', function(error) {
            if (error) return console.log(error);
        });
        rm('./src/sass/templates.scss', function(error) {
            if (error) return console.log(error);
        });
    }
});
<commit_msg>Update default localhost from init.js<commit_after>#!/usr/bin/env node

var program = require('commander');
var fs = require('fs');
var rm = require('rimraf');
var inquirer = require('inquirer');
var glob = require('glob');
var project = require('./package.json');

program
    .version(project.version)
    .parse(process.argv);

function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
}

// Initialisation prompt questions
var questions = [{
    name: 'name',
    message: 'Project name:',
    validate: function(input) {
        return input !== '' ? true : 'You must enter a valid name.';
    }
}, {
    name: 'templates',
    type: 'confirm',
    message: 'Include VTT templates?',
    default: true
}, {
    name: 'version',
    message: 'Project version:',
    default: '0.0.1',
    validate: function(input) {
        return input !== '' ? true : 'You must enter a valid version.';
    }
}, {
    name: 'description',
    message: 'Project description:'
}, {
    name: 'keywords',
    message: 'Project keywords:'
}, {
    name: 'url',
    message: 'Project url:',
    default: 'http://localhost:3000'
}, {
    name: 'repository',
    message: 'Project git repository:'
}];

// Prompt user for project informations
inquirer.prompt(questions, function(answers) {
    // Update project values
    project.name = answers.name;
    project.version = answers.version;
    project.description = answers.description;
    project.keywords = answers.keywords;
    project.url = answers.url;
    project.repository = answers.repository;
    project.jsname = answers.jsname;
    project.templates = answers.templates;

    // Save new project values
    fs.writeFile('./package.json', JSON.stringify(project, null, 2), function(error) {
        if (error) return console.log(error);
    });

    // Save new project values
    glob('./src/js/**/*.js', function(error, files) {
        if (error) return console.log(error);

        for (var i = 0, t = files.length; i < t; i++) {
            (function(i) {
                var file = files[i];

                // Replace module name inside template file
                fs.readFile(file, 'utf8', function(error, data) {
                    if (error) return console.log(error);

                    data = replaceAll('PROJECT_NAME', answers.jsname, data);

                    fs.writeFile(file, data, 'utf8', function(error) {
                        if (error) return console.log(error);
                    });
                });
            })(i);
        }
    });

    // Remove templates files
    if (!answers.templates) {
        rm('./src/twig/templates/', function(error) {
            if (error) return console.log(error);
        });
        rm('./src/sass/templates.scss', function(error) {
            if (error) return console.log(error);
        });
    }
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var phantomjs = require('phantomjs');
process.env.PATH += ':' + path.dirname(phantomjs.path);

var phantom = require('phantom');
var d3graph = require('./d3graph.js').d3graph;
var htmlStub = '';

/**
 * generateGraphImage, a function to generate an image with a graph of the memory usage during the test.
 * @param filename - optional name of file to write graph image to.
 * @param graphData - array of 2 objects containing the memory results.
 * @param graphWidth - integar value for graph width.
 * @param graphHeight - integar value for graph height.
 */
module.exports.generateGraphImage = function(filename, graphData, graphWidth, graphHeight) {
	console.log("Starting Phantomjs to generate graph");
    var d = protractor.promise.defer();
	protractor.promise.controlFlow().execute(function() {
        phantom.create(function(ph) {
            // Create html page server-side for phantom to render
            return ph.createPage(function(page) {
                // Set content of page
                page.content = htmlStub;
                page.set('viewportSize', { width: graphWidth, height : graphHeight });

                //Inject D3 in sandboxed page
                page.injectJs(path.join(__dirname, '../node_modules/d3/d3.js'), function(fileFound) {
                    if(fileFound) {
                        //Execute JavaScript function 'd3graph' to generate graph in page context using evaluate.
                        //Pass graphData, graphWidth and graphHeight to the sandboxed page to use as the 'data' parameter in the third argument in evaluate.
                        page.evaluate(d3graph, function(){ d.fulfill(true) }, graphData, graphWidth, graphHeight);

                        page.render(filename);
                        ph.exit();
                        console.log("Graph generated");
                    } else {
                        console.log("D3 not found, graph could not be created");
                    }
                });
            });
        });
    });

    return d.promise;
};<commit_msg>SDHTML-9666: Handle windows PATH for phantomjs<commit_after>'use strict';

var path = require('path');
var phantomjs = require('phantomjs');

if(process.platform === 'win32' || process.platform === 'win64') {
    process.env.PATH += ';' + path.dirname(phantomjs.path);
} else {
    process.env.PATH += ':' + path.dirname(phantomjs.path);
}

var phantom = require('phantom');
var d3graph = require('./d3graph.js').d3graph;
var htmlStub = '';

/**
 * generateGraphImage, a function to generate an image with a graph of the memory usage during the test.
 * @param filename - optional name of file to write graph image to.
 * @param graphData - array of 2 objects containing the memory results.
 * @param graphWidth - integer value for graph width.
 * @param graphHeight - integer value for graph height.
 */
module.exports.generateGraphImage = function(filename, graphData, graphWidth, graphHeight) {
	console.log("Starting Phantomjs to generate graph");
    var d = protractor.promise.defer();
	protractor.promise.controlFlow().execute(function() {
        phantom.create(function(ph) {
            // Create html page server-side for phantom to render
            return ph.createPage(function(page) {
                // Set content of page
                page.content = htmlStub;
                page.set('viewportSize', { width: graphWidth, height : graphHeight });

                //Inject D3 in sandboxed page
                page.injectJs(path.join(__dirname, '../node_modules/d3/d3.js'), function(fileFound) {
                    if(fileFound) {
                        //Execute JavaScript function 'd3graph' to generate graph in page context using evaluate.
                        //Pass graphData, graphWidth and graphHeight to the sandboxed page to use as the 'data' parameter in the third argument in evaluate.
                        page.evaluate(d3graph, function(){ d.fulfill(true) }, graphData, graphWidth, graphHeight);

                        page.render(filename);
                        ph.exit();
                        console.log("Graph generated");
                    } else {
                        console.log("D3 not found, graph could not be created");
                    }
                });
            });
        }, {
            dnodeOpts: {
                weak: false
            }
        });
    });

    return d.promise;
};<|endoftext|>


<commit_before>(function () {

  var ng = angular.module;

  function identifierForController(controller, ident) {
    if (ident && typeof ident === 'string') return ident;
    if (typeof controller === 'string') {
      var match = /^(\S+)(\s+as\s+(\w+))?$/.exec(controller);
      if (match) return match[3];
    }
  }

  function module() {

    var hijacked = ng.apply(this, arguments);

    if (hijacked.component) {
      return hijacked;
    }

    function component(name, options) {

      function factory($injector) {

        function makeInjectable(fn) {
          var closure;
          var isArray = angular.isArray(fn);
          if (angular.isFunction(fn) || isArray) {
            return function (tElement, tAttrs) {
              return $injector.invoke((isArray ? fn : [
                '$element',
                '$attrs',
                fn
              ]), this, {
                $element: tElement,
                $attrs: tAttrs
              });
            };
          } else {
            return fn;
          }
        }

        var oneWayQueue = [];

        function parseBindings(bindings) {
          var newBindings = {};
          for (var prop in bindings) {
            var binding = bindings[prop];
            if (binding.charAt(0) === '<') {
              var attr = binding.substring(1);
              oneWayQueue.unshift({
              	local: prop,
                attr: attr === '' ? prop : attr
              });
            } else {
              newBindings[prop] = binding;
            }
          }
          return newBindings;
        }

        var modifiedBindings = parseBindings(options.bindings);

        var requires = [name];
        var ctrlNames = [];
        if (angular.isObject(options.require)) {
          for (var prop in options.require) {
            requires.push(options.require[prop]);
            ctrlNames.push(prop);
          }
        }

        return {
          controller: options.controller || angular.noop,
          controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
          template: makeInjectable(
            !options.template && !options.templateUrl ? '' : options.template
          ),
          templateUrl: makeInjectable(options.templateUrl),
          transclude: options.transclude,
          scope: modifiedBindings || {},
          bindToController: !!modifiedBindings,
          restrict: 'E',
          require: requires,
          link: {
            pre: function ($scope, $element, $attrs, $ctrls) {
              var self = $ctrls[0];
              for (var i = 0; i < ctrlNames.length; i++) {
                self[ctrlNames[i]] = $ctrls[i + 1];
              }
              if (typeof self.$onInit === 'function') {
                self.$onInit();
              }
              if (typeof self.$onDestroy === 'function') {
                $scope.$on('$destroy', function () {
                  self.$onDestroy.call(self);
                });
              }
              var changes;
              function triggerOnChanges() {
                self.$onChanges(changes);
                changes = undefined;
              }
              function updateChangeListener(key, newValue, oldValue, flush) {
                if (typeof self.$onChanges === 'function') {
                  if (!changes) {
                    changes = {};
                  }
                  if (changes[key]) {
                    oldValue = changes[key].currentValue;
                  }
                  changes[key] = {
                    currentValue: newValue,
                    previousValue: oldValue
                  };
                  if (flush) {
                    triggerOnChanges();
                  }
                }
              }
              if (oneWayQueue.length) {
                var destroyQueue = [];
                for (var q = oneWayQueue.length; q--;) {
				  (function(current){
					  var unbindParent = $scope.$parent.$watch($attrs[current.attr], function (newValue, oldValue) {
						self[current.local] = newValue;
						updateChangeListener(current.local, newValue, oldValue, true);
					  });
					  destroyQueue.unshift(unbindParent);
					  var unbindLocal = $scope.$watch(function () {
						return self[current.local];
					  }, function (newValue, oldValue) {
						updateChangeListener(current.local, newValue, oldValue, false);
					  });
					  destroyQueue.unshift(unbindLocal);
				  })(oneWayQueue[q]);
                }
                $scope.$on('$destroy', function () {
                  for (var i = destroyQueue.length; i--;) {
                    destroyQueue[i]();
                  }
                });
              }
            },
            post: function ($scope, $element, $attrs, $ctrls) {
              var self = $ctrls[0];
              if (typeof self.$postLink === 'function') {
                self.$postLink();
              }
            }
          }
        };
      }

      for (var key in options) {
        if (key.charAt(0) === '$') {
          factory[key] = options[key];
        }
      }

      factory.$inject = ['$injector'];

      return hijacked.directive(name, factory);

    }

    hijacked.component = component;

    return hijacked;

  }

  angular.module = module;

})();
<commit_msg>Tabs replaced by spaces (2x indentation)<commit_after>(function () {

  var ng = angular.module;

  function identifierForController(controller, ident) {
    if (ident && typeof ident === 'string') return ident;
    if (typeof controller === 'string') {
      var match = /^(\S+)(\s+as\s+(\w+))?$/.exec(controller);
      if (match) return match[3];
    }
  }

  function module() {

    var hijacked = ng.apply(this, arguments);

    if (hijacked.component) {
      return hijacked;
    }

    function component(name, options) {

      function factory($injector) {

        function makeInjectable(fn) {
          var closure;
          var isArray = angular.isArray(fn);
          if (angular.isFunction(fn) || isArray) {
            return function (tElement, tAttrs) {
              return $injector.invoke((isArray ? fn : [
                '$element',
                '$attrs',
                fn
              ]), this, {
                $element: tElement,
                $attrs: tAttrs
              });
            };
          } else {
            return fn;
          }
        }

        var oneWayQueue = [];

        function parseBindings(bindings) {
          var newBindings = {};
          for (var prop in bindings) {
            var binding = bindings[prop];
            if (binding.charAt(0) === '<') {
              var attr = binding.substring(1);
              oneWayQueue.unshift({
              	local: prop,
                attr: attr === '' ? prop : attr
              });
            } else {
              newBindings[prop] = binding;
            }
          }
          return newBindings;
        }

        var modifiedBindings = parseBindings(options.bindings);

        var requires = [name];
        var ctrlNames = [];
        if (angular.isObject(options.require)) {
          for (var prop in options.require) {
            requires.push(options.require[prop]);
            ctrlNames.push(prop);
          }
        }

        return {
          controller: options.controller || angular.noop,
          controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
          template: makeInjectable(
            !options.template && !options.templateUrl ? '' : options.template
          ),
          templateUrl: makeInjectable(options.templateUrl),
          transclude: options.transclude,
          scope: modifiedBindings || {},
          bindToController: !!modifiedBindings,
          restrict: 'E',
          require: requires,
          link: {
            pre: function ($scope, $element, $attrs, $ctrls) {
              var self = $ctrls[0];
              for (var i = 0; i < ctrlNames.length; i++) {
                self[ctrlNames[i]] = $ctrls[i + 1];
              }
              if (typeof self.$onInit === 'function') {
                self.$onInit();
              }
              if (typeof self.$onDestroy === 'function') {
                $scope.$on('$destroy', function () {
                  self.$onDestroy.call(self);
                });
              }
              var changes;
              function triggerOnChanges() {
                self.$onChanges(changes);
                changes = undefined;
              }
              function updateChangeListener(key, newValue, oldValue, flush) {
                if (typeof self.$onChanges === 'function') {
                  if (!changes) {
                    changes = {};
                  }
                  if (changes[key]) {
                    oldValue = changes[key].currentValue;
                  }
                  changes[key] = {
                    currentValue: newValue,
                    previousValue: oldValue
                  };
                  if (flush) {
                    triggerOnChanges();
                  }
                }
              }
              if (oneWayQueue.length) {
                var destroyQueue = [];
                for (var q = oneWayQueue.length; q--;) {
                  (function(current){
                    var unbindParent = $scope.$parent.$watch($attrs[current.attr], function (newValue, oldValue) {
                      self[current.local] = newValue;
                      updateChangeListener(current.local, newValue, oldValue, true);
                    });
                    destroyQueue.unshift(unbindParent);
                    var unbindLocal = $scope.$watch(function () {
                      return self[current.local];
                    }, function (newValue, oldValue) {
                      updateChangeListener(current.local, newValue, oldValue, false);
                    });
                    destroyQueue.unshift(unbindLocal);
                  })(oneWayQueue[q]);
                }
                $scope.$on('$destroy', function () {
                  for (var i = destroyQueue.length; i--;) {
                    destroyQueue[i]();
                  }
                });
              }
            },
            post: function ($scope, $element, $attrs, $ctrls) {
              var self = $ctrls[0];
              if (typeof self.$postLink === 'function') {
                self.$postLink();
              }
            }
          }
        };
      }

      for (var key in options) {
        if (key.charAt(0) === '$') {
          factory[key] = options[key];
        }
      }

      factory.$inject = ['$injector'];

      return hijacked.directive(name, factory);

    }

    hijacked.component = component;

    return hijacked;

  }

  angular.module = module;

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Radium from 'radium'
import { mediaQueries } from '../../styles/common'
import colors from '../../styles/colors'
import { Link } from '../../components'

import hamburgerIcon from './hamburger.svg'

const styles = {
  container: {
    [mediaQueries.mediumUp]: {
      display: 'none'
    }
  },
  hamburger: {
    height: '100%'
  },
  hamburgerIcon: {
    borderStyle: 'solid',
    borderWidth: '1px',
    borderColor: colors.white,
    borderRadius: '5px',
    height: '1.8em',
    margin: '10px',
    padding: '10px'
  },
  image: {
    height: '40%'
  },
  links: {
    color: colors.white,
    marginBottom: '20px',
    marginTop: '20px',
    textDecoration: 'none'
  },
  li: {
    marginBottom: '20px'
  },
  menu: {
    textAlign: 'center',
    width: '100%',
    backgroundColor: colors.primary,
    fontSize: '2em'
  }
}

class MobileMenu extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isMenuVisible: false
    }

    this.toggleMenuVisibility = this.toggleMenuVisibility.bind(this)
  }

  renderButton(button, i) {
    return (

        <Link to={button.to} style={[styles.links, button.style]}>
        {button.title}
        </Link>

    )
  }

  renderMenu() {
    let btns = this.props.navigationButtons

    if (!this.state.isMenuVisible) {
      return
    }

    return (

          {
            btns.map((btn, i) => {
              return this.renderButton(btn, i)
            })
          }

    )
  }

  toggleMenuVisibility() {
    this.setState({
      isMenuVisible: !this.state.isMenuVisible
    })
  }

  render(){
    return(

        { this.renderMenu() }

    )
  }
}

export default Radium(MobileMenu)
<commit_msg>Vertically center mobile navbar<commit_after>import React, { Component } from 'react'
import Radium from 'radium'
import { mediaQueries } from '../../styles/common'
import colors from '../../styles/colors'
import { Link } from '../../components'

import hamburgerIcon from './hamburger.svg'

const styles = {
  container: {
    height: '100%',
    [mediaQueries.mediumUp]: {
      display: 'none'
    }
  },
  hamburger: {
    height: '100%'
  },
  hamburgerIcon: {
    borderStyle: 'solid',
    borderWidth: '1px',
    borderColor: colors.white,
    borderRadius: '5px',
    height: '1.8em',
    margin: '10px',
    padding: '10px'
  },
  image: {
    height: '40%'
  },
  links: {
    color: colors.white,
    marginBottom: '20px',
    marginTop: '20px',
    textDecoration: 'none'
  },
  li: {
    marginBottom: '20px'
  },
  menu: {
    textAlign: 'center',
    width: '100%',
    fontSize: '2em',
    position: 'relative',
    bottom: '0.9em'
  }
}

class MobileMenu extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isMenuVisible: false
    }

    this.toggleMenuVisibility = this.toggleMenuVisibility.bind(this)
  }

  renderButton(button, i) {
    return (

        <Link to={button.to} style={[styles.links, button.style]}>
        {button.title}
        </Link>

    )
  }

  renderMenu() {
    let btns = this.props.navigationButtons

    if (!this.state.isMenuVisible) {
      return
    }

    return (

          {
            btns.map((btn, i) => {
              return this.renderButton(btn, i)
            })
          }

    )
  }

  toggleMenuVisibility() {
    this.setState({
      isMenuVisible: !this.state.isMenuVisible
    })
  }

  render(){
    return(

          { this.renderMenu() }

    )
  }
}

export default Radium(MobileMenu)
<|endoftext|>


<commit_before>'use strict';
const reportErrorRedis = function( error ) {
    if ( error !== null ) {
        console.log( error );
    }
};
const Redis         = require( 'redis' ).createClient().on( 'error', reportErrorRedis );
const Time          = require( '@augur/augur-modules' )( 'time' );
const cacheInMemory = {};
const REQUEST_OPTIONS = {};

Redis.keys('cache:userAgentParser:*', function( error, userAgentKeyList ) {
    if ( error !== null ) {
        return reportErrorRedis({ from:'Load userAgentKeyList', error: error });
    }

    for ( let i = 0, j = userAgentKeyList.length; i < j; i++ ) {
        userAgentKeyList[i] = [ 'get', userAgentKeyList[i] ];
    }

    Redis.multi( userAgentKeyList ).exec(function( error, userAgentKeyCacheValues ) {
        if ( error !== null ) {
            return reportErrorRedis({ from:'Load userAgentKeyCacheValues', error: error });
        }
        for ( let i = 0, j = userAgentKeyCacheValues.length; i < j; i++ ) {
            cacheInMemory[ userAgentKeyList[i] ] = userAgentKeyCacheValues[i];
        }
    });
});

function updateCache( userAgent, UA_DATA ) {
    console.log('UPDATING CACHE');
    cacheInMemory[ userAgent ] = UA_DATA;
    setImmediate(function( userAgent, UA_DATA ) {
        const endOfMonth = Time('endOfMonth');

        Redis.set( 'cache:userAgentParser:' + userAgent, UA_DATA, reportErrorRedis );
        Redis.expire( 'cache:userAgentParser:' + userAgent, endOfMonth, reportErrorRedis );
    }, userAgent, UA_DATA );
}

async function parseUserAgent( userAgent ) { // jshint ignore:line
        if ( cacheInMemory[ userAgent ] !== undefined ) {
            return cacheInMemory[ userAgent ];
        } else {
            const UA_DATA = await require( './cloud.js' )( REQUEST_OPTIONS )( userAgent ); // jshint ignore:line
            updateCache( userAgent, UA_DATA );
            return UA_DATA;
        }
}

module.exports = function( requestOptions ) {
    for ( let option in requestOptions ) {
        REQUEST_OPTIONS[ option ] = requestOptions[ option ];
    }
    return parseUserAgent;
};
<commit_msg>Expire UAs after 20 days.<commit_after>'use strict';
const reportErrorRedis = function( error ) {
    if ( error !== null ) {
        console.log( error );
    }
};
const Redis         = require( 'redis' ).createClient().on( 'error', reportErrorRedis );
const cacheInMemory = {};
const REQUEST_OPTIONS = {};

Redis.keys('cache:userAgentParser:*', function( error, userAgentKeyList ) {
    if ( error !== null ) {
        return reportErrorRedis({ from:'Load userAgentKeyList', error: error });
    }

    for ( let i = 0, j = userAgentKeyList.length; i < j; i++ ) {
        userAgentKeyList[i] = [ 'get', userAgentKeyList[i] ];
    }

    Redis.multi( userAgentKeyList ).exec(function( error, userAgentKeyCacheValues ) {
        if ( error !== null ) {
            return reportErrorRedis({ from:'Load userAgentKeyCacheValues', error: error });
        }
        for ( let i = 0, j = userAgentKeyCacheValues.length; i < j; i++ ) {
            cacheInMemory[ userAgentKeyList[i] ] = userAgentKeyCacheValues[i];
        }
    });
});

function updateCache( userAgent, UA_DATA ) {
    cacheInMemory[ userAgent ] = UA_DATA;
    setImmediate(function( userAgent, UA_DATA ) {
        const twentyDays = new Date().getTime() + 86400 * 1000 * 20;

        Redis.set( 'cache:userAgentParser:' + userAgent, JSON.stringify(UA_DATA), reportErrorRedis );
        Redis.expire( 'cache:userAgentParser:' + userAgent, twentyDays, reportErrorRedis );
    }, userAgent, UA_DATA );
}

async function parseUserAgent( userAgent ) { // jshint ignore:line
        if ( cacheInMemory[ userAgent ] !== undefined ) {
            return cacheInMemory[ userAgent ];
        } else {
            const UA_DATA = await require( './cloud.js' )( REQUEST_OPTIONS )( userAgent ); // jshint ignore:line
            updateCache( userAgent, UA_DATA );
            return UA_DATA;
        }
}

module.exports = function( requestOptions ) {
    for ( let option in requestOptions ) {
        REQUEST_OPTIONS[ option ] = requestOptions[ option ];
    }
    return parseUserAgent;
};
<|endoftext|>


<commit_before>importScripts("simulation.js");
importScripts("simulationtools.js");
importScripts("person.js");
importScripts("hcv.js");

self.onmessage = function (e) {
    var seconds1 = new Date().getTime() / 1000;

	var SimNumber = e.data.SimNumber;
    var SimData = e.data.SimData;

	IncrementSize=Math.round(SimData.NoPeople/100);

	Year=2014.5;
	GenotypeValue=0;
	Age=29;
	Sex=1;
	Alcohol=0;

	HCVParam={};
	HCVParam.F0F1=0.2;
	HCVParam.F1F2=0.1;
	HCVParam.F2F3=0.15;
	HCVParam.F3F4=0.3;
	HCVParam.F4LF=0.5;
	HCVParam.F4HCC=0.4;

	self.postMessage({ConsoleMessage: "Starting to load Person object"});

	var PP=[];
	for (i=0; i<SimData.NoPeople; i++){
		PP.push(new PersonObject(2, 1985.1));
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});

	for (i=0; i<SimData.NoPeople; i++){
		PP[i].HCV.Infection(Year, GenotypeValue, Age, Sex, Alcohol, HCVParam );
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	//Determine fibrosis levels with year

	FibrosisMatrix=new ZeroMatrix(6, 100);

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});
	YearCount=0;
	for (GraphYear=Year-1; GraphYear<Year+40; GraphYear++){
		for (i=0; i<SimData.NoPeople; i++){
			FibrosisLevel=PP[i].HCV.Fibrosis.Get(GraphYear).Value;
			//self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
			FibrosisMatrix[FibrosisLevel][YearCount]=FibrosisMatrix[FibrosisLevel][YearCount]+1;;
		}
		YearCount++;
		self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
	}

	var seconds2 = new Date().getTime() / 1000;
    TotalTime=seconds2 -seconds1;

	self.postMessage({ConsoleMessage: "Finished simulation in "+TotalTime+" seconds"});
	self.postMessage({Result: FibrosisMatrix});
};
<commit_msg>Adding real values<commit_after>importScripts("simulation.js");
importScripts("simulationtools.js");
importScripts("person.js");
importScripts("hcv.js");

self.onmessage = function (e) {
    var seconds1 = new Date().getTime() / 1000;

	var SimNumber = e.data.SimNumber;
    var SimData = e.data.SimData;

	IncrementSize=Math.round(SimData.NoPeople/100);

	Year=2014.5;
	GenotypeValue=0;
	Age=29;
	Sex=1;
	Alcohol=0;

	HCVParam={};
	HCVParam.F0F1=0.117;
	HCVParam.F1F2=0.085;
	HCVParam.F2F3=0.12;
	HCVParam.F3F4=0.116;
	HCVParam.F4LF=0.0001;//not real
	HCVParam.F4HCC=0.4;//not real

	self.postMessage({ConsoleMessage: "Starting to load Person object"});

	var PP=[];
	for (i=0; i<SimData.NoPeople; i++){
		PP.push(new PersonObject(2, 1985.1));
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});

	for (i=0; i<SimData.NoPeople; i++){
		PP[i].HCV.Infection(Year, GenotypeValue, Age, Sex, Alcohol, HCVParam );
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	//Determine fibrosis levels with year

	FibrosisMatrix=new ZeroMatrix(6, 100);

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});
	YearCount=0;
	for (GraphYear=Year-1; GraphYear<Year+40; GraphYear++){
		for (i=0; i<SimData.NoPeople; i++){
			FibrosisLevel=PP[i].HCV.Fibrosis.Get(GraphYear).Value;
			//self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
			FibrosisMatrix[FibrosisLevel][YearCount]=FibrosisMatrix[FibrosisLevel][YearCount]+1;;
		}
		YearCount++;
		self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
	}

	var seconds2 = new Date().getTime() / 1000;
    TotalTime=seconds2 -seconds1;

	self.postMessage({ConsoleMessage: "Finished simulation in "+TotalTime+" seconds"});
	self.postMessage({Result: FibrosisMatrix});
};
<|endoftext|>


<commit_before>/**
 *
 * Anchor Scroll (JS)
 *
 * @author Takuto Yanagida @ Space-Time Inc.
 * @version 2019-07-05
 *
 */

window.ST = window['ST'] || {};

(function (NS) {

	const OFFSET = (NS.ANCHOR_OFFSET_ADDITIONAL !== undefined) ? NS.ANCHOR_OFFSET_ADDITIONAL : 16;

	const SEL_TARGET       = '.stile *[id]:not([class])';
	const CLS_LINK_TARGET  = 'stile-link-target';
	const ST_ANCHOR_OFFSET = 'anchor-offset';

	NS.assignAnchorOffset = assignAnchorOffset;  // Export the function
	NS.addInit(1, initializeAnchorOffset);

	function scrollTo(tar) { window.scrollTo(0, tar.getBoundingClientRect().top + window.pageYOffset); }

	// -------------------------------------------------------------------------

	const getAnchorOffset = NS.makeOffsetFunction();

	function initializeAnchorOffset() {
		if (OFFSET + getAnchorOffset() !== 0) {
			const as1 = [].slice.call(document.getElementsByClassName(CLS_LINK_TARGET));
			const as2 = [].slice.call(document.querySelectorAll(SEL_TARGET));
			const anchorTargets = as1.concat(filterTarget(as2));
			assignAnchorOffset(anchorTargets);

			if (window.location.hash) hashChanged();
		}
		window.addEventListener('hashchange', hashChanged);
	}

	function filterTarget(ts) {
		const newTs = [];
		for (let i = 0; i < ts.length; i += 1) {
			const t = ts[i];
			if (!/^(?:input|button|select|textarea)$/i.test(t.tagName)) newTs.push(t);
		}
		return newTs;
	}

	function hashChanged() {
		let hash = window.location.hash;
		if (hash[0] === '#') hash = hash.substr(1);
		const tar = document.getElementById(hash);
		if (tar) {
			setTimeout(() => { scrollTo(tar); }, 200);
			setTimeout(() => { scrollTo(tar); }, 300);
		}
	}

	// Exported function
	function assignAnchorOffset(ats) {
		for (let i = 0; i < ats.length; i += 1) {
			const at = ats[i];
			const pat = document.createElement('span');
			pat.id               = at.id;
			pat.dataset['stile'] = ST_ANCHOR_OFFSET;

			at.style.position = 'relative';
			at.dataset.id     = at.id;
			at.id             = '';
			at.appendChild(pat);
		}
		NS.onResize(() => { setAnchorOffset(ats); });
		setTimeout(() => { setAnchorOffset(ats); }, 200);
		setTimeout(() => { setAnchorOffset(ats); }, 300);
	}

	function setAnchorOffset(ats) {
		const offset = getAnchorOffset();
		const wpabH = NS.getWpAdminBarHeight();
		const off = offset + wpabH + OFFSET;

		for (let i = 0; i < ats.length; i += 1) {
			const at = ats[i];
			const pat = document.getElementById(at.dataset.id);
			const newTop = -off;
			pat.style.top = newTop + 'px';
		}
	}

})(window.ST);
<commit_msg>Minor change<commit_after>/**
 *
 * Anchor Scroll (JS)
 *
 * @author Takuto Yanagida @ Space-Time Inc.
 * @version 2019-07-05
 *
 */

window.ST = window['ST'] || {};

(function (NS) {

	const OFFSET = (NS.ANCHOR_OFFSET_ADDITIONAL !== undefined) ? NS.ANCHOR_OFFSET_ADDITIONAL : 16;

	const SEL_TARGET       = '.stile *[id]:not([class])';
	const CLS_LINK_TARGET  = 'stile-link-target';
	const ST_ANCHOR_OFFSET = 'anchor-offset';

	NS.assignAnchorOffset = assignAnchorOffset;  // Export the function
	NS.addInit(1, initializeAnchorOffset);

	function scrollTo(tar) { window.scrollTo(0, tar.getBoundingClientRect().top + window.pageYOffset); }

	// -------------------------------------------------------------------------

	const getAnchorOffset = NS.makeOffsetFunction();

	function initializeAnchorOffset() {
		if (OFFSET + getAnchorOffset() !== 0) {
			const as1 = [].slice.call(document.getElementsByClassName(CLS_LINK_TARGET));
			const as2 = [].slice.call(document.querySelectorAll(SEL_TARGET));
			const anchorTargets = as1.concat(filterTarget(as2));
			assignAnchorOffset(anchorTargets);

			if (window.location.hash) hashChanged();
		}
		window.addEventListener('hashchange', hashChanged);
	}

	function filterTarget(ts) {
		const newTs = [];
		for (let i = 0; i < ts.length; i += 1) {
			const t = ts[i];
			if (!/^(?:input|button|select|textarea)$/i.test(t.tagName)) newTs.push(t);
		}
		return newTs;
	}

	function hashChanged() {
		let hash = window.location.hash;
		if (hash[0] === '#') hash = hash.substr(1);
		const tar = document.getElementById(hash);
		if (tar) {
			setTimeout(() => { scrollTo(tar); }, 200);
			setTimeout(() => { scrollTo(tar); }, 300);
		}
	}

	// Exported function
	function assignAnchorOffset(ats) {
		for (let i = 0; i < ats.length; i += 1) {
			const at = ats[i];
			const pat = document.createElement('span');
			pat.id               = at.id;
			pat.dataset['stile'] = ST_ANCHOR_OFFSET;

			at.style.position = 'relative';
			at.dataset.id     = at.id;
			at.id             = '';
			at.appendChild(pat);
		}
		NS.onResize(() => { setAnchorOffset(ats); });
		setTimeout(() => { setAnchorOffset(ats); }, 200);
		setTimeout(() => { setAnchorOffset(ats); }, 300);
		setTimeout(() => { setAnchorOffset(ats); }, 400);
		setTimeout(() => { setAnchorOffset(ats); }, 500);
	}

	function setAnchorOffset(ats) {
		const offset = getAnchorOffset();
		const wpabH = NS.getWpAdminBarHeight();
		const off = offset + wpabH + OFFSET;

		for (let i = 0; i < ats.length; i += 1) {
			const at = ats[i];
			const pat = document.getElementById(at.dataset.id);
			const newTop = -off;
			pat.style.top = newTop + 'px';
		}
	}

})(window.ST);
<|endoftext|>


<commit_before>const util = require("util");
const Base = require("./base");

function Person(data) {
  for (var prop in data) {
    this[prop] = data[prop];
  }
  Base.call(this);
}

util.inherits(Person, Base);

Person.prototype.createPath = function createPath(string) {
  return [this.person.name, string].join("/");
};

Person.prototype.getLikes = function() {
  return this.fetch.call(this, { url: this.createPath("likes") });
};

Person.prototype.getJams = function() {
  return this.fetch.call(this, { url: this.createPath("jams") });
};

Person.prototype.getFollowing = function() {
  return this.fetch.call(this, { url: this.createPath("following") });
};

Person.prototype.getFollowers = function() {
  return this.fetch.call(this, { url: this.createPath("followers") });
};

module.exports = Person;
<commit_msg>Simplify endpoint creation<commit_after>const util = require("util");
const Base = require("./base");
const endpoints = [
  "Likes", "Jams", "Following", "Followers"
];

function Person(data) {
  for (var prop in data) {
    this[prop] = data[prop];
  }
  Base.call(this);
}

util.inherits(Person, Base);

Person.prototype.createPath = function createPath(string) {
  return [this.person.name, string].join("/");
};

Person.prototype.fetchWrapper = function(endpoint) {
  return this.fetch.call(this, { url: this.createPath(endpoint) });
};

endpoints.forEach(function(endpoint) {
  Person.prototype["get" + endpoint] = function() {
    return this.fetchWrapper(endpoint.toLowerCase());
  };
});

module.exports = Person;
<|endoftext|>


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

    angular.module('tubular.services')
        /**
         * @ngdoc service
         * @name tubularHttp
         *
         * @description
         * Use `tubularHttp` to connect a grid or a form to a HTTP Resource. Internally this service is
         * using `$http` to make all the request.
         *
         * This service provides authentication using bearer-tokens. Based on https://bitbucket.org/david.antaramian/so-21662778-spa-authentication-example
         */
        .service('tubularHttp', [
            '$http',
            '$q',
            '$document',
            'tubularConfig',
            '$window',
            function (
                $http,
                $q,
                $document,
                tubularConfig,
                $window) {
                const authData = 'auth_data';
                const prefix = tubularConfig.localStorage.prefix();
                const me = this;

                function init() {
                    const savedData = angular.fromJson($window.localStorage.getItem(prefix + authData));

                    if (savedData != null) {
                        me.userData = savedData;
                    }
                }

                function isAuthenticationExpired(expirationDate) {
                    const now = new Date();
                    expirationDate = new Date(expirationDate);

                    return expirationDate - now <= 0;
                }

                function retrieveSavedData() {
                    const savedData = angular.fromJson($window.localStorage.getItem(prefix + authData));

                    if (angular.isUndefined(savedData)) {
                        throw 'No authentication data exists';
                    } else if (isAuthenticationExpired(savedData.expirationDate)) {
                        throw 'Authentication token has already expired';
                    } else {
                        me.userData = savedData;
                    }
                }

                me.userData = {
                    isAuthenticated: false,
                    username: '',
                    bearerToken: '',
                    expirationDate: null
                };

                me.isBearerTokenExpired = ()  => isAuthenticationExpired(me.userData.expirationDate);

                me.isAuthenticated = () => {
                    if (!me.userData.isAuthenticated || isAuthenticationExpired(me.userData.expirationDate)) {
                        try {
                            retrieveSavedData();
                        } catch (e) {
                            return false;
                        }
                    }

                    return true;
                };

                me.removeAuthentication = function () {
                    $window.localStorage.removeItem(prefix + authData);
                    me.userData.isAuthenticated = false;
                    me.userData.username = '';
                    me.userData.bearerToken = '';
                    me.userData.expirationDate = null;
                    me.userData.refreshToken = null;
                };

                me.authenticate = function (username, password) {
                    this.removeAuthentication();

                    return $http({
                        method: 'POST',
                        url: tubularConfig.webApi.tokenUrl(),
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        data: `grant_type=password&username=${  encodeURIComponent(username)  }&password=${  encodeURIComponent(password)}`
                    }).then(response => {
                        me.initAuth(response.data, username);
                        response.data.authenticated = true;

                        return response.data;
                    }, errorResponse => $q.reject(errorResponse.data));
                };

                // TODO: make private this function
                me.initAuth = (data, username) => {
                    me.userData.isAuthenticated = true;
                    me.userData.username = data.userName || username || me.userData.username;
                    me.userData.bearerToken = data.access_token;
                    me.userData.expirationDate = new Date();
                    me.userData.expirationDate = new Date(me.userData.expirationDate.getTime() + data.expires_in * 1000);
                    me.userData.role = data.role;
                    me.userData.refreshToken = data.refresh_token;

                    $window.localStorage.setItem(prefix + authData, angular.toJson(me.userData));
                };

                init();
            }
        ]);
})(angular);
<commit_msg>Code cleanup on http service<commit_after>(function (angular) {
    'use strict';

    angular.module('tubular.services')
        /**
         * @ngdoc service
         * @name tubularHttp
         *
         * @description
         * Use `tubularHttp` to connect a grid or a form to a HTTP Resource. Internally this service is
         * using `$http` to make all the request.
         *
         * This service provides authentication using bearer-tokens. Based on https://bitbucket.org/david.antaramian/so-21662778-spa-authentication-example
         */
        .service('tubularHttp', [
            '$http',
            '$q',
            '$document',
            'tubularConfig',
            '$window',
            function (
                $http,
                $q,
                $document,
                tubularConfig,
                $window) {
                const authData = 'auth_data';
                const prefix = tubularConfig.localStorage.prefix();
                const me = this;

                function init() {
                    const savedData = angular.fromJson($window.localStorage.getItem(prefix + authData));

                    if (savedData != null) {
                        me.userData = savedData;
                    }
                }

                function isAuthenticationExpired(expirationDate) {
                    const now = new Date();
                    expirationDate = new Date(expirationDate);

                    return expirationDate - now <= 0;
                }

                me.userData = {
                    isAuthenticated: false,
                    username: '',
                    bearerToken: '',
                    expirationDate: null
                };

                me.isBearerTokenExpired = () => isAuthenticationExpired(me.userData.expirationDate);

                me.isAuthenticated = () => me.userData.isAuthenticated && !isAuthenticationExpired(me.userData.expirationDate);

                me.removeAuthentication = function () {
                    $window.localStorage.removeItem(prefix + authData);
                    me.userData.isAuthenticated = false;
                    me.userData.username = '';
                    me.userData.bearerToken = '';
                    me.userData.expirationDate = null;
                    me.userData.refreshToken = null;
                };

                me.authenticate = function (username, password) {
                    this.removeAuthentication();

                    return $http({
                        method: 'POST',
                        url: tubularConfig.webApi.tokenUrl(),
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        data: `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
                    }).then(response => {
                        me.initAuth(response.data, username);
                        response.data.authenticated = true;

                        return response.data;
                    }, errorResponse => $q.reject(errorResponse.data));
                };

                // TODO: make private this function
                me.initAuth = (data, username) => {
                    me.userData.isAuthenticated = true;
                    me.userData.username = data.userName || username || me.userData.username;
                    me.userData.bearerToken = data.access_token;
                    me.userData.expirationDate = new Date();
                    me.userData.expirationDate = new Date(me.userData.expirationDate.getTime() + data.expires_in * 1000);
                    me.userData.role = data.role;
                    me.userData.refreshToken = data.refresh_token;

                    $window.localStorage.setItem(prefix + authData, angular.toJson(me.userData));
                };

                init();
            }
        ]);
})(angular);
<|endoftext|>


<commit_before>import { plugins } from 'mostly-feathers-mongoose';
import { schemas } from 'playing-content-common';

const options = {
  timestamps: true,
  discriminatorKey: 'type'
};

/**
 * Loosely based on the dublincore DCMI schema
 * http://dublincore.org/documents/dcmi-terms/
 */
const fields = {
  authors: [{ type: String }],                 // real author of the document
  contributors: [{ type: 'ObjectId' }],        // contributor of the document
  coverage: { type: String },                  // spatial or temporal topic of the resource
  creator: { type: 'ObjectId' },               // creator of the document
  description: { type: String },               // description of the resource.
  expiredAt: { type: Date },                   // end date of validity of a resource
  file: schemas.blob.schema,                   // main blob of the resource
  files: [schemas.blob.schema],                // attachements of the resource
  format: { type: String },                    // file format, physical medium, or dimensions of the resource.
  issuedAt: { type: Date },                    // date issued
  language: { type: String },                  // language of the resource.
  locker: { type: 'ObjectId' },                // lock owner
  lockedAt: { type: Date },                    // locked time
  nature: { type: String },                    // nature or genre of the resource
  ancestors: [{ type: 'String' }],             // array of typed ids of ancestors
  parent: { type: 'ObjectId' },                // parent resource
  inherited: { type: Boolean, default: true }, // inherite permission from parent
  path: { type: String, default: '/', unique: true }, // path to the document
  rights: [{ type: String }],                  // information about rights held in and over the resource.
  source: { type: String },                    // related resource from which the described resource is derived.
  state: { type: String, enum: [               // lifecycle of the document
    'project', 'approved', 'obsolete', 'deleted'
  ]},
  subjects: [{ type: String }],                // the topic of the resource
  tags: [{ type: String }],                    // the tags of the resource
  type: { type: String, default: 'document' }, // discriminator key
  title: { type: String, required: true },     // name given to the resource
  valid: { type: Date },                       // start date of validity of a resource
  version: { type: Number },                   // version of the resource
};

export default function model (app, name) {
  const mongoose = app.get('mongoose');
  const schema = new mongoose.Schema(fields, options);
  schema.plugin(plugins.softDelete);
  schema.plugin(plugins.sortable, { classify: 'parent' });
  schema.index({ parent: 1 });
  schema.index({ path: 1 });
  schema.index({ ancestors: 1 });
  return mongoose.model(name, schema);
}

model.schema = fields;
<commit_msg>sortable with soft delete<commit_after>import { plugins } from 'mostly-feathers-mongoose';
import { schemas } from 'playing-content-common';

const options = {
  timestamps: true,
  discriminatorKey: 'type'
};

/**
 * Loosely based on the dublincore DCMI schema
 * http://dublincore.org/documents/dcmi-terms/
 */
const fields = {
  authors: [{ type: String }],                 // real author of the document
  contributors: [{ type: 'ObjectId' }],        // contributor of the document
  coverage: { type: String },                  // spatial or temporal topic of the resource
  creator: { type: 'ObjectId' },               // creator of the document
  description: { type: String },               // description of the resource.
  expiredAt: { type: Date },                   // end date of validity of a resource
  file: schemas.blob.schema,                   // main blob of the resource
  files: [schemas.blob.schema],                // attachements of the resource
  format: { type: String },                    // file format, physical medium, or dimensions of the resource.
  issuedAt: { type: Date },                    // date issued
  language: { type: String },                  // language of the resource.
  locker: { type: 'ObjectId' },                // lock owner
  lockedAt: { type: Date },                    // locked time
  nature: { type: String },                    // nature or genre of the resource
  ancestors: [{ type: 'String' }],             // array of typed ids of ancestors
  parent: { type: 'ObjectId' },                // parent resource
  inherited: { type: Boolean, default: true }, // inherite permission from parent
  path: { type: String, default: '/', unique: true }, // path to the document
  rights: [{ type: String }],                  // information about rights held in and over the resource.
  source: { type: String },                    // related resource from which the described resource is derived.
  state: { type: String, enum: [               // lifecycle of the document
    'project', 'approved', 'obsolete', 'deleted'
  ]},
  subjects: [{ type: String }],                // the topic of the resource
  tags: [{ type: String }],                    // the tags of the resource
  type: { type: String, default: 'document' }, // discriminator key
  title: { type: String, required: true },     // name given to the resource
  valid: { type: Date },                       // start date of validity of a resource
  version: { type: Number },                   // version of the resource
};

export default function model (app, name) {
  const mongoose = app.get('mongoose');
  const schema = new mongoose.Schema(fields, options);
  schema.plugin(plugins.softDelete);
  schema.plugin(plugins.sortable, { classify: 'parent', delete: 'destroyedAt' });
  schema.index({ parent: 1 });
  schema.index({ path: 1 });
  schema.index({ ancestors: 1 });
  return mongoose.model(name, schema);
}

model.schema = fields;
<|endoftext|>