<commit_before>import _ from 'lodash';
import React, { PropTypes } from 'react'; // eslint-disable-line
import {Row, Col, Dropdown} from 'react-bootstrap'; // eslint-disable-line
import DropdownMenu from '@folio/stripes-components/lib/DropdownMenu'; // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button'; // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon'; // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField'; // eslint-disable-line
import List from '@folio/stripes-components/lib/List'; // eslint-disable-line
import ListDropdown from './lib/ListDropdown'; // eslint-disable-line
import css from './UserPermissions.css'; // eslint-disable-line

const propTypes = {
  availablePermissions: PropTypes.arrayOf(PropTypes.object),
  usersPermissions: PropTypes.arrayOf(PropTypes.object),
  viewUserProps: PropTypes.shape({
    mutator: PropTypes.shape({
      usersPermissions: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired,
      }),
    }),
  }),
};

class UserPermissions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      addPermissionOpen: false,
      searchTerm: '',
      // handling active Permissions in state for presentation purposes only.
    };

    this.onToggleAddPermDD = this.onToggleAddPermDD.bind(this);
    this.addPermission = this.addPermission.bind(this);
    this.onChangeSearch = this.onChangeSearch.bind(this);
  }

  onToggleAddPermDD() {
    const isOpen = this.state.addPermissionOpen;
    this.setState({
      addPermissionOpen: !isOpen,
    });
  }

  onChangeSearch(e) {
    const searchTerm = e.target.value;
    this.setState({ searchTerm });
  }

  addPermission(perm) {
    this.props.viewUserProps.mutator.usersPermissions.POST(perm, this.props.viewUserProps).then(() => {
      this.onToggleAddPermDD();
    });
  }

  removePermission(perm) {
    this.props.viewUserProps.mutator.usersPermissions.DELETE(perm, this.props.viewUserProps, perm.permissionName);
  }

  render() {
    const { usersPermissions } = this.props;

    const permissionsDD = (
      <ListDropdown
        items={_.filter(this.props.availablePermissions, function(perm) {
          const permInUse = _.some(usersPermissions, perm);

          // This should be replaced with proper search when possible.
          const permNotFiltered = _.includes(perm.permissionName.toLowerCase(), this.state.searchTerm.toLowerCase());

          return !permInUse && permNotFiltered;
        }.bind(this))}
        onClickItem={this.addPermission}
        onChangeSearch={this.onChangeSearch}
      />
    );

    const listFormatter = item => (

        {item.permissionName}
        <Button
          buttonStyle="fieldControl"
          align="end"
          type="button"
          onClick={() => this.removePermission(item)}
          aria-label={`Remove Permission: ${item.permissionName}`}
          title="Remove Permission"
        >
          <Icon icon="hollowX" iconClassName={css.removePermissionIcon} iconRootClass={css.removePermissionButton} />
        </Button>

    );

    return (

        <Row>
          <Col xs={5}>

User permissions

          </Col>
          {/* <Col xs={4} sm={3}>
            <TextField
              rounded
              endControl={<Button buttonStyle="fieldControl"><Icon icon='clearX'/></Button>}
              startControl={<Icon icon='search'/>}
              placeholder="Search"
              fullWidth
              />
          </Col>*/}
          <Col xs={7}>
            <Dropdown open={this.state.addPermissionOpen} pullRight onToggle={this.onToggleAddPermDD} id="AddPermissionDropdown" style={{ float: 'right' }}>
              <Button align="end" bottomMargin0 bsRole="toggle" aria-haspopup="true">+ Add Permission</Button>
              <DropdownMenu bsRole="menu" onToggle={this.onToggleAddPermDD} aria-label="available permissions">{permissionsDD}</DropdownMenu>
            </Dropdown>
          </Col>
        </Row>
        <List itemFormatter={listFormatter} items={usersPermissions} isEmptyMessage="This user has no permissions applied." />

    );
  }
}

UserPermissions.propTypes = propTypes;

export default UserPermissions;
<commit_msg>Invocation of <List> is robust against usersPermissions being null. Fixes STRIPES-228.<commit_after>import _ from 'lodash';
import React, { PropTypes } from 'react'; // eslint-disable-line
import {Row, Col, Dropdown} from 'react-bootstrap'; // eslint-disable-line
import DropdownMenu from '@folio/stripes-components/lib/DropdownMenu'; // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button'; // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon'; // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField'; // eslint-disable-line
import List from '@folio/stripes-components/lib/List'; // eslint-disable-line
import ListDropdown from './lib/ListDropdown'; // eslint-disable-line
import css from './UserPermissions.css'; // eslint-disable-line

const propTypes = {
  availablePermissions: PropTypes.arrayOf(PropTypes.object),
  usersPermissions: PropTypes.arrayOf(PropTypes.object),
  viewUserProps: PropTypes.shape({
    mutator: PropTypes.shape({
      usersPermissions: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired,
      }),
    }),
  }),
};

class UserPermissions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      addPermissionOpen: false,
      searchTerm: '',
      // handling active Permissions in state for presentation purposes only.
    };

    this.onToggleAddPermDD = this.onToggleAddPermDD.bind(this);
    this.addPermission = this.addPermission.bind(this);
    this.onChangeSearch = this.onChangeSearch.bind(this);
  }

  onToggleAddPermDD() {
    const isOpen = this.state.addPermissionOpen;
    this.setState({
      addPermissionOpen: !isOpen,
    });
  }

  onChangeSearch(e) {
    const searchTerm = e.target.value;
    this.setState({ searchTerm });
  }

  addPermission(perm) {
    this.props.viewUserProps.mutator.usersPermissions.POST(perm, this.props.viewUserProps).then(() => {
      this.onToggleAddPermDD();
    });
  }

  removePermission(perm) {
    this.props.viewUserProps.mutator.usersPermissions.DELETE(perm, this.props.viewUserProps, perm.permissionName);
  }

  render() {
    const { usersPermissions } = this.props;

    const permissionsDD = (
      <ListDropdown
        items={_.filter(this.props.availablePermissions, function(perm) {
          const permInUse = _.some(usersPermissions, perm);

          // This should be replaced with proper search when possible.
          const permNotFiltered = _.includes(perm.permissionName.toLowerCase(), this.state.searchTerm.toLowerCase());

          return !permInUse && permNotFiltered;
        }.bind(this))}
        onClickItem={this.addPermission}
        onChangeSearch={this.onChangeSearch}
      />
    );

    const listFormatter = item => (

        {item.permissionName}
        <Button
          buttonStyle="fieldControl"
          align="end"
          type="button"
          onClick={() => this.removePermission(item)}
          aria-label={`Remove Permission: ${item.permissionName}`}
          title="Remove Permission"
        >
          <Icon icon="hollowX" iconClassName={css.removePermissionIcon} iconRootClass={css.removePermissionButton} />
        </Button>

    );

    return (

        <Row>
          <Col xs={5}>

User permissions

          </Col>
          {/* <Col xs={4} sm={3}>
            <TextField
              rounded
              endControl={<Button buttonStyle="fieldControl"><Icon icon='clearX'/></Button>}
              startControl={<Icon icon='search'/>}
              placeholder="Search"
              fullWidth
              />
          </Col>*/}
          <Col xs={7}>
            <Dropdown open={this.state.addPermissionOpen} pullRight onToggle={this.onToggleAddPermDD} id="AddPermissionDropdown" style={{ float: 'right' }}>
              <Button align="end" bottomMargin0 bsRole="toggle" aria-haspopup="true">+ Add Permission</Button>
              <DropdownMenu bsRole="menu" onToggle={this.onToggleAddPermDD} aria-label="available permissions">{permissionsDD}</DropdownMenu>
            </Dropdown>
          </Col>
        </Row>
        <List itemFormatter={listFormatter} items={usersPermissions || []} isEmptyMessage="This user has no permissions applied." />

    );
  }
}

UserPermissions.propTypes = propTypes;

export default UserPermissions;
<|endoftext|>


<commit_before>var ask = require('../index');

ask('busi.vip.kankan.com', '/userinfo/getUserInfo', {
		method: 'GET',
		query: {
			respType: 'json'
		},
		headers: {
			'Cookie': {
				userid: '123455'
			}
		},
		timeout: 1000
	})
	.then(function(data) {
		console.log(data);
		return ask('svr.act.vip.kankan.com', '/giftService/saveUserAddress', {
			method: 'POST',
			query: {
				respType: 'json'
			},
			timeout: 1000
		}, {
			address: 'fafasfaa'
		});
	})
	.then(function(data) {
		console.log(data);
		return Promise.resolve('Bingo');
	})
	.then(function(data) {
		console.log(data);
	});
// var p = new Promise(function(resolve, reject) {
// 	ask.get('busi.vip.kankan.com', '/userinfo/getUserInfo', {
// 		query: {
// 			respType: 'json'
// 		},
// 		headers: {
// 			'Cookie': {
// 				userid: '123455'
// 			}
// 		},
// 		timeout: 1000
// 	}, function(err, res) {
// 		err && console.log(err);
// 		res && res.data && (res.data = JSON.parse(res.data));
// 		res && resolve(res.data);
// 	});
// });

// p.then(function(val){
// 	// console.log(val);
// 	ask.post('svr.act.vip.kankan.com', '/giftService/saveUserAddress', {
// 		query: {
// 			respType: 'json'
// 		},
// 		timeout: 1000
// 	},{
// 		address: 'fasdfadsfa'
// 	}, function(err, res) {
// 		err && console.log(err);
// 		res && res.data && (res.data = JSON.parse(res.data));
// 		res && console.log(res.data);
// 		return res.data;
// 	});
// }, function() {})
// .then(function(val) {
// 	console.log(val);
// }, function() {});<commit_msg>change the test case<commit_after>var request = require('../index');

request({
		host: 'google.com',
		method: 'GET',
		path: '/search',
		query: {
			q: 'nodejs'
		},
		headers: {
			'x-foo-bar' : "Hello World"
		},
		timeout: 3000
	})
	.then(function(data) {
		console.log(data);
		return Promise.resolve('Bingo');
	}, function(err) {
		console.log(err);
		return Promise.reject('Oh no!');
	})
	.then(function(data) {
		console.log(data);
	}, function(err) {
		console.log(err);
	});

<|endoftext|>


<commit_before>describe('Kit library', function () {
    var should = require('chai').should(),
        expect = require('chai').expect,
        _ = require('../src/kit.js');

    describe('#merge()', function () {
        it('Should merge multiple objects to one', function () {
            var merged = _.merge(
                { a: 'a', b: 'b', c: ['a', 'b', 'c'] },
                { a: { a: 'a', b: 'b', c: ['a', 'b', 'c'] }, d: 'd'},
                { b: { a: { a: 'a', b: 'b', c: ['a', 'b', 'c'] } } },
                { b: { a: { a: 'a', e: 'e', c: ['c', 'a', 'b'] } } }
            );

            merged.should.deep.equal({
                a: { a: 'a', b: 'b', c: [ 'a', 'b', 'c' ] },
                b: { a: { a: 'a', b: 'b', c: ['c', 'a', 'b'], e: 'e' } },
                c: [ 'a', 'b', 'c' ],
                d: 'd'
            });
        });

        it('Should return empty object if no object is added', function () {
            var merged = _.merge();

            merged.should.deep.equal({});
        });
    });

    describe('#each()', function () {
        it('Should loop through array passed', function () {
            var a = ['a', 'b', 'c'];

            _.each(a, function (item) {
                if (item === 'a') {
                    item.should.equal(a[0]);
                } else if (item === 'b') {
                    item.should.equal(a[1]);
                } else if (item === 'c') {
                    item.should.equal(a[2]);
                }
            });
        });

    });

    describe('#first()', function () {
        it('Should return first element of passed array', function () {
            var a = ['a', 'b', 'c', 'd'],
                first = _.first(a);

            first.should.equal(a[0]);
        });

        it('Should return null if empty array is passed', function () {
            var first = _.first([]);

            expect(first).to.be.null;
        });

        it('Should return null if no array is passed', function () {
            var first = _.first();

            expect(first).to.be.null;
        });
    });

    describe('#last()', function () {
        it('Should return last element of passed array', function () {
            var a = ['a', 'b', 'c', 'd'],
                last = _.last(a);

            last.should.equal(a[3]);
        });

        it('Should return null if empty array is passed', function () {
            var last = _.last([]);

            expect(last).to.be.null;
        });

        it('Should return null if no array is passed', function () {
            var last = _.last();

            expect(last).to.be.null;
        });
    });

    describe('#remove()', function () {
        it('Should remove element passed from an array', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a, 'b');

            removed.should.deep.equal(['a', 'c', 'd']);
        });

        it('Should remove elements passed from an array', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a, 'b', 'c');

            removed.should.deep.equal(['a', 'd']);
        });

        it('Should return array passed if no elements added', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a);

            removed.should.deep.equal(['a', 'b', 'c', 'd']);
        });
    });

    describe('#unique()', function () {
        it('Should return an unique array', function () {
            var a = ['a', 'b', 'c', 'd', 'b'],
                unique = _.unique(a);

            unique.should.deep.equal(['a', 'b', 'c', 'd']);
        });

        it('Should return null if no array is passed', function () {
            var unique = _.unique();

            expect(unique).to.be.null;
        });

        it('Should return null if empty array is passed', function () {
            var unique = _.unique([]);

            expect(unique).to.be.null;
        });
    });

    describe('#isObject()', function () {
        it('Should return true if object is passed', function () {
            expect(_.isObject({})).to.be.true;
        });

        it('Should return false if no object is passed', function () {
            expect(_.isObject('')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isObject()).to.be.false;
        });
    });

    describe('#isFunction()', function () {
        it('Should return true if function is passed', function () {
            expect(_.isFunction(function () {})).to.be.true;
            expect(_.isFunction(new Function())).to.be.true;
        });

        it('Should return false if no function is passed', function () {
            expect(_.isFunction({})).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isFunction()).to.be.false;
        });
    });

    describe('#isUndefined()', function () {
        it('Should return true if undefined is passed', function () {
            expect(_.isUndefined(undefined)).to.be.true;
            expect(_.isUndefined(void 0)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isUndefined({})).to.be.false;
        });

        it('Should return true if nothing is passed (undefined)', function () {
            expect(_.isUndefined()).to.be.true;
        });
    });

    describe('#isNull()', function () {
        it('Should return true if null is passed', function () {
            expect(_.isNull(null)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isNull('string')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isNull()).to.be.false;
        });
    });

    describe('#isArray()', function () {
        it('Should return true if an array is passed', function () {
            expect(_.isArray([])).to.be.true;
            expect(_.isArray(new Array())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isArray('string')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isArray()).to.be.false;
        });
    });

    describe('#isDate()', function () {
        it('Should return true if a date is passed', function () {
            expect(_.isDate(new Date())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isDate([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isDate()).to.be.false;
        });
    });

    describe('#isRegExp()', function () {
        it('Should return true if a regex is passed', function () {
            expect(_.isRegExp(new RegExp())).to.be.true;
            expect(_.isRegExp(/a-z/)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isRegExp([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isRegExp()).to.be.false;
        });
    });

    describe('#isString()', function () {
        it('Should return true if a string is passed', function () {
            expect(_.isString('I AM STRING')).to.be.true;
            expect(_.isString(new String())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isString([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isString()).to.be.false;
        });
    });

    describe('#isNumber()', function () {
        it('Should return true if a number is passed', function () {
            expect(_.isNumber(213123.23123)).to.be.true;
            expect(_.isNumber(new Number())).to.be.true;
            expect(_.isNumber(2)).to.be.true;
            expect(_.isNumber(0)).to.be.true;
            expect(_.isNumber(-2)).to.be.true;
            expect(_.isNumber(-2.2)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isNumber([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isNumber()).to.be.false;
        });
    });

    describe('#isInteger()', function () {
        it('Should return true if an integer is passed', function () {
            expect(_.isInteger(2)).to.be.true;
            expect(_.isInteger(0)).to.be.true;
            expect(_.isInteger(10.0)).to.be.true;
            expect(_.isInteger(-2)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isInteger([])).to.be.false;
        });

        it('Should return false if float element is passed', function () {
            expect(_.isInteger(2.2)).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isInteger()).to.be.false;
        });
    });

    describe('#isFloat()', function () {
        it('Should return true if a float number is passed', function () {
            expect(_.isFloat(2.1)).to.be.true;
            expect(_.isFloat(-2.01)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isFloat([])).to.be.false;
        });

        it('Should return false if integer element is passed', function () {
            expect(_.isFloat(2)).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isFloat()).to.be.false;
        });
    });

    describe('#isGlobal()', function () {
        it('Should return true if a global object is passed', function () {
            expect(_.isGlobal(global)).to.be.true;
        });

        it('Should return false if another object or element is passed', function () {
            expect(_.isGlobal({})).to.be.false;
            expect(_.isGlobal(function () {})).to.be.false;
        });
    });
});
<commit_msg>updated tests<commit_after>describe('Kit library', function () {
    var should = require('chai').should(),
        expect = require('chai').expect,
        _ = require('../src/kit.js');

    describe('#merge()', function () {
        it('Should merge multiple objects to one', function () {
            var merged = _.merge(
                { a: 'a', b: 'b', c: ['a', 'b', 'c'] },
                { a: { a: 'a', b: 'b', c: ['a', 'b', 'c'] }, d: 'd'},
                { b: { a: { a: 'a', b: 'b', c: ['a', 'b', 'c'] } } },
                { b: { a: { a: 'a', e: 'e', c: ['c', 'a', 'b'] } } }
            );

            merged.should.deep.equal({
                a: { a: 'a', b: 'b', c: [ 'a', 'b', 'c' ] },
                b: { a: { a: 'a', b: 'b', c: ['c', 'a', 'b'], e: 'e' } },
                c: [ 'a', 'b', 'c' ],
                d: 'd'
            });
        });

        it('Should return empty object if no object is added', function () {
            var merged = _.merge();

            merged.should.deep.equal({});
        });
    });

    describe('#each()', function () {
        it('Should loop through array passed', function () {
            var a = ['a', 'b', 'c'];

            _.each(a, function (item) {
                if (item === 'a') {
                    item.should.equal(a[0]);
                } else if (item === 'b') {
                    item.should.equal(a[1]);
                } else if (item === 'c') {
                    item.should.equal(a[2]);
                }
            });
        });
    });

    describe('#first()', function () {
        it('Should return first element of passed array', function () {
            var a = ['a', 'b', 'c', 'd'],
                first = _.first(a);

            first.should.equal(a[0]);
        });

        it('Should return null if empty array is passed', function () {
            var first = _.first([]);

            expect(first).to.be.null;
        });

        it('Should return null if no array is passed', function () {
            var first = _.first();

            expect(first).to.be.null;
        });
    });

    describe('#last()', function () {
        it('Should return last element of passed array', function () {
            var a = ['a', 'b', 'c', 'd'],
                last = _.last(a);

            last.should.equal(a[3]);
        });

        it('Should return null if empty array is passed', function () {
            var last = _.last([]);

            expect(last).to.be.null;
        });

        it('Should return null if no array is passed', function () {
            var last = _.last();

            expect(last).to.be.null;
        });
    });

    describe('#remove()', function () {
        it('Should remove element passed from an array', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a, 'b');

            removed.should.deep.equal(['a', 'c', 'd']);
        });

        it('Should remove all elements passed from an array', function () {
            var a = ['a', 'b', 'c', 'd', 'a', 'a'],
            removed = _.remove(a, true, 'a');

            removed.should.deep.equal(['b', 'c', 'd']);
        });

        it('Should remove elements passed from an array', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a, 'b', 'c');

            removed.should.deep.equal(['a', 'd']);
        });

        it('Should return array passed if no elements added', function () {
            var a = ['a', 'b', 'c', 'd'],
                removed = _.remove(a);

            removed.should.deep.equal(['a', 'b', 'c', 'd']);
        });
    });

    describe('#unique()', function () {
        it('Should return an unique array', function () {
            var a = ['a', 'b', 'c', 'd', 'b'],
                unique = _.unique(a);

            unique.should.deep.equal(['b', 'd', 'c', 'a']);
        });

        it('Should return null if no array is passed', function () {
            var unique = _.unique();

            expect(unique).to.be.null;
        });

        it('Should return null if empty array is passed', function () {
            var unique = _.unique([]);

            expect(unique).to.be.null;
        });
    });

    describe('#isObject()', function () {
        it('Should return true if object is passed', function () {
            expect(_.isObject({})).to.be.true;
        });

        it('Should return false if no object is passed', function () {
            expect(_.isObject('')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isObject()).to.be.false;
        });
    });

    describe('#isFunction()', function () {
        it('Should return true if function is passed', function () {
            expect(_.isFunction(function () {})).to.be.true;
            expect(_.isFunction(new Function())).to.be.true;
        });

        it('Should return false if no function is passed', function () {
            expect(_.isFunction({})).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isFunction()).to.be.false;
        });
    });

    describe('#isUndefined()', function () {
        it('Should return true if undefined is passed', function () {
            expect(_.isUndefined(undefined)).to.be.true;
            expect(_.isUndefined(void 0)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isUndefined({})).to.be.false;
        });

        it('Should return true if nothing is passed (undefined)', function () {
            expect(_.isUndefined()).to.be.true;
        });
    });

    describe('#isNull()', function () {
        it('Should return true if null is passed', function () {
            expect(_.isNull(null)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isNull('string')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isNull()).to.be.false;
        });
    });

    describe('#isArray()', function () {
        it('Should return true if an array is passed', function () {
            expect(_.isArray([])).to.be.true;
            expect(_.isArray(new Array())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isArray('string')).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isArray()).to.be.false;
        });
    });

    describe('#isDate()', function () {
        it('Should return true if a date is passed', function () {
            expect(_.isDate(new Date())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isDate([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isDate()).to.be.false;
        });
    });

    describe('#isRegExp()', function () {
        it('Should return true if a regex is passed', function () {
            expect(_.isRegExp(new RegExp())).to.be.true;
            expect(_.isRegExp(/a-z/)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isRegExp([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isRegExp()).to.be.false;
        });
    });

    describe('#isString()', function () {
        it('Should return true if a string is passed', function () {
            expect(_.isString('I AM STRING')).to.be.true;
            expect(_.isString(new String())).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isString([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isString()).to.be.false;
        });
    });

    describe('#isNumber()', function () {
        it('Should return true if a number is passed', function () {
            expect(_.isNumber(213123.23123)).to.be.true;
            expect(_.isNumber(new Number())).to.be.true;
            expect(_.isNumber(2)).to.be.true;
            expect(_.isNumber(0)).to.be.true;
            expect(_.isNumber(-2)).to.be.true;
            expect(_.isNumber(-2.2)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isNumber([])).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isNumber()).to.be.false;
        });
    });

    describe('#isInteger()', function () {
        it('Should return true if an integer is passed', function () {
            expect(_.isInteger(2)).to.be.true;
            expect(_.isInteger(0)).to.be.true;
            expect(_.isInteger(10.0)).to.be.true;
            expect(_.isInteger(-2)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isInteger([])).to.be.false;
        });

        it('Should return false if float element is passed', function () {
            expect(_.isInteger(2.2)).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isInteger()).to.be.false;
        });
    });

    describe('#isFloat()', function () {
        it('Should return true if a float number is passed', function () {
            expect(_.isFloat(2.1)).to.be.true;
            expect(_.isFloat(-2.01)).to.be.true;
        });

        it('Should return false if other element is passed', function () {
            expect(_.isFloat([])).to.be.false;
        });

        it('Should return false if integer element is passed', function () {
            expect(_.isFloat(2)).to.be.false;
        });

        it('Should return false if nothing is passed', function () {
            expect(_.isFloat()).to.be.false;
        });
    });

    describe('#isGlobal()', function () {
        it('Should return true if a global object is passed', function () {
            expect(_.isGlobal(global)).to.be.true;
        });

        it('Should return false if another object or element is passed', function () {
            expect(_.isGlobal({})).to.be.false;
            expect(_.isGlobal(function () {})).to.be.false;
        });
    });
});
<|endoftext|>


<commit_before>// Compares .sol files to their .sol.js counterparts,
// determines which .sol files have been updated.

var path = require("path");
var async = require("async");
var fs = require("fs");
var Graph = require("graphlib").Graph;
var isAcyclic = require("graphlib/lib/alg").isAcyclic;
var Parser = require("./parser");
var CompileError = require("./compileerror");
var expect = require("truffle-expect");
var find_contracts = require("truffle-contract-sources");

module.exports = {
  updated: function(options, callback) {
    var self = this;

    expect.options(options, [
      "resolver"
    ]);

    var contracts_directory = options.contracts_directory;
    var build_directory = options.contracts_build_directory;

    function getFiles(done) {
      if (options.files) {
        done(null, options.files);
      } else {
        find_contracts(contracts_directory, done);
      }
    }

    var sourceFilesArtifacts = {};
    var sourceFilesArtifactsUpdatedTimes = {};

    var updatedFiles = [];

    async.series([
      // Get all the source files and create an object out of them.
      function(c) {
        getFiles(function(err, files) {
          if (err) return c(err);

          // Use an object for O(1) access.
          files.forEach(function(sourceFile) {
            sourceFilesArtifacts[sourceFile] = [];
          });

          c();
        })
      },
      // Get all the artifact files, and read them, parsing them as JSON
      function(c) {
        fs.readdir(build_directory, function(err, build_files) {
          if (err) {
            // The build directory may not always exist.
            if (err.message.indexOf("ENOENT: no such file or directory") >= 0) {
              // Ignore it.
              build_files = [];
            } else {
              return c(err);
            }
          }

          build_files = build_files.filter(function(build_file) {
            return path.extname(build_file) == ".json";
          });

          async.map(build_files, function(buildFile, finished) {
            fs.readFile(path.join(build_directory, buildFile), "utf8", function(err, body) {
              if (err) return finished(err);
              finished(null, body);
            });
          }, function(err, jsonData) {
            if (err) return c(err);

            try {
              for (var i = 0; i < jsonData.length; i++) {
                var data = JSON.parse(jsonData[i]);

                // In case there are artifacts from other source locations.
                if (sourceFilesArtifacts[data.sourcePath] == null) {
                  sourceFilesArtifacts[data.sourcePath] = [];
                }

                sourceFilesArtifacts[data.sourcePath].push(data);
              }
            } catch (e) {
              return c(e);
            }

            c();
          });
        });
      },
      function(c) {
        // Get the minimum updated time for all of a source file's artifacts
        // (note: one source file might have multiple artifacts).
        Object.keys(sourceFilesArtifacts).forEach(function(sourceFile) {
          var artifacts = sourceFilesArtifacts[sourceFile];

          sourceFilesArtifactsUpdatedTimes[sourceFile] = artifacts.reduce(function(minimum, current) {
            var updatedAt = new Date(current.updatedAt).getTime();

            if (updatedAt < minimum) {
              return updatedAt;
            }
            return minimum;
          }, Number.MAX_SAFE_INTEGER);

          // Empty array?
          if (sourceFilesArtifactsUpdatedTimes[sourceFile] == Number.MAX_SAFE_INTEGER) {
            sourceFilesArtifactsUpdatedTimes[sourceFile] = 0;
          }
        });

        c();
      },
      // Stat all the source files, getting there updated times, and comparing them to
      // the artifact updated times.
      function(c) {
        var sourceFiles = Object.keys(sourceFilesArtifacts);

        async.map(sourceFiles, function(sourceFile, finished) {
          fs.stat(sourceFile, function(err, stat) {
            if (err) {
              // Ignore it. This means the source file was removed
              // but the artifact file possibly exists. Return null
              // to signfy that we should ignore it.
              stat = null;
            }
            finished(null, stat);
          });
        }, function(err, sourceFileStats) {
          if (err) return callback(err);

          sourceFiles.forEach(function(sourceFile, index) {
            var sourceFileStat = sourceFileStats[index];

            // Ignore updating artifacts if source file has been removed.
            if (sourceFileStat == null) {
              return;
            }

            var artifactsUpdatedTime = sourceFilesArtifactsUpdatedTimes[sourceFile] || 0;
            var sourceFileUpdatedTime = (sourceFileStat.mtime || sourceFileStat.ctime).getTime();

            if (sourceFileUpdatedTime > artifactsUpdatedTime) {
              updatedFiles.push(sourceFile);
            }
          });

          c();
        });
      }
    ], function(err) {
      callback(err, updatedFiles);
    });
  },

  required_sources: function(options, callback) {
    expect.options(options, [
      "paths",
      "base_path",
      "resolver"
    ]);

    var paths = this.convert_to_absolute_paths(options.paths, options.base_path);

    this.dependency_graph(paths, options.resolver, function(err, dependsGraph) {
      if (err) return callback(err);

      var required = {};

      function hasBeenTraversed(import_path) {
        return required[import_path] != null;
      }

      function include(import_path) {
        //console.log("Including: " + file)

        required[import_path] = dependsGraph.node(import_path);
      }

      function walk_down(import_path) {
        if (hasBeenTraversed(import_path)) {
          return;
        }

        include(import_path);

        var dependencies = dependsGraph.successors(import_path);

        // console.log("At: " + import_path);
        // console.log("   Dependencies: ", dependencies);

        if (dependencies.length > 0) {
          dependencies.forEach(walk_down);
        }
      }

      function walk_from(import_path) {
        if (hasBeenTraversed(import_path)) {
          return;
        }

        var ancestors = dependsGraph.predecessors(import_path);
        var dependencies = dependsGraph.successors(import_path);

        // console.log("At: " + import_path);
        // console.log("   Ancestors: ", ancestors);
        // console.log("   Dependencies: ", dependencies);

        include(import_path);

        if (ancestors.length > 0) {
          ancestors.forEach(walk_from);
        }

        if (dependencies.length > 0) {
          dependencies.forEach(walk_down);
        }
      }

      paths.forEach(walk_from);

      callback(null, required);
    });
  },

  convert_to_absolute_paths: function(paths, base) {
    var self = this;
    return paths.map(function(p) {
      // If it's anabsolute paths, leave it alone.
      if (path.isAbsolute(p)) return p;

      // If it's not explicitly relative, then leave it alone (i.e., it's a module).
      if (!self.isExplicitlyRelative(p)) return p;

      // Path must be explicitly releative, therefore make it absolute.
      return path.resolve(path.join(base, p));
    });
  },

  isExplicitlyRelative: function(import_path) {
    return import_path.indexOf(".") == 0;
  },

  dependency_graph: function(paths, resolver, callback) {
    var self = this;

    // Iterate through all the contracts looking for libraries and building a dependency graph
    var dependsGraph = new Graph();

    var imports_cache = {};

    // For the purposes of determining correct error messages.
    // The second array item denotes which path imported the current path.
    // In the case of the paths passed in, there was none.
    paths = paths.map(function(p) {
      return [p, null];
    });

    async.whilst(function() {
      return paths.length > 0;
    }, function(finished) {
      var current = paths.shift();
      var import_path = current[0];
      var imported_from = current[1];

      if (dependsGraph.hasNode(import_path) && imports_cache[import_path] != null) {
        return finished();
      }

      resolver.resolve(import_path, imported_from, function(err, resolved_body, resolved_path, source) {
        if (err) return finished(err);

        if (dependsGraph.hasNode(resolved_path) && imports_cache[resolved_path] != null) {
          return finished();
        }

        // Add the contract to the depends graph.
        dependsGraph.setNode(resolved_path, resolved_body);

        var imports;

        try {
          imports = Parser.parseImports(resolved_body);
        } catch (e) {
          e.message = "Error parsing " + import_path + ": " + e.message;
          return finished(e);
        }

        // Convert explicitly relative dependencies of modules
        // back into module paths. We also use this loop to update
        // the graph edges.
        imports = imports.map(function(dependency_path) {
          // Convert explicitly relative paths
          if (self.isExplicitlyRelative(dependency_path)) {
            dependency_path = source.resolve_dependency_path(import_path, dependency_path);
          }

          // Update graph edges
          if (!dependsGraph.hasEdge(import_path, dependency_path)) {
            dependsGraph.setEdge(import_path, dependency_path);
          }

          // Return an array that denotes a new import and the path it was imported from.
          return [dependency_path, import_path];
        });

        imports_cache[import_path] = imports;

        Array.prototype.push.apply(paths, imports);

        finished();
      });
    },
    function(err) {
      if (err) return callback(err);
      callback(null, dependsGraph)
    });
  },

  // Parse all source files in the directory and output the names of contracts and their source paths
  // directory can either be a directory or array of files.
  defined_contracts: function(directory, callback) {
    function getFiles(callback) {
      if (Array.isArray(directory)) {
        callback(null, directory);
      } else {
        find_contracts(directory, callback);
      }
    }

    getFiles(function(err, files) {
      if (err) return callback(err);

      var promises = files.map(function(file) {
        return new Promise(function(accept, reject) {
          fs.readFile(file, "utf8", function(err, body) {
            if (err) return reject(err);

            var output;

            try {
              output = Parser.parse(body);
            } catch (e) {
              e.message = "Error parsing " + file + ": " + e.message;
              return reject(e);
            }

            accept(output.contracts);
          });
        }).then(function(contract_names) {
          var returnVal = {};

          contract_names.forEach(function(contract_name) {
            returnVal[contract_name] = file;
          });

          return returnVal;
        });
      });

      Promise.all(promises).then(function(objects) {
        var contract_source_paths = {};

        objects.forEach(function(object) {
          Object.keys(object).forEach(function(contract_name) {
            contract_source_paths[contract_name] = object[contract_name];
          });
        });

        callback(null, contract_source_paths);
      }).catch(callback);
    });
  }
};
<commit_msg>Use all contracts to determine dependent updates<commit_after>// Compares .sol files to their .sol.js counterparts,
// determines which .sol files have been updated.

var path = require("path");
var async = require("async");
var fs = require("fs");
var Graph = require("graphlib").Graph;
var isAcyclic = require("graphlib/lib/alg").isAcyclic;
var Parser = require("./parser");
var CompileError = require("./compileerror");
var expect = require("truffle-expect");
var find_contracts = require("truffle-contract-sources");
var debug = require("debug")("compile:profiler");

module.exports = {
  updated: function(options, callback) {
    var self = this;

    expect.options(options, [
      "resolver"
    ]);

    var contracts_directory = options.contracts_directory;
    var build_directory = options.contracts_build_directory;

    function getFiles(done) {
      if (options.files) {
        done(null, options.files);
      } else {
        find_contracts(contracts_directory, done);
      }
    }

    var sourceFilesArtifacts = {};
    var sourceFilesArtifactsUpdatedTimes = {};

    var updatedFiles = [];

    async.series([
      // Get all the source files and create an object out of them.
      function(c) {
        getFiles(function(err, files) {
          if (err) return c(err);

          // Use an object for O(1) access.
          files.forEach(function(sourceFile) {
            sourceFilesArtifacts[sourceFile] = [];
          });

          c();
        })
      },
      // Get all the artifact files, and read them, parsing them as JSON
      function(c) {
        fs.readdir(build_directory, function(err, build_files) {
          if (err) {
            // The build directory may not always exist.
            if (err.message.indexOf("ENOENT: no such file or directory") >= 0) {
              // Ignore it.
              build_files = [];
            } else {
              return c(err);
            }
          }

          build_files = build_files.filter(function(build_file) {
            return path.extname(build_file) == ".json";
          });

          async.map(build_files, function(buildFile, finished) {
            fs.readFile(path.join(build_directory, buildFile), "utf8", function(err, body) {
              if (err) return finished(err);
              finished(null, body);
            });
          }, function(err, jsonData) {
            if (err) return c(err);

            try {
              for (var i = 0; i < jsonData.length; i++) {
                var data = JSON.parse(jsonData[i]);

                // In case there are artifacts from other source locations.
                if (sourceFilesArtifacts[data.sourcePath] == null) {
                  sourceFilesArtifacts[data.sourcePath] = [];
                }

                sourceFilesArtifacts[data.sourcePath].push(data);
              }
            } catch (e) {
              return c(e);
            }

            c();
          });
        });
      },
      function(c) {
        // Get the minimum updated time for all of a source file's artifacts
        // (note: one source file might have multiple artifacts).
        Object.keys(sourceFilesArtifacts).forEach(function(sourceFile) {
          var artifacts = sourceFilesArtifacts[sourceFile];

          sourceFilesArtifactsUpdatedTimes[sourceFile] = artifacts.reduce(function(minimum, current) {
            var updatedAt = new Date(current.updatedAt).getTime();

            if (updatedAt < minimum) {
              return updatedAt;
            }
            return minimum;
          }, Number.MAX_SAFE_INTEGER);

          // Empty array?
          if (sourceFilesArtifactsUpdatedTimes[sourceFile] == Number.MAX_SAFE_INTEGER) {
            sourceFilesArtifactsUpdatedTimes[sourceFile] = 0;
          }
        });

        c();
      },
      // Stat all the source files, getting there updated times, and comparing them to
      // the artifact updated times.
      function(c) {
        var sourceFiles = Object.keys(sourceFilesArtifacts);

        async.map(sourceFiles, function(sourceFile, finished) {
          fs.stat(sourceFile, function(err, stat) {
            if (err) {
              // Ignore it. This means the source file was removed
              // but the artifact file possibly exists. Return null
              // to signfy that we should ignore it.
              stat = null;
            }
            finished(null, stat);
          });
        }, function(err, sourceFileStats) {
          if (err) return callback(err);

          sourceFiles.forEach(function(sourceFile, index) {
            var sourceFileStat = sourceFileStats[index];

            // Ignore updating artifacts if source file has been removed.
            if (sourceFileStat == null) {
              return;
            }

            var artifactsUpdatedTime = sourceFilesArtifactsUpdatedTimes[sourceFile] || 0;
            var sourceFileUpdatedTime = (sourceFileStat.mtime || sourceFileStat.ctime).getTime();

            if (sourceFileUpdatedTime > artifactsUpdatedTime) {
              updatedFiles.push(sourceFile);
            }
          });

          c();
        });
      }
    ], function(err) {
      callback(err, updatedFiles);
    });
  },

  required_sources: function(options, callback) {
    var self = this;

    expect.options(options, [
      "paths",
      "base_path",
      "resolver"
    ]);

    var paths = this.convert_to_absolute_paths(options.paths, options.base_path);

    function findRequiredSources(dependsGraph, done) {
      var required = {};

      function hasBeenTraversed(import_path) {
        return required[import_path] != null;
      }

      function include(import_path) {
        //console.log("Including: " + file)

        required[import_path] = dependsGraph.node(import_path);
      }

      function walk_down(import_path) {
        if (hasBeenTraversed(import_path)) {
          return;
        }

        include(import_path);

        var dependencies = dependsGraph.successors(import_path);

        // console.log("At: " + import_path);
        // console.log("   Dependencies: ", dependencies);

        if (dependencies.length > 0) {
          dependencies.forEach(walk_down);
        }
      }

      function walk_from(import_path) {
        if (hasBeenTraversed(import_path)) {
          return;
        }

        var ancestors = dependsGraph.predecessors(import_path);
        var dependencies = dependsGraph.successors(import_path);

        // console.log("At: " + import_path);
        // console.log("   Ancestors: ", ancestors);
        // console.log("   Dependencies: ", dependencies);

        include(import_path);

        if (ancestors.length > 0) {
          ancestors.forEach(walk_from);
        }

        if (dependencies.length > 0) {
          dependencies.forEach(walk_down);
        }
      }

      paths.forEach(walk_from);

      done(null, required);
    }

    find_contracts(options.base_path, function(err, allPaths) {
      if (err) return callback(err);

      self.dependency_graph(allPaths, options.resolver, function(err, dependsGraph) {
        if (err) return callback(err);

        findRequiredSources(dependsGraph, callback);
      });
    });
  },

  convert_to_absolute_paths: function(paths, base) {
    var self = this;
    return paths.map(function(p) {
      // If it's anabsolute paths, leave it alone.
      if (path.isAbsolute(p)) return p;

      // If it's not explicitly relative, then leave it alone (i.e., it's a module).
      if (!self.isExplicitlyRelative(p)) return p;

      // Path must be explicitly releative, therefore make it absolute.
      return path.resolve(path.join(base, p));
    });
  },

  isExplicitlyRelative: function(import_path) {
    return import_path.indexOf(".") == 0;
  },

  dependency_graph: function(paths, resolver, callback) {
    var self = this;

    // Iterate through all the contracts looking for libraries and building a dependency graph
    var dependsGraph = new Graph();

    var imports_cache = {};

    // For the purposes of determining correct error messages.
    // The second array item denotes which path imported the current path.
    // In the case of the paths passed in, there was none.
    paths = paths.map(function(p) {
      return [p, null];
    });

    async.whilst(function() {
      return paths.length > 0;
    }, function(finished) {
      var current = paths.shift();
      var import_path = current[0];
      var imported_from = current[1];

      if (dependsGraph.hasNode(import_path) && imports_cache[import_path] != null) {
        return finished();
      }

      resolver.resolve(import_path, imported_from, function(err, resolved_body, resolved_path, source) {
        if (err) return finished(err);

        if (dependsGraph.hasNode(resolved_path) && imports_cache[resolved_path] != null) {
          return finished();
        }

        // Add the contract to the depends graph.
        dependsGraph.setNode(resolved_path, resolved_body);

        var imports;

        try {
          imports = Parser.parseImports(resolved_body);
        } catch (e) {
          e.message = "Error parsing " + import_path + ": " + e.message;
          return finished(e);
        }

        // Convert explicitly relative dependencies of modules
        // back into module paths. We also use this loop to update
        // the graph edges.
        imports = imports.map(function(dependency_path) {
          // Convert explicitly relative paths
          if (self.isExplicitlyRelative(dependency_path)) {
            dependency_path = source.resolve_dependency_path(import_path, dependency_path);
          }

          // Update graph edges
          if (!dependsGraph.hasEdge(import_path, dependency_path)) {
            dependsGraph.setEdge(import_path, dependency_path);
          }

          // Return an array that denotes a new import and the path it was imported from.
          return [dependency_path, import_path];
        });

        imports_cache[import_path] = imports;

        Array.prototype.push.apply(paths, imports);

        finished();
      });
    },
    function(err) {
      if (err) return callback(err);
      callback(null, dependsGraph)
    });
  },

  // Parse all source files in the directory and output the names of contracts and their source paths
  // directory can either be a directory or array of files.
  defined_contracts: function(directory, callback) {
    function getFiles(callback) {
      if (Array.isArray(directory)) {
        callback(null, directory);
      } else {
        find_contracts(directory, callback);
      }
    }

    getFiles(function(err, files) {
      if (err) return callback(err);

      var promises = files.map(function(file) {
        return new Promise(function(accept, reject) {
          fs.readFile(file, "utf8", function(err, body) {
            if (err) return reject(err);

            var output;

            try {
              output = Parser.parse(body);
            } catch (e) {
              e.message = "Error parsing " + file + ": " + e.message;
              return reject(e);
            }

            accept(output.contracts);
          });
        }).then(function(contract_names) {
          var returnVal = {};

          contract_names.forEach(function(contract_name) {
            returnVal[contract_name] = file;
          });

          return returnVal;
        });
      });

      Promise.all(promises).then(function(objects) {
        var contract_source_paths = {};

        objects.forEach(function(object) {
          Object.keys(object).forEach(function(contract_name) {
            contract_source_paths[contract_name] = object[contract_name];
          });
        });

        callback(null, contract_source_paths);
      }).catch(callback);
    });
  }
};
<|endoftext|>


<commit_before>'use strict';
let expect = require('chai').expect;
let fs = require ('fs');
let path = require ('path');
let index = path.join(__dirname, '..', 'index.js');
let childProcess = require('child_process');
// specifically add test flag, otherwise the path will be wrong
let command = 'node ' + index + ' --tests';
let cp = require('ncp');
let out = path.join(__dirname, 'out');

function removeSync(dir) {
  if( fs.existsSync(dir) ) {
    fs.readdirSync(dir).forEach((file) => {
      let curPath = dir + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) {
        removeSync(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(dir);
  }
}

function getJsonFromFile(file) {
  return JSON.parse(fs.readFileSync(file));
}

function onAppCreated(output, shouldExec) {

  let packageJson = path.join(out, 'package.json');
  describe('On app created in /test/out dir', () => {
    it('Output should be equal to "Happy Coding ^_^"', () => {
      expect(output.trim()).to.equal('Happy Coding ^_^');
    });
    it('package.json should exists', () => {
      let bool = fs.existsSync(packageJson);
      expect(bool).to.be.true;
    });
    it('package.json should have esrol installed config property set to true',
    () => {
      let json = getJsonFromFile(packageJson);
      expect(json.config.esrol.installed).to.be.true;
    });
    let should = `When esrol is installed for first time, the whole content in
      apps/server will be moved to the main directory (where "npm install esrol"
      was runned) and since all of the dependencies are added to "package.json",
      when we run "npm install" again, esrol should not move the whole content
      of apps/server again, which can cause adding removed
      files/directories or merging them. So we'll remove one directory from
      the installed app and will run the command again. directory
      "tests/out/app/middlewares/http-middlewares" should not exists`;
    it(should, (done) => {
      let dir = path.join(out, 'app', 'middlewares', 'http-middlewares');
      expect(fs.existsSync(dir)).to.be.true;
      removeSync(dir);
      expect(fs.existsSync(dir)).to.be.false;
      let cmd = childProcess.exec(command, () => {
        expect(fs.existsSync(dir)).to.be.false;
        done();
      });
    });
  });
  if (shouldExec) {
    describe('On post install Esrol', () => {
      it('App should be created in /tests/out dir', (done) => {
        if (fs.existsSync(out)) {
          removeSync(out);
        }
        cp(path.join(__dirname, 'mocks'), __dirname, () => {
          let cmd = childProcess.exec(command);
          cmd.stdout.on('data', (r) => {
            onAppCreated(r);
            done();
          });
        })
      })
    });
  }
}

describe('On post install Esrol', () => {
  it('App should be created in /tests/out dir', (done) => {
    if (fs.existsSync(out)) {
      removeSync(out);
    }
    cp(path.join(__dirname, 'mocks'), __dirname, () => {
      process.argv[2] = '--tests';
      require('../index');
      setTimeout(() => {
        onAppCreated('Happy Coding ^_^', 'exec');
        let Esrol = require('../lib/esrol');
        new Esrol(null, out);
        done();
      }, 200);
    });
  });
});
<commit_msg>trying to fix broken build<commit_after>'use strict';
let expect = require('chai').expect;
let fs = require ('fs');
let path = require ('path');
let index = path.join(__dirname, '..', 'index.js');
let childProcess = require('child_process');
// specifically add test flag, otherwise the path will be wrong
let command = 'node ' + index + ' --tests';
let cp = require('ncp');
let out = path.join(__dirname, 'out');

function removeSync(dir) {
  if( fs.existsSync(dir) ) {
    fs.readdirSync(dir).forEach((file) => {
      let curPath = dir + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) {
        removeSync(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(dir);
  }
}

function getJsonFromFile(file) {
  return JSON.parse(fs.readFileSync(file));
}

function onAppCreated(output, shouldExec) {

  let packageJson = path.join(out, 'package.json');
  describe('On app created in /test/out dir', () => {
    it('Output should be equal to "Happy Coding ^_^"', () => {
      expect(output.trim()).to.equal('Happy Coding ^_^');
    });
    it('package.json should exists', () => {
      let bool = fs.existsSync(packageJson);
      expect(bool).to.be.true;
    });
    it('package.json should have esrol installed config property set to true',
    () => {
      let json = getJsonFromFile(packageJson);
      expect(json.config.esrol.installed).to.be.true;
    });
    let should = `When esrol is installed for first time, the whole content in
      apps/server will be moved to the main directory (where "npm install esrol"
      was runned) and since all of the dependencies are added to "package.json",
      when we run "npm install" again, esrol should not move the whole content
      of apps/server again, which can cause adding removed
      files/directories or merging them. So we'll remove one directory from
      the installed app and will run the command again. directory
      "tests/out/app/middlewares/http-middlewares" should not exists`;
    it(should, (done) => {
      let dir = path.join(out, 'app', 'middlewares', 'http-middlewares');
      expect(fs.existsSync(dir)).to.be.true;
      removeSync(dir);
      expect(fs.existsSync(dir)).to.be.false;
      let cmd = childProcess.exec(command, () => {
        expect(fs.existsSync(dir)).to.be.false;
        done();
      });
    });
  });
}

describe('On post install Esrol', () => {
  it('App should be created in /tests/out dir', (done) => {
    if (fs.existsSync(out)) {
      removeSync(out);
    }
    cp(path.join(__dirname, 'mocks'), __dirname, () => {
      process.argv[2] = '--tests';
      require('../index');
      setTimeout(() => {
        onAppCreated('Happy Coding ^_^', 'exec');
        let Esrol = require('../lib/esrol');
        new Esrol(null, out);
        done();
      }, 200);
    });
  });
});
<|endoftext|>


<commit_before>import Uppy from '../../../../src/core/Core.js'
import Dummy from '../../../../src/plugins/Dummy'
import Tus10 from '../../../../src/plugins/Tus10.js'
import Modal from '../../../../src/plugins/Modal'
import DragDrop from '../../../../src/plugins/DragDrop.js'
import GoogleDrive from '../../../../src/plugins/GoogleDrive.js'
import ProgressBar from '../../../../src/plugins/ProgressBar.js'
import Webcam from '../../../../src/plugins/Webcam.js'
import { UPPY_SERVER } from '../env'

const uppy = new Uppy({debug: true, autoProceed: false})
uppy
  .use(Modal, {trigger: '#uppyModalOpener'})
  .use(DragDrop, {target: Modal})
  .use(GoogleDrive, {target: Modal, host: UPPY_SERVER})
  .use(Webcam, {target: Modal})
  .use(Dummy, {target: Modal})
  .use(Tus10, {endpoint: 'http://master.tus.io:8080/files/'})
  .use(ProgressBar, {target: 'body'})
  .run()
<commit_msg>Don’t use Webcam yet — permissions on load<commit_after>import Uppy from '../../../../src/core/Core.js'
import Dummy from '../../../../src/plugins/Dummy'
import Tus10 from '../../../../src/plugins/Tus10.js'
import Modal from '../../../../src/plugins/Modal'
// import DragDrop from '../../../../src/plugins/DragDrop.js'
import GoogleDrive from '../../../../src/plugins/GoogleDrive.js'
import ProgressBar from '../../../../src/plugins/ProgressBar.js'
// import Webcam from '../../../../src/plugins/Webcam.js'
import { UPPY_SERVER } from '../env'

const uppy = new Uppy({debug: true, autoProceed: false})
uppy
  .use(Modal, {trigger: '#uppyModalOpener'})
  // .use(DragDrop, {target: Modal})
  .use(GoogleDrive, {target: Modal, host: UPPY_SERVER})
  // .use(Webcam, {target: Modal})
  .use(Dummy, {target: Modal})
  .use(Tus10, {endpoint: 'http://master.tus.io:8080/files/'})
  .use(ProgressBar, {target: 'body'})
  .run()
<|endoftext|>


<commit_before>var tape = require('tape')
var ConnectionPool = require('any-db-pool')

var test = module.exports = tape.bind(null)

test.withAdapter = function (description, callback) {
  test(description, function (t) {
    var config = require('../config')
    callback(config, t)
  })
}

test.withConnection = maybeOpts(function (description, opts, callback) {
  tape(description, function (t) {
    var config = require('../config')
    config.adapter.createConnection(config.url, function (err, conn) {
      if (err) throw err
      if (opts.autoEnd !== false) t.on('end', conn.end.bind(conn))
      callback(conn, t)
    })
  })
})

test.withTransaction = maybeOpts(function (description, opts, callback) {
  test(description, function (t) {
    var config = require('../config')
    config.adapter.createConnection(config.url, function (err, conn) {
      if (err) throw err
      var tx = conn.begin()
      t.on('end', function () {
        if (tx.state() != 'closed') {
          tx.rollback(conn.end.bind(conn))
        } else {
          conn.end()
        }
      })
      callback(tx, t)
    })
  })
})

function maybeOpts(f) {
  return function (description, opts, callback) {
    if (!callback) {
      callback = opts
      opts = {}
    }
    f(description, opts, callback)
  }
}
<commit_msg>remove erroneous require('any-db-pool')<commit_after>var tape = require('tape')

var test = module.exports = tape.bind(null)

test.withAdapter = function (description, callback) {
  test(description, function (t) {
    var config = require('../config')
    callback(config, t)
  })
}

test.withConnection = maybeOpts(function (description, opts, callback) {
  tape(description, function (t) {
    var config = require('../config')
    config.adapter.createConnection(config.url, function (err, conn) {
      if (err) throw err
      if (opts.autoEnd !== false) t.on('end', conn.end.bind(conn))
      callback(conn, t)
    })
  })
})

test.withTransaction = maybeOpts(function (description, opts, callback) {
  test(description, function (t) {
    var config = require('../config')
    config.adapter.createConnection(config.url, function (err, conn) {
      if (err) throw err
      var tx = conn.begin()
      t.on('end', function () {
        if (tx.state() != 'closed') {
          tx.rollback(conn.end.bind(conn))
        } else {
          conn.end()
        }
      })
      callback(tx, t)
    })
  })
})

function maybeOpts(f) {
  return function (description, opts, callback) {
    if (!callback) {
      callback = opts
      opts = {}
    }
    f(description, opts, callback)
  }
}
<|endoftext|>


<commit_before>import centerMean from '@turf/center-mean';
import distance from '@turf/distance';
import centroid from '@turf/centroid';
import { isNumber, point, isObject, featureCollection } from '@turf/helpers';
import { featureEach } from '@turf/meta';
import { getCoord } from '@turf/invariant';

/**
 * Takes a {@link FeatureCollection} of points and calculates the median center,
 * algorithimically. It uses the algorithm described in:
 *
 * Harold W. Kuhn and Robert E. Kuenne, “An Efficient Algorithm for the
 * Numerical Solution of the Generalized Weber Problem in Spatial
 * Economics,” _Journal of Regional Science_ 4, no. 2 (1962): 21–33,
 * doi:{@link https://doi.org/10.1111/j.1467-9787.1962.tb00902.x}.
 *
 * James E. Burt, Gerald M. Barber, and David L. Rigby, _Elementary
 * Statistics for Geographers_, 3rd ed., New York: The Guilford
 * Press, 2009, 150–151.
 *
 * @name centerMedian
 * @param {FeatureCollection<Any>} features GeoJSON Feature or Geometry
 * @param {Object} [options={}] Optional parameters
 * @param {string} [options.weight] the property name used to weight the center
 * @param {number} [options.tolerance=0.001] the difference in distance between candidate medians at which point the algorighim stops iterating.
 * @returns {Feature<Point>} The median center of the collection
 * @example
 * var points = turf.featureCollection([turf.points[[0, 0], [1, 0], [0, 1], [5, 8]]);
 * var medianCenter = turf.centerMedian(points);
 *
 * //addToMap
 * var addToMap = [points, medianCenter]
 */
function centerMedian(features, options) {
    // Optional params
    options = options || {};
    if (!isObject(options)) throw new Error('options is invalid');
    var weightTerm = options.weight;

    // Calculate mean center:
    var meanCenter = centerMean(features, {weight: options.weight});

    // Calculate center of every feature:
    var centroids = [];
    featureEach(features, function (feature) { centroids.push(centroid(feature, {weight: feature.properties[weightTerm]})); });
    centroids = featureCollection(centroids);
    centroids.properties = {
        tolerance: options.tolerance,
        medianCandidates: []
    };
    return findMedian(meanCenter, [0, 0], centroids);
}

/**
 * Recursive function to find new candidate medians.
 *
 * @private
 * @param {Feature<Position>} candidateMedian current candidate median
 * @param {Feature<Position>} previousCandidate the previous candidate median
 * @param {FeatureCollection<Point>} centroids the collection of centroids whose median we are determining
 * @returns {Feature<Point>} the median center of the dataset.
 */
function findMedian(candidateMedian, previousCandidate, centroids) {
    var tolerance = centroids.properties.tolerance || 0.001;
    var candidateXsum = 0;
    var candidateYsum = 0;
    var kSum = 0;
    featureEach(centroids, function (theCentroid) {
        var weight = theCentroid.properties.weight || 1;
        if (!isNumber(weight)) throw new Error('weight value must be a number');
        weight = Number(weight);
        if (weight > 0) {
            var distanceFromCandidate = weight * distance(theCentroid, candidateMedian);
            var k = weight / distanceFromCandidate;
            candidateXsum += getCoord(theCentroid)[0] * k;
            candidateYsum += getCoord(theCentroid)[1] * k;
            kSum += k;
        }
    });
    var candidateX = candidateXsum / kSum;
    var candidateY = candidateYsum / kSum;
    if (Math.abs(candidateX - previousCandidate[0]) < tolerance && Math.abs(candidateY - previousCandidate[1]) < tolerance) {
        return point([candidateX, candidateY], {medianCandidates: centroids.properties.medianCandidates});
    } else {
        centroids.properties.medianCandidates.push([candidateX, candidateY]);
        return findMedian([candidateX, candidateY], candidateMedian, centroids);
    }
}

export default centerMedian;

<commit_msg>Add a lot of error checking.<commit_after>import centerMean from '@turf/center-mean';
import distance from '@turf/distance';
import centroid from '@turf/centroid';
import { isNumber, point, isObject, featureCollection } from '@turf/helpers';
import { featureEach } from '@turf/meta';
import { getCoord } from '@turf/invariant';

/**
 * Takes a {@link FeatureCollection} of points and calculates the median center,
 * algorithimically. It uses the algorithm described in:
 *
 * Harold W. Kuhn and Robert E. Kuenne, “An Efficient Algorithm for the
 * Numerical Solution of the Generalized Weber Problem in Spatial
 * Economics,” _Journal of Regional Science_ 4, no. 2 (1962): 21–33,
 * doi:{@link https://doi.org/10.1111/j.1467-9787.1962.tb00902.x}.
 *
 * James E. Burt, Gerald M. Barber, and David L. Rigby, _Elementary
 * Statistics for Geographers_, 3rd ed., New York: The Guilford
 * Press, 2009, 150–151.
 *
 * @name centerMedian
 * @param {FeatureCollection<Any>} features GeoJSON Feature or Geometry
 * @param {Object} [options={}] Optional parameters
 * @param {string} [options.weight] the property name used to weight the center
 * @param {number} [options.tolerance=0.001] the difference in distance between candidate medians at which point the algorighim stops iterating.
 * @param {number} [options.counter=10] how many attempts to find the median, should the tolerance be insufficient.
 * @returns {Feature<Point>} The median center of the collection
 * @example
 * var points = turf.featureCollection([turf.points[[0, 0], [1, 0], [0, 1], [5, 8]]);
 * var medianCenter = turf.centerMedian(points);
 *
 * //addToMap
 * var addToMap = [points, medianCenter]
 */
function centerMedian(features, options) {
    // Optional params
    options = options || {};
    if (!isObject(options)) throw new Error('options is invalid');
    var counter = options.counter || 10
    if (!isNumber(counter)) throw new Error('counter must be a number');
    var weightTerm = options.weight;

    // Calculate mean center:
    var meanCenter = centerMean(features, {weight: options.weight});

    // Calculate center of every feature:
    var centroids = [];
    featureEach(features, function (feature) { centroids.push(centroid(feature, {weight: feature.properties[weightTerm]})); });
    centroids = featureCollection(centroids);
    centroids.properties = {
        tolerance: options.tolerance,
        medianCandidates: []
    };
    return findMedian(meanCenter, [0, 0], centroids, counter);
}

/**
 * Recursive function to find new candidate medians.
 *
 * @private
 * @param {Feature<Position>} candidateMedian current candidate median
 * @param {Feature<Position>} previousCandidate the previous candidate median
 * @param {FeatureCollection<Point>} centroids the collection of centroids whose median we are determining
 * @param {number} counter how many attempts to try before quitting.
 * @returns {Feature<Point>} the median center of the dataset.
 */
function findMedian(candidateMedian, previousCandidate, centroids, counter) {
    var tolerance = centroids.properties.tolerance || 0.001;
    var candidateXsum = 0;
    var candidateYsum = 0;
    var kSum = 0;
    var centroidCount = 0;
    featureEach(centroids, function (theCentroid) {
        var weight = theCentroid.properties.weight;
        if (weight === 0 || weight < 0) {
          weight = 0;
        } else {
          if (!isNumber(weight)) throw new Error('weight value must be a number');
          weight = weight;
        }
        if (weight > 0) {
            centroidCount += 1;
            var distanceFromCandidate = weight * distance(theCentroid, candidateMedian);
            var k = weight / distanceFromCandidate;
            candidateXsum += getCoord(theCentroid)[0] * k;
            candidateYsum += getCoord(theCentroid)[1] * k;
            kSum += k;
        }
    });
    if (centroidCount < 1) throw new Error('no features to measure');
    var candidateX = candidateXsum / kSum;
    var candidateY = candidateYsum / kSum;
    if (centroidCount === 1 || counter === 0 || (Math.abs(candidateX - previousCandidate[0]) < tolerance && Math.abs(candidateY - previousCandidate[1]) < tolerance)) {
        return point([candidateX, candidateY], {medianCandidates: centroids.properties.medianCandidates});
    } else {
        centroids.properties.medianCandidates.push([candidateX, candidateY]);
        return findMedian([candidateX, candidateY], candidateMedian, centroids, counter - 1);
    }
}

export default centerMedian;

<|endoftext|>


<commit_before>// sass added using api.addFiles
Tinytest.add("Sass - Sass files", function(test) {
	var renderedTemplate = UI.render(Template.testTemplate);
	UI.insert(renderedTemplate, document.body);

	var elem = document.getElementById('test-elem');
	test.equal(getStyleProperty(elem, 'display'), 'none', "Expected display: none;")

	UI.remove(renderedTemplate);
});

Tinytest.add("Sass - Partials", function(test) {
	var renderedTemplate = UI.render(Template.testTemplate);
	UI.insert(renderedTemplate, document.body);

	var elem = document.getElementById('test-elem');
	test.equal(getStyleProperty(elem, 'content'), 'partial', "Expected content: partial;")

	UI.remove(renderedTemplate);
});
<commit_msg>Minor changes in test messages<commit_after>// sass added using api.addFiles
Tinytest.add("Sass - Sass files", function(test) {
	var renderedTemplate = UI.render(Template.testTemplate);
	UI.insert(renderedTemplate, document.body);

	var elem = document.getElementById('test-elem');
	test.equal(getStyleProperty(elem, 'display'), 'none', "Expected display: none");

	UI.remove(renderedTemplate);
});

Tinytest.add("Sass - Partials", function(test) {
	var renderedTemplate = UI.render(Template.testTemplate);
	UI.insert(renderedTemplate, document.body);

	var elem = document.getElementById('test-elem');
	test.equal(getStyleProperty(elem, 'content'), 'partial', "Expected content: \"partial\"");

	UI.remove(renderedTemplate);
});
<|endoftext|>


<commit_before>export const GET_EVENTS = "https://develop-shesmashes-thehub.herokuapp.com/api/events";
export const LOGGIN_USER = "https://develop-shesmashes-thehub.herokuapp.com/api/users/login";
export const GET_EVENTDETAILS = "http://develop-shesmashes-thehub.herokuapp.com/api/events/";
export const GET_INITIATIVES = "http://develop-shesmashes-thehub.herokuapp.com/api/initiatives";
export const CREATE_NEW_INITIATIVE = "https://develop-shesmashes-thehub.herokuapp.com/api/initiatives";
<commit_msg>API urls protocal updated<commit_after>export const GET_EVENTS = "https://develop-shesmashes-thehub.herokuapp.com/api/events";
export const LOGGIN_USER = "https://develop-shesmashes-thehub.herokuapp.com/api/users/login";
export const GET_EVENTDETAILS = "https://develop-shesmashes-thehub.herokuapp.com/api/events/";
export const GET_INITIATIVES = "https://develop-shesmashes-thehub.herokuapp.com/api/initiatives";
export const CREATE_NEW_INITIATIVE = "https://develop-shesmashes-thehub.herokuapp.com/api/initiatives";
<|endoftext|>