<commit_before>var fs = require('fs'),
    path = require('path');
/*
 * key values hash where key will be converted to a regex to match against paths and the value is the name of the file to be
 * served when that regex matchs.
 *
 * Behavior is undefined in the case of paths that match multiple keys. The first key seen (as returned by the javascript engine's iterator)
 * is the winner.
 */

module.exports = exports = {
    "/m/j\\?service=Taxonomy&method=getAllDepartments": "getAllDepartments.json",
    "/m/j\\?service=Taxonomy&method=getRollBacks": "getRollbacks.json",
    "/m/j\\?service=Browse&method=browseByToken.*": "browseByToken.json",
    "/m/j\\?service=Browse&method=search.*": "search.json",
    "/m/j\\?service=Browse&method=searchByDepartment.*": "searchByDepartment.json",
    "/m/j\\?service=Suggestions&method=getSuggestions.*": "getSuggestions.json",
    "/m/j\\?service=Reviews&method=getReviews&p1=.*": "getReviews.json",
    "/m/j\\?service=Vod&method=getVod": "getVod.json",
    "/m/j\\?service=OrderHistory&method=getOrders.*": "getOrders.json",
    "/m/j\\?service=OrderHistory&method=getOrder.*": "getOrder.json",

    "/m/j\\?service=Item&method=get&p1=(.*)": "item.json",
    "/m/j\\?service=ItemInventory&method=get&p1=.*": "items/getItemInventory.json",

    "/m/j\\?service=Authentication&method=login.*": "verify.json",
    "/m/j\\?service=Authentication&method=verify": "verify.json",

    "/m/j\\?service=StoreLocator&method=locate*": "locate.json",

    "/m/j\\?service=Cart&method=getThresholdItemSummary(&version=[\\d])?": "checkout/getThresholdItemSummary.json",
    "/m/j\\?service=Cart&method=get(&version=[\\d])?": "checkout/getCart.json",

    "/m/j\\?service=Checkout&method=getMessageKeys(&version=[\\d])?": "checkout/getMessageKeys.json",
    "/m/j\\?service=Checkout&method=getProtoOrder(&version=[\\d])?": "checkout/getProtoOrder.json",
    "/m/j\\?service=Checkout&method=getAvailableShip2HomeAddresses(&version=[\\d])?": "checkout/getAvailableShip2HomeAddresses.json",
    "/m/j\\?service=Checkout&method=getAvailableCreditCards(&version=[\\d])?": "checkout/getAvailableCreditCards.json",
    "/m/j\\?service=Checkout&method=getItems(&version=[\\d])?": "checkout/getItems.json",
    "/m/j\\?service=Checkout&method=isCidRequired(&version=[\\d])?": "checkout/isCidRequired.json",
    "/m/j\\?service=Checkout&method=verifyOrder(&version=[\\d])?": "checkout/verifyOrder.json",
    "/m/j\\?service=Checkout&method=placeOrder.*": "checkout/placeOrder.json",
    "/m/j\\?service=Checkout&method=getSelectedCreditCard": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=getCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=updateCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=createCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=setSelectedCreditCard.*": "checkout/setSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=updateBillingAddress.*": "checkout/updateBillingAddress.json",
    "/m/j\\?service=Checkout&method=getShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getSelectedShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=updateShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=createShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getAddressBestMatch.*": "checkout/getAvailableShip2HomeAddresses.json",
    "/m/j\\?service=Checkout&method=setSelectedShip2HomeAddress.*": "/checkout/setSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getSelectedShip2StoreAddress.*": "checkout/getSelectedShip2StoreAddress.json",
    "/m/j\\?service=Checkout&method=setSelectedShip2StoreAddress.*": "/checkout/setSelectedShip2StoreAddress.json",
    "/m/j\\?service=Checkout&method=isAssociateLoginRequired(&version=[\\d])?":"/isAssociateLoginRequired.json",
    "/m/j\\?service=Checkout&method=applyAssociateDiscount(&version=[\\d])?":"/checkout/applyAssociateDiscount.json",
    "/m/j\\?service=Checkout&method=setAssociateDeclined(&version=[\\d])?":"/checkout/setAssociateDeclined.json",
    "/m/j\\?service=Authentication&method=createAccount(&version=[\\d])?":"/createAccount.json",

    "/m/j\\?service=ExtendedItem&method=get(&version=[\\d])?&p1=(.*)": function(version, id) {
        var file = path.join(__dirname, 'items', id.replace(/\&.*/, '') + '.json');
        if (!path.existsSync(file)) {
            file = path.join(__dirname, 'items', '15750054.json')
        }
        return fs.readFileSync(file);
    }
};
<commit_msg>Updating mock server to be more tolerant of additional query params<commit_after>var fs = require('fs'),
    path = require('path');
/*
 * key values hash where key will be converted to a regex to match against paths and the value is the name of the file to be
 * served when that regex matchs.
 *
 * Behavior is undefined in the case of paths that match multiple keys. The first key seen (as returned by the javascript engine's iterator)
 * is the winner.
 */

module.exports = exports = {
    "/m/j\\?service=Taxonomy&method=getAllDepartments.*": "getAllDepartments.json",
    "/m/j\\?service=Taxonomy&method=getRollBacks.*": "getRollbacks.json",
    "/m/j\\?service=Browse&method=browseByToken.*": "browseByToken.json",
    "/m/j\\?service=Browse&method=search.*": "search.json",
    "/m/j\\?service=Browse&method=searchByDepartment.*": "searchByDepartment.json",
    "/m/j\\?service=Suggestions&method=getSuggestions.*": "getSuggestions.json",
    "/m/j\\?service=Reviews&method=getReviews&p1=.*": "getReviews.json",
    "/m/j\\?service=Vod&method=getVod.*": "getVod.json",
    "/m/j\\?service=OrderHistory&method=getOrders.*": "getOrders.json",
    "/m/j\\?service=OrderHistory&method=getOrder.*": "getOrder.json",

    "/m/j\\?service=Item&method=get&p1=(.*)": "item.json",
    "/m/j\\?service=ItemInventory&method=get&p1=.*": "items/getItemInventory.json",

    "/m/j\\?service=Authentication&method=login.*": "verify.json",
    "/m/j\\?service=Authentication&method=verify.*": "verify.json",

    "/m/j\\?service=StoreLocator&method=locate.*": "locate.json",

    "/m/j\\?service=Cart&method=getThresholdItemSummary(&version=[\\d])?": "checkout/getThresholdItemSummary.json",
    "/m/j\\?service=Cart&method=get(&version=[\\d])?": "checkout/getCart.json",

    "/m/j\\?service=Checkout&method=getMessageKeys(&version=[\\d])?": "checkout/getMessageKeys.json",
    "/m/j\\?service=Checkout&method=getProtoOrder(&version=[\\d])?": "checkout/getProtoOrder.json",
    "/m/j\\?service=Checkout&method=getAvailableShip2HomeAddresses(&version=[\\d])?": "checkout/getAvailableShip2HomeAddresses.json",
    "/m/j\\?service=Checkout&method=getAvailableCreditCards(&version=[\\d])?": "checkout/getAvailableCreditCards.json",
    "/m/j\\?service=Checkout&method=getItems(&version=[\\d])?": "checkout/getItems.json",
    "/m/j\\?service=Checkout&method=isCidRequired(&version=[\\d])?": "checkout/isCidRequired.json",
    "/m/j\\?service=Checkout&method=verifyOrder(&version=[\\d])?": "checkout/verifyOrder.json",
    "/m/j\\?service=Checkout&method=placeOrder.*": "checkout/placeOrder.json",
    "/m/j\\?service=Checkout&method=getSelectedCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=getCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=updateCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=createCreditCard.*": "checkout/getSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=setSelectedCreditCard.*": "checkout/setSelectedCreditCard.json",
    "/m/j\\?service=Checkout&method=updateBillingAddress.*": "checkout/updateBillingAddress.json",
    "/m/j\\?service=Checkout&method=getShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getSelectedShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=updateShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=createShip2HomeAddress.*": "checkout/getSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getAddressBestMatch.*": "checkout/getAvailableShip2HomeAddresses.json",
    "/m/j\\?service=Checkout&method=setSelectedShip2HomeAddress.*": "/checkout/setSelectedShip2HomeAddress.json",
    "/m/j\\?service=Checkout&method=getSelectedShip2StoreAddress.*": "checkout/getSelectedShip2StoreAddress.json",
    "/m/j\\?service=Checkout&method=setSelectedShip2StoreAddress.*": "/checkout/setSelectedShip2StoreAddress.json",
    "/m/j\\?service=Checkout&method=isAssociateLoginRequired(&version=[\\d])?":"/isAssociateLoginRequired.json",
    "/m/j\\?service=Checkout&method=applyAssociateDiscount(&version=[\\d])?":"/checkout/applyAssociateDiscount.json",
    "/m/j\\?service=Checkout&method=setAssociateDeclined(&version=[\\d])?":"/checkout/setAssociateDeclined.json",
    "/m/j\\?service=Authentication&method=createAccount(&version=[\\d])?":"/createAccount.json",

    "/m/j\\?service=ExtendedItem&method=get(&version=[\\d])?&p1=(.*)": function(version, id) {
        var file = path.join(__dirname, 'items', id.replace(/\&.*/, '') + '.json');
        if (!path.existsSync(file)) {
            file = path.join(__dirname, 'items', '15750054.json')
        }
        return fs.readFileSync(file);
    }
};
<|endoftext|>


<commit_before>var Utils = require("./utils")

module.exports = (function() {
  var QueryChainer = function(emitters) {
    var self = this

    this.finishedEmits = 0
    this.emitters = []
    this.serials = []
    this.fails = []
    this.finished = false
    this.wasRunning = false
    this.eventEmitter = null

    emitters = emitters || []
    emitters.forEach(function(emitter) { self.add(emitter) })
  }

  QueryChainer.prototype.add = function(emitterOrKlass, method, params, options) {
    if(!!method) {
      this.serials.push({ klass: emitterOrKlass, method: method, params: params, options: options })
    } else {
      observeEmitter.call(this, emitterOrKlass)
      this.emitters.push(emitterOrKlass)
    }

    return this
  }

  QueryChainer.prototype.run = function() {
    var self = this
    this.eventEmitter = new Utils.CustomEventEmitter(function() {
      self.wasRunning = true
      finish.call(self)
    })
    return this.eventEmitter.run()
  }

  QueryChainer.prototype.runSerially = function(options) {
    var self = this

    options = Utils._.extend({
      skipOnError: false
    }, options)

    var exec = function() {
      var serial = self.serials.pop()

      if(serial) {
        serial.options = serial.options || {}
        serial.options.before && serial.options.before(serial.klass)

        var onSuccess = function() {
          serial.options.after && serial.options.after(serial.klass)
          self.finishedEmits++
          exec()
        }

        var onError = function(err) {
          serial.options.after && serial.options.after(serial.klass)
          self.finishedEmits++
          self.fails.push(err)
          exec()
        }

        if(options.skipOnError && (self.fails.length > 0)) {
          onError('Skipped due to earlier error!')
        } else {
          var emitter = serial.klass[serial.method].apply(serial.klass, serial.params)
          emitter.success(function() {
            if(serial.options.success)
              serial.options.success(serial.klass, onSuccess)
            else
              onSuccess()
          }).error(onError)
        }
      } else {
        self.wasRunning = true
        finish.call(self)
      }
    }

    this.serials.reverse()
    this.eventEmitter = new Utils.CustomEventEmitter(exec)
    return this.eventEmitter.run()
  }

  // private

  var observeEmitter = function(emitter) {
    var self = this
    emitter
      .success(function(){
        self.finishedEmits++
        finish.call(self)
      })
      .error(function(err){
        self.finishedEmits++
        self.fails.push(err)
        finish.call(self)
      })
      .on('sql', function(sql){ self.eventEmitter.emit('sql', sql) })
  }

  var finish = function() {
    this.finished = true

    if(this.emitters.length > 0)
      this.finished = (this.finishedEmits == this.emitters.length)
    else if(this.serials.length > 0)
      this.finished = (this.finishedEmits == this.serials.length)

    if(this.finished && this.wasRunning) {
      var status = (this.fails.length == 0 ? 'success' : 'failure')
        , result = (this.fails.length == 0 ? result : this.fails)

      this.eventEmitter.emit(status, result)
    }
  }

  return QueryChainer
})()
<commit_msg>fixed eventEmitter<commit_after>var Utils = require("./utils")

module.exports = (function() {
  var QueryChainer = function(emitters) {
    var self = this

    this.finishedEmits = 0
    this.emitters = []
    this.serials = []
    this.fails = []
    this.finished = false
    this.wasRunning = false
    this.eventEmitter = null

    emitters = emitters || []
    emitters.forEach(function(emitter) { self.add(emitter) })
  }

  QueryChainer.prototype.add = function(emitterOrKlass, method, params, options) {
    if(!!method) {
      this.serials.push({ klass: emitterOrKlass, method: method, params: params, options: options })
    } else {
      observeEmitter.call(this, emitterOrKlass)
      this.emitters.push(emitterOrKlass)
    }

    return this
  }

  QueryChainer.prototype.run = function() {
    var self = this
    this.eventEmitter = new Utils.CustomEventEmitter(function() {
      self.wasRunning = true
      finish.call(self)
    })
    return this.eventEmitter.run()
  }

  QueryChainer.prototype.runSerially = function(options) {
    var self = this

    options = Utils._.extend({
      skipOnError: false
    }, options)

    var exec = function() {
      var serial = self.serials.pop()

      if(serial) {
        serial.options = serial.options || {}
        serial.options.before && serial.options.before(serial.klass)

        var onSuccess = function() {
          serial.options.after && serial.options.after(serial.klass)
          self.finishedEmits++
          exec()
        }

        var onError = function(err) {
          serial.options.after && serial.options.after(serial.klass)
          self.finishedEmits++
          self.fails.push(err)
          exec()
        }

        if(options.skipOnError && (self.fails.length > 0)) {
          onError('Skipped due to earlier error!')
        } else {
          var emitter = serial.klass[serial.method].apply(serial.klass, serial.params)
          emitter.success(function() {
            if(serial.options.success)
              serial.options.success(serial.klass, onSuccess)
            else
              onSuccess()
          }).error(onError)
        }
      } else {
        self.wasRunning = true
        finish.call(self)
      }
    }

    this.serials.reverse()
    this.eventEmitter = new Utils.CustomEventEmitter(exec)
    return this.eventEmitter.run()
  }

  // private

  var observeEmitter = function(emitter) {
    var self = this

    emitter
      .success(function() {
        self.finishedEmits++
        finish.call(self)
      })
      .error(function(err) {
        self.finishedEmits++
        self.fails.push(err)
        finish.call(self)
      })
      .on('sql', function(sql) {
        if(self.eventEmitter) {
          self.eventEmitter.emit('sql', sql)
        }
      })
  }

  var finish = function() {
    this.finished = true

    if(this.emitters.length > 0)
      this.finished = (this.finishedEmits == this.emitters.length)
    else if(this.serials.length > 0)
      this.finished = (this.finishedEmits == this.serials.length)

    if(this.finished && this.wasRunning) {
      var status = (this.fails.length == 0 ? 'success' : 'failure')
        , result = (this.fails.length == 0 ? result : this.fails)

      this.eventEmitter.emit(status, result)
    }
  }

  return QueryChainer
})()
<|endoftext|>


<commit_before>/**
 * Created by ar on 7/31/15.
 */

var idRepo = require("./../blogic/IdReposition");
var auxConcept=require("../model/auxConcept");
var auxDescription=require("../model/auxDescription");
var auxRelationship=require("../model/auxRelationship");
var namespaceDm = require("../blogic/NamespaceDataManager");

var idTotal=100000;

var runner = function (){
    namespaceDm.getNamespaces(function(err, namespaces) {
        if (err) {
            console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
            return;
        }
        console.log("namespaces " + namespaces);
        if (namespaces) {
            console.log("namespaces " + namespaces.length);
            namespaces.forEach(function (namespaceRecord) {
                if (namespaceRecord.idPregenerate && namespaceRecord.idPregenerate == "1") {
                    console.log("Ids pregeneration for namespaceId " + namespaceRecord.namespace);
                    var namespace = namespaceRecord.namespace;
                    var partitionId = '00';
                    idRepo.idBulkCreation(auxConcept, namespace, partitionId, idTotal, function (err) {
                        if (err) {
                            console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                        }
                        partitionId = '01';
                        idRepo.idBulkCreation(auxDescription, namespace, partitionId, idTotal, function (err) {
                            if (err) {
                                console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                            }
                            partitionId = '02';
                            idRepo.idBulkCreation(auxRelationship, namespace, partitionId, idTotal, function (err) {
                                if (err) {
                                    console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                                }
                            });
                        });
                    });
                }
            });
        }
    });
};

runner();

setInterval(runner,36000000);
//setTimeout(runner,5000);
<commit_msg>Added service to keep 100000 ids pre generated in available status<commit_after>/**
 * Created by ar on 7/31/15.
 */

var idRepo = require("./../blogic/IdReposition");
var auxConcept=require("../model/auxConcept");
var auxDescription=require("../model/auxDescription");
var auxRelationship=require("../model/auxRelationship");
var namespaceDm = require("../blogic/NamespaceDataManager");

var idTotal=100000;

var runner = function (){
    namespaceDm.getNamespaces(function(err, namespaces) {
        if (err) {
            console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
            return;
        }
        console.log("namespaces " + namespaces);
        if (namespaces) {
            console.log("namespaces " + namespaces.length);
            namespaces.forEach(function (namespaceRecord) {
                if (namespaceRecord.namespace==0){
                    console.log("namespaceRecord.idPregenerate=" + namespaceRecord.idPregenerate);
                }
                if (namespaceRecord.idPregenerate && namespaceRecord.idPregenerate == "1") {
                    console.log("Ids pregeneration for namespaceId " + namespaceRecord.namespace);
                    var namespace = namespaceRecord.namespace;
                    var partitionId = '00';
                    idRepo.idBulkCreation(auxConcept, namespace, partitionId, idTotal, function (err) {
                        if (err) {
                            console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                        }
                        partitionId = '01';
                        idRepo.idBulkCreation(auxDescription, namespace, partitionId, idTotal, function (err) {
                            if (err) {
                                console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                            }
                            partitionId = '02';
                            idRepo.idBulkCreation(auxRelationship, namespace, partitionId, idTotal, function (err) {
                                if (err) {
                                    console.log("[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err);
                                }
                            });
                        });
                    });
                }
            });
        }
    });
};

runner();

setInterval(runner,36000000);
//setTimeout(runner,5000);
<|endoftext|>


<commit_before>'use strict';

var fs    = require('fs');
var chalk = require('chalk');

module.exports = {

  description: 'Adds Photoswipe lib from bower and generate custom src',

  normalizeEntityName: function() {/* generator with no args */},

  afterInstall: function(options) {
    this.addBowerPackageToProject('photoswipe', '4.0.1');

    // we need to make a build without the history module.
    var fsDir    = options.project.bowerDirectory  + '/photoswipe';
    var fsFile   = fsDir + '/dist/photoswipe-ember.js';
    var srcFiles = [
      'framework-bridge',
      'core',
      'down-move-up-handlers',
      'items-controller',
      'tap',
      'desktop-zoom'
      //'history'
    ];
    var newContents = "(function (root, factory) { \n"+
      "\tif (typeof define === 'function' && define.amd) {\n" +
        "\t\tdefine(factory);\n" +
      "\t} else if (typeof exports === 'object') {\n" +
        "\t\tmodule.exports = factory();\n" +
      "\t} else {\n" +
        "\t\troot.PhotoSwipe = factory();\n" +
      "\t}\n" +
    "})(this, function () {\n\n" +
      "\t'use strict';\n"+
      "\tvar PhotoSwipe = function(template, UiClass, items, options){\n";

    var file, data;
    srcFiles.forEach(function(name) {
      file        = fsDir + '/src/js/' + name + '.js';
      newContents += fs.readFileSync(file);
    });

    newContents+= "\tframework.extend(self, publicMethods); };\n";
    newContents+= "\treturn PhotoSwipe;\n";
    newContents+= "});";

    fs.writeFileSync(fsFile, newContents);

    // done!
    console.log(chalk.green('\n[ember-cli-photoswipe]: Done!'));
  }
};
<commit_msg>dry blueprint<commit_after>'use strict';

var fs    = require('fs');
var chalk = require('chalk');

module.exports = {

  description: 'Adds Photoswipe lib from bower and generate custom src',

  normalizeEntityName: function() {/* generator with no args */},

  afterInstall: function(options) {
    this.addBowerPackageToProject('photoswipe', '4.0.1');

    // we need to make a build without the history module.
    var fsDir    = options.project.bowerDirectory  + '/photoswipe';
    var fsFile   = fsDir + '/dist/photoswipe-ember.js';
    var srcFiles = [
      'framework-bridge',
      'core',
      'down-move-up-handlers',
      'items-controller',
      'tap',
      'desktop-zoom'
      //'history'
    ];
    var newContents = "(function (root, factory) { \n"+
      "\tif (typeof define === 'function' && define.amd) {\n" +
        "\t\tdefine(factory);\n" +
      "\t} else if (typeof exports === 'object') {\n" +
        "\t\tmodule.exports = factory();\n" +
      "\t} else {\n" +
        "\t\troot.PhotoSwipe = factory();\n" +
      "\t}\n" +
    "})(this, function () {\n\n" +
      "\t'use strict';\n"+
      "\tvar PhotoSwipe = function(template, UiClass, items, options){\n";

    var file, data;
    srcFiles.forEach(function(name) {
      newContents += fs.readFileSync(fsDir + '/src/js/' + name + '.js');
    });

    newContents+= "\tframework.extend(self, publicMethods); };\n";
    newContents+= "\treturn PhotoSwipe;\n";
    newContents+= "});";

    fs.writeFileSync(fsFile, newContents);

    // done!
    console.log(chalk.green('\n[ember-cli-photoswipe]: Done!'));
  }
};
<|endoftext|>


<commit_before>(function (Raphael) {
  Raphael.fn.graph = {};

  Raphael.fn.graph.enable = function (types)
  {
    // by default only extend circle
    if (!types) types = ['circle'];

    // extend given types
    for (var i = 0; i < types.length; i++)
    {
      var type = types[i];
      this[type] = function (paper, fn)
      {
        return function ()
        {
          var element = fn.apply(paper, arguments);
          element.graph = new GraphExtension(element);
          return element;
        };
      }(this, this[type]);
    }

    return this;
  }

  var GraphExtension = function (element)
  {
    this.element = element;
    this.paper = element.paper;
  }

  GraphExtension.prototype.graph = function (g)
  {
    return this._graph = g || this._graph;
  }

  GraphExtension.prototype.edgeTo = function (el, weight)
  {
    if (this.graph() && el.graph.graph() && this.graph() !== el.graph.graph()) {
      this.graph().each(function (v)
      {
        // copy this graph to el's graph
        for (var u in this.adj(v))
        {
          var edge = this.get(v, u);
          el.graph.graph().set(v, this.vertex(u), edge);
        }

        v.graph.graph(el.graph.graph());
      });

    } else {
      // assign graph
      this.graph(el.graph.graph(this.graph() || el.graph.graph() || new Graph()));
    }

    // no loops, no multiedges
    if (this.element === el || this.graph().has(this.element, el))
      return;

    // create edge
    this.drawEdge(el);

    // attach listeners to redraw edges on drag
    this.setupVertex();
    el.graph.setupVertex();

    return this.element;
  }

  GraphExtension.prototype.edgesToTranslate = function ()
  {
    // edges (paths) with two parents in the set

    if (!this.element.draggable) return;

    if (this.element.draggable.parent && this.element.draggable.parent._to_translate)
    {
      return this.element.draggable.parent._to_translate;
    }

    // find edge paths to translate
    var subgraph = this.graph().subgraph(this.element.draggable.parent.items);
    var to_translate = [];

    subgraph.each(function (u)
    {
      for (var v in this.adj(u))
      {
        to_translate.push(this.get(u, v))
      }
    });

    return this.element.draggable.parent._to_translate = to_translate;
  }

  GraphExtension.prototype.edgesToRedraw = function ()
  {
    // edges (pairs) with one parent in the set

    if (!this.element.draggable) return;

    if (this.element.draggable.parent && this.element.draggable.parent._to_redraw)
    {
      return this.element.draggable.parent._to_redraw;
    }

    var to_redraw = []; // [[u, v], ...]
    var set_vertices = {}; //

    for (var i = 0; i < this.element.draggable.parent.items.length; i++)
      set_vertices[this.element.draggable.parent.items[i]] = 1;

    this.graph().each(function (v)
    {
      for (var u in this.adj(v))
      {
        if (u < v && v in set_vertices !== u in set_vertices)
        {
          to_redraw.push([this.vertex(u), this.vertex(v)]);
        }
      }
    });

    return this.element.draggable.parent._to_redraw = to_redraw;
  }

  GraphExtension.prototype.setupVertex = function ()
  {
    if (!this.element.draggable) return;

    if (this._setup_vertex) return;
    this._setup_vertex = 1;

    // drag start
    this.element.mousedown(function (event)
    {
      if (event.shiftKey)
      {
        // create set or add to existing set
        var set = this.paper._set = this.paper._set || this.paper.set().draggable.enable();
        set.push(this);
        delete set._to_translate;
        delete set._to_redraw;
        this.attr('fill', 'green');
        this.graph.colorNeighbors('red');
      } else if (!this.graph.hasEnabledSet())
      {
        // check for current set
        if (this.paper._set)
        {
          var set = this.paper._set;
          delete this.paper._set;
          // disable the set
          set.draggable.disable();
          // return everything to original color
          this.graph.graph().each(function (v)
          {
            this.vertex(v).attr('fill', 'blue');
          });
        }
        // color neighbors the active-neighbor color
        this.graph.colorNeighbors('red');
      }
    });

    // dragging
    this.element.draggable.dragged(function ()
    {
      // check if we are in a set
      if (this.graph.hasEnabledSet())
      {
        // translate edges with two parents in the set
        var to_translate = this.graph.edgesToTranslate();
        for (var i = 0; i < to_translate.length; i++)
        {
          // translate edge
          var edge = to_translate[i];
          var x = edge.head.attr('cx');
          var y = edge.head.attr('cy');
          edge.translate(x - edge.x, y - edge.y);
          edge.x = x; edge.y = y;
        }

        // redraw edges with one parent in the set
        var to_redraw = this.graph.edgesToRedraw();
        for (var i = 0; i < to_redraw.length; i++)
        {
          to_redraw[i][0].graph.drawEdge(to_redraw[i][1]);
        }
      } else
      {
        this.graph.drawEdges();
      }
    });

    // drag end
    this.element.mouseup(function ()
    {
      if (!this.graph.hasEnabledSet())
      {
        // color neighbors the default color
        this.graph.colorNeighbors('blue');
      }
    });
  }

  GraphExtension.prototype.hasEnabledSet = function ()
  {
    return this.element.draggable.parent && this.element.draggable.parent.draggable.enabled;
  }

  GraphExtension.prototype.isSetNeighbor = function (v)
  {
    return v.attr('fill') === 'green';
  }

  GraphExtension.prototype.isFringeNeighbor = function (v)
  {
    return v.attr('fill') === 'red';
  }

  GraphExtension.prototype.colorNeighbors = function (color)
  {
    for (var id in this.graph().adj(this.element))
    {
      var v = this.graph().vertex(id);
      if (!this.isSetNeighbor(v))
      {
        this.graph().vertex(id).attr('fill', color)
      }
    }

    return this.element;
  }

  GraphExtension.prototype.drawEdges = function ()
  {
    for (var id in this.graph().adj(this.element))
      this.drawEdge(this.graph().vertex(id));

    return this.element;
  }

  GraphExtension.prototype.drawEdge = function (el)
  {
    var x1 = this.element.attr('cx'),
      y1 = this.element.attr('cy'),
      x2 = el.attr('cx'),
      y2 = el.attr('cy');

    if (this.graph().has(this.element, el))
    {
      this.graph().get(this.element, el).remove();
    }

    // create new edge
    var edge = this.paper.path(['M', x1, y1, 'L', x2, y2]);
    edge.head = this.element;
    edge.x = x1; edge.y = y1;
    this.graph().set(this.element, el, edge);
    this.element.toFront();
    el.toFront();

    return this.element;
  }

  Raphael.el.toString = function ()
  {
    // Graph needs toString() on elements to identify vertices
    return "Raphael Object #"+this.id;
  }
})(Raphael);
<commit_msg>move existing edge instead of drawing new edge<commit_after>(function (Raphael) {
  Raphael.fn.graph = {};

  Raphael.fn.graph.enable = function (types)
  {
    // by default only extend circle
    if (!types) types = ['circle'];

    // extend given types
    for (var i = 0; i < types.length; i++)
    {
      var type = types[i];
      this[type] = function (paper, fn)
      {
        return function ()
        {
          var element = fn.apply(paper, arguments);
          element.graph = new GraphExtension(element);
          return element;
        };
      }(this, this[type]);
    }

    return this;
  }

  var GraphExtension = function (element)
  {
    this.element = element;
    this.paper = element.paper;
  }

  GraphExtension.prototype.graph = function (g)
  {
    return this._graph = g || this._graph;
  }

  GraphExtension.prototype.edgeTo = function (el, weight)
  {
    if (this.graph() && el.graph.graph() && this.graph() !== el.graph.graph()) {
      this.graph().each(function (v)
      {
        // copy this graph to el's graph
        for (var u in this.adj(v))
        {
          var edge = this.get(v, u);
          el.graph.graph().set(v, this.vertex(u), edge);
        }

        v.graph.graph(el.graph.graph());
      });

    } else {
      // assign graph
      this.graph(el.graph.graph(this.graph() || el.graph.graph() || new Graph()));
    }

    // no loops, no multiedges
    if (this.element === el || this.graph().has(this.element, el))
      return;

    // create edge
    this.drawEdge(el);

    // attach listeners to redraw edges on drag
    this.setupVertex();
    el.graph.setupVertex();

    return this.element;
  }

  GraphExtension.prototype.edgesToTranslate = function ()
  {
    // edges (paths) with two parents in the set

    if (!this.element.draggable) return;

    if (this.element.draggable.parent && this.element.draggable.parent._to_translate)
    {
      return this.element.draggable.parent._to_translate;
    }

    // find edge paths to translate
    var subgraph = this.graph().subgraph(this.element.draggable.parent.items);
    var to_translate = [];

    subgraph.each(function (u)
    {
      for (var v in this.adj(u))
      {
        to_translate.push(this.get(u, v))
      }
    });

    return this.element.draggable.parent._to_translate = to_translate;
  }

  GraphExtension.prototype.edgesToRedraw = function ()
  {
    // edges (pairs) with one parent in the set

    if (!this.element.draggable) return;

    if (this.element.draggable.parent && this.element.draggable.parent._to_redraw)
    {
      return this.element.draggable.parent._to_redraw;
    }

    var to_redraw = []; // [[u, v], ...]
    var set_vertices = {}; //

    for (var i = 0; i < this.element.draggable.parent.items.length; i++)
      set_vertices[this.element.draggable.parent.items[i]] = 1;

    this.graph().each(function (v)
    {
      for (var u in this.adj(v))
      {
        if (u < v && v in set_vertices !== u in set_vertices)
        {
          to_redraw.push([this.vertex(u), this.vertex(v)]);
        }
      }
    });

    return this.element.draggable.parent._to_redraw = to_redraw;
  }

  GraphExtension.prototype.setupVertex = function ()
  {
    if (!this.element.draggable) return;

    if (this._setup_vertex) return;
    this._setup_vertex = 1;

    // drag start
    this.element.mousedown(function (event)
    {
      if (event.shiftKey)
      {
        // create set or add to existing set
        var set = this.paper._set = this.paper._set || this.paper.set().draggable.enable();
        set.push(this);
        delete set._to_translate;
        delete set._to_redraw;
        this.attr('fill', 'green');
        this.graph.colorNeighbors('red');
      } else if (!this.graph.hasEnabledSet())
      {
        // check for current set
        if (this.paper._set)
        {
          var set = this.paper._set;
          delete this.paper._set;
          // disable the set
          set.draggable.disable();
          // return everything to original color
          this.graph.graph().each(function (v)
          {
            this.vertex(v).attr('fill', 'blue');
          });
        }
        // color neighbors the active-neighbor color
        this.graph.colorNeighbors('red');
      }
    });

    // dragging
    this.element.draggable.dragged(function ()
    {
      // check if we are in a set
      if (this.graph.hasEnabledSet())
      {
        // translate edges with two parents in the set
        var to_translate = this.graph.edgesToTranslate();
        for (var i = 0; i < to_translate.length; i++)
        {
          // translate edge
          var edge = to_translate[i];
          var x = edge.head.attr('cx');
          var y = edge.head.attr('cy');
          edge.translate(x - edge.x, y - edge.y);
          edge.x = x; edge.y = y;
        }

        // redraw edges with one parent in the set
        var to_redraw = this.graph.edgesToRedraw();
        for (var i = 0; i < to_redraw.length; i++)
        {
          to_redraw[i][0].graph.drawEdge(to_redraw[i][1]);
        }
      } else
      {
        this.graph.drawEdges();
      }
    });

    // drag end
    this.element.mouseup(function ()
    {
      if (!this.graph.hasEnabledSet())
      {
        // color neighbors the default color
        this.graph.colorNeighbors('blue');
      }
    });
  }

  GraphExtension.prototype.hasEnabledSet = function ()
  {
    return this.element.draggable.parent && this.element.draggable.parent.draggable.enabled;
  }

  GraphExtension.prototype.isSetNeighbor = function (v)
  {
    return v.attr('fill') === 'green';
  }

  GraphExtension.prototype.isFringeNeighbor = function (v)
  {
    return v.attr('fill') === 'red';
  }

  GraphExtension.prototype.colorNeighbors = function (color)
  {
    for (var id in this.graph().adj(this.element))
    {
      var v = this.graph().vertex(id);
      if (!this.isSetNeighbor(v))
      {
        this.graph().vertex(id).attr('fill', color)
      }
    }

    return this.element;
  }

  GraphExtension.prototype.drawEdges = function ()
  {
    for (var id in this.graph().adj(this.element))
      this.drawEdge(this.graph().vertex(id));

    return this.element;
  }

  GraphExtension.prototype.drawEdge = function (el)
  {
    var x1 = this.element.attr('cx'),
      y1 = this.element.attr('cy'),
      x2 = el.attr('cx'),
      y2 = el.attr('cy');

    var path = ['M', x1, y1, 'L', x2, y2];

    var edge = this.graph().get(this.element, el);
    if (edge) {
      // move existing edge
      edge.attr('path', path);
      return this.element;
    } else {
      // create new edge
      edge = this.paper.path(path);
      edge.head = this.element;
      edge.x = x1; edge.y = y1;
      this.graph().set(this.element, el, edge);
      this.element.toFront();
      el.toFront();
      return this.element;
    }
  }

  Raphael.el.toString = function ()
  {
    // Graph needs toString() on elements to identify vertices
    return "Raphael Object #"+this.id;
  }
})(Raphael);
<|endoftext|>


<commit_before>// Integration tests, template are defined in the tests/tests.jade file and
// instanciated with the following function:

var instanciate = function (tplName, data) {
  var component = UI.renderWithData(Template[tplName], data);

  // Create an invisible <div> node to render the component
  var testDiv = document.createElement("div");
  testDiv.style.display = "none";
  testDiv.className = tplName;

  // Insert the component
  UI.insert(component, testDiv);
  return component.templateInstance;
};

Tinytest.add('Jade - HTML tags', function (test) {
  var tpl = instanciate("htmlTags");
  test.isNotNull(tpl.find('h1'));
  test.isNotNull(tpl.find('h2.myClass'));
  test.isNotNull(tpl.find('h3#myId'));
  test.isNotNull(tpl.find('h4.myClass#myId'));
  test.isNotNull(tpl.find('form > input'));
  test.isNotNull(tpl.find('header > div'));
  test.isNotNull(tpl.find('p > strong'));
  test.isNotNull(tpl.find('div > span > span'));
});

Tinytest.add('Jade - Unwrapped Text', function (test) {
  var tpl = instanciate("unwrappedText");
  // XXX I don't know why but tpl.firstNode is null
  // test.equal(tpl.firstNode.innerText, "Unwrapped text");
  test.equal(tpl.find("h1").innerText, "Hello world");
});

Tinytest.add('Jade - HTML attributes', function (test) {
  var tpl = instanciate("htmlAttributes", {
    isRequired: true,
    placeholder: "test",
    attrs: {
      required: true,
      placeholder: "test"
    }
  });
  var tpl2 = instanciate("htmlAttributes", {
    isRequired: false
  });
  test.isTrue(tpl.find("#i1").required);
  test.equal(tpl.find("#i2").type, "password");
  test.isTrue(tpl.find("#i3").required);
  test.isFalse(tpl2.find("#i3").required);
  test.isTrue(tpl.find("#i4").required);
  test.equal(tpl.find("#i4").placeholder, "test");
  // XXX Bug
  // test.isTrue(tpl.find("#i5").required);
  // test.equal(tpl.find("#i5").placeholder, "test");
  test.equal(tpl.find("div").className, "class1 class2 class3");
});

Tinytest.add('Jade - else if', function (test) {
  var tpl1 = instanciate("elseIf", {isAdmin: true});
  var tpl2 = instanciate("elseIf", {isConnected: true});
  var tpl3 = instanciate("elseIf");
});

Tinytest.add('Jade - Expressions', function (test) {
  var tpl = instanciate("expressions", {
    myTitle: "Hello World",
    address: {country: "France"},
    name: "Maxime",
    surname: "Quandalle",
    btnKind: "btn-success"
  });
  test.equal(tpl.find("h1").innerText, "Hello World");
  test.equal(tpl.find("h2").innerText, "Hello France");
  test.equal(tpl.find("h3").innerText, "Hello Maxime Quandalle");
  // test.equal(tpl.find("button").className, "btn btn-success");
});

Tinytest.add('Jade - Components inclusion', function (test) {
  var tpl = instanciate("componentsInclusion");
  test.equal(tpl.findAll("h1").length, 1);
  test.equal(tpl.findAll("h2").length, 2);
  test.equal(tpl.findAll("h3").length, 3);
});

Tinytest.add('Jade - Components arguments', function (test) {
  // XXX TBD
});

Tinytest.add('Jade - Filters: markdown', function (test) {
  // XXX TBD
});
<commit_msg>Resurrect tests deleted inadvertently<commit_after>// Integration tests, template are defined in the tests/tests.jade file and
// instanciated with the following function:

var instanciate = function (tplName, data) {
  var component = UI.renderWithData(Template[tplName], data);

  // Create an invisible <div> node to render the component
  var testDiv = document.createElement("div");
  testDiv.style.display = "none";
  testDiv.className = tplName;

  // Insert the component
  UI.insert(component, testDiv);
  return component.templateInstance;
};

Tinytest.add('Jade - HTML tags', function (test) {
  var tpl = instanciate("htmlTags");
  test.isNotNull(tpl.find('h1'));
  test.isNotNull(tpl.find('h2.myClass'));
  test.isNotNull(tpl.find('h3#myId'));
  test.isNotNull(tpl.find('h4.myClass#myId'));
  test.isNotNull(tpl.find('form > input'));
  test.isNotNull(tpl.find('header > div'));
  test.isNotNull(tpl.find('p > strong'));
  test.isNotNull(tpl.find('div > span > span'));
});

Tinytest.add('Jade - Unwrapped Text', function (test) {
  var tpl = instanciate("unwrappedText");
  // XXX I don't know why but tpl.firstNode is null
  // test.equal(tpl.firstNode.innerText, "Unwrapped text");
  test.equal(tpl.find("h1").innerText, "Hello world");
});

Tinytest.add('Jade - HTML attributes', function (test) {
  var tpl = instanciate("htmlAttributes", {
    isRequired: true,
    placeholder: "test",
    attrs: {
      required: true,
      placeholder: "test"
    }
  });
  var tpl2 = instanciate("htmlAttributes", {
    isRequired: false
  });
  test.isTrue(tpl.find("#i1").required);
  test.equal(tpl.find("#i2").type, "password");
  test.isTrue(tpl.find("#i3").required);
  test.isFalse(tpl2.find("#i3").required);
  test.isTrue(tpl.find("#i4").required);
  test.equal(tpl.find("#i4").placeholder, "test");
  // XXX Bug
  // test.isTrue(tpl.find("#i5").required);
  // test.equal(tpl.find("#i5").placeholder, "test");
  test.equal(tpl.find("div").className, "class1 class2 class3");
});

Tinytest.add('Jade - else if', function (test) {
  var tpl1 = instanciate("elseIf", {isAdmin: true});
  var tpl2 = instanciate("elseIf", {isConnected: true});
  var tpl3 = instanciate("elseIf");
  test.equal(tpl1.find("h1").innerText, "Hello admin");
  test.equal(tpl2.find("h1").innerText, "Hello user");
  test.equal(tpl3.find("h1").innerText, "Hello visitor");
});

Tinytest.add('Jade - Expressions', function (test) {
  var tpl = instanciate("expressions", {
    myTitle: "Hello World",
    address: {country: "France"},
    name: "Maxime",
    surname: "Quandalle",
    btnKind: "btn-success"
  });
  test.equal(tpl.find("h1").innerText, "Hello World");
  test.equal(tpl.find("h2").innerText, "Hello France");
  test.equal(tpl.find("h3").innerText, "Hello Maxime Quandalle");
  // test.equal(tpl.find("button").className, "btn btn-success");
});

Tinytest.add('Jade - Components inclusion', function (test) {
  var tpl = instanciate("componentsInclusion");
  test.equal(tpl.findAll("h1").length, 1);
  test.equal(tpl.findAll("h2").length, 2);
  test.equal(tpl.findAll("h3").length, 3);
});

Tinytest.add('Jade - Components arguments', function (test) {
  // XXX TBD
});

Tinytest.add('Jade - Filters: markdown', function (test) {
  // XXX TBD
});
<|endoftext|>


<commit_before>
/*!
 * Module dependencies.
 */

import each from 'component-each';
import type from 'component-type';
import index from 'component-indexof';
import {normalize} from '../util/normalize';
import errors from '../errors';

const debug = require('debug')('recurly:token');

/**
 * expose
 */

module.exports = token;

/**
 * Fields that are sent to API.
 *
 * @type {Array}
 * @private
 */

var fields = [
  'first_name',
  'last_name',
  'address1',
  'address2',
  'country',
  'city',
  'state',
  'postal_code',
  'phone',
  'vat_number',
  'token'
];

/**
 * Generates a token from customer data.
 *
 * The callback signature: `err, response` where `err` is a
 * connection, request, or server error, and `response` is the
 * recurly service response. The generated token is accessed
 * at `response.token`.
 *
 * @param {Object|HTMLFormElement} options Billing properties or an HTMLFormElement
 * with children corresponding to billing properties via 'data-reurly' attributes.
 * @param {HTMLIFrameElement} options.number card number hosted field
 * @param {HTMLIFrameElement} options.month card expiration month hosted field
 * @param {HTMLIFrameElement} options.year card expiration year hosted field
 * @param {HTMLIFrameElement} options.cvv card verification value hosted field
 * @param {String} options.first_name customer first name
 * @param {String} options.last_name customer last name
 * @param {String} [options.address1]
 * @param {String} [options.address2]
 * @param {String} [options.country]
 * @param {String} [options.city]
 * @param {String} [options.state]
 * @param {String|Number} [options.postal_code]
 * @param {Function} done callback
 */

function token (options, done) {
  debug('token');

  var data = normalize(fields, options, { parseCard: true });
  var inputs = data.values;

  if (type(done) !== 'function') {
    throw errors('missing-callback');
  }

  // TODO: Need a better indication that we are in the parent role
  if (this.hostedFields) {
    // TODO: Emit this and unify the bus..
    this.bus.send('token:init', inputs);
    this.once('token:done', msg => { done(msg.err, msg.token); });
  } else {
    var userErrors = validate.call(this, inputs);
    if (userErrors.length) {
      return done(errors('validation', { fields: userErrors }));
    }

    this.request('post', '/token', inputs, function (err, res) {
      if (err) return done(err);
      if (data.fields.token && res.id) {
        data.fields.token.value = res.id;
      }
      done(null, res);
    });
  }
}

/**
 * Checks user input on a token call
 *
 * @param {Object} input
 * @return {Array} indicates which fields are not valid
 */

function validate (input) {
  var errors = [];

  if (!this.validate.cardNumber(input.number)) {
    errors.push('number');
  }

  if (!this.validate.expiry(input.month, input.year)) {
    errors.push('month', 'year');
  }

  if (!input.first_name) {
    errors.push('first_name');
  }

  if (!input.last_name) {
    errors.push('last_name');
  }

  if (input.cvv && !this.validate.cvv(input.cvv)) {
    errors.push('cvv');
  }

  each(this.config.required, function(field) {
    if (!input[field] && ~index(fields, field)) {
      errors.push(field);
    }
  });

  debug('validate errors', errors);

  return errors;
}
<commit_msg>Fixes issue with token input placement<commit_after>
/*!
 * Module dependencies.
 */

import each from 'component-each';
import type from 'component-type';
import index from 'component-indexof';
import {normalize} from '../util/normalize';
import errors from '../errors';

const debug = require('debug')('recurly:token');

/**
 * expose
 */

module.exports = token;

/**
 * Fields that are sent to API.
 *
 * @type {Array}
 * @private
 */

var fields = [
  'first_name',
  'last_name',
  'address1',
  'address2',
  'country',
  'city',
  'state',
  'postal_code',
  'phone',
  'vat_number',
  'token'
];

/**
 * Generates a token from customer data.
 *
 * The callback signature: `err, response` where `err` is a
 * connection, request, or server error, and `response` is the
 * recurly service response. The generated token is accessed
 * at `response.token`.
 *
 * @param {Object|HTMLFormElement} options Billing properties or an HTMLFormElement
 * with children corresponding to billing properties via 'data-reurly' attributes.
 * @param {HTMLIFrameElement} options.number card number hosted field
 * @param {HTMLIFrameElement} options.month card expiration month hosted field
 * @param {HTMLIFrameElement} options.year card expiration year hosted field
 * @param {HTMLIFrameElement} options.cvv card verification value hosted field
 * @param {String} options.first_name customer first name
 * @param {String} options.last_name customer last name
 * @param {String} [options.address1]
 * @param {String} [options.address2]
 * @param {String} [options.country]
 * @param {String} [options.city]
 * @param {String} [options.state]
 * @param {String|Number} [options.postal_code]
 * @param {Function} done callback
 */

function token (options, done) {
  debug('token');

  var data = normalize(fields, options, { parseCard: true });
  var inputs = data.values;

  if (type(done) !== 'function') {
    throw errors('missing-callback');
  }

  // TODO: Need a better indication that we are in the parent role
  if (this.hostedFields) {
    // TODO: Emit this and unify the bus..
    this.bus.send('token:init', inputs);
    this.once('token:done', msg => { complete(msg.err, msg.token); });
  } else {
    var userErrors = validate.call(this, inputs);
    if (userErrors.length) {
      return done(errors('validation', { fields: userErrors }));
    }

    this.request('post', '/token', inputs, complete);
  }

  function complete (err, res) {
    if (err) return done(err);
    if (data.fields.token && res.id) {
      data.fields.token.value = res.id;
    }
    done(null, res);
  }
}

/**
 * Checks user input on a token call
 *
 * @param {Object} input
 * @return {Array} indicates which fields are not valid
 */

function validate (input) {
  var errors = [];

  if (!this.validate.cardNumber(input.number)) {
    errors.push('number');
  }

  if (!this.validate.expiry(input.month, input.year)) {
    errors.push('month', 'year');
  }

  if (!input.first_name) {
    errors.push('first_name');
  }

  if (!input.last_name) {
    errors.push('last_name');
  }

  if (input.cvv && !this.validate.cvv(input.cvv)) {
    errors.push('cvv');
  }

  each(this.config.required, function(field) {
    if (!input[field] && ~index(fields, field)) {
      errors.push(field);
    }
  });

  debug('validate errors', errors);

  return errors;
}
<|endoftext|>


<commit_before>QUnit.module('Concur')

QUnit.test('Concur.extend', 12, function() {
  var Widget = Concur.extend({
    constructor: function(kwargs) {
      kwargs = Concur.cp({attrs: null}, kwargs)
      this.attrs = Concur.cp({}, kwargs.attrs)
    }
  , isHidden: false
  })

  var Input = Widget.extend({
    inputType: null
  , render: function(name, value) {
      return '<input type="' + this.inputType + '" name="' + name + '" value="' + value + '">'
    }
  })

  var TextInput = Input.extend({
    inputType: 'text'
  })

  var w = new TextInput({attrs: {style: 'color: red;'}})
  ok(w instanceof Widget, 'Is instanceof grandparent')
  ok(w instanceof Input, 'Is instanceof parent')
  deepEqual(w.attrs, {style: 'color: red;'}, 'Instance property set by grandparent constructor')
  equal(w.inputType, 'text', 'Parent prototype property is overriden')
  strictEqual(w.isHidden, false, 'Grandparent prototype property is overriden')
  equal(w.render('foo', 'bar'), '<input type="text" name="foo" value="bar">', 'Parent method works')

  var HiddenInput = Input.extend({
    inputType: 'hidden'
  , isHidden: true
  })

  var w = new HiddenInput
  ok(w instanceof Widget, 'Is instanceof grandparent')
  ok(w instanceof Input, 'Is instanceof parent')
  deepEqual(w.attrs, {}, 'Instance property set by grandparent constructor')
  equal(w.inputType, 'hidden', 'Parent prototype property is overriden')
  strictEqual(w.isHidden, true, 'Parent prototype property is overriden')
  equal(w.render('foo', 'bar'), '<input type="hidden" name="foo" value="bar">', 'Parent method works')
})

// Regression test for sane bahaviour when a constructor is not supplied on
// initial use of Concur.extend.
QUnit.test('Concur.extend (without supplied constructor)', 5, function() {
  var A = Concur.extend({
      test: function() { return 'a' }
    })
    , B = A.extend({
      test: function() { return 'b' }
    })

  var a = new A(), b = new B()
  ok(a instanceof A, 'Is instance of self')
  equal(a.test(), 'a', 'Prototype property is attached')
  ok(b instanceof B, 'Is instance of self')
  ok(b instanceof A, 'Is instance of parent')
  equal(b.test(), 'b', 'Parent prototype property is overridden')
})
<commit_msg>Test message typos [ci skip]<commit_after>QUnit.module('Concur')

QUnit.test('Concur.extend', 12, function() {
  var Widget = Concur.extend({
    constructor: function(kwargs) {
      kwargs = Concur.cp({attrs: null}, kwargs)
      this.attrs = Concur.cp({}, kwargs.attrs)
    }
  , isHidden: false
  })

  var Input = Widget.extend({
    inputType: null
  , render: function(name, value) {
      return '<input type="' + this.inputType + '" name="' + name + '" value="' + value + '">'
    }
  })

  var TextInput = Input.extend({
    inputType: 'text'
  })

  var w = new TextInput({attrs: {style: 'color: red;'}})
  ok(w instanceof Widget, 'Is instanceof grandparent')
  ok(w instanceof Input, 'Is instanceof parent')
  deepEqual(w.attrs, {style: 'color: red;'}, 'Instance property set by grandparent constructor')
  equal(w.inputType, 'text', 'Parent prototype property is overridden')
  strictEqual(w.isHidden, false, 'Grandparent prototype property is overridden')
  equal(w.render('foo', 'bar'), '<input type="text" name="foo" value="bar">', 'Parent method works')

  var HiddenInput = Input.extend({
    inputType: 'hidden'
  , isHidden: true
  })

  var w = new HiddenInput
  ok(w instanceof Widget, 'Is instanceof grandparent')
  ok(w instanceof Input, 'Is instanceof parent')
  deepEqual(w.attrs, {}, 'Instance property set by grandparent constructor')
  equal(w.inputType, 'hidden', 'Parent prototype property is overridden')
  strictEqual(w.isHidden, true, 'Parent prototype property is overridden')
  equal(w.render('foo', 'bar'), '<input type="hidden" name="foo" value="bar">', 'Parent method works')
})

// Regression test for sane bahaviour when a constructor is not supplied on
// initial use of Concur.extend.
QUnit.test('Concur.extend (without supplied constructor)', 5, function() {
  var A = Concur.extend({
      test: function() { return 'a' }
    })
    , B = A.extend({
      test: function() { return 'b' }
    })

  var a = new A(), b = new B()
  ok(a instanceof A, 'Is instance of self')
  equal(a.test(), 'a', 'Prototype property is attached')
  ok(b instanceof B, 'Is instance of self')
  ok(b instanceof A, 'Is instance of parent')
  equal(b.test(), 'b', 'Parent prototype property is overridden')
})
<|endoftext|>


<commit_before>/**
 * Created by Obscurity on 2016/5/12.
 */

var Diary = {};

Diary.Schema = {
    brief: {
        type: String,
        required: true
    },
    mood: {
        type: String,
        required: true,
        default: "happy"
    },
    tag: {
        type: String,
        required: true,
        default: 'coding'
    },
    content: {
        type: String,
        required: true
    },
    recorded_date: {
        type: Date,
        required: true,
        default: Date.now
    },
    recorded_at: {
        type: Date,
        required: true,
        default: Date.now
    },
    updated_at: {
        type: Date,
        required: true,
        default: Date.now
    }
};

Diary.collection = {
    collection: 'Diaries'
};

Diary.mood_to_color = function () {
    var hash_table = {
        "excited": "bg-orange",
        "happy": "bg-green",
        "angry": "bg-red",
        "tired": "bg-gray",
        "distracted": "bg-aqua",
        "gloomy": "bg-blue",
        "desperate": "bg-black"
    };
    return hash_table[this.mood];
};

Diary.mood_list = function () {
    return {
        "excited": {translation: "一颗赛艇", color: "bg-orange"},
        "happy": {translation: "2333", color: "bg-green"},
        "angry": {translation: "I'm angry!", color: "bg-red"},
        "tired": {translation: "あっ、疲れた。", color: "bg-gray"},
        "distracted": {translation: "忧桑啊...", color: "bg-aqua"},
        "gloomy": {translation: "找静静中...", color: "bg-blue"},
        "desperate": {translation: "日了狗了", color: "bg-black"}
    };
};

Diary.translate_mood = function () {
    var hash_table = {
        "excited": "一颗赛艇",
        "happy": "2333",
        "angry": "I am angry!",
        "tired": "あっ、疲れた。",
        "distracted": "忧桑啊...",
        "gloomy": "找静静中...",
        "desperate": "日了狗了"
    };
    return hash_table[this.mood];
};

Diary.tag_list = function () {
    return {
        "everything": {translation: "不明", icon: "fa-user"},
        "read": {translation: "读书", icon: "fa-book"},
        "movie": {translation: "电影", icon: "fa-film"},
        "music": {translation: "音乐", icon: "fa-music"},
        "coding": {translation: "代码", icon: "fa-code-fork"},
        "academy": {translation: "学术", icon: "fa-university"},
        "writing": {translation: "写作", icon: "fa-keyboard-o"},
        "travel": {translation: "出游", icon: "fa-map"},
        "learning": {translation: "学习", icon: "fa-lightbulb-o"},
        "social": {translation: "社交", icon: "fa-comments-o"},
        "society": {translation: "社会", icon: "fa-transgender-alt"},
        "plan": {translation: "社会", icon: "fa-calendar"}
    };
};

Diary.translate_tag = function () {
    var hash_table = {
        "everything": "不明",
        "read": "读书",
        "movie": "电影",
        "music": "音乐",
        "coding": "代码",
        "academy": "学术",
        "writing": "写作",
        "travel": "出游",
        "learning": "学习",
        "social": "社交",
        "society": "社会"
    };
    return hash_table[this.tag];
}

Diary.tag_to_icon = function () {
    var hash_table = {
        "everything": "fa-user",
        "read": "fa-book",
        "movie": "fa-film",
        "music": "fa-music",
        "coding": "fa-code-fork",
        "academy": "fa-university",
        "writing": "fa-keyboard-o",
        "travel": "fa-map",
        "learning": "fa-lightbulb-o",
        "social": "fa-comments-o",
        "society": "fa-transgender-alt",
        "plan": "fa-calendar"
    };
    return hash_table[this.tag];
};

module.exports = Diary;<commit_msg>修正一项列表中的错误<commit_after>/**
 * Created by Obscurity on 2016/5/12.
 */

var Diary = {};

Diary.Schema = {
    brief: {
        type: String,
        required: true
    },
    mood: {
        type: String,
        required: true,
        default: "happy"
    },
    tag: {
        type: String,
        required: true,
        default: 'coding'
    },
    content: {
        type: String,
        required: true
    },
    recorded_date: {
        type: Date,
        required: true,
        default: Date.now
    },
    recorded_at: {
        type: Date,
        required: true,
        default: Date.now
    },
    updated_at: {
        type: Date,
        required: true,
        default: Date.now
    }
};

Diary.collection = {
    collection: 'Diaries'
};

Diary.mood_to_color = function () {
    var hash_table = {
        "excited": "bg-orange",
        "happy": "bg-green",
        "angry": "bg-red",
        "tired": "bg-gray",
        "distracted": "bg-aqua",
        "gloomy": "bg-blue",
        "desperate": "bg-black"
    };
    return hash_table[this.mood];
};

Diary.mood_list = function () {
    return {
        "excited": {translation: "一颗赛艇", color: "bg-orange"},
        "happy": {translation: "2333", color: "bg-green"},
        "angry": {translation: "I'm angry!", color: "bg-red"},
        "tired": {translation: "あっ、疲れた。", color: "bg-gray"},
        "distracted": {translation: "忧桑啊...", color: "bg-aqua"},
        "gloomy": {translation: "找静静中...", color: "bg-blue"},
        "desperate": {translation: "日了狗了", color: "bg-black"}
    };
};

Diary.translate_mood = function () {
    var hash_table = {
        "excited": "一颗赛艇",
        "happy": "2333",
        "angry": "I am angry!",
        "tired": "あっ、疲れた。",
        "distracted": "忧桑啊...",
        "gloomy": "找静静中...",
        "desperate": "日了狗了"
    };
    return hash_table[this.mood];
};

Diary.tag_list = function () {
    return {
        "everything": {translation: "不明", icon: "fa-user"},
        "read": {translation: "读书", icon: "fa-book"},
        "movie": {translation: "电影", icon: "fa-film"},
        "music": {translation: "音乐", icon: "fa-music"},
        "coding": {translation: "代码", icon: "fa-code-fork"},
        "academy": {translation: "学术", icon: "fa-university"},
        "writing": {translation: "写作", icon: "fa-keyboard-o"},
        "travel": {translation: "出游", icon: "fa-map"},
        "learning": {translation: "学习", icon: "fa-lightbulb-o"},
        "social": {translation: "社交", icon: "fa-comments-o"},
        "society": {translation: "社会", icon: "fa-transgender-alt"},
        "plan": {translation: "计划", icon: "fa-calendar"}
    };
};

Diary.translate_tag = function () {
    var hash_table = {
        "everything": "不明",
        "read": "读书",
        "movie": "电影",
        "music": "音乐",
        "coding": "代码",
        "academy": "学术",
        "writing": "写作",
        "travel": "出游",
        "learning": "学习",
        "social": "社交",
        "society": "社会",
        "plan": "计划"
    };
    return hash_table[this.tag];
}

Diary.tag_to_icon = function () {
    var hash_table = {
        "everything": "fa-user",
        "read": "fa-book",
        "movie": "fa-film",
        "music": "fa-music",
        "coding": "fa-code-fork",
        "academy": "fa-university",
        "writing": "fa-keyboard-o",
        "travel": "fa-map",
        "learning": "fa-lightbulb-o",
        "social": "fa-comments-o",
        "society": "fa-transgender-alt",
        "plan": "fa-calendar"
    };
    return hash_table[this.tag];
};

module.exports = Diary;<|endoftext|>


<commit_before>var yaml = require('yamljs'),
  extend = require('../extend');

var yml = function(file, content){
  return yaml.parse(content);
};

extend.renderer.register('yml', 'json', yml, true);
extend.renderer.register('yaml', 'json', yml, true);<commit_msg>Before rendering YAML, replaces all tabs into spaces<commit_after>var yaml = require('yamljs'),
  extend = require('../extend');

var yml = function(file, content){
  content = content.replace(/\n(\t+)/g, function(match, tabs){
    var result = '\n';

    for (var i=0, len=args.length; i<len; i++){
      result += '  ';
    }

    return result;
  });

  return yaml.parse(content);
};

extend.renderer.register('yml', 'json', yml, true);
extend.renderer.register('yaml', 'json', yml, true);<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Base = require('./base')
  , cursor = Base.cursor
  , color = Base.color;

/**
 * Expose `TAP`.
 */

exports = module.exports = TAP;

/**
 * Initialize a new `TAP` reporter.
 *
 * @param {Runner} runner
 * @api public
 */

function TAP(runner) {
  Base.call(this, runner);

  var self = this
    , stats = this.stats
    , n = 1
    , passes = 0
    , failures = 1;

  runner.on('start', function(){
    var total = runner.grepTotal(runner.suite);
    console.log('%d..%d', 1, total);
  });

  runner.on('test end', function(){
    ++n;
  });

  runner.on('pending', function(test){
    console.log('ok %d %s # SKIP -', n, title(test));
  });

  runner.on('pass', function(test){
    passes++;
    console.log('ok %d %s', n, title(test));
  });

  runner.on('fail', function(test, err){
    failures++;
    console.log('not ok %d %s', n, title(test));
    console.log(err.stack.replace(/^/gm, '  '));
  });

  runner.on('end', function () {
    console.log('# tests ' + (passes + failures));
    console.log('# pass ' + passes);
    console.log('# fail ' + failures);
  });
}

/**
 * Return a TAP-safe title of `test`
 *
 * @param {Object} test
 * @return {String}
 * @api private
 */

function title(test) {
  return test.fullTitle().replace(/#/g, '');
}
<commit_msg>fix style in previous merge<commit_after>
/**
 * Module dependencies.
 */

var Base = require('./base')
  , cursor = Base.cursor
  , color = Base.color;

/**
 * Expose `TAP`.
 */

exports = module.exports = TAP;

/**
 * Initialize a new `TAP` reporter.
 *
 * @param {Runner} runner
 * @api public
 */

function TAP(runner) {
  Base.call(this, runner);

  var self = this
    , stats = this.stats
    , n = 1
    , passes = 0
    , failures = 1;

  runner.on('start', function(){
    var total = runner.grepTotal(runner.suite);
    console.log('%d..%d', 1, total);
  });

  runner.on('test end', function(){
    ++n;
  });

  runner.on('pending', function(test){
    console.log('ok %d %s # SKIP -', n, title(test));
  });

  runner.on('pass', function(test){
    passes++;
    console.log('ok %d %s', n, title(test));
  });

  runner.on('fail', function(test, err){
    failures++;
    console.log('not ok %d %s', n, title(test));
    console.log(err.stack.replace(/^/gm, '  '));
  });

  runner.on('end', function(){
    console.log('# tests ' + (passes + failures));
    console.log('# pass ' + passes);
    console.log('# fail ' + failures);
  });
}

/**
 * Return a TAP-safe title of `test`
 *
 * @param {Object} test
 * @return {String}
 * @api private
 */

function title(test) {
  return test.fullTitle().replace(/#/g, '');
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var fs = require('fs');
var yeoman = require('yeoman-generator');
var childProcess = require('child_process');

var foldername = path.basename(process.cwd());

var DjangoModelGenerator = module.exports = function DjangoModelGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);
  this.APPNAME = args[0];
  this.appDir = 'apps/' + args[0];
  this.modelFile = this.appDir + '/models.py';
  this.testFile = this.appDir + '/test_unit.py';
  this.on('end', function () {
  });
  this.model = {
    className: args[1],
    fields: [],
    unicode: 'self.'
  }

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(DjangoModelGenerator, yeoman.generators.Base);

function getType(fullType) {
  return fullType.split( ' - ' )[0];
}

DjangoModelGenerator.prototype.createFile = function createFile() {
    if(fs.existsSync(this.modelFile)){
      this.log('Model file already exists');
    } else {
      this.log('Creating new model file');
      this.copy('models.py', this.modelFile);
    }
    if(fs.existsSync(this.testFile)){
      this.log('Test file already exists');
    } else {
      this.log('Creating new test file');
      this.copy('../../startapp/templates/test_unit.py', this.testFile);
    }
}

DjangoModelGenerator.prototype.unicode = function unicode() {
  var cb = this.async();
  var prompts = [{
    name: 'unicode',
    message: 'Unicode representation [optional]'
  }];
  this.prompt(prompts, function(props) {
    this.model.unicode = props.unicode || 'pass';
    cb();
  }.bind(this));
};

DjangoModelGenerator.prototype.addFields = function addFields() {
  var cb = this.async();
  var that = this;
  function addField(fieldName) {
    var prompts = [{
      name: 'fieldType'+that.fieldCount,
      message: 'Type',
      type: 'list',
      choices: [
        'Text - CharField - VARCHAR',
        'Long text - TextField - TEXT',
        'Slug - SlugField - VARCHAR',
        'Boolean - BooleanField|NullBooleanField - BOOL',
        'Decimal - DecimalField - DECIMAL',
        'Integer - IntegerField - INT',
        'Float - FloatField - FLOAT',
        'File - FileField - VARCHAR',
        'Image - ImageField - VARCHAR',
        'Foreign key - ForeignKey - INT',
        'One to one key - OneToOneField - INT',
        'Many to many - ManyToManyField',
        'Date - DateField - DATE',
        'Date and time - DateTimeField - DATETIME',
        'Time - TimeField - TIME',
      ]
    },
    {
      name: 'nullable'+that.fieldCount,
      message: 'Nullable',
      type: 'confirm',
      default: false
    },
    {
      name: 'defaultValue'+that.fieldCount,
      message: 'Default value',
      default: ''
    },
    {
      name: 'max_length'+that.fieldCount,
      message: 'max_length',
      default: 255,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Text', 'File', 'Image', 'Slug'], t);
      }
    },
    // File and image stuff
    {
      name: 'upload_to'+that.fieldCount,
      message: 'upload_to',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['File', 'Image'], t);
      }
    },
    // Decimal stuff
    {
      name: 'max_digits'+that.fieldCount,
      message: 'max_digits',
      default: 10,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return t === 'Decimal'
      }
    },
    {
      name: 'decimal_places'+that.fieldCount,
      message: 'decimal_places',
      default: 2,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return t === 'Decimal'
      }
    },
    // Foreign and one to one keys
    {
      name: 'key_model'+that.fieldCount,
      message: 'Key model',
      default: '',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Foreign key', 'One to one key', 'Many to many'], t);
      }
    },
    {
      name: 'related_name'+that.fieldCount,
      message: 'Related name',
      default: '',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Foreign key', 'One to one key', 'Many to many'], t);
      }
    },
    {
      name: 'primary_key'+that.fieldCount,
      message: 'Primary key',
      default: false,
      type: 'confirm',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['One to one key'], t);
      }
    },
    // Date and datetime stuff
    {
      name: 'auto_now'+that.fieldCount,
      message: 'Auto now',
      type: 'confirm',
      default: true,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Date', 'Date and time', 'Time'], t);
      }
    }
    ];
    that.prompt(prompts, function(props) {
      that.fieldCount++;
      // Needed because mock prompts don't work _exactly_ the same way as a real loop
      var p = that._.clone(props);
      p.name = fieldName;
      that.model.fields.push(p);
      that.addFields();
    });
  }

  // Initialize count
  that.fieldCount = that.fieldCount || 0;
  var prompts = [
    {
      name: 'fieldName'+that.fieldCount,
      message: 'Field name [leave blank to pass]'
    },
  ];

  this.prompt(prompts, function (props) {
    var name = 'fieldName'+that.fieldCount;
    if(props[name]) {
      addField(props[name]);
    } else {
      that.model.fields = that._.map(that.model.fields, function(field, index) {
        // Get rid of the index everywhere
        var cleanField = {};
        that._.each(field, function(v, k) {
          var clean = k.replace(index, '');
          cleanField[clean] = v;
        });

        cleanField.fieldType = getType(cleanField.fieldType);
        return cleanField;
      });
      cb();
    }
  }.bind(this));
};

DjangoModelGenerator.prototype._makeField = function _makeField(name, type, params) {
  return name + ' = django.db.models.' + type + '(' + params.join(', ') + ')';
};

DjangoModelGenerator.prototype._null = function _null(field, params) {
  if(field.nullable){
    params.push('null=True');
  }
};

DjangoModelGenerator.prototype._default = function _default(field, params) {
  if(field.default){
    params.push('default='+field.default);
  }
};

// All the helper functions to prepare field string
// TODO Any reason to have them on the prototype?
DjangoModelGenerator.prototype._makeFieldImage = function _makeFieldImage(field) {
  var type = 'ImageField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  params.push("upload_to='"+field.upload_to+"'");
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldBoolean = function _makeFieldBoolean(field) {
  var type = field.nullable ? 'NullBooleanField' : 'BooleanField';
  var params = [];
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldFile = function _makeFieldFile(field) {
  var type = 'FileField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  params.push("upload_to='"+field.upload_to+"'");
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldDecimal = function _makeFieldDecimal(field) {
  var type = 'DecimalField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_digits='+field.max_digits);
  params.push('decimal_places='+field.decimal_places);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldInteger = function _makeFieldInteger(field) {
  var type = 'IntegerField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldFloat = function _makeFieldFloat(field) {
  var type = 'FloatField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldText = function _makeFieldText(field) {
  var type = 'CharField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldSlug = function _makeFieldSlug(field) {
  var type = 'SlugField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  return this._makeField(field.name, type, params);
};

// Yewwww naming... SO UGLY
DjangoModelGenerator.prototype['_makeFieldLong text'] = function (field) {
  var type = 'TextField';
  var params = [];
  // Text fields should not be nullable, they should have a default ''
  if(field.default) {
    params.push("default=" + field.default);
  } else {
    params.push("default=''");
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldForeign key'] = function (field) {
  var type = 'ForeignKey';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push("'"+field.key_model+"'");
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  return this._makeField(field.name, type, params);
};
DjangoModelGenerator.prototype['_makeFieldMany to many'] = function (field) {
  var type = 'ManyToManyField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push("'"+field.key_model+"'");
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldOne to one key'] = function (field) {
  var type = 'OneToOneField';
  var params = [];
  params.push("'"+field.key_model+"'");
  this._null(field, params);
  this._default(field, params);
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  if(field.primary_key) {
    params.push('primary_key=True');
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldDate and time'] = function (field) {
  var type = 'DateTimeField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True');
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldDate = function _makeFieldDate(field) {
  var type = 'DateField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True')
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldTime = function _makeFieldTime(field) {
  var type = 'TimeField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True')
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeModel = function _makeModel(model) {
  // Prepare model fields
  this._.each(model.fields, function(field) {
    field.asString = this['_makeField' + field.fieldType](field);
  }.bind(this));
  var fileContent = this.src.read('_modelClass.js');
  var compiled = this.engine(fileContent, model);
  return compiled;
};

DjangoModelGenerator.prototype.appendModel = function appendModel() {
  var that = this;
  // Append the model to the model file
  var fileContent = this.readFileAsString(this.modelFile);

  fileContent += that._makeModel(that.model);

  this.writeFileFromString(fileContent, this.modelFile);
  this.log('Model ' + that.model.className + ' created');
};

DjangoModelGenerator.prototype.appendUnit = function appendUnit() {
  var that = this;
  // Append the model to the model file
  var fileContent = this.readFileAsString(this.testFile);

  fileContent += that.engine(this.src.read('_modelTest.js'), that.model);

  this.writeFileFromString(fileContent, this.testFile);
  this.log('Model test created');
};

DjangoModelGenerator.prototype._getVersion = function _getVersion(cb) {
    if(this.VERSION) {
        return cb();
    }
    childProcess.exec(
     'python manage.py version', function(err, out) {
        this.VERSION = out.replace('\n', '');
        cb();
     }.bind(this));
}

DjangoModelGenerator.prototype.migrations = function unicode() {
  var cb = this.async();
  var prompts = [{
    name: 'migrations',
    message: 'Migrations',
    type: 'checkbox',
    choices: ['create', 'apply'],
    default: ['create', 'apply']
  }];
  this.prompt(prompts, function(props) {
    // Find out Django version
    this._getVersion(function() {
        var commands = [];
        if(this._.contains(props.migrations, 'create')) {
            // Depending on version, call South or built in
            if(this.VERSION >= '1.7') {
                var command = 'makemigrations <%= appName %>';
            } else {
                var command = 'schemamigrations <%= appName %> --initial';
            }
            commands.push( 'python manage.py ' + this._.template(command, {appName: this.APPNAME}) + ' --settings=settings.development' );
        }
        if(this._.contains(props.migrations, 'apply')) {
            commands.push( 'python manage.py migrate' + this.APPNAME + ' --settings=settings.development');
        }

        if(commands.length) {
            var fullCommand = commands.join(';');
            console.log(fullCommand);
            childProcess.exec(fullCommand, cb);
        } else {
            cb();
        }

    }.bind(this));
  }.bind(this));
};

<commit_msg>Try default on list using indexes<commit_after>'use strict';
var util = require('util');
var path = require('path');
var fs = require('fs');
var yeoman = require('yeoman-generator');
var childProcess = require('child_process');

var foldername = path.basename(process.cwd());

var DjangoModelGenerator = module.exports = function DjangoModelGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);
  this.APPNAME = args[0];
  this.appDir = 'apps/' + args[0];
  this.modelFile = this.appDir + '/models.py';
  this.testFile = this.appDir + '/test_unit.py';
  this.on('end', function () {
  });
  this.model = {
    className: args[1],
    fields: [],
    unicode: 'self.'
  }

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(DjangoModelGenerator, yeoman.generators.Base);

function getType(fullType) {
  return fullType.split( ' - ' )[0];
}

DjangoModelGenerator.prototype.createFile = function createFile() {
    if(fs.existsSync(this.modelFile)){
      this.log('Model file already exists');
    } else {
      this.log('Creating new model file');
      this.copy('models.py', this.modelFile);
    }
    if(fs.existsSync(this.testFile)){
      this.log('Test file already exists');
    } else {
      this.log('Creating new test file');
      this.copy('../../startapp/templates/test_unit.py', this.testFile);
    }
}

DjangoModelGenerator.prototype.unicode = function unicode() {
  var cb = this.async();
  var prompts = [{
    name: 'unicode',
    message: 'Unicode representation [optional]'
  }];
  this.prompt(prompts, function(props) {
    this.model.unicode = props.unicode || 'pass';
    cb();
  }.bind(this));
};

DjangoModelGenerator.prototype.addFields = function addFields() {
  var cb = this.async();
  var that = this;
  function addField(fieldName) {
    var prompts = [{
      name: 'fieldType'+that.fieldCount,
      message: 'Type',
      type: 'list',
      choices: [
        'Text - CharField - VARCHAR',
        'Long text - TextField - TEXT',
        'Slug - SlugField - VARCHAR',
        'Boolean - BooleanField|NullBooleanField - BOOL',
        'Decimal - DecimalField - DECIMAL',
        'Integer - IntegerField - INT',
        'Float - FloatField - FLOAT',
        'File - FileField - VARCHAR',
        'Image - ImageField - VARCHAR',
        'Foreign key - ForeignKey - INT',
        'One to one key - OneToOneField - INT',
        'Many to many - ManyToManyField',
        'Date - DateField - DATE',
        'Date and time - DateTimeField - DATETIME',
        'Time - TimeField - TIME',
      ]
    },
    {
      name: 'nullable'+that.fieldCount,
      message: 'Nullable',
      type: 'confirm',
      default: false
    },
    {
      name: 'defaultValue'+that.fieldCount,
      message: 'Default value',
      default: ''
    },
    {
      name: 'max_length'+that.fieldCount,
      message: 'max_length',
      default: 255,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Text', 'File', 'Image', 'Slug'], t);
      }
    },
    // File and image stuff
    {
      name: 'upload_to'+that.fieldCount,
      message: 'upload_to',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['File', 'Image'], t);
      }
    },
    // Decimal stuff
    {
      name: 'max_digits'+that.fieldCount,
      message: 'max_digits',
      default: 10,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return t === 'Decimal'
      }
    },
    {
      name: 'decimal_places'+that.fieldCount,
      message: 'decimal_places',
      default: 2,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return t === 'Decimal'
      }
    },
    // Foreign and one to one keys
    {
      name: 'key_model'+that.fieldCount,
      message: 'Key model',
      default: '',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Foreign key', 'One to one key', 'Many to many'], t);
      }
    },
    {
      name: 'related_name'+that.fieldCount,
      message: 'Related name',
      default: '',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Foreign key', 'One to one key', 'Many to many'], t);
      }
    },
    {
      name: 'primary_key'+that.fieldCount,
      message: 'Primary key',
      default: false,
      type: 'confirm',
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['One to one key'], t);
      }
    },
    // Date and datetime stuff
    {
      name: 'auto_now'+that.fieldCount,
      message: 'Auto now',
      type: 'confirm',
      default: true,
      when: function(answers) {
        var t = getType(answers['fieldType'+that.fieldCount]);
        return that._.contains(['Date', 'Date and time', 'Time'], t);
      }
    }
    ];
    that.prompt(prompts, function(props) {
      that.fieldCount++;
      // Needed because mock prompts don't work _exactly_ the same way as a real loop
      var p = that._.clone(props);
      p.name = fieldName;
      that.model.fields.push(p);
      that.addFields();
    });
  }

  // Initialize count
  that.fieldCount = that.fieldCount || 0;
  var prompts = [
    {
      name: 'fieldName'+that.fieldCount,
      message: 'Field name [leave blank to pass]'
    },
  ];

  this.prompt(prompts, function (props) {
    var name = 'fieldName'+that.fieldCount;
    if(props[name]) {
      addField(props[name]);
    } else {
      that.model.fields = that._.map(that.model.fields, function(field, index) {
        // Get rid of the index everywhere
        var cleanField = {};
        that._.each(field, function(v, k) {
          var clean = k.replace(index, '');
          cleanField[clean] = v;
        });

        cleanField.fieldType = getType(cleanField.fieldType);
        return cleanField;
      });
      cb();
    }
  }.bind(this));
};

DjangoModelGenerator.prototype._makeField = function _makeField(name, type, params) {
  return name + ' = django.db.models.' + type + '(' + params.join(', ') + ')';
};

DjangoModelGenerator.prototype._null = function _null(field, params) {
  if(field.nullable){
    params.push('null=True');
  }
};

DjangoModelGenerator.prototype._default = function _default(field, params) {
  if(field.default){
    params.push('default='+field.default);
  }
};

// All the helper functions to prepare field string
// TODO Any reason to have them on the prototype?
DjangoModelGenerator.prototype._makeFieldImage = function _makeFieldImage(field) {
  var type = 'ImageField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  params.push("upload_to='"+field.upload_to+"'");
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldBoolean = function _makeFieldBoolean(field) {
  var type = field.nullable ? 'NullBooleanField' : 'BooleanField';
  var params = [];
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldFile = function _makeFieldFile(field) {
  var type = 'FileField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  params.push("upload_to='"+field.upload_to+"'");
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldDecimal = function _makeFieldDecimal(field) {
  var type = 'DecimalField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_digits='+field.max_digits);
  params.push('decimal_places='+field.decimal_places);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldInteger = function _makeFieldInteger(field) {
  var type = 'IntegerField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldFloat = function _makeFieldFloat(field) {
  var type = 'FloatField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldText = function _makeFieldText(field) {
  var type = 'CharField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldSlug = function _makeFieldSlug(field) {
  var type = 'SlugField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push('max_length='+field.max_length);
  return this._makeField(field.name, type, params);
};

// Yewwww naming... SO UGLY
DjangoModelGenerator.prototype['_makeFieldLong text'] = function (field) {
  var type = 'TextField';
  var params = [];
  // Text fields should not be nullable, they should have a default ''
  if(field.default) {
    params.push("default=" + field.default);
  } else {
    params.push("default=''");
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldForeign key'] = function (field) {
  var type = 'ForeignKey';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push("'"+field.key_model+"'");
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  return this._makeField(field.name, type, params);
};
DjangoModelGenerator.prototype['_makeFieldMany to many'] = function (field) {
  var type = 'ManyToManyField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  params.push("'"+field.key_model+"'");
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldOne to one key'] = function (field) {
  var type = 'OneToOneField';
  var params = [];
  params.push("'"+field.key_model+"'");
  this._null(field, params);
  this._default(field, params);
  if(field.related_name) {
    params.push("related_name='" + field.related_name + "'");
  }
  if(field.primary_key) {
    params.push('primary_key=True');
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype['_makeFieldDate and time'] = function (field) {
  var type = 'DateTimeField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True');
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldDate = function _makeFieldDate(field) {
  var type = 'DateField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True')
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeFieldTime = function _makeFieldTime(field) {
  var type = 'TimeField';
  var params = [];
  this._null(field, params);
  this._default(field, params);
  if(field.auto_now) {
    params.push('auto_now=True')
  }
  return this._makeField(field.name, type, params);
};

DjangoModelGenerator.prototype._makeModel = function _makeModel(model) {
  // Prepare model fields
  this._.each(model.fields, function(field) {
    field.asString = this['_makeField' + field.fieldType](field);
  }.bind(this));
  var fileContent = this.src.read('_modelClass.js');
  var compiled = this.engine(fileContent, model);
  return compiled;
};

DjangoModelGenerator.prototype.appendModel = function appendModel() {
  var that = this;
  // Append the model to the model file
  var fileContent = this.readFileAsString(this.modelFile);

  fileContent += that._makeModel(that.model);

  this.writeFileFromString(fileContent, this.modelFile);
  this.log('Model ' + that.model.className + ' created');
};

DjangoModelGenerator.prototype.appendUnit = function appendUnit() {
  var that = this;
  // Append the model to the model file
  var fileContent = this.readFileAsString(this.testFile);

  fileContent += that.engine(this.src.read('_modelTest.js'), that.model);

  this.writeFileFromString(fileContent, this.testFile);
  this.log('Model test created');
};

DjangoModelGenerator.prototype._getVersion = function _getVersion(cb) {
    if(this.VERSION) {
        return cb();
    }
    childProcess.exec(
     'python manage.py version', function(err, out) {
        this.VERSION = out.replace('\n', '');
        cb();
     }.bind(this));
}

DjangoModelGenerator.prototype.migrations = function unicode() {
  var cb = this.async();
  var prompts = [{
    name: 'migrations',
    message: 'Migrations',
    type: 'checkbox',
    choices: ['create', 'apply'],
    default: [0,1]
  }];
  this.prompt(prompts, function(props) {
    // Find out Django version
    this._getVersion(function() {
        var commands = [];
        if(this._.contains(props.migrations, 'create')) {
            // Depending on version, call South or built in
            if(this.VERSION >= '1.7') {
                var command = 'makemigrations <%= appName %>';
            } else {
                var command = 'schemamigrations <%= appName %> --initial';
            }
            commands.push( 'python manage.py ' + this._.template(command, {appName: this.APPNAME}) + ' --settings=settings.development' );
        }
        if(this._.contains(props.migrations, 'apply')) {
            commands.push( 'python manage.py migrate' + this.APPNAME + ' --settings=settings.development');
        }

        if(commands.length) {
            var fullCommand = commands.join(';');
            console.log(fullCommand);
            childProcess.exec(fullCommand, cb);
        } else {
            cb();
        }

    }.bind(this));
  }.bind(this));
};

<|endoftext|>