<commit_before>/*
 * Copyright (c) 2011 Adam Rudd.
 * See LICENSE for more information
 */

var net = require('net')
  , MqttServer = require('./server').MqttServer
  , MqttSecureServer = require('./server').MqttSecureServer
  , MqttClient = require('./client')
  , MqttConnection = require('./connection')
  , utils = require('./auth_utils')
  , tls = require("tls")
  , url = require('url')
  , fs = require("fs");

var defaultPort = 1883
  , defaultSslPort = 8883
  , defaultHost = 'localhost';

/**
 * connect - connect to an MQTT broker.
 *
 * @param {String} brokerUrl - url of the broker
 * @param {Object} [opts] - see MqttClient#constructor
 */
module.exports.connect = function (brokerUrl, opts) {
  var host, port, auth, query;

  if ('undefined' === typeof brokerUrl) {
    throw new Error('Missing brokerUrl for connect method');
  }

  brokerUrl = url.parse(brokerUrl, true);

  host = brokerUrl.host;
  query = brokerUrl.query;

  opts = opts || {};

  // merge in the auth options if supplied
  utils.parseAuthOptions(brokerUrl.auth, opts);

  // support clientId passed in the query string of the url
  if('string' === typeof query.clientId) {
    opts.clientId = query.clientId;
  }

  if(brokerUrl.protocol.match(/(mqtt|tcp):/)) {
    port = brokerUrl.port || defaultPort;
    return exports.createClient(port, host, opts);
  }

  if(brokerUrl.protocol.match(/(mqtts|ssl):/)) {
    port = brokerUrl.port || defaultSslPort;
    return exports.createSecureClient(port, host, opts);
  }

  throw new Error('Unknown protocol - ' + brokerUrl.protocol);

};

/**
 * createClient - create an MQTT client
 *
 * @param {Number} [port] - broker port
 * @param {String} [host] - broker host
 * @param {Object} [opts] - see MqttClient#constructor
 * @api public
 */
module.exports.createClient = function(port, host, opts) {
  var builder, mqttClient;

  if ('undefined' === typeof port) {
    // createClient()
    port = defaultPort;
    host = defaultHost;
    opts = {};
  } else if ('object' === typeof port) {
    // createClient({})
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    // createClient(1883, {})
    opts = host;
    host = defaultHost;
  }

  if (opts && opts.clean === false && !opts.clientId) {
    throw new Error("Missing clientId for unclean clients");
  }

  builder = function() {
    return net.createConnection(port, host);
  };

  mqttClient = new MqttClient(builder, opts);

  return mqttClient;
};

/**
 * createSecureClient - create a tls secured MQTT client
 *
 * @param {Number} [port]
 * @param {String} [host]
 * @param {Object} opts
 * @api public
 */
module.exports.createSecureClient = function(port, host, opts) {
  var builder, mqttClient, tls_opts = {};

  if ('object' === typeof port) {
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    opts = host;
    host = defaultHost;
  } else if ('object' !== typeof opts) {
    opts = {};
  }

  if (opts && opts.clean === false && !opts.clientId) {
    throw new Error("Missing clientId for unclean clients");
  }

  tls_opts.rejectUnauthorized = false;

  if (opts.keyPath && opts.certPath) {
    tls_opts.key = fs.readFileSync(opts.keyPath);
    tls_opts.cert = fs.readFileSync(opts.certPath);
    tls_opts.ca = [];
    if (opts.ca) {
        for (var i = 0;i<opts.ca.length;i++) {
            tls_opts.ca[i] = fs.readFileSync(opts.ca[i]);
        }
    }
    tls_opts.rejectUnauthorized = opts.rejectUnauthorized || false;
  }

  builder = function() {
    var tls_client = tls.connect(port, host, tls_opts, function() {

      if (process.env.NODE_DEBUG) {
        if (tls_client.authorized) {
          console.log("Connection authorized by a Certificate Authority.");
        } else {
          console.log("Connection not authorized: " + tls_client.authorizationError)
        }
      }

    })

    tls_client.on('secureConnect', function() {
      if (tls_opts.rejectUnauthorized && !tls_client.authorized) {
        throw new Error('TLS not authorized');
      }
    });

    return tls_client;
  };

  mqttClient = new MqttClient(builder, opts);

  return mqttClient;
};

/**
 * createServer - create an MQTT server
 *
 * @param {Function} listener - called on new client connections
 */

module.exports.createServer = function(listener) {
  return new MqttServer(listener);
};

/**
 * createSecureServer - create a tls secured MQTT server
 *
 * @param {String} keyPath - path to private key
 * @param {String} certPath - path to public cert
 * @param {Function} listener - called on new client conns
 */

module.exports.createSecureServer =
function(keyPath, certPath, listener) {
  return new MqttSecureServer(keyPath, certPath, listener);
};

/**
 * createConnection - create a bare MQTT connection
 *
 * @param {Number} [port]
 * @param {String} [host]
 * @param {Function} [callback]
 */
module.exports.createConnection = function(port, host, callback) {
  var net_client, mqtt_conn;
  if ('undefined' === typeof port) {
    // createConnection();
    port = defaultPort;
    host = defaultHost;
    callback = function(){};
  } else if ('function' === typeof port) {
    // createConnection(function(){});
    callback = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('function' === typeof host) {
    // createConnection(1883, function(){});
    callback = host;
    host = defaultHost;
  } else if ('function' !== typeof callback) {
    // createConnection(1883, 'localhost');
    callback = function(){};
  }

  net_client = net.createConnection(port, host);
  mqtt_conn = net_client.pipe(new MqttConnection());

  // Echo net errors
  net_client.on('error', mqtt_conn.emit.bind(mqtt_conn, 'error'));

  net_client.on('close', mqtt_conn.emit.bind(mqtt_conn, 'close'));

  net_client.on('connect', function() {
    mqtt_conn.emit('connected');
  });

  mqtt_conn.once('connected', function() {
    callback(null, mqtt_conn);
  });

  mqtt_conn.once('error', function(err) {
    callback(err);
  });

  return mqtt_conn;
};

// Expose MqttClient
module.exports.MqttClient = MqttClient;

// Expose servers
module.exports.MqttServer = MqttServer;
module.exports.MqttSecureServer = MqttSecureServer;

// Expose Connection
module.exports.MqttConnection = MqttConnection;
<commit_msg>Added small fix for reconnect code not working reliably with TLS connections.<commit_after>/*
 * Copyright (c) 2011 Adam Rudd.
 * See LICENSE for more information
 */

var net = require('net')
  , MqttServer = require('./server').MqttServer
  , MqttSecureServer = require('./server').MqttSecureServer
  , MqttClient = require('./client')
  , MqttConnection = require('./connection')
  , utils = require('./auth_utils')
  , tls = require("tls")
  , url = require('url')
  , fs = require("fs");

var defaultPort = 1883
  , defaultSslPort = 8883
  , defaultHost = 'localhost';

/**
 * connect - connect to an MQTT broker.
 *
 * @param {String} brokerUrl - url of the broker
 * @param {Object} [opts] - see MqttClient#constructor
 */
module.exports.connect = function (brokerUrl, opts) {
  var host, port, auth, query;

  if ('undefined' === typeof brokerUrl) {
    throw new Error('Missing brokerUrl for connect method');
  }

  brokerUrl = url.parse(brokerUrl, true);

  host = brokerUrl.host;
  query = brokerUrl.query;

  opts = opts || {};

  // merge in the auth options if supplied
  utils.parseAuthOptions(brokerUrl.auth, opts);

  // support clientId passed in the query string of the url
  if('string' === typeof query.clientId) {
    opts.clientId = query.clientId;
  }

  if(brokerUrl.protocol.match(/(mqtt|tcp):/)) {
    port = brokerUrl.port || defaultPort;
    return exports.createClient(port, host, opts);
  }

  if(brokerUrl.protocol.match(/(mqtts|ssl):/)) {
    port = brokerUrl.port || defaultSslPort;
    return exports.createSecureClient(port, host, opts);
  }

  throw new Error('Unknown protocol - ' + brokerUrl.protocol);

};

/**
 * createClient - create an MQTT client
 *
 * @param {Number} [port] - broker port
 * @param {String} [host] - broker host
 * @param {Object} [opts] - see MqttClient#constructor
 * @api public
 */
module.exports.createClient = function(port, host, opts) {
  var builder, mqttClient;

  if ('undefined' === typeof port) {
    // createClient()
    port = defaultPort;
    host = defaultHost;
    opts = {};
  } else if ('object' === typeof port) {
    // createClient({})
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    // createClient(1883, {})
    opts = host;
    host = defaultHost;
  }

  if (opts && opts.clean === false && !opts.clientId) {
    throw new Error("Missing clientId for unclean clients");
  }

  builder = function() {
    return net.createConnection(port, host);
  };

  mqttClient = new MqttClient(builder, opts);

  return mqttClient;
};

/**
 * createSecureClient - create a tls secured MQTT client
 *
 * @param {Number} [port]
 * @param {String} [host]
 * @param {Object} opts
 * @api public
 */
module.exports.createSecureClient = function(port, host, opts) {
  var builder, mqttClient, tls_opts = {};

  if ('object' === typeof port) {
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    opts = host;
    host = defaultHost;
  } else if ('object' !== typeof opts) {
    opts = {};
  }

  if (opts && opts.clean === false && !opts.clientId) {
    throw new Error("Missing clientId for unclean clients");
  }

  tls_opts.rejectUnauthorized = false;

  if (opts.keyPath && opts.certPath) {
    tls_opts.key = fs.readFileSync(opts.keyPath);
    tls_opts.cert = fs.readFileSync(opts.certPath);
    tls_opts.ca = [];
    if (opts.ca) {
        for (var i = 0;i<opts.ca.length;i++) {
            tls_opts.ca[i] = fs.readFileSync(opts.ca[i]);
        }
    }
    tls_opts.rejectUnauthorized = opts.rejectUnauthorized || false;
  }

  builder = function() {
    var tls_client = tls.connect(port, host, tls_opts, function() {

      if (process.env.NODE_DEBUG) {
        if (tls_client.authorized) {
          console.log("Connection authorized by a Certificate Authority.");
        } else {
          console.error("Connection not authorized: " + tls_client.authorizationError)
        }
      }

    });

    tls_client.on('secureConnect', function() {
      if (tls_opts.rejectUnauthorized && !tls_client.authorized) {
        throw new Error('TLS not authorized');
      }
    });

    tls_client.on('error', function(err) {
      if (process.env.NODE_DEBUG) {
        console.error("Error occurred in tls_client, ending connection:", err);
      }
      // close this connection to match the behaviour of net
      // otherwise all we get is an error from the tls_client
      // and close event doesn't fire. This is a work around
      // to enable the reconnect code to work the same as with
      // net.createConnection
      this.end();
    }.bind(tls_client));

    return tls_client;
  };

  mqttClient = new MqttClient(builder, opts);

  return mqttClient;
};

/**
 * createServer - create an MQTT server
 *
 * @param {Function} listener - called on new client connections
 */

module.exports.createServer = function(listener) {
  return new MqttServer(listener);
};

/**
 * createSecureServer - create a tls secured MQTT server
 *
 * @param {String} keyPath - path to private key
 * @param {String} certPath - path to public cert
 * @param {Function} listener - called on new client conns
 */

module.exports.createSecureServer =
function(keyPath, certPath, listener) {
  return new MqttSecureServer(keyPath, certPath, listener);
};

/**
 * createConnection - create a bare MQTT connection
 *
 * @param {Number} [port]
 * @param {String} [host]
 * @param {Function} [callback]
 */
module.exports.createConnection = function(port, host, callback) {
  var net_client, mqtt_conn;
  if ('undefined' === typeof port) {
    // createConnection();
    port = defaultPort;
    host = defaultHost;
    callback = function(){};
  } else if ('function' === typeof port) {
    // createConnection(function(){});
    callback = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('function' === typeof host) {
    // createConnection(1883, function(){});
    callback = host;
    host = defaultHost;
  } else if ('function' !== typeof callback) {
    // createConnection(1883, 'localhost');
    callback = function(){};
  }

  net_client = net.createConnection(port, host);
  mqtt_conn = net_client.pipe(new MqttConnection());

  // Echo net errors
  net_client.on('error', mqtt_conn.emit.bind(mqtt_conn, 'error'));

  net_client.on('close', mqtt_conn.emit.bind(mqtt_conn, 'close'));

  net_client.on('connect', function() {
    mqtt_conn.emit('connected');
  });

  mqtt_conn.once('connected', function() {
    callback(null, mqtt_conn);
  });

  mqtt_conn.once('error', function(err) {
    callback(err);
  });

  return mqtt_conn;
};

// Expose MqttClient
module.exports.MqttClient = MqttClient;

// Expose servers
module.exports.MqttServer = MqttServer;
module.exports.MqttSecureServer = MqttSecureServer;

// Expose Connection
module.exports.MqttConnection = MqttConnection;
<|endoftext|>


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

describe('scope module locals', function () {
    var scope;

    beforeEach(function () {
        scope = Scope.create();
        scope.set('expect', expect);
    });
    afterEach(function () {
        scope = null;
    });

    it('should retain locally set globals in subsequent calls', function (done) {
        scope.exec(`
            expect(typeof userSetGlobal).to.equal('undefined');
            userSetGlobal = true;
        `, function (err) {
            if (err) { return done(err); }

            scope.exec('expect(userSetGlobal).to.be.true;', done);
        });
    });
});
<commit_msg>Updated changes in scope locals test<commit_after>var Scope = require('../../');

describe('scope module locals', function () {
    var scope;

    beforeEach(function () {
        scope = Scope.create();
        scope.set('expect', expect);
    });
    afterEach(function () {
        scope = null;
    });

    it('should retain locally set globals in subsequent calls', function (done) {
        scope.exec(`
            expect(this.userSetGlobal).to.be.undefined;
            userSetGlobal = true;
        `, function (err) {
            if (err) { return done(err); }

            scope.exec('expect(userSetGlobal).to.be.true;', done);
        });
    });
});
<|endoftext|>


<commit_before>var eventbus = require('./eventbus');
var mqtt = require('mqtt');
var config = require('../etc/mqtt.json');

const T_SCHEDULE = config.prefix + 'schedule';
const T_SCHEDULE_SET = config.prefix + 'schedule/set';
const T_ZONE_SET = T_SCHEDULE + '/+/set';
const T_ZONE_TEMP_SET = T_SCHEDULE + '/+/temperature/set';
const T_ZONE_TEMP_INC = T_SCHEDULE + '/+/temperature/increase';
const T_ZONE_TEMP_DEC = T_SCHEDULE + '/+/temperature/decrease';

var client = mqtt.connect(config.url);

client.on('connect', function() { // When connected
    console.info('MQTT: Successfully connected');
    client.subscribe(T_SCHEDULE);
    client.subscribe(T_SCHEDULE_SET);
    client.subscribe(T_ZONE_SET);
    client.subscribe(T_ZONE_TEMP_SET);
    client.subscribe(T_ZONE_TEMP_INC);
    client.subscribe(T_ZONE_TEMP_DEC);
});

client.on('close', function() {
   console.info('MQTT: Connection closed');
});

// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
  message = message.toString();
  console.log("MQTT: Recieved a message on "+topic+' topic');
  switch(topic) {
    case T_SCHEDULE:
      // Load last schedule, then unsubscribe
      client.unsubscribe(T_SCHEDULE);
    case T_SCHEDULE_SET:
      eventbus.emit('override.post', { schedule: message });
      break;
    default:

      var match, zone;
      if( (match = topic.match(/schedule\/(\w+?)\/set/)) != null ) {
        zone = match[1];
        console.log("MQTT: zone "+zone+" requested to be "+message);
        if( message == 'on' || message == 'off' ) {
          eventbus.emit('override.post', { zone: zone, state: message });
        } else {
          console.log("MQTT: Ignored, should be on or off");
        }
      } else if( (match = topic.match(/schedule\/(\w+?)\/temperature\/(set|increase|decrease)/)) != null ) {
        zone = match[1];
        var action = match[2];
        console.log("MQTT: zone "+zone+" requested temperature to be "+message);
        var temp = parseFloat(message);
        if( !isNaN( temp ) ) {
          if( action == 'set' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target: temp} );
          } else if ( action == 'increase' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target_increase: temp} );
          } else if ( action == 'decrease' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target_decrease: temp} );
          }
        } else {
          console.log('MQTT: Ignoring, not a valid float');
        }
      }
      break;
  }

});

eventbus.on('schedule', msg => {
  client.publish(T_SCHEDULE, msg.schedule, {retain:true});
});

eventbus.on('schedule.event', msg => {
  client.publish(T_SCHEDULE+'/'+msg.zone, msg.state, {retain:true});
  client.publish(T_SCHEDULE+'/'+msg.zone+'/temperature', msg.temperature_target.toString(), {retain:true});
});<commit_msg>relay messages from eventbus<commit_after>var eventbus = require('./eventbus');
var mqtt = require('mqtt');
var config = require('../etc/mqtt.json');
var _ = require('underscore');

const T_SCHEDULE = config.prefix + 'schedule';
const T_SCHEDULE_SET = config.prefix + 'schedule/set';
const T_ZONE_SET = T_SCHEDULE + '/+/set';
const T_ZONE_TEMP_SET = T_SCHEDULE + '/+/temperature/set';
const T_ZONE_TEMP_INC = T_SCHEDULE + '/+/temperature/increase';
const T_ZONE_TEMP_DEC = T_SCHEDULE + '/+/temperature/decrease';

var client = mqtt.connect(config.url);

client.on('connect', function() { // When connected
    console.info('MQTT: Successfully connected');
    client.subscribe(T_SCHEDULE);
    client.subscribe(T_SCHEDULE_SET);
    client.subscribe(T_ZONE_SET);
    client.subscribe(T_ZONE_TEMP_SET);
    client.subscribe(T_ZONE_TEMP_INC);
    client.subscribe(T_ZONE_TEMP_DEC);
});

client.on('close', function() {
   console.info('MQTT: Connection closed');
});

// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
  message = message.toString();
  console.log("MQTT: Recieved a message on "+topic+' topic');
  switch(topic) {
    case T_SCHEDULE:
      // Load last schedule, then unsubscribe
      client.unsubscribe(T_SCHEDULE);
    case T_SCHEDULE_SET:
      eventbus.emit('override.post', { schedule: message });
      break;
    default:

      var match, zone;
      if( (match = topic.match(/schedule\/(\w+?)\/set/)) != null ) {
        zone = match[1];
        console.log("MQTT: zone "+zone+" requested to be "+message);
        if( message == 'on' || message == 'off' ) {
          eventbus.emit('override.post', { zone: zone, state: message });
        } else {
          console.log("MQTT: Ignored, should be on or off");
        }
      } else if( (match = topic.match(/schedule\/(\w+?)\/temperature\/(set|increase|decrease)/)) != null ) {
        zone = match[1];
        var action = match[2];
        console.log("MQTT: zone "+zone+" requested temperature to be "+message);
        var temp = parseFloat(message);
        if( !isNaN( temp ) ) {
          if( action == 'set' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target: temp} );
          } else if ( action == 'increase' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target_increase: temp} );
          } else if ( action == 'decrease' ) {
            eventbus.emit('override.post', {zone: zone, temperature_target_decrease: temp} );
          }
        } else {
          console.log('MQTT: Ignoring, not a valid float');
        }
      }
      break;
  }

});

eventbus.on('schedule', msg => {
  client.publish(T_SCHEDULE, msg.schedule, {retain:true});
});

eventbus.on('schedule.event', msg => {
  if( _.has(msg, 'zone') && _.has(msg, 'state') ) {
    client.publish(T_SCHEDULE+'/'+msg.zone, msg.state, {retain:true});
    if( _.has(msg, 'temperature_target') ) {
      client.publish(T_SCHEDULE+'/'+msg.zone+'/temperature', msg.temperature_target, {retain:true});
    }
  }
});<|endoftext|>


<commit_before>describe('Denimar test', function() {

  var uiDeniGridService;

  /*
  beforeEach(module('ui-deni-grid'));
  beforeEach(function () {
      inject(function ($injector) {
          uiDeniGridService = $injector.get('uiDeniGridService');
      });
  });
  */

  it('Sum value testing', function() {
    var value = 25; //uiDeniGridService.sum(20, 5);
    expect(value).toEqual(25);
  });
});
<commit_msg>implementing tests...<commit_after>describe('Denimar test', function() {

  var uiDeniGridService;

  /*
  beforeEach(module('ui-deni-grid'));
  beforeEach(function () {
      inject(function ($injector) {
          uiDeniGridService = $injector.get('uiDeniGridService');
      });
  });
  */

  it('Sum value testing', function() {
    var value = 25; //uiDeniGridService.sum(20, 5);
    expect(value).toEqual(26);
  });
});
<|endoftext|>


<commit_before>var EventEmitter = require('events');

module.exports = function Node (options) {

    var node = new EventEmitter();
    node._corked = true;
    node._writableState = {needDrain: false};
    node.chunks = [];
    node.pipes = [];

    // write to input sequence
    node.write = function (chunk) {

        // buffer writes if input is full or not yet set
        if (!node._corked && node.input) {
            if (!node.input.write(chunk)) {
                node._corked = true;
                node._writableState.needDrain = true;
            }

            return;
        }

        node.chunks.push(chunk);
    };

    // pipe
    node.pipe = function (dest) {

        if (node.output) {
            return node.output.pipe(dest);
        }

        node.pipes.push(des);
    };

    node.unpipe = function (dest) {

        if (node.output) {
            return node.output.unpipe(dest);
        }

        // ..remove from node.pipes array
    };

    // set seq
    node._link = function (input, output) {

        node.output = output;
        node.input = input;

        // bind ouput events to node
        output.on('end', node.emit.bind(node, 'end'));
        output.on('data', node.emit.bind(node, 'data'));
        output.on('error', node.emit.bind(node, 'error'));

        if (node.pipes[0]) {
            node.pipes.forEach(output.pipe.bind(output));
        }

        // write bufferd chunks to input after drain
        input.on('drain', function () {
            node._corked = false;
            node._writableState.needDrain = false;
            node.emit('drain');

            // emit buffered chunks
            node.chunks.forEach(input.write.bind(input));
            node.chunks = [];
        });

        // write chunks to input if node has ended already
        if (node.ended) {
            node.chunks.forEach(input.write.bind(input));
            node.chunks = [];
            input.end();
        }

        node._corked = false;
    };

    // ending
    node.end = function (chunk) {
        node.ended = true;
        if (node.input) {
            node.input.end(chunk);
        }
    };

    return node;
};
<commit_msg>push chunk form end call<commit_after>var EventEmitter = require('events');

module.exports = function Node (options) {

    var node = new EventEmitter();
    node._corked = true;
    node._writableState = {needDrain: false};
    node.chunks = [];
    node.pipes = [];

    // write to input sequence
    node.write = function (chunk) {

        // buffer writes if input is full or not yet set
        if (!node._corked && node.input) {
            if (!node.input.write(chunk)) {
                node._corked = true;
                node._writableState.needDrain = true;
            }

            return;
        }

        node.chunks.push(chunk);
    };

    // pipe
    node.pipe = function (dest) {

        if (node.output) {
            return node.output.pipe(dest);
        }

        node.pipes.push(des);
    };

    node.unpipe = function (dest) {

        if (node.output) {
            return node.output.unpipe(dest);
        }

        // ..remove from node.pipes array
    };

    // set seq
    node._link = function (input, output) {

        node.output = output;
        node.input = input;

        // bind ouput events to node
        output.on('end', node.emit.bind(node, 'end'));
        output.on('data', node.emit.bind(node, 'data'));
        output.on('error', node.emit.bind(node, 'error'));

        if (node.pipes[0]) {
            node.pipes.forEach(output.pipe.bind(output));
        }

        // write bufferd chunks to input after drain
        input.on('drain', function () {
            node._corked = false;
            node._writableState.needDrain = false;
            node.emit('drain');

            // emit buffered chunks
            node.chunks.forEach(input.write.bind(input));
            node.chunks = [];
        });

        // write chunks to input if node has ended already
        if (node.ended) {
            node.chunks.forEach(input.write.bind(input));
            node.chunks = [];
            input.end();
        }

        node._corked = false;
    };

    // ending
    node.end = function (chunk) {
        node.ended = true;
        if (node.input) {
            node.input.end(chunk);
        }

        if (typeof chunk !== 'undefined') {
            node.chunks.push(chunk);
        }
    };

    return node;
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    config = require('./config'),
    then = require('./util').then;

function processLanguage(opts, cb)
{

    switch (opts.language)
    {
        case 'lua':
            opts.language = 'lua';
            opts.ext = 'lua';
            break;

        case 'js':
        case 'javascript':
        case 'jscript':
            opts.language = 'javascript';
            opts.ext = 'js';
            break;

        case 'coffee':
        case 'coffeescript':
            opts.language = 'coffeescript';
            opts.ext = 'coffee';
            break;

        case 'ts':
        case 'typescript':
            opts.language = 'typescript';
            opts.ext = 'ts';
            break;

        case 'hs':
        case 'haskell':
            opts.language = 'haskell';
            opts.ext = 'hs';
            break;

        case 'clj':
        case 'clojure':
            opts.language = 'clojure';
            opts.ext = 'clj';
            break;

        case 'cl':
        case 'lisp':
            opts.language = 'lisp';
            opts.ext = 'lisp';
            break;

        case 'rkt':
        case 'racket':
            opts.language = 'racket';
            opts.ext = 'rkt';
            break;

        case 'jl':
        case 'julia':
            opts.language = 'julia';
            opts.ext = 'jl';
            break;

        case 'erl':
        case 'erlang':
            opts.language = 'erlang';
            opts.ext = 'erl';
            break;

        case 'rb':
        case 'ruby':
            opts.language = 'ruby';
            opts.ext = 'rb';
            break;

        case 'py':
        case 'python':
            opts.language = 'python';
            opts.ext = 'py';
            break;

        case 'php':
            opts.language = 'php';
            opts.ext = 'php';
            break;

        case 'go':
            opts.language = 'go';
            opts.ext = 'go';
            break;

        case 'cs':
        case 'csharp':
            opts.language = 'csharp';
            opts.ext = 'cs';
            break;

        case 'fsx':
        case 'fsharp':
            opts.language = 'fsharp';
            opts.ext = 'fsx';
            break;

        case 'bash':
        case 'sh':
            opts.language = 'bash';
            opts.ext = 'bs';
            break;

        case 'perl':
        case 'pl':
            opts.language = 'perl';
            opts.ext = 'pl';
            break;

        default:
            return cb('language is missing or not supported');
    }

    cb();
}

// checks one of the code options (setup, solution, fixture, etc),
// converts any inline code into a file, validates the argument if its required.
function processCodeOption(key, opts, required, cb)
{
    var file_key = key + 'File';

    if (required && !opts[key] && !opts[file_key])
    {
        cb(key + ' or ' + file_key + ' must be specified');
    }
    // if a file was provided then we will read it in, as we will likely need to modify it later
    else if (opts[file_key])
    {
        fs.readFile(opts[file_key], 'utf-8', function (err, data)
        {
            if (err)
            {
                cb(err);
            }
            else if (!data)
            {
                cb(key + ' file was not found or has no data');
            }
            else
            {
                opts[key] = data;
                cb();
            }
        });
    }
    else
    {
        cb();
    }
}

module.exports.process = function process(opts, cb)
{

    // make sure the tmp folder exists, in case we need it later.
    try
    {
        fs.mkdirSync('tmp');
    }
    catch (e)
    {
    }

    processLanguage(opts, function ()
    {
        processCodeOption('setup', opts, false, then(cb, function ()
        {
            processCodeOption('solution', opts, true, then(cb, function ()
            {
                processCodeOption('fixture', opts, false, then(cb, function ()
                {
                    // set the default test framework if it isn't already set
                    opts.testFramework = opts.testFramework || config.testFramework.defaults[opts.language];

                    if (opts.debug) console.info('Processed options: ', opts);
                    cb(opts);
                }));
            }));
        }));
    });
};

<commit_msg>Adding C extension<commit_after>var fs = require('fs'),
    config = require('./config'),
    then = require('./util').then;

function processLanguage(opts, cb)
{

    switch (opts.language)
    {
        case 'lua':
            opts.language = 'lua';
            opts.ext = 'lua';
            break;

        case 'js':
        case 'javascript':
        case 'jscript':
            opts.language = 'javascript';
            opts.ext = 'js';
            break;

        case 'coffee':
        case 'coffeescript':
            opts.language = 'coffeescript';
            opts.ext = 'coffee';
            break;

        case 'ts':
        case 'typescript':
            opts.language = 'typescript';
            opts.ext = 'ts';
            break;

        case 'hs':
        case 'haskell':
            opts.language = 'haskell';
            opts.ext = 'hs';
            break;

        case 'clj':
        case 'clojure':
            opts.language = 'clojure';
            opts.ext = 'clj';
            break;

        case 'cl':
        case 'lisp':
            opts.language = 'lisp';
            opts.ext = 'lisp';
            break;

        case 'rkt':
        case 'racket':
            opts.language = 'racket';
            opts.ext = 'rkt';
            break;

        case 'c':
            opts.language = 'c';
            opts.ext = 'c';
            break;

        case 'jl':
        case 'julia':
            opts.language = 'julia';
            opts.ext = 'jl';
            break;

        case 'erl':
        case 'erlang':
            opts.language = 'erlang';
            opts.ext = 'erl';
            break;

        case 'rb':
        case 'ruby':
            opts.language = 'ruby';
            opts.ext = 'rb';
            break;

        case 'py':
        case 'python':
            opts.language = 'python';
            opts.ext = 'py';
            break;

        case 'php':
            opts.language = 'php';
            opts.ext = 'php';
            break;

        case 'go':
            opts.language = 'go';
            opts.ext = 'go';
            break;

        case 'cs':
        case 'csharp':
            opts.language = 'csharp';
            opts.ext = 'cs';
            break;

        case 'fsx':
        case 'fsharp':
            opts.language = 'fsharp';
            opts.ext = 'fsx';
            break;

        case 'bash':
        case 'sh':
            opts.language = 'bash';
            opts.ext = 'bs';
            break;

        case 'perl':
        case 'pl':
            opts.language = 'perl';
            opts.ext = 'pl';
            break;

        default:
            return cb('language is missing or not supported');
    }

    cb();
}

// checks one of the code options (setup, solution, fixture, etc),
// converts any inline code into a file, validates the argument if its required.
function processCodeOption(key, opts, required, cb)
{
    var file_key = key + 'File';

    if (required && !opts[key] && !opts[file_key])
    {
        cb(key + ' or ' + file_key + ' must be specified');
    }
    // if a file was provided then we will read it in, as we will likely need to modify it later
    else if (opts[file_key])
    {
        fs.readFile(opts[file_key], 'utf-8', function (err, data)
        {
            if (err)
            {
                cb(err);
            }
            else if (!data)
            {
                cb(key + ' file was not found or has no data');
            }
            else
            {
                opts[key] = data;
                cb();
            }
        });
    }
    else
    {
        cb();
    }
}

module.exports.process = function process(opts, cb)
{

    // make sure the tmp folder exists, in case we need it later.
    try
    {
        fs.mkdirSync('tmp');
    }
    catch (e)
    {
    }

    processLanguage(opts, function ()
    {
        processCodeOption('setup', opts, false, then(cb, function ()
        {
            processCodeOption('solution', opts, true, then(cb, function ()
            {
                processCodeOption('fixture', opts, false, then(cb, function ()
                {
                    // set the default test framework if it isn't already set
                    opts.testFramework = opts.testFramework || config.testFramework.defaults[opts.language];

                    if (opts.debug) console.info('Processed options: ', opts);
                    cb(opts);
                }));
            }));
        }));
    });
};

<|endoftext|>


<commit_before>var fs = require('fs');
var sep = (/^win/i.test(process.platform) ? '\\' : '/');

function path(p) {
	if (!(this instanceof path)) return new path(p);
	if (p instanceof path) return new path(p.full());

	this.parts = p.split(sep);

	var normalize = function() {
		for (var idx = 0 ; idx < this.parts.length ; idx++) {
			if (idx > 0 && idx < this.parts.length - 1 && this.parts[idx] === '') {
				this.parts.splice(idx, 1);
				idx--;
			} else if (this.parts[idx] == '.') {
				this.parts.splice(idx, 1);
				idx--;
			} else if (idx > 0 && this.parts[idx] == '..') {
				this.parts.splice(idx - 1, 2);
				idx -= 2;
			}
		}
	};

	normalize.call(this);

	this.full = function() {
		return this.parts.join(sep);
	};

	this.isAbsolute = function() {
		return (this.parts.length > 0 && this.parts[0] === '');
	};

	this.isRelative = function() {
		return !this.isAbsolute();
	};

	this.isFile = function() {
		return (this.parts.length > 0 && this.parts[this.parts.length - 1] !== '');
	};

	this.isDirectory = function() {
		return !this.isFile();
	};

	this.isIn = function(p) {
		if (!(p instanceof path)) return this.isIn(new path(p));
		if (p.parts.length <= this.parts.length) {
			for (var idx = 0 ; idx < p.parts.length - (p.isDirectory() ? 1 : 0) ; idx++) {
				if (p.parts[idx] != this.parts[idx]) {
					return false;
				}
			}
			return true;
		}
		return false;
	};

	this.join = function(p) {
		if (!(p instanceof path)) return this.join(new path(p));
		return path(this.parts.concat(p.parts).join(sep));
	};

	this.relative = function(p) {
		if (!(p instanceof path)) return this.relative(new path(p));
		if (p.isRelative()) return this.join(p);
		return path(p);
	};

	this.path = function() {
		if (this.isDirectory()) {
			return path(this.full());
		}
		return path(this.parts.splice(0, this.parts.length - 1).join(sep));
	};

	this.name = function() {
		if (this.isFile()) return this.parts[this.parts.length - 1];
		return '';
	};

	this.base = function() {
		if (this.isFile()) return this.name().split('.')[0];
		return '';
	};

	this.ext = function() {
		if (this.isFile()) return this.name().split('.').splice(1).join('.');
		return '';
	};

	this.level = function() {
		var level = 0;
		for (var idx = 0 ; idx < this.parts.length ; idx++) {
			if (!(idx === 0 && this.parts[idx] === '') && this.parts[idx] !== '.') {
				if (this.parts[idx] == '..') level--;
				else level++;
			}
		}
		return level;
	};

	this.slice = function() {
		return path(this.parts.slice.apply(this.parts, arguments).join(sep));
	};

	this.exists = function(cb) {
		fs.exists(this.full(), cb);
	};

	this.stat = function(cb) {
		fs.stat(this.full(), function(err, stats) {
			cb(err, stats);
		});
	};

	this.sub = function(start, length) {
		if (length === undefined) length = this.parts.length - start;
		var parts = [];
		for (var idx = start ; idx < this.parts.length && idx < start + length ; idx++) {
			parts.push(this.parts[idx]);
		}
		return path(parts.join(sep));
	};

	this.newer = function(other, cb) {
		this.stat(function(err, tStat) {
			if (err) return cb(err);
			other.stat(function(err, oStat) {
				if (err) return cb(err);
				cb(null, (tStat.mtime > oStat.mtime));
			});
		});
	};

	this.older = function(other, cb) {
		return other.newer(this, function(err, newer) {
			if (err) return cb(err);
			cb(null, !newer);
		});
	};

}

module.exports = exports = path;
<commit_msg>FIXED: Corrupted internals.<commit_after>var fs = require('fs');
var sep = (/^win/i.test(process.platform) ? '\\' : '/');

function path(p) {
	if (!(this instanceof path)) return new path(p);
	if (p instanceof path) return new path(p.full());

	this.parts = p.split(sep);

	var normalize = function() {
		for (var idx = 0 ; idx < this.parts.length ; idx++) {
			if (idx > 0 && idx < this.parts.length - 1 && this.parts[idx] === '') {
				this.parts.splice(idx, 1);
				idx--;
			} else if (this.parts[idx] == '.') {
				this.parts.splice(idx, 1);
				idx--;
			} else if (idx > 0 && this.parts[idx] == '..') {
				this.parts.splice(idx - 1, 2);
				idx -= 2;
			}
		}
	};

	normalize.call(this);

	this.full = function() {
		return this.parts.join(sep);
	};

	this.isAbsolute = function() {
		return (this.parts.length > 0 && this.parts[0] === '');
	};

	this.isRelative = function() {
		return !this.isAbsolute();
	};

	this.isFile = function() {
		return (this.parts.length > 0 && this.parts[this.parts.length - 1] !== '');
	};

	this.isDirectory = function() {
		return !this.isFile();
	};

	this.isIn = function(p) {
		if (!(p instanceof path)) return this.isIn(new path(p));
		if (p.parts.length <= this.parts.length) {
			for (var idx = 0 ; idx < p.parts.length - (p.isDirectory() ? 1 : 0) ; idx++) {
				if (p.parts[idx] != this.parts[idx]) {
					return false;
				}
			}
			return true;
		}
		return false;
	};

	this.join = function(p) {
		if (!(p instanceof path)) return this.join(new path(p));
		return path(this.parts.concat(p.parts).join(sep));
	};

	this.relative = function(p) {
		if (!(p instanceof path)) return this.relative(new path(p));
		if (p.isRelative()) return this.join(p);
		return path(p);
	};

	this.path = function() {
		if (this.isDirectory()) {
			return path(this.full());
		}
		var parts = this.parts;
		return path(parts.splice(0, parts.length - 1).join(sep));
	};

	this.name = function() {
		if (this.isFile()) return this.parts[this.parts.length - 1];
		return '';
	};

	this.base = function() {
		if (this.isFile()) return this.name().split('.')[0];
		return '';
	};

	this.ext = function() {
		if (this.isFile()) return this.name().split('.').splice(1).join('.');
		return '';
	};

	this.level = function() {
		var level = 0;
		for (var idx = 0 ; idx < this.parts.length ; idx++) {
			if (!(idx === 0 && this.parts[idx] === '') && this.parts[idx] !== '.') {
				if (this.parts[idx] == '..') level--;
				else level++;
			}
		}
		return level;
	};

	this.slice = function() {
		return path(this.parts.slice.apply(this.parts, arguments).join(sep));
	};

	this.exists = function(cb) {
		fs.exists(this.full(), cb);
	};

	this.stat = function(cb) {
		fs.stat(this.full(), function(err, stats) {
			cb(err, stats);
		});
	};

	this.sub = function(start, length) {
		if (length === undefined) length = this.parts.length - start;
		var parts = [];
		for (var idx = start ; idx < this.parts.length && idx < start + length ; idx++) {
			parts.push(this.parts[idx]);
		}
		return path(parts.join(sep));
	};

	this.newer = function(other, cb) {
		this.stat(function(err, tStat) {
			if (err) return cb(err);
			other.stat(function(err, oStat) {
				if (err) return cb(err);
				cb(null, (tStat.mtime > oStat.mtime));
			});
		});
	};

	this.older = function(other, cb) {
		return other.newer(this, function(err, newer) {
			if (err) return cb(err);
			cb(null, !newer);
		});
	};

}

module.exports = exports = path;
<|endoftext|>


<commit_before>var lob = require('lob-enc');
var util = require('util')
var events = require('events');
var countListeners = events.EventEmitter.listenerCount;

util.inherits(Pipe, events.EventEmitter)

var uids = 0;
function Pipe(type, keepalive)
{
  this.type = type;
  this.isPipe = true;
  this.uid = uids++;
  this.cloaked = false;

  if(keepalive)
    this.keepalive(keepalive);
}

Pipe.prototype.keepalive = function Pipe_keepalive(timeout)
{
  clearInterval(this.timer);
  if(typeof timeout === 'number'){
    this.timer = setInterval(function keepalive_interval(pipe){
      if (!pipe.emit('keepalive'))
        clearInterval(pipe.timer);
    }, timeout, this);
  }
}

Pipe.prototype.send = function Pipe_send()
{
  this.keepalive();
  this.sentAt = Date.now();
  if(!countListeners(this,'send') && !this.onSend)
    return console.log((new Error('internal error, no pipe.onSend')).stack  ,this);
  // automatically add cloaking
  if(this.cloaked && lob.isPacket(arguments[0]))
    arguments[0] = lob.cloak(arguments[0]);

  if (!this.onSend)
    this.emit('send',this,arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
  else
    this.onSend.apply(this, arguments)
},

module.exports.Pipe = Pipe;
<commit_msg>remove old named pipe.js<commit_after><|endoftext|>


<commit_before>var debug = require('debug')('prop');
var events = require('events');
var util = require('util');
var propFn = require('./prop/index');

function Prop(options) {
  var peripheral = options.peripheral;
  var bluetooth = options.bluetooth;
  var service = options.service;

  events.EventEmitter.call(this);

  // PUBLIC
  this.uuid = peripheral.uuid;
  this.name = peripheral.advertisement.localName;

  // PRIVATE
  this._peripheral = peripheral;
  this._bluetooth = bluetooth;
  this._service = service;
  this._characteristics = {
    'ballControl': null,
    'ballNotification': null
  };
  this._colorLastTime;
  this._colorDeferTimer;

  debug('Created prop ' + this.name + ' (uuid: ' + this.uuid + '). Ready to connect.');
}

util.inherits(Prop, events.EventEmitter);

// PUBLIC

Prop.prototype.shutdown = function() {
  return propFn.shutdown({
    prop: this,
    props: this._service.connectedProps,
    characteristic: this._characteristics.ballControl,
    service: this._service
  });
};

Prop.prototype.disconnect = function() {
  this._service.connectedProps.remove(this.uuid);
  this._peripheral.removeListener('disconnect', this.reconnectListener);

  this.emit('disconnected', this);
  this._service.emit('diconnected', this);

  this._peripheral.disconnect();
};

Prop.prototype.chargingIndication = function(options) {
  return propFn.chargingIndication({
    enable: options.enable,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.standAloneMode = function(options) {
  return propFn.standAloneMode({
    enable: options.enable,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.stopMode = function(options) {
  propFn.stopMode({
    seconds: options.seconds,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.standbyMode = function(options) {
  propFn.standbyMode({
    minutes: options.minutes,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.txPower = function(options) {
  propFn.txPower({
    strength: options.strength,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.color = function(options) {
  options = Array.isArray(options) ? { color: options } : options;

  var now = +new Date;
  var threshhold = 100;
  var that = this;

  if (this._colorLastTime && now < this._colorLastTime + threshhold) {
      console.log('defer - last ' + this._colorLastTime + ' now ' + now);
      var deferTime = now;

      // hold on to it
      clearTimeout(this._colorDeferTimer);

      this._colorDeferTimer = setTimeout(function () {
        console.log('rund defered - last ' + that._colorLastTime + ' now ' + now);
        that._colorLastTime = now;

        propFn.color({
          color: options.color,
          color2: options.color2,
          characteristic: that._characteristics.ballControl
        });
      }, threshhold);
    } else {
      console.log('immediate prev last: ' + this._colorLastTime + ' now ' + now);
      this._colorLastTime = now;
      clearTimeout(this._colorDeferTimer);

      propFn.color({
        color: options.color,
        color2: options.color2,
        characteristic: this._characteristics.ballControl
      });
    }
};

Prop.prototype.fade = function(options) {
  propFn.fade({
    colorStart: options.colorStart,
    colorEnd: options.colorEnd,
    duration: options.duration,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.rainbow = function(options) {
  propFn.rainbow({
    duration: options.duration,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.strobe = function(options) {
  propFn.strobe({
    interval: options.interval,
    dutyCycle: options.dutyCycle,
    color: options.color,
    color2: options.color2,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.randomColor = function(options) {
  propFn.randomColor({
    interval: options.interval,
    dutyCycle: options.dutyCycle,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.runSequence = function(options) {
  propFn.runSequence({
    sequenceNo: options.sequenceNo,
    delay: options.delay,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.effectOnEvent = function(options) {
  propFn.effectOnEvent({
    event: options.event,
    command: options.command,
    permanent: options.permanent,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.removeEffectOnEvents = function() {
  propFn.removeEffectOnEvents({
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.upload = function(options) {
  return propFn.upload({
    filePath: options.filePath,
    flashData: this._characteristics.flashData,
    flashControl: this._characteristics.flashControl
  });
};

Prop.prototype.raw = function(options) {
  propFn.raw({
    command: options.command,
    characteristic: this._characteristics.ballControl
  });
};

// PRIVATE
Prop.prototype._connect = function() {
  return propFn.connect({
    prop: this,
    connectedProps: this._service.connectedProps,
    foundProps: this._service.foundProps,
    service: this._service,
    bluetooth: this._bluetooth
  });
};

Prop.prototype._activateEventNotifications = function(service) {
  propFn.activateEventNotifications(this, this._characteristics.ballEventNotification, service);
};

module.exports = Prop;<commit_msg>Cleanup log messages from Prop.color function.<commit_after>var debug = require('debug')('prop');
var events = require('events');
var util = require('util');
var propFn = require('./prop/index');

function Prop(options) {
  var peripheral = options.peripheral;
  var bluetooth = options.bluetooth;
  var service = options.service;

  events.EventEmitter.call(this);

  // PUBLIC
  this.uuid = peripheral.uuid;
  this.name = peripheral.advertisement.localName;

  // PRIVATE
  this._peripheral = peripheral;
  this._bluetooth = bluetooth;
  this._service = service;
  this._characteristics = {
    'ballControl': null,
    'ballNotification': null
  };
  this._colorLastTime;
  this._colorDeferTimer;

  debug('Created prop ' + this.name + ' (uuid: ' + this.uuid + '). Ready to connect.');
}

util.inherits(Prop, events.EventEmitter);

// PUBLIC

Prop.prototype.shutdown = function() {
  return propFn.shutdown({
    prop: this,
    props: this._service.connectedProps,
    characteristic: this._characteristics.ballControl,
    service: this._service
  });
};

Prop.prototype.disconnect = function() {
  this._service.connectedProps.remove(this.uuid);
  this._peripheral.removeListener('disconnect', this.reconnectListener);

  this.emit('disconnected', this);
  this._service.emit('diconnected', this);

  this._peripheral.disconnect();
};

Prop.prototype.chargingIndication = function(options) {
  return propFn.chargingIndication({
    enable: options.enable,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.standAloneMode = function(options) {
  return propFn.standAloneMode({
    enable: options.enable,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.stopMode = function(options) {
  propFn.stopMode({
    seconds: options.seconds,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.standbyMode = function(options) {
  propFn.standbyMode({
    minutes: options.minutes,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.txPower = function(options) {
  propFn.txPower({
    strength: options.strength,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.color = function(options) {
  options = Array.isArray(options) ? { color: options } : options;

  var now = +new Date;
  var threshhold = 100;
  var that = this;

  if (this._colorLastTime && now < this._colorLastTime + threshhold) {
      var deferTime = now;

      // hold on to it
      clearTimeout(this._colorDeferTimer);

      this._colorDeferTimer = setTimeout(function () {
        that._colorLastTime = now;

        propFn.color({
          color: options.color,
          color2: options.color2,
          characteristic: that._characteristics.ballControl
        });
      }, threshhold);
    } else {
      this._colorLastTime = now;
      clearTimeout(this._colorDeferTimer);

      propFn.color({
        color: options.color,
        color2: options.color2,
        characteristic: this._characteristics.ballControl
      });
    }
};

Prop.prototype.fade = function(options) {
  propFn.fade({
    colorStart: options.colorStart,
    colorEnd: options.colorEnd,
    duration: options.duration,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.rainbow = function(options) {
  propFn.rainbow({
    duration: options.duration,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.strobe = function(options) {
  propFn.strobe({
    interval: options.interval,
    dutyCycle: options.dutyCycle,
    color: options.color,
    color2: options.color2,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.randomColor = function(options) {
  propFn.randomColor({
    interval: options.interval,
    dutyCycle: options.dutyCycle,
    mode: options.mode,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.runSequence = function(options) {
  propFn.runSequence({
    sequenceNo: options.sequenceNo,
    delay: options.delay,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.effectOnEvent = function(options) {
  propFn.effectOnEvent({
    event: options.event,
    command: options.command,
    permanent: options.permanent,
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.removeEffectOnEvents = function() {
  propFn.removeEffectOnEvents({
    characteristic: this._characteristics.ballControl
  });
};

Prop.prototype.upload = function(options) {
  return propFn.upload({
    filePath: options.filePath,
    flashData: this._characteristics.flashData,
    flashControl: this._characteristics.flashControl
  });
};

Prop.prototype.raw = function(options) {
  propFn.raw({
    command: options.command,
    characteristic: this._characteristics.ballControl
  });
};

// PRIVATE
Prop.prototype._connect = function() {
  return propFn.connect({
    prop: this,
    connectedProps: this._service.connectedProps,
    foundProps: this._service.foundProps,
    service: this._service,
    bluetooth: this._bluetooth
  });
};

Prop.prototype._activateEventNotifications = function(service) {
  propFn.activateEventNotifications(this, this._characteristics.ballEventNotification, service);
};

module.exports = Prop;<|endoftext|>


<commit_before>const fse = require('fs-extra');
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const { JHIPSTER_CONFIG_DIR } = require('../../generators/generator-constants');
const { appDefaultConfig, serverDefaultConfig } = require('../../generators/generator-defaults');

const mockedComposedGenerators = ['jhipster:entity-client', 'jhipster:entity-server', 'jhipster:database-changelog'];

describe('jhipster:entities with entitiesToImport option', () => {
  const localConfig = { baseName: 'jhipster', ...appDefaultConfig, ...serverDefaultConfig };
  describe('with --with-entities', () => {
    describe('and single entity', () => {
      let runResult;
      before(() => {
        return helpers
          .create(require.resolve('../../generators/entities'))
          .withOptions({
            localConfig,
            entitiesToImport: [{ name: 'Foo' }],
            fromCli: true,
            skipInstall: true,
            defaults: true,
            withEntities: true,
          })
          .withMockedGenerators(mockedComposedGenerators)
          .run()
          .then(result => {
            runResult = result;
          });
      });

      after(() => runResult.cleanup());

      it('writes .yo-rc.json', () => {
        runResult.assertFile('.yo-rc.json');
        runResult.assertFileContent('.yo-rc.json', /"baseName": "jhipster"/);
      });
      it('writes entity config file', () => {
        runResult.assertFile('.jhipster/Foo.json');
        runResult.assertFileContent('.jhipster/Foo.json', /"name": "Foo"/);
      });
      it('should compose with entity-client generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:entity-client'];
        assert(EntityGenerator.calledOnce);
        assert.equal(EntityGenerator.getCall(0).args[0], 'Foo');
      });
      it('should compose with entity-server generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:entity-server'];
        assert(EntityGenerator.calledOnce);
        assert.equal(EntityGenerator.getCall(0).args[0], 'Foo');
      });
    });

    describe('and 2 entities', () => {
      let runResult;
      before(() => {
        return helpers
          .create(require.resolve('../../generators/entities'))
          .withOptions({
            localConfig,
            entitiesToImport: [{ name: 'Foo' }, { name: 'Bar' }],
            fromCli: true,
            skipInstall: true,
            defaults: true,
            withEntities: true,
          })
          .withMockedGenerators(mockedComposedGenerators)
          .run()
          .then(result => {
            runResult = result;
          });
      });

      after(() => runResult.cleanup());

      it('writes .yo-rc.json', () => {
        runResult.assertFile('.yo-rc.json');
        runResult.assertFileContent('.yo-rc.json', /"baseName": "jhipster"/);
      });
      it('writes entity config file', () => {
        runResult.assertFile('.jhipster/Foo.json');
        runResult.assertFileContent('.jhipster/Foo.json', /"name": "Foo"/);
        runResult.assertFile('.jhipster/Bar.json');
        runResult.assertFileContent('.jhipster/Bar.json', /"name": "Bar"/);
      });
      it('should compose with entity-client generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:entity-client'];
        assert.equal(EntityGenerator.callCount, 2);
        assert.equal(EntityGenerator.getCall(0).args[0], 'Foo');
        assert.equal(EntityGenerator.getCall(1).args[0], 'Bar');
      });
      it('should compose with database-changelog generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:database-changelog'];
        assert.equal(EntityGenerator.callCount, 1);
        assert.deepStrictEqual(EntityGenerator.getCall(0).args[0], ['Foo', 'Bar']);
      });
    });

    describe('and 1 entity and 1 entity file', () => {
      let runResult;
      before(() => {
        return helpers
          .create(require.resolve('../../generators/entities'))
          .withOptions({
            localConfig,
            entitiesToImport: [{ name: 'Foo', changelogDate: '20201012010501' }],
            fromCli: true,
            skipInstall: true,
            defaults: true,
            withEntities: true,
          })
          .doInDir(dir => {
            const entitiesPath = path.join(dir, JHIPSTER_CONFIG_DIR);
            fse.ensureDirSync(entitiesPath);
            const entityPath = path.join(entitiesPath, 'Bar.json');
            fse.writeFileSync(entityPath, '{"changelogDate": "20201012010502"}');
          })
          .withMockedGenerators(mockedComposedGenerators)
          .run()
          .then(result => {
            runResult = result;
          });
      });

      after(() => runResult.cleanup());

      it('should compose with mocked entity-client generator ordered by changelogDate', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:entity-client'];
        assert.equal(EntityGenerator.callCount, 2);
        assert.deepStrictEqual(EntityGenerator.getCall(0).args[0], ['Foo']);
        assert.deepStrictEqual(EntityGenerator.getCall(1).args[0], ['Bar']);
      });
      it('should compose with database-changelog generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:database-changelog'];
        assert.equal(EntityGenerator.callCount, 1);
        assert.deepStrictEqual(EntityGenerator.getCall(0).args[0], ['Foo', 'Bar']);
      });
    });

    describe('and more than 1 entity and more than 1 entity file', () => {
      let runResult;
      before(() => {
        return helpers
          .create(require.resolve('../../generators/entities'))
          .withOptions({
            localConfig,
            entitiesToImport: [
              { name: 'Four', changelogDate: '20201012010500' },
              { name: 'Two', changelogDate: '20201012010502' },
            ],
            fromCli: true,
            skipInstall: true,
            defaults: true,
            withEntities: true,
          })
          .doInDir(dir => {
            const entitiesPath = path.join(dir, JHIPSTER_CONFIG_DIR);
            fse.ensureDirSync(entitiesPath);
            fse.writeFileSync(path.join(entitiesPath, 'One.json'), '{"changelogDate": "20201012010503"}');
            fse.writeFileSync(path.join(entitiesPath, 'Three.json'), '{"changelogDate": "20201012010501"}');
          })
          .withMockedGenerators(mockedComposedGenerators)
          .run()
          .then(result => {
            runResult = result;
          });
      });

      after(() => runResult.cleanup());

      it('should compose with mocked entity-client generator ordered by changelogDate', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:entity-client'];
        assert.equal(EntityGenerator.callCount, 4);
        assert.deepStrictEqual(EntityGenerator.getCall(0).args[0], ['Four']);
        assert.deepStrictEqual(EntityGenerator.getCall(1).args[0], ['Three']);
        assert.deepStrictEqual(EntityGenerator.getCall(2).args[0], ['Two']);
        assert.deepStrictEqual(EntityGenerator.getCall(3).args[0], ['One']);
      });
      it('should compose with database-changelog generator', () => {
        const EntityGenerator = runResult.mockedGenerators['jhipster:database-changelog'];
        assert.equal(EntityGenerator.callCount, 1);
        assert.deepStrictEqual(EntityGenerator.getCall(0).args[0], ['Four', 'Three', 'Two', 'One']);
      });
    });
  });
});
<commit_msg>drop entities composing test<commit_after><|endoftext|>


<commit_before>var helper = require("../../helper");
var Manager = require("../../../src/etl/dim-unit-etl-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

// it("#01. should success when create etl for dim-unit", function (done) {
//     instanceManager.run()
//         .then((a) => {
//             done();
//         })
//         .catch((e) => {
//             done(e);
//         });
// });

it("#02. should success when transforming data for dim-category", function (done) {
    var data = [{}, {}];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

// it("#03. should error when load empty data", function (done) {
//     instanceManager.load({})
//         .then(id => {
//             done("should error when create with empty data");
//         })
//         .catch(e => {
//             try {
//                 done();
//             }
//             catch (ex) {
//                 done(ex);
//             }
//         });
// });<commit_msg>update etl<commit_after>var helper = require("../../helper");
var Manager = require("../../../src/etl/dim-unit-etl-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

it("#01. should success when create etl for dim-unit", function (done) {
    instanceManager.run()
        .then((a) => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#02. should success when transforming data for dim-category", function (done) {
    var data = [{}, {}];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#03. should error when load empty data", function (done) {
    instanceManager.load({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});<|endoftext|>


<commit_before>'use strict';

// mocha defines to avoid JSHint breakage
/* global describe, it, before, beforeEach, after, afterEach */

var preq   = require('preq');
var assert = require('../../utils/assert.js');
var server = require('../../utils/server.js');

describe('errors', function() {

    this.timeout(20000);

    before(function () { return server.start(); });

    // common URI prefix for the errors
    var uri = server.config.uri + 'ex/err/';

    it('array creation error', function() {
        return preq.get({
            uri: uri + 'array'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'RangeError');
        });
    });

    it('file read error', function() {
        return preq.get({
            uri: uri + 'file'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'OperationalError');
        });
    });

    it('constraint check error', function() {
        return preq.get({
            uri: uri + 'manual/error'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'Error');
        });
    });

    it('access denied error', function() {
        return preq.get({
            uri: uri + 'manual/deny'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 403);
            // check the error title
            assert.deepEqual(err.body.type, 'access_denied');
        });
    });

    it('authorisation error', function() {
        return preq.get({
            uri: uri + 'manual/auth'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 401);
            // check the error title
            assert.deepEqual(err.body.type, 'unauthorized');
        });
    });

});

<commit_msg>Updated unit tests<commit_after>'use strict';

// mocha defines to avoid JSHint breakage
/* global describe, it, before, beforeEach, after, afterEach */

var preq   = require('preq');
var assert = require('../../utils/assert.js');
var server = require('../../utils/server.js');

describe('errors', function() {

    this.timeout(20000);

    before(function () { return server.start(); });

    // common URI prefix for the errors
    var uri = server.config.uri + 'ex/err/';

    it('array creation error', function() {
        return preq.get({
            uri: uri + 'array'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'RangeError');
        });
    });

    it('file read error', function() {
        return preq.get({
            uri: uri + 'file'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'Error');
        });
    });

    it('constraint check error', function() {
        return preq.get({
            uri: uri + 'manual/error'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 500);
            // check the error title
            assert.deepEqual(err.body.title, 'Error');
        });
    });

    it('access denied error', function() {
        return preq.get({
            uri: uri + 'manual/deny'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 403);
            // check the error title
            assert.deepEqual(err.body.type, 'access_denied');
        });
    });

    it('authorisation error', function() {
        return preq.get({
            uri: uri + 'manual/auth'
        }).then(function(res) {
            // if we are here, no error was thrown, not good
            throw new Error('Expected an error to be thrown, got status: ' + res.status);
        }, function(err) {
            // inspect the status
            assert.deepEqual(err.status, 401);
            // check the error title
            assert.deepEqual(err.body.type, 'unauthorized');
        });
    });

});

<|endoftext|>


<commit_before>/*
 * Load files *locally* (GeoJSON, KML, GPX) into the map
 * using the HTML5 File API.
 *
 * Requires Pavel Shramov's GPX.js
 * https://github.com/shramov/leaflet-plugins/blob/d74d67/layer/vector/GPX.js
 */
var FileLoader = L.Class.extend({
    includes: L.Mixin.Events,
    options: {
        layerOptions: {}
    },

    initialize: function (map, options) {
        this._map = map;
        L.Util.setOptions(this, options);

        this._parsers = {
            'geojson': this._loadGeoJSON,
            'gpx': this._convertToGeoJSON,
            'kml': this._convertToGeoJSON
        };
    },

    load: function (file /* File */) {
        // Check file extension
        var ext = file.name.split('.').pop(),
            parser = this._parsers[ext];
        if (!parser) {
            window.alert("Unsupported file type " + file.type + '(' + ext + ')');
            return;
        }
        // Read selected file using HTML5 File API
        var reader = new FileReader();
        reader.onload = L.Util.bind(function (e) {
            this.fire('data:loading', {filename: file.name, format: ext});
            var layer = parser.call(this, e.target.result, ext);
            this.fire('data:loaded', {layer: layer, filename: file.name, format: ext});
        }, this);
        reader.readAsText(file);
    },

    _loadGeoJSON: function (content) {
        var layer = L.geoJson(content, this.options.layerOptions);
        if (typeof content == 'string') {
            content = JSON.parse(content);
        }
        return layer.addTo(this._map);
    },

    _convertToGeoJSON: function (content, format) {
        // Format is either 'gpx' or 'kml'
        if (typeof content == 'string') {
            content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
        }
        var geojson = toGeoJSON[format](content);
        return this._loadGeoJSON(geojson);
    }
});

L.Control.FileLayerLoad = L.Control.extend({
    statics: {
        TITLE: 'Load local file (GPX, KML, GeoJSON)',
        LABEL: '⌅'
    },
    options: {
        position: 'topleft',
        fitBounds: true,
        layerOptions: {}
    },

    initialize: function (options) {
        L.Util.setOptions(this, options);
        this.loader = null;
    },

    onAdd: function (map) {
        this.loader = new FileLoader(map, {layerOptions: this.options.layerOptions});

        this.loader.on('data:loaded', function (e) {
            // Fit bounds after loading
            if (this.options.fitBounds) {
                window.setTimeout(function () {
                    map.fitBounds(e.layer.getBounds()).zoomOut();
                }, 500);
            }
        }, this);

        return this._initContainer();
    },

    _initContainer: function () {
        // Create an invisible file input
        var fileInput = L.DomUtil.create('input', 'hidden', container);
        fileInput.type = 'file';
        fileInput.accept = '.gpx,.kml,.geojson';
        fileInput.style.display = 'none';
        // Load on file change
        var fileLoader = this.loader;
        fileInput.addEventListener("change", function (e) {
            fileLoader.load(this.files[0]);
        }, false);

        // Create a button, and bind click on hidden file input
        var zoomName = 'leaflet-control-filelayer leaflet-control-zoom',
            barName = 'leaflet-bar',
            partName = barName + '-part',
            container = L.DomUtil.create('div', zoomName + ' ' + barName);
        var link = L.DomUtil.create('a', zoomName + '-in ' + partName, container);
        link.innerHTML = L.Control.FileLayerLoad.LABEL;
        link.href = '#';
        link.title = L.Control.FileLayerLoad.TITLE;

        var stop = L.DomEvent.stopPropagation;
        L.DomEvent
            .on(link, 'click', stop)
            .on(link, 'mousedown', stop)
            .on(link, 'dblclick', stop)
            .on(link, 'click', L.DomEvent.preventDefault)
            .on(link, 'click', function (e) {
                fileInput.click();
                e.preventDefault();
            });
        return container;
    }
});

L.Control.fileLayerLoad = function (options) {
    return new L.Control.FileLayerLoad(options);
};
<commit_msg>First implementation of Drag-n-drop (fixes #1)<commit_after>/*
 * Load files *locally* (GeoJSON, KML, GPX) into the map
 * using the HTML5 File API.
 *
 * Requires Pavel Shramov's GPX.js
 * https://github.com/shramov/leaflet-plugins/blob/d74d67/layer/vector/GPX.js
 */
var FileLoader = L.Class.extend({
    includes: L.Mixin.Events,
    options: {
        layerOptions: {}
    },

    initialize: function (map, options) {
        this._map = map;
        L.Util.setOptions(this, options);

        this._parsers = {
            'geojson': this._loadGeoJSON,
            'gpx': this._convertToGeoJSON,
            'kml': this._convertToGeoJSON
        };
    },

    load: function (file /* File */) {
        // Check file extension
        var ext = file.name.split('.').pop(),
            parser = this._parsers[ext];
        if (!parser) {
            window.alert("Unsupported file type " + file.type + '(' + ext + ')');
            return;
        }
        // Read selected file using HTML5 File API
        var reader = new FileReader();
        reader.onload = L.Util.bind(function (e) {
            this.fire('data:loading', {filename: file.name, format: ext});
            var layer = parser.call(this, e.target.result, ext);
            this.fire('data:loaded', {layer: layer, filename: file.name, format: ext});
        }, this);
        reader.readAsText(file);
    },

    _loadGeoJSON: function (content) {
        var layer = L.geoJson(content, this.options.layerOptions);
        if (typeof content == 'string') {
            content = JSON.parse(content);
        }
        return layer.addTo(this._map);
    },

    _convertToGeoJSON: function (content, format) {
        // Format is either 'gpx' or 'kml'
        if (typeof content == 'string') {
            content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
        }
        var geojson = toGeoJSON[format](content);
        return this._loadGeoJSON(geojson);
    }
});

L.Control.FileLayerLoad = L.Control.extend({
    statics: {
        TITLE: 'Load local file (GPX, KML, GeoJSON)',
        LABEL: '⌅'
    },
    options: {
        position: 'topleft',
        fitBounds: true,
        layerOptions: {}
    },

    initialize: function (options) {
        L.Util.setOptions(this, options);
        this.loader = null;
    },

    onAdd: function (map) {
        this.loader = new FileLoader(map, {layerOptions: this.options.layerOptions});

        this.loader.on('data:loaded', function (e) {
            // Fit bounds after loading
            if (this.options.fitBounds) {
                window.setTimeout(function () {
                    map.fitBounds(e.layer.getBounds()).zoomOut();
                }, 500);
            }
        }, this);

        // Initialize Drag-and-drop
        this._initDragAndDrop(map);

        // Initialize map control
        return this._initContainer();
    },

    _initDragAndDrop: function (map) {
        var fileLoader = this.loader,
            dropbox = map._container;

        var callbacks = {
            dragenter: function () {
                map.scrollWheelZoom.disable();
            },
            dragleave: function () {
                map.scrollWheelZoom.enable();
            },
            dragover: function (e) {
                e.stopPropagation();
                e.preventDefault();
            },
            drop: function (e) {
                e.stopPropagation();
                e.preventDefault();

                var files = Array.prototype.slice.apply(e.dataTransfer.files),
                    i = files.length;
                setTimeout(function(){
                    fileLoader.load(files.shift());
                    if (files.length > 0) {
                        setTimeout(arguments.callee, 25);
                    }
                }, 25);
                map.scrollWheelZoom.enable();
            }
        };
        for (var name in callbacks)
            dropbox.addEventListener(name, callbacks[name], false);
    },

    _initContainer: function () {
        // Create an invisible file input
        var fileInput = L.DomUtil.create('input', 'hidden', container);
        fileInput.type = 'file';
        fileInput.accept = '.gpx,.kml,.geojson';
        fileInput.style.display = 'none';
        // Load on file change
        var fileLoader = this.loader;
        fileInput.addEventListener("change", function (e) {
            fileLoader.load(this.files[0]);
        }, false);

        // Create a button, and bind click on hidden file input
        var zoomName = 'leaflet-control-filelayer leaflet-control-zoom',
            barName = 'leaflet-bar',
            partName = barName + '-part',
            container = L.DomUtil.create('div', zoomName + ' ' + barName);
        var link = L.DomUtil.create('a', zoomName + '-in ' + partName, container);
        link.innerHTML = L.Control.FileLayerLoad.LABEL;
        link.href = '#';
        link.title = L.Control.FileLayerLoad.TITLE;

        var stop = L.DomEvent.stopPropagation;
        L.DomEvent
            .on(link, 'click', stop)
            .on(link, 'mousedown', stop)
            .on(link, 'dblclick', stop)
            .on(link, 'click', L.DomEvent.preventDefault)
            .on(link, 'click', function (e) {
                fileInput.click();
                e.preventDefault();
            });
        return container;
    }
});

L.Control.fileLayerLoad = function (options) {
    return new L.Control.FileLayerLoad(options);
};
<|endoftext|>


<commit_before>require("soya-next/config/default");

process.on("unhandledRejection", err => {
  // eslint-disable-next-line no-console
  console.error(err);
});

const express = require("express");
const next = require("next");
const { join } = require("path");
const { createRouter } = require("soya-next/server/router");
const config = require("config");
// @remove-on-eject-begin
const conf = require("../next.config");
// @remove-on-eject-end

const { appDir } = require("../config/paths");
const app = next({
  dev: true
  // @remove-on-eject-begin
  // eslint-disable-next-line comma-style
  , conf
  // @remove-on-eject-end
});
const buildSoya = require("./utils/build-soya");

app
  .prepare()
  .then(() => buildSoya({ dev: true }))
  .then(() => require.resolve("soya"))
  .then(
    stats =>
      stats ? require(join(appDir, "build/server", "index.js")).default : null,
    err => {
      if (err.code !== "MODULE_NOT_FOUND") {
        throw err;
      }
    }
  )
  .then((soyaMiddleware = null) => {
    const server = express();
    if (soyaMiddleware !== null) {
      server.use(soyaMiddleware);
    }
    server.use(
      createRouter(app, {
        basePath: config.basePath,
        routes: config.routes,
        redirects: config.redirects,
        defaultLocale: config.defaultLocale,
        siteLocales: config.siteLocales,
        compression: config.server.compression,
        whoami: config.whoami
      })
    );
    server.listen(config.server.port, config.server.host, err => {
      if (err) {
        throw err;
      }

      if (typeof process.send === "function") {
        process.send("ready");
      }

      // eslint-disable-next-line no-console
      console.log(`> Ready on ${config.server.host}:${config.server.port}`);
    });
  })
  .catch(ex => {
    // eslint-disable-next-line no-console
    console.error(ex.stack);
    process.exit(1);
  });
<commit_msg>Add --skip-soya-legacy<commit_after>require("soya-next/config/default");

process.on("unhandledRejection", err => {
  // eslint-disable-next-line no-console
  console.error(err);
});

const express = require("express");
const next = require("next");
const { join } = require("path");
const { createRouter } = require("soya-next/server/router");
const config = require("config");
// @remove-on-eject-begin
const conf = require("../next.config");
// @remove-on-eject-end

const { appDir } = require("../config/paths");
const app = next({
  dev: true
  // @remove-on-eject-begin
  // eslint-disable-next-line comma-style
  , conf
  // @remove-on-eject-end
});
const argv = process.argv ? process.argv.slice(2) : [];
const shouldBuildSoyaLegacy = argv.indexOf("--skip-soya-legacy") === -1;
const buildSoya = shouldBuildSoyaLegacy ? require("./utils/build-soya") : null;

app
  .prepare()
  .then(
    () =>
      shouldBuildSoyaLegacy
        ? buildSoya({ dev }).then(() => require.resolve("soya"))
        : null
  )
  .then(
    stats =>
      stats ? require(join(appDir, "build/server", "index.js")).default : null,
    err => {
      if (err.code !== "MODULE_NOT_FOUND") {
        throw err;
      }
    }
  )
  .then((soyaMiddleware = null) => {
    const server = express();
    if (soyaMiddleware !== null) {
      server.use(soyaMiddleware);
    }
    server.use(
      createRouter(app, {
        basePath: config.basePath,
        routes: config.routes,
        redirects: config.redirects,
        defaultLocale: config.defaultLocale,
        siteLocales: config.siteLocales,
        compression: config.server.compression,
        whoami: config.whoami
      })
    );
    server.listen(config.server.port, config.server.host, err => {
      if (err) {
        throw err;
      }

      if (typeof process.send === "function") {
        process.send("ready");
      }

      // eslint-disable-next-line no-console
      console.log(`> Ready on ${config.server.host}:${config.server.port}`);
    });
  })
  .catch(ex => {
    // eslint-disable-next-line no-console
    console.error(ex.stack);
    process.exit(1);
  });
<|endoftext|>


<commit_before>Topics = new Mongo.Collection('topics');

TopicSchema = new SimpleSchema({
  title: {
    type: String
  },
  categoryId: {
    type: String
  },
  body: {
    type: String
  },
  author: {
    type: String
  },
  authorId: {
    type: String
  },
  slug: {
    type: String,
    index: true,
    unique: true
  },
  createdAt: {
    type: Date,
    autoValue: function () {
      return new Date();
    }
  }
});

Topics.attachSchema(TopicSchema);
<commit_msg>Add custom validation message for uniqueness constraint for topic slug<commit_after>Topics = new Mongo.Collection('topics');

TopicSchema = new SimpleSchema({
  title: {
    type: String
  },
  categoryId: {
    type: String
  },
  body: {
    type: String
  },
  author: {
    type: String
  },
  authorId: {
    type: String
  },
  slug: {
    type: String,
    index: true,
    unique: true
  },
  createdAt: {
    type: Date,
    autoValue: function () {
      return new Date();
    }
  }
});

Topics.attachSchema(TopicSchema);

Topics.simpleSchema().messages({
  notUnique: 'A duplicate slug exists.'
});
<|endoftext|>