<commit_before>/* jshint node: true  */
'use strict';

var async = require('async');
var util = require('util');
var path = require('path');
var fs = require('fs-extra');
var tar = require('tar-fs');
var zlib = require('zlib');
var spawn = require('child_process').spawn;
var mustache = require('mustache');
var unzip = require('node-unzip-2');
var _ = require('underscore');
var tmp = require('tmp');
tmp.setGracefulCleanup();

var ziputils = require('./ziputils');

var DeploymentDelay = 60
var ProxyBase = 'apiproxy';

module.exports.createApiProxy = function(opts, request, done) {
  // Create a dummy "API proxy" file for the root of this thing.
  var rootDoc = mustache.render('<APIProxy name="{{api}}"/>', opts);
  var rootEntryName = opts.api + '.xml';

  var uri = util.format('%s/v1/o/%s/apis?action=import&validate=false&name=%s',
                        opts.baseuri, opts.organization, opts.api);
  if (opts.debug) {
    console.log('Calling %s', uri);
  }
  if (opts.verbose) {
    console.log('Creating revision %d of API %s', opts.deploymentVersion,
               opts.api);
  }
  // The only way to do this is to import a ZIP. What fun.
  var zipBuf = ziputils.makeOneFileZip(ProxyBase, rootEntryName, rootDoc);
  // For debugging
  //fs.writeFileSync('./test.zip', zipBuf);
  request({
    uri: uri,
    headers: { 'Content-Type': 'application/octet-stream' },
    json: false,
    method: 'POST',
    body: zipBuf
  }, function(err, req, body) {
    proxyCreationDone(err, req, body, opts, done);
  });
}

module.exports.createProxy = function(opts, request, done) {
  var vhostStr = (opts.virtualhosts ? opts.virtualhosts : 'default,secure');
  // Create an array of objects for underscore
  var vhosts = _.map(vhostStr.split(','), function(i) {
    return { name: i };
  });

  var basepath = (opts['base-path'] ? opts['base-path'] : '/');

  var targetDoc = mustache.render(
    '<ProxyEndpoint name="default">' +
    '<PreFlow name="PreFlow"/>' +
    '<PostFlow name="PostFlow"/>' +
    '<HTTPProxyConnection>' +
    '<BasePath>{{basepath}}</BasePath>' +
    '{{#vhosts}}<VirtualHost>{{name}}</VirtualHost>{{/vhosts}}' +
    '</HTTPProxyConnection>' +
    '<RouteRule name="default">' +
    '<TargetEndpoint>default</TargetEndpoint>' +
    '</RouteRule>' +
    '</ProxyEndpoint>', {
      vhosts: vhosts,
      basepath: basepath
    });
  if (opts.debug) {
    console.log('vhosts = %j', vhosts);
    console.log('proxy = %s', targetDoc);
  }

  var uri = util.format('%s/v1/o/%s/apis/%s/revisions/%d/proxies?name=default',
              opts.baseuri, opts.organization, opts.api,
              opts.deploymentVersion);
  if (opts.verbose) {
    console.log('Creating the proxy endpoint');
  }

  request({
    uri: uri,
    method: 'POST',
    json: false,
    headers: { 'Content-Type': 'application/xml' },
    body: targetDoc
  }, function(err, req, body) {
    handleUploadResult(err, req, 'proxies/default.xml', done);
  });
}

module.exports.deployProxy = function(opts, request, done) {
  if (opts['import-only']) {
    if (opts.verbose) {
      console.log('Not deploying the proxy right now');
    }
    done();
    return;
  }

  if (opts.verbose) {
    console.log('Deploying revision %d of %s to %s', opts.deploymentVersion,
                opts.api, opts.environments);
  }

  var environments = opts.environments.split(',');

  function deployToEnvironment(environment, done) {

    var uri = util.format('%s/v1/o/%s/e/%s/apis/%s/revisions/%d/deployments',
      opts.baseuri, opts.organization, environment, opts.api,
      opts.deploymentVersion);

    if (opts.debug) { console.log('Going to POST to %s', uri); }

    // Unlike "deployproxy" command, ignore the base path here, because we baked it into the proxy definition.
    var deployCmd = util.format('action=deploy&override=true&delay=%d', DeploymentDelay);

    if (opts.debug) { console.log('Going go send command %s', deployCmd); }

    request({
      uri: uri,
      method: 'POST',
      json: false,
      body: deployCmd,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      }
    }, function(err, req, body) {
      if (err) { return done(err); }

      var jsonBody = (body ? JSON.parse(body) : null);

      if (req.statusCode === 200) {
        if (opts.verbose) { console.log('Deployment on %s successful', environment); }
        if (opts.debug) { console.log('%s', body); }
        return done(undefined, jsonBody);
      }

      if (opts.verbose) { console.error('Deployment on %s result: %j', environment, body); }
      var errMsg;
      if (jsonBody && (jsonBody.message)) {
        errMsg = jsonBody.message;
      } else {
        errMsg = util.format('Deployment on %s failed with status code %d', environment, req.statusCode);
      }
      done(new Error(errMsg));
    });
  }

  var tasks = {};
  environments.forEach(function(env) {
    tasks[env] = deployToEnvironment.bind(this, env);
  });

  async.parallel(tasks, done);
}

module.exports.unzipProxy = function(opts, destDir, ignoreDir, cb) {

    if (opts.debug) { console.log('Extracting proxy to', destDir); }

    var count = 1;
    var called = false;
    function done(err) {
      if (!called) {
        count--;
        if (err || count === 0) { cb(err); }
      }
    }

    fs.createReadStream(opts.file)
      .pipe(unzip.Parse())
      .on('error', done)
      .on('close', done)
      .on('entry', function (entry) {
        if (entry.path.indexOf(ignoreDir) === 0) {
          if (opts.debug) { console.log('skipping', entry.path); }
          entry.autodrain(); // ignore all hosted resources
        } else {
          count++;
          if (opts.debug) { console.log('extracting', entry.path); }
          var destFile = path.resolve(destDir, entry.path);
          mkdirs(path.dirname(destFile), function(err) {
            if (err) { return cb(err); }

            entry
              .pipe(fs.createWriteStream(destFile))
              .on('error', done)
              .on('close', done);
          });
        }
      });
  }

module.exports.handleUploadResult = handleUploadResult;

function handleUploadResult(err, req, fileName, itemDone) {
  if (err) {
    itemDone(err);
  } else if ((req.statusCode === 200) || (req.statusCode === 201)) {
    itemDone();
  } else {
    itemDone(new Error(util.format('Error uploading resource %s: %d\n%s',
      fileName, req.statusCode, req.body)));
  }
}

function mkdirs(dirpath, cb) {

  var parts = dirpath.split(path.sep);
  var start = 1;
  if (dirpath[0] === path.sep) {
  parts[0] = '/';
  start = 2;
  }
  for (var i = start; i <= parts.length; i++) {
  try {
      var dir = path.join.apply(null, parts.slice(0, i));
      fs.mkdirSync(dir);
  } catch (err) {
      if (err.code !== 'EEXIST') { return cb(err); }
  }
  }
  cb();
}

module.exports.copyFile = function(source, target, cb) {

    mkdirs(path.dirname(target), function(err) {
    if (err) { return cb(err); }

    cb = _.once(cb);
    var wr = fs.createWriteStream(target)
        .on('error', cb)
        .on('close', cb);
    fs.createReadStream(source)
        .pipe(wr)
        .on('error', cb);
    });
}

module.exports.uploadSource = function(sourceDir, type, opts, request, done) {
// Get a list of entries, broken down by which are directories
  ziputils.enumerateDirectory(sourceDir, type, opts.remoteNpm, function(err, entries) {
    if (err) { return done(err); }

    if (opts.debug) { console.log('Directories to upload: %j', entries); }

    async.eachLimit(entries, opts.asynclimit, function(entry, entryDone) {
      var uri =
        util.format('%s/v1/o/%s/apis/%s/revisions/%d/resources?type=%s&name=%s',
          opts.baseuri, opts.organization, opts.api,
          opts.deploymentVersion, type, entry.resourceName);
      if (entry.directory) {
        // ZIP up all directories, possibly with additional file prefixes
        ziputils.zipDirectory(entry.fileName, entry.zipEntryName, function(err, zipBuf) {
          if (err) {
            entryDone(err);
          } else {
            if (opts.verbose) {
              console.log('Uploading resource %s of size %d',  entry.resourceName, zipBuf.length);
            }
            request({
              uri: uri,
              method: 'POST',
              json: false,
              headers: { 'Content-Type': 'application/octet-stream' },
              body: zipBuf
            }, function(err, req, body) {
              handleUploadResult(err, req, entry.fileName, entryDone);
            });
          }
        });

      } else {
        if (opts.verbose) {
          console.log('Uploading resource %s', entry.resourceName);
        }
        var httpReq = request({
          uri: uri,
          method: 'POST',
          json: false,
          headers: { 'Content-Type': 'application/octet-stream' }
        }, function(err, req, body) {
          handleUploadResult(err, req, entry.fileName, entryDone);
        });

        var fileStream = fs.createReadStream(entry.fileName);
        fileStream.pipe(httpReq);
      }
    }, function(err) {
      done(err);
    });
  });
}

module.exports.usePackedSource = function(sourceDir, opts, cb) {
  if (opts.debug) {
    console.log('packaging bundled dependencies for upload')
  }

  tmp.dir(function(err, tempDir) {
    if (err) {
      return cb(err);
    }

    fs.copy(sourceDir, tempDir, function(err) {
      if (err) {
        return cb(err)
      }

      var packageName;
      var pack = spawn('npm', ['pack'], {cwd: tempDir});
      pack.on('error', function(err) {
        return cb(err)
      });

      pack.stdout.on('data', function(data) {
        packageName = data.toString().trim()
      });

      pack.on('close', function() {
        try {
          var packageArchive =  path.join(tempDir, packageName);
          fs.createReadStream(packageArchive).pipe(zlib.createGunzip()).pipe(tar.extract(tempDir)).on('finish', function() {
            fs.removeSync(packageArchive) // remove the pack archive so it doesn't show up in the proxy

            if (opts.debug) {
              console.log('bundled dependencies ready for upload')
            }

            // return path to packed directory
            return cb(undefined, path.join(tempDir, 'package'))
          }).on('error', function(err) {
            return cb(err);
          });
        } catch(err) {
          return cb(err)
        }
      });
    });
  });
}

function proxyCreationDone (err, req, body, opts, done) {
  if (err) {
    done(err);
  } else if ((req.statusCode === 200) || (req.statusCode === 201)) {
    done();
  } else {
    if (opts.verbose) {
      console.error('Proxy creation error:', body);
    }
    done(new Error(util.format('Proxy creation failed. Status code %d',
                   req.statusCode)));
  }
}<commit_msg>Fix --bundled-dependencies support on Windows<commit_after>/* jshint node: true  */
'use strict';

var async = require('async');
var util = require('util');
var path = require('path');
var fs = require('fs-extra');
var tar = require('tar-fs');
var zlib = require('zlib');
var spawn = require('child_process').spawn;
var mustache = require('mustache');
var unzip = require('node-unzip-2');
var _ = require('underscore');
var tmp = require('tmp');
tmp.setGracefulCleanup();

var ziputils = require('./ziputils');

var DeploymentDelay = 60
var ProxyBase = 'apiproxy';

module.exports.createApiProxy = function(opts, request, done) {
  // Create a dummy "API proxy" file for the root of this thing.
  var rootDoc = mustache.render('<APIProxy name="{{api}}"/>', opts);
  var rootEntryName = opts.api + '.xml';

  var uri = util.format('%s/v1/o/%s/apis?action=import&validate=false&name=%s',
                        opts.baseuri, opts.organization, opts.api);
  if (opts.debug) {
    console.log('Calling %s', uri);
  }
  if (opts.verbose) {
    console.log('Creating revision %d of API %s', opts.deploymentVersion,
               opts.api);
  }
  // The only way to do this is to import a ZIP. What fun.
  var zipBuf = ziputils.makeOneFileZip(ProxyBase, rootEntryName, rootDoc);
  // For debugging
  //fs.writeFileSync('./test.zip', zipBuf);
  request({
    uri: uri,
    headers: { 'Content-Type': 'application/octet-stream' },
    json: false,
    method: 'POST',
    body: zipBuf
  }, function(err, req, body) {
    proxyCreationDone(err, req, body, opts, done);
  });
}

module.exports.createProxy = function(opts, request, done) {
  var vhostStr = (opts.virtualhosts ? opts.virtualhosts : 'default,secure');
  // Create an array of objects for underscore
  var vhosts = _.map(vhostStr.split(','), function(i) {
    return { name: i };
  });

  var basepath = (opts['base-path'] ? opts['base-path'] : '/');

  var targetDoc = mustache.render(
    '<ProxyEndpoint name="default">' +
    '<PreFlow name="PreFlow"/>' +
    '<PostFlow name="PostFlow"/>' +
    '<HTTPProxyConnection>' +
    '<BasePath>{{basepath}}</BasePath>' +
    '{{#vhosts}}<VirtualHost>{{name}}</VirtualHost>{{/vhosts}}' +
    '</HTTPProxyConnection>' +
    '<RouteRule name="default">' +
    '<TargetEndpoint>default</TargetEndpoint>' +
    '</RouteRule>' +
    '</ProxyEndpoint>', {
      vhosts: vhosts,
      basepath: basepath
    });
  if (opts.debug) {
    console.log('vhosts = %j', vhosts);
    console.log('proxy = %s', targetDoc);
  }

  var uri = util.format('%s/v1/o/%s/apis/%s/revisions/%d/proxies?name=default',
              opts.baseuri, opts.organization, opts.api,
              opts.deploymentVersion);
  if (opts.verbose) {
    console.log('Creating the proxy endpoint');
  }

  request({
    uri: uri,
    method: 'POST',
    json: false,
    headers: { 'Content-Type': 'application/xml' },
    body: targetDoc
  }, function(err, req, body) {
    handleUploadResult(err, req, 'proxies/default.xml', done);
  });
}

module.exports.deployProxy = function(opts, request, done) {
  if (opts['import-only']) {
    if (opts.verbose) {
      console.log('Not deploying the proxy right now');
    }
    done();
    return;
  }

  if (opts.verbose) {
    console.log('Deploying revision %d of %s to %s', opts.deploymentVersion,
                opts.api, opts.environments);
  }

  var environments = opts.environments.split(',');

  function deployToEnvironment(environment, done) {

    var uri = util.format('%s/v1/o/%s/e/%s/apis/%s/revisions/%d/deployments',
      opts.baseuri, opts.organization, environment, opts.api,
      opts.deploymentVersion);

    if (opts.debug) { console.log('Going to POST to %s', uri); }

    // Unlike "deployproxy" command, ignore the base path here, because we baked it into the proxy definition.
    var deployCmd = util.format('action=deploy&override=true&delay=%d', DeploymentDelay);

    if (opts.debug) { console.log('Going go send command %s', deployCmd); }

    request({
      uri: uri,
      method: 'POST',
      json: false,
      body: deployCmd,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      }
    }, function(err, req, body) {
      if (err) { return done(err); }

      var jsonBody = (body ? JSON.parse(body) : null);

      if (req.statusCode === 200) {
        if (opts.verbose) { console.log('Deployment on %s successful', environment); }
        if (opts.debug) { console.log('%s', body); }
        return done(undefined, jsonBody);
      }

      if (opts.verbose) { console.error('Deployment on %s result: %j', environment, body); }
      var errMsg;
      if (jsonBody && (jsonBody.message)) {
        errMsg = jsonBody.message;
      } else {
        errMsg = util.format('Deployment on %s failed with status code %d', environment, req.statusCode);
      }
      done(new Error(errMsg));
    });
  }

  var tasks = {};
  environments.forEach(function(env) {
    tasks[env] = deployToEnvironment.bind(this, env);
  });

  async.parallel(tasks, done);
}

module.exports.unzipProxy = function(opts, destDir, ignoreDir, cb) {

    if (opts.debug) { console.log('Extracting proxy to', destDir); }

    var count = 1;
    var called = false;
    function done(err) {
      if (!called) {
        count--;
        if (err || count === 0) { cb(err); }
      }
    }

    fs.createReadStream(opts.file)
      .pipe(unzip.Parse())
      .on('error', done)
      .on('close', done)
      .on('entry', function (entry) {
        if (entry.path.indexOf(ignoreDir) === 0) {
          if (opts.debug) { console.log('skipping', entry.path); }
          entry.autodrain(); // ignore all hosted resources
        } else {
          count++;
          if (opts.debug) { console.log('extracting', entry.path); }
          var destFile = path.resolve(destDir, entry.path);
          mkdirs(path.dirname(destFile), function(err) {
            if (err) { return cb(err); }

            entry
              .pipe(fs.createWriteStream(destFile))
              .on('error', done)
              .on('close', done);
          });
        }
      });
  }

module.exports.handleUploadResult = handleUploadResult;

function handleUploadResult(err, req, fileName, itemDone) {
  if (err) {
    itemDone(err);
  } else if ((req.statusCode === 200) || (req.statusCode === 201)) {
    itemDone();
  } else {
    itemDone(new Error(util.format('Error uploading resource %s: %d\n%s',
      fileName, req.statusCode, req.body)));
  }
}

function mkdirs(dirpath, cb) {

  var parts = dirpath.split(path.sep);
  var start = 1;
  if (dirpath[0] === path.sep) {
  parts[0] = '/';
  start = 2;
  }
  for (var i = start; i <= parts.length; i++) {
  try {
      var dir = path.join.apply(null, parts.slice(0, i));
      fs.mkdirSync(dir);
  } catch (err) {
      if (err.code !== 'EEXIST') { return cb(err); }
  }
  }
  cb();
}

module.exports.copyFile = function(source, target, cb) {

    mkdirs(path.dirname(target), function(err) {
    if (err) { return cb(err); }

    cb = _.once(cb);
    var wr = fs.createWriteStream(target)
        .on('error', cb)
        .on('close', cb);
    fs.createReadStream(source)
        .pipe(wr)
        .on('error', cb);
    });
}

module.exports.uploadSource = function(sourceDir, type, opts, request, done) {
// Get a list of entries, broken down by which are directories
  ziputils.enumerateDirectory(sourceDir, type, opts.remoteNpm, function(err, entries) {
    if (err) { return done(err); }

    if (opts.debug) { console.log('Directories to upload: %j', entries); }

    async.eachLimit(entries, opts.asynclimit, function(entry, entryDone) {
      var uri =
        util.format('%s/v1/o/%s/apis/%s/revisions/%d/resources?type=%s&name=%s',
          opts.baseuri, opts.organization, opts.api,
          opts.deploymentVersion, type, entry.resourceName);
      if (entry.directory) {
        // ZIP up all directories, possibly with additional file prefixes
        ziputils.zipDirectory(entry.fileName, entry.zipEntryName, function(err, zipBuf) {
          if (err) {
            entryDone(err);
          } else {
            if (opts.verbose) {
              console.log('Uploading resource %s of size %d',  entry.resourceName, zipBuf.length);
            }
            request({
              uri: uri,
              method: 'POST',
              json: false,
              headers: { 'Content-Type': 'application/octet-stream' },
              body: zipBuf
            }, function(err, req, body) {
              handleUploadResult(err, req, entry.fileName, entryDone);
            });
          }
        });

      } else {
        if (opts.verbose) {
          console.log('Uploading resource %s', entry.resourceName);
        }
        var httpReq = request({
          uri: uri,
          method: 'POST',
          json: false,
          headers: { 'Content-Type': 'application/octet-stream' }
        }, function(err, req, body) {
          handleUploadResult(err, req, entry.fileName, entryDone);
        });

        var fileStream = fs.createReadStream(entry.fileName);
        fileStream.pipe(httpReq);
      }
    }, function(err) {
      done(err);
    });
  });
}

module.exports.usePackedSource = function(sourceDir, opts, cb) {
  if (opts.debug) {
    console.log('packaging bundled dependencies for upload')
  }

  tmp.dir(function(err, tempDir) {
    if (err) {
      return cb(err);
    }

    fs.copy(sourceDir, tempDir, function(err) {
      if (err) {
        return cb(err)
      }

      var cmd = 'npm' + (process.platform === 'win32' ? '.cmd' : '');
      var pack = spawn(cmd, ['pack'], {cwd: tempDir});
      pack.on('error', function(err) {
        return cb(err)
      });
      var packageName;

      pack.stdout.on('data', function(data) {
        packageName = data.toString().trim()
      });

      pack.on('close', function() {
        try {
          var packageArchive =  path.join(tempDir, packageName);
          fs.createReadStream(packageArchive).pipe(zlib.createGunzip()).pipe(tar.extract(tempDir)).on('finish', function() {
            fs.removeSync(packageArchive) // remove the pack archive so it doesn't show up in the proxy

            if (opts.debug) {
              console.log('bundled dependencies ready for upload')
            }

            // return path to packed directory
            return cb(undefined, path.join(tempDir, 'package'))
          }).on('error', function(err) {
            return cb(err);
          });
        } catch(err) {
          return cb(err)
        }
      });
    });
  });
}

function proxyCreationDone (err, req, body, opts, done) {
  if (err) {
    done(err);
  } else if ((req.statusCode === 200) || (req.statusCode === 201)) {
    done();
  } else {
    if (opts.verbose) {
      console.error('Proxy creation error:', body);
    }
    done(new Error(util.format('Proxy creation failed. Status code %d',
                   req.statusCode)));
  }
}<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import moment from 'moment';
import Chip from 'material-ui/Chip';
import { blue300 } from 'material-ui/styles/colors';

import { requestForecasts } from '../redux/modules/perfectWeather';
import { isPreferred } from '../lib/timeUtils';

class PerfectWeatherContainer extends React.Component {
  static propTypes = {
    requestForecasts: React.PropTypes.func.isRequired,
    forecasts: React.PropTypes.object.isRequired
  };

  componentWillMount () {
    this.props.requestForecasts();
  }

  render () {
    const list = this.props.forecasts.get('list');

    if (!list) return
;

    const forecastsByDay = list.groupBy((item) => {
      return moment.unix(item.get('timestamp')).format('Y-M-D');
    });

    const nodes = forecastsByDay.map((dailyForecasts, day) => {
      const dayNodes = dailyForecasts.reduce((nodeArray, item) => {
        if (!isPreferred(item.get('timestamp'))) {
          return nodeArray;
        };

        return nodeArray.concat([
          <Chip
            style={{display: 'inline-block'}}
            backgroundColor={item.get('isPerfect') ? blue300 : ''}
            key={item.get('timestamp')}
          >
            {moment.unix(item.get('timestamp')).format('hA')}
          </Chip>
        ]);
      }, []);
      // const dayNodes = dailyForecasts.map((item) => {
      //   return (
      //     <Chip
      //       style={{display: 'inline-block'}}
      //       backgroundColor={item.get('isPerfect') ? blue300 : ''}
      //       key={item.get('timestamp')}
      //     >
      //       {moment.unix(item.get('timestamp')).format('hA')}
      //     </Chip>
      //   );
      // });

      return (

{moment(day, 'YYYY-MM-DD').format('dddd M/D')}

          {dayNodes}

      );
    });

    return (

        {nodes}

    );
  }
}

const mapStateToProps = (state) => {
  return {
    forecasts: state.perfectWeather.get('forecasts')
  };
};

function mapDispatchToProps (dispatch) {
  return bindActionCreators({
    requestForecasts
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(PerfectWeatherContainer);
<commit_msg>Remove comments<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import moment from 'moment';
import Chip from 'material-ui/Chip';
import { blue300 } from 'material-ui/styles/colors';

import { requestForecasts } from '../redux/modules/perfectWeather';
import { isPreferred } from '../lib/timeUtils';

class PerfectWeatherContainer extends React.Component {
  static propTypes = {
    requestForecasts: React.PropTypes.func.isRequired,
    forecasts: React.PropTypes.object.isRequired
  };

  componentWillMount () {
    this.props.requestForecasts();
  }

  render () {
    const list = this.props.forecasts.get('list');

    if (!list) return
;

    const forecastsByDay = list.groupBy((item) => {
      return moment.unix(item.get('timestamp')).format('Y-M-D');
    });

    const nodes = forecastsByDay.map((dailyForecasts, day) => {
      const dayNodes = dailyForecasts.reduce((nodeArray, item) => {
        if (!isPreferred(item.get('timestamp'))) {
          return nodeArray;
        };

        return nodeArray.concat([
          <Chip
            style={{display: 'inline-block'}}
            backgroundColor={item.get('isPerfect') ? blue300 : ''}
            key={item.get('timestamp')}
          >
            {moment.unix(item.get('timestamp')).format('hA')}
          </Chip>
        ]);
      }, []);

      return (

{moment(day, 'YYYY-MM-DD').format('dddd M/D')}

          {dayNodes}

      );
    });

    return (

        {nodes}

    );
  }
}

const mapStateToProps = (state) => {
  return {
    forecasts: state.perfectWeather.get('forecasts')
  };
};

function mapDispatchToProps (dispatch) {
  return bindActionCreators({
    requestForecasts
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(PerfectWeatherContainer);
<|endoftext|>


<commit_before>/*

dev_mode_app.js
===============

This is the entry point for development(TDD) mode.

*/

var Server = require('./server')
  , fs = require('fs')
  , log = require('winston')
  , child_process = require('child_process')
  , AppView = require('./appview').AppView
  , Path = require('path')
  , yaml = require('js-yaml')
  , FileWatcher = require('./filewatcher')
  , Config = require('./config')

function App(progOptions){
    this.config = new Config(progOptions)

    this.fileWatcher = new FileWatcher
    this.fileWatcher.on('change', this.onFileChanged.bind(this))

    this.configure(function(){
        this.server = new Server(this)
        with(this.server){
            on('server-start', this.initView.bind(this))
            on('file-requested', this.onFileRequested.bind(this))
        }
        this.server.start()
    })
}

App.prototype = {
    initView: function(){
        this.view = new AppView({
            app: this
        })
        if (this.view.on)
            this.view.on('inputChar', this.onInputChar.bind(this))
        this.startPhantomJS()
    },
    configure: function(cb){
        var self = this
          , fileWatcher = self.fileWatcher
          , config = self.config
        config.read(function(){
            var watch_files = config.get('watch_files')
            fileWatcher.clear()
            fileWatcher.add(config.get('file'))
            if (config.isCwdMode())
                fileWatcher.add(process.cwd())
            if (watch_files)
                fileWatcher.add(watch_files)
            if (cb) cb.call(self)
        })
    },
    onFileRequested: function(filepath){
        this.fileWatcher.add(filepath)
    },
    onFileChanged: function(filepath){
        if (filepath === Path.resolve(this.config.get('file')) ||
            (this.config.isCwdMode() && filepath === process.cwd())){
            // config changed
            this.configure(this.startTests.bind(this))
        }else{
            this.startTests()
        }
    },
    startPhantomJS: function(){
        var path = Path.dirname(__dirname) + '/assets/phantom.js'
        this.phantomProcess = child_process.spawn('phantomjs', [path,
            this.config.get('port')])
        log.info('Spawning PhantomJS')
    },
    quit: function(code){
        if (this.phantomProcess)
            this.phantomProcess.kill('SIGKILL')
        setTimeout(function(){
            this.view.cleanup(function(){
                process.exit(code)
            })
        }.bind(this), 100)
    },
    onInputChar: function(chr, i) {
        if (chr === 'q')
            this.quit()
        else if (i === 13) // ENTER
            this.startTests()
    },
    startTests: function(){
        this.server.startTests()
    }
}

module.exports = App<commit_msg>support array for files to watch<commit_after>/*

dev_mode_app.js
===============

This is the entry point for development(TDD) mode.

*/

var Server = require('./server')
  , fs = require('fs')
  , log = require('winston')
  , child_process = require('child_process')
  , AppView = require('./appview').AppView
  , Path = require('path')
  , yaml = require('js-yaml')
  , FileWatcher = require('./filewatcher')
  , Config = require('./config')

function App(progOptions){
    this.config = new Config(progOptions)

    this.fileWatcher = new FileWatcher
    this.fileWatcher.on('change', this.onFileChanged.bind(this))

    this.configure(function(){
        this.server = new Server(this)
        with(this.server){
            on('server-start', this.initView.bind(this))
            on('file-requested', this.onFileRequested.bind(this))
        }
        this.server.start()
    })
}

App.prototype = {
    initView: function(){
        this.view = new AppView({
            app: this
        })
        if (this.view.on)
            this.view.on('inputChar', this.onInputChar.bind(this))
        this.startPhantomJS()
    },
    configure: function(cb){
        var self = this
          , fileWatcher = self.fileWatcher
          , config = self.config
        config.read(function(){
            var watch_files = config.get('watch_files')
            fileWatcher.clear()
            fileWatcher.add(config.get('file'))
            if (config.isCwdMode())
                fileWatcher.add(process.cwd())
            if (watch_files) {
                if (Array.isArray(watch_files)) {
                    fileWatcher.add.apply(fileWatcher, watch_files)
                } else {
                    fileWatcher.add(watch_files)
                }
            }
            if (cb) cb.call(self)
        })
    },
    onFileRequested: function(filepath){
        this.fileWatcher.add(filepath)
    },
    onFileChanged: function(filepath){
        if (filepath === Path.resolve(this.config.get('file')) ||
            (this.config.isCwdMode() && filepath === process.cwd())){
            // config changed
            this.configure(this.startTests.bind(this))
        }else{
            this.startTests()
        }
    },
    startPhantomJS: function(){
        var path = Path.dirname(__dirname) + '/assets/phantom.js'
        this.phantomProcess = child_process.spawn('phantomjs', [path,
            this.config.get('port')])
        log.info('Spawning PhantomJS')
    },
    quit: function(code){
        if (this.phantomProcess)
            this.phantomProcess.kill('SIGKILL')
        setTimeout(function(){
            this.view.cleanup(function(){
                process.exit(code)
            })
        }.bind(this), 100)
    },
    onInputChar: function(chr, i) {
        if (chr === 'q')
            this.quit()
        else if (i === 13) // ENTER
            this.startTests()
    },
    startTests: function(){
        this.server.startTests()
    }
}

module.exports = App<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { observer } from 'mobx-react';
import store from './../../store';

@observer
class Actions extends Component {
  render() {
    return (

        <button onClick={e => store.start() }>Gather Data</button>
        <button onClick={e => store.report() }>Generate Report</button>
        <button onClick={e => store.drawer.close() }>Close</button>

        { store.crawler.isCrawling && <button onClick={e => store.crawler.stop() }>
          Stop Gathering Data
        </button> }

    );
  }
}

Actions.propTypes = {};
Actions.defaultProps = {};

export default Actions;
<commit_msg>clear buttons<commit_after>import React, { Component } from 'react';
import { observer } from 'mobx-react';
import store from './../../store';

@observer
class Actions extends Component {
  render() {
    return (

        { store.crawler.isCrawling ?
          <button onClick={e => store.start() }>
            Gather Data
          </button> :
          <button onClick={e => store.crawler.stop() }>
            Stop Gathering Data
          </button> }

        <button onClick={e => store.drawer.close() }>Close</button>

    );
  }
}

Actions.propTypes = {};
Actions.defaultProps = {};

export default Actions;
<|endoftext|>


<commit_before>import BaseShim from '../baseShim';
import { events, nameSpace } from '../hashiBase';

export default class H5P extends BaseShim {
  constructor(mediator) {
    super(mediator);
    this.data = {};
    this.userData = {};
    this.nameSpace = 'H5P';
    // Bind this to ensure that we don't end up with unpredictable this.
    this.__setData = this.__setData.bind(this);
    this.__setUserData = this.__setUserData.bind(this);
    this.loaded = this.loaded.bind(this);
    this.errored = this.errored.bind(this);
    this.on(this.events.STATEUPDATE, this.__setData);
    this.on(this.events.USERDATAUPDATE, this.__setUserData);
  }

  init(iframe, filepath) {
    import(/* webpackChunkName: "H5PRunner" */ './H5PRunner').then(({ default: H5PRunner }) => {
      this.H5PRunner = new H5PRunner(this);
      this.H5PRunner.init(iframe, filepath, this.loaded, this.errored);
    });
  }

  __setData(data = {}) {
    this.data = data;
  }

  __setUserData(userData = {}) {
    this.userData = userData;
  }

  /*
   * Called by Hashi when the iframe is ready
   * This will setup the H5PIntegration property that H5P then uses
   * to configure itself.
   */
  iframeInitialize(contentWindow) {
    this.H5PRunner.shimH5PIntegration(contentWindow);
  }

  loaded() {
    this.__mediator.sendMessage({ nameSpace, event: events.LOADING, data: false });
  }

  errored(err) {
    this.__mediator.sendMessage({ nameSpace, event: events.ERROR, data: err });
  }
}
<commit_msg>Don't try to initialize H5P when it is does not exist.<commit_after>import BaseShim from '../baseShim';
import { events, nameSpace } from '../hashiBase';

export default class H5P extends BaseShim {
  constructor(mediator) {
    super(mediator);
    this.data = {};
    this.userData = {};
    this.nameSpace = 'H5P';
    // Bind this to ensure that we don't end up with unpredictable this.
    this.__setData = this.__setData.bind(this);
    this.__setUserData = this.__setUserData.bind(this);
    this.loaded = this.loaded.bind(this);
    this.errored = this.errored.bind(this);
    this.on(this.events.STATEUPDATE, this.__setData);
    this.on(this.events.USERDATAUPDATE, this.__setUserData);
  }

  init(iframe, filepath) {
    import(/* webpackChunkName: "H5PRunner" */ './H5PRunner').then(({ default: H5PRunner }) => {
      this.H5PRunner = new H5PRunner(this);
      this.H5PRunner.init(iframe, filepath, this.loaded, this.errored);
    });
  }

  __setData(data = {}) {
    this.data = data;
  }

  __setUserData(userData = {}) {
    this.userData = userData;
  }

  /*
   * Called by Hashi when the iframe is ready
   * This will setup the H5PIntegration property that H5P then uses
   * to configure itself.
   */
  iframeInitialize(contentWindow) {
    this.H5PRunner && this.H5PRunner.shimH5PIntegration(contentWindow);
  }

  loaded() {
    this.__mediator.sendMessage({ nameSpace, event: events.LOADING, data: false });
  }

  errored(err) {
    this.__mediator.sendMessage({ nameSpace, event: events.ERROR, data: err });
  }
}
<|endoftext|>


<commit_before>Template.IMonScatterWidget.onCreated(function() {
  var template = this;
  template.autorun(function() {
    var indicators = [
      Template.currentData().x.indicator,
      Template.currentData().y.indicator
    ];
    template.subscribe('imon_data', 'all', indicators);
    template.subscribe('imon_countries');
  });
});

Template.IMonScatterWidget.onRendered(function() {
  var template = this;
  var node = template.find('.scatter-chart');
  var widgetNode = template.firstNode.parentNode.parentNode;
  var $widgetBody = $(widgetNode).find('.widget-body');

  var chart = d3.select(node).chart('Compose', function(options) {
    var xs = _.pluck(options.data, 'x'), ys = _.pluck(options.data, 'y');

    var scales = {
      x: { domain: [_.min(xs), _.max(xs)] },
      y: { domain: [_.min(ys), _.max(ys)] },
    };

    var charts = [{
      type: 'Dots',
      id: 'dots',
      data: options.data,
      xScale: scales.x,
      yScale: scales.y,
      xJitter: options.xJitter,
      yJitter: options.yJitter,
      labels: {
        offset: 3
      }
    }];

    var title = d3c.title('Custom Chart');
    var xAxis = d3c.axis('xAxis', {scale: scales.x, ticks: 3});
    var yAxis = d3c.axis('yAxis', {scale: scales.y, ticks: 3});
    var xAxisTitle = d3c.axisTitle(options.xAxisTitle);
    var yAxisTitle = d3c.axisTitle(options.yAxisTitle);

    return [
      [yAxisTitle, yAxis, d3c.layered(charts)],
      xAxis,
      xAxisTitle
    ];
  });

  var setChartDims = function() {
    var width = $widgetBody.outerWidth() - Settings.chart.padding.right;
    var height = $widgetBody.outerHeight() - Settings.chart.padding.bottom;
    console.log(width + ' ' + height);
    chart.width(width);
    chart.height(height);
  };

  $(widgetNode).on('gridster:resizestop', function() {
    setChartDims();
    chart.redraw();
  });

  var redrawn = false;
  template.autorun(function() {
    if (!template.subscriptionsReady()) { return; }
    var xIndicator = Template.currentData().x.indicator;
    var yIndicator = Template.currentData().y.indicator;
    var xTitle = xIndicator, yTitle = yIndicator;
    if (Template.currentData().x.log) {
      xTitle = 'Log ' + xTitle;
    }
    if (Template.currentData().y.log) {
      yTitle = 'Log ' + yTitle;
    }

    var data = [];
    IMonCountries.find().forEach(function(country) {
      var x = IMonData.findOne({ countryCode: country.code, name: xIndicator });
      var y = IMonData.findOne({ countryCode: country.code, name: yIndicator });
      if (_.isUndefined(x) || _.isUndefined(y)) { return; }

      var xValue = x.value, yValue = y.value;
      if (Template.currentData().x.log && xValue > 0) {
        xValue = Math.log(xValue);
      }
      if (Template.currentData().y.log && yValue > 0) {
        yValue = Math.log(yValue);
      }

      data.push({
        x: xValue,
        y: yValue,
        code: country.code,
        label: country.name
      });
    });

    chart.margins(Settings.chart.margins);
    chart.responsive(false);

    chart.draw({
      data: data,
      xAxisTitle: xTitle,
      yAxisTitle: yTitle,
      xJitter: Template.currentData().x.jitter,
      yJitter: Template.currentData().y.jitter
    });

    // This is a hacky way to get the chart to fit the widget on first draw
    // because it wouldn't throw the draw event correctly.
    if (!redrawn) {
      setChartDims();
      chart.redraw();
      redrawn = true;
    }
  });
});
<commit_msg>make all labels always show up - #13103<commit_after>Template.IMonScatterWidget.onCreated(function() {
  var template = this;
  template.autorun(function() {
    var indicators = [
      Template.currentData().x.indicator,
      Template.currentData().y.indicator
    ];
    template.subscribe('imon_data', 'all', indicators);
    template.subscribe('imon_countries');
  });
});

Template.IMonScatterWidget.onRendered(function() {
  var template = this;
  var node = template.find('.scatter-chart');
  var widgetNode = template.firstNode.parentNode.parentNode;
  var $widgetBody = $(widgetNode).find('.widget-body');

  var chart = d3.select(node).chart('Compose', function(options) {
    var xs = _.pluck(options.data, 'x'), ys = _.pluck(options.data, 'y');

    var scales = {
      x: { domain: [_.min(xs), _.max(xs)] },
      y: { domain: [_.min(ys), _.max(ys)] },
    };

    var charts = [{
      type: 'Dots',
      id: 'dots',
      data: options.data,
      xScale: scales.x,
      yScale: scales.y,
      xJitter: options.xJitter,
      yJitter: options.yJitter,
      labels: {
        offset: 3
      }
    }];

    var title = d3c.title('Custom Chart');
    var xAxis = d3c.axis('xAxis', {scale: scales.x, ticks: 3});
    var yAxis = d3c.axis('yAxis', {scale: scales.y, ticks: 3});
    var xAxisTitle = d3c.axisTitle(options.xAxisTitle);
    var yAxisTitle = d3c.axisTitle(options.yAxisTitle);

    return [
      [yAxisTitle, yAxis, d3c.layered(charts)],
      xAxis,
      xAxisTitle
    ];
  });

  var setChartDims = function() {
    var width = $widgetBody.outerWidth() - Settings.chart.padding.right;
    var height = $widgetBody.outerHeight() - Settings.chart.padding.bottom;
    console.log(width + ' ' + height);
    chart.width(width);
    chart.height(height);
  };

  $(widgetNode).on('gridster:resizestop', function() {
    setChartDims();
    chart.redraw();
  });

  var redrawn = false;
  template.autorun(function() {
    if (!template.subscriptionsReady()) { return; }
    var xIndicator = Template.currentData().x.indicator;
    var yIndicator = Template.currentData().y.indicator;
    var xTitle = xIndicator, yTitle = yIndicator;
    if (Template.currentData().x.log) {
      xTitle = 'Log ' + xTitle;
    }
    if (Template.currentData().y.log) {
      yTitle = 'Log ' + yTitle;
    }

    var data = [];
    IMonCountries.find().forEach(function(country) {
      var x = IMonData.findOne({ countryCode: country.code, name: xIndicator });
      var y = IMonData.findOne({ countryCode: country.code, name: yIndicator });
      if (_.isUndefined(x) || _.isUndefined(y)) { return; }

      var xValue = x.value, yValue = y.value;
      if (Template.currentData().x.log && xValue > 0) {
        xValue = Math.log(xValue);
      }
      if (Template.currentData().y.log && yValue > 0) {
        yValue = Math.log(yValue);
      }

      data.push({
        x: xValue,
        y: yValue,
        code: country.code,
        key: country.code,
        label: country.name
      });
    });

    chart.margins(Settings.chart.margins);
    chart.responsive(false);

    chart.draw({
      data: data,
      xAxisTitle: xTitle,
      yAxisTitle: yTitle,
      xJitter: Template.currentData().x.jitter,
      yJitter: Template.currentData().y.jitter
    });

    // This is a hacky way to get the chart to fit the widget on first draw
    // because it wouldn't throw the draw event correctly.
    if (!redrawn) {
      setChartDims();
      chart.redraw();
      redrawn = true;
    }
  });
});
<|endoftext|>


<commit_before>var Ripple = require('ripple-lib')
var request = require('request')
var RippleAddress = require('../app/models/ripple_address.js');
var RippleTransaction = require('../app/models/ripple_transaction.js');
var RippleSimpleClient = require('../lib/ripple_simple_client.js');
var sequelize = require("../config/initializers/sequelize.js");
var nconf = require('../config/nconf.js');

var client = new RippleSimpleClient({
  apiUrl: nconfg.get('RIPPLE_REST_API');
});

// Proposed!!
/*
client.on('payment:inbound', function(payment) {

});

client.on('payment:outbound', function(payment) {

});

client.listener.start();
*/

sequelize.sync().success(function(){

  getHotWallet(function(wallet){
    address = wallet.address;
    client.address = wallet.address;
    getNextNotification();
    console.log("listening for transactions to ", address);
  });

});

function getNextNotification() {
  client.getNextNotification(function(err, notification){
    if (notification) {
      handlePayment(notification, function(){
        setTimeout(getNextNotification, 2000);
      });
    } else {
      setTimeout(getNextNotification, 2000);
    }
  });
}

function getHotWallet(fn) {
  RippleAddress.find({ where: { type: 'hot' }}).complete(function(err, address) {
    fn(address);
  });
}

function lookupTransaction(transactionHash, fn){
  RippleTransaction.find({ where: {
    transaction_hash: transactionHash
  }}).complete(fn);
}

function handleUnknownPayment(notification, fn) {
  client.getPayment(notification.tx_hash, function(err, payment) {
    if (payment && payment.dst_tag) {
      RippleAddress.find({ where: {
        address: address,
        tag: payment.dst_tag.toString()
      }}).complete(function(err, address){
        if (address) {
          RippleTransaction.create({
            ripple_address_id: address.id,
            to_address: payment.dst_address,
            from_address: payment.src_address,
            from_amount: payment.src_amount.value,
            from_currency: payment.src_amount.currency,
            from_issuer: payment.src_amount.issuer,
            to_address: payment.dst_address,
            to_amount: payment.dst_amount.value,
            to_currency: payment.dst_amount.currency,
            to_issuer: payment.dst_amount.issuer,
            transaction_state: payment.tx_state,
            transaction_hash: payment.tx_hash,
            issuance: false
          }).complete(function(err, transaction) {
            console.log(err);
            fn();
          });
        } else {
          console.log(err);
          fn();
        }
      });
    } else {
      console.log('no destination tag');
      fn();
    }
  });
}

function handleKnownPayment(notification, record, fn) {
  record.transaction_state = notification.tx_result;
  record.save().complete(fn);
}

function handlePayment(notification,fn) {
  if (notification.type == 'payment') {
    lookupTransaction(notification.tx_hash, function(err, transaction) {
      console.log(notification.tx_hash);
      if (transaction) {
        handleKnownPayment(notification, transaction, fn);
      } else {
        handleUnknownPayment(notification, fn);
      }
    });
  } else {
    fn();
  }
}

<commit_msg>[BUG] correst misspelling, remove semicolon.<commit_after>var Ripple = require('ripple-lib')
var request = require('request')
var RippleAddress = require('../app/models/ripple_address.js');
var RippleTransaction = require('../app/models/ripple_transaction.js');
var RippleSimpleClient = require('../lib/ripple_simple_client.js');
var sequelize = require("../config/initializers/sequelize.js");
var nconf = require('../config/nconf.js');

var client = new RippleSimpleClient({
  apiUrl: nconf.get('RIPPLE_REST_API')
});

// Proposed!!
/*
client.on('payment:inbound', function(payment) {

});

client.on('payment:outbound', function(payment) {

});

client.listener.start();
*/

sequelize.sync().success(function(){

  getHotWallet(function(wallet){
    address = wallet.address;
    client.address = wallet.address;
    getNextNotification();
    console.log("listening for transactions to ", address);
  });

});

function getNextNotification() {
  client.getNextNotification(function(err, notification){
    if (notification) {
      handlePayment(notification, function(){
        setTimeout(getNextNotification, 2000);
      });
    } else {
      setTimeout(getNextNotification, 2000);
    }
  });
}

function getHotWallet(fn) {
  RippleAddress.find({ where: { type: 'hot' }}).complete(function(err, address) {
    fn(address);
  });
}

function lookupTransaction(transactionHash, fn){
  RippleTransaction.find({ where: {
    transaction_hash: transactionHash
  }}).complete(fn);
}

function handleUnknownPayment(notification, fn) {
  client.getPayment(notification.tx_hash, function(err, payment) {
    if (payment && payment.dst_tag) {
      RippleAddress.find({ where: {
        address: address,
        tag: payment.dst_tag.toString()
      }}).complete(function(err, address){
        if (address) {
          RippleTransaction.create({
            ripple_address_id: address.id,
            to_address: payment.dst_address,
            from_address: payment.src_address,
            from_amount: payment.src_amount.value,
            from_currency: payment.src_amount.currency,
            from_issuer: payment.src_amount.issuer,
            to_address: payment.dst_address,
            to_amount: payment.dst_amount.value,
            to_currency: payment.dst_amount.currency,
            to_issuer: payment.dst_amount.issuer,
            transaction_state: payment.tx_state,
            transaction_hash: payment.tx_hash,
            issuance: false
          }).complete(function(err, transaction) {
            console.log(err);
            fn();
          });
        } else {
          console.log(err);
          fn();
        }
      });
    } else {
      console.log('no destination tag');
      fn();
    }
  });
}

function handleKnownPayment(notification, record, fn) {
  record.transaction_state = notification.tx_result;
  record.save().complete(fn);
}

function handlePayment(notification,fn) {
  if (notification.type == 'payment') {
    lookupTransaction(notification.tx_hash, function(err, transaction) {
      console.log(notification.tx_hash);
      if (transaction) {
        handleKnownPayment(notification, transaction, fn);
      } else {
        handleUnknownPayment(notification, fn);
      }
    });
  } else {
    fn();
  }
}

<|endoftext|>


<commit_before>import Vue from 'vue';
import { Inkline } from '@inkline/inkline/src/index';
import InklineValidation from '@inkline/inkline/src/validation';
import '@inkline/inkline/index.scss';

Vue.use(Inkline);
Vue.use(InklineValidation);
<commit_msg>Removed validation imports.<commit_after>import Vue from 'vue';
import { Inkline } from '@inkline/inkline/src/index';
import '@inkline/inkline/index.scss';

Vue.use(Inkline);
<|endoftext|>


<commit_before>/**
 * @file        Http functions specific to easyRTC, including those for setting up API hosting
 * @module      easyrtc_http
 * @author      Priologic Software, info@easyrtc.com
 * @copyright   Copyright 2013 Priologic Software. All rights reserved.
 */

var e           = require("./easyrtc_private_obj");     // easyRTC private object
var eu          = require("./easyrtc_util");        // easyRTC utility functions

exports.initHttpApp = function(httpApp, next) {
    httpApp.configure( function() {
        // Set the easyRTC demos
        if (e.options.demosEnable) {
            eu.logDebug("Setting up demos to be accessed from '" + e.options.demosPublicFolder + "/'");
            httpApp.get(e.options.demosPublicFolder + "/*", function(req, res) {
                res.sendfile(
                    './demos/' + (req.params[0] ? req.params[0] : 'index.html'),
                    {root:__dirname + "/../"},
                    function(err) {
                        try{if (err && err.status && res && !res._headerSent) {
                            res.status(404);
                            var body =    "<title>File Not Found</title>
File Not Found
";
                            res.setHeader('Content-Type', 'text/html');
                            res.setHeader('Content-Length', body.length);
                            res.end(body);
                        }}catch(e){}
                    }
                );
            });
            // Forward people who forget the trailing slash to the folder.
            httpApp.get(e.options.demosPublicFolder, function(req, res) {res.redirect(e.options.demosPublicFolder + "/");});
        }

        if (e.options.apiEnable) {
            // Set the easyRTC API files
            // TODO: Minified version
            eu.logDebug("Setting up API files to be accessed from '" + e.options.apiPublicFolder + "/'");
            httpApp.get(e.options.apiPublicFolder + "/easyrtc.js",              function(req, res) {res.sendfile('api/easyrtc.js',              {root:__dirname + "/../"});});
            httpApp.get(e.options.apiPublicFolder + "/easyrtc.css",             function(req, res) {res.sendfile('api/easyrtc.css',             {root:__dirname + "/../"});});
            httpApp.get(e.options.apiPublicFolder + "/powered_by_easyrtc.png",  function(req, res) {res.sendfile('api/powered_by_easyrtc.png',  {root:__dirname + "/../"});});
        }

        if (e.options.apiEnable && e.options.apiOldLocationEnable) {
            eu.logWarning("Enabling listening for API files in older depreciated location.");
            // Transition - Old locations of easyRTC API files
            httpApp.get("/js/easyrtc.js",                   function(req, res) {res.sendfile('api/easyrtc.js',              {root:__dirname + "/../"});});
            httpApp.get("/css/easyrtc.css",                 function(req, res) {res.sendfile('api/easyrtc.css',             {root:__dirname + "/../"});});
        }
    });
    next(null);
}
<commit_msg>Adjusted powered_by image location to match api folder<commit_after>/**
 * @file        Http functions specific to easyRTC, including those for setting up API hosting
 * @module      easyrtc_http
 * @author      Priologic Software, info@easyrtc.com
 * @copyright   Copyright 2013 Priologic Software. All rights reserved.
 */

var e           = require("./easyrtc_private_obj");     // easyRTC private object
var eu          = require("./easyrtc_util");        // easyRTC utility functions

exports.initHttpApp = function(httpApp, next) {
    httpApp.configure( function() {
        // Set the easyRTC demos
        if (e.options.demosEnable) {
            eu.logDebug("Setting up demos to be accessed from '" + e.options.demosPublicFolder + "/'");
            httpApp.get(e.options.demosPublicFolder + "/*", function(req, res) {
                res.sendfile(
                    './demos/' + (req.params[0] ? req.params[0] : 'index.html'),
                    {root:__dirname + "/../"},
                    function(err) {
                        try{if (err && err.status && res && !res._headerSent) {
                            res.status(404);
                            var body =    "<title>File Not Found</title>
File Not Found
";
                            res.setHeader('Content-Type', 'text/html');
                            res.setHeader('Content-Length', body.length);
                            res.end(body);
                        }}catch(e){}
                    }
                );
            });
            // Forward people who forget the trailing slash to the folder.
            httpApp.get(e.options.demosPublicFolder, function(req, res) {res.redirect(e.options.demosPublicFolder + "/");});
        }

        if (e.options.apiEnable) {
            // Set the easyRTC API files
            // TODO: Minified version
            eu.logDebug("Setting up API files to be accessed from '" + e.options.apiPublicFolder + "/'");
            httpApp.get(e.options.apiPublicFolder + "/easyrtc.js",                  function(req, res) {res.sendfile('api/easyrtc.js',                  {root:__dirname + "/../"});});
            httpApp.get(e.options.apiPublicFolder + "/easyrtc.css",                 function(req, res) {res.sendfile('api/easyrtc.css',                 {root:__dirname + "/../"});});
            httpApp.get(e.options.apiPublicFolder + "/img/powered_by_easyrtc.png",  function(req, res) {res.sendfile('api/img/powered_by_easyrtc.png',  {root:__dirname + "/../"});});
        }

        if (e.options.apiEnable && e.options.apiOldLocationEnable) {
            eu.logWarning("Enabling listening for API files in older depreciated location.");
            // Transition - Old locations of easyRTC API files
            httpApp.get("/js/easyrtc.js",                   function(req, res) {res.sendfile('api/easyrtc.js',              {root:__dirname + "/../"});});
            httpApp.get("/css/easyrtc.css",                 function(req, res) {res.sendfile('api/easyrtc.css',             {root:__dirname + "/../"});});
        }
    });
    next(null);
}
<|endoftext|>


<commit_before>import db from '../models';
import { NotFoundError, ModelValidationError, ValidationError } from '../components/errors';
import ConflictError from '../components/errors';
import Sequelize from 'sequelize';
import Bluebird from 'bluebird';
import SERIALIZATION_FAILURE from '../components/constants';

function checkIfSellerIsSeller(sellerId, needSeller) {
    if (needSeller) {
        return db.Customer.findById(sellerId)
        .then(customer => customer.getCustomerRole())
        .then(role => role.isSeller);
    }
    return Bluebird.resolve(true);
}

export function list(req, res, next) {
    req.system.getTransactions()
    .then(res.json.bind(res))
    .catch(next);
}

export function retrieve(req, res, next) {
    db.Transaction.findOne({ where: {
        id: req.params.transactionId,
        systemId: req.system.id
    } })
    .then(transaction => {
        if (!transaction) throw new NotFoundError();
        res.json(transaction);
    })
    .catch(next);
}

export function add(req, res, next) {
    let currentTransaction;
    let currentCustomer;
    let currentTotal;
    let currentCustomerRole;

    // start database transaction
    db.sequelize.transaction(t => {
        // transaction must contain products
        if (!req.body.products || req.body.products.length === 0) {
            return next(new ValidationError('A transaction must contain at least one product'));
        }

        // check that seller is included if system needs seller
        if (req.system.needSeller && !req.body.sellerId) {
            return next(new ValidationError('A transaction for this system requires a seller'));
        }
        // find and store customer
        return checkIfSellerIsSeller(req.body.sellerId, req.system.needSeller)
        .then(isSeller => {
            if (!isSeller) {
                throw new ValidationError('sellerId does not belong to a seller');
            }
            return db.Customer.findById(req.body.customerId);
        })
        .then(customer => {
            if (!customer) {
                throw new ValidationError('Customer for transaction not found');
            }
            currentCustomer = customer;
            return customer.getCustomerRole();
        })

        // find customer role
        .then(customerRole => {
            currentCustomerRole = customerRole;
            // reduce stock for all products. database transaction must explicitly be
            // set because a new transaction promise chain implies a new transaction
            return Bluebird.mapSeries(req.body.products, id =>
                db.Product.findById(id, { transaction: t })
                .then(product => {
                    if (product.keepStock) {
                        product.stock--;
                    }
                    return product.save({ transaction: t });
                })
            );
        })

        // calculate sum of all products
        .reduce((sum, product) =>
            (currentCustomerRole.internalSales ? product.internalPrice : product.price) + sum
        , 0)

        // store total and create transaction
        .then(total => {
            currentTotal = total;
            return db.Transaction.create({
                ...req.body,
                systemId: req.system.id,
                total
            });
        })

        // decrease customer balance
        .then(transaction => {
            currentTransaction = transaction;
            currentCustomer.balance -= currentTotal;
            if (currentCustomer.balance < 0 && currentCustomerRole.allowCredit !== true) {
                throw new ValidationError('Insufficient balance');
            }
            return currentCustomer.save();
        });
    }).then(result => {
        // entire database transaction OK, return newly created transaction
        res.status(201).json(currentTransaction);
    }).catch(Sequelize.ValidationError, err => {
        throw new ModelValidationError(err);
    }).catch(err => {
        if (err.parent) {
            return err.parent.code === SERIALIZATION_FAILURE;
        }
        return false;
    }, err => {
        throw new ConflictError(err);
    })
    .catch(next);
}
<commit_msg>Conflict error (#141)<commit_after>import db from '../models';
import * as errors from '../components/errors';
import Sequelize from 'sequelize';
import Bluebird from 'bluebird';
import SERIALIZATION_FAILURE from '../components/constants';

function checkIfSellerIsSeller(sellerId, needSeller) {
    if (needSeller) {
        return db.Customer.findById(sellerId)
        .then(customer => customer.getCustomerRole())
        .then(role => role.isSeller);
    }
    return Bluebird.resolve(true);
}

export function list(req, res, next) {
    req.system.getTransactions()
    .then(res.json.bind(res))
    .catch(next);
}

export function retrieve(req, res, next) {
    db.Transaction.findOne({ where: {
        id: req.params.transactionId,
        systemId: req.system.id
    } })
    .then(transaction => {
        if (!transaction) throw new errors.NotFoundError();
        res.json(transaction);
    })
    .catch(next);
}

export function add(req, res, next) {
    let currentTransaction;
    let currentCustomer;
    let currentTotal;
    let currentCustomerRole;

    // start database transaction
    db.sequelize.transaction(t => {
        // transaction must contain products
        if (!req.body.products || req.body.products.length === 0) {
            return next(
                new errors.ValidationError('A transaction must contain at least one product')
            );
        }

        // check that seller is included if system needs seller
        if (req.system.needSeller && !req.body.sellerId) {
            return next(
                new errors.ValidationError('A transaction for this system requires a seller')
            );
        }
        // find and store customer
        return checkIfSellerIsSeller(req.body.sellerId, req.system.needSeller)
        .then(isSeller => {
            if (!isSeller) {
                throw new errors.ValidationError('sellerId does not belong to a seller');
            }
            return db.Customer.findById(req.body.customerId);
        })
        .then(customer => {
            if (!customer) {
                throw new errors.ValidationError('Customer for transaction not found');
            }
            currentCustomer = customer;
            return customer.getCustomerRole();
        })

        // find customer role
        .then(customerRole => {
            currentCustomerRole = customerRole;
            // reduce stock for all products. database transaction must explicitly be
            // set because a new transaction promise chain implies a new transaction
            return Bluebird.mapSeries(req.body.products, id =>
                db.Product.findById(id, { transaction: t })
                .then(product => {
                    if (product.keepStock) {
                        product.stock--;
                    }
                    return product.save({ transaction: t });
                })
            );
        })

        // calculate sum of all products
        .reduce((sum, product) =>
            (currentCustomerRole.internalSales ? product.internalPrice : product.price) + sum
        , 0)

        // store total and create transaction
        .then(total => {
            currentTotal = total;
            return db.Transaction.create({
                ...req.body,
                systemId: req.system.id,
                total
            });
        })

        // decrease customer balance
        .then(transaction => {
            currentTransaction = transaction;
            currentCustomer.balance -= currentTotal;
            if (currentCustomer.balance < 0 && currentCustomerRole.allowCredit !== true) {
                throw new errors.ValidationError('Insufficient balance');
            }
            return currentCustomer.save();
        });
    }).then(result => {
        // entire database transaction OK, return newly created transaction
        res.status(201).json(currentTransaction);
    }).catch(Sequelize.ValidationError, err => {
        throw new errors.ModelValidationError(err);
    }).catch(err => err.parent && err.parent.code === SERIALIZATION_FAILURE, err => {
        throw new errors.ConflictError(err);
    })
    .catch(next);
}
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import {create} from './actions/project'
import {Button} from './components/buttons'
import Panel, {Body, Heading} from './components/panel'
import {Text} from './components/input'
import messages from './messages'

function mapStateToProps () {
  return {
    isEditing: false
  }
}

function mapDispatchToProps (dispatch) {
  return {
    create: (opts) => dispatch(create(opts))
  }
}

class EditProject extends Component {
  static propTypes = {
    bounds: PropTypes.shape({
      north: PropTypes.number,
      east: PropTypes.number,
      south: PropTypes.number,
      west: PropTypes.number
    }),
    description: PropTypes.string,
    id: PropTypes.string,
    isEditing: PropTypes.bool.isRequired,
    name: PropTypes.string,
    r5Version: PropTypes.string
  }

  state = {
    bounds: this.props.bounds,
    description: this.props.description,
    name: this.props.name,
    r5Version: this.props.r5Version
  }

  render () {
    const {isEditing} = this.props
    const {description, name} = this.state
    const action = isEditing ? messages.project.editAction : messages.project.createAction
    const title = isEditing ? messages.project.editTitle : messages.project.createTitle

    return (
      <Panel>
        <Heading>{title}</Heading>

          <Text
            name='Name'
            onChange={(e) => this.setState({
              ...this.state,
              name: e.target.value
            })}
            defaultValue={name}
            />
          <Text
            name='Description'
            onChange={(e) => this.setState({
              ...this.state,
              description: e.target.value
            })}
            defaultValue={description}
            />
          <Button
            block
            onClick={() => this.props.create(this.state)}
            style='success'
            >{action}
          </Button>

      </Panel>
    )
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(EditProject)
<commit_msg>style(project): Remove
<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import {create} from './actions/project'
import {Button} from './components/buttons'
import Panel, {Body, Heading} from './components/panel'
import {Text} from './components/input'
import messages from './messages'

function mapStateToProps () {
  return {
    isEditing: false
  }
}

function mapDispatchToProps (dispatch) {
  return {
    create: (opts) => dispatch(create(opts))
  }
}

class EditProject extends Component {
  static propTypes = {
    bounds: PropTypes.shape({
      north: PropTypes.number,
      east: PropTypes.number,
      south: PropTypes.number,
      west: PropTypes.number
    }),
    description: PropTypes.string,
    id: PropTypes.string,
    isEditing: PropTypes.bool.isRequired,
    name: PropTypes.string,
    r5Version: PropTypes.string
  }

  state = {
    bounds: this.props.bounds,
    description: this.props.description,
    name: this.props.name,
    r5Version: this.props.r5Version
  }

  render () {
    const {isEditing} = this.props
    const {description, name} = this.state
    const action = isEditing ? messages.project.editAction : messages.project.createAction
    const title = isEditing ? messages.project.editTitle : messages.project.createTitle

    return (
      <Panel>
        <Heading>{title}</Heading>

          <Text
            name='Name'
            onChange={(e) => this.setState({
              ...this.state,
              name: e.target.value
            })}
            defaultValue={name}
            />
          <Text
            name='Description'
            onChange={(e) => this.setState({
              ...this.state,
              description: e.target.value
            })}
            defaultValue={description}
            />
          <Button
            block
            onClick={() => this.props.create(this.state)}
            style='success'
            >{action}
          </Button>

      </Panel>
    )
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(EditProject)
<|endoftext|>


<commit_before>/**
 * 气泡图控制器
 * 控制气泡图的显示方向
 *
 * Created by GUY on 2015/8/21.
 * @class
 */
BI.BubblesController = BI.inherit(BI.Controller, {
    init: function () {
        this.storeBubbles = {};
    },

    /**
     *
     * @param name
     * @param text
     * @param context
     * @param offsetStyle center, left, right三种类型， 默认left
     * @returns {BI.BubblesController}
     */
    show: function (name, text, context, opt) {
        opt || (opt = {});
        var container = opt.container || context;
        var offsetStyle = opt.offsetStyle || "left";
        var level = opt.level || "error";
        var adjustYOffset = opt.adjustYOffset || 0;
        var adjustXOffset = opt.adjustXOffset || 0;
        // var fixed = opt.fixed !== false;

        if (!this.storeBubbles[name]) {
            this.storeBubbles[name] = BI.createWidget({
                type: "bi.label",
                cls: "bi-bubble" + " bubble-" + level,
                text: text,
                hgap: 5,
                height: 18
            });
        }
        var bubble = this.storeBubbles[name];

        BI.createWidget({
            type: "bi.default",
            element: container,
            items: [{
                el: bubble
            }]
        });
        BI.Popper.createPopper(context.element[0], bubble.element[0], {
            placement: ({
                left: "top-start",
                center: "top",
                right: "top-end"
            })[offsetStyle],
            strategy: "fixed",
            modifiers: [
                {
                    name: "offset",
                    options: {
                        offset: [adjustXOffset, adjustYOffset]
                    }
                }
            ]
        });
        return this;
    },

    hide: function (name) {
        this.remove(name);
        return this;
    },

    has: function (name) {
        return this.storeBubbles[name] != null;
    },

    remove: function (name) {
        if (!this.has(name)) {
            return this;
        }
        this.storeBubbles[name].destroy();
        delete this.storeBubbles[name];
        return this;
    }
});
<commit_msg>Pull request #2049: 无JIRA任务 fix: bi.editor在连续调用BI.Bubbles.show(name,text)的场景下, name相同,text不同, text永远显示的是第一次调用的<commit_after>/**
 * 气泡图控制器
 * 控制气泡图的显示方向
 *
 * Created by GUY on 2015/8/21.
 * @class
 */
BI.BubblesController = BI.inherit(BI.Controller, {
    init: function () {
        this.storeBubbles = {};
    },

    /**
     *
     * @param name
     * @param text
     * @param context
     * @param offsetStyle center, left, right三种类型， 默认left
     * @returns {BI.BubblesController}
     */
    show: function (name, text, context, opt) {
        opt || (opt = {});
        var container = opt.container || context;
        var offsetStyle = opt.offsetStyle || "left";
        var level = opt.level || "error";
        var adjustYOffset = opt.adjustYOffset || 0;
        var adjustXOffset = opt.adjustXOffset || 0;
        // var fixed = opt.fixed !== false;

        if (!this.storeBubbles[name]) {
            this.storeBubbles[name] = BI.createWidget({
                type: "bi.label",
                cls: "bi-bubble" + " bubble-" + level,
                text: text,
                hgap: 5,
                height: 18
            });
        }
        var bubble = this.storeBubbles[name];
        if (bubble.getText() !== text) {
            bubble.setText(text);
        }

        BI.createWidget({
            type: "bi.default",
            element: container,
            items: [{
                el: bubble
            }]
        });
        BI.Popper.createPopper(context.element[0], bubble.element[0], {
            placement: ({
                left: "top-start",
                center: "top",
                right: "top-end"
            })[offsetStyle],
            strategy: "fixed",
            modifiers: [
                {
                    name: "offset",
                    options: {
                        offset: [adjustXOffset, adjustYOffset]
                    }
                }
            ]
        });
        return this;
    },

    hide: function (name) {
        this.remove(name);
        return this;
    },

    has: function (name) {
        return this.storeBubbles[name] != null;
    },

    remove: function (name) {
        if (!this.has(name)) {
            return this;
        }
        this.storeBubbles[name].destroy();
        delete this.storeBubbles[name];
        return this;
    }
});
<|endoftext|>


<commit_before>//export * from "./cookies-consent/index.js";
//export * from "./text-editor/index.js";
export * from "./toast/index.js";
export * from "./confirm/index.js";

<commit_msg>neutrine: export loading bar component<commit_after>//export * from "./cookies-consent/index.js";
//export * from "./text-editor/index.js";
export * from "./toast/index.js";
export * from "./confirm/index.js";
export * from "./loading/index.js";

<|endoftext|>


<commit_before>import { isUndefined, clone } from 'underscore';

const Backbone = require('backbone');
const $ = Backbone.$;

module.exports = Backbone.View.extend({
  events: {
    change: 'onChange'
  },

  attributes() {
    return this.model.get('attributes');
  },

  initialize(o) {
    const model = this.model;
    const name = model.get('name');
    const target = model.target;
    this.config = o.config || {};
    this.pfx = this.config.stylePrefix || '';
    this.ppfx = this.config.pStylePrefix || '';
    this.target = target;
    this.className = this.pfx + 'trait';
    this.labelClass = this.ppfx + 'label';
    this.fieldClass =
      this.ppfx + 'field ' + this.ppfx + 'field-' + model.get('type');
    this.inputhClass = this.ppfx + 'input-holder';
    model.off('change:value', this.onValueChange);
    this.listenTo(model, 'change:value', this.onValueChange);
    model.view = this;
    this.tmpl =
      '

';
  },

  /**
   * Fires when the input is changed
   * @private
   */
  onChange() {
    this.model.set('value', this.getInputEl().value);
  },

  getValueForTarget() {
    return this.model.get('value');
  },

  setInputValue(value) {
    this.getInputEl().value = value;
  },

  /**
   * On change callback
   * @private
   */
  onValueChange(model, value, opts = {}) {
    const mod = this.model;
    const trg = this.target;
    const name = mod.get('name');

    if (opts.fromTarget) {
      this.setInputValue(mod.get('value'));
    } else {
      const value = this.getValueForTarget();
      mod.setTargetValue(value, opts);
    }
  },

  /**
   * Render label
   * @private
   */
  renderLabel() {
    const label = this.getLabel();
    this.$el.html(
      `<div class="${this.labelClass}" title="${label}">${label}</div>`
    );
  },

  /**
   * Returns label for the input
   * @return {string}
   * @private
   */
  getLabel() {
    var model = this.model;
    var label = model.get('label') || model.get('name');
    return label.charAt(0).toUpperCase() + label.slice(1).replace(/-/g, ' ');
  },

  /**
   * Returns input element
   * @return {HTMLElement}
   * @private
   */
  getInputEl() {
    if (!this.$input) {
      const md = this.model;
      const plh = md.get('placeholder') || md.get('default') || '';
      const type = md.get('type') || 'text';
      const min = md.get('min');
      const max = md.get('max');
      const value = this.getModelValue();
      const input = $(`<input type="${type}" placeholder="${plh}">`);

      if (value) {
        input.prop('value', value);
      }

      if (min) {
        input.prop('min', min);
      }

      if (max) {
        input.prop('max', max);
      }

      this.$input = input;
    }
    return this.$input.get(0);
  },

  getModelValue() {
    let value;
    const model = this.model;
    const target = this.target;
    const name = model.get('name');

    if (model.get('changeProp')) {
      value = target.get(name);
    } else {
      const attrs = target.get('attributes');
      value = model.get('value') || attrs[name];
    }

    return !isUndefined(value) ? value : '';
  },

  /**
   * Renders input
   * @private
   * */
  renderField() {
    if (!this.$input) {
      this.$el.append(this.tmpl);
      const el = this.getInputEl();
      // I use prepand expecially for checkbox traits
      const inputWrap = this.el.querySelector(`.${this.inputhClass}`);
      inputWrap.insertBefore(el, inputWrap.childNodes[0]);
    }
  },

  render() {
    this.renderLabel();
    this.renderField();
    this.el.className = this.className;
    return this;
  }
});
<commit_msg>Ensure the trait gets the initial value. Fixes #1290<commit_after>import { isUndefined, clone } from 'underscore';

const Backbone = require('backbone');
const $ = Backbone.$;

module.exports = Backbone.View.extend({
  events: {
    change: 'onChange'
  },

  attributes() {
    return this.model.get('attributes');
  },

  initialize(o) {
    const model = this.model;
    const name = model.get('name');
    const target = model.target;
    this.config = o.config || {};
    this.pfx = this.config.stylePrefix || '';
    this.ppfx = this.config.pStylePrefix || '';
    this.target = target;
    this.className = this.pfx + 'trait';
    this.labelClass = this.ppfx + 'label';
    this.fieldClass =
      this.ppfx + 'field ' + this.ppfx + 'field-' + model.get('type');
    this.inputhClass = this.ppfx + 'input-holder';
    model.off('change:value', this.onValueChange);
    this.listenTo(model, 'change:value', this.onValueChange);
    model.view = this;
    this.tmpl =
      '

';
  },

  /**
   * Fires when the input is changed
   * @private
   */
  onChange() {
    this.model.set('value', this.getInputEl().value);
  },

  getValueForTarget() {
    return this.model.get('value');
  },

  setInputValue(value) {
    this.getInputEl().value = value;
  },

  /**
   * On change callback
   * @private
   */
  onValueChange(model, value, opts = {}) {
    const mod = this.model;
    const trg = this.target;
    const name = mod.get('name');

    if (opts.fromTarget) {
      this.setInputValue(mod.get('value'));
    } else {
      const value = this.getValueForTarget();
      mod.setTargetValue(value, opts);
    }
  },

  /**
   * Render label
   * @private
   */
  renderLabel() {
    const label = this.getLabel();
    this.$el.html(
      `<div class="${this.labelClass}" title="${label}">${label}</div>`
    );
  },

  /**
   * Returns label for the input
   * @return {string}
   * @private
   */
  getLabel() {
    var model = this.model;
    var label = model.get('label') || model.get('name');
    return label.charAt(0).toUpperCase() + label.slice(1).replace(/-/g, ' ');
  },

  /**
   * Returns input element
   * @return {HTMLElement}
   * @private
   */
  getInputEl() {
    if (!this.$input) {
      const md = this.model;
      const plh = md.get('placeholder') || md.get('default') || '';
      const type = md.get('type') || 'text';
      const min = md.get('min');
      const max = md.get('max');
      const value = this.getModelValue();
      const input = $(`<input type="${type}" placeholder="${plh}">`);

      if (value) {
        md.set({ value }, { silent: true });
        input.prop('value', value);
      }

      if (min) {
        input.prop('min', min);
      }

      if (max) {
        input.prop('max', max);
      }

      this.$input = input;
    }
    return this.$input.get(0);
  },

  getModelValue() {
    let value;
    const model = this.model;
    const target = this.target;
    const name = model.get('name');

    if (model.get('changeProp')) {
      value = target.get(name);
    } else {
      const attrs = target.get('attributes');
      value = model.get('value') || attrs[name];
    }

    return !isUndefined(value) ? value : '';
  },

  /**
   * Renders input
   * @private
   * */
  renderField() {
    if (!this.$input) {
      this.$el.append(this.tmpl);
      const el = this.getInputEl();
      // I use prepand expecially for checkbox traits
      const inputWrap = this.el.querySelector(`.${this.inputhClass}`);
      inputWrap.insertBefore(el, inputWrap.childNodes[0]);
    }
  },

  render() {
    this.renderLabel();
    this.renderField();
    this.el.className = this.className;
    return this;
  }
});
<|endoftext|>


<commit_before>'use strict';

var Config = require('../src/config');
var fs = require('fs');
var sh = require('shelljs');

describe('Config', function() {
  var config = new Config();

  afterEach(function() {
    sh.rm('-rf', './config/');
  });

  describe('Create config', function() {
    it('should call init and load the methods when creating', function() {
      Config.prototype.init = function() {
      };
      Config.prototype.load = function() {
      };
      spyOn(Config.prototype, 'init').and.callThrough();
      spyOn(Config.prototype, 'load').and.callThrough();

      var config = new Config();

      expect(Config.prototype.init).toHaveBeenCalled();
      expect(Config.prototype.load).toHaveBeenCalled();
    });
  });

  it('should create config data and fs when initing', function() {
    expect(config.fs).toBeDefined();
    expect(config.config.dirName).toEqual('config/');
    expect(config.config.fileName).toEqual('config-manager.json');
  });

  it('should get path', function() {
    var expected = 'config/config-manager.json';
    var path = config.getPath();
    expect(path).toEqual(expected);
  });
});
<commit_msg>Add test<commit_after>'use strict';

var Config = require('../src/config');
var fs = require('fs');
var sh = require('shelljs');

describe('Config', function() {
  var config = new Config();

  afterEach(function() {
    sh.rm('-rf', './config/');
  });

  describe('Create config', function() {
    it('should call init and load the methods when creating', function() {
      Config.prototype.init = function() {
      };
      Config.prototype.load = function() {
      };
      spyOn(Config.prototype, 'init').and.callThrough();
      spyOn(Config.prototype, 'load').and.callThrough();

      var config = new Config();

      expect(Config.prototype.init).toHaveBeenCalled();
      expect(Config.prototype.load).toHaveBeenCalled();
    });
  });

  it('should create config data and fs when initing', function() {
    expect(config.fs).toBeDefined();
    expect(config.config.dirName).toEqual('config/');
    expect(config.config.fileName).toEqual('config-manager.json');
  });

  it('should get path', function() {
    var expected = 'config/config-manager.json';
    var path = config.getPath();
    expect(path).toEqual(expected);
  });

  it('should create', function() {
    config.craeteDir = function() {
    };
    config.save = function() {
    };
    spyOn(config, 'craeteDir').and.callThrough();
    spyOn(config, 'save').and.callThrough();

    config.create();

    expect(config.craeteDir).toHaveBeenCalled();
    expect(config.save).toHaveBeenCalled();
  });
});
<|endoftext|>