<commit_before>'use strict';

const assert = require('assert'),
    api = require('../api/api').create(),
    port = api.port + 1,
    mb = require('../mb').create(port),
    isWindows = require('os').platform().indexOf('win') === 0,
    promiseIt = require('../testHelpers').promiseIt,
    baseTimeout = parseInt(process.env.MB_SLOW_TEST_TIMEOUT || 3000),
    timeout = isWindows ? 2 * baseTimeout : baseTimeout,
    hostname = require('os').hostname(),
    BaseHttpClient = require('../api/http/baseHttpClient'),
    http = BaseHttpClient.create('http'),
    fs = require('fs'),
    Q = require('q'),
    path = require('path');

describe('--host', function () {
    this.timeout(timeout);

    promiseIt('should allow binding to specific host', function () {
        return mb.start(['--host', hostname])
            .then(() => mb.get('/'))
            .then(response => {
                const links = response.body._links,
                    hrefs = Object.keys(links).map(key => links[key].href);
                assert.ok(hrefs.length > 0, 'no hrefs to test');
                hrefs.forEach(href => {
                    assert.ok(href.indexOf(`http://${hostname}`) === 0, `${href} does not use hostname`);
                });
            })
            .finally(() => mb.stop());
    });

    promiseIt('should disallow localhost calls when bound to specific host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        return mb.start(['--host', hostname])
            .then(() => http.responseFor({ method: 'GET', path: '/', hostname: 'localhost', port: mb.port }))
            .then(
                () => { assert.fail(`should not have connected (hostname: ${hostname})`); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); })
            .finally(() => mb.stop());
    });

    promiseIt('should work with --configfile', function () {
        const args = ['--host', hostname, '--configfile', path.join(__dirname, 'noparse.json'), '--noParse'];

        return mb.start(args)
            .then(() => http.responseFor({ method: 'GET', path: '/', hostname, port: 4545 }))
            .then(response => {
                assert.strictEqual(response.body, '<% should not render through ejs');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should work with mb save', function () {
        const imposters = { imposters: [{ protocol: 'http', port: 3000, recordRequests: false, stubs: [] }] };

        return mb.start(['--host', hostname])
            .then(() => mb.put('/imposters', imposters))
            .then(response => {
                assert.strictEqual(response.statusCode, 200);
                return mb.save(['--host', hostname]);
            })
            .then(() => {
                assert.ok(fs.existsSync('mb.json'));
                assert.deepEqual(JSON.parse(fs.readFileSync('mb.json')), imposters);
                fs.unlinkSync('mb.json');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should work with mb replay', function () {
        const originServerPort = mb.port + 1,
            originServerStub = { responses: [{ is: { body: 'ORIGIN' } }] },
            originServerRequest = { protocol: 'http', port: originServerPort, stubs: [originServerStub] },
            proxyPort = mb.port + 2,
            proxyDefinition = { to: `http://${hostname}:${originServerPort}`, mode: 'proxyAlways' },
            proxyStub = { responses: [{ proxy: proxyDefinition }] },
            proxyRequest = { protocol: 'http', port: proxyPort, stubs: [proxyStub] };

        return mb.start(['--host', hostname])
            .then(() => mb.put('/imposters', { imposters: [originServerRequest, proxyRequest] }))
            .then(response => {
                assert.strictEqual(response.statusCode, 200, JSON.stringify(response.body));
                return http.responseFor({ method: 'GET', path: '/', hostname, port: proxyPort });
            })
            .then(() => mb.replay(['--host', hostname]))
            .then(() => mb.get('/imposters?replayable=true'))
            .then(response => {
                const imposters = response.body.imposters,
                    oldProxyImposter = imposters.find(imposter => imposter.port === proxyPort),
                    responses = oldProxyImposter.stubs[0].responses;
                assert.strictEqual(responses.length, 1);
                assert.strictEqual(responses[0].is.body, 'ORIGIN');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should bind http imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        const imposter = { protocol: 'http', port: mb.port + 1 };

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return http.responseFor({
                    method: 'GET',
                    path: '/',
                    hostname: hostname,
                    port: imposter.port
                });
            })
            .then(response => {
                assert.strictEqual(response.statusCode, 200);

                return http.responseFor({
                    method: 'GET',
                    path: '/',
                    hostname: 'localhost',
                    port: imposter.port
                });
            })
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });

    promiseIt('should bind tcp imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        const imposter = {
                protocol: 'tcp',
                port: mb.port + 1,
                stubs: [{ responses: [{ is: { data: 'OK' } }] }]
            },
            client = require('../api/tcp/tcpClient');

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return client.send('TEST', imposter.port, 0, hostname);
            })
            .then(response => {
                assert.strictEqual(response.toString(), 'OK');
                return client.send('TEST', imposter.port, 0, 'localhost');
            })
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });

    promiseIt('should bind smtp imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        if (process.env.TRAVIS === 'true') {
            return Q(true);
        }

        const imposter = { protocol: 'smtp', port: mb.port + 1 },
            message = { from: '"From" <from@mb.org>', to: ['"To" <to@mb.org>'], subject: 'subject', text: 'text' },
            client = require('../api/smtp/smtpClient');

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return client.send(message, imposter.port, hostname);
            })
            .then(() => client.send(message, imposter.port, 'localhost'))
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });
});
<commit_msg>Increase timeout due to recent test failures<commit_after>'use strict';

const assert = require('assert'),
    api = require('../api/api').create(),
    port = api.port + 1,
    mb = require('../mb').create(port),
    promiseIt = require('../testHelpers').promiseIt,
    baseTimeout = parseInt(process.env.MB_SLOW_TEST_TIMEOUT || 3000),
    timeout = 2 * baseTimeout,
    hostname = require('os').hostname(),
    BaseHttpClient = require('../api/http/baseHttpClient'),
    http = BaseHttpClient.create('http'),
    fs = require('fs'),
    Q = require('q'),
    path = require('path');

describe('--host', function () {
    this.timeout(timeout);

    promiseIt('should allow binding to specific host', function () {
        return mb.start(['--host', hostname])
            .then(() => mb.get('/'))
            .then(response => {
                const links = response.body._links,
                    hrefs = Object.keys(links).map(key => links[key].href);
                assert.ok(hrefs.length > 0, 'no hrefs to test');
                hrefs.forEach(href => {
                    assert.ok(href.indexOf(`http://${hostname}`) === 0, `${href} does not use hostname`);
                });
            })
            .finally(() => mb.stop());
    });

    promiseIt('should disallow localhost calls when bound to specific host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        return mb.start(['--host', hostname])
            .then(() => http.responseFor({ method: 'GET', path: '/', hostname: 'localhost', port: mb.port }))
            .then(
                () => { assert.fail(`should not have connected (hostname: ${hostname})`); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); })
            .finally(() => mb.stop());
    });

    promiseIt('should work with --configfile', function () {
        const args = ['--host', hostname, '--configfile', path.join(__dirname, 'noparse.json'), '--noParse'];

        return mb.start(args)
            .then(() => http.responseFor({ method: 'GET', path: '/', hostname, port: 4545 }))
            .then(response => {
                assert.strictEqual(response.body, '<% should not render through ejs');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should work with mb save', function () {
        const imposters = { imposters: [{ protocol: 'http', port: 3000, recordRequests: false, stubs: [] }] };

        return mb.start(['--host', hostname])
            .then(() => mb.put('/imposters', imposters))
            .then(response => {
                assert.strictEqual(response.statusCode, 200);
                return mb.save(['--host', hostname]);
            })
            .then(() => {
                assert.ok(fs.existsSync('mb.json'));
                assert.deepEqual(JSON.parse(fs.readFileSync('mb.json')), imposters);
                fs.unlinkSync('mb.json');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should work with mb replay', function () {
        const originServerPort = mb.port + 1,
            originServerStub = { responses: [{ is: { body: 'ORIGIN' } }] },
            originServerRequest = { protocol: 'http', port: originServerPort, stubs: [originServerStub] },
            proxyPort = mb.port + 2,
            proxyDefinition = { to: `http://${hostname}:${originServerPort}`, mode: 'proxyAlways' },
            proxyStub = { responses: [{ proxy: proxyDefinition }] },
            proxyRequest = { protocol: 'http', port: proxyPort, stubs: [proxyStub] };

        return mb.start(['--host', hostname])
            .then(() => mb.put('/imposters', { imposters: [originServerRequest, proxyRequest] }))
            .then(response => {
                assert.strictEqual(response.statusCode, 200, JSON.stringify(response.body));
                return http.responseFor({ method: 'GET', path: '/', hostname, port: proxyPort });
            })
            .then(() => mb.replay(['--host', hostname]))
            .then(() => mb.get('/imposters?replayable=true'))
            .then(response => {
                const imposters = response.body.imposters,
                    oldProxyImposter = imposters.find(imposter => imposter.port === proxyPort),
                    responses = oldProxyImposter.stubs[0].responses;
                assert.strictEqual(responses.length, 1);
                assert.strictEqual(responses[0].is.body, 'ORIGIN');
            })
            .finally(() => mb.stop());
    });

    promiseIt('should bind http imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        const imposter = { protocol: 'http', port: mb.port + 1 };

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return http.responseFor({
                    method: 'GET',
                    path: '/',
                    hostname: hostname,
                    port: imposter.port
                });
            })
            .then(response => {
                assert.strictEqual(response.statusCode, 200);

                return http.responseFor({
                    method: 'GET',
                    path: '/',
                    hostname: 'localhost',
                    port: imposter.port
                });
            })
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });

    promiseIt('should bind tcp imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        // Not sure why it doesn't work in airplane mode
        if (process.env.TRAVIS === 'true' || process.env.MB_AIRPLANE_MODE === 'true') {
            return Q(true);
        }

        const imposter = {
                protocol: 'tcp',
                port: mb.port + 1,
                stubs: [{ responses: [{ is: { data: 'OK' } }] }]
            },
            client = require('../api/tcp/tcpClient');

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return client.send('TEST', imposter.port, 0, hostname);
            })
            .then(response => {
                assert.strictEqual(response.toString(), 'OK');
                return client.send('TEST', imposter.port, 0, 'localhost');
            })
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });

    promiseIt('should bind smtp imposter to provided host', function () {
        // Travis adds hostname into /etc/hosts file
        if (process.env.TRAVIS === 'true') {
            return Q(true);
        }

        const imposter = { protocol: 'smtp', port: mb.port + 1 },
            message = { from: '"From" <from@mb.org>', to: ['"To" <to@mb.org>'], subject: 'subject', text: 'text' },
            client = require('../api/smtp/smtpClient');

        return mb.start(['--host', hostname])
            .then(() => mb.post('/imposters', imposter))
            .then(response => {
                assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body, null, 2));
                return client.send(message, imposter.port, hostname);
            })
            .then(() => client.send(message, imposter.port, 'localhost'))
            .then(
                () => { assert.fail('should not have connected to localhost'); },
                error => { assert.strictEqual(error.errno, 'ECONNREFUSED'); }
            )
            .finally(() => mb.stop());
    });
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Grid from './Grid';

export default class extends Component {
  constructor(props) {
    super(props);

    this.state = {
      page: props.pagination.page,
      query: props.query
    };
  }

  static propTypes = {
    forms: PropTypes.object,
    perms: PropTypes.object,
    getForms: PropTypes.func,
    query: PropTypes.object,
    onAction: PropTypes.func
  }

  static defaultProps = {
    perms: {
      view: true,
      edit: true,
      data: true,
      delete: true
    },
    pagination: {
      page: 1,
      numPages: 1,
      total: 1
    },
    getForms: () => {},
    query: {
      sort: ''
    }
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.query !== prevState.query) {
      return {
        query: nextProps.query
      };
    }

    return null;
  }

  onPage = (page) => {
    this.setState(prevState => {
      prevState.page = page;
      return prevState;
    }, () => this.props.getForms(this.state.page, this.state.query));
  };

  onSort = (field) => {
    if (!this.state.query.sort) {
      this.setState(prevState => {
        prevState.query.sort = field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    const currentSort = this.state.query.sort[0] === '-'
      ? this.state.query.sort.slice(1, this.state.query.sort.length)
      : this.state.query.sort;
    if (currentSort !== field) {
      this.setState(prevState => {
        prevState.query.sort = field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    else if (this.state.query.sort[0] !== '-') {
      this.setState(prevState => {
        prevState.query.sort = '-' + field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    else {
      this.setState(prevState => {
        prevState.query.sort = '';
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
  };

  getColumns() {
    return [
      {
        key: 'title',
        title: 'Form',
        sort: true
      },
      {
        key: 'operations',
        title: 'Operations',
        sort: false
      }
    ];
  }

  Cell = props => {
    const {row: form, column} = props;

    if (column.key === 'title') {
      return (
         props.onAction(form, 'view')}>
{form.title}

      );
    }
    else {
      return (

          {props.perms.view
            ?  props.onAction(form, 'view')}>

              Enter Data

            : null
          }
          {props.perms.data
            ?  props.onAction(form, 'submission')}>

              View Data

            : null
          }
          {props.perms.edit
            ?  props.onAction(form, 'edit')}>

              Edit Form

            : null
          }
          {props.perms.delete
            ?  props.onAction(form, 'delete')}>

            : null
          }

      );
    }
  }

  render() {
    const {forms: {forms, limit, pagination}, onAction, perms} = this.props;
    const columns = this.getColumns();
    const columnWidths = {0: 8, 1: 4};
    const skip = (parseInt(this.state.page) - 1) * parseInt(limit);
    const last = skip + parseInt(limit) > pagination.total ? pagination.total : skip + parseInt(limit);
    const sortOrder = this.state.query.sort;

    return (
      <Grid
        items={forms}
        columns={columns}
        columnWidths={columnWidths}
        onAction={onAction}
        onSort={this.onSort}
        onPage={this.onPage}
        sortOrder={sortOrder}
        activePage={pagination.page}
        firstItem={skip + 1}
        lastItem={last}
        total={parseInt(pagination.total)}
        pages={Math.ceil(parseInt(pagination.total) / limit)}
        emptyText="No forms found"
        Cell={this.Cell}
        perms={perms}
      />
    );
  }
}
<commit_msg>Porting formaccess changes to formgrid from 3.x.<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Grid from './Grid';

export default class extends Component {
  constructor(props) {
    super(props);

    this.state = {
      page: props.pagination.page,
      query: props.query
    };
  }

  static propTypes = {
    forms: PropTypes.object,
    perms: PropTypes.object,
    getForms: PropTypes.func,
    query: PropTypes.object,
    onAction: PropTypes.func,
    formAccess: PropTypes.func,
  }

  static defaultProps = {
    perms: {
      view: true,
      edit: true,
      data: true,
      delete: true
    },
    getForms: () => {},
    query: {
      sort: ''
    },
    formAccess: () => ({
      form: {
        create: true,
        view: true,
        edit: true,
        delete: true,
      },
      submission: {
        create: true,
        view: true,
        edit: true,
        delete: true,
      },
    }),
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.query !== prevState.query) {
      return {
        query: nextProps.query
      };
    }

    return null;
  }

  onPage = (page) => {
    this.setState(prevState => {
      prevState.page = page;
      return prevState;
    }, () => this.props.getForms(this.state.page, this.state.query));
  };

  onSort = (field) => {
    if (!this.state.query.sort) {
      this.setState(prevState => {
        prevState.query.sort = field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    const currentSort = this.state.query.sort[0] === '-'
      ? this.state.query.sort.slice(1, this.state.query.sort.length)
      : this.state.query.sort;
    if (currentSort !== field) {
      this.setState(prevState => {
        prevState.query.sort = field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    else if (this.state.query.sort[0] !== '-') {
      this.setState(prevState => {
        prevState.query.sort = '-' + field;
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
    else {
      this.setState(prevState => {
        prevState.query.sort = '';
        return prevState;
      }, () => this.props.getForms(this.state.page, this.state.query));
    }
  };

  getColumns() {
    return [
      {
        key: 'title',
        title: 'Form',
        sort: true
      },
      {
        key: 'operations',
        title: 'Operations',
        sort: false
      }
    ];
  }

  Cell = props => {
    const {row: form, column, formAccess} = props;

    const access = formAccess(form);

    if (column.key === 'title') {
      return (
         {
          if (access.submission.create) {
            props.onAction(form, 'view');
          }
        }}>
{form.title}

      );
    }
    else {
      return (

          {access.submission.create
            ?  props.onAction(form, 'view')}>

              Enter Data

            : null
          }
          {access.submission.view
            ?  props.onAction(form, 'submission')}>

              View Data

            : null
          }
          {access.form.edit
            ?  props.onAction(form, 'edit')}>

              Edit Form

            : null
          }
          {access.form.delete
            ?  props.onAction(form, 'delete')}>

            : null
          }

      );
    }
  };

  render() {
    const {forms: {forms, limit, pagination}, onAction, formAccess, perms} = this.props;
    const columns = this.getColumns();
    const columnWidths = {0: 8, 1: 4};
    const skip = (parseInt(this.state.page) - 1) * parseInt(limit);
    const last = skip + parseInt(limit) > pagination.total ? pagination.total : skip + parseInt(limit);
    const sortOrder = this.state.query.sort;

    return (
      <Grid
        items={forms}
        columns={columns}
        columnWidths={columnWidths}
        onAction={onAction}
        onSort={this.onSort}
        onPage={this.onPage}
        sortOrder={sortOrder}
        activePage={pagination.page}
        firstItem={skip + 1}
        lastItem={last}
        total={parseInt(pagination.total)}
        pages={Math.ceil(parseInt(pagination.total) / limit)}
        emptyText="No forms found"
        Cell={this.Cell}
        formAccess={formAccess}
        perms={perms}
      />
    );
  }
}
<|endoftext|>


<commit_before>/* global require */
const Winston = require('winston');
const _ = require('lodash');
const readPkg = require('read-pkg');
const pkgDir = require('pkg-dir');
const fs = require('fs');
const path = require('path');

const logLevels = require('./config-levels');
const defaultTransports = require('./default-transports');

let logger;

class Logger {
  constructor(namespace /* , context */) {
    this.options = {};
    this.options.namespace = namespace || {};

    this.winston = new (Winston.Logger)({
      level: logLevels.defaultLevel,
      levels: logLevels.levels,
      colors: logLevels.colors,
      exitOnError: false
    });
    // this._patchInternals();
    this._config();
    this._configTransports();
  }

  // Allow easy instantiation by using `require('winster').instance()`
  static instance() {
    if (!logger) {
      logger = new Logger();
    }
    return logger;
  }

  _config() {

    // Expose a method for each of the custom log levels
    for (const level in logLevels.levels) { // eslint-disable-line guard-for-in
      this[level] = function (msg, msgContext) {
        this.winston[level](msg, msgContext);
      };
    }
  }

  // Fix to include a line break into the log
  // See: https://github.com/winstonjs/winston/issues/460
  // _patchInternals() {
  //   const self = this;
  //   this.winston.log = function () {
  //     const args = arguments;
  //     args[1] += '\r\n';
  //     self.winston.Logger.prototype.log.apply(this, args);
  //   };
  // }

  /**
   * Determines which transport configuration file to use:
   *
   * - 1st fetch the configuration in package.json
   * - 2nd Look for a file called .winster.js in the project's root
   * - 3rd fall back to  ./src/default-transports.js
   *
   * @returns {*}
   * @private
   */
  _getTransportDefinition() {

    // 1st: fetch the configuration in package.json
    const pkg = readPkg.sync();
    //this._internalLog('[winster] package from ' + pkg.name + ': ', pkg.winster);
    if (pkg.winster && pkg.winster.configFile) {
      const configPkg = path.join(pkgDir.sync(), pkg.winster.configFile);
      if (fs.existsSync(configPkg)) {
        this._internalLog('[winster] Using transports as defined in package.json\r\n');
        return _.extend(require(configPkg), {from: 'package.json'});
      }
    }

    // 2nd: Look for a file called .winster.js in the project's root.
    const rootFile = path.join(process.cwd(), '.winster.js');
    // this._internalLog('[winster] Rootfile:', rootFile);
    if (fs.existsSync(rootFile)) {
      this._internalLog('[winster] Loading .winster.js');
      return _.extend(require(rootFile), {from: '.winster.js'});
    }

    this._internalLog('[winster] Loading default transports');
    return _.extend(defaultTransports, {from: 'default'});
  }

  /**
   * Logging for the internal stuff, where we cannot use Winster, yet.
   * @param msg
   * @private
   */
  _internalLog(msg, msgContext) {
    if (process.env.WINSTER_SUPRESS_LOGGING !== 'true') {
      console.log.apply(console, arguments);
    }
  }

  _configTransports() {
    this._transportConfig = this._getTransportDefinition();
    const env = !_.isEmpty(process.env.NODE_ENV) ? process.env.NODE_ENV : 'development';

    const transports = this._transportConfig[env];
    const transportsList = _.map(transports, item => {
      return item.options.name;
    });
    this._internalLog('[winster] Adding ' + (transports ? transports.length : 0) + ' transport(s) to ' + env + ': ' + (!_.isEmpty(transportsList) ? transportsList : '-') + '\r\n');
    if (transports) {
      transports.forEach(item => {
        this.winston.add(item.transporter, item.options);
      });
    }
  }

  log(level, msg, context) {
      this.winston.log(level, msg, context);
  }

}

module.exports = Logger;
<commit_msg>style: satisfy linter<commit_after>/* global require */
const Winston = require('winston');
const _ = require('lodash');
const readPkg = require('read-pkg');
const pkgDir = require('pkg-dir');
const fs = require('fs');
const path = require('path');

const logLevels = require('./config-levels');
const defaultTransports = require('./default-transports');

let logger;

class Logger {
  constructor(namespace /* , context */) {
    this.options = {};
    this.options.namespace = namespace || {};

    this.winston = new (Winston.Logger)({
      level: logLevels.defaultLevel,
      levels: logLevels.levels,
      colors: logLevels.colors,
      exitOnError: false
    });
    // this._patchInternals();
    this._config();
    this._configTransports();
  }

  // Allow easy instantiation by using `require('winster').instance()`
  static instance() {
    if (!logger) {
      logger = new Logger();
    }
    return logger;
  }

  _config() {

    // Expose a method for each of the custom log levels
    for (const level in logLevels.levels) { // eslint-disable-line guard-for-in
      this[level] = function (msg, msgContext) {
        this.winston[level](msg, msgContext);
      };
    }
  }

  // Fix to include a line break into the log
  // See: https://github.com/winstonjs/winston/issues/460
  // _patchInternals() {
  //   const self = this;
  //   this.winston.log = function () {
  //     const args = arguments;
  //     args[1] += '\r\n';
  //     self.winston.Logger.prototype.log.apply(this, args);
  //   };
  // }

  /**
   * Determines which transport configuration file to use:
   *
   * - 1st fetch the configuration in package.json
   * - 2nd Look for a file called .winster.js in the project's root
   * - 3rd fall back to  ./src/default-transports.js
   *
   * @returns {*}
   * @private
   */
  _getTransportDefinition() {

    // 1st: fetch the configuration in package.json
    const pkg = readPkg.sync();
    // this._internalLog('[winster] package from ' + pkg.name + ': ', pkg.winster);
    if (pkg.winster && pkg.winster.configFile) {
      const configPkg = path.join(pkgDir.sync(), pkg.winster.configFile);
      if (fs.existsSync(configPkg)) {
        this._internalLog('[winster] Using transports as defined in package.json\r\n');
        return _.extend(require(configPkg), {from: 'package.json'});
      }
    }

    // 2nd: Look for a file called .winster.js in the project's root.
    const rootFile = path.join(process.cwd(), '.winster.js');
    // this._internalLog('[winster] Rootfile:', rootFile);
    if (fs.existsSync(rootFile)) {
      this._internalLog('[winster] Loading .winster.js');
      return _.extend(require(rootFile), {from: '.winster.js'});
    }

    this._internalLog('[winster] Loading default transports');
    return _.extend(defaultTransports, {from: 'default'});
  }

  /**
   * Logging for the internal stuff, where we cannot use Winster, yet.
   * @param msg
   * @private
   */
  _internalLog(/* msg, msgContext */) {
    if (process.env.WINSTER_SUPRESS_LOGGING !== 'true') {
      console.log.apply(console, arguments);
    }
  }

  _configTransports() {
    this._transportConfig = this._getTransportDefinition();
    const env = !_.isEmpty(process.env.NODE_ENV) ? process.env.NODE_ENV : 'development'; // eslint-disable-line no-negated-condition

    const transports = this._transportConfig[env];
    const transportsList = _.map(transports, item => {
      return item.options.name;
    });
    this._internalLog('[winster] Adding ' + (transports ? transports.length : 0) + ' transport(s) to ' + env + ': ' + (!_.isEmpty(transportsList) ? transportsList : '-') + '\r\n');  // eslint-disable-line no-negated-condition
    if (transports) {
      transports.forEach(item => {
        this.winston.add(item.transporter, item.options);
      });
    }
  }

  log(level, msg, context) {
    this.winston.log(level, msg, context);
  }

}

module.exports = Logger;
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/form-for';

const {
  get,
  isPresent,
  set,
  Component
} = Ember;

const FormForComponent = Component.extend({
  layout,

  tagName: 'form',

  attributeBindings: ['tabindex'],
  tabindex: '-1',

  submit: (object) => object.save(),
  reset:  (object) => object.rollback(),

  update(object, propertyName, value) {
    set(object, propertyName, value);
  },

  actions: {
    submit(object) {
      get(this, 'submit')(object);

      let errors = get(object, 'errors');
      if (errors) {
        for (let propertyName in errors) {
          if (isPresent(get(errors, propertyName))) {
            this.$().focus();
            break;
          }
        }
      }
    }
  }
});

FormForComponent.reopenClass({
  positionalParams: ['object']
});

export default FormForComponent;
<commit_msg>Only add tabindex to form when form has errors<commit_after>import Ember from 'ember';
import layout from '../templates/components/form-for';

const {
  get,
  isPresent,
  set,
  run: { schedule },
  Component
} = Ember;

const FormForComponent = Component.extend({
  layout,

  tagName: 'form',

  attributeBindings: ['tabindex'],

  submit: (object) => object.save(),
  reset:  (object) => object.rollback(),

  update(object, propertyName, value) {
    set(object, propertyName, value);
  },

  actions: {
    submit(object) {
      get(this, 'submit')(object);
      set(this, 'tabindex', undefined);

      let errors = get(object, 'errors');
      if (errors) {
        for (let propertyName in errors) {
          if (isPresent(get(errors, propertyName))) {
            set(this, 'tabindex', -1);
            schedule('afterRender', () => this.$().focus());
            break;
          }
        }
      }
    }
  }
});

FormForComponent.reopenClass({
  positionalParams: ['object']
});

export default FormForComponent;
<|endoftext|>


<commit_before>/*!
Copyright 2013 ASTEA

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

// Declare dependencies
/*global fluid, jqUnit, expect, jQuery*/

// JSLint options
/*jslint white: true, funcinvoke: true, undef: true, newcap: true, nomen: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */

(function ($) {
    fluid.registerNamespace("gpii.prefs.gpiiStore.tests");

    jqUnit.module("GPIIStore Tests");

    var store = gpii.prefs.gpiiStore();

    var exampleModel = '{"gpii_primarySchema_volume":80,' +
                        '"gpii_primarySchema_keyEcho":false,' +
                        '"gpii_primarySchema_wordEcho":false,' +
                        '"gpii_primarySchema_fontSize":12,' +
                        '"gpii_primarySchema_speakText":false,' +
                        '"gpii_primarySchema_voicePitch":80,' +
                        '"gpii_primarySchema_cursorSize":1,' +
                        '"gpii_primarySchema_magnification":100,' +
                        '"gpii_primarySchema_contrast_theme":"black-white",' +
                        '"gpii_primarySchema_showCrosshairs":false,' +
                        '"gpii_primarySchema_universalVolume":80,' +
                        '"gpii_primarySchema_contrastEnabled":false,' +
                        '"gpii_primarySchema_announceCapitals":false,' +
                        '"gpii_primarySchema_textHighlighting":"Word",' +
                        '"gpii_primarySchema_magnifierEnabled":false,' +
                        '"gpii_primarySchema_universalLanguage":"en",' +
                        '"gpii_primarySchema_punctuationVerbosity":"none",' +
                        '"gpii_primarySchema_screenReaderLanguage":"en",' +
                        '"gpii_primarySchema_wordsSpokenPerMinute":130,' +
                        '"gpii_primarySchema_speakTutorialMessages":false,' +
                        '"gpii_primarySchema_magnificationPosition":"TopHalf",' +
                        '"gpii_primarySchema_screenReaderBrailleOutput":false}';

    var convertedExampleModel = '{"http://registry.gpii.org/common/pitch":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/volume":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/keyEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/language":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/wordEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/fontSize":[{"value":12}],' +
                                 '"http://registry.gpii.org/common/volumeTTS":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/speechRate":[{"value":130}],' +
                                 '"http://registry.gpii.org/common/cursorSize":[{"value":0.2}],' +
                                 '"http://registry.gpii.org/common/readingUnit":[{"value":"Word"}],' +
                                 '"http://registry.gpii.org/common/magnification":[{"value":1}],' +
                                 '"http://registry.gpii.org/common/showCrosshairs":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/announceCapitals":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/magnifierEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/highContrastTheme":[{"value":"black-white"}],' +
                                 '"http://registry.gpii.org/common/magnifierPosition":[{"value":"TopHalf"}],' +
                                 '"http://registry.gpii.org/common/auditoryOutLanguage":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/highContrastEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/punctuationVerbosity":[{"value":"none"}],' +
                                 '"http://registry.gpii.org/common/speakTutorialMessages":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderTTSEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderBrailleOutput":[{"value":false}]}';

    var userToWorkWith = "sammy";

    var loginSuccessMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith + "/login",
        responseText: "User with token " + userToWorkWith + " was successfully logged in."
    };

    var getRequestMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json"
    };

    setRequestNoUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/",
        dataType: "json",
        responseText: {
            "token": userToWorkWith
        }
    };

    gpii.prefs.gpiiStore.tests.assertNotUndefined = function () {
        jqUnit.assertValue("Object should not be null or undefined.", store);
    };

    gpii.prefs.gpiiStore.tests.assertModeflTransofrmation = function () {
        var exampleModelObject = JSON.parse(exampleModel);
        var transformedExampleModel = store.modelTransform(exampleModelObject, gpii.prefs.commonTermsTransformationRules);
        var stringifiedExampleObject = JSON.stringify(transformedExampleModel); // Comparing stringified objects, since JSON.parse(JSON.stringify(obj)) != obj

        jqUnit.assertEquals("Transforming the model from schema to http://registry.gpii.org/common/...", stringifiedExampleObject, convertedExampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation = function () {
        var exampleTransformedObject = JSON.parse(convertedExampleModel);
        var inverseTransformedExampleModel = store.inverseModelTransform(exampleTransformedObject, gpii.prefs.commonTermsInverseTransformationRules);
        var stringifiedExampleObject = JSON.stringify(inverseTransformedExampleModel);

        jqUnit.assertEquals("Transforming the model from http://registry.gpii.org/common/... to schema-like", stringifiedExampleObject, exampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser = function () {
        var gpiiModel = store.get();
        jqUnit.assertNoValue("Settings object is undefined when no user is logged.", gpiiModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser = function () {
        var keys = ["keyEcho", "wordEcho", "fontSize", "tracking", "speakText", "contrast_theme", "showCrosshairs", "contrastEnabled", "announceCapitals", "textHighlighting", "magnifierEnabled", "universalLanguage", "punctuationVerbosity", "screenReaderLanguage", "wordsSpokenPerMinute", "screenReaderTracking", "speakTutorialMessages", "magnificationPosition", "screenReaderBrailleOutput"];
        var modelKeys = [];

        fluid.each(keys, function (key) {
            modelKeys.push("gpii_primarySchema_" + key);
        });

        store.gpiiSession.login(userToWorkWith);
        var gpiiModel = store.get();

        jqUnit.assertEquals("Checking if the GET invoker successfully calls the transform function.", JSON.stringify(Object.keys(gpiiModel)), JSON.stringify(modelKeys));
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser = function () {
        store.set();
        jqUnit.assertValue("Set creates token.", store.gpiiSession.options.loggedUser);
    };

    gpii.prefs.gpiiStore.tests.mockTest = function (testTitle, assertFunction, enabledMockSettings) {
        jqUnit.test(testTitle, function () {
            $.mockjaxClear();
            fluid.each(enabledMockSettings, $.mockjax);
            assertFunction();
            $.mockjaxClear();
        });
    };

    gpii.prefs.gpiiStore.tests.mockTest("Object not undefined.", gpii.prefs.gpiiStore.tests.assertNotUndefined);
    gpii.prefs.gpiiStore.tests.mockTest("Model transformation is correct.", gpii.prefs.gpiiStore.tests.assertModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Inverted model transformation is correct.", gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Set invoker when user is logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser, [setRequestNoUserMockSettings, loginSuccessMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Get invoker when no user is logged.", gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser);
    gpii.prefs.gpiiStore.tests.mockTest("Get invoker when user is logged.", gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser, [loginSuccessMockSettings, getRequestMockSettings]);

})(jQuery);
<commit_msg>GPII-663: Fixed wrong test explanation.<commit_after>/*!
Copyright 2013 ASTEA

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

// Declare dependencies
/*global fluid, jqUnit, expect, jQuery*/

// JSLint options
/*jslint white: true, funcinvoke: true, undef: true, newcap: true, nomen: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */

(function ($) {
    fluid.registerNamespace("gpii.prefs.gpiiStore.tests");

    jqUnit.module("GPIIStore Tests");

    var store = gpii.prefs.gpiiStore();

    var exampleModel = '{"gpii_primarySchema_volume":80,' +
                        '"gpii_primarySchema_keyEcho":false,' +
                        '"gpii_primarySchema_wordEcho":false,' +
                        '"gpii_primarySchema_fontSize":12,' +
                        '"gpii_primarySchema_speakText":false,' +
                        '"gpii_primarySchema_voicePitch":80,' +
                        '"gpii_primarySchema_cursorSize":1,' +
                        '"gpii_primarySchema_magnification":100,' +
                        '"gpii_primarySchema_contrast_theme":"black-white",' +
                        '"gpii_primarySchema_showCrosshairs":false,' +
                        '"gpii_primarySchema_universalVolume":80,' +
                        '"gpii_primarySchema_contrastEnabled":false,' +
                        '"gpii_primarySchema_announceCapitals":false,' +
                        '"gpii_primarySchema_textHighlighting":"Word",' +
                        '"gpii_primarySchema_magnifierEnabled":false,' +
                        '"gpii_primarySchema_universalLanguage":"en",' +
                        '"gpii_primarySchema_punctuationVerbosity":"none",' +
                        '"gpii_primarySchema_screenReaderLanguage":"en",' +
                        '"gpii_primarySchema_wordsSpokenPerMinute":130,' +
                        '"gpii_primarySchema_speakTutorialMessages":false,' +
                        '"gpii_primarySchema_magnificationPosition":"TopHalf",' +
                        '"gpii_primarySchema_screenReaderBrailleOutput":false}';

    var convertedExampleModel = '{"http://registry.gpii.org/common/pitch":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/volume":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/keyEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/language":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/wordEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/fontSize":[{"value":12}],' +
                                 '"http://registry.gpii.org/common/volumeTTS":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/speechRate":[{"value":130}],' +
                                 '"http://registry.gpii.org/common/cursorSize":[{"value":0.2}],' +
                                 '"http://registry.gpii.org/common/readingUnit":[{"value":"Word"}],' +
                                 '"http://registry.gpii.org/common/magnification":[{"value":1}],' +
                                 '"http://registry.gpii.org/common/showCrosshairs":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/announceCapitals":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/magnifierEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/highContrastTheme":[{"value":"black-white"}],' +
                                 '"http://registry.gpii.org/common/magnifierPosition":[{"value":"TopHalf"}],' +
                                 '"http://registry.gpii.org/common/auditoryOutLanguage":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/highContrastEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/punctuationVerbosity":[{"value":"none"}],' +
                                 '"http://registry.gpii.org/common/speakTutorialMessages":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderTTSEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderBrailleOutput":[{"value":false}]}';

    var userToWorkWith = "sammy";

    var loginSuccessMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith + "/login",
        responseText: "User with token " + userToWorkWith + " was successfully logged in."
    };

    var getRequestMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json"
    };

    setRequestNoUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/",
        dataType: "json",
        responseText: {
            "token": userToWorkWith
        }
    };

    gpii.prefs.gpiiStore.tests.assertNotUndefined = function () {
        jqUnit.assertValue("Object should not be null or undefined.", store);
    };

    gpii.prefs.gpiiStore.tests.assertModeflTransofrmation = function () {
        var exampleModelObject = JSON.parse(exampleModel);
        var transformedExampleModel = store.modelTransform(exampleModelObject, gpii.prefs.commonTermsTransformationRules);
        var stringifiedExampleObject = JSON.stringify(transformedExampleModel); // Comparing stringified objects, since JSON.parse(JSON.stringify(obj)) != obj

        jqUnit.assertEquals("Transforming the model from schema to http://registry.gpii.org/common/...", stringifiedExampleObject, convertedExampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation = function () {
        var exampleTransformedObject = JSON.parse(convertedExampleModel);
        var inverseTransformedExampleModel = store.inverseModelTransform(exampleTransformedObject, gpii.prefs.commonTermsInverseTransformationRules);
        var stringifiedExampleObject = JSON.stringify(inverseTransformedExampleModel);

        jqUnit.assertEquals("Transforming the model from http://registry.gpii.org/common/... to schema-like", stringifiedExampleObject, exampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser = function () {
        var gpiiModel = store.get();
        jqUnit.assertNoValue("Settings object is undefined when no user is logged.", gpiiModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser = function () {
        var keys = ["keyEcho", "wordEcho", "fontSize", "tracking", "speakText", "contrast_theme", "showCrosshairs", "contrastEnabled", "announceCapitals", "textHighlighting", "magnifierEnabled", "universalLanguage", "punctuationVerbosity", "screenReaderLanguage", "wordsSpokenPerMinute", "screenReaderTracking", "speakTutorialMessages", "magnificationPosition", "screenReaderBrailleOutput"];
        var modelKeys = [];

        fluid.each(keys, function (key) {
            modelKeys.push("gpii_primarySchema_" + key);
        });

        store.gpiiSession.login(userToWorkWith);
        var gpiiModel = store.get();

        jqUnit.assertEquals("Checking if the GET invoker successfully calls the transform function.", JSON.stringify(Object.keys(gpiiModel)), JSON.stringify(modelKeys));
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser = function () {
        store.set();
        jqUnit.assertValue("Set creates token.", store.gpiiSession.options.loggedUser);
    };

    gpii.prefs.gpiiStore.tests.mockTest = function (testTitle, assertFunction, enabledMockSettings) {
        jqUnit.test(testTitle, function () {
            $.mockjaxClear();
            fluid.each(enabledMockSettings, $.mockjax);
            assertFunction();
            $.mockjaxClear();
        });
    };

    gpii.prefs.gpiiStore.tests.mockTest("Object not undefined.", gpii.prefs.gpiiStore.tests.assertNotUndefined);
    gpii.prefs.gpiiStore.tests.mockTest("Model transformation is correct.", gpii.prefs.gpiiStore.tests.assertModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Inverted model transformation is correct.", gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Set invoker when no user is logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser, [setRequestNoUserMockSettings, loginSuccessMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Get invoker when no user is logged.", gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser);
    gpii.prefs.gpiiStore.tests.mockTest("Get invoker when user is logged.", gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser, [loginSuccessMockSettings, getRequestMockSettings]);

})(jQuery);
<|endoftext|>


<commit_before>var iNatAPI = angular.module( "iNatAPI", [ ]);

iNatAPI.factory( "shared", [ "$http", "$rootScope", "$filter",
function( $http, $rootScope, $filter ) {
  var basicGet = function( url, options ) {
    options = options || { };
    if( options.cache !== true ) { options.cache = false; }
    var config = {
      cache: options.cache,
      timeout: 20000 // 20 second timeout
    };
    var apiURL = $( "meta[name='config:inaturalist_api_url']" ).attr( "content" );
    if ( apiURL && url.indexOf( apiURL ) >= 0 ) {
      var apiToken = $( "meta[name='inaturalist-api-token']" ).attr( "content" );
      if ( apiToken ) {
        config.headers = {
          Authorization: apiToken
        }
      }
    }
    return $http.get( url, config ).then(
      function( response ) {
        return response;
      }, function( errorResponse ) {
        // Handle error case
      }
    );
  };

  var numberWithCommas = function( num ) {
    if( !_.isNumber( num ) ) { return num; }
    return I18n.toNumber( num, { precision: 0 } );
  };

  var t = function( k, options ) {
    options = options || { };
    return I18n.t( k, options );
  };

  var taxonStatusTitle = function( taxon ) {
    if( !taxon.conservation_status ) { return; }
    var title = $filter( "capitalize" )( taxon.conservationStatus( ), "title" );
    if( taxon.conservation_status && taxon.conservation_status.place ) {
      title = t( "status_in_place", {
        status: title, place: taxon.conservation_status.place.display_name });
    } else {
      title = t( "status_globally", { status: title });
    }
    return title;
  };

  var taxonMeansTitle = function( taxon ) {
    if( !taxon.establishment_means ) { return; }
    var title = $filter( "capitalize" )(
      t( taxon.establishment_means.establishment_means ), "title" );
    if( taxon.establishment_means && taxon.establishment_means.place ) {
      title = t( "status_in_place", {
        status: $filter( "capitalize" )(
          t( taxon.establishment_means.establishment_means, { locale: "en" }), "title" ),
        place: taxon.establishment_means.place.display_name });
    }
    return title;
  };

  var backgroundIf = function( url ) {
    if( url ) {
      return { "background-image": "url('" + url + "')" };
    }
  };

  var offsetCenter = function( options, callback ) {
    if( !options.map ) { return callback( ); }
    var overlay = new google.maps.OverlayView( );
    overlay.draw = function( ) { };
    overlay.setMap( options.map );
    var proj = overlay.getProjection( );
    var currentCenter = options.map.getCenter( );
    if( !proj ) {
      options.attempts = options.attempts || 0;
      options.attempts += 1;
      if( options.attempts >= 10 ) { return callback( currentCenter ); }
      setTimeout( function( ) {
        offsetCenter( options, callback );
      }, 5);
      return;
    }
    var cPoint = proj.fromLatLngToDivPixel( currentCenter );
    cPoint.x = cPoint.x + options.left; // left of center
    cPoint.y = cPoint.y + options.up; // north of center
    var newCenter = proj.fromDivPixelToLatLng( cPoint );
    overlay.setMap( null );
    overlay = null;
    callback( newCenter );
  };

  var processPoints = function( geometry, callback, thisArg ) {
    if( !geometry ) { return; }
    if( geometry instanceof google.maps.LatLng ) {
      callback.call( thisArg, geometry );
    } else if( geometry instanceof google.maps.Data.Point ) {
      callback.call( thisArg, geometry.get( ) );
    } else {
      geometry.getArray( ).forEach( function( g ) {
        processPoints( g, callback, thisArg );
      });
    }
  };

  var stringStartsWith = function( str, pattern, position ) {
    position = _.isNumber( position ) ? position : 0;
    // We use `lastIndexOf` instead of `indexOf` to avoid tying execution
    // time to string length when string doesn't start with pattern.
    return str.toLowerCase( ).lastIndexOf( pattern.toLowerCase( ), position ) === position;
  };

  var pp = function( obj ) {
    console.log( JSON.stringify( obj, null, "  " ) );
  };

  return {
    basicGet: basicGet,
    numberWithCommas: numberWithCommas,
    t: t,
    taxonStatusTitle: taxonStatusTitle,
    taxonMeansTitle: taxonMeansTitle,
    backgroundIf: backgroundIf,
    offsetCenter: offsetCenter,
    processPoints: processPoints,
    stringStartsWith: stringStartsWith,
    pp: pp
  }
}]);

// prints a date like "Today 12:34 PM" with some stylable wrapper elements
iNatAPI.directive('inatCalendarDate', ["shared", function(shared) {
  return {
    scope: {
      time: "=",
      date: "=",
      timezone: "="
    },
    link: function(scope, elt, attr) {
      scope.dateString = function() {
        if( !scope.date ) {
          return shared.t('unknown');
        }
        var date = moment(scope.date),
            now = moment(new Date()),
            dateString;
        if (date.isSame(now, 'day')) {
          dateString = I18n.t('today');
        } else if (date.isSame(now.subtract(1, 'day'), 'day')) {
          dateString = I18n.t('yesterday');
        } else {
          dateString = date.format('ll');
        }
        return dateString;
      }
      scope.timeString = function() {
        if( !scope.time ) { return; }
        scope.timezone = scope.timezone || "UTC";
        return moment(scope.time).tz(scope.timezone).format("LT z");
      }
    },
    template: '{{ dateString() }}{{ timeString() }}'
  }
}]);

// print a taxon with correctly formatted common and scientific names
iNatAPI.directive('inatTaxon', ["shared", function(shared) {
  return {
    scope: {
      taxon: '=',
      url: '@'
    },
    link: function(scope, elt, attr) {
      scope.iconicTaxonNameForID = function(iconicTaxonID) {
        var t = window.ICONIC_TAXA[iconicTaxonID]
        if (t) {
          return t.name;
        } else {
          return 'Unknown'
        }
      };
      scope.shared = shared;
      scope.user = CURRENT_USER;
      scope.displayName = function() {
        var name;
        if ( !scope.taxon ) { return; }
        if ( scope.user && scope.user.prefers_scientific_name_first ) {
          name = scope.taxon.name;
        } else if ( scope.taxon.preferred_common_name ) {
          name = iNatModels.Taxon.titleCaseName( scope.taxon.preferred_common_name );
        }
        return name || scope.taxon.name;
      }
      scope.secondaryName = function() {
        var name;
        if ( !scope.taxon ) { return; }
        if ( scope.user && scope.user.prefers_scientific_name_first ) {
          name = iNatModels.Taxon.titleCaseName( scope.taxon.preferred_common_name );
        } else if ( scope.taxon.preferred_common_name ) {
          name = scope.taxon.name;
        }
        return name;
      }
      scope.showRank = function() {
        return scope.taxon && scope.taxon.rank_level > 10;
      }
    },
    templateUrl: 'ang/templates/shared/taxon.html'
  }
}]);

iNatAPI.directive( "observationSnippet", [ "shared", function( shared ) {
  return {
    scope: { o: "=" },
    link: function( scope ) {
      scope.shared = shared;
    },
    templateUrl: "ang/templates/shared/observation.html"
  };
}]);

iNatAPI.directive( "userIcon", [ "shared", function( shared ) {
  return {
    scope: { u: "=" },
    link: function( scope ) {
      scope.shared = shared;
    },
    templateUrl: "ang/templates/shared/user_icon.html"
  };
}]);

iNatAPI.directive( "userLogin", [ function( ) {
  return {
    scope: { u: "=" },
    templateUrl: "ang/templates/shared/user_login.html"
  };
}]);
<commit_msg>remove seemingly unnecessary code causing issues with Google maps on obs search<commit_after>var iNatAPI = angular.module( "iNatAPI", [ ]);

iNatAPI.factory( "shared", [ "$http", "$rootScope", "$filter",
function( $http, $rootScope, $filter ) {
  var basicGet = function( url, options ) {
    options = options || { };
    if( options.cache !== true ) { options.cache = false; }
    var config = {
      cache: options.cache,
      timeout: 20000 // 20 second timeout
    };
    var apiURL = $( "meta[name='config:inaturalist_api_url']" ).attr( "content" );
    if ( apiURL && url.indexOf( apiURL ) >= 0 ) {
      var apiToken = $( "meta[name='inaturalist-api-token']" ).attr( "content" );
      if ( apiToken ) {
        config.headers = {
          Authorization: apiToken
        }
      }
    }
    return $http.get( url, config ).then(
      function( response ) {
        return response;
      }, function( errorResponse ) {
        // Handle error case
      }
    );
  };

  var numberWithCommas = function( num ) {
    if( !_.isNumber( num ) ) { return num; }
    return I18n.toNumber( num, { precision: 0 } );
  };

  var t = function( k, options ) {
    options = options || { };
    return I18n.t( k, options );
  };

  var taxonStatusTitle = function( taxon ) {
    if( !taxon.conservation_status ) { return; }
    var title = $filter( "capitalize" )( taxon.conservationStatus( ), "title" );
    if( taxon.conservation_status && taxon.conservation_status.place ) {
      title = t( "status_in_place", {
        status: title, place: taxon.conservation_status.place.display_name });
    } else {
      title = t( "status_globally", { status: title });
    }
    return title;
  };

  var taxonMeansTitle = function( taxon ) {
    if( !taxon.establishment_means ) { return; }
    var title = $filter( "capitalize" )(
      t( taxon.establishment_means.establishment_means ), "title" );
    if( taxon.establishment_means && taxon.establishment_means.place ) {
      title = t( "status_in_place", {
        status: $filter( "capitalize" )(
          t( taxon.establishment_means.establishment_means, { locale: "en" }), "title" ),
        place: taxon.establishment_means.place.display_name });
    }
    return title;
  };

  var backgroundIf = function( url ) {
    if( url ) {
      return { "background-image": "url('" + url + "')" };
    }
  };

  var offsetCenter = function( options, callback ) {
    if( !options.map ) { return callback( ); }
    var overlay = new google.maps.OverlayView( );
    overlay.draw = function( ) { };
    overlay.setMap( options.map );
    var proj = overlay.getProjection( );
    var currentCenter = options.map.getCenter( );
    if( !proj ) {
      options.attempts = options.attempts || 0;
      options.attempts += 1;
      if( options.attempts >= 10 ) { return callback( currentCenter ); }
      setTimeout( function( ) {
        offsetCenter( options, callback );
      }, 5);
      return;
    }
    var cPoint = proj.fromLatLngToDivPixel( currentCenter );
    cPoint.x = cPoint.x + options.left; // left of center
    cPoint.y = cPoint.y + options.up; // north of center
    var newCenter = proj.fromDivPixelToLatLng( cPoint );
    callback( newCenter );
  };

  var processPoints = function( geometry, callback, thisArg ) {
    if( !geometry ) { return; }
    if( geometry instanceof google.maps.LatLng ) {
      callback.call( thisArg, geometry );
    } else if( geometry instanceof google.maps.Data.Point ) {
      callback.call( thisArg, geometry.get( ) );
    } else {
      geometry.getArray( ).forEach( function( g ) {
        processPoints( g, callback, thisArg );
      });
    }
  };

  var stringStartsWith = function( str, pattern, position ) {
    position = _.isNumber( position ) ? position : 0;
    // We use `lastIndexOf` instead of `indexOf` to avoid tying execution
    // time to string length when string doesn't start with pattern.
    return str.toLowerCase( ).lastIndexOf( pattern.toLowerCase( ), position ) === position;
  };

  var pp = function( obj ) {
    console.log( JSON.stringify( obj, null, "  " ) );
  };

  return {
    basicGet: basicGet,
    numberWithCommas: numberWithCommas,
    t: t,
    taxonStatusTitle: taxonStatusTitle,
    taxonMeansTitle: taxonMeansTitle,
    backgroundIf: backgroundIf,
    offsetCenter: offsetCenter,
    processPoints: processPoints,
    stringStartsWith: stringStartsWith,
    pp: pp
  }
}]);

// prints a date like "Today 12:34 PM" with some stylable wrapper elements
iNatAPI.directive('inatCalendarDate', ["shared", function(shared) {
  return {
    scope: {
      time: "=",
      date: "=",
      timezone: "="
    },
    link: function(scope, elt, attr) {
      scope.dateString = function() {
        if( !scope.date ) {
          return shared.t('unknown');
        }
        var date = moment(scope.date),
            now = moment(new Date()),
            dateString;
        if (date.isSame(now, 'day')) {
          dateString = I18n.t('today');
        } else if (date.isSame(now.subtract(1, 'day'), 'day')) {
          dateString = I18n.t('yesterday');
        } else {
          dateString = date.format('ll');
        }
        return dateString;
      }
      scope.timeString = function() {
        if( !scope.time ) { return; }
        scope.timezone = scope.timezone || "UTC";
        return moment(scope.time).tz(scope.timezone).format("LT z");
      }
    },
    template: '{{ dateString() }}{{ timeString() }}'
  }
}]);

// print a taxon with correctly formatted common and scientific names
iNatAPI.directive('inatTaxon', ["shared", function(shared) {
  return {
    scope: {
      taxon: '=',
      url: '@'
    },
    link: function(scope, elt, attr) {
      scope.iconicTaxonNameForID = function(iconicTaxonID) {
        var t = window.ICONIC_TAXA[iconicTaxonID]
        if (t) {
          return t.name;
        } else {
          return 'Unknown'
        }
      };
      scope.shared = shared;
      scope.user = CURRENT_USER;
      scope.displayName = function() {
        var name;
        if ( !scope.taxon ) { return; }
        if ( scope.user && scope.user.prefers_scientific_name_first ) {
          name = scope.taxon.name;
        } else if ( scope.taxon.preferred_common_name ) {
          name = iNatModels.Taxon.titleCaseName( scope.taxon.preferred_common_name );
        }
        return name || scope.taxon.name;
      }
      scope.secondaryName = function() {
        var name;
        if ( !scope.taxon ) { return; }
        if ( scope.user && scope.user.prefers_scientific_name_first ) {
          name = iNatModels.Taxon.titleCaseName( scope.taxon.preferred_common_name );
        } else if ( scope.taxon.preferred_common_name ) {
          name = scope.taxon.name;
        }
        return name;
      }
      scope.showRank = function() {
        return scope.taxon && scope.taxon.rank_level > 10;
      }
    },
    templateUrl: 'ang/templates/shared/taxon.html'
  }
}]);

iNatAPI.directive( "observationSnippet", [ "shared", function( shared ) {
  return {
    scope: { o: "=" },
    link: function( scope ) {
      scope.shared = shared;
    },
    templateUrl: "ang/templates/shared/observation.html"
  };
}]);

iNatAPI.directive( "userIcon", [ "shared", function( shared ) {
  return {
    scope: { u: "=" },
    link: function( scope ) {
      scope.shared = shared;
    },
    templateUrl: "ang/templates/shared/user_icon.html"
  };
}]);

iNatAPI.directive( "userLogin", [ function( ) {
  return {
    scope: { u: "=" },
    templateUrl: "ang/templates/shared/user_login.html"
  };
}]);
<|endoftext|>


<commit_before>import React from 'react';
var PieChart = require('react-chartjs').Pie;

export default React.createClass({
  getInitialState: function () {
    var stats = this.props.user || [];

    var chartDataCount = [
      {
        value: Math.floor(stats.total_road_count_add),
        color: '#F9E698',
        highlight: '#F7EEC1',
        label: 'Roads'
      },
      {
        value: Math.floor(stats.total_waterway_count_add),
        color: '#91B7FF',
        highlight: '#BDD4FF',
        label: 'Waterways'
      },
      {
        value: Math.floor(stats.total_building_count_add),
        color: '#FFA3A2',
        highlight: '#FFC6C5',
        label: 'Buildings'
      },
      {
        value: Math.floor(stats.total_poi_count_add),
        color: '#C6EAA7',
        highlight: '#DDEDCE',
        label: 'Points of Interest'
      }
    ];
    var chartDataDist = [
      {
        value: Math.floor(stats.total_road_km_add),
        color: '#E1E300',
        highlight: '#E8EA6B',
        label: 'Roads'
      },
      {
        value: Math.floor(stats.total_waterway_count_add),
        color: '#91B7FF',
        highlight: '#BDD4FF',
        label: 'Waterways'
      },
      {
        value: 0,
        color: '#BEBFBF',
        highlight: '#D2D3D3',
        label: 'Buildings'
      },
      {
        value: 0,
        color: '#FFA3A2',
        highlight: '#FFC6C5',
        label: 'Points of Interest'
      }
    ];
    return {
      chartOptions: {
        animationSteps: 50,
        animationEasing: 'easeOutQuart'
      },
      chartData: chartDataCount,
      chartDataCount: chartDataCount,
      chartDataDist: chartDataDist
    };
  },
  loadDist: function () {
    this.setState({
      chartData: this.state.chartDataDist
    });
  },
  loadCounts: function () {
    this.setState({
      chartData: this.state.chartDataCount
    });
  },

  render: function () {
    return

        <PieChart data={this.state.chartData} options={this.state.chartOptions} width='250' height='155' />

        <input type="button" onClick={this.loadCounts} value="By Quantity" />
        <input type="button" onClick={this.loadDist} value="By Distance" />

;
  }
});
<commit_msg>Greyscale pie chart<commit_after>import React from 'react';
var PieChart = require('react-chartjs').Pie;

export default React.createClass({
  getInitialState: function () {
    var stats = this.props.user || [];

    var chartDataCount = [
      {
        value: Math.floor(stats.total_road_count_add),
        color: '#eaeaea',
        highlight: '#f2f2f2',
        label: 'Roads'
      },
      {
        value: Math.floor(stats.total_waterway_count_add),
        color: '#cccccc',
        highlight: '#dddddd',
        label: 'Waterways'
      },
      {
        value: Math.floor(stats.total_building_count_add),
        color: '#969696',
        highlight: '#aaaaaa',
        label: 'Buildings'
      },
      {
        value: Math.floor(stats.total_poi_count_add),
        color: '#6b6b6b',
        highlight: '#8e8e8e',
        label: 'Points of Interest'
      }
    ];
    var chartDataDist = [
      {
        value: Math.floor(stats.total_road_km_add),
        color: '##f7f7f7',
        highlight: '#E8EA6B',
        label: 'Roads'
      },
      {
        value: Math.floor(stats.total_waterway_count_add),
        color: '#cccccc',
        highlight: '#BDD4FF',
        label: 'Waterways'
      },
      {
        value: 0,
        color: '#969696',
        highlight: '#D2D3D3',
        label: 'Buildings'
      },
      {
        value: 0,
        color: '#525252',
        highlight: '#FFC6C5',
        label: 'Points of Interest'
      }
    ];
    return {
      chartOptions: {
        animationSteps: 50,
        animationEasing: 'easeOutQuart'
      },
      chartData: chartDataCount,
      chartDataCount: chartDataCount,
      chartDataDist: chartDataDist
    };
  },
  loadDist: function () {
    this.setState({
      chartData: this.state.chartDataDist
    });
  },
  loadCounts: function () {
    this.setState({
      chartData: this.state.chartDataCount
    });
  },

  render: function () {
    return

        <PieChart data={this.state.chartData} options={this.state.chartOptions} width='250' height='155' />

        <input type="button" onClick={this.loadCounts} value="By Quantity" />
        <input type="button" onClick={this.loadDist} value="By Distance" />

;
  }
});
<|endoftext|>


<commit_before>import bunyan from 'bunyan';
import chalk from 'chalk';
import moment from 'moment';
import nconf from 'nconf';
import R from 'ramda';

const production = (nconf.get('NODE_ENV') === 'production');
const config = {name: 'gravebot'};
if (nconf.get('SHARDING') && nconf.get('SHARD_NUMBER')) config.shard_number = nconf.get('SHARD_NUMBER');
const logger = bunyan.createLogger(config);

function _submitToLogger(type, msg) {
  if (R.is(Object, msg)) return logger[type](msg, msg.message || '');
  return logger[type](msg);
}

function cmd(cmd, suffix) {
  if (production) return logger.info({cmd, suffix}, 'cmd');
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.bold.green('[COMMAND]'), chalk.bold.green(cmd), suffix);
}

function info(msg) {
  if (production) return _submitToLogger('info', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), msg);
}

function warn(msg) {
  if (production) return _submitToLogger('warn', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.yellow(`[WARN] ${msg}`));
}

function error(msg) {
  if (production) return _submitToLogger('error', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.red(`[ERROR] ${msg}`));
}

export default {cmd, info, warn, error};
<commit_msg>bot name<commit_after>import bunyan from 'bunyan';
import chalk from 'chalk';
import moment from 'moment';
import nconf from 'nconf';
import R from 'ramda';

const production = (nconf.get('NODE_ENV') === 'production');
const config = {name: 'stratsbot'};
if (nconf.get('SHARDING') && nconf.get('SHARD_NUMBER')) config.shard_number = nconf.get('SHARD_NUMBER');
const logger = bunyan.createLogger(config);

function _submitToLogger(type, msg) {
  if (R.is(Object, msg)) return logger[type](msg, msg.message || '');
  return logger[type](msg);
}

function cmd(cmd, suffix) {
  if (production) return logger.info({cmd, suffix}, 'cmd');
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.bold.green('[COMMAND]'), chalk.bold.green(cmd), suffix);
}

function info(msg) {
  if (production) return _submitToLogger('info', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), msg);
}

function warn(msg) {
  if (production) return _submitToLogger('warn', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.yellow(`[WARN] ${msg}`));
}

function error(msg) {
  if (production) return _submitToLogger('error', msg);
  console.log(chalk.cyan(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.red(`[ERROR] ${msg}`));
}

export default {cmd, info, warn, error};
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/sl-chart';

/**
 * @module
 * @augments ember/Component
 */
export default Ember.Component.extend({

    // -------------------------------------------------------------------------
    // Dependencies

    // -------------------------------------------------------------------------
    // Attributes

    /** @type {String[]} */
    classNameBindings: [
        'isLoading:sl-loading'
    ],

    /** @type {String[]} */
    classNames: [
        'panel',
        'panel-default',
        'sl-chart',
        'sl-panel'
    ],

    /** @type {Object} */
    layout,

    // -------------------------------------------------------------------------
    // Actions

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

    // -------------------------------------------------------------------------
    // Properties

    /**
     * The highchart instantiation
     *
     * @type {?Object}
     */
    chart: null,

    /**
     * Height value used for inline style
     *
     * @type {String}
     */
    height: 'auto',

    /**
     * When true, the chart's panel body will be in a loading state
     *
     * @type {Boolean}
     */
    isLoading: false,

    /**
     * The collection of series data for the chart
     *
     * @type {?Object[]}
     */
    series: null,

    /**
     * Width value used for inline style
     *
     * @type {Number|String}
     */
    width: 'auto',

    // -------------------------------------------------------------------------
    // Observers

    /**
     * Check passed parameters on initialization
     *
     * @function
     * @throws {ember.assert} 'Series property must be an array'
     * @throws {ember.assert} 'Options property must be an Object'
     * @returns {undefined}
     */
    initialize: Ember.on(
        'init',
        function() {
            Ember.assert(
                'Series property must be an array',
                'array' === Ember.typeOf( this.get( 'series' ) )
            );
            Ember.assert(
                'Options property must be an Object',
                'instance' === Ember.typeOf( this.get( 'options' ) ) ||
                'object' === Ember.typeOf ( this.get( 'options' ) )
            );
        }
    ),

    /**
     * Sets up Highcharts initialization
     *
     * @function
     * @returns {undefined}
     */
    setupChart: Ember.on(
        'didInsertElement',
        function() {
            let chartDiv = this.$( 'div.chart' );

            chartDiv.highcharts( this.get( 'highchartsOptions' ) );
            this.set( 'chart', chartDiv.highcharts() );
            this.updateData();
        }
    ),

    /**
     * Updates the chart's series data
     *
     * @function
     * @returns {undefined}
     */
    updateData: Ember.observer(
        'series',
        function() {
            let chart = this.get( 'chart' );
            let series = this.get( 'series' );

            if ( !chart.hasOwnProperty( 'series' ) ) {
                chart.series = [];
            }

            for ( let i = 0; i < series.length; i++ ) {
                if ( chart.series.length <= i ) {
                    chart.addSeries( series[ i ] );
                } else {
                    chart.series[ i ].setData( series[ i ].data );
                }
            }
        }
    ),

    // -------------------------------------------------------------------------
    // Methods

    /**
     * Options for Highcharts
     *
     * @function
     * @returns {Object}
     */
     highchartsOptions: Ember.computed(
        'options',
        function() {
            let chartStyle = {
                fontFamily: '"Benton Sans", "Helvetica Neue", Helvetica, Arial, sans-serif',
                fontSize: '13px'
            };

            let options = Ember.$.extend( true, {
                chart: {
                    animation: false,
                    backgroundColor: 'rgba(255, 255, 255, 0)',
                    style: chartStyle
                },
                colors: [
                    '#298fce',
                    '#94302e',
                    '#00a14b',
                    '#f29c1e',
                    '#fadb00',
                    '#34495d'
                ],
                credits: {
                    enabled: false
                },
                legend: {
                    itemStyle: chartStyle
                },
                plotOptions: {
                    bar: {
                        borderColor: 'transparent'
                    },
                    series: {
                        animation: false
                    }
                },
                tooltip: {
                    animation: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    borderWidth: 0,
                    shadow: false,
                    style: {
                        color: '#fff'
                    }
                },
                xAxis: {
                    labels: {
                        style: chartStyle
                    }
                },
                yAxis: {
                    labels: {
                        style: chartStyle
                    }
                }
            }, this.get( 'options' ) || {} );

            // Title property in options must be kept null in order to suppress its default behavior for our specific usage.
            options.title = null;

            return options;
        }
    ),

    /**
     * Inline style containing height and width, required by Highcharts
     *
     * @function
     * @returns {String}
     */
    style: Ember.computed(
        'height',
        'width',
        function() {
            let height = this.get( 'height' );
            let width = this.get( 'width' );

            return Ember.String.htmlSafe( `height: ${height}; width: ${width};` );
        }
    )

});
<commit_msg>got rid of apostrophes in init doc block<commit_after>import Ember from 'ember';
import layout from '../templates/components/sl-chart';

/**
 * @module
 * @augments ember/Component
 */
export default Ember.Component.extend({

    // -------------------------------------------------------------------------
    // Dependencies

    // -------------------------------------------------------------------------
    // Attributes

    /** @type {String[]} */
    classNameBindings: [
        'isLoading:sl-loading'
    ],

    /** @type {String[]} */
    classNames: [
        'panel',
        'panel-default',
        'sl-chart',
        'sl-panel'
    ],

    /** @type {Object} */
    layout,

    // -------------------------------------------------------------------------
    // Actions

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

    // -------------------------------------------------------------------------
    // Properties

    /**
     * The highchart instantiation
     *
     * @type {?Object}
     */
    chart: null,

    /**
     * Height value used for inline style
     *
     * @type {String}
     */
    height: 'auto',

    /**
     * When true, the chart's panel body will be in a loading state
     *
     * @type {Boolean}
     */
    isLoading: false,

    /**
     * The collection of series data for the chart
     *
     * @type {?Object[]}
     */
    series: null,

    /**
     * Width value used for inline style
     *
     * @type {Number|String}
     */
    width: 'auto',

    // -------------------------------------------------------------------------
    // Observers

    /**
     * Check passed parameters on initialization
     *
     * @function
     * @throws {ember.assert} Series property must be an Array
     * @throws {ember.assert} Options property must be an Object
     * @returns {undefined}
     */
    initialize: Ember.on(
        'init',
        function() {
            Ember.assert(
                'Series property must be an array',
                'array' === Ember.typeOf( this.get( 'series' ) )
            );
            Ember.assert(
                'Options property must be an Object',
                'instance' === Ember.typeOf( this.get( 'options' ) ) ||
                'object' === Ember.typeOf ( this.get( 'options' ) )
            );
        }
    ),

    /**
     * Sets up Highcharts initialization
     *
     * @function
     * @returns {undefined}
     */
    setupChart: Ember.on(
        'didInsertElement',
        function() {
            let chartDiv = this.$( 'div.chart' );

            chartDiv.highcharts( this.get( 'highchartsOptions' ) );
            this.set( 'chart', chartDiv.highcharts() );
            this.updateData();
        }
    ),

    /**
     * Updates the chart's series data
     *
     * @function
     * @returns {undefined}
     */
    updateData: Ember.observer(
        'series',
        function() {
            let chart = this.get( 'chart' );
            let series = this.get( 'series' );

            if ( !chart.hasOwnProperty( 'series' ) ) {
                chart.series = [];
            }

            for ( let i = 0; i < series.length; i++ ) {
                if ( chart.series.length <= i ) {
                    chart.addSeries( series[ i ] );
                } else {
                    chart.series[ i ].setData( series[ i ].data );
                }
            }
        }
    ),

    // -------------------------------------------------------------------------
    // Methods

    /**
     * Options for Highcharts
     *
     * @function
     * @returns {Object}
     */
     highchartsOptions: Ember.computed(
        'options',
        function() {
            let chartStyle = {
                fontFamily: '"Benton Sans", "Helvetica Neue", Helvetica, Arial, sans-serif',
                fontSize: '13px'
            };

            let options = Ember.$.extend( true, {
                chart: {
                    animation: false,
                    backgroundColor: 'rgba(255, 255, 255, 0)',
                    style: chartStyle
                },
                colors: [
                    '#298fce',
                    '#94302e',
                    '#00a14b',
                    '#f29c1e',
                    '#fadb00',
                    '#34495d'
                ],
                credits: {
                    enabled: false
                },
                legend: {
                    itemStyle: chartStyle
                },
                plotOptions: {
                    bar: {
                        borderColor: 'transparent'
                    },
                    series: {
                        animation: false
                    }
                },
                tooltip: {
                    animation: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    borderWidth: 0,
                    shadow: false,
                    style: {
                        color: '#fff'
                    }
                },
                xAxis: {
                    labels: {
                        style: chartStyle
                    }
                },
                yAxis: {
                    labels: {
                        style: chartStyle
                    }
                }
            }, this.get( 'options' ) || {} );

            // Title property in options must be kept null in order to suppress its default behavior for our specific usage.
            options.title = null;

            return options;
        }
    ),

    /**
     * Inline style containing height and width, required by Highcharts
     *
     * @function
     * @returns {String}
     */
    style: Ember.computed(
        'height',
        'width',
        function() {
            let height = this.get( 'height' );
            let width = this.get( 'width' );

            return Ember.String.htmlSafe( `height: ${height}; width: ${width};` );
        }
    )

});
<|endoftext|>


<commit_before>'use strict';

var config = require('./config.json'),
    winston = require('winston'),
    moment = require('moment');

if (config.logger.enable) {
    var logger = new (winston.Logger)({
        transports: [
            new (winston.transports.Console)({
                colorize: true,
                timestamp: function () {
                    return moment().format("D MMM HH:MM:ss")
                },
                handleExceptions: true,
                humanReadableUnhandledException: true
            })
        ]
    });
}

if (config.logger.graylog2.enable) {
    logger.add(require('winston-graylog2'), {
        name: 'Chat',
        handleExceptions: true,
        graylog: {
            //TODO: put the facility in config
            facility: 'NodeJS Chat App',
            servers: [{
                host: config.logger.graylog2.host,
                port: config.logger.graylog2.port
            }]
        }
    });
    logger.info('Using graylog2');
}

exports.log = function (msg, meta) {
    if (!config.logger.enable) {
        return false;
    }
    if (!meta) {
        meta = {};
    }
    logger.log(msg, meta);
};

exports.info = function (msg, meta) {
    if (!config.logger.enable) {
        return false;
    }
    if (!meta) {
        meta = {};
    }
    logger.info(msg, meta);
};

exports.error = function (msg, meta) {
    if (!config.logger.enable) {
        return false;
    }
    if (!meta) {
        meta = {};
    }
    logger.error(msg, meta);
};
<commit_msg>added stringified meta to the message<commit_after>'use strict';

var config = require('./config.json'),
    winston = require('winston'),
    moment = require('moment');

if (config.logger.enable) {
    var logger = new (winston.Logger)({
        transports: [
            new (winston.transports.Console)({
                colorize: true,
                timestamp: function () {
                    return moment().format("D MMM HH:MM:ss")
                },
                handleExceptions: true,
                humanReadableUnhandledException: true
            })
        ]
    });
}

if (config.logger.graylog2.enable) {
    logger.add(require('winston-graylog2'), {
        name: 'Chat',
        handleExceptions: true,
        graylog: {
            //TODO: put the facility in config
            facility: 'NodeJS Chat App',
            servers: [{
                host: config.logger.graylog2.host,
                port: config.logger.graylog2.port
            }]
        }
    });
    logger.info('Using graylog2');
}

exports.info = function (msg, meta) {
    if (!config.logger.enable) {
        return false;
    }
    if (!meta) {
        meta = {};
    }
    logger.info(msg + JSON.stringify(meta), meta);
};

exports.error = function (msg, meta) {
    if (!config.logger.enable) {
        return false;
    }
    if (!meta) {
        meta = {};
    }
    logger.error(msg, meta);
};<|endoftext|>


<commit_before>import { Component, PropTypes, Children } from 'react'
import storeShape from '../utils/storeShape'
import warning from '../utils/warning'

let didWarnAboutReceivingStore = false
function warnAboutReceivingStore() {
  if (didWarnAboutReceivingStore) {
    return
  }
  didWarnAboutReceivingStore = true

  warning(
    '<Provider> does not support changing `store` on the fly. ' +
    'It is most likely that you see this error because you updated to ' +
    'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' +
    'automatically. See https://github.com/reactjs/react-redux/releases/' +
    'tag/v2.0.0 for the migration instructions.'
  )
}

export default class Provider extends Component {
  getChildContext() {
    return { store: this.store }
  }

  constructor(props, context) {
    super(props, context)
    this.store = props.store
  }

  render() {
    const { children } = this.props
    return Children.only(children)
  }
}

if (process.env.NODE_ENV !== 'production') {
  Provider.prototype.componentWillReceiveProps = function (nextProps) {
    const { store } = this
    const { store: nextStore } = nextProps

    if (store !== nextStore) {
      warnAboutReceivingStore()
    }
  }
}

Provider.propTypes = {
  store: storeShape.isRequired,
  children: PropTypes.element.isRequired
}
Provider.childContextTypes = {
  store: storeShape.isRequired
}
<commit_msg>Update Provider.js<commit_after>import { Component, PropTypes, Children } from 'react'
import storeShape from '../utils/storeShape'
import warning from '../utils/warning'

let didWarnAboutReceivingStore = false
function warnAboutReceivingStore() {
  if (didWarnAboutReceivingStore) {
    return
  }
  didWarnAboutReceivingStore = true

  warning(
    '<Provider> does not support changing `store` on the fly. ' +
    'It is most likely that you see this error because you updated to ' +
    'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' +
    'automatically. See https://github.com/reactjs/react-redux/releases/' +
    'tag/v2.0.0 for the migration instructions.'
  )
}

export default class Provider extends Component {
  getChildContext() {
    return { store: this.store }
  }

  constructor(props, context) {
    super(props, context)
    this.store = props.store
  }

  render() {
    return Children.only(this.props.children)
  }
}

if (process.env.NODE_ENV !== 'production') {
  Provider.prototype.componentWillReceiveProps = function (nextProps) {
    const { store } = this
    const { store: nextStore } = nextProps

    if (store !== nextStore) {
      warnAboutReceivingStore()
    }
  }
}

Provider.propTypes = {
  store: storeShape.isRequired,
  children: PropTypes.element.isRequired
}
Provider.childContextTypes = {
  store: storeShape.isRequired
}
<|endoftext|>


<commit_before>import Em from 'ember';
import Column from './column';
var ArrayProxy = Em.ArrayProxy;
var Sortable = Em.SortableMixin;

var mapColumn = function (column) {
	return Column.create({
		content: column
	});
};

var Columns = ArrayProxy.extend(Sortable, {
	arrangedContent: function () {
		return this.get('content').map(mapColumn);
	}.property('content'),
	contentArrayDidChange: function (arr, i, removedCount, addedCount) {
		var addedObjects = arr.slice(i, i + addedCount);
		addedObjects = addedObjects.map(mapColumn);
		this.get('arrangedContent').replace(i, removedCount, addedObjects);
	}
});

export default Columns;
<commit_msg>Fixed column definition bindings<commit_after>import Em from 'ember';
import Column from './column';
var ArrayProxy = Em.ArrayProxy;
var Sortable = Em.SortableMixin;

var ControllerArray = ArrayProxy.extend({
	itemController: Em.ObjectController,
	mapController: function (obj) {
		return this.itemController.create({
			content: obj
		});
	},
	arrangedContent: function () {
		return this.get('content').map(this.mapController, this);
	}.property('content'),
	contentArrayDidChange: function (arr, i, removedCount, addedCount) {
		var addedObjects = arr.slice(i, i + addedCount);
		addedObjects = addedObjects.map(this.mapController, this);
		this.get('arrangedContent').replace(i, removedCount, addedObjects);
	}
});

var Columns = ArrayProxy.extend(Sortable, {
	content: function (key, value) {
		return ControllerArray.create({
			itemController: Column,
			content: value
		});
	}.property()
});

export default Columns;
<|endoftext|>


<commit_before>'use strict';

import winston, { Logger } from 'winston';
import config from 'config';

const name = 'runtime';
const logger = winston.loggers.add(name, config.get('logger'));

export default logger;
<commit_msg>fix code<commit_after>'use strict';

import winston from 'winston';
import config from 'config';

const name = 'runtime';
const logger = winston.loggers.add(name, config.get('logger'));

export default logger;
<|endoftext|>


<commit_before>export default class Recorder {
  // Record logic API goes here
}
<commit_msg>Started on a skeleton for the recorder [HFP-969]<commit_after>export default class Recorder {
  // Record logic API goes here
  constructor() {
    this.getUserMedia = navigator.getUserMedia ||
                        navigator.webkitGetUserMedia ||
                        navigator.mozGetUserMedia;
  }

  init() {
    this.chunks = [];

    this.getUserMedia({
      audio: true
    },
    function(stream) {
      this.recorder = new MediaRecorder(stream);

      this.recorder.ondataavailable = function (event) {
        this.chunks.push(event.data);
      }

      // Need to trigger events, eg:
      // this.recorder.onstop
    },
    function(err) {
      // TODO - Trigger event here
    }
  }

  start() {
    this.recorder.start();
  }

  stop() {
    this.recorder.stop();
  }

  pause() {
    this.recorder.pause();
  }

  resume() {
    this.recorder.resume();
  }

  supported() {
    return true;
  }

  getData() {
    return this.chunks;
  }

  reset() {
    // TODO
  }
}
<|endoftext|>