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

var JqueryGenerator = module.exports = function JqueryGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

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

util.inherits(JqueryGenerator, yeoman.generators.NamedBase);

JqueryGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome = this.yeoman +
  '_Project Name_ should not contain "jquery" or "js" and ' +
  'should be a unique ID not already in use at plugins.jquery.com. _Project ' +
  'title_ should be a human-readable title, and doesn\'t need to contain ' +
  'the word "jQuery", although it may. For example, a plugin titled "Awesome ' +
  'Plugin" might have the name "awesome-plugin".' +
  '\n\n' +
  'For more information, please see the following documentation:' +
  '\n\n' +
  'Naming Your Plugin      http://plugins.jquery.com/docs/names/\n' +
  'Publishing Your Plugin  http://plugins.jquery.com/docs/publish/\n' +
  'Package Manifest        http://plugins.jquery.com/docs/package-manifest/\n';

  console.log(welcome);

  var prompts = [{
    name: 'name',
    message: 'Project Name'
  }, {
    name: 'title',
    default: 'Awesome jQuery plugin'
  }, {
    name: 'description',
    default: 'The best jQuery plugin ever.'
  }, {
    name: 'version'
  }, {
    name: 'repository'
  }, {
    name: 'bugs'
  }, {
    name: 'license',
    default: 'MIT'
  }, {
    name: 'github_username',
  }, {
    name: 'author_name'
  }, {
    name: 'author_email'
  }, {
    name: 'jquery_version',
    message: 'jQuery Version'
  }];

  var nameToMessage = function (name) {
    return name.split('_').map(
      function (x) { return this._.capitalize(x); }.bind(this)
    ).join(' ') + ':';
  }.bind(this);

  // Generate prompt messages if only the name is defined.
  prompts.map(function (entry) {
    if (entry.message === undefined) {
      entry.message = nameToMessage(entry.name);
    }
    return entry;
  }.bind(this));

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.props = props;
    // For easier access in the templates.
    this.slugname = this._.slugify(props.name);
    cb();
  }.bind(this));
};

JqueryGenerator.prototype.src = function src() {
  this.mkdir('src');
  this.copy('src/jshintrc', 'src/.jshintrc');
  this.template('src/name.js', 'src/' + this.slugname + '.js');
};

JqueryGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.copy('test/jshintrc', 'test/.jshintrc');
  this.template('test/name_test.js', 'test/' + this.slugname + '_test.js');
  this.template('test/name.html', 'test/' + this.slugname + '.html');
};

JqueryGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('travis.yml', '.travis.yml');

  this.template('README.md');
  this.template('Gruntfile.js');
  this.template('_bower.json', 'bower.json');
  this.template('_package.json', 'package.json');
  this.template('bowerrc', '.bowerrc');
  this.copy('CONTRIBUTING.md', 'CONTRIBUTING.md');
};
<commit_msg>Removed check for new prompt system<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var JqueryGenerator = module.exports = function JqueryGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

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

util.inherits(JqueryGenerator, yeoman.generators.NamedBase);

JqueryGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome = this.yeoman +
  '_Project Name_ should not contain "jquery" or "js" and ' +
  'should be a unique ID not already in use at plugins.jquery.com. _Project ' +
  'title_ should be a human-readable title, and doesn\'t need to contain ' +
  'the word "jQuery", although it may. For example, a plugin titled "Awesome ' +
  'Plugin" might have the name "awesome-plugin".' +
  '\n\n' +
  'For more information, please see the following documentation:' +
  '\n\n' +
  'Naming Your Plugin      http://plugins.jquery.com/docs/names/\n' +
  'Publishing Your Plugin  http://plugins.jquery.com/docs/publish/\n' +
  'Package Manifest        http://plugins.jquery.com/docs/package-manifest/\n';

  console.log(welcome);

  var prompts = [{
    name: 'name',
    message: 'Project Name'
  }, {
    name: 'title',
    default: 'Awesome jQuery plugin'
  }, {
    name: 'description',
    default: 'The best jQuery plugin ever.'
  }, {
    name: 'version'
  }, {
    name: 'repository'
  }, {
    name: 'bugs'
  }, {
    name: 'license',
    default: 'MIT'
  }, {
    name: 'github_username',
  }, {
    name: 'author_name'
  }, {
    name: 'author_email'
  }, {
    name: 'jquery_version',
    message: 'jQuery Version'
  }];

  var nameToMessage = function (name) {
    return name.split('_').map(
      function (x) { return this._.capitalize(x); }.bind(this)
    ).join(' ') + ':';
  }.bind(this);

  // Generate prompt messages if only the name is defined.
  prompts.map(function (entry) {
    if (entry.message === undefined) {
      entry.message = nameToMessage(entry.name);
    }
    return entry;
  }.bind(this));

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (props) {
    this.props = props;
    // For easier access in the templates.
    this.slugname = this._.slugify(props.name);
    cb();
  }.bind(this));
};

JqueryGenerator.prototype.src = function src() {
  this.mkdir('src');
  this.copy('src/jshintrc', 'src/.jshintrc');
  this.template('src/name.js', 'src/' + this.slugname + '.js');
};

JqueryGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.copy('test/jshintrc', 'test/.jshintrc');
  this.template('test/name_test.js', 'test/' + this.slugname + '_test.js');
  this.template('test/name.html', 'test/' + this.slugname + '.html');
};

JqueryGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('travis.yml', '.travis.yml');

  this.template('README.md');
  this.template('Gruntfile.js');
  this.template('_bower.json', 'bower.json');
  this.template('_package.json', 'package.json');
  this.template('bowerrc', '.bowerrc');
  this.copy('CONTRIBUTING.md', 'CONTRIBUTING.md');
};
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('confirmController', function($rootScope, $scope, $interval, $filter, $timeout, $ionicScrollDelegate, gettextCatalog, walletService, platformInfo, lodash, configService, rateService, $stateParams, $window, $state, $log, profileService, bitcore, gettext, txFormatService, ongoingProcess, $ionicModal, popupService, $ionicHistory, $ionicConfig) {
  var cachedTxp = {};
  var isChromeApp = platformInfo.isChromeApp;
  var countDown = null;
  $ionicConfig.views.swipeBackEnabled(false);

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.isWallet = data.stateParams.isWallet;
    $scope.cardId = data.stateParams.cardId;
    $scope.toAmount = data.stateParams.toAmount;
    $scope.toAddress = data.stateParams.toAddress;
    $scope.toName = data.stateParams.toName;
    $scope.toEmail = data.stateParams.toEmail;
    $scope.description = data.stateParams.description;
    $scope.paypro = data.stateParams.paypro;
    $scope.paymentExpired = {
      value: false
    };
    $scope.remainingTimeStr = {
      value: null
    };
    initConfirm();
  });

  var initConfirm = function() {
    if ($scope.paypro) {
      return setFromPayPro($scope.paypro, function(err) {
        if (err && !isChromeApp) {
          popupService.showAlert(gettext('Could not fetch payment'));
        }
      });
    }
    // TODO (URL , etc)
    if (!$scope.toAddress || !$scope.toAmount) {
      $log.error('Bad params at amount');
      throw ('bad params');
    }
    $scope.isCordova = platformInfo.isCordova;
    $scope.hasClick = platformInfo.hasClick;
    $scope.data = {};

    var config = configService.getSync().wallet;
    $scope.feeLevel = config.settings && config.settings.feeLevel ? config.settings.feeLevel : 'normal';

    $scope.toAmount = parseInt($scope.toAmount);
    $scope.amountStr = txFormatService.formatAmountStr($scope.toAmount);
    $scope.displayAmount = getDisplayAmount($scope.amountStr);
    $scope.displayUnit = getDisplayUnit($scope.amountStr);

    var networkName = (new bitcore.Address($scope.toAddress)).network.name;
    $scope.network = networkName;

    $scope.insuffientFunds = false;
    $scope.noMatchingWallet = false;

    var wallets = profileService.getWallets({
      onlyComplete: true,
      network: networkName,
    });

    if (!wallets || !wallets.length) {
      $scope.noMatchingWallet = true;
    }

    var filteredWallets = [];
    var index = 0;
    var enoughFunds = false;

    lodash.each(wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {
        if (err || !status) {
          $log.error(err);
        } else {
          w.status = status;
          if (!status.availableBalanceSat) $log.debug('No balance available in: ' + w.name);
          if (status.availableBalanceSat > $scope.toAmount) {
            filteredWallets.push(w);
            enoughFunds = true;
          }
        }

        if (++index == wallets.length) {
          if (!lodash.isEmpty(filteredWallets)) {
            $scope.wallets = lodash.clone(filteredWallets);
            setWallet($scope.wallets[0]);
          } else {

            if (!enoughFunds)
              $scope.insuffientFunds = true;

            $log.warn('No wallet available to make the payment');
          }
        }
      });
    });

    txFormatService.formatAlternativeStr($scope.toAmount, function(v) {
      $scope.alternativeAmountStr = v;
    });

    $timeout(function() {
      $scope.$apply();
    }, 100);
  };

  $scope.$on('accepted', function(event) {
    $scope.approve();
  });

  $scope.$on('Wallet/Changed', function(event, wallet) {
    if (lodash.isEmpty(wallet)) {
      $log.debug('No wallet provided');
      return;
    }
    $log.debug('Wallet changed: ' + wallet.name);
    setWallet(wallet, true);
  });

  $scope.showWalletSelector = function() {
    $scope.showWallets = true;
  };

  $scope.onWalletSelect = function(wallet) {
    setWallet(wallet);
  };

  $scope.showDescriptionPopup = function() {
    var message = gettextCatalog.getString('Add description');
    var opts = {
      defaultText: $scope.description
    };

    popupService.showPrompt(null, message, opts, function(res) {
      if (typeof res != 'undefined') $scope.description = res;
      $timeout(function() {
        $scope.$apply();
      }, 100);
    });
  };

  function getDisplayAmount(amountStr) {
    return amountStr.split(' ')[0];
  }

  function getDisplayUnit(amountStr) {
    return amountStr.split(' ')[1];
  }

  var setFromPayPro = function(uri, cb) {
    if (!cb) cb = function() {};

    var wallet = profileService.getWallets({
      onlyComplete: true
    })[0];

    if (!wallet) return cb();

    if (isChromeApp) {
      popupService.showAlert(gettextCatalog.getString('Payment Protocol not supported on Chrome App'));
      return cb(true);
    }

    $log.debug('Fetch PayPro Request...', uri);

    ongoingProcess.set('fetchingPayPro', true);
    wallet.fetchPayPro({
      payProUrl: uri,
    }, function(err, paypro) {

      ongoingProcess.set('fetchingPayPro', false);

      if (err) {
        $log.warn('Could not fetch payment request:', err);
        var msg = err.toString();
        if (msg.match('HTTP')) {
          msg = gettextCatalog.getString('Could not fetch payment information');
        }
        popupService.showAlert(msg);
        return cb(true);
      }

      if (!paypro.verified) {
        $log.warn('Failed to verify payment protocol signatures');
        popupService.showAlert(gettextCatalog.getString('Payment Protocol Invalid'));
        return cb(true);
      }

      $scope.toAmount = paypro.amount;
      $scope.toAddress = paypro.toAddress;
      $scope.description = paypro.memo;
      $scope.paypro = null;

      $scope._paypro = paypro;
      _paymentTimeControl(paypro.expires);
      return initConfirm();
    });
  };

  function _paymentTimeControl(expirationTime) {
    $scope.paymentExpired.value = false;
    setExpirationTime();

    countDown = $interval(function() {
      setExpirationTime();
    }, 1000);

    function setExpirationTime() {
      var now = Math.floor(Date.now() / 1000);

      if (now > expirationTime) {
        setExpiredValues();
        return;
      }

      var totalSecs = expirationTime - now;
      var m = Math.floor(totalSecs / 60);
      var s = totalSecs % 60;
      $scope.remainingTimeStr.value = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2);
    };

    function setExpiredValues() {
      $scope.paymentExpired.value = true;
      $scope.remainingTimeStr.value = gettextCatalog.getString('Expired');
      if (countDown) $interval.cancel(countDown);
      $timeout(function() {
        $scope.$apply();
      });
    };
  };

  function setWallet(wallet, delayed) {
    var stop;
    $scope.wallet = wallet;
    $scope.fee = $scope.txp = null;

    $timeout(function() {
      $ionicScrollDelegate.resize();
      $scope.$apply();
    }, 10);

    if (stop) {
      $timeout.cancel(stop);
      stop = null;
    }

    if (cachedTxp[wallet.id]) {
      apply(cachedTxp[wallet.id]);
    } else {
      stop = $timeout(function() {
        createTx(wallet, true, function(err, txp) {
          if (err) return;
          cachedTxp[wallet.id] = txp;
          apply(txp);
        });
      }, delayed ? 2000 : 1);
    }
  };

  var setSendError = function(msg) {
    $scope.sendStatus = '';
    $timeout(function() {
      $scope.$apply();
    });
    popupService.showAlert(gettextCatalog.getString('Error at confirm:'), msg);
  };

  function apply(txp) {
    $scope.fee = txFormatService.formatAmountStr(txp.fee);
    $scope.txp = txp;
    $scope.$apply();
  }

  var createTx = function(wallet, dryRun, cb) {
    var config = configService.getSync().wallet;
    var currentSpendUnconfirmed = config.spendUnconfirmed;
    var outputs = [];

    var paypro = $scope.paypro;
    var toAddress = $scope.toAddress;
    var toAmount = $scope.toAmount;
    var description = $scope.description;

    // ToDo: use a credential's (or fc's) function for this
    if (description && !wallet.credentials.sharedEncryptingKey) {
      var msg = 'Could not add message to imported wallet without shared encrypting key';
      $log.warn(msg);
      return setSendError(msg);
    }

    if (toAmount > Number.MAX_SAFE_INTEGER) {
      var msg = 'Amount too big';
      $log.warn(msg);
      return setSendError(msg);
    };

    outputs.push({
      'toAddress': toAddress,
      'amount': toAmount,
      'message': description
    });

    var txp = {};

    // TODO
    if (!lodash.isEmpty($scope.sendMaxInfo)) {
      txp.sendMax = true;
      txp.inputs = $scope.sendMaxInfo.inputs;
      txp.fee = $scope.sendMaxInfo.fee;
    }

    txp.outputs = outputs;
    txp.message = description;
    txp.payProUrl = paypro;
    txp.excludeUnconfirmedUtxos = config.spendUnconfirmed ? false : true;
    txp.feeLevel = config.settings && config.settings.feeLevel ? config.settings.feeLevel : 'normal';
    txp.dryRun = dryRun;

    walletService.createTx(wallet, txp, function(err, ctxp) {
      if (err) {
        setSendError(err);
        return cb(err);
      }
      return cb(null, ctxp);
    });
  };

  $scope.openPPModal = function() {
    $ionicModal.fromTemplateUrl('views/modals/paypro.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.payproModal = modal;
      $scope.payproModal.show();
    });
  };

  $scope.approve = function(onSendStatusChange) {
    if ($scope._paypro && $scope.paymentExpired.value) {
      popupService.showAlert(null, gettextCatalog.getString('The payment request has expired'));
      return;
    }

    var wallet = $scope.wallet;
    if (!wallet) {
      return setSendError(gettextCatalog.getString('No wallet selected'));
    };

    if (!wallet.canSign() && !wallet.isPrivKeyExternal()) {
      $log.info('No signing proposal: No private key');

      return walletService.onlyPublish(wallet, txp, function(err, txp) {
        if (err) return setSendError(err);
      });
    }

    ongoingProcess.set('creatingTx', true, onSendStatusChange);
    createTx(wallet, false, function(err, txp) {
      ongoingProcess.set('creatingTx', false, onSendStatusChange);
      if (err) return;

      var config = configService.getSync();
      var spendingPassEnabled = walletService.isEncrypted(wallet);
      var touchIdEnabled = config.touchIdFor && config.touchIdFor[wallet.id];
      var isCordova = $scope.isCordova;
      var bigAmount = parseFloat(txFormatService.formatToUSD(txp.amount)) > 20;
      var message = gettextCatalog.getString('Sending {{amountStr}} from your {{name}} wallet', {
        amountStr: $scope.amountStr,
        name: wallet.name
      });
      var okText = gettextCatalog.getString('Confirm');
      var cancelText = gettextCatalog.getString('Cancel');

      if (!spendingPassEnabled && !touchIdEnabled) {
        if (isCordova) {
          if (bigAmount) {
            popupService.showConfirm(null, message, okText, cancelText, function(ok) {
              if (!ok) {
                $scope.sendStatus = '';
                $timeout(function() {
                  $scope.$apply();
                });
                return;
              }
              publishAndSign(wallet, txp, onSendStatusChange);
            });
          } else publishAndSign(wallet, txp, onSendStatusChange);
        } else {
          popupService.showConfirm(null, message, okText, cancelText, function(ok) {
            if (!ok) {
              $scope.sendStatus = '';
              return;
            }
            publishAndSign(wallet, txp, onSendStatusChange);
          });
        }
      } else publishAndSign(wallet, txp, onSendStatusChange);
    });
  };

  function statusChangeHandler(processName, showName, isOn) {
    $log.debug('statusChangeHandler: ', processName, showName, isOn);
    if ((processName === 'broadcastingTx' || ((processName === 'signingTx') && $scope.wallet.m > 1)) && !isOn) {
      $scope.sendStatus = 'success';
      $scope.$digest();
    } else if (showName) {
      $scope.sendStatus = showName;
    }
  }

  $scope.statusChangeHandler = statusChangeHandler;

  $scope.onConfirm = function() {
    $scope.approve(statusChangeHandler);
  };

  $scope.onSuccessConfirm = function() {
    var previousView = $ionicHistory.viewHistory().backView && $ionicHistory.viewHistory().backView.stateName;
    var fromBitPayCard = previousView.match(/tabs.bitpayCard/) ? true : false;

    $ionicHistory.nextViewOptions({
      disableAnimate: true
    });
    $ionicHistory.removeBackView();
    $scope.sendStatus = '';

    if (fromBitPayCard) {
      $timeout(function() {
        $state.transitionTo('tabs.bitpayCard', {
          id: $stateParams.cardId
        });
      }, 100);
    } else {
      $state.go('tabs.send');
    }
  };

  function publishAndSign(wallet, txp, onSendStatusChange) {
    walletService.publishAndSign(wallet, txp, function(err, txp) {
      if (err) return setSendError(err);
    }, onSendStatusChange);
  }
});
<commit_msg>fix spinner after slide to pay<commit_after>'use strict';

angular.module('copayApp.controllers').controller('confirmController', function($rootScope, $scope, $interval, $filter, $timeout, $ionicScrollDelegate, gettextCatalog, walletService, platformInfo, lodash, configService, rateService, $stateParams, $window, $state, $log, profileService, bitcore, gettext, txFormatService, ongoingProcess, $ionicModal, popupService, $ionicHistory, $ionicConfig) {
  var cachedTxp = {};
  var isChromeApp = platformInfo.isChromeApp;
  var countDown = null;
  $ionicConfig.views.swipeBackEnabled(false);

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.isWallet = data.stateParams.isWallet;
    $scope.cardId = data.stateParams.cardId;
    $scope.toAmount = data.stateParams.toAmount;
    $scope.toAddress = data.stateParams.toAddress;
    $scope.toName = data.stateParams.toName;
    $scope.toEmail = data.stateParams.toEmail;
    $scope.description = data.stateParams.description;
    $scope.paypro = data.stateParams.paypro;
    $scope.paymentExpired = {
      value: false
    };
    $scope.remainingTimeStr = {
      value: null
    };
    initConfirm();
  });

  var initConfirm = function() {
    if ($scope.paypro) {
      return setFromPayPro($scope.paypro, function(err) {
        if (err && !isChromeApp) {
          popupService.showAlert(gettext('Could not fetch payment'));
        }
      });
    }
    // TODO (URL , etc)
    if (!$scope.toAddress || !$scope.toAmount) {
      $log.error('Bad params at amount');
      throw ('bad params');
    }
    $scope.isCordova = platformInfo.isCordova;
    $scope.hasClick = platformInfo.hasClick;
    $scope.data = {};

    var config = configService.getSync().wallet;
    $scope.feeLevel = config.settings && config.settings.feeLevel ? config.settings.feeLevel : 'normal';

    $scope.toAmount = parseInt($scope.toAmount);
    $scope.amountStr = txFormatService.formatAmountStr($scope.toAmount);
    $scope.displayAmount = getDisplayAmount($scope.amountStr);
    $scope.displayUnit = getDisplayUnit($scope.amountStr);

    var networkName = (new bitcore.Address($scope.toAddress)).network.name;
    $scope.network = networkName;

    $scope.insuffientFunds = false;
    $scope.noMatchingWallet = false;

    var wallets = profileService.getWallets({
      onlyComplete: true,
      network: networkName,
    });

    if (!wallets || !wallets.length) {
      $scope.noMatchingWallet = true;
    }

    var filteredWallets = [];
    var index = 0;
    var enoughFunds = false;

    lodash.each(wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {
        if (err || !status) {
          $log.error(err);
        } else {
          w.status = status;
          if (!status.availableBalanceSat) $log.debug('No balance available in: ' + w.name);
          if (status.availableBalanceSat > $scope.toAmount) {
            filteredWallets.push(w);
            enoughFunds = true;
          }
        }

        if (++index == wallets.length) {
          if (!lodash.isEmpty(filteredWallets)) {
            $scope.wallets = lodash.clone(filteredWallets);
            setWallet($scope.wallets[0]);
          } else {

            if (!enoughFunds)
              $scope.insuffientFunds = true;

            $log.warn('No wallet available to make the payment');
          }
        }
      });
    });

    txFormatService.formatAlternativeStr($scope.toAmount, function(v) {
      $scope.alternativeAmountStr = v;
    });

    $timeout(function() {
      $scope.$apply();
    }, 100);
  };

  $scope.$on('accepted', function(event) {
    $scope.approve();
  });

  $scope.$on('Wallet/Changed', function(event, wallet) {
    if (lodash.isEmpty(wallet)) {
      $log.debug('No wallet provided');
      return;
    }
    $log.debug('Wallet changed: ' + wallet.name);
    setWallet(wallet, true);
  });

  $scope.showWalletSelector = function() {
    $scope.showWallets = true;
  };

  $scope.onWalletSelect = function(wallet) {
    setWallet(wallet);
  };

  $scope.showDescriptionPopup = function() {
    var message = gettextCatalog.getString('Add description');
    var opts = {
      defaultText: $scope.description
    };

    popupService.showPrompt(null, message, opts, function(res) {
      if (typeof res != 'undefined') $scope.description = res;
      $timeout(function() {
        $scope.$apply();
      }, 100);
    });
  };

  function getDisplayAmount(amountStr) {
    return amountStr.split(' ')[0];
  }

  function getDisplayUnit(amountStr) {
    return amountStr.split(' ')[1];
  }

  var setFromPayPro = function(uri, cb) {
    if (!cb) cb = function() {};

    var wallet = profileService.getWallets({
      onlyComplete: true
    })[0];

    if (!wallet) return cb();

    if (isChromeApp) {
      popupService.showAlert(gettextCatalog.getString('Payment Protocol not supported on Chrome App'));
      return cb(true);
    }

    $log.debug('Fetch PayPro Request...', uri);

    ongoingProcess.set('fetchingPayPro', true);
    wallet.fetchPayPro({
      payProUrl: uri,
    }, function(err, paypro) {

      ongoingProcess.set('fetchingPayPro', false);

      if (err) {
        $log.warn('Could not fetch payment request:', err);
        var msg = err.toString();
        if (msg.match('HTTP')) {
          msg = gettextCatalog.getString('Could not fetch payment information');
        }
        popupService.showAlert(msg);
        return cb(true);
      }

      if (!paypro.verified) {
        $log.warn('Failed to verify payment protocol signatures');
        popupService.showAlert(gettextCatalog.getString('Payment Protocol Invalid'));
        return cb(true);
      }

      $scope.toAmount = paypro.amount;
      $scope.toAddress = paypro.toAddress;
      $scope.description = paypro.memo;
      $scope.paypro = null;

      $scope._paypro = paypro;
      _paymentTimeControl(paypro.expires);
      return initConfirm();
    });
  };

  function _paymentTimeControl(expirationTime) {
    $scope.paymentExpired.value = false;
    setExpirationTime();

    countDown = $interval(function() {
      setExpirationTime();
    }, 1000);

    function setExpirationTime() {
      var now = Math.floor(Date.now() / 1000);

      if (now > expirationTime) {
        setExpiredValues();
        return;
      }

      var totalSecs = expirationTime - now;
      var m = Math.floor(totalSecs / 60);
      var s = totalSecs % 60;
      $scope.remainingTimeStr.value = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2);
    };

    function setExpiredValues() {
      $scope.paymentExpired.value = true;
      $scope.remainingTimeStr.value = gettextCatalog.getString('Expired');
      if (countDown) $interval.cancel(countDown);
      $timeout(function() {
        $scope.$apply();
      });
    };
  };

  function setWallet(wallet, delayed) {
    var stop;
    $scope.wallet = wallet;
    $scope.fee = $scope.txp = null;

    $timeout(function() {
      $ionicScrollDelegate.resize();
      $scope.$apply();
    }, 10);

    if (stop) {
      $timeout.cancel(stop);
      stop = null;
    }

    if (cachedTxp[wallet.id]) {
      apply(cachedTxp[wallet.id]);
    } else {
      stop = $timeout(function() {
        createTx(wallet, true, function(err, txp) {
          if (err) return;
          cachedTxp[wallet.id] = txp;
          apply(txp);
        });
      }, delayed ? 2000 : 1);
    }
  };

  var setSendError = function(msg) {
    $scope.sendStatus = '';
    $timeout(function() {
      $scope.$apply();
    });
    popupService.showAlert(gettextCatalog.getString('Error at confirm:'), msg);
  };

  function apply(txp) {
    $scope.fee = txFormatService.formatAmountStr(txp.fee);
    $scope.txp = txp;
    $scope.$apply();
  }

  var createTx = function(wallet, dryRun, cb) {
    var config = configService.getSync().wallet;
    var currentSpendUnconfirmed = config.spendUnconfirmed;
    var outputs = [];

    var paypro = $scope.paypro;
    var toAddress = $scope.toAddress;
    var toAmount = $scope.toAmount;
    var description = $scope.description;

    // ToDo: use a credential's (or fc's) function for this
    if (description && !wallet.credentials.sharedEncryptingKey) {
      var msg = 'Could not add message to imported wallet without shared encrypting key';
      $log.warn(msg);
      return setSendError(msg);
    }

    if (toAmount > Number.MAX_SAFE_INTEGER) {
      var msg = 'Amount too big';
      $log.warn(msg);
      return setSendError(msg);
    };

    outputs.push({
      'toAddress': toAddress,
      'amount': toAmount,
      'message': description
    });

    var txp = {};

    // TODO
    if (!lodash.isEmpty($scope.sendMaxInfo)) {
      txp.sendMax = true;
      txp.inputs = $scope.sendMaxInfo.inputs;
      txp.fee = $scope.sendMaxInfo.fee;
    }

    txp.outputs = outputs;
    txp.message = description;
    txp.payProUrl = paypro;
    txp.excludeUnconfirmedUtxos = config.spendUnconfirmed ? false : true;
    txp.feeLevel = config.settings && config.settings.feeLevel ? config.settings.feeLevel : 'normal';
    txp.dryRun = dryRun;

    walletService.createTx(wallet, txp, function(err, ctxp) {
      if (err) {
        setSendError(err);
        return cb(err);
      }
      return cb(null, ctxp);
    });
  };

  $scope.openPPModal = function() {
    $ionicModal.fromTemplateUrl('views/modals/paypro.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.payproModal = modal;
      $scope.payproModal.show();
    });
  };

  $scope.approve = function(onSendStatusChange) {
    if ($scope._paypro && $scope.paymentExpired.value) {
      popupService.showAlert(null, gettextCatalog.getString('The payment request has expired'));
      $scope.sendStatus = '';
      $timeout(function() {
        $scope.$apply();
      });
      return;
    }

    var wallet = $scope.wallet;
    if (!wallet) {
      return setSendError(gettextCatalog.getString('No wallet selected'));
    };

    if (!wallet.canSign() && !wallet.isPrivKeyExternal()) {
      $log.info('No signing proposal: No private key');

      return walletService.onlyPublish(wallet, txp, function(err, txp) {
        if (err) return setSendError(err);
      });
    }

    ongoingProcess.set('creatingTx', true, onSendStatusChange);
    createTx(wallet, false, function(err, txp) {
      ongoingProcess.set('creatingTx', false, onSendStatusChange);
      if (err) return;

      var config = configService.getSync();
      var spendingPassEnabled = walletService.isEncrypted(wallet);
      var touchIdEnabled = config.touchIdFor && config.touchIdFor[wallet.id];
      var isCordova = $scope.isCordova;
      var bigAmount = parseFloat(txFormatService.formatToUSD(txp.amount)) > 20;
      var message = gettextCatalog.getString('Sending {{amountStr}} from your {{name}} wallet', {
        amountStr: $scope.amountStr,
        name: wallet.name
      });
      var okText = gettextCatalog.getString('Confirm');
      var cancelText = gettextCatalog.getString('Cancel');

      if (!spendingPassEnabled && !touchIdEnabled) {
        if (isCordova) {
          if (bigAmount) {
            popupService.showConfirm(null, message, okText, cancelText, function(ok) {
              if (!ok) {
                $scope.sendStatus = '';
                $timeout(function() {
                  $scope.$apply();
                });
                return;
              }
              publishAndSign(wallet, txp, onSendStatusChange);
            });
          } else publishAndSign(wallet, txp, onSendStatusChange);
        } else {
          popupService.showConfirm(null, message, okText, cancelText, function(ok) {
            if (!ok) {
              $scope.sendStatus = '';
              return;
            }
            publishAndSign(wallet, txp, onSendStatusChange);
          });
        }
      } else publishAndSign(wallet, txp, onSendStatusChange);
    });
  };

  function statusChangeHandler(processName, showName, isOn) {
    $log.debug('statusChangeHandler: ', processName, showName, isOn);
    if ((processName === 'broadcastingTx' || ((processName === 'signingTx') && $scope.wallet.m > 1)) && !isOn) {
      $scope.sendStatus = 'success';
      $scope.$digest();
    } else if (showName) {
      $scope.sendStatus = showName;
    }
  }

  $scope.statusChangeHandler = statusChangeHandler;

  $scope.onConfirm = function() {
    $scope.approve(statusChangeHandler);
  };

  $scope.onSuccessConfirm = function() {
    var previousView = $ionicHistory.viewHistory().backView && $ionicHistory.viewHistory().backView.stateName;
    var fromBitPayCard = previousView.match(/tabs.bitpayCard/) ? true : false;

    $ionicHistory.nextViewOptions({
      disableAnimate: true
    });
    $ionicHistory.removeBackView();
    $scope.sendStatus = '';

    if (fromBitPayCard) {
      $timeout(function() {
        $state.transitionTo('tabs.bitpayCard', {
          id: $stateParams.cardId
        });
      }, 100);
    } else {
      $state.go('tabs.send');
    }
  };

  function publishAndSign(wallet, txp, onSendStatusChange) {
    walletService.publishAndSign(wallet, txp, function(err, txp) {
      if (err) return setSendError(err);
    }, onSendStatusChange);
  }
});
<|endoftext|>


<commit_before>'use strict'

var _ = require('lodash')
var path = require('path')
var yosay = require('yosay')
var superb = require('superb')
var mkdirp = require('mkdirp')
var finepack = require('finepack')
var askName = require('inquirer-npm-name')
var generators = require('yeoman-generator')
var latestVersion = require('latest-version')

function setupDependenciesVersions (pkg) {
  function fetchVersions (dependencies) {
    return Promise.all(dependencies.map(function (dependency) {
      return latestVersion(dependency)
    }, []))
  }

  function updatePkg (namespace, versions) {
    Object.keys(pkg[namespace]).forEach(function (dep, index) {
      pkg[namespace][dep] = '~' + versions[index]
    })
  }

  var promise = Promise.all(['dependencies', 'devDependencies'].map(function (dep) {
    var pkgs = Object.keys(pkg[dep])
    return fetchVersions(pkgs).then(function (versions) {
      updatePkg(dep, versions)
    })
  }))

  return promise.then(function () {
    return Promise.resolve(pkg)
  })
}

var CONST = {
  TRANSPILERS: ['coffee-script'],
  STYLES: ['standard', 'jshint', 'jscs'],
  TESTING: ['mocha', 'should', 'tap', 'tape']
}

var proxy = process.env.http_proxy || process.env.HTTP_PROXY ||
  process.env.https_proxy || process.env.HTTPS_PROXY || null

var githubOptions = {
  version: '3.0.0'
}

if (proxy) {
  var proxyUrl = url.parse(proxy)
  githubOptions.proxy = {
    host: proxyUrl.hostname,
    port: proxyUrl.port
  }
}

var GitHubApi = require('github')
var github = new GitHubApi(githubOptions)

if (process.env.GITHUB_TOKEN) {
  github.authenticate({
    type: 'oauth',
    token: process.env.GITHUB_TOKEN
  })
}

function githubUserInfo (name, cb, log) {
  var emptyGithubRes = {
    name: '',
    email: '',
    html_url: ''
  }

  github.user.getFrom({
    user: name
  }, function (err, res) {
    if (err) {
      log.error("Cannot fetch your github profile. Make sure you've typed it correctly.")
      res = emptyGithubRes
    }

    return cb(JSON.parse(JSON.stringify(res)))
  })
}

function capitalizeName (name) {
  return _.reduce(name.split('-'), function (acc, str, index) {
    var separator = index === 0 ? '' : ' '
    return acc + separator + _.capitalize(str)
  }, '')
}

/**
 * Generate a new Project.
 * Currently settings that will be configured are:
 *
 * about project name
 *
 * - appName
 * - camelAppName
 * - appDescription
 *
 * about user info (Github)
 *
 * - userLogin
 * - userUrl
 * - userEmail
 * - userBlog
 * - userName
 *
 *  about style
 *
 * - coffee
 * - cli
 * - browser
 * - jshint
 * - jscs
 */
module.exports = generators.Base.extend({
  initializing: function () {
    this.licenseYear = new Date().getFullYear()
  },

  projectName: function () {
    this.log(yosay('Initializing ' + superb() + ' Project'))
    var cb = this.async()
    askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: function (str) {
        return str.length > 0
      }
    }, this, function (name) {
      this.appName = name
      this.camelAppName = _.camelCase(name)
      this.capitalizeName = capitalizeName(this.appName)
      cb()
    }.bind(this))
  },

  setupPath: function () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        'Your generator must be inside a folder named ' + this.appName + '\n' +
        "I'll automatically create this folder."
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  },

  questions: function () {
    var cb = this.async()

    this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }, {
      name: 'browser',
      message: 'Do you need a Browser Support (powered by Browserify) ?',
      type: 'confirm',
      default: false
    }], function (props) {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      this.browser = props.browser
      cb()
    }.bind(this))
  },

  userInfo: function () {
    var done = this.async()

    githubUserInfo(this.userLogin, function (res) {
      this.userName = res.name
      this.userEmail = res.email
      this.userBlog = res.blog
      this.userUrl = res.html_url
      done()
    }.bind(this), this.log)
  },

  transpilers: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS
    }], function (props) {
      _.forEach(CONST.TRANSPILERS, function (choice) {
        this[choice] = _.includes(props.transpilers, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  style: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'styles',
      message: 'Select the style:',
      choices: CONST.STYLES
    }], function (props) {
      _.forEach(CONST.STYLES, function (choice) {
        this[choice] = _.includes(props.styles, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  testing: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING,
    }], function (props) {
      _.forEach(CONST.TESTING, function (choice) {
        this[choice] = _.includes(props.testing, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  setup: function () {
    this.copy('_editorconfig', '.editorconfig')
    this.copy('_gitignore', '.gitignore')
    this.copy('_gitattributes', '.gitattributes')
    this.copy('_npmignore', '.npmignore')
    this.copy('_npmrc', '.npmrc')
    this.copy('_travis.yml', '.travis.yml')
    this.template('_LICENSE.md', 'LICENSE.md')

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      _.merge(this.package, this.fs.readJSON(this.templatePath('package/cli.json'), {}))
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.template('bin/help.txt', 'bin/_help.txt')
      this.copy('bin/index.js', 'bin/_index.js')
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    if (this.browser) {
      _.merge(this.package, this.fs.readJSON(this.templatePath('package/browser.json'), {}))

      this.readme += this.fs.read(this.templatePath('README/install/browser.md'))
      this.template('_bower.json', 'bower.json')
      this.bulkCopy('_gulpfile.coffee', 'gulpfile.coffee')
      this.mkdir('dist')
      this.template('dist/_index.html', 'dist/index.html')
      this.copy('bumped/browser', '.bumpedrc')
    } else {
      this.copy('bumped/base', '.bumpedrc')
    }

    /* STYLES */

    var lintScript = ''

    _.forEach(CONST.STYLES, function (style) {
      if (this[style]) {
        var script = style + ' lib'
        this.package.devDependencies[style] = 'latest'
        lintScript += lintScript === '' ? script : ' && ' + script
      }
    }.bind(this))

    if (this.jshint) this.copy('_jshintrc', '.jshintrc')
    if (this.jscs) this.copy('_jscsrc', '.jscsrc')

    /* SCRIPTS */

    this.package.scripts.lint = lintScript

    /* TRANSPILERS */

    _.forEach(CONST.TRANSPILERS, function (transpiler) {
      if (this[transpiler])
        this.package.dependencies[transpiler] = 'latest'
    }.bind(this))

    /* TESTING */

    _.forEach(CONST.TESTING, function (testing) {
      if (this[testing])
        this.package.devDependencies[testing] = 'latest'
    }.bind(this))

    var testScript = 'mocha'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test = testScript

    /* INDEX.JS */

    var indexExtension = 'js'

    if (!this['coffee-script'])
      this.package.devDependencies['coffee-script'] = 'latest'
    else
      indexExtension = 'coffee'

    this.copy('_index.' + indexExtension, 'index.js')

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  },

  dependenciesVersion: function () {
    var cb = this.async()
    var _this = this

    setupDependenciesVersions(this.package).then(function (newPkg) {
      console.log(newPkg)
      _this.package = newPkg
      cb()
    })
  },

  write: function () {
    var cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, function (err, packageFormated) {
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    }.bind(this))
  },

  install: function () {
    this.installDependencies({bower: false})
  }
})
<commit_msg>Remove console.log debug :P<commit_after>'use strict'

var _ = require('lodash')
var path = require('path')
var yosay = require('yosay')
var superb = require('superb')
var mkdirp = require('mkdirp')
var finepack = require('finepack')
var askName = require('inquirer-npm-name')
var generators = require('yeoman-generator')
var latestVersion = require('latest-version')

function setupDependenciesVersions (pkg) {
  function fetchVersions (dependencies) {
    return Promise.all(dependencies.map(function (dependency) {
      return latestVersion(dependency)
    }, []))
  }

  function updatePkg (namespace, versions) {
    Object.keys(pkg[namespace]).forEach(function (dep, index) {
      pkg[namespace][dep] = '~' + versions[index]
    })
  }

  var promise = Promise.all(['dependencies', 'devDependencies'].map(function (dep) {
    var pkgs = Object.keys(pkg[dep])
    return fetchVersions(pkgs).then(function (versions) {
      updatePkg(dep, versions)
    })
  }))

  return promise.then(function () {
    return Promise.resolve(pkg)
  })
}

var CONST = {
  TRANSPILERS: ['coffee-script'],
  STYLES: ['standard', 'jshint', 'jscs'],
  TESTING: ['mocha', 'should', 'tap', 'tape']
}

var proxy = process.env.http_proxy || process.env.HTTP_PROXY ||
  process.env.https_proxy || process.env.HTTPS_PROXY || null

var githubOptions = {
  version: '3.0.0'
}

if (proxy) {
  var proxyUrl = url.parse(proxy)
  githubOptions.proxy = {
    host: proxyUrl.hostname,
    port: proxyUrl.port
  }
}

var GitHubApi = require('github')
var github = new GitHubApi(githubOptions)

if (process.env.GITHUB_TOKEN) {
  github.authenticate({
    type: 'oauth',
    token: process.env.GITHUB_TOKEN
  })
}

function githubUserInfo (name, cb, log) {
  var emptyGithubRes = {
    name: '',
    email: '',
    html_url: ''
  }

  github.user.getFrom({
    user: name
  }, function (err, res) {
    if (err) {
      log.error("Cannot fetch your github profile. Make sure you've typed it correctly.")
      res = emptyGithubRes
    }

    return cb(JSON.parse(JSON.stringify(res)))
  })
}

function capitalizeName (name) {
  return _.reduce(name.split('-'), function (acc, str, index) {
    var separator = index === 0 ? '' : ' '
    return acc + separator + _.capitalize(str)
  }, '')
}

/**
 * Generate a new Project.
 * Currently settings that will be configured are:
 *
 * about project name
 *
 * - appName
 * - camelAppName
 * - appDescription
 *
 * about user info (Github)
 *
 * - userLogin
 * - userUrl
 * - userEmail
 * - userBlog
 * - userName
 *
 *  about style
 *
 * - coffee
 * - cli
 * - browser
 * - jshint
 * - jscs
 */
module.exports = generators.Base.extend({
  initializing: function () {
    this.licenseYear = new Date().getFullYear()
  },

  projectName: function () {
    this.log(yosay('Initializing ' + superb() + ' Project'))
    var cb = this.async()
    askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: function (str) {
        return str.length > 0
      }
    }, this, function (name) {
      this.appName = name
      this.camelAppName = _.camelCase(name)
      this.capitalizeName = capitalizeName(this.appName)
      cb()
    }.bind(this))
  },

  setupPath: function () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        'Your generator must be inside a folder named ' + this.appName + '\n' +
        "I'll automatically create this folder."
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  },

  questions: function () {
    var cb = this.async()

    this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }, {
      name: 'browser',
      message: 'Do you need a Browser Support (powered by Browserify) ?',
      type: 'confirm',
      default: false
    }], function (props) {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      this.browser = props.browser
      cb()
    }.bind(this))
  },

  userInfo: function () {
    var done = this.async()

    githubUserInfo(this.userLogin, function (res) {
      this.userName = res.name
      this.userEmail = res.email
      this.userBlog = res.blog
      this.userUrl = res.html_url
      done()
    }.bind(this), this.log)
  },

  transpilers: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS
    }], function (props) {
      _.forEach(CONST.TRANSPILERS, function (choice) {
        this[choice] = _.includes(props.transpilers, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  style: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'styles',
      message: 'Select the style:',
      choices: CONST.STYLES
    }], function (props) {
      _.forEach(CONST.STYLES, function (choice) {
        this[choice] = _.includes(props.styles, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  testing: function () {
    var cb = this.async()

    this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING,
    }], function (props) {
      _.forEach(CONST.TESTING, function (choice) {
        this[choice] = _.includes(props.testing, choice)
      }.bind(this))
      cb()
    }.bind(this))
  },

  setup: function () {
    this.copy('_editorconfig', '.editorconfig')
    this.copy('_gitignore', '.gitignore')
    this.copy('_gitattributes', '.gitattributes')
    this.copy('_npmignore', '.npmignore')
    this.copy('_npmrc', '.npmrc')
    this.copy('_travis.yml', '.travis.yml')
    this.template('_LICENSE.md', 'LICENSE.md')

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      _.merge(this.package, this.fs.readJSON(this.templatePath('package/cli.json'), {}))
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.template('bin/help.txt', 'bin/_help.txt')
      this.copy('bin/index.js', 'bin/_index.js')
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    if (this.browser) {
      _.merge(this.package, this.fs.readJSON(this.templatePath('package/browser.json'), {}))

      this.readme += this.fs.read(this.templatePath('README/install/browser.md'))
      this.template('_bower.json', 'bower.json')
      this.bulkCopy('_gulpfile.coffee', 'gulpfile.coffee')
      this.mkdir('dist')
      this.template('dist/_index.html', 'dist/index.html')
      this.copy('bumped/browser', '.bumpedrc')
    } else {
      this.copy('bumped/base', '.bumpedrc')
    }

    /* STYLES */

    var lintScript = ''

    _.forEach(CONST.STYLES, function (style) {
      if (this[style]) {
        var script = style + ' lib'
        this.package.devDependencies[style] = 'latest'
        lintScript += lintScript === '' ? script : ' && ' + script
      }
    }.bind(this))

    if (this.jshint) this.copy('_jshintrc', '.jshintrc')
    if (this.jscs) this.copy('_jscsrc', '.jscsrc')

    /* SCRIPTS */

    this.package.scripts.lint = lintScript

    /* TRANSPILERS */

    _.forEach(CONST.TRANSPILERS, function (transpiler) {
      if (this[transpiler])
        this.package.dependencies[transpiler] = 'latest'
    }.bind(this))

    /* TESTING */

    _.forEach(CONST.TESTING, function (testing) {
      if (this[testing])
        this.package.devDependencies[testing] = 'latest'
    }.bind(this))

    var testScript = 'mocha'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test = testScript

    /* INDEX.JS */

    var indexExtension = 'js'

    if (!this['coffee-script'])
      this.package.devDependencies['coffee-script'] = 'latest'
    else
      indexExtension = 'coffee'

    this.copy('_index.' + indexExtension, 'index.js')

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  },

  dependenciesVersion: function () {
    var cb = this.async()
    var _this = this

    setupDependenciesVersions(this.package).then(function (newPkg) {
      _this.package = newPkg
      cb()
    })
  },

  write: function () {
    var cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, function (err, packageFormated) {
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    }.bind(this))
  },

  install: function () {
    this.installDependencies({bower: false})
  }
})
<|endoftext|>


<commit_before>// All pages:
$(document).ready(function () {
  $('.main-header__bars').on('click', function () {
    $('.nav__list').toggle('slow');
  });
// Main page
// smooth scroll to first content block
  $('.pointerdown').on('click', function (event) {
    $('html, body').animate({
      scrollTop: $('.scrollhere').offset().top
    }, 800, function () {
    });
  });

// CTA buttons panel attached to footer
  $(window).scroll(function () {
    if ( $(window).scrollTop() + $(window).height() > $(document).height() - ( $('.subscribe').outerHeight() + $('footer').outerHeight() - 75 ) ) {
      $('.main-wrapper__button').css({'position': 'relative', 'z-index': 1});
      $('.buttons').css({'position': 'relative', 'z-index': 1});
    } else if ( $(window).scrollTop() + $(window).height() < $(document).height() - ( $('.subscribe').outerHeight() + $('footer').outerHeight() ) ) {
      $('.buttons').css({'bottom': 0, 'position': 'fixed', 'z-index': 9999});
      $('.main-wrapper__button').css({'bottom': 0, 'position': 'fixed'});
    }
    $('.buttons').show();
  });

// Top menu scrolling
  $(window).scroll(function () {
    if ($(window).scrollTop() == 0) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 1)');
    } else {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 0.6)');
    }
  });

// Changing top menu opacity
  $('.header__nav').on('mouseover', function(event) {
    if ( $(window).scrollTop() > 0 ) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 1)');
    }
  });
  $('.header__nav').on('mouseout', function(event) {
    if ( $(window).scrollTop() > 0 ) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 0.6)');
    }
  });

// Validate e-mail on subscribe module
  $('#mc-embedded-subscribe').on('click', function(event) {
    if ( !validateEmail( $('#mce-EMAIL').val() )  ) {
      if ( $('#mce-success-response').length ) $('#mce-success-response').hide();
      $('#mce-error-response').show();
      return false;
    } else {
      if ( $('#mce-error-response').length ) $('#mce-error-response').hide();
      $('#mce-success-response').show();
    }
  });

  function validateEmail(email) {
    var pattern = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    return pattern.test($.trim(email)) ? true : false;
  }

// Adding arrows on community page
  function showArrows() {
    if ( $(".current-projects").length && $(window).width() > 1023 ) {
      $(".arrows").show();
      $(".arrows").css("padding-top", "145px");
    } else if ( $(window).width() < 1024 ) {
      $(".arrows").css("padding-top", "120px");
      $(".arrows").show();
    } else if ( !$(".current-projects").length && $(window).width() >= 1023 ) {
      $(".arrows").hide();
    }
  }

// Compute dynamical height of paragraphs in histories-blocks
  function setHeightOfHistories(selector) {
    var entries = selector + " .item p";
    var arr = [];
    for ( var i = 0; i < $(entries).length; i++ ) {
      document.querySelectorAll(entries)[i].style.height = "initial";
      arr.push( document.querySelectorAll(entries)[i].offsetHeight );
    }
    $(entries).css({ 'height': Math.max(...arr) });
  }
  setHeightOfHistories(".card-vol");
  setHeightOfHistories(".card-init");
  setHeightOfHistories(".card-projects");

    $('.arrows').on('click', function (event) {
      setHeightOfHistories(".card-vol");
      setHeightOfHistories(".card-init");
      setHeightOfHistories(".card-projects");
  });

    $(window).on('resize', function (event) {
      setHeightOfHistories(".card-vol");
      setHeightOfHistories(".card-init");
      setHeightOfHistories(".card-projects");
      setPositionOfArrows();
      showArrows();
      if ( $(window).width() < 1023 ) {
        resetMobile(".card-vol");
        resetMobile(".card-init");
        resetMobile(".card-projects");
      } else {
        resetDesktop(".card-projects");
        resetDesktop(".card-vol");
        resetDesktop(".card-init");
      }
  });

  setPositionOfArrows();
  showArrows();

  if ( $(".card-projects").length && $(window).width() > 1023 && $(".card-projects").children().length > 5 ) {
    $(".card-projects").children().each(function(index, item) {
      if ( index > 3 && index !== $(".card-projects").children().length - 1 ) {
        $( this ).hide();
      }
    });
  } else if ( $(".card-projects").length && $(window).width() > 1023 && $(".card-projects").children().length <= 5 ) {
      $(".arrows").each(function() {
        if ( $(this).hasClass("nonblocked-arrow") ) {
          $( this ).removeClass("nonblocked-arrow");
          $( this ).addClass("blocked-arrow");
        }
      });
  }
});

// Functions for reset of carousel on mobile and desktop devices
function resetMobile(sel) {
  if ( !$(sel).length ) {
    return;
  }
  currents.curInit = currents.curVol = currents.curProj = 1;
  $(sel).children().each(function(index, item) {
    if ( index > 1 && index !== $(sel).children().length - 1 ) {
      $( this ).hide();
    } else if ( index === 1 ) {
      $( this ).show();
    } else if ( index === 0 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index === $(sel).children().length - 1 ) {
      $( this ).removeClass("blocked-arrow");
      $( this ).addClass("nonblocked-arrow");
    }
  });
 }

 function resetDesktop(sel) {
  if ( !$(sel).length ) {
    return;
  }
  currents.curInit = currents.curVol = currents.curProj = 1;
  $(sel).children().each(function(index, item) {
    if ( index === 0 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index > 4 && index === $(sel).children().length - 1 ) {
      $( this ).removeClass("blocked-arrow");
      $( this ).addClass("nonblocked-arrow");
    } else if ( index === 4 && index === $(sel).children().length - 1 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index > 0 && index < 4 ) {
      $(this).show();
    } else {
      $(this).hide();
    }
 });
}

// Compute alignment of arrows on mobile devices
function setPositionOfArrows() {
    if ( $(window).width() > 1023 ) return;
    var position = $(".card-img:visible:first").position();
    var left = position.left - 27;
    var right = position.left + $(".card-img:visible:first").width() + 9;
    var top = ( $(".card-img:visible:first").height() - 120 ) / 2.5;
    $(".arrows:eq(0), .arrows:eq(2)").css("left", left + "px");
    $(".arrows:eq(1), .arrows:eq(3)").css("left", right + "px");
    $(".arrows").css("top", top + "px");
}

// Carousel histories initiatives, volunteers and current projects
  var currents = {
    curInit: 1,
    curVol: 1,
    curProj: 1
  };
  $('.arrows i').on('click', function(ev) {
    var arr = ev.target.parentNode.parentNode.children;
    var cur, check, projects;
    if ( ~ev.target.parentNode.parentNode.className.indexOf("card-vol") ) {
      cur = currents.curVol;
      check = "vol";
    } else if ( ~ev.target.parentNode.parentNode.className.indexOf("card-init") ) {
      cur = currents.curInit;
      check = "init";
    } else if ( ~ev.target.parentNode.parentNode.className.indexOf("card-projects") ) {
      cur = currents.curProj;
      check = "proj";
    }

    if ( ~ev.target.parentNode.parentNode.className.indexOf("card-projects") && $(window).width() > 1023 ) {
      projects = true;
    } else projects = false;

    if ( ( ~ev.target.className.indexOf("fa-caret-left") && cur === 1 ) || ( ~ev.target.className.indexOf("fa-caret-right") && ( cur === arr.length - 2 || ( projects === true && cur === arr.length - 4 ) ) ) ) {
      return;
    } else if ( ~ev.target.className.indexOf("fa-caret-left") ) {
      arrows("item-nonactive", "item-nonactive", cur, "minus", projects);
    } else if ( ~ev.target.className.indexOf("fa-caret-right") ) {
      arrows("item-nonactive", "item-nonactive", cur, "plus", projects);
    }
     if ( cur === 1 ) {
      arrows("nonblocked-arrow", "blocked-arrow", 0);
      arrows("blocked-arrow", "nonblocked-arrow", arr.length - 1);
     } else if ( cur === arr.length - 2 || ( projects === true && cur === arr.length - 4 ) ) {
      arrows("nonblocked-arrow", "blocked-arrow", arr.length - 1);
      arrows("blocked-arrow", "nonblocked-arrow", 0);
     } else {
      arrows("blocked-arrow", "nonblocked-arrow", 0);
      arrows("blocked-arrow", "nonblocked-arrow", arr.length - 1);
     }

  function arrows(remove, add, num, sign, projects) {
    var show;
    if (!sign) {
      arr[num].classList.remove(remove);
      arr[num].classList.add(add);
      return;
    }
    if (sign) {
      if ( projects && sign === "plus" ) {
        arr[num].style.display = "none";
        show = cur + 3;
        cur += 1;
      } else if ( sign === "plus" ) {
        arr[num].style.display = "none";
        show = cur + 1;
        cur += 1;
      } else if ( projects && sign === "minus" ) {
        arr[num+2].style.display = "none";
        show = cur - 1;
        cur -= 1;
      } else if ( sign === "minus" ) {
        arr[num].style.display = "none";
        show = cur - 1;
        cur -= 1;
      }
      arr[show].style.display = "inherit";
    }
  }

  if (check === "vol") {
    currents.curVol = cur;
  } else if (check === "init") {
    currents.curInit = cur;
  } else if (check === "proj") {
    currents.curProj = cur;
  }
  });
<commit_msg>модальное окно "Апiсанне спосабу аплаты" перекрывает кнопки  "стань валанцёрам" и "запытай  дапамогу"<commit_after>// All pages:
$(document).ready(function () {
  $('.main-header__bars').on('click', function () {
    $('.nav__list').toggle('slow');
  });
// Main page
// smooth scroll to first content block
  $('.pointerdown').on('click', function (event) {
    $('html, body').animate({
      scrollTop: $('.scrollhere').offset().top
    }, 800, function () {
    });
  });

// CTA buttons panel attached to footer
  $(window).scroll(function () {
    if ( $(window).scrollTop() + $(window).height() > $(document).height() - ( $('.subscribe').outerHeight() + $('footer').outerHeight() - 75 ) ) {
      $('.main-wrapper__button').css({'position': 'relative', 'z-index': 1});
      $('.buttons').css({'position': 'relative', 'z-index': 1});
    } else if ( $(window).scrollTop() + $(window).height() < $(document).height() - ( $('.subscribe').outerHeight() + $('footer').outerHeight() ) ) {
      $('.buttons').css({'bottom': 0, 'position': 'fixed', 'z-index': 99});
      $('.main-wrapper__button').css({'bottom': 0, 'position': 'fixed'});
    }
    $('.buttons').show();
  });

// Top menu scrolling
  $(window).scroll(function () {
    if ($(window).scrollTop() == 0) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 1)');
    } else {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 0.6)');
    }
  });

// Changing top menu opacity
  $('.header__nav').on('mouseover', function(event) {
    if ( $(window).scrollTop() > 0 ) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 1)');
    }
  });
  $('.header__nav').on('mouseout', function(event) {
    if ( $(window).scrollTop() > 0 ) {
      $('.header__nav').css('background-color', 'rgba(128, 128, 128, 0.6)');
    }
  });

// Validate e-mail on subscribe module
  $('#mc-embedded-subscribe').on('click', function(event) {
    if ( !validateEmail( $('#mce-EMAIL').val() )  ) {
      if ( $('#mce-success-response').length ) $('#mce-success-response').hide();
      $('#mce-error-response').show();
      return false;
    } else {
      if ( $('#mce-error-response').length ) $('#mce-error-response').hide();
      $('#mce-success-response').show();
    }
  });

  function validateEmail(email) {
    var pattern = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    return pattern.test($.trim(email)) ? true : false;
  }

// Adding arrows on community page
  function showArrows() {
    if ( $(".current-projects").length && $(window).width() > 1023 ) {
      $(".arrows").show();
      $(".arrows").css("padding-top", "145px");
    } else if ( $(window).width() < 1024 ) {
      $(".arrows").css("padding-top", "120px");
      $(".arrows").show();
    } else if ( !$(".current-projects").length && $(window).width() >= 1023 ) {
      $(".arrows").hide();
    }
  }

// Compute dynamical height of paragraphs in histories-blocks
  function setHeightOfHistories(selector) {
    var entries = selector + " .item p";
    var arr = [];
    for ( var i = 0; i < $(entries).length; i++ ) {
      document.querySelectorAll(entries)[i].style.height = "initial";
      arr.push( document.querySelectorAll(entries)[i].offsetHeight );
    }
    $(entries).css({ 'height': Math.max(...arr) });
  }
  setHeightOfHistories(".card-vol");
  setHeightOfHistories(".card-init");
  setHeightOfHistories(".card-projects");

    $('.arrows').on('click', function (event) {
      setHeightOfHistories(".card-vol");
      setHeightOfHistories(".card-init");
      setHeightOfHistories(".card-projects");
  });

    $(window).on('resize', function (event) {
      setHeightOfHistories(".card-vol");
      setHeightOfHistories(".card-init");
      setHeightOfHistories(".card-projects");
      setPositionOfArrows();
      showArrows();
      if ( $(window).width() < 1023 ) {
        resetMobile(".card-vol");
        resetMobile(".card-init");
        resetMobile(".card-projects");
      } else {
        resetDesktop(".card-projects");
        resetDesktop(".card-vol");
        resetDesktop(".card-init");
      }
  });

  setPositionOfArrows();
  showArrows();

  if ( $(".card-projects").length && $(window).width() > 1023 && $(".card-projects").children().length > 5 ) {
    $(".card-projects").children().each(function(index, item) {
      if ( index > 3 && index !== $(".card-projects").children().length - 1 ) {
        $( this ).hide();
      }
    });
  } else if ( $(".card-projects").length && $(window).width() > 1023 && $(".card-projects").children().length <= 5 ) {
      $(".arrows").each(function() {
        if ( $(this).hasClass("nonblocked-arrow") ) {
          $( this ).removeClass("nonblocked-arrow");
          $( this ).addClass("blocked-arrow");
        }
      });
  }
});

// Functions for reset of carousel on mobile and desktop devices
function resetMobile(sel) {
  if ( !$(sel).length ) {
    return;
  }
  currents.curInit = currents.curVol = currents.curProj = 1;
  $(sel).children().each(function(index, item) {
    if ( index > 1 && index !== $(sel).children().length - 1 ) {
      $( this ).hide();
    } else if ( index === 1 ) {
      $( this ).show();
    } else if ( index === 0 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index === $(sel).children().length - 1 ) {
      $( this ).removeClass("blocked-arrow");
      $( this ).addClass("nonblocked-arrow");
    }
  });
 }

 function resetDesktop(sel) {
  if ( !$(sel).length ) {
    return;
  }
  currents.curInit = currents.curVol = currents.curProj = 1;
  $(sel).children().each(function(index, item) {
    if ( index === 0 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index > 4 && index === $(sel).children().length - 1 ) {
      $( this ).removeClass("blocked-arrow");
      $( this ).addClass("nonblocked-arrow");
    } else if ( index === 4 && index === $(sel).children().length - 1 ) {
      $( this ).removeClass("nonblocked-arrow");
      $( this ).addClass("blocked-arrow");
    } else if ( index > 0 && index < 4 ) {
      $(this).show();
    } else {
      $(this).hide();
    }
 });
}

// Compute alignment of arrows on mobile devices
function setPositionOfArrows() {
    if ( $(window).width() > 1023 ) return;
    var position = $(".card-img:visible:first").position();
    var left = position.left - 27;
    var right = position.left + $(".card-img:visible:first").width() + 9;
    var top = ( $(".card-img:visible:first").height() - 120 ) / 2.5;
    $(".arrows:eq(0), .arrows:eq(2)").css("left", left + "px");
    $(".arrows:eq(1), .arrows:eq(3)").css("left", right + "px");
    $(".arrows").css("top", top + "px");
}

// Carousel histories initiatives, volunteers and current projects
  var currents = {
    curInit: 1,
    curVol: 1,
    curProj: 1
  };
  $('.arrows i').on('click', function(ev) {
    var arr = ev.target.parentNode.parentNode.children;
    var cur, check, projects;
    if ( ~ev.target.parentNode.parentNode.className.indexOf("card-vol") ) {
      cur = currents.curVol;
      check = "vol";
    } else if ( ~ev.target.parentNode.parentNode.className.indexOf("card-init") ) {
      cur = currents.curInit;
      check = "init";
    } else if ( ~ev.target.parentNode.parentNode.className.indexOf("card-projects") ) {
      cur = currents.curProj;
      check = "proj";
    }

    if ( ~ev.target.parentNode.parentNode.className.indexOf("card-projects") && $(window).width() > 1023 ) {
      projects = true;
    } else projects = false;

    if ( ( ~ev.target.className.indexOf("fa-caret-left") && cur === 1 ) || ( ~ev.target.className.indexOf("fa-caret-right") && ( cur === arr.length - 2 || ( projects === true && cur === arr.length - 4 ) ) ) ) {
      return;
    } else if ( ~ev.target.className.indexOf("fa-caret-left") ) {
      arrows("item-nonactive", "item-nonactive", cur, "minus", projects);
    } else if ( ~ev.target.className.indexOf("fa-caret-right") ) {
      arrows("item-nonactive", "item-nonactive", cur, "plus", projects);
    }
     if ( cur === 1 ) {
      arrows("nonblocked-arrow", "blocked-arrow", 0);
      arrows("blocked-arrow", "nonblocked-arrow", arr.length - 1);
     } else if ( cur === arr.length - 2 || ( projects === true && cur === arr.length - 4 ) ) {
      arrows("nonblocked-arrow", "blocked-arrow", arr.length - 1);
      arrows("blocked-arrow", "nonblocked-arrow", 0);
     } else {
      arrows("blocked-arrow", "nonblocked-arrow", 0);
      arrows("blocked-arrow", "nonblocked-arrow", arr.length - 1);
     }

  function arrows(remove, add, num, sign, projects) {
    var show;
    if (!sign) {
      arr[num].classList.remove(remove);
      arr[num].classList.add(add);
      return;
    }
    if (sign) {
      if ( projects && sign === "plus" ) {
        arr[num].style.display = "none";
        show = cur + 3;
        cur += 1;
      } else if ( sign === "plus" ) {
        arr[num].style.display = "none";
        show = cur + 1;
        cur += 1;
      } else if ( projects && sign === "minus" ) {
        arr[num+2].style.display = "none";
        show = cur - 1;
        cur -= 1;
      } else if ( sign === "minus" ) {
        arr[num].style.display = "none";
        show = cur - 1;
        cur -= 1;
      }
      arr[show].style.display = "inherit";
    }
  }

  if (check === "vol") {
    currents.curVol = cur;
  } else if (check === "init") {
    currents.curInit = cur;
  } else if (check === "proj") {
    currents.curProj = cur;
  }
  });
<|endoftext|>


<commit_before>(function () {

    'use strict';

    var util = require('util'),
        path = require('path'),
        slug = require('slug'),
        fs = require('fs'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    var ScaffoldGenerator = module.exports = function ScaffoldGenerator(args, options, config) {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            this.installDependencies({
                skipInstall: options['skip-install']
            });
        });

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

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

    ScaffoldGenerator.prototype.init = function init () {
        var cb = this.async();

        this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
        this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
        this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
        this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_|'));
        this.log(chalk.cyan('\n'));

        this.log(chalk.cyan('\t \t [ Welcome to Scaffold Generator ] \n \n'));
        this.log(chalk.green('I will guide you to generate your best workflow. Come with me... \n \n'));

        cb();
    };

    ScaffoldGenerator.prototype.askFor = function askFor () {
        var cb = this.async(),
            prompts = [{
                name: 'projectName',
                message: 'What is the name of your project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide a name for your project');

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectDescription',
                message: 'What is the description?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide a description');

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectMember',
                message: 'Which members involved in the project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide which members');

                        return;
                    }

                    done(true);
                }
            }, {
                type: 'list',
                name: 'projectType',
                message: 'What kind of project?',
                choices: ['Web Only', 'Mobile Only', 'Responsive', 'Wordpress'],
                default: 0
            }, {
                type: 'confirm',
                name: 'hasMinify',
                message: 'Would you like to minify files at build?'
            }];

        this.prompt(prompts, function (props) {
            for(var item in props) {
                this[item] = props[item];
            }

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

    ScaffoldGenerator.prototype.getScaffoldCore = function getScaffoldCore () {
        var cb = this.async();

        this.log(chalk.green('\n \n Downloading core of scaffold'));
        this.tarball('https://github.com/marcosmoura/scaffold/archive/v2.zip', '.', cb);
    };

    ScaffoldGenerator.prototype.processPackage = function processPackage () {
        var cb = this.async(),
            pkgPath = path.join(this.env.cwd, 'package.json'),
            pkg = JSON.parse(this.readFileAsString(pkgPath));

        pkg.projectName = this.projectName;
        pkg.name = slug(this.projectName).toLowerCase();
        pkg.description = this.projectDescription;
        pkg.developers = this.projectMember;

        var dev = this.projectMember.split(','),
            devList = [];

        for(var member in dev) {
            devList.push({
                'name': dev[member].trim()
            });
        }

        pkg.author = devList;

        fs.unlink(pkgPath);

        this.write(pkgPath, JSON.stringify(pkg, null, 2));

        cb();
    };

    ScaffoldGenerator.prototype.processGruntFile = function processGruntFile () {
        var cb = this.async(),
            tasksPath = path.join(this.env.cwd, 'grunt/options'),
            tasks = {
                assemble: 'assemble.js',
                clean: 'clean.js',
                cmq: 'cmq.js',
                compress: 'compress.js',
                concat: 'concat.js',
                connect: 'connect.js',
                copy: 'copy.js',
                cssmin: 'cssmin.js',
                csso: 'csso.js',
                hash: 'hash.js',
                htmlCompressor: 'htmlCompressor.js',
                htmlhint: 'htmlhint.js',
                htmlmin: 'htmlmin.js',
                imageEmbed: 'imageEmbed.js',
                imagemin: 'imagemin.js',
                jshint: 'jshint.js',
                less: 'less.js',
                modernizr: 'modernizr.js',
                replace: 'replace.js',
                svgmin: 'svgmin.js',
                uglify: 'uglify.js',
                usemin: 'usemin.js',
                useminPrepare: 'useminPrepare.js',
                watch: 'watch.js'
            };

        if (this.projectType == 'Mobile Only') {
            this.log(chalk.green('\n \n Downloading mobile version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        } else if (this.projectType == 'Web Only') {
            this.log(chalk.green('\n \n Downloading web version'));
            this.tarball('https://github.com/marcosmoura/scaffold-web/archive/master.zip', 'dev/', cb);
        } else if (this.projectType == 'Responsive') {
            this.log(chalk.green('\n \n Downloading responsive version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        }
    };

    ScaffoldGenerator.prototype.garbageRemoval = function garbageRemoval () {
        var cb = this.async(),
            devPath = path.join(this.env.cwd, 'dev');

        fs.unlink(path.join(devPath, 'LICENSE'));
        fs.unlink(path.join(devPath, 'README.md'));
    };

})();
<commit_msg>Change header<commit_after>(function () {

    'use strict';

    var util = require('util'),
        path = require('path'),
        slug = require('slug'),
        fs = require('fs'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    var ScaffoldGenerator = module.exports = function ScaffoldGenerator(args, options, config) {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            this.installDependencies({
                skipInstall: options['skip-install']
            });
        });

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

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

    ScaffoldGenerator.prototype.init = function init () {
        var cb = this.async();

        this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
        this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
        this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
        this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_|'));

        this.log('\n');

        this.log(chalk.cyan('\t \t [ Welcome to Scaffold Generator ] \n \n'));
        this.log(chalk.green('I will guide you to generate your best workflow. Come with me... \n \n'));

        cb();
    };

    ScaffoldGenerator.prototype.askFor = function askFor () {
        var cb = this.async(),
            prompts = [{
                name: 'projectName',
                message: 'What is the name of your project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide a name for your project');

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectDescription',
                message: 'What is the description?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide a description');

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectMember',
                message: 'Which members involved in the project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        done('You need to provide which members');

                        return;
                    }

                    done(true);
                }
            }, {
                type: 'list',
                name: 'projectType',
                message: 'What kind of project?',
                choices: ['Web Only', 'Mobile Only', 'Responsive', 'Wordpress'],
                default: 0
            }, {
                type: 'confirm',
                name: 'hasMinify',
                message: 'Would you like to minify files at build?'
            }];

        this.prompt(prompts, function (props) {
            for(var item in props) {
                this[item] = props[item];
            }

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

    ScaffoldGenerator.prototype.getScaffoldCore = function getScaffoldCore () {
        var cb = this.async();

        this.log(chalk.green('\n \n Downloading core of scaffold'));
        this.tarball('https://github.com/marcosmoura/scaffold/archive/v2.zip', '.', cb);
    };

    ScaffoldGenerator.prototype.processPackage = function processPackage () {
        var cb = this.async(),
            pkgPath = path.join(this.env.cwd, 'package.json'),
            pkg = JSON.parse(this.readFileAsString(pkgPath));

        pkg.projectName = this.projectName;
        pkg.name = slug(this.projectName).toLowerCase();
        pkg.description = this.projectDescription;
        pkg.developers = this.projectMember;

        var dev = this.projectMember.split(','),
            devList = [];

        for(var member in dev) {
            devList.push({
                'name': dev[member].trim()
            });
        }

        pkg.author = devList;

        fs.unlink(pkgPath);

        this.write(pkgPath, JSON.stringify(pkg, null, 2));

        cb();
    };

    ScaffoldGenerator.prototype.processGruntFile = function processGruntFile () {
        var cb = this.async(),
            tasksPath = path.join(this.env.cwd, 'grunt/options'),
            tasks = {
                assemble: 'assemble.js',
                clean: 'clean.js',
                cmq: 'cmq.js',
                compress: 'compress.js',
                concat: 'concat.js',
                connect: 'connect.js',
                copy: 'copy.js',
                cssmin: 'cssmin.js',
                csso: 'csso.js',
                hash: 'hash.js',
                htmlCompressor: 'htmlCompressor.js',
                htmlhint: 'htmlhint.js',
                htmlmin: 'htmlmin.js',
                imageEmbed: 'imageEmbed.js',
                imagemin: 'imagemin.js',
                jshint: 'jshint.js',
                less: 'less.js',
                modernizr: 'modernizr.js',
                replace: 'replace.js',
                svgmin: 'svgmin.js',
                uglify: 'uglify.js',
                usemin: 'usemin.js',
                useminPrepare: 'useminPrepare.js',
                watch: 'watch.js'
            };

        if (this.projectType == 'Mobile Only') {
            this.log(chalk.green('\n \n Downloading mobile version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        } else if (this.projectType == 'Web Only') {
            this.log(chalk.green('\n \n Downloading web version'));
            this.tarball('https://github.com/marcosmoura/scaffold-web/archive/master.zip', 'dev/', cb);
        } else if (this.projectType == 'Responsive') {
            this.log(chalk.green('\n \n Downloading responsive version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        }
    };

    ScaffoldGenerator.prototype.garbageRemoval = function garbageRemoval () {
        var cb = this.async(),
            devPath = path.join(this.env.cwd, 'dev');

        fs.unlink(path.join(devPath, 'LICENSE'));
        fs.unlink(path.join(devPath, 'README.md'));
    };

})();
<|endoftext|>


<commit_before>/* simpParallax - Arthur Camara -  https://github.com/arthurcamara1/simpParallax */

(function ($) {

    $.fn.simpParallax = function(options) {

    	var defaults = {
    		factor: 0.2,
    		parallaxtype: 'top'
    	};

    	var settings = $.extend( defaults, options );
    	var scrolledY = $(window).scrollTop();

    	if(settings.parallaxtype === "background") {
    		this.css("background-position","center -"+((scrolledY*settings.factor))+"px");
    	} else {
    		this.css(settings.scrollType,"-"+((scrolledY*settings.factor))+"px");
    	}
        return this;
    };

    $.simpParallax = function() {

        $(window).bind("scroll",function(e){

            $("[data-parallax='true']").each(function() {
                //set options according to data attributes
                var options = {};
                var attrs = ["factor", "parallaxtype"];
                for(var i=0, size=attrs.length; i<size; i++) {
                    var attribute = attrs[i];
                    if($(this).attr("data-"+attribute)) {
                        options[attribute] = $(this).data(attribute);
                    }
                }
                $(this).simpParallax(options);
            });

        });

    }

}(jQuery));<commit_msg>Fixes the parallax effect<commit_after>/* simpParallax - Arthur Camara -  https://github.com/arthurcamara1/simpParallax

-----------------------------------------
Usage:

OR

-----------------------------------------
*/

(function ($) {

    $.fn.simpParallax = function(options) {

        var defaults = {
            factor: 0.5,
            parallaxtype: 'top'
        };

        var settings = $.extend( defaults, options );
        var scrolledY = $(window).scrollTop();

        if(settings.parallaxtype === "background") {
            this.css("background-position","center -"+((scrolledY*settings.factor))+"px");
        } else {

            var top;
            if ($.isNumeric(this.attr('data-initialpos'))) {
                top = this.attr('data-initialpos');
            } else {
                top = parseInt(this.css('top'),10);
                this.attr('data-initialpos', top);
            }

            var position = (top-(scrolledY*settings.factor));

            this.css(settings.parallaxtype,position+"px");
        }
        return this;
    };

    $.simpParallax = function() {

        $("[data-parallax='true']").each(function() {
            if (!$(this).attr('data-parallaxtype')) {
                $(this).attr('data-parallaxtype', 'top');
            }
            if (!$(this).attr('data-factor')) {
                $(this).attr('data-factor', 0.5);
            }
        });

        $(window).bind("scroll",function(e){

            $("[data-parallax='true']").each(function() {
                //set options according to data attributes
                var options = {};
                var attrs = ["factor", "parallaxtype"];
                for(var i=0, size=attrs.length; i<size; i++) {
                    var attribute = attrs[i];
                    if($(this).attr("data-"+attribute)) {
                        options[attribute] = $(this).attr("data-"+attribute)
                    }
                }
                $(this).simpParallax(options);
            });

        });

    }

}(jQuery));<|endoftext|>


<commit_before>var generators = require('yeoman-generator');

var projectTypes = [{
  name: 'Basic JS App',
  value: 'basic'
}, {
  name: 'ES6 App (using Babel transpiler)',
  short: 'ES6 App',
  value: 'es6'
}, {
  name: 'TypeScript App',
  value: 'ts'
}];

var props;

module.exports = generators.Base.extend({
  prompting: function() {
    var done = this.async();
    this.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Your project name',
        default: this.appname, // defaults to current working dir
        filter: toId
      }, {
        type: 'input',
        name: 'version',
        message: 'Initial version',
        default: '0.1.0'
      }, {
        type: 'list',
        name: 'proj_type',
        message: 'Type of project',
        choices: projectTypes
      }, {
        type: 'confirm',
        name: 'prep_build',
        message: 'Prepare app build',
        default: true
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_id',
        message: 'App ID',
        default: answers => answers.name
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_name',
        message: 'App name',
        default: answers => toName(answers.name)
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_description',
        message: 'App description',
        default: 'Example Tabris.js App'
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'author_name',
        message: 'Author',
        default: this.user.git.name
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'author_email',
        message: 'Email',
        default: this.user.git.email
      }
    ], (answers) => {
      props = answers;
      props.build = answers.proj_type !== 'basic';
      props.main = answers.build ? 'dist/app.js' : 'src/app.js';
      done();
    });
  },

  writing: function() {
    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'),
      props
    );
    if (props.prep_build) {
      this.fs.copyTpl(
        this.templatePath('cordova'),
        this.destinationPath('cordova'),
        props
      );
    }
    if (props.proj_type === 'es6') {
      this.fs.copyTpl(
        this.templatePath('es6/_babelrc'),
        this.destinationPath('.babelrc')
      );
      this.fs.copyTpl(
        this.templatePath('es6/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('es6/src'),
        this.destinationPath('src'),
        props
      );
    } else if (props.proj_type === 'ts') {
      this.fs.copyTpl(
        this.templatePath('ts/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('ts/src'),
        this.destinationPath('src'),
        props
      );
      this.fs.copyTpl(
        this.templatePath('ts/tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
    } else {
      this.fs.copyTpl(
        this.templatePath('basic/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('basic/src'),
        this.destinationPath('src'),
        props
      );
    }
  },

  install: function() {
    this.npmInstall(['tabris'], {
      save: true
    });
    if (props.proj_type === 'es6') {
      this.npmInstall([
        'babel-cli',
        'babel-plugin-transform-es2015-arrow-functions',
        'babel-plugin-transform-es2015-block-scoping',
        'babel-plugin-transform-es2015-classes',
        'babel-plugin-transform-es2015-modules-commonjs',
        'babel-plugin-transform-es2015-computed-properties',
        'babel-plugin-transform-es2015-destructuring',
        'babel-plugin-transform-es2015-parameters',
        'babel-plugin-transform-es2015-shorthand-properties',
        'babel-plugin-transform-es2015-spread',
        'babel-plugin-transform-es2015-template-literals'
      ], {
        saveDev: true
      });
    } else if (props.proj_type === 'ts') {
      this.npmInstall(['typescript'], {
        saveDev: true
      });
    }
  }

});

function toId(string) {
  return string.replace(/\s+/g, '-').toLowerCase();
}

function toName(str) {
  return str.split(/[-_\s]+/)
    .filter(str => !!str)
    .map(word => word.charAt(0).toUpperCase() + word.substr(1))
    .join(' ');
}
<commit_msg>Set installed tabris version to 1.x<commit_after>var generators = require('yeoman-generator');

var projectTypes = [{
  name: 'Basic JS App',
  value: 'basic'
}, {
  name: 'ES6 App (using Babel transpiler)',
  short: 'ES6 App',
  value: 'es6'
}, {
  name: 'TypeScript App',
  value: 'ts'
}];

var props;

module.exports = generators.Base.extend({
  prompting: function() {
    var done = this.async();
    this.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Your project name',
        default: this.appname, // defaults to current working dir
        filter: toId
      }, {
        type: 'input',
        name: 'version',
        message: 'Initial version',
        default: '0.1.0'
      }, {
        type: 'list',
        name: 'proj_type',
        message: 'Type of project',
        choices: projectTypes
      }, {
        type: 'confirm',
        name: 'prep_build',
        message: 'Prepare app build',
        default: true
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_id',
        message: 'App ID',
        default: answers => answers.name
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_name',
        message: 'App name',
        default: answers => toName(answers.name)
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'app_description',
        message: 'App description',
        default: 'Example Tabris.js App'
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'author_name',
        message: 'Author',
        default: this.user.git.name
      }, {
        when: answers => answers.prep_build,
        type: 'input',
        name: 'author_email',
        message: 'Email',
        default: this.user.git.email
      }
    ], (answers) => {
      props = answers;
      props.build = answers.proj_type !== 'basic';
      props.main = answers.build ? 'dist/app.js' : 'src/app.js';
      done();
    });
  },

  writing: function() {
    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'),
      props
    );
    if (props.prep_build) {
      this.fs.copyTpl(
        this.templatePath('cordova'),
        this.destinationPath('cordova'),
        props
      );
    }
    if (props.proj_type === 'es6') {
      this.fs.copyTpl(
        this.templatePath('es6/_babelrc'),
        this.destinationPath('.babelrc')
      );
      this.fs.copyTpl(
        this.templatePath('es6/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('es6/src'),
        this.destinationPath('src'),
        props
      );
    } else if (props.proj_type === 'ts') {
      this.fs.copyTpl(
        this.templatePath('ts/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('ts/src'),
        this.destinationPath('src'),
        props
      );
      this.fs.copyTpl(
        this.templatePath('ts/tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
    } else {
      this.fs.copyTpl(
        this.templatePath('basic/_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('basic/src'),
        this.destinationPath('src'),
        props
      );
    }
  },

  install: function() {
    this.npmInstall(['tabris@^1.0.0'], {
      save: true
    });
    if (props.proj_type === 'es6') {
      this.npmInstall([
        'babel-cli',
        'babel-plugin-transform-es2015-arrow-functions',
        'babel-plugin-transform-es2015-block-scoping',
        'babel-plugin-transform-es2015-classes',
        'babel-plugin-transform-es2015-modules-commonjs',
        'babel-plugin-transform-es2015-computed-properties',
        'babel-plugin-transform-es2015-destructuring',
        'babel-plugin-transform-es2015-parameters',
        'babel-plugin-transform-es2015-shorthand-properties',
        'babel-plugin-transform-es2015-spread',
        'babel-plugin-transform-es2015-template-literals'
      ], {
        saveDev: true
      });
    } else if (props.proj_type === 'ts') {
      this.npmInstall(['typescript'], {
        saveDev: true
      });
    }
  }

});

function toId(string) {
  return string.replace(/\s+/g, '-').toLowerCase();
}

function toName(str) {
  return str.split(/[-_\s]+/)
    .filter(str => !!str)
    .map(word => word.charAt(0).toUpperCase() + word.substr(1))
    .join(' ');
}
<|endoftext|>