<commit_before>/**
 * Dynamically load templates
 * @param  {[type]}   name     [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
dust.onLoad = function(name, callback) {
  $.ajax('templates/' + name + '.tpl', {
    success: function(data) {
      callback(undefined, data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      callback(textStatus, undefined);
    }
  });
};

/**
 * Formbuilder
 * Copyright (c) 2009, 2014 (v2) Mike Botsko, Helion3 LLC (http://www.helion3.com)
 * http://www.botsko.net/blog/2009/04/jquery-form-builder-plugin/
 * Originally designed for AspenMSM, a CMS product from Trellis Development
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 */
(function (window,undefined){

  var formbuilder = function( opts ){
    return new formbuilderEngine(opts);
  };

  var formbuilderEngine = function(opts){

    if( !_.has(opts,'targets') || !_.isObject(opts.targets) || opts.targets.length === 0 ){
      throw new Error('Invalid or missing target element(s)');
    }

    if( !_.has(opts,'save_url') || !_.isString(opts.save_url) || opts.save_url.trim() === '' ){
      throw new Error('Invalid or missing save url');
    }

    // Define all default options
    var defaultOptions = {

      // A unique ID shared with the server-side code
      form_id: 'frmb-'+_.now(),

      // Injected model, allows us to start with an
      // existing form
      startingModel: false,

      // A dom-lib wrapped element
      targets: false,

      // A url we'll POST form data to on save
      save_url: false,

      // Description of allowed field types
      field_types: [
        {
          key: 'text',
          label: 'Text',
          schema: {
            name: false,
            label: '',
            required: false
          }
        },{
          key: 'textarea',
          label: 'Textarea',
          schema: {
            name: false,
            label: '',
            required: false
          }
        },{
          key: 'select',
          label: 'Select',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        },{
          key: 'radio',
          label: 'Radio',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        },{
          key: 'checkbox',
          label: 'Checkbox',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        }
      ]
    };

    this._opts = _.assign(defaultOptions,opts);

    (function(engine){

      var targets = engine._opts.targets;

      engine.render();

          // Load the starting model
      if( _.isObject(engine._opts.startingModel) ){

        engine._model = engine._opts.startingModel;
        // @todo validate against the field schema

        // Iterate model and render proper editors
        _.each(engine._model,function(model,id){

          var field = engine.getFieldTypeByName( model.type );
          engine.addFormElementEditor( field, model );

          // console.log(field);
          // console.log(model);
          // console.log(id);
        })

      }

      /**
       * Event listeners
       */

      // New form element editor
      targets.on('change', '.frmb-add-elem', function(){
        var val = $(this).val();
        engine.addFormElementEditor( engine.getFieldTypeByName(val) );
        $(this).val('');
      });

      // Add a choice entry
      targets.on('click', '.frmb-add-choice', function(e){
        e.preventDefault();
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');

        var fieldType = engine.getFieldTypeByName( engine._model[id].type );

        engine.appendFieldToFormElementEditor( parent, fieldType, engine._model[id] );

        return false;
      });

      // Remove a form element editor
      targets.on('click', '.frmb-remove', function(e){
        e.preventDefault();
        var elem = $(this);
        var parent = elem.parents('.frmb-group:eq(0)');
        var id = parent.attr('id');
        engine.removeModel( id );
        parent.remove();
        return false;
      });

      // Update model with keyboard entries
      targets.on('keyup', 'input[type=text]', function(e){

        // specific field editor container
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');
        var type = elem.attr('name').replace(id+'_', '');

        engine.setModelValue( id, type, elem.val() );

      });

      // Update model with checkbox entries
      targets.on('change', 'input[type=checkbox]', function(e){

        // specific field editor container
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');
        var type = elem.attr('name').replace(id+'_', '');

        engine.setModelValue( id, type, elem.is(':checked') );

      });

      // Save
      targets.on('click', '.frmb-save', function(e){
        e.preventDefault();
        engine.save();
        return false;
      });

    })(this);

    return this;

  };

  formbuilderEngine.prototype = {

    // store options
    _opts: false,

    // current object representing the form
    _model: {},

    /**
     * Render the form editor
     * @return {[type]} [description]
     */
    render: function(){

      var self = this;

      // Pass data to the original rendering
      var frmObj = {
        field_types: this._opts.field_types
      };

      dust.render('base', frmObj, function(err, out) {

        // Append final content
        self._opts.targets.append( out );

      });
    },

    /**
     * Returns the field type object by given name
     * @param  {string} field_type_name Field type name
     * @return {object}
     */
    getFieldTypeByName: function( field_type_name ){
      return _.find(this._opts.field_types, { 'key': field_type_name });
    },

    /**
     * Add a new form element editing box
     */
    addFormElementEditor: function( field, existingModel ){

      var self = this;

      if( !_.isObject(field) ){
        throw new Error('Failed to add form element editor: Invalid field object');
      }

      // Determine field name
      var name = field.key + '_' + _.now();
      if( _.has(existingModel,'name') && _.isString(existingModel.name) ){
        name = existingModel.name;
      }
      else if( _.isString(field.name) ){
        name = field.name;
      }

      // Create a new model entry
      if( !_.isObject(existingModel) ){
        self._model[name] = _.assign(field.schema, {
          name: name,
          type: field.key
        });
        existingModel = self._model[name];
      }

      // Prep data for template
      var bodyObj = {
        name: name,
        model: existingModel
      };
      bodyObj = _.assign(bodyObj,field);

      // Render base element (all fields need these base values)
      dust.render('element-base', bodyObj, function(err, out){

        var elem = $(out);

        // append base
        self._opts.targets.find('.frmb-group:last-of-type').after( elem );

        // Load choices already present
        if( _.has(existingModel,'choices') ){
          _.each(existingModel.choices,function(choice){
            self.appendFieldToFormElementEditor( elem, field, existingModel, choice );
          });
          return;
        }

        // Add a default/empty one
        self.appendFieldToFormElementEditor( elem, field, existingModel );

      });
    },

    /**
     * Appends secondary details to an existing form editor
     * @param  {element} frmb_group Form group description to append to
     * @param  {object} field      Field type schema to use
     */
    appendFieldToFormElementEditor: function( frmb_group, field, parentModel, existingModel ){

      // load additional details template
      if( _.has(field,'template') ){

        // choices
        if( _.has(parentModel,'choices') && _.isArray(parentModel.choices) ){

          // Create a new model
          if( !_.isObject(existingModel) ){
            existingModel = _.clone(field.choiceSchema);
            parentModel.choices.push( existingModel);
          }

          var bodyObj = {
            name: parentModel.name,
            model: existingModel
          };

          // new index
          var index = parentModel.choices.length;
          bodyObj.name += '_choices.'+index;

          dust.render(field.template, bodyObj, function(err, out){
            frmb_group.append( out );
          });
        }
      }
    },

    /**
     * Sets a new value for a field's model
     * @param {string} id   Model ID
     * @param {string} type Schema field value belongs to
     * @param {string} val
     */
    setModelValue: function( id, type, val ){

      // Some paths are namespaced
      var path = false;
      if( type.indexOf('.') !== false ){
        path = type.split('.');
        type = path[0];
      }

      if( !_.isObject( this._model[id] ) ){
        throw new Error('Model has no entry for ' + id);
      }

      if( !_.has( this._model[id], type ) ){
        throw new Error('Invalid schema field ' + type + ' for model ' + id);
      }

      var fieldType = this.getFieldTypeByName( this._model[id].type );

      // Special handling for choice
      if( type === 'choices' ){

        var index = _.parseInt(path[1]);

        // verify field is in schema
        if( !_.has( this._model[id][type][index], path[2] ) ){
          throw new Error('Invalid choice schema field ' + path[2] + ' for model ' + id);
        }

        // set value
        this._model[id][type][index][path[2]] = val;

        return;

      }

      this._model[id][type] = val;

    },

    /**
     * Removes a field model
     * @param  {string} id
     */
    removeModel: function( id ){

      if( id.indexOf('.') !== false ){

        // we're deleting a sub model
        var _tmp = id.replace(/.*_/,'');
        var path = _tmp.split('.');
        var index = _.parseInt(path[1]);
        id = id.replace('_'+_tmp,'');

        delete this._model[id][path[0]][index];
        return;

      }

      delete this._model[id];

    },

    /**
     * Passes a JSON model of the resulting form to the server-side
     * code.
     */
    save: function(){

      var save = {
        form_id: this._opts.form_id,
        model: this._model
      }

      $.ajax({
        url: this._opts.save_url,
        data: JSON.stringify(save),
        contentType : 'application/json',
        type: 'post',
        success: function(resp){
          console.log(resp);
        }
      });

      console.log(this._model);
    }
  };

  // map!
  window.formbuilder = formbuilder;

})(this);<commit_msg>Choiceindex bugfix<commit_after>/**
 * Dynamically load templates
 * @param  {[type]}   name     [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
dust.onLoad = function(name, callback) {
  $.ajax('templates/' + name + '.tpl', {
    success: function(data) {
      callback(undefined, data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      callback(textStatus, undefined);
    }
  });
};

/**
 * Formbuilder
 * Copyright (c) 2009, 2014 (v2) Mike Botsko, Helion3 LLC (http://www.helion3.com)
 * http://www.botsko.net/blog/2009/04/jquery-form-builder-plugin/
 * Originally designed for AspenMSM, a CMS product from Trellis Development
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 */
(function (window,undefined){

  var formbuilder = function( opts ){
    return new formbuilderEngine(opts);
  };

  var formbuilderEngine = function(opts){

    if( !_.has(opts,'targets') || !_.isObject(opts.targets) || opts.targets.length === 0 ){
      throw new Error('Invalid or missing target element(s)');
    }

    if( !_.has(opts,'save_url') || !_.isString(opts.save_url) || opts.save_url.trim() === '' ){
      throw new Error('Invalid or missing save url');
    }

    // Define all default options
    var defaultOptions = {

      // A unique ID shared with the server-side code
      form_id: 'frmb-'+_.now(),

      // Injected model, allows us to start with an
      // existing form
      startingModel: false,

      // A dom-lib wrapped element
      targets: false,

      // A url we'll POST form data to on save
      save_url: false,

      // Description of allowed field types
      field_types: [
        {
          key: 'text',
          label: 'Text',
          schema: {
            name: false,
            label: '',
            required: false
          }
        },{
          key: 'textarea',
          label: 'Textarea',
          schema: {
            name: false,
            label: '',
            required: false
          }
        },{
          key: 'select',
          label: 'Select',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        },{
          key: 'radio',
          label: 'Radio',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        },{
          key: 'checkbox',
          label: 'Checkbox',
          template: 'choices',
          schema: {
            name: false,
            label: '',
            required: false,
            choices: []
          },
          choiceSchema: {
            selected: false,
            label: ''
          }
        }
      ]
    };

    this._opts = _.assign(defaultOptions,opts);

    (function(engine){

      var targets = engine._opts.targets;

      engine.render();

          // Load the starting model
      if( _.isObject(engine._opts.startingModel) ){

        engine._model = engine._opts.startingModel;
        // @todo validate against the field schema

        // Iterate model and render proper editors
        _.each(engine._model,function(model,id){

          var field = engine.getFieldTypeByName( model.type );
          engine.addFormElementEditor( field, model );

          // console.log(field);
          // console.log(model);
          // console.log(id);
        })

      }

      /**
       * Event listeners
       */

      // New form element editor
      targets.on('change', '.frmb-add-elem', function(){
        var val = $(this).val();
        engine.addFormElementEditor( engine.getFieldTypeByName(val) );
        $(this).val('');
      });

      // Add a choice entry
      targets.on('click', '.frmb-add-choice', function(e){
        e.preventDefault();
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');

        var fieldType = engine.getFieldTypeByName( engine._model[id].type );

        engine.appendFieldToFormElementEditor( parent, fieldType, engine._model[id] );

        return false;
      });

      // Remove a form element editor
      targets.on('click', '.frmb-remove', function(e){
        e.preventDefault();
        var elem = $(this);
        var parent = elem.parents('.frmb-group:eq(0)');
        var id = parent.attr('id');
        engine.removeModel( id );
        parent.remove();
        return false;
      });

      // Update model with keyboard entries
      targets.on('keyup', 'input[type=text]', function(e){

        // specific field editor container
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');
        var type = elem.attr('name').replace(id+'_', '');

        engine.setModelValue( id, type, elem.val() );

      });

      // Update model with checkbox entries
      targets.on('change', 'input[type=checkbox]', function(e){

        // specific field editor container
        var elem = $(this);
        var parent = elem.parents('.frmb-group').last();
        var id = parent.attr('id');
        var type = elem.attr('name').replace(id+'_', '');

        engine.setModelValue( id, type, elem.is(':checked') );

      });

      // Save
      targets.on('click', '.frmb-save', function(e){
        e.preventDefault();
        engine.save();
        return false;
      });

    })(this);

    return this;

  };

  formbuilderEngine.prototype = {

    // store options
    _opts: false,

    // current object representing the form
    _model: {},

    /**
     * Render the form editor
     * @return {[type]} [description]
     */
    render: function(){

      var self = this;

      // Pass data to the original rendering
      var frmObj = {
        field_types: this._opts.field_types
      };

      dust.render('base', frmObj, function(err, out) {

        // Append final content
        self._opts.targets.append( out );

      });
    },

    /**
     * Returns the field type object by given name
     * @param  {string} field_type_name Field type name
     * @return {object}
     */
    getFieldTypeByName: function( field_type_name ){
      return _.find(this._opts.field_types, { 'key': field_type_name });
    },

    /**
     * Add a new form element editing box
     */
    addFormElementEditor: function( field, existingModel ){

      var self = this;

      if( !_.isObject(field) ){
        throw new Error('Failed to add form element editor: Invalid field object');
      }

      // Determine field name
      var name = field.key + '_' + _.now();
      if( _.has(existingModel,'name') && _.isString(existingModel.name) ){
        name = existingModel.name;
      }
      else if( _.isString(field.name) ){
        name = field.name;
      }

      // Create a new model entry
      if( !_.isObject(existingModel) ){
        self._model[name] = _.assign(field.schema, {
          name: name,
          type: field.key
        });
        existingModel = self._model[name];
      }

      // Prep data for template
      var bodyObj = {
        name: name,
        model: existingModel
      };
      bodyObj = _.assign(bodyObj,field);

      // Render base element (all fields need these base values)
      dust.render('element-base', bodyObj, function(err, out){

        var elem = $(out);

        // append base
        self._opts.targets.find('.frmb-group:last-of-type').after( elem );

        // Load choices already present
        if( _.has(existingModel,'choices') ){
          _.each(existingModel.choices,function(choice,key){
            self.appendFieldToFormElementEditor( elem, field, existingModel, choice, key );
          });
          return;
        }

        // Add a default/empty one
        self.appendFieldToFormElementEditor( elem, field, existingModel );

      });
    },

    /**
     * Appends secondary details to an existing form editor
     * @param  {element} frmb_group Form group description to append to
     * @param  {object} field      Field type schema to use
     */
    appendFieldToFormElementEditor: function( frmb_group, field, parentModel, existingModel, index ){

      // load additional details template
      if( _.has(field,'template') ){

        // choices
        if( _.has(parentModel,'choices') && _.isArray(parentModel.choices) ){

          // Create a new model
          if( !_.isObject(existingModel) ){
            existingModel = _.clone(field.choiceSchema);
            parentModel.choices.push( existingModel);
          }

          var bodyObj = {
            name: parentModel.name,
            model: existingModel
          };

          // new index
          index = _.isNumber(index) ? index : parentModel.choices.length;
          bodyObj.name += '_choices.'+index;

          dust.render(field.template, bodyObj, function(err, out){
            frmb_group.append( out );
          });
        }
      }
    },

    /**
     * Sets a new value for a field's model
     * @param {string} id   Model ID
     * @param {string} type Schema field value belongs to
     * @param {string} val
     */
    setModelValue: function( id, type, val ){

      // Some paths are namespaced
      var path = false;
      if( type.indexOf('.') !== false ){
        path = type.split('.');
        type = path[0];
      }

      if( !_.isObject( this._model[id] ) ){
        throw new Error('Model has no entry for ' + id);
      }

      if( !_.has( this._model[id], type ) ){
        throw new Error('Invalid schema field ' + type + ' for model ' + id);
      }

      var fieldType = this.getFieldTypeByName( this._model[id].type );

      // Special handling for choice
      if( type === 'choices' ){

        var index = _.parseInt(path[1]);

        // verify field is in schema
        if( !_.has( this._model[id][type][index], path[2] ) ){
          throw new Error('Invalid choice schema field ' + path[2] + ' for model ' + id);
        }

        // set value
        this._model[id][type][index][path[2]] = val;

        return;

      }

      this._model[id][type] = val;

    },

    /**
     * Removes a field model
     * @param  {string} id
     */
    removeModel: function( id ){

      if( id.indexOf('.') !== false ){

        // we're deleting a sub model
        var _tmp = id.replace(/.*_/,'');
        var path = _tmp.split('.');
        var index = _.parseInt(path[1]);
        id = id.replace('_'+_tmp,'');

        delete this._model[id][path[0]][index];
        return;

      }

      delete this._model[id];

    },

    /**
     * Passes a JSON model of the resulting form to the server-side
     * code.
     */
    save: function(){

      var save = {
        form_id: this._opts.form_id,
        model: this._model
      }

      $.ajax({
        url: this._opts.save_url,
        data: JSON.stringify(save),
        contentType : 'application/json',
        type: 'post',
        success: function(resp){
          console.log(resp);
        }
      });

      console.log(this._model);
    }
  };

  // map!
  window.formbuilder = formbuilder;

})(this);<|endoftext|>


<commit_before>'use strict';

var Transform = require('stream').Transform;
var Parser = require('./parser.js');

function Streamer(options) {
  Transform.call(this,  {
    readableObjectMode: true,
    writableObjectMode: false,
  });
  this.buffer = '';
  this.sep = (options && options.separator) ? options.separator : undefined;
  this.quo = (options && options.quote) ? options.quote : undefined;
}

Streamer.prototype = Object.create(
  Transform.prototype, { constructor: { value: Streamer }});

Streamer.prototype._transform = function(chunk, encoding, done) {

  this.buffer = this.buffer.concat(chunk.toString());
  if (this.sep === undefined) {
    // try to detect the separator if not provided
    this.sep = require('./csv.js').detect(this.buffer);
  }

  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();

  if (csv.pointer > this.buffer.length) {
    this.buffer = this.buffer.slice(csv.pointer);
  }
  else {
    if (csv.pointer === this.buffer.length) {
      rows.pop();
    }
    this.buffer = this.buffer.slice(csv.linePointer);
  }
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.push(row);
      }
    )
  }
  done();
}

Streamer.prototype._flush = function (done) {
  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.push(row);
      }
    )
  }
  done();
};

module.exports = Streamer;
<commit_msg>fix tests and bug<commit_after>'use strict';

var Transform = require('stream').Transform;
var Parser = require('./parser.js');

function Streamer(options) {
  Transform.call(this,  {
    readableObjectMode: true,
    writableObjectMode: false,
  });
  this.buffer = '';
  this.sep = (options && options.separator) ? options.separator : undefined;
  this.quo = (options && options.quote) ? options.quote : undefined;
}

Streamer.prototype = Object.create(
  Transform.prototype, { constructor: { value: Streamer }});

Streamer.prototype._transform = function(chunk, encoding, done) {

  this.buffer = this.buffer.concat(chunk.toString());
  if (this.sep === undefined) {
    // try to detect the separator if not provided
    this.sep = require('./csv.js').detect(this.buffer);
  }

  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();

  if (csv.linePointer !== csv.pointer) {
    rows.pop();
  }
  this.buffer = this.buffer.slice(csv.linePointer);
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.push(row);
      }
    )
  }
  done();
}

Streamer.prototype._flush = function (done) {
  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.push(row);
      }
    )
  }
  done();
};

module.exports = Streamer;
<|endoftext|>


<commit_before>/*
Rushed ugly code by <thomasalwyndavis@gmail.com>

Will clean up and make available

*/
var MailChimpAPI = require('mailchimp').MailChimpAPI;
var MongoClient = require('mongodb').MongoClient
  , format = require('util').format;
var apiKey = process.env.MAILCHIMP_API_KEY;

try {
    var api = new MailChimpAPI(apiKey, { version : '2.0' });
} catch (error) {
    console.log(error.message);
}

var express = require('express');
var port = process.env.PORT || 8080;
var allowCrossDomain = function(req, res, next) {
  var allowedHost = [
    'http://dev.stopwatching.us',
    'http://rally.stopwatching.us',
    'http://2.stopwatching.us',
    'http://localhost:4000',
    'https://dev.stopwatching.us',
    'https://rally.stopwatching.us',
    'https://2.stopwatching.us',
    'https://localhost:4000'
  ];
  if(allowedHost.indexOf(req.headers.origin) !== -1 ) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send({auth: false});
  }
}
MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
  if(err) throw err;

  var collection = db.collection('emails');
  var server = express();
  server.use(express.bodyParser());
  server.use(allowCrossDomain);

  server.options("*", function(req,res,next){res.send({});});

  server.post('/subscribe', function(req,res,next){

      var email = req.body.email;
      var name = req.body.name || '';
      var phone = req.body.phone || '';
      var zipcode = req.body.zipcode || '';

      var about = req.body.about || '';
      var viewing_party = req.body.viewing_party || '';
      var transportation = req.body.transportation || '';
      var call_banking = req.body.call_banking || '';

      var merge_vars = {
        EMAIL: email,
        PHONE: phone,
        NAME: name,
        ZIPCODE: zipcode,
        ABOUT: about,
        VP: viewing_party,
        VT: transportation,
        CB: call_banking
      };

      collection.insert(merge_vars, function(err, docs) {console.log('Saved Email')});
      api.call('lists', 'subscribe', {
          id: 'c05d6bd75f',
          email: {email: email},
          merge_vars: merge_vars,
          send_welcome: true,
          double_optin: false

      }, function (error, data) {
      });
      res.send(JSON.stringify(merge_vars)); // Do something with your data!

  });

  server.listen(port, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

})
<commit_msg>Added new vars<commit_after>/*
Rushed ugly code by <thomasalwyndavis@gmail.com>

Will clean up and make available

*/
var MailChimpAPI = require('mailchimp').MailChimpAPI;
var MongoClient = require('mongodb').MongoClient
  , format = require('util').format;
var apiKey = process.env.MAILCHIMP_API_KEY;

try {
    var api = new MailChimpAPI(apiKey, { version : '2.0' });
} catch (error) {
    console.log(error.message);
}

var express = require('express');
var port = process.env.PORT || 8080;
var allowCrossDomain = function(req, res, next) {
  var allowedHost = [
    'http://dev.stopwatching.us',
    'http://rally.stopwatching.us',
    'http://2.stopwatching.us',
    'http://localhost:4000',
    'https://dev.stopwatching.us',
    'https://rally.stopwatching.us',
    'https://2.stopwatching.us',
    'https://localhost:4000'
  ];
  if(allowedHost.indexOf(req.headers.origin) !== -1 ) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send({auth: false});
  }
}
MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
  if(err) throw err;

  var collection = db.collection('emails');
  var server = express();
  server.use(express.bodyParser());
  server.use(allowCrossDomain);

  server.options("*", function(req,res,next){res.send({});});

  server.post('/subscribe', function(req,res,next){

      var email = req.body.email;
      var name = req.body.name || '';
      var phone = req.body.phone || '';
      var zipcode = req.body.zipcode || '';

      var about = req.body.about || '';
      var viewing_party = req.body.viewing_party || '';
      var transportation = req.body.transportation || '';
      var call_banking = req.body.call_banking || '';

      var merge_vars = {
        EMAIL: email,
        PHONE: phone,
        NAME: name,
        ZIPCODE: zipcode,
        ABOUT: about,
        VP: viewing_party,
        VT: transportation,
        CB: call_banking
      };

      collection.insert(merge_vars, function(err, docs) {console.log('Saved Email')});
      api.call('lists', 'subscribe', {
          id: 'c05d6bd75f',
          email: {email: email},
          merge_vars: merge_vars,
          send_welcome: true,
          double_optin: false,
          update_existing: true

      }, function (error, data) {
      });
      res.send(JSON.stringify(merge_vars)); // Do something with your data!

  });

  server.listen(port, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

})
<|endoftext|>


<commit_before>angular
  .module("animeHub")
  .factory('User', User);

User.$inject = ['$resource', 'API'];
function User($resource, API) {

  return $resource(API + 'users/:id', null, {
    'login':{method: "POST", url: API + 'login'},
    'signup':{method: "POST", url: API + 'signup'},
    'update': { method:'PUT', url: API + 'comment/:id' }
  });

}<commit_msg>removed url from update method<commit_after>angular
  .module("animeHub")
  .factory('User', User);

User.$inject = ['$resource', 'API'];
function User($resource, API) {

  return $resource(API + 'users/:id', null, {
    'login':{method: "POST", url: API + 'login'},
    'signup':{method: "POST", url: API + 'signup'},
    'update': { method:'PUT'}
  });

}<|endoftext|>


<commit_before>
/****************************
       Hex Heatmap
 ****************************/

// Thanks to :
// http://bl.ocks.org/mbostock/4248145

function drawHexmap(map, layer){

  // http://bl.ocks.org/mbostock/4248145
  var width = map.getSize().x;
  var height = map.getSize().y;

  // Current zoom level ~[0 - 19]
  var zoom = map._zoom

  // Filtered array
  var points = [];

  // Create map-able set of points. For each point,
  // convert the lat/long into a plottable x/y position
  acc = layer.data.filter(function(p) {

    // Check for missing data points
    if (!p.latitude || !p.longitude){
      console.log("ERROR. Missing Latitude/Longitude Data.");
      return false;
    }

    // Create new leaflet Lat/Long Object
    var latlng = new L.LatLng(p.latitude, p.longitude);

    // Remove points that are outside current viewport
    if (!bounds.contains(latlng)) { return false };

    // Convert Latitude and Longitude into a Mapable
    // point using leaflet's LayerPoint API.
    var point = map.latLngToLayerPoint(latlng);

    // Save the resulting x & y values
    // onto the current point object.
    p.x = point.x;
    p.y = point.y;

    if (!p.bedrooms || p.bedrooms < 1){
      p.bedrooms = 1;
    }

    points.push([point.x, point.y, p.value]);

    return true;
  });

  var color = d3.scale.linear()
      .domain([500, 3500])
      .range(["white", "steelblue"])
      .interpolate(d3.interpolateLab)

  var hexbin = d3.hexbin()
      .size([width, height])
      .radius(layer.width);

  // Create an SVG elemnt for plotting points on
  var svg = d3.select(map.getPanes().overlayPane)

      .append("svg")
      .attr('id', layer.id)
      .attr("class", "leaflet-zoom-hide")
      .style("width",  map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .append("g")

  // clipPath is a trick for rendering custom
  // svg shapes. It restricts the region of
  // a shape where color can be applied.
  svg.append("clipPath")

      .attr("id", "clip")
      .append("rect")
      .attr("class", "mesh")
      .attr("width", width)
      .attr("height", height);

  svg.append("g")

      .attr("clip-path", "url(#clip)")
      .selectAll(".hexagon")

      // Use the hexbin d3.js plugin for
      // bulking data points into their
      // overlapping "bin"

      .data(hexbin(points))
      .enter().append("path")
      .attr("class", "hexagon")
      .attr("d", hexbin.hexagon())
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style("fill", function(d) {

        // Ugly calculation for finding average prie
        var sum = 0;

        // For each apartment in the current bin
        for (var i = d.length - 1; i >= 0; i--) {
          var price = d[i][2];
          sum += price;
        };

        return color(sum / d.length);
      })

      .style("opacity", .8);
}

<commit_msg>Draw hexmap REALLY big.<commit_after>
/****************************
       Hex Heatmap
 ****************************/

// Thanks to :
// http://bl.ocks.org/mbostock/4248145

function drawHexmap(map, layer){

  // http://bl.ocks.org/mbostock/4248145
  var width = map.getSize().x;
  var height = map.getSize().y;

  // Current zoom level ~[0 - 19]
  var zoom = map._zoom

  // Filtered array
  var points = [];

  // Create map-able set of points. For each point,
  // convert the lat/long into a plottable x/y position
  acc = layer.data.filter(function(p) {

    // Check for missing data points
    if (!p.latitude || !p.longitude){
      console.log("ERROR. Missing Latitude/Longitude Data.");
      return false;
    }

    // Create new leaflet Lat/Long Object
    var latlng = new L.LatLng(p.latitude, p.longitude);

    // Remove points that are outside current viewport
    if (!bounds.contains(latlng)) { return false };

    // Convert Latitude and Longitude into a Mapable
    // point using leaflet's LayerPoint API.
    var point = map.latLngToLayerPoint(latlng);

    // Save the resulting x & y values
    // onto the current point object.
    p.x = point.x;
    p.y = point.y;

    if (!p.bedrooms || p.bedrooms < 1){
      p.bedrooms = 1;
    }

    points.push([point.x, point.y, p.value]);

    return true;
  });

  var color = d3.scale.linear()
      .domain([500, 3500])
      .range(["white", "steelblue"])
      .interpolate(d3.interpolateLab)

  var hexbin = d3.hexbin()
      .size([2000, 2000])
      .radius(layer.width);

  // Create an SVG elemnt for plotting points on
  var svg = d3.select(map.getPanes().overlayPane)

      .append("svg")
      .attr('id', layer.id)
      .attr("class", "leaflet-zoom-hide")
      .style("width",  map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .append("g")

  // clipPath is a trick for rendering custom
  // svg shapes. It restricts the region of
  // a shape where color can be applied.
  svg.append("clipPath")

      .attr("id", "clip")
      .append("rect")
      .attr("class", "mesh")
      .attr("width", width)
      .attr("height", height);

  svg.append("g")

      .attr("clip-path", "url(#clip)")
      .selectAll(".hexagon")

      // Use the hexbin d3.js plugin for
      // bulking data points into their
      // overlapping "bin"

      .data(hexbin(points))
      .enter().append("path")
      .attr("class", "hexagon")
      .attr("d", hexbin.hexagon())
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style("fill", function(d) {

        // Ugly calculation for finding average prie
        var sum = 0;

        // For each apartment in the current bin
        for (var i = d.length - 1; i >= 0; i--) {
          var price = d[i][2];
          sum += price;
        };

        return color(sum / d.length);
      })

      .style("opacity", .8);
}

<|endoftext|>


<commit_before>'use strict';
global.Promise = require('bluebird');
var http = require('http');
http.globalAgent.maxSockets = 5000;
var url = require('url');
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var config = require('config');
var co = require('co');
var superagent = require('superagent');
var mkdirp = require('mkdirp');
var concat = require('concat-stream');
var db = require('level-sublevel')(require('levelup')(config.db.path, xtend(config.db.config, {
    valueEncoding: 'json'
})));
var dbCache = db.sublevel('cache');
var dbCacheJson = dbCache.sublevel('json');
var logger = require('bunyan-hub-logger');
logger.replaceDebug('simple-npm-cache-proxy');
var log = logger({
    app: 'simple-npm-cache-proxy',
    name: 'server',
    serializers: {
        response: logger.stdSerializers.res
    },
});
var Schedule = require('level-schedule');
var dbSchedule = db.sublevel('schedule');

promisifyEachAll([db, dbCache, dbCacheJson, dbSchedule]);

function promisifyEachAll(arr) {
    arr.forEach(Promise.promisifyAll);
}

function replaceBodyRegistry(body) {
    return body.replace(config.replaceHost[0], config.replaceHost[1]);
}

function xtend() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift({});
    return _.assign.apply(_, args);
}

var schedule = Schedule(dbSchedule);
/*
 * payload: {
 *   url,
 *   etag,
 *   registry: public | private
 * }
 */
schedule.job('update', function(payload, done) {
    log.trace({
        job: 'update',
        payload: payload,
    });
    superagent.get(config.registry[payload.registry] + payload.url)
        .set('if-none-match', payload.etag)
        .end(co.wrap(function * (err, r) {
            log.trace({
                job: 'update',
                payload: payload,
                err: err,
                response: r,
            });
            if (err || r.statusCode !== 200 || !r.headers.etag) {
                schedule.run('update', payload, Date.now() + 60000);
                done();
                return;
            }
            var headers = r.headers;
            if (r.text && headers.etag && headers.etag !== payload.etag) {
                var body = replaceBodyRegistry(r.text);
                var cacheObject = {
                    statusCode: r.statusCode,
                    headers: xtend(pickHeaders(r.headers), {
                        'content-length': Buffer.byteLength(body)
                    }),
                    etag: r.headers.etag,
                    body: body,
                };
                log.info({
                    updated: true,
                    cacheObject: cacheObject,
                });
                yield dbCacheJson.putAsync(payload.url, cacheObject);
            }
            schedule.run('update', xtend(payload, {
                etag: r.headers.etag,
            }), Date.now() + 60000);
            done();
        }));
});
var st = require('st');
var mount = st({
    path: config.tarballCacheDir,
    cache: { // specify cache:false to turn off caching entirely
        fd: {
            max: 1000, // number of fd's to hang on to
            maxAge: 1000 * 60 * 60, // amount of ms before fd's expire
        },

        stat: false,

        content: {
            max: 1024 * 1024 * 64, // how much memory to use on caching contents
            maxAge: 1000 * 60 * 10, // how long to cache contents for
            // if `false` does not set cache control headers
            cacheControl: 'public, max-age=600' // to set an explicit cache-control
            // header value
        },
    },
    index: false, // return 404's for directories
    passthrough: true, // calls next/returns instead of returning a 404 error
});

function pickHeaders(headers) {
    return _.pick(headers, [
        'etag',
        'content-type',
        'content-length',
    ]);
}

var cachedRequest = {};
var proxy = co.wrap(function * (registry, req, res) {
    var crkey = registry + '|' + req.url;
    if (req.method === 'GET') {
        var cache = yield dbCacheJson.getAsync(req.url).catch(function(err) {
            return false;
        })
        if (cache) {
            log.debug({
                req: req,
                cachedObject: cache
            });
            if ('if-none-match' in req.headers && req.headers['if-none-match'] === cache.etag) {
                cache.headers['content-length'] = 0;
                return {
                    statusCode: 304,
                    headers: cache.headers,
                    body: new Buffer(0),
                };
            }
            return cache;
        }
        var cr;
        if ((cr = cachedRequest[crkey])) {
            return cr;
        }
    }
    if ('if-none-match' in req.headers) { // make sure upstream return 200 instead of 304
        delete req.headers['if-none-match'];
    }
    if ('accept-encoding' in req.headers) { // remove gzip, get raw text body
        req.headers['accept-encoding'] = 'identity';
    }
    req.headers.host = url.parse(config.registry[registry]).host;

    var rp = new Promise(function(resolve, reject) {
        var request = superagent(req.method, config.registry[registry] + req.url)
            .redirects(1)
            .set(req.headers);
        request._callback = function(err) {
            if (err) reject(err);
        };
        if (['GET', 'HEAD'].indexOf(req.method) === -1) {
            req.pipe(request);
        }
        request.pipe(concat(function(body) {
            var response = request.res;
            var headers = response.headers;
            // cache tarball
            if (config.cache[registry] && req.method === 'GET' && !headers.location &&
                headers['content-type'] === 'application/octet-stream') {
                var filePath = path.resolve(config.tarballCacheDir, req.url.replace(/^\/+/, ''));
                mkdirp(path.dirname(filePath), function(err) {
                    if (err) log.error(err);
                    fs.writeFile(filePath, body, function(err) {
                        if (err) log.error(err);
                    });
                });
            }
            // cache json
            else if ((headers['content-type'] || '').match(/^application\/json/i)) {
                body = body.toString('utf8');
                log.debug({
                    req: req,
                    body: body,
                });
                body = replaceBodyRegistry(body);
                log.debug({
                    req: req,
                    headers: headers,
                    replacedBody: body,
                });
                headers = xtend(headers, {
                    'content-length': Buffer.byteLength(body)
                });
                if (config.cache[registry] && req.method === 'GET' && typeof headers['etag'] === 'string') {
                    dbCacheJson.put(req.url, {
                        statusCode: response.statusCode,
                        headers: headers,
                        body: body,
                        etag: headers.etag,
                    });
                    schedule.run('update', {
                        registry: registry,
                        url: req.url,
                        etag: headers.etag,
                    }, Date.now() + 60000);
                }
            }
            resolve({
                statusCode: response.statusCode,
                headers: pickHeaders(headers),
                body: body,
            });
        }));
    });
    if (req.method === 'GET') {
        cachedRequest[crkey] = rp;
        rp.finally(function() {
            delete cachedRequest[crkey];
        });
    }
    return rp;
});

var server = http.createServer();
server.on('request', function(req, res) {
    req.url = req.url.replace(/\/+/g, '/').replace(/\?.*$/g, '');
    res.status = function(code) {
        res.statusCode = code;
    };
    req.res = res;
    res.req = req;
    log.debug({
        req: req,
        res: res
    });

    mount(req, res, function() {
        co(function * () {
            if (req.url.match(/^\/[^\/]+\/download\/.*\.tgz$/)) return proxy('taobao', req, res);
            if (req.url.match(/^\/-\/|@/) || req.method !== 'GET') return proxy('private', req, res);
            if (req.url.match(/^\/[^@\/]+$/)) return proxy('public', req, res);
            if (req.url.match(/^\/[^\/]+$/)) return proxy('private', req, res);
            return proxy('public', req, res);
        })
            .then(function(cache) {
                res.writeHeader(cache.statusCode, cache.headers);
                res.end(cache.body);
            })
            .catch(function(err) {
                if (err) log.error(err);
                if (err && !res.headersSent) {
                    res.status(500);
                    log.error(err);
                    res.end('500 internal error.');
                }
            });
    });
});

server.listen(config.server.port);
<commit_msg>fix private upstream setting<commit_after>'use strict';
global.Promise = require('bluebird');
var http = require('http');
http.globalAgent.maxSockets = 5000;
var url = require('url');
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var config = require('config');
var co = require('co');
var superagent = require('superagent');
var mkdirp = require('mkdirp');
var concat = require('concat-stream');
var db = require('level-sublevel')(require('levelup')(config.db.path, xtend(config.db.config, {
    valueEncoding: 'json'
})));
var dbCache = db.sublevel('cache');
var dbCacheJson = dbCache.sublevel('json');
var logger = require('bunyan-hub-logger');
logger.replaceDebug('simple-npm-cache-proxy');
var log = logger({
    app: 'simple-npm-cache-proxy',
    name: 'server',
    serializers: {
        response: logger.stdSerializers.res
    },
});
var Schedule = require('level-schedule');
var dbSchedule = db.sublevel('schedule');

promisifyEachAll([db, dbCache, dbCacheJson, dbSchedule]);

function promisifyEachAll(arr) {
    arr.forEach(Promise.promisifyAll);
}

function replaceBodyRegistry(body) {
    return body.replace(config.replaceHost[0], config.replaceHost[1]);
}

function xtend() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift({});
    return _.assign.apply(_, args);
}

var schedule = Schedule(dbSchedule);
/*
 * payload: {
 *   url,
 *   etag,
 *   registry: public | private
 * }
 */
schedule.job('update', function(payload, done) {
    log.trace({
        job: 'update',
        payload: payload,
    });
    var registryUrl, registryHost;
    if (Array.isArray(config.registry[payload.registry])) {
        registryUrl = config.registry[payload.registry][0];
        registryHost = config.registry[payload.registry][1];
    } else {
        registryUrl = config.registry[payload.registry];
        registryHost = url.parse(config.registry[payload.registry]).host;
    }
    superagent.get(registryUrl + payload.url)
        .set('host', registryHost)
        .set('if-none-match', payload.etag)
        .end(co.wrap(function * (err, r) {
            log.trace({
                job: 'update',
                payload: payload,
                err: err,
                response: r,
            });
            if (err || r.statusCode !== 200 || !r.headers.etag) {
                schedule.run('update', payload, Date.now() + 60000);
                done();
                return;
            }
            var headers = r.headers;
            if (r.text && headers.etag && headers.etag !== payload.etag) {
                var body = replaceBodyRegistry(r.text);
                var cacheObject = {
                    statusCode: r.statusCode,
                    headers: xtend(pickHeaders(r.headers), {
                        'content-length': Buffer.byteLength(body)
                    }),
                    etag: r.headers.etag,
                    body: body,
                };
                log.info({
                    updated: true,
                    cacheObject: cacheObject,
                });
                yield dbCacheJson.putAsync(payload.url, cacheObject);
            }
            schedule.run('update', xtend(payload, {
                etag: r.headers.etag,
            }), Date.now() + 60000);
            done();
        }));
});
var st = require('st');
var mount = st({
    path: config.tarballCacheDir,
    cache: { // specify cache:false to turn off caching entirely
        fd: {
            max: 1000, // number of fd's to hang on to
            maxAge: 1000 * 60 * 60, // amount of ms before fd's expire
        },

        stat: false,

        content: {
            max: 1024 * 1024 * 64, // how much memory to use on caching contents
            maxAge: 1000 * 60 * 10, // how long to cache contents for
            // if `false` does not set cache control headers
            cacheControl: 'public, max-age=600' // to set an explicit cache-control
            // header value
        },
    },
    index: false, // return 404's for directories
    passthrough: true, // calls next/returns instead of returning a 404 error
});

function pickHeaders(headers) {
    return _.pick(headers, [
        'etag',
        'content-type',
        'content-length',
    ]);
}

var cachedRequest = {};
var proxy = co.wrap(function * (registry, req, res) {
    var crkey = registry + '|' + req.url;
    if (req.method === 'GET') {
        var cache = yield dbCacheJson.getAsync(req.url).catch(function(err) {
            return false;
        })
        if (cache) {
            log.debug({
                req: req,
                cachedObject: cache
            });
            if ('if-none-match' in req.headers && req.headers['if-none-match'] === cache.etag) {
                cache.headers['content-length'] = 0;
                return {
                    statusCode: 304,
                    headers: cache.headers,
                    body: new Buffer(0),
                };
            }
            return cache;
        }
        var cr;
        if ((cr = cachedRequest[crkey])) {
            return cr;
        }
    }
    if ('if-none-match' in req.headers) { // make sure upstream return 200 instead of 304
        delete req.headers['if-none-match'];
    }
    if ('accept-encoding' in req.headers) { // remove gzip, get raw text body
        req.headers['accept-encoding'] = 'identity';
    }
    var registryUrl, registryHost;
    if (Array.isArray(config.registry[registry])) {
        registryUrl = config.registry[registry][0];
        registryHost = config.registry[registry][1];
    } else {
        registryUrl = config.registry[registry];
        registryHost = url.parse(config.registry[registry]).host;
    }
    req.headers.host = registryHost;

    var rp = new Promise(function(resolve, reject) {
        var request = superagent(req.method, registryUrl + req.url)
            .redirects(1)
            .set(req.headers);
        request._callback = function(err) {
            if (err) reject(err);
        };
        if (['GET', 'HEAD'].indexOf(req.method) === -1) {
            req.pipe(request);
        }
        request.pipe(concat(function(body) {
            var response = request.res;
            var headers = response.headers;
            // cache tarball
            if (config.cache[registry] && req.method === 'GET' && !headers.location &&
                headers['content-type'] === 'application/octet-stream') {
                var filePath = path.resolve(config.tarballCacheDir, req.url.replace(/^\/+/, ''));
                mkdirp(path.dirname(filePath), function(err) {
                    if (err) log.error(err);
                    fs.writeFile(filePath, body, function(err) {
                        if (err) log.error(err);
                    });
                });
            }
            // cache json
            else if ((headers['content-type'] || '').match(/^application\/json/i)) {
                body = body.toString('utf8');
                log.debug({
                    req: req,
                    body: body,
                });
                body = replaceBodyRegistry(body);
                log.debug({
                    req: req,
                    headers: headers,
                    replacedBody: body,
                });
                headers = xtend(headers, {
                    'content-length': Buffer.byteLength(body)
                });
                if (config.cache[registry] && req.method === 'GET' && typeof headers['etag'] === 'string') {
                    dbCacheJson.put(req.url, {
                        statusCode: response.statusCode,
                        headers: headers,
                        body: body,
                        etag: headers.etag,
                    });
                    schedule.run('update', {
                        registry: registry,
                        url: req.url,
                        etag: headers.etag,
                    }, Date.now() + 60000);
                }
            }
            resolve({
                statusCode: response.statusCode,
                headers: pickHeaders(headers),
                body: body,
            });
        }));
    });
    if (req.method === 'GET') {
        cachedRequest[crkey] = rp;
        rp.finally(function() {
            delete cachedRequest[crkey];
        });
    }
    return rp;
});

var server = http.createServer();
server.on('request', function(req, res) {
    req.url = req.url.replace(/\/+/g, '/').replace(/\?.*$/g, '');
    res.status = function(code) {
        res.statusCode = code;
    };
    req.res = res;
    res.req = req;
    log.debug({
        req: req,
        res: res
    });

    mount(req, res, function() {
        co(function * () {
            if (req.url.match(/^\/[^\/]+\/download\/.*\.tgz$/)) return proxy('taobao', req, res);
            if (req.url.match(/^\/-\/|@/) || req.method !== 'GET') return proxy('private', req, res);
            if (req.url.match(/^\/[^@\/]+$/)) return proxy('public', req, res);
            if (req.url.match(/^\/[^\/]+$/)) return proxy('private', req, res);
            return proxy('public', req, res);
        })
            .then(function(cache) {
                res.writeHeader(cache.statusCode, cache.headers);
                res.end(cache.body);
            })
            .catch(function(err) {
                if (err) log.error(err);
                if (err && !res.headersSent) {
                    res.status(500);
                    log.error(err);
                    res.end('500 internal error.');
                }
            });
    });
});

server.listen(config.server.port);
<|endoftext|>


<commit_before>function convertRippleAdrr(address) {
        return window.basex('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz').encode(
           window.basex('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz').decode(address)
        )
      }

function convertRipplePriv(priv)   {
        return window.basex('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz').decode(priv).toString("hex").slice(2)
}

<commit_msg>deleting the remaining checksum from the private key<commit_after>function convertRippleAdrr(address) {
        return window.basex('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz').encode(
           window.basex('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz').decode(address)
        )
      }

function convertRipplePriv(priv)   {
        return window.basex('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz').decode(priv).toString("hex").slice(2,-4)
}

<|endoftext|>


<commit_before>import express from 'express';
const app = express();
const data          = require('./api/data')

/************************************************************
 *
 * Express routes for:
 *   - app.js
 *   - style.css
 *   - index.html
 *
 ************************************************************/

// Serve application file depending on environment
app.get('/app.js', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/app.js');
  } else {
    res.redirect('//localhost:9090/build/app.js');
  }
});

// Serve aggregate stylesheet depending on environment
app.get('/style.css', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/style.css');
  } else {
    res.redirect('//localhost:9090/build/style.css');
  }
});

const path = require('path')

/********************************* DATA PATHS *********************************/

app.post('*', (req, res) => {
  res.send({status: 'posted'})
})

app.get('/api/competition/:id', (req, res) => {
  const id = parseInt(req.params.id)
  const comps = data.competitions.filter(c => c.id === id)
  res.send(comps[0])
})

app.get('/api/competition/:cid/events', (req, res) => {
  const cid = parseInt(req.params.cid)
  const events = data.events.filter(e => e.competitionId === cid)
  res.send(events)
})

app.get('/api/competitors', (req, res) => {
  res.send(data.competitors)
})

app.get('/api/competitors/:id', (req, res) => {
  const id = parseInt(req.params.id)
  const comps = data.competitors.filter(c => c.id === id)
  res.send(comps[0])
})

app.get('/api/competitors/:id/events', (req, res) => {
  res.send(data.events)
})

app.get('/api/competitions', (req, res) => {
  res.send(data.competitions)
})

app.get('/api/events', (req, res) => {
  res.send(data.events)
})

app.get('/api/event/:eid/', (req, res) => {
  const eid =  parseInt(req.params.eid)
  const events = data.events.filter(e => e.id === eid)
  res.send(events[0])
})

app.get('/api/event/:rid/rounds', (req, res) => {
  const rid = parseInt(req.params.rid)
  const rounds = data.rounds.filter(e => e.id === rid)
  res.send(rounds)
})

app.get('/api/rounds', (req, res) => {
  res.send(data.rounds)
})

app.get('/api/schedule', (req, res) => {
  res.send(data.schedule)
})

app.get('/api/partnerships', (req, res) => {
  res.send(data.partnerships)
})

app.get('/api/organizations', (req, res) => {
  res.send(data.organizations)
})

app.get('/api/payment_records', (req, res) => {
  res.send(data.payment_records)
})

app.get('/api/callbacks', (req, res) => {
  res.send(data.callbacks)
})

app.get('/api/admins', (req, res) => {
  res.send(data.admins)
})

app.get('/api/judges', (req, res) => {
  res.send(data.judges)
})

app.get('/api/', (req, res) => {
  res.send({routes: [
    '/api/competitors',
    '/api/competitions',
    '/api/events',
    '/api/rounds',
    '/api/partnerships',
    '/api/organizations',
    '/api/payment_records',
    '/api/callbacks',
    '/api/admins',
    '/api/judges'
  ]})
})

const routes = [
  "/",
  "/home",
  "/competition/:competition_id/",
  "/competition/:competition_id/eventregistration",
  "/competition/:competition_id/editschedule",
  "/competition/:competition_id/run",
  "/competition/:competition_id/:competitor_id",
  "/competitions",
  "/admin/competition/:competition_id",
  '/editprofile'
]

// Serve index page
app.get(routes, (req, res) => {
  res.sendFile(__dirname + '/build/index.html');
});

/*************************************************************
 *
 * Webpack Dev Server
 *
 * See: http://webpack.github.io/docs/webpack-dev-server.html
 *
 *************************************************************/

if (!process.env.PRODUCTION) {
  const webpack = require('webpack');
  const WebpackDevServer = require('webpack-dev-server');
  const config = require('./webpack.local.config');

  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: true,
    historyApiFallback: true
  }).listen(9090, 'localhost', (err, result) => {
    if (err) {
      console.log(err);
    }
  });
}

/******************
 *
 * Express server
 *
 *****************/

const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Essential React listening at http://%s:%s', host, port);
});
<commit_msg>New paths to get information from<commit_after>import express from 'express';
const app = express();
const data          = require('./api/data')

/************************************************************
 *
 * Express routes for:
 *   - app.js
 *   - style.css
 *   - index.html
 *
 ************************************************************/

// Serve application file depending on environment
app.get('/app.js', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/app.js');
  } else {
    res.redirect('//localhost:9090/build/app.js');
  }
});

// Serve aggregate stylesheet depending on environment
app.get('/style.css', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/style.css');
  } else {
    res.redirect('//localhost:9090/build/style.css');
  }
});

const path = require('path')

/********************************* DATA PATHS *********************************/

app.post('*', (req, res) => {
  res.send({status: 'posted'})
})

app.get('/api/competition/:id', (req, res) => {
  const id = parseInt(req.params.id)
  const comps = data.competitions.filter(c => c.id === id)
  res.send(comps[0])
})

app.get('/api/competition/:cid/events', (req, res) => {
  const cid = parseInt(req.params.cid)
  const events = data.events.filter(e => e.competitionId === cid)
  res.send(events)
})

app.get('/api/competitors', (req, res) => {
  res.send(data.competitors)
})

app.get('/api/competitors/:id', (req, res) => {
  const id = parseInt(req.params.id)
  const comps = data.competitors.filter(c => c.id === id)
  res.send(comps[0])
})

app.get('/api/competitors/:id1/competition/:id2', (req, res) => {
  const id1 = parseInt(req.params.id1)
  const id2 = parseInt(req.params.id2)
  res.send(data.competitor_competition_information)
})

app.get('/api/competitors/:id/events', (req, res) => {
  res.send(data.competitor_events)
})

app.get('/api/competitions', (req, res) => {
  res.send(data.competitions)
})

app.get('/api/events', (req, res) => {
  res.send(data.events)
})

app.get('/api/event/:eid/', (req, res) => {
  const eid =  parseInt(req.params.eid)
  const events = data.events.filter(e => e.id === eid)
  res.send(events[0])
})

app.get('/api/event/:rid/rounds', (req, res) => {
  const rid = parseInt(req.params.rid)
  const rounds = data.rounds.filter(e => e.id === rid)
  res.send(rounds)
})

app.get('/api/rounds', (req, res) => {
  res.send(data.rounds)
})

app.get('/api/schedule', (req, res) => {
  res.send(data.schedule)
})

app.get('/api/partnerships', (req, res) => {
  res.send(data.partnerships)
})

app.get('/api/organizations', (req, res) => {
  res.send(data.organizations)
})

app.get('/api/payment_records', (req, res) => {
  res.send(data.payment_records)
})

app.get('/api/callbacks', (req, res) => {
  res.send(data.callbacks)
})

app.get('/api/admins', (req, res) => {
  res.send(data.admins)
})

app.get('/api/judges', (req, res) => {
  res.send(data.judges)
})

app.get('/api/', (req, res) => {
  res.send({routes: [
    '/api/competitors',
    '/api/competitions',
    '/api/events',
    '/api/rounds',
    '/api/partnerships',
    '/api/organizations',
    '/api/payment_records',
    '/api/callbacks',
    '/api/admins',
    '/api/judges'
  ]})
})

const routes = [
  "/",
  "/home",
  "/competition/:competition_id/",
  "/competition/:competition_id/eventregistration",
  "/competition/:competition_id/editschedule",
  "/competition/:competition_id/run",
  "/competition/:competition_id/:competitor_id",
  "/competitions",
  "/admin/competition/:competition_id",
  '/editprofile'
]

// Serve index page
app.get(routes, (req, res) => {
  res.sendFile(__dirname + '/build/index.html');
});

/*************************************************************
 *
 * Webpack Dev Server
 *
 * See: http://webpack.github.io/docs/webpack-dev-server.html
 *
 *************************************************************/

if (!process.env.PRODUCTION) {
  const webpack = require('webpack');
  const WebpackDevServer = require('webpack-dev-server');
  const config = require('./webpack.local.config');

  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: true,
    historyApiFallback: true
  }).listen(9090, 'localhost', (err, result) => {
    if (err) {
      console.log(err);
    }
  });
}

/******************
 *
 * Express server
 *
 *****************/

const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Essential React listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>var Promise = require('bluebird')
  , which = require('which')
  , path = require('path')
  , _ = require('lodash')
  , ejs = require('ejs')
  , underscoreString = require('underscore.string')
  , rimraf = Promise.promisify(require('rimraf'))
  , exec = Promise.promisify(require('child_process').exec)
  , readdirp = Promise.promisify(require('readdirp'))
  , ncp = Promise.promisify(require('ncp').ncp)
  , fs = Promise.promisifyAll(require('fs'))
  , dns = Promise.promisifyAll(require('dns'));

module.exports = (function () {

  /*
   * Given a Sprout instance and a name, returns a
   * Template instance.
   * @param {Function} sprout - Sprout instance.
   * @param {String} name - Name of template
   * @param {String} src (optional) - Path or URL to source.  Only required for `template.save`.
   * @return {Function} - Template instance.
   */

  var Template = function (sprout, name, src) {
    this.sprout = sprout;
    this.name = name;
    this.path = path.join(sprout.path, name);
    this.root = path.join(this.path, 'root');

    /*
     * If `src` is set, use RegExp to determine
     * whether `src` is a local path or a remote
     * URL.
     */

    if (src) {
      this.src = src;
      this.isRemote = /(?:[A-Za-z0-9]+@|https?:\/\/)[A-Za-z0-9.]+(?::|\/)[A-Za-z0-9\/]+(?:\.git)?/.test(src);
    }

  }

  Template.prototype = {

    /*
     * Saves `template.src` to `template.path`
     * @return {Promise} - promise for Template instance.
     */

    save: function () {
      var self = this;
      return new Promise(
        function (resolve, reject) {

          var command;

          /*
           * Check if `src` (path or URL) is provided.
           */

          if (!self.src) {
            return reject(new Error('no source provided'));
          }

          /*
           * Check if git is installed
           */

          if (!which.sync('git')) {
            return reject(new Error('you need to have git installed'));
          }

          return resolve();
        }
      ).then(
        function () {
          if (self.isRemote) {

            /*
             * If source is remote, try to resolve
             * google.com to make sure internet
             * connection exists.
             */

            return dns.resolveAsync('google.com').catch(
              function () {
                throw new Error('make sure that you are connected to the internet!');
              }
            );

          }

          /*
           * If source is local, make
           * sure path exists.
           */

          if (!fs.existsSync(self.src)) {
            throw new Error('there is no sprout template located at ' + self.src);
          }

        }
      ).then(
        function () {

          /*
           * Remove existing template with the
           * same name.
           */

          return self.remove();

        }
      ).then(
        function () {

          /*
           * If source is remote, clone into
           * path. If source is local, symlink
           * to sprout's path.
           */

          command = self.isRemote ? ('git clone ' + self.src + ' ' + self.path)
            : ('ln -s ' + self.src + ' ' + self.path);

          return exec(command);

        }
      ).return(this);
    },

    /*
     * Initialize template and save to `target`
     * param {String} target - The path to save the template to.
     * @return {Promise} - Promise for Template instance.
     */

    init: function (target, options) {
      var self = this
        , options = (options || {})
        , config;
      return this.update().then(
        function () {

          /*
           * Check for init.coffee.  If init.coffee doesn't
           * exist, assume init is to located at init.js.
           * Require init once this is determined.
           */

          var initCoffee = path.join(self.path, 'init.coffee')
            , initJS = path.join(self.path, 'init.js')
            , initPath = fs.existsSync(initCoffee) ? initCoffee : initJS;

          try {
            /*
             * Register CoffeeScript; `init` file in template
             * can be either CoffeeScript or JavaScript.
             */

            require('coffee-script/register');

            init = require(initPath);
          } catch (_) {
            throw new Error('neither init.coffee nor init.js exist.');
          }

          /*
           * Run before hook if present.
           */

          if (init.before) {
            return new Promise(
              function (resolve, reject) {
                return init.before(resolve, reject);
              }
            )
          }

        }
      ).then(
        function () {

          /*
           * If target not passed,
           * throw an error.
           */

          if (!target) {
            throw new Error('target path required');
          }

          /*
           * If target directory exists,
           * throw an error.
           */

          if (fs.existsSync(target)) {
            throw new Error(target + ' already exists');
          }

        }
      ).then(
        function () {

          /*
           * Create the target directory.
           */

          return fs.mkdirAsync(target);

        }
      ).then(
        function () {

          var paths;

          /*
           * If questionnaire function exists,
           * run it to get answers.
           */

          if (_.isFunction(options.questionnaire) && _.isObject(init.configure)) {
            return options.questionnaire(init.configure, _.keys(locals));
          }

        }
      ).then(
        function (answers) {

          /*
           * Merge in all options and underscore.string.
           */

          config = _.extend(
            {},
            init.defaults,
            options.locals,
            answers,
            options,
            { S: underscoreString }
          );

          /*
           * Copy all file in root to target.
           */

          return ncp(self.root, target);

        }
      ).then(
        function () {

          /*
           * Run beforeRender hook if present.
           */

          if (init.beforeRender) {
            return new Promise(
              function (resolve, reject) {
                return init.beforeRender(config, resolve, reject);
              }
            )
          }

        }
      ).then(
        function () {

          /*
           * Read target directory.
           */

          return readdirp({ root: target });

        }
      ).then(
        function (result) {

          /*
           * Write all files with EJS replaced.
           */

          return Promise.map(result.files,
            function (file) {
              try {

                return fs.writeFileAsync(file.fullPath, ejs.render(fs.readFileSync(file.fullPath, 'utf8'), config));
              } catch (error) {
                throw new Error('ejs error in ' + file.path);
              }
            }
          )

        }
      ).then(
        function () {

          /*
           * Run after hook if present.
           */

          if (init.after) {
            return new Promise(
              function (resolve, reject) {
                return init.after(config, resolve, reject);
              }
            )
          }

        }
      ).return(this);
    },

    /*
     * Update template source.  Checks for remote origins.
     * If one or more exists, runs update.  Otherwise,
     * the promise simply resolves.
     * @return {Promise} - Promise for Template instance.
     */

    update: function () {
      var self = this;
      return exec('git remote', { cwd: self.path }).then(
        function (stdout) {
          if (stdout) {
            return exec('git remote update', { cwd: self.path });
          }
        }
      ).return(this);
    },

    /*
     * Delete the template.
     * @return {Promise} - Promise for Template instance.
     */

    remove: function () {
      return rimraf(this.path)
        .return(this);
    }

  }

  return Template;

}.call(this));
<commit_msg>Fix template.js<commit_after>var Promise = require('bluebird')
  , which = require('which')
  , path = require('path')
  , _ = require('lodash')
  , ejs = require('ejs')
  , underscoreString = require('underscore.string')
  , rimraf = Promise.promisify(require('rimraf'))
  , exec = Promise.promisify(require('child_process').exec)
  , readdirp = Promise.promisify(require('readdirp'))
  , ncp = Promise.promisify(require('ncp').ncp)
  , fs = Promise.promisifyAll(require('fs'))
  , dns = Promise.promisifyAll(require('dns'));

/*
 * Register CoffeeScript; `init` file in template
 * can be either CoffeeScript or JavaScript.
 */

require('coffee-script/register');

module.exports = (function () {

  /*
   * Given a Sprout instance and a name, returns a
   * Template instance.
   * @param {Function} sprout - Sprout instance.
   * @param {String} name - Name of template
   * @param {String} src (optional) - Path or URL to source.  Only required for `template.save`.
   * @return {Function} - Template instance.
   */

  var Template = function (sprout, name, src) {
    this.sprout = sprout;
    this.name = name;
    this.path = path.join(sprout.path, name);
    this.root = path.join(this.path, 'root');

    /*
     * If `src` is set, use RegExp to determine
     * whether `src` is a local path or a remote
     * URL.
     */

    if (src) {
      this.src = src;
      this.isRemote = /(?:[A-Za-z0-9]+@|https?:\/\/)[A-Za-z0-9.]+(?::|\/)[A-Za-z0-9\/]+(?:\.git)?/.test(src);
    }

  }

  Template.prototype = {

    /*
     * Saves `template.src` to `template.path`
     * @return {Promise} - promise for Template instance.
     */

    save: function () {
      var self = this;
      return new Promise(
        function (resolve, reject) {

          var command;

          /*
           * Check if `src` (path or URL) is provided.
           */

          if (!self.src) {
            return reject(new Error('no source provided'));
          }

          /*
           * Check if git is installed
           */

          if (!which.sync('git')) {
            return reject(new Error('you need to have git installed'));
          }

          return resolve();
        }
      ).then(
        function () {
          if (self.isRemote) {

            /*
             * If source is remote, try to resolve
             * google.com to make sure internet
             * connection exists.
             */

            return dns.resolveAsync('google.com').catch(
              function () {
                throw new Error('make sure that you are connected to the internet!');
              }
            );

          }

          /*
           * If source is local, make
           * sure path exists.
           */

          if (!fs.existsSync(self.src)) {
            throw new Error('there is no sprout template located at ' + self.src);
          }

        }
      ).then(
        function () {

          /*
           * Remove existing template with the
           * same name.
           */

          return self.remove();

        }
      ).then(
        function () {

          /*
           * If source is remote, clone into
           * path. If source is local, symlink
           * to sprout's path.
           */

          command = self.isRemote ? ('git clone ' + self.src + ' ' + self.path)
            : ('ln -s ' + self.src + ' ' + self.path);

          return exec(command);

        }
      ).return(this);
    },

    /*
     * Initialize template and save to `target`
     * param {String} target - The path to save the template to.
     * @return {Promise} - Promise for Template instance.
     */

    init: function (target, options) {
      var self = this
        , options = (options || {})
        , config;
      return this.update().then(
        function () {

          /*
           * Check for init.coffee.  If init.coffee doesn't
           * exist, assume init is to located at init.js.
           * Require init once this is determined.
           */

          var initCoffee = path.join(self.path, 'init.coffee')
            , initJS = path.join(self.path, 'init.js')
            , initPath = fs.existsSync(initCoffee) ? initCoffee : initJS;

          try {
            init = require(initPath);
          } catch (_) {
            throw new Error('neither init.coffee nor init.js exist.');
          }

          /*
           * Run before hook if present.
           */

          if (init.before) {
            return new Promise(
              function (resolve, reject) {
                return init.before(resolve, reject);
              }
            )
          }

        }
      ).then(
        function () {

          /*
           * If target not passed,
           * throw an error.
           */

          if (!target) {
            throw new Error('target path required');
          }

          /*
           * If target directory exists,
           * throw an error.
           */

          if (fs.existsSync(target)) {
            throw new Error(target + ' already exists');
          }

        }
      ).then(
        function () {

          /*
           * Create the target directory.
           */

          return fs.mkdirAsync(target);

        }
      ).then(
        function () {

          var paths;

          /*
           * If questionnaire function exists,
           * run it to get answers.
           */

          if (_.isFunction(options.questionnaire) && _.isObject(init.configure)) {
            return options.questionnaire(init.configure, _.keys(locals));
          }

        }
      ).then(
        function (answers) {

          /*
           * Merge in all options and underscore.string.
           */

          config = _.extend(
            {},
            init.defaults || {},
            options.locals || {},
            answers || {},
            { S: underscoreString }
          );

          /*
           * Copy all file in root to target.
           */

          return ncp(self.root, target);

        }
      ).then(
        function () {

          /*
           * Run beforeRender hook if present.
           */

          if (init.beforeRender) {
            return new Promise(
              function (resolve, reject) {
                return init.beforeRender(config, resolve, reject);
              }
            )
          }

        }
      ).then(
        function () {

          /*
           * Read target directory.
           */

          return readdirp({ root: target });

        }
      ).then(
        function (result) {

          /*
           * Write all files with EJS replaced.
           */

          return Promise.map(result.files,
            function (file) {
              try {

                return fs.writeFileAsync(file.fullPath, ejs.render(fs.readFileSync(file.fullPath, 'utf8'), config));
              } catch (error) {
                throw new Error('ejs error in ' + file.path);
              }
            }
          )

        }
      ).then(
        function () {

          /*
           * Run after hook if present.
           */

          if (init.after) {
            return new Promise(
              function (resolve, reject) {
                return init.after(config, resolve, reject);
              }
            )
          }

        }
      ).return(this);
    },

    /*
     * Update template source.  Checks for remote origins.
     * If one or more exists, runs update.  Otherwise,
     * the promise simply resolves.
     * @return {Promise} - Promise for Template instance.
     */

    update: function () {
      var self = this;
      return exec('git remote', { cwd: self.path }).then(
        function (stdout) {
          if (stdout) {
            return exec('git remote update', { cwd: self.path });
          }
        }
      ).return(this);
    },

    /*
     * Delete the template.
     * @return {Promise} - Promise for Template instance.
     */

    remove: function () {
      return rimraf(this.path)
        .return(this);
    }

  }

  return Template;

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


<commit_before>(function($, document, undefined){
  "use strict";

  function Searchfield($el, options){
    this.$el = $el;
    this.options = options;

    this.$cancelButton = null;

    options.showCancel && this.setupCancelButton();
  }

  Searchfield.prototype = {
    /**
     * Focusing a search field
     */
    focusin: function focusin(){
      this.maybeHideCancelButton();
    },
    keyup: function keyup(){
      this.maybeHideCancelButton();
    },
    /**
     * Leaving a search field
     */
    focusout: function focusout(){
      this.maybeHideCancelButton();
    },
    /**
     * Clear the field
     */
    clear: function clear(){
      this.$el.val('');

      this.options.focusAfterClear && this.$el.focus();
      this.hideCancelButton();
    },
    /**
     * Creates a Cancel Button and attach events to it
     */
    setupCancelButton: function setupCancelButton(){
      this.$cancelButton = $( document.createElement('div') );

      this.$cancelButton
        .addClass('search-cancel-button')
        .css('visibility', 'hidden')
        .on('click', $.proxy(this.clear, this) )
        .insertAfter(this.$el);
    },
    /**
     * Positions the Cancel Button to where it belongs
     */
    repositionCancelButton: function repositionCancelButton(){
      var position = this.$el.position();

      position.left += this.$el.outerWidth() - this.$cancelButton.width();

      //simulating top=50% + margin-top=-halfsize for middle vertical align
      position.top += (this.$el.outerHeight() + (parseInt(this.$el.css('border-top-width') || 0, 10))) / 2;
      position.top -= this.$cancelButton.height() / 2;

      this.$cancelButton.offset(position);
    },
    /**
     * Hide the Cancel Button if there is any reason of that
     * Aka field empty
     */
    maybeHideCancelButton: function maybeHideCancelButton(){
      var isVisible = !this.$cancelButton.hasClass('hidden');

      this.$el.val().trim().length === 0
        ? (isVisible && this.hideCancelButton())
        : (!isVisible && this.showCancelButton());
    },
    /**
     * Hide the Cancel Button
     */
    hideCancelButton: function hideCancelButton(){
      this.$cancelButton.addClass('hidden');
    },
    /**
     * Show the Cancel Button
     */
    showCancelButton: function showCancelButton(){
      this.repositionCancelButton();

      this.$cancelButton.css('visibility', '').removeClass('hidden');
    }
  };

  /**
   *
   * @param {Object|String|undefined=} option
   */
  $.fn.inputSearch = function inputSearch(option){
    return $(this).each(function(){
      var $input = $(this);
      var data = $input.data('input-search');
      var options = $.extend({}, $.fn.inputSearch.defaults, typeof option === 'object' && option);

      if (!data){
        $input.data('input-search', (data = new Searchfield($input, options)));
      }

      if (typeof option === 'string'){
        data[option]();
      }
    });
  };

  /**
   * Plugin Defaults
   *
   * @type {{showCancel: boolean}}
   */
  $.fn.inputSearch.defaults = {
    showCancel: true,
    focusAfterClear: true
  };

  /**
   * Keep an eye on the Object for testing purpose
   *
   * @type {Searchfield}
   */
  $.fn.inputSearch.Constructor = Searchfield;

  /**
   * Default Event Listeners
   */
  $(document)
    .on('focus blur keyup', 'input[type="search"].input-search', function(event){
      $(this).inputSearch(event.type);
    });
})(jQuery, document);<commit_msg>Simplifying<commit_after>(function($, document, undefined){
  "use strict";

  function Searchfield($el, options){
    this.$el = $el;
    this.options = options;

    this.$cancelButton = null;

    options.showCancel && this.setupCancelButton();
  }

  Searchfield.prototype = {
    /**
     * Clear the field
     */
    clear: function clear(){
      this.$el.val('');

      this.options.focusAfterClear && this.$el.focus();
      this.hideCancelButton();
    },
    /**
     * Creates a Cancel Button and attach events to it
     */
    setupCancelButton: function setupCancelButton(){
      this.$cancelButton = $( document.createElement('div') );

      this.$cancelButton
        .addClass('search-cancel-button')
        .css('visibility', 'hidden')
        .on('click', $.proxy(this.clear, this) )
        .insertAfter(this.$el);
    },
    /**
     * Positions the Cancel Button to where it belongs
     */
    repositionCancelButton: function repositionCancelButton(){
      var position = this.$el.position();

      position.left += this.$el.outerWidth() - this.$cancelButton.width();

      //simulating top=50% + margin-top=-halfsize for middle vertical align
      position.top += (this.$el.outerHeight() + (parseInt(this.$el.css('border-top-width') || 0, 10))) / 2;
      position.top -= this.$cancelButton.height() / 2;

      this.$cancelButton.offset(position);
    },
    /**
     * Hide the Cancel Button if there is any reason of that
     * Aka field empty
     */
    maybeHideCancelButton: function maybeHideCancelButton(){
      var isVisible = !this.$cancelButton.hasClass('hidden');

      this.$el.val().trim().length === 0
        ? (isVisible && this.hideCancelButton())
        : (!isVisible && this.showCancelButton());
    },
    /**
     * Hide the Cancel Button
     */
    hideCancelButton: function hideCancelButton(){
      this.$cancelButton.addClass('hidden');
    },
    /**
     * Show the Cancel Button
     */
    showCancelButton: function showCancelButton(){
      this.repositionCancelButton();

      this.$cancelButton.css('visibility', '').removeClass('hidden');
    }
  };

  /**
   *
   * @param {Object|String|undefined=} option
   */
  $.fn.inputSearch = function inputSearch(option){
    return $(this).each(function(){
      var $input = $(this);
      var data = $input.data('input-search');
      var options = $.extend({}, $.fn.inputSearch.defaults, typeof option === 'object' && option);

      if (!data){
        $input.data('input-search', (data = new Searchfield($input, options)));
      }

      if (typeof option === 'string'){
        data[option]();
      }
    });
  };

  /**
   * Plugin Defaults
   *
   * @type {{showCancel: boolean}}
   */
  $.fn.inputSearch.defaults = {
    showCancel: true,
    focusAfterClear: true
  };

  /**
   * Keep an eye on the Object for testing purpose
   *
   * @type {Searchfield}
   */
  $.fn.inputSearch.Constructor = Searchfield;

  /**
   * Default Event Listeners
   */
  $(document)
    .on('focus blur keyup', 'input[type="search"].input-search', function(event){
      $(this).inputSearch('maybeHideCancelButton');
    });
})(jQuery, document);<|endoftext|>


<commit_before>#!/usr/bin/env node

(function(){
    var mod = {};
    exports.serve = mod.serve = function() {
		var express = require("express");
		var app = express();
		var path = __dirname + '/';
		//var editor = require(path + "app/editor/js/editor.js");
		// respond with "Hello World!" on the homepage
		app.get('/', function (req, res) {
		  res.sendFile(path + 'app/game/views/index.html');
		});

		app.get('/edit', function (req, res) {
		  res.sendFile(path + 'app/editor/views/index.html');
		});

		app.use(express.static('app/shared/public'));
		app.use(express.static('app/editor/public'));
		app.use(express.static('app/game/public'));

		app.use('*', function (req, res) {
		  res.sendFile(path + 'app/shared/views/error/404.html');
		});

		app.listen(8080,function(){
		  console.log("Live at Port 8080");
		});
	}

    if (!module.parent) {
        mod.serve();
    }
})();<commit_msg>argh!<commit_after>#!/usr/bin/env node

(function(){
    var mod = {};
    exports.serve = mod.serve = function() {
		var express = require("express");
		var app = express();
		var path = __dirname + '/';
		//var editor = require(path + "app/editor/js/editor.js");
		// respond with "Hello World!" on the homepage
		app.get('/', function (req, res) {
		  res.sendFile(path + 'app/game/views/index.html');
		});

		app.get('/edit', function (req, res) {
		  res.sendFile(path + 'app/editor/views/index.html');
		});

		app.use(express.static('app/shared/public'));
		app.use(express.static('app/editor/public'));
		app.use(express.static('app/game/public'));

		app.use('*', function (req, res) {
		  res.sendFile(path + 'app/shared/views/error/404.html');
		});

		app.listen((process.env.PORT || 8080),function(){
		  console.log("Live at Port 8080");
		});
	}

    if (!module.parent) {
        mod.serve();
    }
})();<|endoftext|>


<commit_before>var dgram = require('dgram')

var syslog_regex = /<([0-9]{1,3})>([A-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}) (\S+) (.*)/

syslog = dgram.createSocket('udp4')
syslog.on('message', function(msg_orig, rinfo) {
	var msg = syslog_regex.exec(msg_orig)
	if (msg != null) {
		var facility = Math.floor(msg[1] / 8)
		var msg_info = {
			date: msg[2],
			host: msg[3],
			level: msg[1] - (facility * 8),
			facility: facility,
			message: msg[4],
		}
		console.log(msg_info)
	}
})

syslog.bind(514)
<commit_msg>http hello world, high range port for syslog dev<commit_after>var dgram = require('dgram')

var syslog_regex = /<([0-9]{1,3})>([A-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}) (\S+) (.*)/

syslog = dgram.createSocket('udp4')
syslog.on('message', function(msg_orig, rinfo) {
	var msg = syslog_regex.exec(msg_orig)
	if (msg != null) {
		var facility = Math.floor(msg[1] / 8)
		var msg_info = {
			date: msg[2],
			host: msg[3],
			level: msg[1] - (facility * 8),
			facility: facility,
			message: msg[4],
		}
		console.log(msg_info)
	}
})

syslog.bind(5140)

var http = require('http')

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('Hello World\n')
}).listen(8080)
<|endoftext|>