<commit_before>(function() {
  var ApiBase, debug, querystring, slumber,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  debug = require('debug')('mailgun:ApiBaseHTTP');

  ApiBase = require('./ApiBase').ApiBase;

  querystring = require('querystring');

  slumber = require('slumber');

  module.exports.ApiBaseHTTP = (function(superClass) {
    extend(ApiBaseHTTP, superClass);

    function ApiBaseHTTP() {
      this.patch = bind(this.patch, this);
      this.put = bind(this.put, this);
      this.post = bind(this.post, this);
      this["delete"] = bind(this["delete"], this);
      this.get = bind(this.get, this);
      this.fn_wrapper = bind(this.fn_wrapper, this);
      this.prepare_opts = bind(this.prepare_opts, this);
      this.init = bind(this.init, this);
      this.handleOptions = bind(this.handleOptions, this);
      return ApiBaseHTTP.__super__.constructor.apply(this, arguments);
    }

    ApiBaseHTTP.prototype.handleOptions = function() {
      var base, base1, base2;
      ApiBaseHTTP.__super__.handleOptions.apply(this, arguments);
      if ((base = this.options).base_url == null) {
        base.base_url = '';
      }
      if (!this.options.auth) {
        throw "`auth` is mandatory";
      }
      if ((base1 = this.options).slumber == null) {
        base1.slumber = {};
      }
      if ((base2 = this.options.slumber).append_slash == null) {
        base2.append_slash = false;
      }
      if (this.options.auth != null) {
        this.options.slumber.auth = this.options.auth;
      }
      return debug("handleOptions()");
    };

    ApiBaseHTTP.prototype.init = function() {
      var api;
      ApiBaseHTTP.__super__.init.apply(this, arguments);
      api = slumber.API('https://api.mailgun.net/', this.options.slumber);
      return this.slumber = api(this.options.base_url);
    };

    ApiBaseHTTP.prototype.prepare_opts = function(opts) {
      if (opts.__query == null) {
        opts.__query = {};
      }
      opts.headers = {
        'content-type': 'application/x-www-form-urlencoded'
      };
      return opts;
    };

    ApiBaseHTTP.prototype.fn_wrapper = function(fn) {
      return (function(_this) {
        return function(err, response, ret) {
          var arity;
          arity = fn.length;
          switch (arity) {
            case 1:
              return fn(ret);
            case 2:
              return fn(err, (!!err ? response.statusMessage : JSON.parse(response.body)));
            case 3:
              return fn(err, response, ret);
          }
        };
      })(this);
    };

    ApiBaseHTTP.prototype.get = function(path, query, fn) {
      var opts;
      if (query == null) {
        query = {};
      }
      if (fn == null) {
        fn = null;
      }
      if ('function' === typeof query) {
        fn = query;
        query = {};
      }
      opts = this.prepare_opts(query);
      return this.slumber(path).get(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype["delete"] = function(path, fn) {
      var opts;
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts({});
      return this.slumber(path)["delete"](opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.post = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).post(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.put = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).put(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.patch = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).patch(opts, this.fn_wrapper(fn));
    };

    return ApiBaseHTTP;

  })(ApiBase);

}).call(this);
<commit_msg>fix err<commit_after>(function() {
  var ApiBase, debug, querystring, slumber,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  debug = require('debug')('mailgun:ApiBaseHTTP');

  ApiBase = require('./ApiBase').ApiBase;

  querystring = require('querystring');

  slumber = require('slumber');

  module.exports.ApiBaseHTTP = (function(superClass) {
    extend(ApiBaseHTTP, superClass);

    function ApiBaseHTTP() {
      this.patch = bind(this.patch, this);
      this.put = bind(this.put, this);
      this.post = bind(this.post, this);
      this["delete"] = bind(this["delete"], this);
      this.get = bind(this.get, this);
      this.fn_wrapper = bind(this.fn_wrapper, this);
      this.prepare_opts = bind(this.prepare_opts, this);
      this.init = bind(this.init, this);
      this.handleOptions = bind(this.handleOptions, this);
      return ApiBaseHTTP.__super__.constructor.apply(this, arguments);
    }

    ApiBaseHTTP.prototype.handleOptions = function() {
      var base, base1, base2;
      ApiBaseHTTP.__super__.handleOptions.apply(this, arguments);
      if ((base = this.options).base_url == null) {
        base.base_url = '';
      }
      if (!this.options.auth) {
        throw "`auth` is mandatory";
      }
      if ((base1 = this.options).slumber == null) {
        base1.slumber = {};
      }
      if ((base2 = this.options.slumber).append_slash == null) {
        base2.append_slash = false;
      }
      if (this.options.auth != null) {
        this.options.slumber.auth = this.options.auth;
      }
      return debug("handleOptions()");
    };

    ApiBaseHTTP.prototype.init = function() {
      var api;
      ApiBaseHTTP.__super__.init.apply(this, arguments);
      api = slumber.API('https://api.mailgun.net/', this.options.slumber);
      return this.slumber = api(this.options.base_url);
    };

    ApiBaseHTTP.prototype.prepare_opts = function(opts) {
      if (opts.__query == null) {
        opts.__query = {};
      }
      opts.headers = {
        'content-type': 'application/x-www-form-urlencoded'
      };
      return opts;
    };

    ApiBaseHTTP.prototype.fn_wrapper = function(fn) {
      return (function(_this) {
        return function(err, response, ret) {
          var arity;
          arity = fn.length;
          switch (arity) {
            case 1:
              return fn(ret);
            case 2:
              return fn(err);
            case 3:
              return fn(err, response, ret);
          }
        };
      })(this);
    };

    ApiBaseHTTP.prototype.get = function(path, query, fn) {
      var opts;
      if (query == null) {
        query = {};
      }
      if (fn == null) {
        fn = null;
      }
      if ('function' === typeof query) {
        fn = query;
        query = {};
      }
      opts = this.prepare_opts(query);
      return this.slumber(path).get(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype["delete"] = function(path, fn) {
      var opts;
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts({});
      return this.slumber(path)["delete"](opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.post = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).post(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.put = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).put(opts, this.fn_wrapper(fn));
    };

    ApiBaseHTTP.prototype.patch = function(path, data, fn) {
      var opts;
      if (data == null) {
        data = {};
      }
      if (fn == null) {
        fn = null;
      }
      opts = this.prepare_opts(data);
      return this.slumber(path).patch(opts, this.fn_wrapper(fn));
    };

    return ApiBaseHTTP;

  })(ApiBase);

}).call(this);
<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';

import Branch, {nullBranch} from '../../lib/models/branch';
import BranchSet from '../../lib/models/branch-set';
import Issueish from '../../lib/models/issueish';
import IssueishListView from '../../lib/views/issueish-list-view';
import CheckSuitesAccumulator from '../../lib/containers/accumulators/check-suites-accumulator';
import {pullRequestBuilder} from '../builder/graphql/pr';

import issueishQuery from '../../lib/controllers/__generated__/issueishListController_results.graphql';

function createPullRequestResult({number, states}) {
  return pullRequestBuilder(issueishQuery)
    .number(number)
    .commits(conn => {
      conn.addNode(n => n.commit(c => {
        if (states) {
          c.status(st => {
            for (const state of states) {
              st.addContext(con => con.state(state));
            }
          });
        } else {
          c.nullStatus();
        }
      }));
    })
    .build();
}

const allGreen = new Issueish(createPullRequestResult({number: 1, states: ['SUCCESS', 'SUCCESS', 'SUCCESS']}));
const mixed = new Issueish(createPullRequestResult({number: 2, states: ['SUCCESS', 'PENDING', 'FAILURE']}));
const allRed = new Issueish(createPullRequestResult({number: 3, states: ['FAILURE', 'ERROR', 'FAILURE']}));
const noStatus = new Issueish(createPullRequestResult({number: 4, states: null}));

class CustomComponent extends React.Component {
  render() {
    return
;
  }
}

describe('IssueishListView', function() {
  let branch, branchSet;

  beforeEach(function() {
    branch = new Branch('master', nullBranch, nullBranch, true);
    branchSet = new BranchSet();
    branchSet.add(branch);
  });

  function buildApp(overrideProps = {}) {
    return (
      <IssueishListView
        title="aaa"
        isLoading={true}
        total={0}
        issueishes={[]}

        onCreatePr={() => {}}
        onIssueishClick={() => {}}
        onMoreClick={() => {}}

        {...overrideProps}
      />
    );
  }

  it('sets the accordion title to the search name', function() {
    const wrapper = shallow(buildApp({
      title: 'the search name',
    }));
    assert.strictEqual(wrapper.find('Accordion').prop('leftTitle'), 'the search name');
  });

  describe('while loading', function() {
    it('sets its accordion as isLoading', function() {
      const wrapper = shallow(buildApp());
      assert.isTrue(wrapper.find('Accordion').prop('isLoading'));
    });

    it('passes an empty result list', function() {
      const wrapper = shallow(buildApp());
      assert.lengthOf(wrapper.find('Accordion').prop('results'), 0);
    });
  });

  describe('with empty results', function() {
    it('uses a custom EmptyComponent if one is provided', function() {
      const wrapper = shallow(buildApp({isLoading: false, emptyComponent: CustomComponent}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is(CustomComponent));
    });

    it('renders an error tile if an error is present', function() {
      const error = new Error('error');
      error.rawStack = error.stack;
      const wrapper = shallow(buildApp({isLoading: false, error}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is('QueryErrorTile'));
    });
  });

  describe('with nonempty results', function() {
    it('passes its results to the accordion', function() {
      const issueishes = [allGreen, mixed, allRed];
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
      }));
      assert.deepEqual(wrapper.find('Accordion').prop('results'), issueishes);
    });

    it('renders a check if all status checks are successful', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allGreen);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'check');
    });

    it('renders an x if all status checks have failed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allRed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'x');
    });

    it('renders a donut chart if status checks are mixed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(mixed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      const chart = accumulated.find('StatusDonutChart');
      assert.strictEqual(chart.prop('pending'), 1);
      assert.strictEqual(chart.prop('failure'), 1);
      assert.strictEqual(chart.prop('success'), 1);
    });

    it('renders nothing with no status checks are present', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(noStatus);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'dash');
    });

    it('calls its onIssueishClick handler when an item is clicked', function() {
      const onIssueishClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onIssueishClick}));

      wrapper.find('Accordion').prop('onClickItem')(mixed);
      assert.isTrue(onIssueishClick.calledWith(mixed));
    });

    it('calls its onMoreClick handler when a "more" component is clicked', function() {
      const onMoreClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onMoreClick}));

      const more = wrapper.find('Accordion').renderProp('moreComponent')();
      more.find('.github-IssueishList-more a').simulate('click');
      assert.isTrue(onMoreClick.called);
    });

    it('calls its `showActionsMenu` handler when the menu icon is clicked', function() {
      const issueishes = [allGreen, mixed, allRed];
      const showActionsMenu = sinon.stub();
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
        showActionsMenu,
      }));

      wrapper.find('Octicon.github-IssueishList-item--menu').at(1).simulate('click');
      assert.isTrue(showActionsMenu.calledWith(mixed));
    });
  });

  it('renders review button only if needed', function() {
    const openReviews = sinon.spy();
    const wrapper = shallow(buildApp({total: 1, openReviews}));
    assert.isFalse(wrapper.exists('.github-IssueishList-openReviewsButton'));

    wrapper.setProps({needReviewsButton: true});
    const reviews = wrapper.find('Accordion').renderProp('reviewsButton')();
    assert.isTrue(reviews.exists('.github-IssueishList-openReviewsButton'));
    reviews.find('.github-IssueishList-openReviewsButton').simulate('click', {stopPropagation() {}});
    assert.isTrue(openReviews.called);
  });
});
<commit_msg>Fix logical regressions in IssueishListView tests<commit_after>import React from 'react';
import {shallow} from 'enzyme';

import Branch, {nullBranch} from '../../lib/models/branch';
import BranchSet from '../../lib/models/branch-set';
import Issueish from '../../lib/models/issueish';
import IssueishListView from '../../lib/views/issueish-list-view';
import CheckSuitesAccumulator from '../../lib/containers/accumulators/check-suites-accumulator';
import {pullRequestBuilder} from '../builder/graphql/pr';

import issueishQuery from '../../lib/controllers/__generated__/issueishListController_results.graphql';

function createPullRequestResult({number, states}) {
  return pullRequestBuilder(issueishQuery)
    .number(number)
    .commits(conn => {
      conn.addNode(n => n.commit(c => {
        if (states) {
          c.status(st => {
            for (const state of states) {
              st.addContext(con => con.state(state));
            }
          });
        } else {
          c.nullStatus();
        }
      }));
    })
    .build();
}

const allGreen = new Issueish(createPullRequestResult({number: 1, states: ['SUCCESS', 'SUCCESS', 'SUCCESS']}));
const mixed = new Issueish(createPullRequestResult({number: 2, states: ['SUCCESS', 'PENDING', 'FAILURE']}));
const allRed = new Issueish(createPullRequestResult({number: 3, states: ['FAILURE', 'ERROR', 'FAILURE']}));
const noStatus = new Issueish(createPullRequestResult({number: 4, states: null}));

class CustomComponent extends React.Component {
  render() {
    return
;
  }
}

describe('IssueishListView', function() {
  let branch, branchSet;

  beforeEach(function() {
    branch = new Branch('master', nullBranch, nullBranch, true);
    branchSet = new BranchSet();
    branchSet.add(branch);
  });

  function buildApp(overrideProps = {}) {
    return (
      <IssueishListView
        title="aaa"
        isLoading={true}
        total={0}
        issueishes={[]}

        onCreatePr={() => {}}
        onIssueishClick={() => {}}
        onMoreClick={() => {}}

        {...overrideProps}
      />
    );
  }

  it('sets the accordion title to the search name', function() {
    const wrapper = shallow(buildApp({
      title: 'the search name',
    }));
    assert.strictEqual(wrapper.find('Accordion').prop('leftTitle'), 'the search name');
  });

  describe('while loading', function() {
    it('sets its accordion as isLoading', function() {
      const wrapper = shallow(buildApp());
      assert.isTrue(wrapper.find('Accordion').prop('isLoading'));
    });

    it('passes an empty result list', function() {
      const wrapper = shallow(buildApp());
      assert.lengthOf(wrapper.find('Accordion').prop('results'), 0);
    });
  });

  describe('with empty results', function() {
    it('uses a custom EmptyComponent if one is provided', function() {
      const wrapper = shallow(buildApp({isLoading: false, emptyComponent: CustomComponent}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is(CustomComponent));
    });

    it('renders an error tile if an error is present', function() {
      const error = new Error('error');
      error.rawStack = error.stack;
      const wrapper = shallow(buildApp({isLoading: false, error}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is('QueryErrorTile'));
    });
  });

  describe('with nonempty results', function() {
    it('passes its results to the accordion', function() {
      const issueishes = [allGreen, mixed, allRed];
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
      }));
      assert.deepEqual(wrapper.find('Accordion').prop('results'), issueishes);
    });

    it('renders a check if all status checks are successful', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allGreen);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon.github-IssueishList-item--status').prop('icon'), 'check');
    });

    it('renders an x if all status checks have failed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allRed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon.github-IssueishList-item--status').prop('icon'), 'x');
    });

    it('renders a donut chart if status checks are mixed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(mixed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      const chart = accumulated.find('StatusDonutChart');
      assert.strictEqual(chart.prop('pending'), 1);
      assert.strictEqual(chart.prop('failure'), 1);
      assert.strictEqual(chart.prop('success'), 1);
    });

    it('renders nothing with no status checks are present', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(noStatus);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      assert.strictEqual(accumulated.find('Octicon.github-IssueishList-item--status').prop('icon'), 'dash');
    });

    it('calls its onIssueishClick handler when an item is clicked', function() {
      const onIssueishClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onIssueishClick}));

      wrapper.find('Accordion').prop('onClickItem')(mixed);
      assert.isTrue(onIssueishClick.calledWith(mixed));
    });

    it('calls its onMoreClick handler when a "more" component is clicked', function() {
      const onMoreClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onMoreClick}));

      const more = wrapper.find('Accordion').renderProp('moreComponent')();
      more.find('.github-IssueishList-more a').simulate('click');
      assert.isTrue(onMoreClick.called);
    });

    it('calls its `showActionsMenu` handler when the menu icon is clicked', function() {
      const issueishes = [allGreen, mixed, allRed];
      const showActionsMenu = sinon.stub();
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
        showActionsMenu,
      }));
      const result = wrapper.find('Accordion').renderProp('children')(mixed);
      const child = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      child.find('Octicon.github-IssueishList-item--menu').simulate('click', {
        preventDefault() {},
        stopPropagation() {},
      });
      assert.isTrue(showActionsMenu.calledWith(mixed));
    });
  });

  it('renders review button only if needed', function() {
    const openReviews = sinon.spy();
    const wrapper = shallow(buildApp({total: 1, issueishes: [allGreen], openReviews}));
    const child0 = wrapper.find('Accordion').renderProp('reviewsButton')();
    assert.isFalse(child0.exists('.github-IssueishList-openReviewsButton'));

    wrapper.setProps({needReviewsButton: true});
    const child1 = wrapper.find('Accordion').renderProp('reviewsButton')();
    assert.isTrue(child1.exists('.github-IssueishList-openReviewsButton'));
    child1.find('.github-IssueishList-openReviewsButton').simulate('click', {stopPropagation() {}});
    assert.isTrue(openReviews.called);
  });
});
<|endoftext|>


<commit_before>'use strinct';
/**
 * Proposal of basic schema for projects and plugins collections.
 * @returns {*}
 */
UniCollection.getBasicSchema = function () {
    return {
        createdAt: {
            type: Date,
            autoValue: function () {
                if (this.isInsert) {
                    return this.value || new Date();
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        updatedAt: {
            type: Date,
            autoValue: function () {
                if (this.isUpdate) {
                    return new Date();
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        lastModifiedBy: {
            type: String,
            optional: true,
            autoValue: function () {
                if (this.isUpdate) {
                    return this.value || this.userId;
                }
            },
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        ownerId: {
            type: String,
            autoValue: function () {
                if (this.isInsert || this.isUpsert) {
                    return this.value || this.userId;
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        disabled: {
            type: Boolean,
            defaultValue: false,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        }

    };
};
<commit_msg>Fixes use strict;<commit_after>'use strict';
/**
 * Proposal of basic schema for projects and plugins collections.
 * @returns {*}
 */
UniCollection.getBasicSchema = function () {
    return {
        createdAt: {
            type: Date,
            autoValue: function () {
                if (this.isInsert) {
                    return this.value || new Date();
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        updatedAt: {
            type: Date,
            autoValue: function () {
                if (this.isUpdate) {
                    return new Date();
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        lastModifiedBy: {
            type: String,
            optional: true,
            autoValue: function () {
                if (this.isUpdate) {
                    return this.value || this.userId;
                }
            },
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        ownerId: {
            type: String,
            autoValue: function () {
                if (this.isInsert || this.isUpsert) {
                    return this.value || this.userId;
                }
            },
            optional: true,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        },
        disabled: {
            type: Boolean,
            defaultValue: false,
            uniUI: {
                component: 'none'
            },
            autoform: {
                omit: true
            }
        }

    };
};
<|endoftext|>


<commit_before>/**
 * Created by Domon on 17/4/18.
 */

class HuffNode {
  constructor(weight = 0, parent) {
    this.weight = weight
    this.parent = parent
    this.right = this.left = null
  }

  get path() {
    return this.parent ? this.parent.path + (this.parent.right === this ? '1' : '0') : ''
  }
}

export default class HuffCoder {
  constructor(defaultCode) {
    this._NYT = this._root = new HuffNode()
    this._dict = {}
    this.defaultCode = defaultCode || (c => {
        let code = Array.from({length: 8}, _ => 0).join('') + c.charCodeAt().toString(2)
        return code.substr(code.length - 8)
      })
  }

  encode(c) {
    if (this._dict[c]) {
      var code = this._dict[c].path
    } else {
      code = (this._NYT.path || '0') + this.defaultCode(c)
      this._dict[c] = this._NYT.right = new HuffNode(0, this._NYT)
      this._NYT = this._NYT.left = new HuffNode(0, this._NYT)
    }
    this._updateTree(c)
    return code
  }

  _updateTree(c) {            // increase weight and swap nodes
    for (let p = this._dict[c]; p; p.weight++, p = p.parent) {
      let leader = this._leaderOfWeight(p.weight)
      ![p, p.parent, undefined].includes(leader) && HuffCoder._swap(leader, p)
    }
  }

  _leaderOfWeight(w) {
    for (let q = [this._root], p; p = q.shift(); p.left && q.push(p.right, p.left)) {
      if (p.weight === w) return p
    }
  }

  static _swap(leader, p) {
    const temp = p.parent.right           // prevent p and leader are siblings
    leader.parent.right === leader ? leader.parent.right = p : leader.parent.left = p
    temp === p ? p.parent.right = leader : p.parent.left = leader
    leader.parent = [p.parent, p.parent = leader.parent][0]
  }
}
<commit_msg>shorter<commit_after>/**
 * Created by Domon on 17/4/18.
 */

class HuffNode {
  constructor(weight = 0, parent) {
    this.weight = weight
    this.parent = parent
    this.right = this.left = null
  }

  get path() {
    return this.parent ? this.parent.path + (this.parent.right === this ? '1' : '0') : ''
  }
}

export default class HuffCoder {
  constructor(defaultCode) {
    this._NYT = this._root = new HuffNode()
    this._dict = {}
    this.defaultCode = defaultCode || (c => {
        let code = Array.from({length: 8}, _ => 0).join('') + c.charCodeAt().toString(2)
        return code.substr(code.length - 8)
      })
  }

  encode(c) {
    if (this._dict[c]) var code = this._dict[c].path
    else {
      code = (this._NYT.path || '0') + this.defaultCode(c)
      this._dict[c] = this._NYT.right = new HuffNode(0, this._NYT)
      this._NYT = this._NYT.left = new HuffNode(0, this._NYT)
    }
    this._updateTree(c)
    return code
  }

  _updateTree(c) {            // increase weight and swap nodes
    for (let p = this._dict[c]; p; p.weight++, p = p.parent) {
      let leader = this._leaderOfWeight(p.weight)
      ![p, p.parent, undefined].includes(leader) && HuffCoder._swap(leader, p)
    }
  }

  _leaderOfWeight(w) {
    for (let q = [this._root], p; p = q.shift(); p.left && q.push(p.right, p.left)) {
      if (p.weight === w) return p
    }
  }

  static _swap(leader, p) {
    const temp = p.parent.right           // prevent p and leader are siblings
    leader.parent.right === leader ? leader.parent.right = p : leader.parent.left = p
    temp === p ? p.parent.right = leader : p.parent.left = leader
    leader.parent = [p.parent, p.parent = leader.parent][0]
  }
}
<|endoftext|>


<commit_before>(function() {
  if (Ember.OAuth2 == undefined) {
    Ember.OAuth2 = Ember.Object.extend({

      init: function() {
        this._super();
        this.providerConfig = Ember.OAuth2.config[this.providerId];
        this.setProperties(this.providerConfig);
      },

      uuid: function() {
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
              var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                  return v.toString(16);
        });
      },

      requestObj: function() {
        var request = { 'response_type': 'token' };
        request.providerId = this.providerId;
        request.state = this.state;
        request.client_id = this.clientId;
        request.state = this.state;
        if (this.scope) request.scope = this.scope;
        return request;
      },

      authUri: function() {
        if (this.state == null) this.state = this.uuid();
        var uri = this.authBaseUri;
        uri += '?response_type=token'
            + '&redirect_uri=' + encodeURIComponent(this.redirectUri)
            + '&client_id=' + encodeURIComponent(this.clientId)
            + '&state=' + encodeURIComponent(this.state);
        if (this.scope) uri += '&scope=' + encodeURIComponent(this.scope);
        return uri;
      },

      /*
       * Open authorize window if configuration is correct
       */
      authorize: function() {
        if (!this.providerId) throw new Error('No provider id given.');
        if (!this.clientId) throw new Error('No client id given.');
        if (!this.authBaseUri) throw new Error('No auth base uri given.');
        if (!this.redirectUri) throw new Error('No redirect uri given.');
        this.authorizeUri = this.authUri();
        this.saveState(this.state, this.requestObj());
        this.dialog = window.open(this.authorizeUri, 'Authorize', 'height=600, width=450');
        if (window.focus) this.dialog.focus();
      },

      authSuccess: function(params) {
        return params['access_token'];
      },

      createToken: function(stateObj) {
      },

      /*
       * call on redirect from OAuth2 provider response
       */
      onRedirect: function(hash) {
        var params = this.parseCallback(hash);
        if (this.authSuccess(params)) {
          stateObj = this.getState(params.state);
          this.checkState(stateObj);
          this.saveToken(this.generateToken(params));
          this.onSuccess(stateObj);
        } else {
          this.onError(params);
        }
      },

      /*
       * Check if the state returned from the OAuth2 server matches the saved state.
       */
      checkState: function(stateObj) {
        if (!stateObj) throw new Error("Could not find state.");
        if (stateObj.state != this.state) throw new Error("State returned from the server did not match the local saved state.");
      },

      /*
       * Parse the callback function from the OAuth2 provider
       *
       * callback should have the following params if authentication is successful
       * state
       * access_token
       * token_type
       * expires_in
       */
      parseCallback: function(locationHash) {
        var oauthParams = {}, queryString = locationHash.substring(1),
        regex = /([^#?&=]+)=([^&]*)/g, m;
        while (m = regex.exec(queryString)) {
          oauthParams[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
        }
        return oauthParams;
      },

      saveState: function(state, requestObj) {
        window.localStorage.setItem('state-' + this.state, JSON.stringify(requestObj));
      },

      /*
       * return the saved state and remove it from the localStoage.
       */
      getState: function(state) {
        var obj = JSON.parse(window.localStorage.getItem('state-' + state));
        window.localStorage.removeItem('state-' + state);
        return obj;
      },

      /*
       * saveToken stores the token by the provider
       * expires : time that the token expires
       * providerId: the providerId
       * scopes: array of scopes
       */
      saveToken: function(token) {
        window.localStorage.setItem('token-' + this.providerId, JSON.stringify(token));
      },

      getToken: function() {
        var token = window.localStorage.getItem('token-' + this.providerId);
        if (!token) return null;
        if (!token['accessToken']) return null;
        return token;
      },

      onSuccess: function(params) {},
      onError: function() {}
    });
  }

  Ember.OAuth2.config = {}

})(this);
<commit_msg>return the time<commit_after>(function() {
  if (Ember.OAuth2 == undefined) {
    Ember.OAuth2 = Ember.Object.extend({

      init: function() {
        this._super();
        this.providerConfig = Ember.OAuth2.config[this.providerId];
        this.setProperties(this.providerConfig);
      },

      uuid: function() {
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
              var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                  return v.toString(16);
        });
      },

      now: function() {
        return Math.round(new Date().getTime()/1000.0);
      },

      requestObj: function() {
        var request = { 'response_type': 'token' };
        request.providerId = this.providerId;
        request.state = this.state;
        request.client_id = this.clientId;
        request.state = this.state;
        if (this.scope) request.scope = this.scope;
        return request;
      },

      authUri: function() {
        if (this.state == null) this.state = this.uuid();
        var uri = this.authBaseUri;
        uri += '?response_type=token'
            + '&redirect_uri=' + encodeURIComponent(this.redirectUri)
            + '&client_id=' + encodeURIComponent(this.clientId)
            + '&state=' + encodeURIComponent(this.state);
        if (this.scope) uri += '&scope=' + encodeURIComponent(this.scope);
        return uri;
      },

      /*
       * Open authorize window if configuration is correct
       */
      authorize: function() {
        if (!this.providerId) throw new Error('No provider id given.');
        if (!this.clientId) throw new Error('No client id given.');
        if (!this.authBaseUri) throw new Error('No auth base uri given.');
        if (!this.redirectUri) throw new Error('No redirect uri given.');
        this.authorizeUri = this.authUri();
        this.saveState(this.state, this.requestObj());
        this.dialog = window.open(this.authorizeUri, 'Authorize', 'height=600, width=450');
        if (window.focus) this.dialog.focus();
      },

      authSuccess: function(params) {
        return params['access_token'];
      },

      createToken: function(stateObj) {
      },

      /*
       * call on redirect from OAuth2 provider response
       */
      onRedirect: function(hash) {
        var params = this.parseCallback(hash);
        if (this.authSuccess(params)) {
          stateObj = this.getState(params.state);
          this.checkState(stateObj);
          this.saveToken(this.generateToken(params));
          this.onSuccess(stateObj);
        } else {
          this.onError(params);
        }
      },

      /*
       * Check if the state returned from the OAuth2 server matches the saved state.
       */
      checkState: function(stateObj) {
        if (!stateObj) throw new Error("Could not find state.");
        if (stateObj.state != this.state) throw new Error("State returned from the server did not match the local saved state.");
      },

      /*
       * Parse the callback function from the OAuth2 provider
       *
       * callback should have the following params if authentication is successful
       * state
       * access_token
       * token_type
       * expires_in
       */
      parseCallback: function(locationHash) {
        var oauthParams = {}, queryString = locationHash.substring(1),
        regex = /([^#?&=]+)=([^&]*)/g, m;
        while (m = regex.exec(queryString)) {
          oauthParams[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
        }
        return oauthParams;
      },

      saveState: function(state, requestObj) {
        window.localStorage.setItem('state-' + this.state, JSON.stringify(requestObj));
      },

      /*
       * return the saved state and remove it from the localStoage.
       */
      getState: function(state) {
        var obj = JSON.parse(window.localStorage.getItem('state-' + state));
        window.localStorage.removeItem('state-' + state);
        return obj;
      },

      /*
       * saveToken stores the token by the provider
       * expires : time that the token expires
       * providerId: the providerId
       * scopes: array of scopes
       */
      saveToken: function(token) {
        window.localStorage.setItem('token-' + this.providerId, JSON.stringify(token));
      },

      getToken: function() {
        var token = window.localStorage.getItem('token-' + this.providerId);
        if (!token) return null;
        if (!token['accessToken']) return null;
        return token;
      },

      onSuccess: function(params) {},
      onError: function() {}
    });
  }

  Ember.OAuth2.config = {}

})(this);
<|endoftext|>


<commit_before>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    if (!r.call) {
      r.call = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        call_assigned_to:              (r.call.assigned_to || ""),
        call_fm_number:                (r.call.fm_number || ""),
        call_mail_sent:                (r.call.mail_sent  || false),
        call_email_sent:               (r.call.email_sent || false),
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        mail_call_name:                ((r.mail_call && r.mail_call.name) || ""),
        mail_call_phone:               ((r.mail_call && r.mail_call.address.phone) || ""),
        mail_call_email:               ((r.mail_call && r.mail_call.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<commit_msg>Add medical exam required to the flight export.<commit_after>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    if (!r.call) {
      r.call = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        call_assigned_to:              (r.call.assigned_to || ""),
        call_fm_number:                (r.call.fm_number || ""),
        call_mail_sent:                (r.call.mail_sent  || false),
        call_email_sent:               (r.call.email_sent || false),
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_exam_required:         (r.medical.examRequired || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        mail_call_name:                ((r.mail_call && r.mail_call.name) || ""),
        mail_call_phone:               ((r.mail_call && r.mail_call.address.phone) || ""),
        mail_call_email:               ((r.mail_call && r.mail_call.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<|endoftext|>


<commit_before>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    if (!r.homecoming) {
      r.homecoming = {};
    }

    if (!r.call) {
      r.call = {};
    }

    if (!r.alt_contact) {
      r.alt_contact = {};
    }

    if (!r.alt_contact.address) {
      r.alt_contact.address = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        call_assigned_to:              (r.call.assigned_to || ""),
        call_fm_number:                (r.call.fm_number || ""),
        call_mail_sent:                (r.call.mail_sent  || false),
        call_email_sent:               (r.call.email_sent || false),
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_nofly:                  (r.flight.nofly || false),
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_media_waiver:           (r.flight.mediaWaiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        media_newspaper_ok:            (r.media_newspaper_ok || ""),
        media_interview_ok:            (r.media_interview_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_alt_level:             (r.medical.alt_level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_exam_required:         (r.medical.examRequired || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        service_dates:                 ((r.service && r.service.dates) || ""),
        service_activity:              ((r.service && r.service.activity.replace("\"", "''")) || ""),
        mail_call_name:                ((r.mail_call && r.mail_call.name) || ""),
        mail_call_phone:               ((r.mail_call && r.mail_call.address.phone) || ""),
        mail_call_email:               ((r.mail_call && r.mail_call.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        homecoming_destination:        (r.homecoming.destination || ""),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        emerg_contact_name:            (r.emerg_contact.name || r.alt_contact.name || ""),
        emerg_contact_phone:           (r.emerg_contact.address.phone || r.emerg_contact.address.phone_eve || r.emerg_contact.address.phone_mbl || r.alt_contact.address.phone || r.alt_contact.address.phone_eve || r.alt_contact.address.phone_mbl || ""),
        emerg_contact_email:           (r.emerg_contact.address.email || r.alt_contact.address.email || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key].toString().trim());
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString().trim());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}
<commit_msg>Fix for empty service notes.<commit_after>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    if (!r.homecoming) {
      r.homecoming = {};
    }

    if (!r.call) {
      r.call = {};
    }

    if (!r.alt_contact) {
      r.alt_contact = {};
    }

    if (!r.alt_contact.address) {
      r.alt_contact.address = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        call_assigned_to:              (r.call.assigned_to || ""),
        call_fm_number:                (r.call.fm_number || ""),
        call_mail_sent:                (r.call.mail_sent  || false),
        call_email_sent:               (r.call.email_sent || false),
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_nofly:                  (r.flight.nofly || false),
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_media_waiver:           (r.flight.mediaWaiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        media_newspaper_ok:            (r.media_newspaper_ok || ""),
        media_interview_ok:            (r.media_interview_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_alt_level:             (r.medical.alt_level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_exam_required:         (r.medical.examRequired || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        service_dates:                 ((r.service && r.service.dates) || ""),
        service_activity:              ((r.service && r.service.activity && r.service.activity.replace("\"", "''".replace("\n", "|")).replace("\r", ";")) || ""),
        mail_call_name:                ((r.mail_call && r.mail_call.name) || ""),
        mail_call_phone:               ((r.mail_call && r.mail_call.address.phone) || ""),
        mail_call_email:               ((r.mail_call && r.mail_call.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        homecoming_destination:        (r.homecoming.destination || ""),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        emerg_contact_name:            (r.emerg_contact.name || r.alt_contact.name || ""),
        emerg_contact_phone:           (r.emerg_contact.address.phone || r.emerg_contact.address.phone_eve || r.emerg_contact.address.phone_mbl || r.alt_contact.address.phone || r.alt_contact.address.phone_eve || r.alt_contact.address.phone_mbl || ""),
        emerg_contact_email:           (r.emerg_contact.address.email || r.alt_contact.address.email || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key].toString().trim());
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString().trim());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}
<|endoftext|>


<commit_before>import { updateQueue } from './Component'
import * as _ from './util'

// event config
export const unbubbleEvents = {
    onmouseleave: 1,
    onmouseenter: 1,
    onload: 1,
    onunload: 1,
    onscroll: 1,
    onfocus: 1,
    onblur: 1,
    onrowexit: 1,
    onbeforeunload: 1,
    onstop: 1,
    ondragdrop: 1,
    ondragenter: 1,
    ondragexit: 1,
    ondraggesture: 1,
    ondragover: 1,
    oncontextmenu: 1
}

export function getEventName(key) {
    if (key === 'onDoubleClick') {
        key = 'ondblclick'
    } else if (key === 'onTouchTap') {
        key = 'onclick'
    }

    return key.toLowerCase()
}

// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
let inMobile = 'ontouchstart' in document
let emptyFunction = () => {}
let ON_CLICK_KEY = 'onclick'

let eventTypes = {}
export function addEvent(elem, eventType, listener) {
    eventType = getEventName(eventType)

    let eventStore = elem.eventStore || (elem.eventStore = {})
    eventStore[eventType] = listener

    if (unbubbleEvents[eventType] === 1) {
        elem[eventType] = dispatchUnbubbleEvent
        return
    } else if (!eventTypes[eventType]) {
        // onclick -> click
        document.addEventListener(eventType.substr(2), dispatchEvent, false)
        eventTypes[eventType] = true
    }

    if (inMobile && eventType === ON_CLICK_KEY) {
        elem.addEventListener('click', emptyFunction, false)
        return
    }

    let nodeName = elem.nodeName

    if (eventType === 'onchange' && (nodeName === 'INPUT' || nodeName === 'TEXTAREA')) {
        addEvent(elem, 'oninput', listener)
    }
}

export function removeEvent(elem, eventType) {
    eventType = getEventName(eventType)

    let eventStore = elem.eventStore || (elem.eventStore = {})
    delete eventStore[eventType]

    if (unbubbleEvents[eventType] === 1) {
        elem[eventType] = null
        return
    } else if (inMobile && eventType === ON_CLICK_KEY) {
        elem.removeEventListener('click', emptyFunction, false)
        return
    }

    let nodeName = elem.nodeName

    if (eventType === 'onchange' && (nodeName === 'INPUT' || nodeName === 'TEXTAREA')) {
        delete eventStore['oninput']
    }
}

function dispatchEvent(event) {
    let { target, type } = event
    let eventType = 'on' + type
    let syntheticEvent

    updateQueue.isPending = true
    while (target) {
        let { eventStore } = target
        let listener = eventStore && eventStore[eventType]
        if (!listener) {
            target = target.parentNode
            continue
        }
        if (!syntheticEvent) {
            syntheticEvent = createSyntheticEvent(event)
        }
        syntheticEvent.currentTarget = target
        listener.call(target, syntheticEvent)
        if (syntheticEvent.$cancalBubble) {
            break
        }
        target = target.parentNode
    }
    updateQueue.isPending = false
    updateQueue.batchUpdate()
}

function dispatchUnbubbleEvent(event) {
    let target = event.currentTarget || event.target
    let eventType = 'on' + event.type
    let syntheticEvent = createSyntheticEvent(event)

    syntheticEvent.currentTarget = target
    updateQueue.isPending = true

    let { eventStore } = target
    let listener = eventStore && eventStore[eventType]
    if (listener) {
    	listener.call(target, syntheticEvent)
    }

    updateQueue.isPending = false
    updateQueue.batchUpdate()
}

function createSyntheticEvent(nativeEvent) {
    let syntheticEvent = {}
    let cancalBubble = () => syntheticEvent.$cancalBubble = true
    syntheticEvent.nativeEvent = nativeEvent
    syntheticEvent.persist = _.noop
    for (let key in nativeEvent) {
        if (typeof nativeEvent[key] !== 'function') {
            syntheticEvent[key] = nativeEvent[key]
        } else if (key === 'stopPropagation' || key === 'stopImmediatePropagation') {
            syntheticEvent[key] = cancalBubble
        } else {
            syntheticEvent[key] = nativeEvent[key].bind(nativeEvent)
        }
    }
    return syntheticEvent
}
<commit_msg>Typo fix "cancal" =>"cancel"<commit_after>import { updateQueue } from './Component'
import * as _ from './util'

// event config
export const unbubbleEvents = {
    onmouseleave: 1,
    onmouseenter: 1,
    onload: 1,
    onunload: 1,
    onscroll: 1,
    onfocus: 1,
    onblur: 1,
    onrowexit: 1,
    onbeforeunload: 1,
    onstop: 1,
    ondragdrop: 1,
    ondragenter: 1,
    ondragexit: 1,
    ondraggesture: 1,
    ondragover: 1,
    oncontextmenu: 1
}

export function getEventName(key) {
    if (key === 'onDoubleClick') {
        key = 'ondblclick'
    } else if (key === 'onTouchTap') {
        key = 'onclick'
    }

    return key.toLowerCase()
}

// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
let inMobile = 'ontouchstart' in document
let emptyFunction = () => {}
let ON_CLICK_KEY = 'onclick'

let eventTypes = {}
export function addEvent(elem, eventType, listener) {
    eventType = getEventName(eventType)

    let eventStore = elem.eventStore || (elem.eventStore = {})
    eventStore[eventType] = listener

    if (unbubbleEvents[eventType] === 1) {
        elem[eventType] = dispatchUnbubbleEvent
        return
    } else if (!eventTypes[eventType]) {
        // onclick -> click
        document.addEventListener(eventType.substr(2), dispatchEvent, false)
        eventTypes[eventType] = true
    }

    if (inMobile && eventType === ON_CLICK_KEY) {
        elem.addEventListener('click', emptyFunction, false)
        return
    }

    let nodeName = elem.nodeName

    if (eventType === 'onchange' && (nodeName === 'INPUT' || nodeName === 'TEXTAREA')) {
        addEvent(elem, 'oninput', listener)
    }
}

export function removeEvent(elem, eventType) {
    eventType = getEventName(eventType)

    let eventStore = elem.eventStore || (elem.eventStore = {})
    delete eventStore[eventType]

    if (unbubbleEvents[eventType] === 1) {
        elem[eventType] = null
        return
    } else if (inMobile && eventType === ON_CLICK_KEY) {
        elem.removeEventListener('click', emptyFunction, false)
        return
    }

    let nodeName = elem.nodeName

    if (eventType === 'onchange' && (nodeName === 'INPUT' || nodeName === 'TEXTAREA')) {
        delete eventStore['oninput']
    }
}

function dispatchEvent(event) {
    let { target, type } = event
    let eventType = 'on' + type
    let syntheticEvent

    updateQueue.isPending = true
    while (target) {
        let { eventStore } = target
        let listener = eventStore && eventStore[eventType]
        if (!listener) {
            target = target.parentNode
            continue
        }
        if (!syntheticEvent) {
            syntheticEvent = createSyntheticEvent(event)
        }
        syntheticEvent.currentTarget = target
        listener.call(target, syntheticEvent)
        if (syntheticEvent.$cancelBubble) {
            break
        }
        target = target.parentNode
    }
    updateQueue.isPending = false
    updateQueue.batchUpdate()
}

function dispatchUnbubbleEvent(event) {
    let target = event.currentTarget || event.target
    let eventType = 'on' + event.type
    let syntheticEvent = createSyntheticEvent(event)

    syntheticEvent.currentTarget = target
    updateQueue.isPending = true

    let { eventStore } = target
    let listener = eventStore && eventStore[eventType]
    if (listener) {
    	listener.call(target, syntheticEvent)
    }

    updateQueue.isPending = false
    updateQueue.batchUpdate()
}

function createSyntheticEvent(nativeEvent) {
    let syntheticEvent = {}
    let cancelBubble = () => syntheticEvent.$cancelBubble = true
    syntheticEvent.nativeEvent = nativeEvent
    syntheticEvent.persist = _.noop
    for (let key in nativeEvent) {
        if (typeof nativeEvent[key] !== 'function') {
            syntheticEvent[key] = nativeEvent[key]
        } else if (key === 'stopPropagation' || key === 'stopImmediatePropagation') {
            syntheticEvent[key] = cancelBubble
        } else {
            syntheticEvent[key] = nativeEvent[key].bind(nativeEvent)
        }
    }
    return syntheticEvent
}
<|endoftext|>


<commit_before>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth_scrollbar';
import {
    getOriginalEvent,
    getPosition,
    getTouchID,
    pickInRange
} from '../utils/index';

export { SmoothScrollbar };

const EASING_DURATION = navigator.userAgent.match(/android/i) ? 1500 : 750;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
let __touchHandler = function() {
    const { container } = this.targets;

    let lastTouchTime, lastTouchID;
    let moveVelocity = {}, lastTouchPos = {}, touchRecords = {};

    let updateRecords = (evt) => {
        const touchList = getOriginalEvent(evt).touches;

        Object.keys(touchList).forEach((key) => {
            // record all touches that will be restored
            if (key === 'length') return;

            const touch = touchList[key];

            touchRecords[touch.identifier] = getPosition(touch);
        });
    };

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag) return;

        const { movement } = this;

        updateRecords(evt);

        lastTouchTime = Date.now();
        lastTouchID = getTouchID(evt);
        lastTouchPos = getPosition(evt);

        // stop scrolling
        movement.x = movement.y = 0;
        moveVelocity.x = moveVelocity.y = 0;
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (this.__ignoreEvent(evt) || this.__isDrag) return;

        updateRecords(evt);

        const touchID = getTouchID(evt);
        const { offset, limit } = this;

        if (lastTouchID === undefined) {
            // reset last touch info from records
            lastTouchID = touchID;

            // don't need error handler
            lastTouchTime = Date.now();
            lastTouchPos = touchRecords[touchID];
        } else if (touchID !== lastTouchID) {
            // prevent multi-touch bouncing
            return;
        }

        if (!lastTouchPos) return;

        let duration = Date.now() - lastTouchTime;
        let { x: lastX, y: lastY } = lastTouchPos;
        let { x: curX, y: curY } = lastTouchPos = getPosition(evt);

        duration = duration || 1; // fix Infinity error

        moveVelocity.x = (lastX - curX) / duration;
        moveVelocity.y = (lastY - curY) / duration;

        let destX = pickInRange(lastX - curX + offset.x, 0, limit.x);
        let destY = pickInRange(lastY - curY + offset.y, 0, limit.y);

        if (Math.abs(destX - offset.x) < 1 && Math.abs(destY - offset.y) < 1) {
            return this.__updateThrottle();
        }

        evt.preventDefault();

        this.setPosition(destX, destY);
    });

    this.__addEvent(container, 'touchend', (evt) => {
        if (this.__ignoreEvent(evt) || this.__isDrag) return;

        // release current touch
        delete touchRecords[lastTouchID];
        lastTouchID = undefined;

        let { x, y } = moveVelocity;

        this.__addMovement(x * EASING_DURATION, y * EASING_DURATION);

        moveVelocity.x = moveVelocity.y = 0;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true
});
<commit_msg>update(touch): update touch movement calc<commit_after>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth_scrollbar';
import {
    getOriginalEvent,
    getPosition,
    getTouchID,
    pickInRange
} from '../utils/index';

export { SmoothScrollbar };

const EASING_DURATION = navigator.userAgent.match(/android/i) ? 1500 : 750;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
let __touchHandler = function() {
    const { container } = this.targets;

    let lastTouchTime, lastTouchID;
    let moveVelocity = {}, lastTouchPos = {}, touchRecords = {};

    let updateRecords = (evt) => {
        const touchList = getOriginalEvent(evt).touches;

        Object.keys(touchList).forEach((key) => {
            // record all touches that will be restored
            if (key === 'length') return;

            const touch = touchList[key];

            touchRecords[touch.identifier] = getPosition(touch);
        });
    };

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag) return;

        const { movement } = this;

        updateRecords(evt);

        lastTouchTime = Date.now();
        lastTouchID = getTouchID(evt);
        lastTouchPos = getPosition(evt);

        // stop scrolling
        movement.x = movement.y = 0;
        moveVelocity.x = moveVelocity.y = 0;
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (this.__ignoreEvent(evt) || this.__isDrag) return;

        updateRecords(evt);

        const touchID = getTouchID(evt);
        const { offset, limit } = this;

        if (lastTouchID === undefined) {
            // reset last touch info from records
            lastTouchID = touchID;

            // don't need error handler
            lastTouchTime = Date.now();
            lastTouchPos = touchRecords[touchID];
        } else if (touchID !== lastTouchID) {
            // prevent multi-touch bouncing
            return;
        }

        if (!lastTouchPos) return;

        let duration = Date.now() - lastTouchTime;
        let { x: lastX, y: lastY } = lastTouchPos;
        let { x: curX, y: curY } = lastTouchPos = getPosition(evt);

        duration = duration || 1; // fix Infinity error

        moveVelocity.x = (lastX - curX) / duration;
        moveVelocity.y = (lastY - curY) / duration;

        let destX = pickInRange(lastX - curX + offset.x, 0, limit.x);
        let destY = pickInRange(lastY - curY + offset.y, 0, limit.y);

        if (Math.abs(destX - offset.x) < 1 && Math.abs(destY - offset.y) < 1) {
            return this.__updateThrottle();
        }

        evt.preventDefault();

        this.setPosition(destX, destY);
    });

    this.__addEvent(container, 'touchend', (evt) => {
        if (this.__ignoreEvent(evt) || this.__isDrag) return;

        // release current touch
        delete touchRecords[lastTouchID];
        lastTouchID = undefined;

        let { x, y } = moveVelocity;

        this.__setMovement(
            x ? x / Math.abs(x) * Math.sqrt(Math.abs(x) * 1e3) * 20 : 0,
            y ? y / Math.abs(y) * Math.sqrt(Math.abs(y) * 1e3) * 20 : 0
        );

        moveVelocity.x = moveVelocity.y = 0;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { I18n } from 'react-i18next';

class CheckForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      address: '',
      isLoading: false,
      validStatus: null,
      isDisabled: true,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const address = event.target.value;
    const isDisabled = address === '';

    this.setState({
      address,
      isDisabled,
    });
  }

  handleSubmit(event) {
    this.setState({
      validStatus: null,
    });

    if (this.state.address !== '') {
      this.setState({
        isLoading: true,
      });

      fetch(
        `${process.env.REACT_APP_API_URL}/users/${this.state.address.trim()}`,
      )
        .then(response => {
          return response.json();
        })
        .then(users => {
          this.setState({
            validStatus: users.length > 0,
            isLoading: false,
          });
        });
    }
    event.preventDefault();
  }

  renderMessage() {
    if (this.state.validStatus === true) {
      return (

          Your email has been verified, we'll keep you updated!{' '}

            😉

      );
    } else if (this.state.validStatus === false) {
      return (

            We're sorry, but unfortunately you did not make it to the first tier
            of our whitelist.{' '}

              😑

            To guarantee your spot, please ensure you complete the form below.

            Here!

      );
    } else {
      return;
    }
  }

  render() {
    let buttonClasses = 'button is-primary';

    if (this.state.isLoading) {
      buttonClasses += ' is-loading';
    }

    return (
      <I18n ns="translations">
        {(t, { i18n }) => (

Pre-Sale Check

                  <input
                    className="input"
                    type="text"
                    value={this.state.address}
                    placeholder="Enter your ETH address"
                    style={{ maxWidth: '30rem', textAlign: 'center' }}
                    onChange={this.handleChange}
                  />

                    Check

                {this.renderMessage()}

        )}
      </I18n>
    );
  }
}

export default CheckForm;
<commit_msg>Update check form sentence<commit_after>import React, { Component } from 'react';
import { I18n } from 'react-i18next';

class CheckForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      address: '',
      isLoading: false,
      validStatus: null,
      isDisabled: true,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const address = event.target.value;
    const isDisabled = address === '';

    this.setState({
      address,
      isDisabled,
    });
  }

  handleSubmit(event) {
    this.setState({
      validStatus: null,
    });

    if (this.state.address !== '') {
      this.setState({
        isLoading: true,
      });

      fetch(
        `${process.env.REACT_APP_API_URL}/users/${this.state.address.trim()}`,
      )
        .then(response => {
          return response.json();
        })
        .then(users => {
          this.setState({
            validStatus: users.length > 0,
            isLoading: false,
          });
        });
    }
    event.preventDefault();
  }

  renderMessage() {
    if (this.state.validStatus === true) {
      return (

          Your are on the whitelist!

          Please read
          this guide
           to learn how buy ELTCOINs.

      );
    } else if (this.state.validStatus === false) {
      return (

            We're sorry, but unfortunately you did not make it to the first tier
            of our whitelist.{' '}

              😑

            To guarantee your spot, please ensure you complete the form below.

            Here!

      );
    } else {
      return;
    }
  }

  render() {
    let buttonClasses = 'button is-primary';

    if (this.state.isLoading) {
      buttonClasses += ' is-loading';
    }

    return (
      <I18n ns="translations">
        {(t, { i18n }) => (

Pre-Sale Check

                  <input
                    className="input"
                    type="text"
                    value={this.state.address}
                    placeholder="Enter your ETH address"
                    style={{ maxWidth: '30rem', textAlign: 'center' }}
                    onChange={this.handleChange}
                  />

                    Check

                {this.renderMessage()}

        )}
      </I18n>
    );
  }
}

export default CheckForm;
<|endoftext|>


<commit_before>const React = require('react');
import { connect } from 'react-redux';
import { createChart } from '../helpers/backendInterface';

const inputBox = function(props) {
  return (

      {props.msg}:
      <input ref={props.ref} type="text"></input>

  )
}

class createPollsPage extends React.Component{
  constructor(props){
    super(props);
    this.sendForChartCreation = this.sendForChartCreation.bind(this);
  }

  sendForChartCreation(){
    createChart(this.props.token, {
        title: this.title.value,
        desc:  this.desc.value,
        points: {
          pepsi: this.point1.value,
          coke: 0
        }
      },
      function(data){
        console.log('data I received: ' + data);
    });
  }

  render() {
    return (

        {inputBox({ref: node=>{this.title = node}, msg: 'Title'})}
        {inputBox({ref: node=>{this.desc = node}, msg: 'Description'})}
        {inputBox({ref: node=>{this.point1 = node}, msg: 'Point 1'})}
        {inputBox({msg: 'Point 2'})}
        {inputBox({msg: 'Point 3'})}
        {inputBox({msg: 'Point 4'})}
        {inputBox({msg: 'Point 5'})}
        {inputBox({msg: 'Point 6'})}
        {inputBox({msg: 'Point 7'})}
        {inputBox({msg: 'Point 8'})}
        {inputBox({msg: 'Point 9'})}
        {inputBox({msg: 'Point 10'})}
        <button onClick={this.sendForChartCreation}>Create Poll</button>

          {this.props.token}

    );
  }
}

createPollsPage.propTypes = {
  loggedIn: React.PropTypes.bool,
  updateLogInStatus: React.PropTypes.func
};
const mapStateToProps = (state) => {
  return {
    token: state.login.token
  }
}

export default connect(mapStateToProps)(createPollsPage);
<commit_msg>can send chart data to create chart in services<commit_after>const React = require('react');
import { connect } from 'react-redux';
import { createChart } from '../helpers/backendInterface';

const inputBox = function(props) {
  return (

      {props.msg}:
      <input ref={props.ref} type="text"></input>

  )
}

class createPollsPage extends React.Component{
  constructor(props){
    super(props);
    this.sendForChartCreation = this.sendForChartCreation.bind(this);
  }

  sendForChartCreation(){
    const points = this.point.reduce((p, x)=>{
      return (x.value) ? Object.assign({}, p, {[x.value]: 0}) : p;
    }, {});
    createChart(this.props.token, {
        title: this.title.value,
        desc:  this.desc.value,
        points
      },
      function(data){
        console.log('data I received: ' + data);
    });
  }

  render() {
    this.point = [];
    return (

        {inputBox({ref: node=>{this.title = node}, msg: 'Title'})}
        {inputBox({ref: node=>{this.desc = node}, msg: 'Description'})}
        {inputBox({ref: node=>{this.point[0] = node}, msg: 'Point 0'})}
        {inputBox({ref: node=>{this.point[1] = node}, msg: 'Point 1'})}
        {inputBox({ref: node=>{this.point[2] = node}, msg: 'Point 2'})}
        {inputBox({ref: node=>{this.point[3] = node}, msg: 'Point 3'})}
        {inputBox({ref: node=>{this.point[4] = node}, msg: 'Point 4'})}
        {inputBox({ref: node=>{this.point[5] = node}, msg: 'Point 5'})}
        {inputBox({ref: node=>{this.point[6] = node}, msg: 'Point 6'})}
        {inputBox({ref: node=>{this.point[7] = node}, msg: 'Point 7'})}
        <button onClick={this.sendForChartCreation}>Create Poll</button>

          {this.props.token}

    );
  }
}

createPollsPage.propTypes = {
  loggedIn: React.PropTypes.bool,
  updateLogInStatus: React.PropTypes.func
};
const mapStateToProps = (state) => {
  return {
    token: state.login.token
  }
}

export default connect(mapStateToProps)(createPollsPage);
<|endoftext|>


<commit_before>import React from 'react';
import remote from 'remote';
import Dropzone from 'react-dropzone';
import {
    RaisedButton
}
from 'material-ui';

import utils from '../utils/util';
import ModalActions from './Modal/actions';

export
default React.createClass({
    addSource(source) {
        switch (source) {
            case 'url':
                ModalActions.open({
                    title: 'Add URL',
                    type: 'URLAdd'
                });
                break;
            case 'local-video':
                var filters = [{
                    name: 'Video Files',
                    extensions: ['MP4', 'MKV', 'MOV', 'AVI', 'WMV', 'WMA', 'ASF', '3GP', 'OGM', 'OGG', 'WAV', 'Real']
                }];
            case 'local-torrent':
                remote.require('dialog')
                    .showOpenDialog({
                        title: 'Select file',
                        properties: ['openFile', 'createDirectory'],
                        filters: filters ? filters : [{
                            name: 'Torrents',
                            extensions: ['TORRENT', 'MAGNET']
                        }]
                    }, (filename) => {
                        console.log(filename)
                    });
        }
    },
    onDrop(file) {
        console.log('Received file:', file);
    },
    render() {
        return (

                    <Dropzone className="holder" onDrop={this.onDrop}>

                        Drag & Drop a File

                        or select an option below

                            <RaisedButton style={{float: 'left', width: '130px'}} onClick={this.addSource.bind(this, 'local-torrent')} label="Add Torrent" />
                            <RaisedButton style={{width: '130px'}} onClick={this.addSource.bind(this, 'local-video')} label="Add Video" />
                            <RaisedButton style={{float: 'right', width: '130px'}} onClick={this.addSource.bind(this, 'url')} label="Use a URL" />

                    </Dropzone>

        );
    }
});<commit_msg>remove dropzone for now<commit_after>import React from 'react';
import remote from 'remote';
import Dropzone from 'react-dropzone';
import {
    RaisedButton
}
from 'material-ui';

import utils from '../utils/util';
import ModalActions from './Modal/actions';

export
default React.createClass({
    addSource(source) {
        switch (source) {
            case 'url':
                ModalActions.open({
                    title: 'Add URL',
                    type: 'URLAdd'
                });
                break;
            case 'local-video':
                var filters = [{
                    name: 'Video Files',
                    extensions: ['MP4', 'MKV', 'MOV', 'AVI', 'WMV', 'WMA', 'ASF', '3GP', 'OGM', 'OGG', 'WAV', 'Real']
                }];
            case 'local-torrent':
                remote.require('dialog')
                    .showOpenDialog({
                        title: 'Select file',
                        properties: ['openFile', 'createDirectory'],
                        filters: filters ? filters : [{
                            name: 'Torrents',
                            extensions: ['TORRENT', 'MAGNET']
                        }]
                    }, (filename) => {
                        console.log(filename)
                    });
        }
    },
    onDrop(file) {
        console.log('Received file:', file);
    },
    render() {
        return (

                        Drag & Drop a File

                        or select an option below

                            <RaisedButton style={{float: 'left', width: '130px'}} onClick={this.addSource.bind(this, 'local-torrent')} label="Add Torrent" />
                            <RaisedButton style={{width: '130px'}} onClick={this.addSource.bind(this, 'local-video')} label="Add Video" />
                            <RaisedButton style={{float: 'right', width: '130px'}} onClick={this.addSource.bind(this, 'url')} label="Use a URL" />

        );
    }
});<|endoftext|>