<commit_before>var assert = require('assert');

var PartialQueryActions = require('../actions/PartialQueryActions');
var PartialQueryStore = require('../stores/PartialQueryStore');
var ColumnToken = require('../tokens/ColumnToken');
var KeywordToken = require('../tokens/KeywordToken');
var TableToken = require('../tokens/TableToken');
var TokenTypes = require('../constants/TokenTypes');
var AliasToken = require('../tokens/AliasToken');
var FunctionToken = require('../tokens/FunctionToken');

var FUNCTION_TYPES = TokenTypes.FUNCTION_TYPES;

function _addToken(token) {
  PartialQueryActions.addToken(token);
}

function _addTokens() {
  for (var i = 0; i < arguments.length; i++) {
    PartialQueryActions.addToken(arguments[i]);
  }
}

function _colToken(name) {
  return new ColumnToken('foo_table', {name: name || 'bar'});
}

function _colAliasToken(colName, aliasName) {
  return new AliasToken(
    _colToken(colName),
    aliasName
  );
}

function _aliasToken(subToken, aliasName) {
  return new AliasToken(
    subToken,
    aliasName
  );
}

function _keywordToken(name) {
  return new KeywordToken(name);
}

function _tableToken(name) {
  return new TableToken(name);
}

function _functionToken(functionType, params) {
  return new FunctionToken(
    functionType,
    params
  );
}

describe('partial query store', () => {

  beforeEach(() => {
    PartialQueryActions.clearTokens();
  })

  describe('insertIndex', () => {
    it('can increment and decrement', function() {
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      PartialQueryActions.incrementInsertIndex();
      // since no tokens yet
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      _addToken(_colToken());
      _addToken(_colToken());
      // we added two
      assert.equal(PartialQueryStore.getInsertIndex(), 2);
      PartialQueryActions.incrementInsertIndex();
      // its maxed
      assert.equal(PartialQueryStore.getInsertIndex(), 2);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 1);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
    });
  });

  describe('token formatting ', () => {
    it('can format with commas', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('*'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT *, name FROM foo_table'
      );
    });

    it('handles formatting aliases correctly', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, bar as baz, foo FROM foo_table'
      );
    });

    it('handles functions also', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: '1'}
        ),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, bar as baz, COUNT(1) FROM foo_table'
      );
    });

    it('can handle counts as aliases ', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _aliasToken(
          _functionToken(
            FUNCTION_TYPES.COUNT,
            {countName: '*'}
          ),
          'total'
        ),
        _colAliasToken('bat', 'banana'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT ' +
          'name, bar as baz, COUNT(*) as total, bat as banana ' +
          'FROM foo_table'
      );
    });

    it('does some basic group by formatting', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('GROUP BY'),
        _colToken('name'),
        _colToken('baz')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table GROUP BY name, baz'
      );
    });

    it('does some basic ordering by', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('ORDER BY'),
        _colToken('name'),
        _colToken('baz')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table ORDER BY name, baz'
      );
    });

    it('can count columns too', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: 'bar'}
        ),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: 'baz', isDistinct: true}
        ),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT COUNT(bar), COUNT(DISTINCT baz) FROM foo_table'
      );

    });

    it('can even order by for asc desc', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('ORDER BY'),
        _colToken('name'),
        _keywordToken('DESC'),
        _colToken('baz'),
        _keywordToken('ASC'),
        _colToken('foo')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table ' +
          'ORDER BY name DESC, baz ASC, foo'
      );
    });

    it('can export specific table col selections', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.name FROM foo_table'
      );
    });

    it('can format table col aliases', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colAliasToken('bar', 'baz'),
        _colToken('name'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.bar as baz, name, foo FROM foo_table'
      );
    });

    it('can format table col aliases (multiple)', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colAliasToken('bar', 'baz'),
        _tableToken('foo_table'),
        _colToken('name'),
        _tableToken('foo_table'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.bar as baz, foo_table.name, ' +
          'foo_table.foo FROM foo_table'
      );
    });

    it('can select from multiple tables woah', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _tableToken('bar_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, foo FROM foo_table, bar_table'
      );
    });

  });

});
<commit_msg>and table aliases<commit_after>var assert = require('assert');

var PartialQueryActions = require('../actions/PartialQueryActions');
var PartialQueryStore = require('../stores/PartialQueryStore');
var ColumnToken = require('../tokens/ColumnToken');
var KeywordToken = require('../tokens/KeywordToken');
var TableToken = require('../tokens/TableToken');
var TokenTypes = require('../constants/TokenTypes');
var AliasToken = require('../tokens/AliasToken');
var FunctionToken = require('../tokens/FunctionToken');

var FUNCTION_TYPES = TokenTypes.FUNCTION_TYPES;

function _addToken(token) {
  PartialQueryActions.addToken(token);
}

function _addTokens() {
  for (var i = 0; i < arguments.length; i++) {
    PartialQueryActions.addToken(arguments[i]);
  }
}

function _colToken(name) {
  return new ColumnToken('foo_table', {name: name || 'bar'});
}

function _colAliasToken(colName, aliasName) {
  return new AliasToken(
    _colToken(colName),
    aliasName
  );
}

function _aliasToken(subToken, aliasName) {
  return new AliasToken(
    subToken,
    aliasName
  );
}

function _keywordToken(name) {
  return new KeywordToken(name);
}

function _tableToken(name) {
  return new TableToken(name);
}

function _functionToken(functionType, params) {
  return new FunctionToken(
    functionType,
    params
  );
}

describe('partial query store', () => {

  beforeEach(() => {
    PartialQueryActions.clearTokens();
  })

  describe('insertIndex', () => {
    it('can increment and decrement', function() {
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      PartialQueryActions.incrementInsertIndex();
      // since no tokens yet
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      _addToken(_colToken());
      _addToken(_colToken());
      // we added two
      assert.equal(PartialQueryStore.getInsertIndex(), 2);
      PartialQueryActions.incrementInsertIndex();
      // its maxed
      assert.equal(PartialQueryStore.getInsertIndex(), 2);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 1);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
      PartialQueryActions.decrementInsertIndex();
      assert.equal(PartialQueryStore.getInsertIndex(), 0);
    });
  });

  describe('token formatting ', () => {
    it('can format with commas', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('*'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT *, name FROM foo_table'
      );
    });

    it('handles formatting aliases correctly', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, bar as baz, foo FROM foo_table'
      );
    });

    it('handles functions also', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: '1'}
        ),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, bar as baz, COUNT(1) FROM foo_table'
      );
    });

    it('can handle counts as aliases ', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colAliasToken('bar', 'baz'),
        _aliasToken(
          _functionToken(
            FUNCTION_TYPES.COUNT,
            {countName: '*'}
          ),
          'total'
        ),
        _colAliasToken('bat', 'banana'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT ' +
          'name, bar as baz, COUNT(*) as total, bat as banana ' +
          'FROM foo_table'
      );
    });

    it('does some basic group by formatting', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('GROUP BY'),
        _colToken('name'),
        _colToken('baz')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table GROUP BY name, baz'
      );
    });

    it('does some basic ordering by', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('ORDER BY'),
        _colToken('name'),
        _colToken('baz')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table ORDER BY name, baz'
      );
    });

    it('can count columns too', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: 'bar'}
        ),
        _functionToken(
          FUNCTION_TYPES.COUNT,
          {countName: 'baz', isDistinct: true}
        ),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT COUNT(bar), COUNT(DISTINCT baz) FROM foo_table'
      );

    });

    it('can even order by for asc desc', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _keywordToken('ORDER BY'),
        _colToken('name'),
        _keywordToken('DESC'),
        _colToken('baz'),
        _keywordToken('ASC'),
        _colToken('foo')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name FROM foo_table ' +
          'ORDER BY name DESC, baz ASC, foo'
      );
    });

    it('can export specific table col selections', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colToken('name'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.name FROM foo_table'
      );
    });

    it('can format table col aliases', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colAliasToken('bar', 'baz'),
        _colToken('name'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.bar as baz, name, foo FROM foo_table'
      );
    });

    it('can format table col aliases (multiple)', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('foo_table'),
        _colAliasToken('bar', 'baz'),
        _tableToken('foo_table'),
        _colToken('name'),
        _tableToken('foo_table'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT foo_table.bar as baz, foo_table.name, ' +
          'foo_table.foo FROM foo_table'
      );
    });

    it('can select from multiple tables woah', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _colToken('name'),
        _colToken('foo'),
        _keywordToken('FROM'),
        _tableToken('foo_table'),
        _tableToken('bar_table')
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT name, foo FROM foo_table, bar_table'
      );
    });

    it('can select from multiple tables with aliases', () => {
      _addTokens(
        _keywordToken('SELECT'),
        _tableToken('o'),
        _colToken('name'),
        _tableToken('o'),
        _colToken('bar'),
        _keywordToken('FROM'),
        _aliasToken(
          _tableToken('foo_table'),
          'o'
        )
      );
      assert.equal(
        PartialQueryStore.exportToStringQuery(),
        'SELECT o.name, o.bar FROM foo_table as o'
      );
    });

  });

});
<|endoftext|>


<commit_before>function (user, context, callback) {
  if (!user.email_verified) {
    var reason = 'You primary email is not verified. Please contact EUS.';
    context.redirect = {
     url: "https://sso.mozilla.com/forbidden?reason="+encodeURIComponent(reason)
    };
    console.log('Primary email not verified');
    return callback(null, user, context);
  }

  if (context.connectionStrategy === 'ad') {
    // this is the highest level of account, always let in
    console.log('ad account passthru');
    return callback(null, user, context);
  }

  if (context.connectionStrategy === 'google-oauth2') {
    // this is == to 'ad' for us
    if (user.email.endsWith('mozilla.com') || user.email.endsWith('mozillafoundation.org')) {
      console.log('ad account via google-oauth2 passthru');
      return callback(null, user, context);
    }
  }

  // Query all users to find matches for everything else...
  var request = require('request@2.56.0');
  var userApiUrl = auth0.baseUrl + '/users';

  // Lower is better
  var matchOrder = {'ad': 0,
                    'github': 1,
                    'google-oauth2': 2,
                    'email': 3
                   };

  request({
   url: userApiUrl,
   headers: {
     Authorization: 'Bearer ' + auth0.accessToken
   },
   qs: {
     search_engine: 'v2',
     q: 'email:"' + user.email+'"',
   }
  },
  function(err, response, body) {
    if (err) return callback(err);

    if (response.statusCode !== 200) return callback(new Error(body));

    var data = JSON.parse(body);
    if (data.length > 0) {
      var myprovider = context.connectionStrategy;
      console.log(myprovider);
      console.log('All users matching '+user.email+' current match order '+matchOrder[myprovider]);
      var selected_user = user;
      async.each(data, function(targetUser, cb) {
        // Only list "not us" ;-)
        if (targetUser.user_id !== user.user_id) {
          // XXX This currently assumes single identity/no linked account /!\
          var provider = targetUser.identities[0].provider;
          console.log(targetUser.user_id+' match order '+matchOrder[provider]);
          if (matchOrder[provider] < matchOrder[myprovider]) {
            console.log('Found better account target');
            selected_user = targetUser;
          }
        }
        console.log('Final selected user is '+selected_user.user_id);
        if (user.user_id !== selected_user.user_id) {
          var reason = 'Sorry - you may not login with that user account. Please always' +
              ' use your '+selected_user.identities[0].connection+' account instead.';
          context.redirect = {
            url: "https://sso.mozilla.com/forbidden?reason="+encodeURIComponent(reason)
          };
        }
        cb(); // bail + success
      }, function(err) {
        callback(err, user, context);
      });
    } else {
      callback(null, user, context);
    }
  });
}
<commit_msg>whitelist support for the force rule - so that account verification clients can verify all accounts. whitelisted dev client id.<commit_after>function (user, context, callback) {
  var WHITELIST = ['HvN5D3R64YNNhvcHKuMKny1O0KJZOOwH' // mozillians.org account verification
             ];

  if (!user.email_verified) {
    var reason = 'You primary email is not verified. Please contact EUS.';
    context.redirect = {
     url: "https://sso.mozilla.com/forbidden?reason="+encodeURIComponent(reason)
    };
    console.log('Primary email not verified');
    return callback(null, user, context);
  }

  if (context.connectionStrategy === 'ad') {
    // this is the highest level of account, always let in
    console.log('ad account passthru');
    return callback(null, user, context);
  }

  try {
    if (WHITELIST.indexOf(context.clientID) >= 0) {
      console.log('Whitelisted client '+context.clientID+', no login enforcement taking place');
      return callback(null, user, context);
    }
  } catch (e) {
    console.log('Client not found while checking force-user-to-login-with-most-secure-method whitelist (non-fatal): '+e);
  }

  if (context.connectionStrategy === 'google-oauth2') {
    // this is == to 'ad' for us
    if (user.email.endsWith('mozilla.com') || user.email.endsWith('mozillafoundation.org')) {
      console.log('ad account via google-oauth2 passthru');
      return callback(null, user, context);
    }
  }

  // Query all users to find matches for everything else...
  var request = require('request@2.56.0');
  var userApiUrl = auth0.baseUrl + '/users';

  // Lower is better
  var matchOrder = {'ad': 0,
                    'github': 1,
                    'google-oauth2': 2,
                    'email': 3
                   };

  request({
   url: userApiUrl,
   headers: {
     Authorization: 'Bearer ' + auth0.accessToken
   },
   qs: {
     search_engine: 'v2',
     q: 'email:"' + user.email+'"',
   }
  },
  function(err, response, body) {
    if (err) return callback(err);

    if (response.statusCode !== 200) return callback(new Error(body));

    var data = JSON.parse(body);
    if (data.length > 0) {
      var myprovider = context.connectionStrategy;
      console.log('All users matching '+user.email+' current match order '+matchOrder[myprovider]);
      var selected_user = user;
      async.each(data, function(targetUser, cb) {
        // Only list "not us" ;-)
        if (targetUser.user_id !== user.user_id) {
          // XXX This currently assumes single identity/no linked account /!\
          var provider = targetUser.identities[0].provider;
          console.log(targetUser.user_id+' match order '+matchOrder[provider]);
          if (matchOrder[provider] < matchOrder[myprovider]) {
            console.log('Found better account target');
            selected_user = targetUser;
          }
        }
        console.log('Final selected user is '+selected_user.user_id);
        if (user.user_id !== selected_user.user_id) {
          var reason = 'Sorry - you may not login with that user account. Please always' +
              ' use your '+selected_user.identities[0].connection+' account instead.';
          context.redirect = {
            url: "https://sso.mozilla.com/forbidden?reason="+encodeURIComponent(reason)
          };
        }
        cb(); // bail + success
      }, function(err) {
        callback(err, user, context);
      });
    } else {
      callback(null, user, context);
    }
  });
}
<|endoftext|>


<commit_before>/**
  * HammerSlider - Hammerslider is a lightweight infinite carousel plugin
  * v0.1.2 | https://github.com/davidcetinkaya/hammer-slider
  * Copyright David Cetinkaya
  *
  * MIT license
  */
  "use strict";function HammerSlider(e,t){function n(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function i(e,t,n,i){e&&e.addEventListener(t,n,!!i)}function o(e,t){e&&e.classList.add(t)}function r(e,t){e&&e.classList.remove(t)}function a(e){var t=["","-webkit-","-moz-","-ms-","-o-"],n=document.createElement("div");for(var i in t)if("undefined"!=typeof n.style[t[i]+e])return t[i]+e;return!1}function s(e,t,n){e.style[x]="translateX("+t+(n?n:"px")+")"}function d(e){for(var t=0;t<_;t++)e.call(D,t)}function c(){var e=window.getComputedStyle(D.container,null).getPropertyValue(x);return parseInt(e.split(",")[4])}function l(){return{relativeSlideFunc:Y?v:p,nrSlidesInPercent:100*_,lastSlide:_-1,isLastSlide:function(e){return e===this.lastSlide}}}function u(t){var n=t?Math.abs(t):q.startSlide;X=n,D.width=e.offsetWidth,q.rewind||(I[1]={slide:n?0:k.lastSlide,flipPoint:(k.isLastSlide(n)?n-1:n)*D.width*-1+D.width*-.5,toPos:n?k.nrSlidesInPercent:0},I[-1]={slide:k.isLastSlide(n)?0:n?k.lastSlide:k.lastSlide-1,flipPoint:n*D.width*-1+.5*D.width,toPos:k.isLastSlide(n)?0:k.nrSlidesInPercent*-1}),d(function(e){var t=0;q.rewind||(!e&&k.isLastSlide(n)?t=k.nrSlidesInPercent:k.isLastSlide(e)&&!n&&(t=k.nrSlidesInPercent*-1)),s(this.slides[e],t,"%"),this.slides[e].style.width=this.width+"px"}),D.container.style.width=_*D.width+"px",s(D.container,n*D.width*-1),y(n)}function f(e){var t=I[1].flipPoint,n=I[-1].flipPoint;return e<t?1:e>n&&-1}function m(e){if(e){var t=e>0?-1:1,i=I[e];s(D.slides[i.slide],i.toPos,"%"),n(I[t],{flipPoint:i.flipPoint,slide:i.slide,toPos:i.toPos+k.nrSlidesInPercent*t}),i.flipPoint+=D.width*t,h(i,e)&&(i.toPos+=k.nrSlidesInPercent*e)}}function h(e,t){switch(t){case 1:return e.slide=k.isLastSlide(e.slide)?0:++e.slide,!e.slide;case-1:return e.slide=e.slide?--e.slide:k.lastSlide,k.isLastSlide(e.slide)}}function w(e){if(q.rewind)if(1===e){if(k.isLastSlide(X))return 0}else if(!X)return k.lastSlide;return X+e}function p(e){var t=c(),n=Math.ceil(t/D.width),i=Math.ceil(n/_),o=Math.abs(i*_-e);return t>0?o*-1:o}function v(e){var t=c()/D.width,n=t<0?Math.ceil(Math.abs(t)):Math.floor(t*-1),i=!(Math.abs(n%_)%2),o=i&&e?1:i||e?0:-1;return n+o}function S(e){var t=Math.abs(X%_),n=(e||c())<0?t:_-t;return n>k.lastSlide?0:n}function g(e,t,n,i){var o=t?k.relativeSlideFunc(e):e,r=o*D.width*-1,a=void 0;T(),X=o,a=S(r),q.beforeSlideChange&&q.beforeSlideChange(a),y(a),P(r,n,i)}function P(e,t,n){function i(){l===o?(X%_===q.startSlide&&u(),q.afterSlideChange&&q.afterSlideChange(S()),A(n)):(!q.rewind&&m(f(r)),l+=h,r=parseInt(Math.easeOutQuad(l,a,d,o)),s(D.container,r),D.animationFrame=requestAnimationFrame(i))}var o=t||q.slideSpeed,r=c(),a=r,d=e-a,l=0,h=2;D.animationFrame=requestAnimationFrame(i)}function b(){D.autoTimeOut=setTimeout(function(){return g(w(1),!1,!1,!0)},q.slideInterval)}function T(){cancelAnimationFrame(D.animationFrame),clearTimeout(D.autoTimeOut)}function A(e){(q.slideShow&&!q.stopAfterInteraction||e)&&b()}function C(){g(w(1))}function M(){g(w(-1))}function y(e){q.dots&&(r(D.dotWrap.querySelector("."+O.dotActiveClass),O.dotActiveClass),o(D.dots[Y?Math.abs(X%(_-Y)):e],O.dotActiveClass))}function F(){T(),u(S()),A()}function E(){var e=void 0,t=void 0,n=void 0;TouchEvents(D.container,{mouse:q.mouseDrag,dragThreshold:q.dragThreshold,start:function(t){T(),e=c(),n=X%_,o(D.container,O.dragging)},move:function(i,o,r){"left"!==o&&"right"!==o||(D.animationFrame=requestAnimationFrame(function(){t=e+r.X,q.rewind?(!n&&"right"===o||k.isLastSlide(n)&&"left"===o)&&(t=e+r.X/2.5):m(f(t)),s(D.container,t)}))},end:function(e,t,i){var o=X;Math.abs(i.X)>q.minimumDragDistance&&("left"===t?o=q.rewind&&k.isLastSlide(n)?k.lastSlide:w(1):"right"===t&&(o=q.rewind&&!n?0:w(-1))),g(o,!1,q.touchSpeed),r(D.container,O.dragging)}})}function L(){var t=document.createDocumentFragment();if(D.container=q.slideContainer||e.children[0],_=D.container.children.length,x=a("transform"),_<=1||!x)return d(function(e){this.container.children[e].style.width="100%",this.container.style.width=100*_+"%"}),void(x&&s(D.container,0));if(!q.rewind&&2===_){var n=D.container,r=n.children;n.appendChild(r[0].cloneNode(1)),n.appendChild(r[_-1].cloneNode(1)),_+=2,Y=2}k=l(),q.slideSpeed=q.slideSpeed<2?2:10*Math.ceil(q.slideSpeed/10),d(function(n){if(this.slides.push(this.container.children[n]),i(this.slides[n],"focus",function(t){T(),e.scrollLeft=0,g(n,!0)},!0),q.dots){var r=document.createElement("li");!function(e,n){n>=_-Y||(o(e,O.dotItem),e.setAttribute("tabindex",0),e.setAttribute("role","button"),e.innerHTML="",i(e,"click",function(t){g(n,!0),e.blur()}),i(e,"keyup",function(e){13===e.keyCode&&g(n,!0)}),t.appendChild(e))}(r,n),this.dots.push(r),k.isLastSlide(n)&&(this.dotWrap=q.dotContainer||document.createElement("ul"),this.dotWrap.appendChild(t),q.dotContainer||(o(this.dotWrap,O.dotWrap),e.appendChild(this.dotWrap)))}}),i(window,"resize",F),i(window,"orientationchange",F),E(),u(),q.mouseDrag&&o(D.container,O.mouseDrag),q.slideShow&&b(),q.onSetup&&setTimeout(function(){return q.onSetup(_)},0)}var D={slides:[],dots:[]},I={},X=0,_=0,Y=0,x=void 0,k=void 0,q={slideShow:!1,slideInterval:5e3,slideSpeed:50,touchSpeed:50,startSlide:0,dragThreshold:10,minimumDragDistance:30,stopAfterInteraction:!0,rewind:!1,dots:!1,mouseDrag:!1,dotContainer:void 0,slideContainer:void 0,beforeSlideChange:void 0,afterSlideChange:void 0,onSetup:void 0,cssPrefix:"c-slider"};t&&n(q,t);var O={dotWrap:q.cssPrefix+"__dots",dotItem:q.cssPrefix+"__dot",dotActiveClass:q.cssPrefix+"__dot--is-active",dragging:q.cssPrefix+"__container--is-dragging",mouseDrag:q.cssPrefix+"__container--mouse-drag-enabled"};return Math.easeOutQuad=function(e,t,n,i){return e/=i,-n*e*(e-2)+t},L(),{next:C,prev:M,stop:T,start:b,getActiveSlideNr:S,setupSlider:function(e){return u(e)},moveTo:function(e,t){return g(e,!0,t)}}}function TouchEvents(e,t){function n(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function i(e,t,n,i){t&&e.addEventListener(t,n,!!i)}function o(e,t,n,i){t&&e.removeEventListener(t,n,!!i)}function r(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function a(e){h={X:(p?e.clientX:e.touches[0].clientX)-m.X,Y:(p?e.clientY:e.touches[0].clientY)-m.Y,time:(new Date).getTime()-m.time}}function s(e,t){if(w="",f.clicksAllowed=!0,p=t,!b[p](e)){r&&p&&r(e),i(document,P[p][1],d),i(document,P[p][2],c),i(document,P[p][3],c),m={X:p?e.clientX:e.touches[0].clientX,Y:p?e.clientY:e.touches[0].clientY,time:(new Date).getTime()};for(var n in h)h[n]=0;f.start(e)}}function d(e){a(e),v?"X"===v?(w=h.X<0?"left":"right",r&&r(e)):"Y"===v&&(w=h.Y<0?"up":"down"):v=f.dragThreshold<Math.abs(h.X)?"X":f.dragThreshold<Math.abs(h.Y)&&"Y",f.move(e,w,h)}function c(e){!f.clicksAllowed&&e.target&&e.target.blur&&e.target.blur(),o(document,P[p][1],d),o(document,P[p][2],c),o(document,P[p][3],c),f.end(e,w,h),v=!1}function l(){i(e,P[g][0],function(e){s(e,g)}),i(e,"dragstart",r),f.mouse&&!g&&i(e,P[3][0],function(e){s(e,3)}),i(e,"click",function(e){f.clicksAllowed?u(e):r(e)})}var u=function(){},f={preventDefault:!0,clicksAllowed:!0,mouse:!0,dragThreshold:10,start:u,move:u,end:u};t&&n(f,t);var m={},h={},w=void 0,p=void 0,v=void 0,S={pointerEvents:!!window.navigator.pointerEnabled,msPointerEvents:!!window.navigator.msPointerEnabled},g=S.pointerEvents?1:S.msPointerEvents?2:0,P=[["touchstart","touchmove","touchend","touchcancel"],["pointerdown","pointermove","pointerup","pointercancel"],["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerCancel"],["mousedown","mousemove","mouseup",!1]],b=[function(e){return e.touches&&e.touches.length>1||e.scale&&1!==e.scale},function(e){return!e.isPrimary||e.buttons&&1!==e.buttons||!f.mouse&&"touch"!==e.pointerType&&"pen"!==e.pointerType},function(e){return!e.isPrimary||e.buttons&&1!==e.buttons||!f.mouse&&e.pointerType!==e.MSPOINTER_TYPE_TOUCH&&e.pointerType!==e.MSPOINTER_TYPE_PEN},function(e){return e.buttons&&1!==e.buttons}];l()}window.jQuery&&!function(e){e.fn.HammerSlider=function(t){return this.each(function(){e(this).data("HammerSlider",HammerSlider(this,t))}),this}}(window.jQuery),function(){for(var e=0,t=["ms","moz","webkit","o"],n=0;n<t.length&&!window.requestAnimationFrame;++n)window.requestAnimationFrame=window[t[n]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[n]+"CancelAnimationFrame"]||window[t[n]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,n){var i=(new Date).getTime(),o=Math.max(0,16-(i-e)),r=window.setTimeout(function(){t(i+o)},o);return e=i+o,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}();<commit_msg>Bump version patch number<commit_after>/**
  * HammerSlider - Hammerslider is a lightweight infinite carousel plugin
  * v0.1.3 | https://github.com/davidcetinkaya/hammer-slider
  * Copyright David Cetinkaya
  *
  * MIT license
  */
  "use strict";function HammerSlider(e,t){function n(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function i(e,t,n,i){e&&e.addEventListener(t,n,!!i)}function o(e,t){e&&e.classList.add(t)}function r(e,t){e&&e.classList.remove(t)}function a(e){var t=["","-webkit-","-moz-","-ms-","-o-"],n=document.createElement("div");for(var i in t)if("undefined"!=typeof n.style[t[i]+e])return t[i]+e;return!1}function s(e,t,n){e.style[x]="translateX("+t+(n?n:"px")+")"}function d(e){for(var t=0;t<_;t++)e.call(D,t)}function c(){var e=window.getComputedStyle(D.container,null).getPropertyValue(x);return parseInt(e.split(",")[4])}function l(){return{relativeSlideFunc:Y?v:p,nrSlidesInPercent:100*_,lastSlide:_-1,isLastSlide:function(e){return e===this.lastSlide}}}function u(t){var n=t?Math.abs(t):q.startSlide;X=n,D.width=e.offsetWidth,q.rewind||(I[1]={slide:n?0:k.lastSlide,flipPoint:(k.isLastSlide(n)?n-1:n)*D.width*-1+D.width*-.5,toPos:n?k.nrSlidesInPercent:0},I[-1]={slide:k.isLastSlide(n)?0:n?k.lastSlide:k.lastSlide-1,flipPoint:n*D.width*-1+.5*D.width,toPos:k.isLastSlide(n)?0:k.nrSlidesInPercent*-1}),d(function(e){var t=0;q.rewind||(!e&&k.isLastSlide(n)?t=k.nrSlidesInPercent:k.isLastSlide(e)&&!n&&(t=k.nrSlidesInPercent*-1)),s(this.slides[e],t,"%"),this.slides[e].style.width=this.width+"px"}),D.container.style.width=_*D.width+"px",s(D.container,n*D.width*-1),y(n)}function f(e){var t=I[1].flipPoint,n=I[-1].flipPoint;return e<t?1:e>n&&-1}function m(e){if(e){var t=e>0?-1:1,i=I[e];s(D.slides[i.slide],i.toPos,"%"),n(I[t],{flipPoint:i.flipPoint,slide:i.slide,toPos:i.toPos+k.nrSlidesInPercent*t}),i.flipPoint+=D.width*t,h(i,e)&&(i.toPos+=k.nrSlidesInPercent*e)}}function h(e,t){switch(t){case 1:return e.slide=k.isLastSlide(e.slide)?0:++e.slide,!e.slide;case-1:return e.slide=e.slide?--e.slide:k.lastSlide,k.isLastSlide(e.slide)}}function w(e){if(q.rewind)if(1===e){if(k.isLastSlide(X))return 0}else if(!X)return k.lastSlide;return X+e}function p(e){var t=c(),n=Math.ceil(t/D.width),i=Math.ceil(n/_),o=Math.abs(i*_-e);return t>0?o*-1:o}function v(e){var t=c()/D.width,n=t<0?Math.ceil(Math.abs(t)):Math.floor(t*-1),i=!(Math.abs(n%_)%2),o=i&&e?1:i||e?0:-1;return n+o}function S(e){var t=Math.abs(X%_),n=(e||c())<0?t:_-t;return n>k.lastSlide?0:n}function g(e,t,n,i){var o=t?k.relativeSlideFunc(e):e,r=o*D.width*-1,a=void 0;T(),X=o,a=S(r),q.beforeSlideChange&&q.beforeSlideChange(a),y(a),P(r,n,i)}function P(e,t,n){function i(){l===o?(X%_===q.startSlide&&u(),q.afterSlideChange&&q.afterSlideChange(S()),A(n)):(!q.rewind&&m(f(r)),l+=h,r=parseInt(Math.easeOutQuad(l,a,d,o)),s(D.container,r),D.animationFrame=requestAnimationFrame(i))}var o=t||q.slideSpeed,r=c(),a=r,d=e-a,l=0,h=2;D.animationFrame=requestAnimationFrame(i)}function b(){D.autoTimeOut=setTimeout(function(){return g(w(1),!1,!1,!0)},q.slideInterval)}function T(){cancelAnimationFrame(D.animationFrame),clearTimeout(D.autoTimeOut)}function A(e){(q.slideShow&&!q.stopAfterInteraction||e)&&b()}function C(){g(w(1))}function M(){g(w(-1))}function y(e){q.dots&&(r(D.dotWrap.querySelector("."+O.dotActiveClass),O.dotActiveClass),o(D.dots[Y?Math.abs(X%(_-Y)):e],O.dotActiveClass))}function F(){T(),u(S()),A()}function E(){var e=void 0,t=void 0,n=void 0;TouchEvents(D.container,{mouse:q.mouseDrag,dragThreshold:q.dragThreshold,start:function(t){T(),e=c(),n=X%_,o(D.container,O.dragging)},move:function(i,o,r){"left"!==o&&"right"!==o||(D.animationFrame=requestAnimationFrame(function(){t=e+r.X,q.rewind?(!n&&"right"===o||k.isLastSlide(n)&&"left"===o)&&(t=e+r.X/2.5):m(f(t)),s(D.container,t)}))},end:function(e,t,i){var o=X;Math.abs(i.X)>q.minimumDragDistance&&("left"===t?o=q.rewind&&k.isLastSlide(n)?k.lastSlide:w(1):"right"===t&&(o=q.rewind&&!n?0:w(-1))),g(o,!1,q.touchSpeed),r(D.container,O.dragging)}})}function L(){var t=document.createDocumentFragment();if(D.container=q.slideContainer||e.children[0],_=D.container.children.length,x=a("transform"),_<=1||!x)return d(function(e){this.container.children[e].style.width="100%",this.container.style.width=100*_+"%"}),void(x&&s(D.container,0));if(!q.rewind&&2===_){var n=D.container,r=n.children;n.appendChild(r[0].cloneNode(1)),n.appendChild(r[_-1].cloneNode(1)),_+=2,Y=2}k=l(),q.slideSpeed=q.slideSpeed<2?2:10*Math.ceil(q.slideSpeed/10),d(function(n){if(this.slides.push(this.container.children[n]),i(this.slides[n],"focus",function(t){T(),e.scrollLeft=0,g(n,!0)},!0),q.dots){var r=document.createElement("li");!function(e,n){n>=_-Y||(o(e,O.dotItem),e.setAttribute("tabindex",0),e.setAttribute("role","button"),e.innerHTML="",i(e,"click",function(t){g(n,!0),e.blur()}),i(e,"keyup",function(e){13===e.keyCode&&g(n,!0)}),t.appendChild(e))}(r,n),this.dots.push(r),k.isLastSlide(n)&&(this.dotWrap=q.dotContainer||document.createElement("ul"),this.dotWrap.appendChild(t),q.dotContainer||(o(this.dotWrap,O.dotWrap),e.appendChild(this.dotWrap)))}}),i(window,"resize",F),i(window,"orientationchange",F),E(),u(),q.mouseDrag&&o(D.container,O.mouseDrag),q.slideShow&&b(),q.onSetup&&setTimeout(function(){return q.onSetup(_)},0)}var D={slides:[],dots:[]},I={},X=0,_=0,Y=0,x=void 0,k=void 0,q={slideShow:!1,slideInterval:5e3,slideSpeed:50,touchSpeed:50,startSlide:0,dragThreshold:10,minimumDragDistance:30,stopAfterInteraction:!0,rewind:!1,dots:!1,mouseDrag:!1,dotContainer:void 0,slideContainer:void 0,beforeSlideChange:void 0,afterSlideChange:void 0,onSetup:void 0,cssPrefix:"c-slider"};t&&n(q,t);var O={dotWrap:q.cssPrefix+"__dots",dotItem:q.cssPrefix+"__dot",dotActiveClass:q.cssPrefix+"__dot--is-active",dragging:q.cssPrefix+"__container--is-dragging",mouseDrag:q.cssPrefix+"__container--mouse-drag-enabled"};return Math.easeOutQuad=function(e,t,n,i){return e/=i,-n*e*(e-2)+t},L(),{next:C,prev:M,stop:T,start:b,getActiveSlideNr:S,setupSlider:function(e){return u(e)},moveTo:function(e,t){return g(e,!0,t)}}}function TouchEvents(e,t){function n(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function i(e,t,n,i){t&&e.addEventListener(t,n,!!i)}function o(e,t,n,i){t&&e.removeEventListener(t,n,!!i)}function r(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function a(e){h={X:(p?e.clientX:e.touches[0].clientX)-m.X,Y:(p?e.clientY:e.touches[0].clientY)-m.Y,time:(new Date).getTime()-m.time}}function s(e,t){if(w="",f.clicksAllowed=!0,p=t,!b[p](e)){r&&p&&r(e),i(document,P[p][1],d),i(document,P[p][2],c),i(document,P[p][3],c),m={X:p?e.clientX:e.touches[0].clientX,Y:p?e.clientY:e.touches[0].clientY,time:(new Date).getTime()};for(var n in h)h[n]=0;f.start(e)}}function d(e){a(e),v?"X"===v?(w=h.X<0?"left":"right",r&&r(e)):"Y"===v&&(w=h.Y<0?"up":"down"):v=f.dragThreshold<Math.abs(h.X)?"X":f.dragThreshold<Math.abs(h.Y)&&"Y",f.move(e,w,h)}function c(e){!f.clicksAllowed&&e.target&&e.target.blur&&e.target.blur(),o(document,P[p][1],d),o(document,P[p][2],c),o(document,P[p][3],c),f.end(e,w,h),v=!1}function l(){i(e,P[g][0],function(e){s(e,g)}),i(e,"dragstart",r),f.mouse&&!g&&i(e,P[3][0],function(e){s(e,3)}),i(e,"click",function(e){f.clicksAllowed?u(e):r(e)})}var u=function(){},f={preventDefault:!0,clicksAllowed:!0,mouse:!0,dragThreshold:10,start:u,move:u,end:u};t&&n(f,t);var m={},h={},w=void 0,p=void 0,v=void 0,S={pointerEvents:!!window.navigator.pointerEnabled,msPointerEvents:!!window.navigator.msPointerEnabled},g=S.pointerEvents?1:S.msPointerEvents?2:0,P=[["touchstart","touchmove","touchend","touchcancel"],["pointerdown","pointermove","pointerup","pointercancel"],["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerCancel"],["mousedown","mousemove","mouseup",!1]],b=[function(e){return e.touches&&e.touches.length>1||e.scale&&1!==e.scale},function(e){return!e.isPrimary||e.buttons&&1!==e.buttons||!f.mouse&&"touch"!==e.pointerType&&"pen"!==e.pointerType},function(e){return!e.isPrimary||e.buttons&&1!==e.buttons||!f.mouse&&e.pointerType!==e.MSPOINTER_TYPE_TOUCH&&e.pointerType!==e.MSPOINTER_TYPE_PEN},function(e){return e.buttons&&1!==e.buttons}];l()}window.jQuery&&!function(e){e.fn.HammerSlider=function(t){return this.each(function(){e(this).data("HammerSlider",HammerSlider(this,t))}),this}}(window.jQuery),function(){for(var e=0,t=["ms","moz","webkit","o"],n=0;n<t.length&&!window.requestAnimationFrame;++n)window.requestAnimationFrame=window[t[n]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[n]+"CancelAnimationFrame"]||window[t[n]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,n){var i=(new Date).getTime(),o=Math.max(0,16-(i-e)),r=window.setTimeout(function(){t(i+o)},o);return e=i+o,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}();<|endoftext|>


<commit_before><commit_msg>add storago<commit_after><|endoftext|>


<commit_before>import React from 'react';
import {StyleSheet, ScrollView, Text, View, TouchableHighlight} from 'react-native';
import {NavigationBackAndroid, spring} from 'navigation-react-native';

export default ({color, colorRef, moveScene, stateNavigator}) => {
  const {url} = stateNavigator.stateContext;
  return (
    <View style={styles.detail}>
      <NavigationBackAndroid stateNavigator={stateNavigator} />
      <TouchableHighlight
        underlayColor="#fff"
        onPress={() => {
          colorRef.measure((ox, oy, w, h, x, y) => {
            moveScene({w, h, x, y});
            if (url === stateNavigator.stateContext.url)
              stateNavigator.navigateBack(1);
          });
        }}>
        <Text style={styles.back}>X</Text>
      </TouchableHighlight>
      <View
        onLayout={() => {
          this.color.measure((ox, oy, w, h, x, y) => {
            moveScene({w, h, x, y});
          });
        }}
        ref={el => this.color = el}
        style={[
          {backgroundColor: color},
          styles.color
        ]} />
      <Text style={styles.text}>{color}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  detail: {
    flex: 1,
    backgroundColor: '#fff',
  },
  back: {
    height: 50,
    fontSize: 20,
    color: '#000',
    fontWeight: 'bold',
    paddingTop: 20,
    paddingLeft: 20,
  },
  color: {
    flex: .6,
    marginLeft: 15,
    marginRight: 15,
  },
  text:{
    flex: .4,
    fontSize: 80,
    color: '#000',
    textAlign:'center',
    fontWeight: 'bold',
  },
});
<commit_msg>Removed unused component from import<commit_after>import React from 'react';
import {StyleSheet, Text, View, TouchableHighlight} from 'react-native';
import {NavigationBackAndroid, spring} from 'navigation-react-native';

export default ({color, colorRef, moveScene, stateNavigator}) => {
  const {url} = stateNavigator.stateContext;
  return (
    <View style={styles.detail}>
      <NavigationBackAndroid stateNavigator={stateNavigator} />
      <TouchableHighlight
        underlayColor="#fff"
        onPress={() => {
          colorRef.measure((ox, oy, w, h, x, y) => {
            moveScene({w, h, x, y});
            if (url === stateNavigator.stateContext.url)
              stateNavigator.navigateBack(1);
          });
        }}>
        <Text style={styles.back}>X</Text>
      </TouchableHighlight>
      <View
        onLayout={() => {
          this.color.measure((ox, oy, w, h, x, y) => {
            moveScene({w, h, x, y});
          });
        }}
        ref={el => this.color = el}
        style={[
          {backgroundColor: color},
          styles.color
        ]} />
      <Text style={styles.text}>{color}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  detail: {
    flex: 1,
    backgroundColor: '#fff',
  },
  back: {
    height: 50,
    fontSize: 20,
    color: '#000',
    fontWeight: 'bold',
    paddingTop: 20,
    paddingLeft: 20,
  },
  color: {
    flex: .6,
    marginLeft: 15,
    marginRight: 15,
  },
  text:{
    flex: .4,
    fontSize: 80,
    color: '#000',
    textAlign:'center',
    fontWeight: 'bold',
  },
});
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @author       Vladimir Agafonkin
 * @see          Based on Simplify.js mourner.github.io/simplify-js
 */

/**
 * Copyright (c) 2017, Vladimir Agafonkin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @ignore
 */
function getSqDist (p1, p2)
{
    var dx = p1.x - p2.x,
        dy = p1.y - p2.y;

    return dx * dx + dy * dy;
}

/**
 * Square distance from a point to a segment
 *
 * @ignore
 */
function getSqSegDist (p, p1, p2)
{
    var x = p1.x,
        y = p1.y,
        dx = p2.x - x,
        dy = p2.y - y;

    if (dx !== 0 || dy !== 0)
    {
        var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

        if (t > 1)
        {
            x = p2.x;
            y = p2.y;
        }
        else if (t > 0)
        {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}

/**
 * Basic distance-based simplification
 *
 * @ignore
 */
function simplifyRadialDist (points, sqTolerance)
{
    var prevPoint = points[0],
        newPoints = [ prevPoint ],
        point;

    for (var i = 1, len = points.length; i < len; i++)
    {
        point = points[i];

        if (getSqDist(point, prevPoint) > sqTolerance)
        {
            newPoints.push(point);
            prevPoint = point;
        }
    }

    if (prevPoint !== point)
    {
        newPoints.push(point);
    }

    return newPoints;
}

/**
 * @ignore
 */
function simplifyDPStep (points, first, last, sqTolerance, simplified)
{
    var maxSqDist = sqTolerance,
        index;

    for (var i = first + 1; i < last; i++)
    {
        var sqDist = getSqSegDist(points[i], points[first], points[last]);

        if (sqDist > maxSqDist)
        {
            index = i;
            maxSqDist = sqDist;
        }
    }

    if (maxSqDist > sqTolerance)
    {
        if (index - first > 1)
        {
            simplifyDPStep(points, first, index, sqTolerance, simplified);
        }

        simplified.push(points[index]);

        if (last - index > 1)
        {
            simplifyDPStep(points, index, last, sqTolerance, simplified);
        }
    }
}

/**
 * Simplification using Ramer-Douglas-Peucker algorithm
 *
 * @ignore
 */
function simplifyDouglasPeucker (points, sqTolerance)
{
    var last = points.length - 1;

    var simplified = [ points[0] ];

    simplifyDPStep(points, 0, last, sqTolerance, simplified);

    simplified.push(points[last]);

    return simplified;
}

/**
 * Takes a Polygon object and simplifies the points by running them through a combination of
 * Douglas-Peucker and Radial Distance algorithms. Simplification dramatically reduces the number of
 * points in a polygon while retaining its shape, giving a huge performance boost when processing
 * it and also reducing visual noise.
 *
 * @function Phaser.Geom.Polygon.Simplify
 * @since 3.50.0
 *
 * @generic {Phaser.Geom.Polygon} O - [polygon,$return]
 *
 * @param {Phaser.Geom.Polygon} polygon - The polygon to be simplified. The polygon will be modified in-place and returned.
 * @param {number} [tolerance=1] - Affects the amount of simplification (in the same metric as the point coordinates).
 * @param {boolean} [highestQuality=false] - Excludes distance-based preprocessing step which leads to highest quality simplification but runs ~10-20 times slower.
 *
 * @return {Phaser.Geom.Polygon} The input polygon.
 */
var Simplify = function (polygon, tolerance, highestQuality)
{
    if (tolerance === undefined) { tolerance = 1; }
    if (highestQuality === undefined) { highestQuality = false; }

    var points = polygon.points;

    if (points.length <= 2)
    {
        return points;
    }

    var sqTolerance = tolerance * tolerance;

    if (!highestQuality)
    {
        points = simplifyRadialDist(points, sqTolerance);
    }

    polygon.setTo(simplifyDouglasPeucker(points, sqTolerance));

    return polygon;
};

module.exports = Simplify;
<commit_msg>Always return polygon, even if points <= 2.<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @author       Vladimir Agafonkin
 * @see          Based on Simplify.js mourner.github.io/simplify-js
 */

/**
 * Copyright (c) 2017, Vladimir Agafonkin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @ignore
 */
function getSqDist (p1, p2)
{
    var dx = p1.x - p2.x,
        dy = p1.y - p2.y;

    return dx * dx + dy * dy;
}

/**
 * Square distance from a point to a segment
 *
 * @ignore
 */
function getSqSegDist (p, p1, p2)
{
    var x = p1.x,
        y = p1.y,
        dx = p2.x - x,
        dy = p2.y - y;

    if (dx !== 0 || dy !== 0)
    {
        var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

        if (t > 1)
        {
            x = p2.x;
            y = p2.y;
        }
        else if (t > 0)
        {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}

/**
 * Basic distance-based simplification
 *
 * @ignore
 */
function simplifyRadialDist (points, sqTolerance)
{
    var prevPoint = points[0],
        newPoints = [ prevPoint ],
        point;

    for (var i = 1, len = points.length; i < len; i++)
    {
        point = points[i];

        if (getSqDist(point, prevPoint) > sqTolerance)
        {
            newPoints.push(point);
            prevPoint = point;
        }
    }

    if (prevPoint !== point)
    {
        newPoints.push(point);
    }

    return newPoints;
}

/**
 * @ignore
 */
function simplifyDPStep (points, first, last, sqTolerance, simplified)
{
    var maxSqDist = sqTolerance,
        index;

    for (var i = first + 1; i < last; i++)
    {
        var sqDist = getSqSegDist(points[i], points[first], points[last]);

        if (sqDist > maxSqDist)
        {
            index = i;
            maxSqDist = sqDist;
        }
    }

    if (maxSqDist > sqTolerance)
    {
        if (index - first > 1)
        {
            simplifyDPStep(points, first, index, sqTolerance, simplified);
        }

        simplified.push(points[index]);

        if (last - index > 1)
        {
            simplifyDPStep(points, index, last, sqTolerance, simplified);
        }
    }
}

/**
 * Simplification using Ramer-Douglas-Peucker algorithm
 *
 * @ignore
 */
function simplifyDouglasPeucker (points, sqTolerance)
{
    var last = points.length - 1;

    var simplified = [ points[0] ];

    simplifyDPStep(points, 0, last, sqTolerance, simplified);

    simplified.push(points[last]);

    return simplified;
}

/**
 * Takes a Polygon object and simplifies the points by running them through a combination of
 * Douglas-Peucker and Radial Distance algorithms. Simplification dramatically reduces the number of
 * points in a polygon while retaining its shape, giving a huge performance boost when processing
 * it and also reducing visual noise.
 *
 * @function Phaser.Geom.Polygon.Simplify
 * @since 3.50.0
 *
 * @generic {Phaser.Geom.Polygon} O - [polygon,$return]
 *
 * @param {Phaser.Geom.Polygon} polygon - The polygon to be simplified. The polygon will be modified in-place and returned.
 * @param {number} [tolerance=1] - Affects the amount of simplification (in the same metric as the point coordinates).
 * @param {boolean} [highestQuality=false] - Excludes distance-based preprocessing step which leads to highest quality simplification but runs ~10-20 times slower.
 *
 * @return {Phaser.Geom.Polygon} The input polygon.
 */
var Simplify = function (polygon, tolerance, highestQuality)
{
    if (tolerance === undefined) { tolerance = 1; }
    if (highestQuality === undefined) { highestQuality = false; }

    var points = polygon.points;

    if (points.length > 2)
    {
        var sqTolerance = tolerance * tolerance;

        if (!highestQuality)
        {
            points = simplifyRadialDist(points, sqTolerance);
        }

        polygon.setTo(simplifyDouglasPeucker(points, sqTolerance));
    }

    return polygon;
};

module.exports = Simplify;
<|endoftext|>


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

  angular
    .module('csvupload')
    .controller('CsvuploadController', CsvuploadController);

  CsvuploadController.$inject = ['$scope', '$state','Upload','CsvuploadService','ngTableParams','$filter','$window'];

  function CsvuploadController($scope, $state, Upload,CsvUploadService,ngTableParams,$filter,$window) {
    var vm = this;
    vm.submit = submit;
    vm.upload = upload;
    vm.removeFile =removeFile;
    $scope.tableParams = {};
    vm.deviceList = [];

    CsvUploadService.query(function(data){
    vm.deviceList = data;
    $scope.tableParams.reload();
    });

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10,          // count per page
        sorting: {
            snmp_version: 'asc'     // initial sorting
        }
    }, {
        total: vm.deviceList.length,           // length of data
        getData: function($defer, params) {
        var orderedData = params.sorting() ? $filter('orderBy')(vm.deviceList, params.orderBy()) : data;
        orderedData	= $filter('filter')(orderedData, params.filter());
        params.total(orderedData.length);
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));                     }
    });

    // Save Article
    function submit() {
        vm.upload(vm.file);
    }

    function removeFile() {
            vm.file =null;
        }

    function upload(file) {
      Upload.upload({
        url: 'http://localhost:3000/upload/deviceList', //webAPI exposed to upload the file
        data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
              $window.alert(resp.config.data.file.name + 'Uploaded Successfully.');
              vm.deviceList = resp.data.respDeviceList;
              $scope.tableParams.reload();
              vm.file = null;
            } else {
              $window.alert('Upload Failed');
            }
        }, function (resp) { //catch error
          $window.alert('Upload Failed');
        })
    }
  }
}());
<commit_msg>Removed alerts in Upload Csvflow<commit_after>(function () {
  'use strict';

  angular
    .module('csvupload')
    .controller('CsvuploadController', CsvuploadController);

  CsvuploadController.$inject = ['$scope', '$state','Upload','CsvuploadService','ngTableParams','$filter','$window'];

  function CsvuploadController($scope, $state, Upload,CsvUploadService,ngTableParams,$filter,$window) {
    var vm = this;
    vm.submit = submit;
    vm.upload = upload;
    vm.removeFile =removeFile;
    $scope.tableParams = {};
    vm.deviceList = [];

    CsvUploadService.query(function(data){
    vm.deviceList = data;
    $scope.tableParams.reload();
    });

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10,          // count per page
        sorting: {
            snmp_version: 'asc'     // initial sorting
        }
    }, {
        total: vm.deviceList.length,           // length of data
        getData: function($defer, params) {
        var orderedData = params.sorting() ? $filter('orderBy')(vm.deviceList, params.orderBy()) : data;
        orderedData	= $filter('filter')(orderedData, params.filter());
        params.total(orderedData.length);
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));                     }
    });

    // Save Article
    function submit() {
        vm.upload(vm.file);
    }

    function removeFile() {
            vm.file =null;
        }

    function upload(file) {
      Upload.upload({
        url: 'http://localhost:3000/upload/deviceList', //webAPI exposed to upload the file
        data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
              //$window.alert(resp.config.data.file.name + 'Uploaded Successfully.');
              vm.deviceList = resp.data.respDeviceList;
              $scope.tableParams.reload();
              vm.file = null;
            } else {
              //$window.alert('Upload Failed');
            }
        }, function (resp) { //catch error
          //$window.alert('Upload Failed');
        })
    }
  }
}());
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import transitions from '../styles/transitions';
import EnhancedButton from '../internal/EnhancedButton';
import StepLabel from './StepLabel';

const isLabel = (child) => {
  return child && child.type && child.type.muiName === 'StepLabel';
};

const getStyles = (props, context, state) => {
  const {hovered} = state;
  const {backgroundColor, hoverBackgroundColor} = context.muiTheme.stepper;

  const styles = {
    root: {
      padding: 0,
      backgroundColor: hovered ? hoverBackgroundColor : backgroundColor,
      transition: transitions.easeOut(),
    },
  };

  if (context.stepper.orientation === 'vertical') {
    styles.root.width = '100%';
  }

  return styles;
};

class StepButton extends Component {

  static propTypes = {
    /**
     * Passed from `Step` Is passed to StepLabel.
     */
    active: PropTypes.bool,
    /**
     * Can be a `StepLabel` or a node to place inside `StepLabel` as children.
     */
    children: PropTypes.node,
    /**
     * Sets completed styling. Is passed to StepLabel.
     */
    completed: PropTypes.bool,
    /**
     * Disables the button and sets disabled styling. Is passed to StepLabel.
     */
    disabled: PropTypes.bool,
    /**
     * The icon displayed by the step label.
     */
    icon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
      PropTypes.number,
    ]),
    /**
     * Override the inline-styles of the icon container element.
     */
    iconContainerStyle: PropTypes.object,
    /** @ignore */
    last: PropTypes.bool,
    /** @ignore */
    onMouseEnter: PropTypes.func,
    /** @ignore */
    onMouseLeave: PropTypes.func,
    /** @ignore */
    onTouchStart: PropTypes.func,
    /**
     * Override the inline-style of the root element.
     */
    style: PropTypes.object,
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
    stepper: PropTypes.object,
  };

  state = {
    hovered: false,
    touched: false,
  };

  handleMouseEnter = (event) => {
    const {onMouseEnter} = this.props;
    // Cancel hover styles for touch devices
    if (!this.state.touched) {
      this.setState({hovered: true});
    }
    if (typeof onMouseEnter === 'function') {
      onMouseEnter(event);
    }
  };

  handleMouseLeave = (event) => {
    const {onMouseLeave} = this.props;
    this.setState({hovered: false});
    if (typeof onMouseLeave === 'function') {
      onMouseLeave(event);
    }
  };

  handleTouchStart = (event) => {
    const {onTouchStart} = this.props;
    if (!this.state.touched) {
      this.setState({touched: true});
    }
    if (typeof onTouchStart === 'function') {
      onTouchStart(event);
    }
  };

  render() {
    const {
      active,
      children,
      completed,
      disabled,
      icon,
      iconContainerStyle,
      last, // eslint-disable-line no-unused-vars
      onMouseEnter, // eslint-disable-line no-unused-vars
      onMouseLeave, // eslint-disable-line no-unused-vars
      onTouchStart, // eslint-disable-line no-unused-vars
      style,
      ...other
    } = this.props;

    const styles = getStyles(this.props, this.context, this.state);

    const child = isLabel(children) ? children : <StepLabel>{children}</StepLabel>;

    return (
      <EnhancedButton
        disabled={disabled}
        style={Object.assign(styles.root, style)}
        onMouseEnter={this.handleMouseEnter}
        onMouseLeave={this.handleMouseLeave}
        onTouchStart={this.handleTouchStart}
        {...other}
      >
        {React.cloneElement(child, {active, completed, disabled, icon, iconContainerStyle})}
      </EnhancedButton>
    );
  }
}

export default StepButton;
<commit_msg>added id generation and pass in to StepButton #26 if id is passed in the class name is appended to it so its not posted out as a duplicated value<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import transitions from '../styles/transitions';
import EnhancedButton from '../internal/EnhancedButton';
import StepLabel from './StepLabel';

const isLabel = (child) => {
  return child && child.type && child.type.muiName === 'StepLabel';
};

const getStyles = (props, context, state) => {
  const {hovered} = state;
  const {backgroundColor, hoverBackgroundColor} = context.muiTheme.stepper;

  const styles = {
    root: {
      padding: 0,
      backgroundColor: hovered ? hoverBackgroundColor : backgroundColor,
      transition: transitions.easeOut(),
    },
  };

  if (context.stepper.orientation === 'vertical') {
    styles.root.width = '100%';
  }

  return styles;
};

class StepButton extends Component {

  static propTypes = {
    /**
     * Passed from `Step` Is passed to StepLabel.
     */
    active: PropTypes.bool,
    /**
     * Can be a `StepLabel` or a node to place inside `StepLabel` as children.
     */
    children: PropTypes.node,
    /**
     * Sets completed styling. Is passed to StepLabel.
     */
    completed: PropTypes.bool,
    /**
     * Disables the button and sets disabled styling. Is passed to StepLabel.
     */
    disabled: PropTypes.bool,
    /**
     * The icon displayed by the step label.
     */
    icon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
      PropTypes.number,
    ]),
    /**
     * Override the inline-styles of the icon container element.
     */
    iconContainerStyle: PropTypes.object,
    /**
     * The id value used for the component.
     * This will be used as a base for all child components also.
     * If not provided the class name along with appropriate properties and a random number will be used.
     */
    id: PropTypes.string,
    /** @ignore */
    last: PropTypes.bool,
    /** @ignore */
    onMouseEnter: PropTypes.func,
    /** @ignore */
    onMouseLeave: PropTypes.func,
    /** @ignore */
    onTouchStart: PropTypes.func,
    /**
     * Override the inline-style of the root element.
     */
    style: PropTypes.object,
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
    stepper: PropTypes.object,
  };

  state = {
    hovered: false,
    touched: false,
  };

  componentWillMount() {
    const uniqueId = `${this.constructor.name}-${Math.floor(Math.random() * 0xFFFF)}`;
    this.uniqueId = uniqueId.replace(/[^A-Za-z0-9-]/gi, '');
  }

  handleMouseEnter = (event) => {
    const {onMouseEnter} = this.props;
    // Cancel hover styles for touch devices
    if (!this.state.touched) {
      this.setState({hovered: true});
    }
    if (typeof onMouseEnter === 'function') {
      onMouseEnter(event);
    }
  };

  handleMouseLeave = (event) => {
    const {onMouseLeave} = this.props;
    this.setState({hovered: false});
    if (typeof onMouseLeave === 'function') {
      onMouseLeave(event);
    }
  };

  handleTouchStart = (event) => {
    const {onTouchStart} = this.props;
    if (!this.state.touched) {
      this.setState({touched: true});
    }
    if (typeof onTouchStart === 'function') {
      onTouchStart(event);
    }
  };

  render() {
    const {
      active,
      children,
      completed,
      disabled,
      icon,
      iconContainerStyle,
      id,
      last, // eslint-disable-line no-unused-vars
      onMouseEnter, // eslint-disable-line no-unused-vars
      onMouseLeave, // eslint-disable-line no-unused-vars
      onTouchStart, // eslint-disable-line no-unused-vars
      style,
      ...other
    } = this.props;

    const baseId = id ? `${id}-${this.constructor.name}` : this.uniqueId;

    const styles = getStyles(this.props, this.context, this.state);

    const child = isLabel(children) ? children : <StepLabel>{children}</StepLabel>;

    return (
      <EnhancedButton
        id={baseId}
        disabled={disabled}
        style={Object.assign(styles.root, style)}
        onMouseEnter={this.handleMouseEnter}
        onMouseLeave={this.handleMouseLeave}
        onTouchStart={this.handleTouchStart}
        {...other}
      >
        {React.cloneElement(child, {active, completed, disabled, icon, iconContainerStyle})}
      </EnhancedButton>
    );
  }
}

export default StepButton;
<|endoftext|>


<commit_before>// ==UserScript==
// @name         OPR Show EXIF Info
// @version      0.3
// @namespace    https://github.com/DeepAQ/SmartIntel
// @description  Show EXIF info of photos in OPR
// @match        *://opr.ingress.com/recon
// @require      https://cdn.bootcss.com/zepto/1.2.0/zepto.min.js
// @require      https://cdn.bootcss.com/exif-js/2.3.0/exif.min.js
// ==/UserScript==

(function() {
    var tagsToShow = ['DateTime', 'Make', 'Model', 'Software', 'GPSLatitude', 'GPSLongitude'];

    var dms_to_deg = function (dms) {
        var d = dms[0];
        var m = dms[1];
        var s = dms[2];
        return Math.round((d / 1 + m / 60 + s / 3600) * 1E6) / 1E6;
    };

    var distance = function (lat1, lng1, lat2, lng2) {
        var dx = Math.abs(lng1 - lng2);
        var dy = Math.abs(lat1 - lat2);
        var b = (lat1 + lat2) / 2.0;
        var lx = (dx / 180.0 * Math.PI) * 6367000.0 * Math.cos(b / 180.0 * Math.PI);
        var ly = 6367000.0 * dy / 180.0 * Math.PI;
        // var l = Math.sqrt(lx * lx + ly * ly);
        return (lat1 < lat2 ? '↑' : '↓') + Math.ceil(lx) + 'm ' + (lng1 < lng2 ? '→' : '←') + Math.ceil(ly) + 'm';
    };

    var getExif = function (url) {
        var img = document.createElement('img');
        img.src = url;
        img.onload = function () {
            EXIF.getData(img, function () {
                var tags = EXIF.getAllTags(this);
                var info = '';
                for (var key in tagsToShow) {
                    if (tags[tagsToShow[key]]) {
                        info += tagsToShow[key] + ': ' + tags[tagsToShow[key]];
                        if (tagsToShow[key] == 'GPSLatitude' || tagsToShow[key] == 'GPSLongitude') {
                            info += ' (' + dms_to_deg(tags[tagsToShow[key]]) + ')';
                        }
                        info += '
';
                    }
                }
                if (info !== '') {
                    info = '[EXIF]
' + info;
                } else {
                    info = '[EXIF]
No EXIF data present';
                }
                if (tags['GPSLatitude'] && tags['GPSLongitude']) {
                    var deglat = dms_to_deg(tags['GPSLatitude']);
                    var deglon = dms_to_deg(tags['GPSLongitude']);
                    var portalPos = /@([^,]+),([^,]+)$/.exec(document.getElementById('descriptionDiv').getElementsByTagName('a')[1].getAttribute('href'));
                    var portalLat = Number(portalPos[1]);
                    var portalLng = Number(portalPos[2]);
                    info += 'Distance (portal -> photo): ' + distance(portalLat, portalLng, deglat, deglon) + '
';
                    info += '
Open in OSM
';
                }
                $('#descriptionDiv').append('
' + info + '
');
            });
        };
    };

    var tryGetImgUrl = function () {
        var url = $('.center-cropped-img').attr('src');
        if (!url) {
            setTimeout(tryGetImgUrl, 1000);
        } else {
            getExif((url + '=s0').replace('http:', 'https:'));
        }
    };

    tryGetImgUrl();
})();
<commit_msg>bump 0.4<commit_after>// ==UserScript==
// @name         OPR Show EXIF Info
// @version      0.4
// @namespace    https://github.com/DeepAQ/SmartIntel
// @description  Show EXIF info of photos in OPR
// @match        *://opr.ingress.com/recon
// @require      https://cdn.bootcss.com/zepto/1.2.0/zepto.min.js
// @require      https://cdn.bootcss.com/exif-js/2.3.0/exif.min.js
// ==/UserScript==

(function() {
    var tagsToShow = ['DateTime', 'Make', 'Model', 'Software', 'GPSLatitude', 'GPSLongitude'];

    var dms_to_deg = function (dms) {
        var d = dms[0];
        var m = dms[1];
        var s = dms[2];
        return Math.round((d / 1 + m / 60 + s / 3600) * 1E6) / 1E6;
    };

    var distance = function (lat1, lng1, lat2, lng2) {
        var dx = Math.abs(lng1 - lng2);
        var dy = Math.abs(lat1 - lat2);
        var b = (lat1 + lat2) / 2.0;
        var lx = (dx / 180.0 * Math.PI) * 6367000.0 * Math.cos(b / 180.0 * Math.PI);
        var ly = 6367000.0 * dy / 180.0 * Math.PI;
        // var l = Math.sqrt(lx * lx + ly * ly);
        return (lat1 < lat2 ? '↑' : '↓') + Math.ceil(lx) + 'm ' + (lng1 < lng2 ? '→' : '←') + Math.ceil(ly) + 'm';
    };

    var getExif = function (url) {
        var img = document.createElement('img');
        img.src = url;
        img.onload = function () {
            EXIF.getData(img, function () {
                var tags = EXIF.getAllTags(this);
                var info = '';
                for (var key in tagsToShow) {
                    if (tags[tagsToShow[key]]) {
                        info += tagsToShow[key] + ': ' + tags[tagsToShow[key]];
                        if (tagsToShow[key] == 'GPSLatitude' || tagsToShow[key] == 'GPSLongitude') {
                            info += ' (' + dms_to_deg(tags[tagsToShow[key]]) + ')';
                        }
                        info += '
';
                    }
                }
                if (info !== '') {
                    info = '[EXIF]
' + info;
                } else {
                    info = '[EXIF]
No EXIF data present';
                }
                if (tags['GPSLatitude'] && tags['GPSLongitude']) {
                    var deglat = dms_to_deg(tags['GPSLatitude']);
                    var deglon = dms_to_deg(tags['GPSLongitude']);
                    var portalPos = /@([^,]+),([^,]+)$/.exec(document.getElementById('descriptionDiv').getElementsByTagName('a')[1].getAttribute('href'));
                    var portalLat = Number(portalPos[1]);
                    var portalLng = Number(portalPos[2]);
                    info += 'Distance (portal -> photo): ' + distance(portalLat, portalLng, deglat, deglon) + '
';
                    info += '
Open in OSM
';
                }
                $('#descriptionDiv').append('
' + info + '
');
            });
        };
    };

    var tryGetImgUrl = function () {
        var url = $('.center-cropped-img').attr('src');
        if (!url) {
            setTimeout(tryGetImgUrl, 1000);
        } else {
            getExif((url + '=s0').replace('http:', 'https:'));
        }
    };

    tryGetImgUrl();
})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import * as firebase from 'firebase';
import CONSTANTS from '../../config/constants.json'
import '../../css/App.css';
import logo_calzaweb_blanco_mini from '../../img/logo-calzaweb-blanco-mini.png';

class HeaderPanel extends Component {
  constructor(props) {
    super(props);

    this.state = {
      userName : ""
    };
  }

  /**
   * Get the user name from the DB for displaying it.
   */
  componentWillMount () {
    if ( this.props.userId ) {
      firebase.database().ref(CONSTANTS.REFERENCE1).once('value').then( (snapshot) => {
        this.setState ({
          userName : snapshot.val().name
        });
      });
    }
  }

  render() {
    return (

              <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

              </button>

                   Bienvenido { this.state.userName }

    );
  }
}

export default HeaderPanel;
<commit_msg>href removed from tag a.<commit_after>import React, { Component } from 'react';
import * as firebase from 'firebase';
import CONSTANTS from '../../config/constants.json'
import '../../css/App.css';
import logo_calzaweb_blanco_mini from '../../img/logo-calzaweb-blanco-mini.png';

class HeaderPanel extends Component {
  constructor(props) {
    super(props);

    this.state = {
      userName : ""
    };
  }

  /**
   * Get the user name from the DB for displaying it.
   */
  componentWillMount () {
    if ( this.props.userId ) {
      firebase.database().ref(CONSTANTS.REFERENCE1).once('value').then( (snapshot) => {
        this.setState ({
          userName : snapshot.val().name
        });
      });
    }
  }

  render() {
    return (

              <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

              </button>

                   Bienvenido { this.state.userName }

    );
  }
}

export default HeaderPanel;
<|endoftext|>


<commit_before>// Avatar application. Will handle switching logic between avatar & freelook camera (clientside), and
// spawning avatars for clients (serverside). Note: this is not a startup script, but is meant to be
// placed in an entity in a scene that wishes to implement avatar functionality.

var avatar_area_size = 10;
var avatar_area_x = 0;
var avatar_area_y = 0;
var avatar_area_z = 20;

var isserver = server.IsRunning();

if (isserver == false)
{
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    inputmapper.SetTemporary(true);
    inputmapper.contextPriority = 102;
    inputmapper.RegisterMapping("Ctrl+Tab", "ToggleCamera", 1);

    me.Action("ToggleCamera").Triggered.connect(ClientHandleToggleCamera);
}
else
{
    server.UserConnected.connect(ServerHandleUserConnected);
    server.UserDisconnected.connect(ServerHandleUserDisconnected);
}

function ClientHandleToggleCamera()
{
    // For camera switching to work, must have both the freelookcamera & avatarcamera in the scene
    var freelookcameraentity = scene.GetEntityByNameRaw("FreeLookCamera");
    var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
    if ((freelookcameraentity == null) || (avatarcameraentity == null))
        return;
    var freelookcamera = freelookcameraentity.GetComponentRaw("EC_OgreCamera");
    var avatarcamera = avatarcameraentity.GetComponentRaw("EC_OgreCamera");

    if (avatarcamera.IsActive())
    {
        freelookcameraentity.GetComponentRaw("EC_Placeable").transform = avatarcameraentity.GetComponentRaw("EC_Placeable").transform
        freelookcamera.SetActive();
    }
    else
    {
        avatarcamera.SetActive();
    }
}

function ServerHandleUserConnected(connectionID, username)
{
    var avatarEntityName = "Avatar" + connectionID;
    var avatarEntity = scene.CreateEntityRaw(scene.NextFreeId(), ["EC_Script", "EC_Placeable"]);
    avatarEntity.SetName(avatarEntityName);
    avatarEntity.SetDescription(username);

    var script = avatarEntity.GetComponentRaw("EC_Script");
    script.type = "js";
    script.runOnLoad = true;
    var r = script.scriptRef;
    r.ref = "./jsmodules/camera/freelookcamera.js";
    script.scriptRef = r;

    var placeable = avatarEntity.GetComponentRaw("EC_Placeable");
    // Set random starting position for avatar
    var transform = placeable.transform;
    transform.pos.x = (Math.random() - 0.5) * avatar_area_size + avatar_area_x;
    transform.pos.y = (Math.random() - 0.5) * avatar_area_size + avatar_area_y;
    transform.pos.z = avatar_area_z;
    placeable.transform = transform;

    scene.EmitEntityCreated(avatarEntity);
}

function ServerHandleUserDisconnected(connectionID)
{
    var avatarEntityName = "Avatar" + connectionID;
    var entityID = scene.GetEntityByNameRaw(avatarEntityName).Id;
    scene.RemoveEntityRaw(entityID);
}

<commit_msg>Fixed avatar application.<commit_after>// Avatar application. Will handle switching logic between avatar & freelook camera (clientside), and
// spawning avatars for clients (serverside). Note: this is not a startup script, but is meant to be
// placed in an entity in a scene that wishes to implement avatar functionality.

var avatar_area_size = 10;
var avatar_area_x = 0;
var avatar_area_y = 0;
var avatar_area_z = 20;

var isserver = server.IsRunning();

if (isserver == false)
{
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    inputmapper.SetTemporary(true);
    inputmapper.contextPriority = 102;
    inputmapper.RegisterMapping("Ctrl+Tab", "ToggleCamera", 1);

    me.Action("ToggleCamera").Triggered.connect(ClientHandleToggleCamera);
}
else
{
    server.UserConnected.connect(ServerHandleUserConnected);
    server.UserDisconnected.connect(ServerHandleUserDisconnected);
}

function ClientHandleToggleCamera()
{
    // For camera switching to work, must have both the freelookcamera & avatarcamera in the scene
    var freelookcameraentity = scene.GetEntityByNameRaw("FreeLookCamera");
    var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
    if ((freelookcameraentity == null) || (avatarcameraentity == null))
        return;
    var freelookcamera = freelookcameraentity.GetComponentRaw("EC_OgreCamera");
    var avatarcamera = avatarcameraentity.GetComponentRaw("EC_OgreCamera");

    if (avatarcamera.IsActive())
    {
        freelookcameraentity.GetComponentRaw("EC_Placeable").transform = avatarcameraentity.GetComponentRaw("EC_Placeable").transform
        freelookcamera.SetActive();
    }
    else
    {
        avatarcamera.SetActive();
    }
}

function ServerHandleUserConnected(connectionID, username)
{
    var avatarEntityName = "Avatar" + connectionID;
    var avatarEntity = scene.CreateEntityRaw(scene.NextFreeId(), ["EC_Script", "EC_Placeable"]);
    avatarEntity.SetName(avatarEntityName);
    avatarEntity.SetDescription(username);

    var script = avatarEntity.GetComponentRaw("EC_Script");
    script.type = "js";
    script.runOnLoad = true;
    var r = script.scriptRef;
    r.ref = "./jsmodules/avatar/simpleavatar.js";
    script.scriptRef = r;

    var placeable = avatarEntity.GetComponentRaw("EC_Placeable");
    // Set random starting position for avatar
    var transform = placeable.transform;
    transform.pos.x = (Math.random() - 0.5) * avatar_area_size + avatar_area_x;
    transform.pos.y = (Math.random() - 0.5) * avatar_area_size + avatar_area_y;
    transform.pos.z = avatar_area_z;
    placeable.transform = transform;

    scene.EmitEntityCreated(avatarEntity);
}

function ServerHandleUserDisconnected(connectionID)
{
    var avatarEntityName = "Avatar" + connectionID;
    var entityID = scene.GetEntityByNameRaw(avatarEntityName).Id;
    scene.RemoveEntityRaw(entityID);
}

<|endoftext|>