<commit_before>var fs = require('fs');
var prompt = require('prompt');
var template = require('lodash.template');
var merge = require('lodash.merge');
var rmraf = require('rimraf');
var exec = require('child_process').exec;

var argv = process.argv;

var defaults = {
  version: '0.0.1',
  yourName: 'Fractal',
  yourEmail: 'contact@wearefractal.com',
  yourDomain: 'http://wearefractal.com',
  gitUserName: 'wearefractal'
};

var questions = {
  properties: {
    projectName: {
      pattern: /^[a-zA-Z\-]+$/,
      message: 'name must not contain spaces',
      required: true
    },
    description: {},
    version: {
      default: defaults.version
    },
    yourName: {
      required: true,
      default: defaults.yourName
    },
    yourEmail: {
      required: true,
      default: defaults.yourEmail
    },
    yourDomain: {
      required: true,
      default: defaults.yourDomain
    },
    gitUserName: {
      required: true,
      default: defaults.gitUserName
    }
  }
};

prompt.start();

if (argv[2] == '--use-defaults') {
  console.log('Using defaults \n');

  var defaultQuestions = {
    properties: {
      projectName: {
        pattern: /^[a-zA-Z\-]+$/,
        message: 'name must not contain spaces',
        required: true
      },
      description: {},
    }
  };

  return prompt.get(defaultQuestions, function(err, data) {
    data.gitUrl = getGitUrl(data);
    data = merge(data, defaults);
    save(data);
  });
}

prompt.get(questions, function(err, data) {
  data.gitUrl = getGitUrl(data);
  save(data);
});

function save(data) {
  if (data === null || data === undefined) {
    return console.log('\n Error: inputs are undefined');
  }
  data.year = new Date().getFullYear();
  var files = [
    './package.json.bk',
    './README.md.bk',
    './LICENSE.bk',
    './test/index.js.bk'
  ];

  files.forEach(function(v, k, a) {
    templateFile(v, data);
  });

  cleanSetup(function(err) {
    if (err) return console.error(err);
    gitInit(data);
  });
}

function getGitUrl(data) {
  return 'https://github.com/' + data.gitUserName + '/' + data.projectName;
}

function templateFile(oldName, data) {
  var newName = oldName.replace('.bk', '');
  fs.writeFileSync(newName, template(fs.readFileSync(oldName), data)());
  fs.unlinkSync(oldName);
}

function cleanSetup(cb) {
  rmraf('node_modules', function (err) {
    if (err) return cb(err);

    rmraf('.git', function(err) {
      if (err) return cb(err);
      fs.unlink('./setup.js', function(err) {
        if (err) return cb(err);
        cb();
      });
    });
  });
}

function gitInit(data) {
  var cmd = 'git init';
  cmd += ' && git remote add origin ' + data.gitUrl;
  cmd += ' && git add . -A';
  cmd += ' && git commit -m \'init\'';
  cmd += ' && git push origin master';
  cmd += ' && git branch --set-upstream-to=origin/master master';
  exec(cmd, function(err) {
    if (err) return console.log(err);
    console.log('\n Completed successfully');
  });
}
<commit_msg>template fix<commit_after>var fs = require('fs');
var prompt = require('prompt');
var template = require('lodash.template');
var merge = require('lodash.merge');
var rmraf = require('rimraf');
var exec = require('child_process').exec;

var argv = process.argv;

var defaults = {
  version: '0.0.1',
  yourName: 'Fractal',
  yourEmail: 'contact@wearefractal.com',
  yourDomain: 'http://wearefractal.com',
  gitUserName: 'wearefractal'
};

var questions = {
  properties: {
    projectName: {
      pattern: /^[a-zA-Z\-]+$/,
      message: 'name must not contain spaces',
      required: true
    },
    description: {},
    version: {
      default: defaults.version
    },
    yourName: {
      required: true,
      default: defaults.yourName
    },
    yourEmail: {
      required: true,
      default: defaults.yourEmail
    },
    yourDomain: {
      required: true,
      default: defaults.yourDomain
    },
    gitUserName: {
      required: true,
      default: defaults.gitUserName
    }
  }
};

prompt.start();

if (argv[2] == '--use-defaults') {
  console.log('Using defaults \n');

  var defaultQuestions = {
    properties: {
      projectName: {
        pattern: /^[a-zA-Z\-]+$/,
        message: 'name must not contain spaces',
        required: true
      },
      description: {},
    }
  };

  return prompt.get(defaultQuestions, function(err, data) {
    data.gitUrl = getGitUrl(data);
    data = merge(data, defaults);
    save(data);
  });
}

prompt.get(questions, function(err, data) {
  data.gitUrl = getGitUrl(data);
  save(data);
});

function save(data) {
  if (data === null || data === undefined) {
    return console.log('\n Error: inputs are undefined');
  }
  data.year = new Date().getFullYear();
  var files = [
    './package.json.bk',
    './README.md.bk',
    './LICENSE.bk',
    './test/index.js.bk'
  ];

  files.forEach(function(v, k, a) {
    templateFile(v, data);
  });

  cleanSetup(function(err) {
    if (err) return console.error(err);
    gitInit(data);
  });
}

function getGitUrl(data) {
  return 'https://github.com/' + data.gitUserName + '/' + data.projectName;
}

function templateFile(oldName, data) {
  var newName = oldName.replace('.bk', '');
  fs.writeFileSync(newName, template(fs.readFileSync(oldName))(data));
  fs.unlinkSync(oldName);
}

function cleanSetup(cb) {
  rmraf('node_modules', function (err) {
    if (err) return cb(err);

    rmraf('.git', function(err) {
      if (err) return cb(err);
      fs.unlink('./setup.js', function(err) {
        if (err) return cb(err);
        cb();
      });
    });
  });
}

function gitInit(data) {
  var cmd = 'git init';
  cmd += ' && git remote add origin ' + data.gitUrl;
  cmd += ' && git add . -A';
  cmd += ' && git commit -m \'init\'';
  cmd += ' && git push origin master';
  cmd += ' && git branch --set-upstream-to=origin/master master';
  exec(cmd, function(err) {
    if (err) return console.log(err);
    console.log('\n Completed successfully');
  });
}
<|endoftext|>


<commit_before>var dutils = require('./deck.js');

var Deck = dutils.Deck;
var dealerAction = dutils.dealerAction;
var totalValue = dutils.totalValue;
var allPossibleValues = dutils.allPossibleValues;
var bestOfValues = dutils.bestOfValues;

function CurrentGame(type, bet, payout, gd) {
  this.type = type;
  this.bet = bet;
  this.scoredata = {};
  this.person = payout;
  this.gd = gd;
  this.finished = false;
}

CurrentGame.prototype.start = function(cb) {
  if (this.type == "blackjack") {
    this.scoredata.deck = new Deck();
    this.scoredata.dealer_hand = [this.scoredata.deck.top(), this.scoredata.deck.top()];
    this.scoredata.player_hand = [this.scoredata.deck.top(), this.scoredata.deck.top()];
    if (bestOfValues(allPossibleValues(this.scoredata.player_hand)) == 21) {
      this.finish(cb);
      return;
    }
    cb("Dealer Hand: " + this.scoredata.dealer_hand[0] + ",??\nYour Hand: " + this.scoredata.player_hand.join(","));
  }
  return this.scoredata;
};

CurrentGame.prototype.run = function(params, cb) {
  if (this.finished === true) {
    return;
  }
  if (this.type == "blackjack") {
    if (params[0] == "hit") {
      this.scoredata.player_hand.push(this.scoredata.deck.top());
      let pbest = bestOfValues(allPossibleValues(this.scoredata.player_hand));
      if (pbest == 21) {
        this.finish(cb);
        return;
      }
      if (pbest > 21) { //this calculation is false somehow
        this.finish(cb);
      } else {
        cb("Your hand is " + this.scoredata.player_hand.join(",") + ".");
      }
    } else if (params[0] == "stand") {
      this.finish(cb);
    }
  }
};

function betterNonBust(hand) {
  let x = totalValue(hand, true);
  let y = totalValue(hand, false);
  if (x > 21) return y;
  else return x;
}

CurrentGame.prototype.finish = function(cb) {
  this.finished = true;
  if (this.type == "blackjack") {
    let dealer_going = dealerAction(this.scoredata.dealer_hand);
    while (dealer_going) {
      this.scoredata.dealer_hand.push(this.scoredata.deck.top());
      dealer_going = dealerAction(this.scoredata.dealer_hand);
    }
    let dbest = bestOfValues(allPossibleValues(this.scoredata.dealer_hand));
    let pbest = bestOfValues(allPossibleValues(this.scoredata.player_hand));
    // let dbj = totalValue(this.scoredata.dealer_hand, true) == 21 || totalValue(this.scoredata.dealer_hand, false) === 21;
    // let pbj = totalValue(this.scoredata.player_hand, true) == 21 || totalValue(this.scoredata.player_hand, false) === 21; //lol pbj
    let dbj = dbest==21;
    let pbj = pbest==21;
    if (dbj && pbj) {
      cb("It's a tie! Both blackjack.\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 1.1);
      return;
    }
    if (pbj) {
      cb("Blackjack!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, parseInt(this.bet * 3.3));
      return;
    }
    if (dbj) {
      cb("You lose!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    }
    if (pbest > 21) {
      cb("You busted! Idiot!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    }
    if (dbest > 21) {
      cb("Dealer busted, you win!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 2.2);
      return;
    }
    if (dbest == pbest) {
      cb("It's a tie!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet);
      return;
    }
    if (dbest > pbest) {
      cb("Dealer wins!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    } else {
      cb("You win!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 2.2);
    }
  }
};

function GameData(gamedata) {
  this.data = gamedata;
}

GameData.prototype.newPlayer = function(id, name) {
  let player = {
    id,
    credits: 100,
    last: Date.now(),
    name,
    currgame: null
  };
  this.data.players.push(player);
};

GameData.prototype.getBalOf = function(id) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      return this.data.players[i].credits;
    }
  }
  return "Not Found";
};

GameData.prototype.setBalOf = function(id, credits) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].credits = parseInt(credits);
    }
  }
};

GameData.prototype.pay = function(id, credits) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].credits += parseInt(credits);
    }
  }
};

GameData.prototype.playerExists = function(id) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      return true;
    }
  }
  return false;
};

GameData.prototype.getLeaderboard = function(leaderlength) {
  let ret = [this.data.players[0]];
  //I know this will fail if there is nothing in this.data.players but I don't care.
  for (let i = 1; i < this.data.players.length; i++) {
    for (let j = 0; j < ret.length; j++) {
      if (this.data.players[i].credits >= ret[j].credits) {
        ret.splice(j, 0, this.data.players[i]);
        break;
      }
      if (j == ret.length-1) {
        ret.push(this.data.players[i]);
      }
    }
  }
  let retar = "Leaderboard: \n";
  for (let i = 0; i < leaderlength; i++) {
    if (i >= ret.length) {
      break;
    }
    retar = retar + (i + 1) + ") " + ret[i].name + " " + ret[i].credits + " points" + "\n";
  }
  return retar;
};

GameData.prototype.dataToSave = function() {
  let tdata = {
    players: []
  };
  for (let i = 0; i < this.data.players.length; i++) {
    tdata.players.push({
      id: this.data.players[i].id,
      credits: this.data.players[i].credits,
      last: this.data.players[i].last,
      name: this.data.players[i].name
    });
  }
  return JSON.stringify(tdata);
};

GameData.prototype.startGame = function(id, type, bet, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id && this.data.players[i].credits > bet) {
      this.data.players[i].credits -= parseInt(bet + 0.9);
      this.data.players[i].currgame = new CurrentGame(type, bet, this.data.players[i].id, this);
      this.data.players[i].currgame.start((x) => {
        cb(this.data.players[i].name + "'s Game:\n" + x);
      });
    }
  }
};

GameData.prototype.moveGame = function(id, params, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id && this.data.players[i].currgame) {
      this.data.players[i].currgame.run(params, (x) => {
        cb(this.data.players[i].name + "'s Game:\n" + x);
      });
    }
  }
};

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function getRandomFromList(list) {
  return list[getRandomInt(0, list.length)];
}

function millisToMinutes(t) {
  return parseInt(t/1000/60);
}

GameData.prototype.refill = function(id, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      if (this.data.players[i].last + (1000 * 60 * 60 * 4) > Date.now()) {
        cb("Cannot refill now, try again later. You need to wait 240 minutes. between refills. You last got free coins " + millisToMinutes(Date.now() - this.data.players[i].last) + " minutes ago");
      } else {
        if (this.data.players[i].credits > 500) {
          cb("You don't need a refill now. Go coinflip it all away.");
        } else {
          let x = getRandomFromList([10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 40, 40, 80, 160]);
          cb("You just got a refill of " + x + " credits");
          this.data.players[i].credits += x;
          this.data.players[i].last = Date.now();
        }
      }
    }
  }
};

GameData.prototype.freefill = function(id, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].last = 0;
    }
  }
};

module.exports = {
  GameData
};<commit_msg>Refill buff<commit_after>var dutils = require('./deck.js');

var Deck = dutils.Deck;
var dealerAction = dutils.dealerAction;
var totalValue = dutils.totalValue;
var allPossibleValues = dutils.allPossibleValues;
var bestOfValues = dutils.bestOfValues;

function CurrentGame(type, bet, payout, gd) {
  this.type = type;
  this.bet = bet;
  this.scoredata = {};
  this.person = payout;
  this.gd = gd;
  this.finished = false;
}

CurrentGame.prototype.start = function(cb) {
  if (this.type == "blackjack") {
    this.scoredata.deck = new Deck();
    this.scoredata.dealer_hand = [this.scoredata.deck.top(), this.scoredata.deck.top()];
    this.scoredata.player_hand = [this.scoredata.deck.top(), this.scoredata.deck.top()];
    if (bestOfValues(allPossibleValues(this.scoredata.player_hand)) == 21) {
      this.finish(cb);
      return;
    }
    cb("Dealer Hand: " + this.scoredata.dealer_hand[0] + ",??\nYour Hand: " + this.scoredata.player_hand.join(","));
  }
  return this.scoredata;
};

CurrentGame.prototype.run = function(params, cb) {
  if (this.finished === true) {
    return;
  }
  if (this.type == "blackjack") {
    if (params[0] == "hit") {
      this.scoredata.player_hand.push(this.scoredata.deck.top());
      let pbest = bestOfValues(allPossibleValues(this.scoredata.player_hand));
      if (pbest == 21) {
        this.finish(cb);
        return;
      }
      if (pbest > 21) { //this calculation is false somehow
        this.finish(cb);
      } else {
        cb("Your hand is " + this.scoredata.player_hand.join(",") + ".");
      }
    } else if (params[0] == "stand") {
      this.finish(cb);
    }
  }
};

function betterNonBust(hand) {
  let x = totalValue(hand, true);
  let y = totalValue(hand, false);
  if (x > 21) return y;
  else return x;
}

CurrentGame.prototype.finish = function(cb) {
  this.finished = true;
  if (this.type == "blackjack") {
    let dealer_going = dealerAction(this.scoredata.dealer_hand);
    while (dealer_going) {
      this.scoredata.dealer_hand.push(this.scoredata.deck.top());
      dealer_going = dealerAction(this.scoredata.dealer_hand);
    }
    let dbest = bestOfValues(allPossibleValues(this.scoredata.dealer_hand));
    let pbest = bestOfValues(allPossibleValues(this.scoredata.player_hand));
    // let dbj = totalValue(this.scoredata.dealer_hand, true) == 21 || totalValue(this.scoredata.dealer_hand, false) === 21;
    // let pbj = totalValue(this.scoredata.player_hand, true) == 21 || totalValue(this.scoredata.player_hand, false) === 21; //lol pbj
    let dbj = dbest == 21;
    let pbj = pbest == 21;
    if (dbj && pbj) {
      cb("It's a tie! Both blackjack.\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 1.1);
      return;
    }
    if (pbj) {
      cb("Blackjack!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, parseInt(this.bet * 3.3));
      return;
    }
    if (dbj) {
      cb("You lose!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    }
    if (pbest > 21) {
      cb("You busted! Idiot!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    }
    if (dbest > 21) {
      cb("Dealer busted, you win!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 2.2);
      return;
    }
    if (dbest == pbest) {
      cb("It's a tie!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet);
      return;
    }
    if (dbest > pbest) {
      cb("Dealer wins!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      return;
    } else {
      cb("You win!\nDealer Hand: " + this.scoredata.dealer_hand.join(",") + "\nYour Hand: " + this.scoredata.player_hand.join(","));
      this.gd.pay(this.person, this.bet * 2.2);
    }
  }
};

function GameData(gamedata) {
  this.data = gamedata;
}

GameData.prototype.newPlayer = function(id, name) {
  let player = {
    id,
    credits: 100,
    last: Date.now(),
    name,
    currgame: null
  };
  this.data.players.push(player);
};

GameData.prototype.getBalOf = function(id) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      return this.data.players[i].credits;
    }
  }
  return "Not Found";
};

GameData.prototype.setBalOf = function(id, credits) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].credits = parseInt(credits);
    }
  }
};

GameData.prototype.pay = function(id, credits) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].credits += parseInt(credits);
    }
  }
};

GameData.prototype.playerExists = function(id) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      return true;
    }
  }
  return false;
};

GameData.prototype.getLeaderboard = function(leaderlength) {
  let ret = [this.data.players[0]];
  //I know this will fail if there is nothing in this.data.players but I don't care.
  for (let i = 1; i < this.data.players.length; i++) {
    for (let j = 0; j < ret.length; j++) {
      if (this.data.players[i].credits >= ret[j].credits) {
        ret.splice(j, 0, this.data.players[i]);
        break;
      }
      if (j == ret.length - 1) {
        ret.push(this.data.players[i]);
      }
    }
  }
  let retar = "Leaderboard: \n";
  for (let i = 0; i < leaderlength; i++) {
    if (i >= ret.length) {
      break;
    }
    retar = retar + (i + 1) + ") " + ret[i].name + " " + ret[i].credits + " points" + "\n";
  }
  return retar;
};

GameData.prototype.dataToSave = function() {
  let tdata = {
    players: []
  };
  for (let i = 0; i < this.data.players.length; i++) {
    tdata.players.push({
      id: this.data.players[i].id,
      credits: this.data.players[i].credits,
      last: this.data.players[i].last,
      name: this.data.players[i].name
    });
  }
  return JSON.stringify(tdata);
};

GameData.prototype.startGame = function(id, type, bet, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id && this.data.players[i].credits > bet) {
      this.data.players[i].credits -= parseInt(bet + 0.9);
      this.data.players[i].currgame = new CurrentGame(type, bet, this.data.players[i].id, this);
      this.data.players[i].currgame.start((x) => {
        cb(this.data.players[i].name + "'s Game:\n" + x);
      });
    }
  }
};

GameData.prototype.moveGame = function(id, params, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id && this.data.players[i].currgame) {
      this.data.players[i].currgame.run(params, (x) => {
        cb(this.data.players[i].name + "'s Game:\n" + x);
      });
    }
  }
};

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function getRandomFromList(list) {
  return list[getRandomInt(0, list.length)];
}

function millisToMinutes(t) {
  return parseInt(t / 1000 / 60);
}

GameData.prototype.refill = function(id, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      if (this.data.players[i].last + (1000 * 60 * 60 * 3) > Date.now()) {
        cb("Cannot refill now, try again later. You need to wait 180 minutes. between refills. You need to wait " + (180 - millisToMinutes(Date.now() - this.data.players[i].last)) + " minutes you greedy bastard.");
      } else {
        if (this.data.players[i].credits > 500) {
          cb("You don't need a refill now. Go coinflip it all away.");
        } else {
          let x = getRandomFromList([10, 10, 10, 10, 15, 15, 15, 15, 20, 20, 20, 20, 40, 40, 80, 160]);
          cb("You just got a refill of " + x + " credits");
          this.data.players[i].credits += x;
          this.data.players[i].last = Date.now();
        }
      }
    }
  }
};

GameData.prototype.freefill = function(id, cb) {
  for (let i = 0; i < this.data.players.length; i++) {
    if (this.data.players[i].id == id) {
      this.data.players[i].last = 0;
    }
  }
};

module.exports = {
  GameData
};<|endoftext|>


<commit_before>/** @module deliteful/ViewStack */
define(["dcl/dcl",
	"dojo/sniff",
	"dojo/on",
	"dojo/Deferred",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"delite/register",
	"delite/Widget",
	"delite/DisplayContainer",
	"delite/theme!./ViewStack/themes/{{theme}}/ViewStack_css",
	"delite/css!./ViewStack/transitions/slide_css",
	"delite/css!./ViewStack/transitions/reveal_css",
	"delite/css!./ViewStack/transitions/flip_css",
	"delite/css!./ViewStack/transitions/fade_css"],
	function (dcl, has, on, Deferred, domGeometry, domClass, register, Widget, DisplayContainer) {
		function setVisibility(node, val) {
			if (node) {
				if (val) {
					node.style.visibility = "visible";
					node.style.display = "";
				} else {
					node.style.visibility = "hidden";
					node.style.display = "none";
				}
			}
		}
		function setReverse(node) {
			if (node) {
				domClass.add(node, "-d-view-stack-reverse");
			}
		}
		function cleanCSS(node) {
			if (node) {
				node.className = node.className.split(/ +/).filter(function (x) {
					return !/^-d-view-stack/.test(x);
				}).join(" ");
			}
		}
		function transitionClass(s) {
			return "-d-view-stack-" + s;
		}

		/**
		 * ViewStack container widget. Display one child at a time.
		 *
		 * The first child is displayed by default.
		 * The methods 'show' is used to change the visible child.
		 *
		 * Styling
		 * The following CSS attributes must not be changed.
		 *  ViewStack node:  position, box-sizing, overflow-x
		 *  ViewStack children:  position, box-sizing, width, height
		 *
		 * @example:
		 * <d-view-stack id="vs">
		 *
...

		 *
...

		 *
...

		 * </d-view-stack>
		 * <button onclick="vs.show(childB, {transition: 'reveal', reverse: true})">...</button>
		 * @class module:deliteful/ViewStack
		 * @augments {module:delite/DisplayContainer}
		 */
		return register("d-view-stack", [HTMLElement, DisplayContainer],
			/** @lends module:deliteful/ViewStack# */{
			/**
			 * The name of the CSS class of this widget.
			 * @member {string}
			 * @default "d-view-stack"
			 */
			baseClass: "d-view-stack",

			/**
			 * The transition type used if not specified in the second argument of the show method.
			 * Transitions type are: "none", "slide", "reveal", "flip", "fade".
			 * @member {string}
			 * @default "slide"
			 */
			transition: "slide",

			/**
			 * If true, the transition animation is reversed.
			 * This attribute is supported by "slide" and "reveal" transition types.
			 * @member {boolean}
			 * @default false
			 */
			reverse: false,

			/**
			 * The selected child id, can be set explicitly or through the show() method.
			 * The effect of setting this property (i.e. getting the value through the getter) might be
			 * asynchronous when an animated transition occurs.
			 * @member {string}
			 * @default ""
			 */
			selectedChildId: "",

			_setSelectedChildIdAttr: function (child) {
				this.show(child, this._started ? null : {transition: "none"});
			},

			_getSelectedChildIdAttr: function () {
				return this._visibleChild ? this._visibleChild.id : "";
			},

			_timing: 0,

			_setChildrenVisibility: function () {
				var cdn = this.children;
				if (!this._visibleChild && cdn.length > 0) {
					this._visibleChild = cdn[0];
				}
				for (var i = 0; i < cdn.length; i++) {
					setVisibility(cdn[i], cdn[i] === this._visibleChild);
				}
			},

			preCreate: function () {
				this._transitionTiming = {default: 0, chrome: 20, ios: 20, android: 100, mozilla: 100};
				for (var o in this._transitionTiming) {
					if (has(o) && this._timing < this._transitionTiming[o]) {
						this._timing = this._transitionTiming[o];
					}
				}
				if (typeof MutationObserver !== "undefined") {
					new MutationObserver(this._setChildrenVisibility.bind(this)).observe(this, {childList: true});
				}
				else {
					this._setupContainerMethods();
				}
			},

			_setupContainerMethods: function () {
				var superAppendChild = this.appendChild;
				this.appendChild = function (newChild) {
					var res = superAppendChild.apply(this, [newChild]);
					this._setChildrenVisibility();
					return res;
				};
				var superInsertBefore = this.insertBefore;
				this.insertBefore = function (newChild, refChild) {
					var res = superInsertBefore.apply(this, [newChild, refChild]);
					this._setChildrenVisibility();
					return res;
				};
			},

			buildRendering: function () {
				this._setChildrenVisibility();
			},

			showNext: function (props) {
				//		Shows the next child in the container.
				this._showPreviousNext("nextElementSibling", props);
			},

			showPrevious: function (props) {
				//		Shows the previous child in the container.
				this._showPreviousNext("previousElementSibling", props);
			},

			_showPreviousNext: function (direction, props) {
				if (!this._visibleChild && this.children.length > 0) {
					this._visibleChild = this.children[0];
				}
				if (this._visibleChild) {
					var target = this._visibleChild[direction];
					if (target) {
						this.show(target, props);
					}
				}
			},

			_doTransition: function (origin, target, transition, reverse, deferred) {
				if (transition !== "none") {
					if (origin) {
						this._setAfterTransitionHandlers(origin, event);
						domClass.add(origin, transitionClass(transition));
					}
					if (target) {
						this._setAfterTransitionHandlers(target, event, deferred);
						domClass.add(target, [transitionClass(transition), "-d-view-stack-in"]);
					}
					if (reverse) {
						setReverse(origin);
						setReverse(target);
					}
					this.defer(function () {
						if (target) {
							domClass.add(target, "-d-view-stack-transition");
						}
						if (origin) {
							domClass.add(origin, ["-d-view-stack-transition", "-d-view-stack-out"]);
						}
						if (reverse) {
							setReverse(origin);
							setReverse(target);
						}
						if (target) {
							domClass.add(target, "-d-view-stack-in");
						}
					}, this._timing);
				} else {
					if (origin !== target) {
						setVisibility(origin, false);
					}
					deferred.resolve();
				}
			},

			changeDisplay: function (widget, event) {
				// Resolved when display is completed.
				var deferred = new Deferred();

				if (!widget || widget.parentNode !== this) {
					deferred.resolve();
					return deferred.promise;
				}

				var origin = this._visibleChild;

				// Needed because the CSS state of a node can be incorrect
				// if a previous transitionEnd has been dropped
				cleanCSS(origin);
				cleanCSS(widget);

				setVisibility(widget, true);
				this._visibleChild = widget;

				var transition  = (origin === widget) ? "none" : (event.transition || "slide");
				var reverse = this.isLeftToRight() ? event.reverse : !event.reverse;
				this._doTransition(origin, widget, transition, reverse, deferred);

				return deferred.promise;
			},
			/**
			 * Shows a children of the ViewStack. The parameter 'params' is optional. If not specified,
			 * this.transition, and this.reverse are used.
			 * This method must be called to display a particular destination child on this container.
			 * @param {dest} Widget or HTMLElement or id that points to the child this container must display.
			 * @param {params} Optional params. A hash like {transition: "reveal", reverse: true}. The transition value
			 * can be "slide", "overlay", "fade" or "flip". Reverse transition applies to "slide" and
			 * "reveal".
			 * @returns {module:dojo/promise/Promise} A promise that will be resolved when the display and
			 * transition effect will have been performed.
			 */
			show: dcl.superCall(function (sup) {
				return function (dest, params) {

					if (this._visibleChild && this._visibleChild.parentNode !== this) {
						// The visible child has been removed.
						this._visibleChild = null;
					}
					if (!this._visibleChild && this.children.length > 0) {
						// The default visible child is the first one.
						this._visibleChild = this.children[0];
					}
					return sup.apply(this, [dest, params]);
				};
			}),

			_setAfterTransitionHandlers: function (node, event, deferred) {
				var self = this, endProps = {
					node: node,
					handle: function () { self._afterTransitionHandle(endProps); },
					props: event,
					deferred: deferred
				};

				domClass.add(this, "-d-view-stack-transition");
				node.addEventListener("webkitTransitionEnd", endProps.handle);
				node.addEventListener("transitionend", endProps.handle); // IE10 + FF
			},

			_afterTransitionHandle: function (item) {
				// Defensive approach
				// We should work only on item.node but transitionEnd events can be dropped on aggressive interactions
				for (var i = 0; i < this.children.length; i++) {
					setVisibility(this.children[i], this._visibleChild === this.children[i]);
				}
				cleanCSS(item.node);
				item.node.removeEventListener("webkitTransitionEnd", item.handle);
				item.node.removeEventListener("transitionend", item.handle);
				if (item.deferred) {
					domClass.remove(this, "-d-view-stack-transition");
					item.deferred.resolve();
				}
			}
		});
	});

<commit_msg>Fix #163: ViewStack is broken since commit 79f4285c2e6f0869bd8b24e3ec947aafb66e708b<commit_after>/** @module deliteful/ViewStack */
define(["dcl/dcl",
	"dojo/sniff",
	"dojo/on",
	"dojo/Deferred",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"delite/register",
	"delite/Widget",
	"delite/DisplayContainer",
	"delite/theme!./ViewStack/themes/{{theme}}/ViewStack_css",
	"delite/css!./ViewStack/transitions/slide_css",
	"delite/css!./ViewStack/transitions/reveal_css",
	"delite/css!./ViewStack/transitions/flip_css",
	"delite/css!./ViewStack/transitions/fade_css"],
	function (dcl, has, on, Deferred, domGeometry, domClass, register, Widget, DisplayContainer) {
		function setVisibility(node, val) {
			if (node) {
				if (val) {
					node.style.visibility = "visible";
					node.style.display = "";
				} else {
					node.style.visibility = "hidden";
					node.style.display = "none";
				}
			}
		}
		function setReverse(node) {
			if (node) {
				domClass.add(node, "-d-view-stack-reverse");
			}
		}
		function cleanCSS(node) {
			if (node) {
				node.className = node.className.split(/ +/).filter(function (x) {
					return !/^-d-view-stack/.test(x);
				}).join(" ");
			}
		}
		function transitionClass(s) {
			return "-d-view-stack-" + s;
		}

		/**
		 * ViewStack container widget. Display one child at a time.
		 *
		 * The first child is displayed by default.
		 * The methods 'show' is used to change the visible child.
		 *
		 * Styling
		 * The following CSS attributes must not be changed.
		 *  ViewStack node:  position, box-sizing, overflow-x
		 *  ViewStack children:  position, box-sizing, width, height
		 *
		 * @example:
		 * <d-view-stack id="vs">
		 *
...

		 *
...

		 *
...

		 * </d-view-stack>
		 * <button onclick="vs.show(childB, {transition: 'reveal', reverse: true})">...</button>
		 * @class module:deliteful/ViewStack
		 * @augments {module:delite/DisplayContainer}
		 */
		return register("d-view-stack", [HTMLElement, DisplayContainer],
			/** @lends module:deliteful/ViewStack# */{
			/**
			 * The name of the CSS class of this widget.
			 * @member {string}
			 * @default "d-view-stack"
			 */
			baseClass: "d-view-stack",

			/**
			 * The transition type used if not specified in the second argument of the show method.
			 * Transitions type are: "none", "slide", "reveal", "flip", "fade".
			 * @member {string}
			 * @default "slide"
			 */
			transition: "slide",

			/**
			 * If true, the transition animation is reversed.
			 * This attribute is supported by "slide" and "reveal" transition types.
			 * @member {boolean}
			 * @default false
			 */
			reverse: false,

			/**
			 * The selected child id, can be set explicitly or through the show() method.
			 * The effect of setting this property (i.e. getting the value through the getter) might be
			 * asynchronous when an animated transition occurs.
			 * @member {string}
			 * @default ""
			 */
			selectedChildId: "",

			_setSelectedChildIdAttr: function (child) {
				this.show(child, this._started ? null : {transition: "none"});
			},

			_getSelectedChildIdAttr: function () {
				return this._visibleChild ? this._visibleChild.id : "";
			},

			_timing: 0,

			_setChildrenVisibility: function () {
				var cdn = this.children;
				if (!this._visibleChild && cdn.length > 0) {
					this._visibleChild = cdn[0];
				}
				for (var i = 0; i < cdn.length; i++) {
					setVisibility(cdn[i], cdn[i] === this._visibleChild);
				}
			},

			preCreate: function () {
				this._transitionTiming = {default: 0, chrome: 20, ios: 20, android: 100, mozilla: 100};
				for (var o in this._transitionTiming) {
					if (has(o) && this._timing < this._transitionTiming[o]) {
						this._timing = this._transitionTiming[o];
					}
				}
				if (typeof MutationObserver !== "undefined") {
					new MutationObserver(this._setChildrenVisibility.bind(this)).observe(this, {childList: true});
				}
				else {
					this._setupContainerMethods();
				}
			},

			_setupContainerMethods: function () {
				var superAppendChild = this.appendChild;
				this.appendChild = function (newChild) {
					var res = superAppendChild.apply(this, [newChild]);
					this._setChildrenVisibility();
					return res;
				};
				var superInsertBefore = this.insertBefore;
				this.insertBefore = function (newChild, refChild) {
					var res = superInsertBefore.apply(this, [newChild, refChild]);
					this._setChildrenVisibility();
					return res;
				};
			},

			buildRendering: function () {
				this._setChildrenVisibility();
			},

			showNext: function (props) {
				//		Shows the next child in the container.
				this._showPreviousNext("nextElementSibling", props);
			},

			showPrevious: function (props) {
				//		Shows the previous child in the container.
				this._showPreviousNext("previousElementSibling", props);
			},

			_showPreviousNext: function (direction, props) {
				if (!this._visibleChild && this.children.length > 0) {
					this._visibleChild = this.children[0];
				}
				if (this._visibleChild) {
					var target = this._visibleChild[direction];
					if (target) {
						this.show(target, props);
					}
				}
			},

			_doTransition: function (origin, target, event, transition, reverse, deferred) {
				if (transition !== "none") {
					if (origin) {
						this._setAfterTransitionHandlers(origin, event);
						domClass.add(origin, transitionClass(transition));
					}
					if (target) {
						this._setAfterTransitionHandlers(target, event, deferred);
						domClass.add(target, [transitionClass(transition), "-d-view-stack-in"]);
					}
					if (reverse) {
						setReverse(origin);
						setReverse(target);
					}
					this.defer(function () {
						if (target) {
							domClass.add(target, "-d-view-stack-transition");
						}
						if (origin) {
							domClass.add(origin, ["-d-view-stack-transition", "-d-view-stack-out"]);
						}
						if (reverse) {
							setReverse(origin);
							setReverse(target);
						}
						if (target) {
							domClass.add(target, "-d-view-stack-in");
						}
					}, this._timing);
				} else {
					if (origin !== target) {
						setVisibility(origin, false);
					}
					deferred.resolve();
				}
			},

			changeDisplay: function (widget, event) {
				// Resolved when display is completed.
				var deferred = new Deferred();

				if (!widget || widget.parentNode !== this) {
					deferred.resolve();
					return deferred.promise;
				}

				var origin = this._visibleChild;

				// Needed because the CSS state of a node can be incorrect
				// if a previous transitionEnd has been dropped
				cleanCSS(origin);
				cleanCSS(widget);

				setVisibility(widget, true);
				this._visibleChild = widget;

				var transition  = (origin === widget) ? "none" : (event.transition || "slide");
				var reverse = this.isLeftToRight() ? event.reverse : !event.reverse;
				this._doTransition(origin, widget, event, transition, reverse, deferred);

				return deferred.promise;
			},
			/**
			 * Shows a children of the ViewStack. The parameter 'params' is optional. If not specified,
			 * this.transition, and this.reverse are used.
			 * This method must be called to display a particular destination child on this container.
			 * @param {dest} Widget or HTMLElement or id that points to the child this container must display.
			 * @param {params} Optional params. A hash like {transition: "reveal", reverse: true}. The transition value
			 * can be "slide", "overlay", "fade" or "flip". Reverse transition applies to "slide" and
			 * "reveal".
			 * @returns {module:dojo/promise/Promise} A promise that will be resolved when the display and
			 * transition effect will have been performed.
			 */
			show: dcl.superCall(function (sup) {
				return function (dest, params) {

					if (this._visibleChild && this._visibleChild.parentNode !== this) {
						// The visible child has been removed.
						this._visibleChild = null;
					}
					if (!this._visibleChild && this.children.length > 0) {
						// The default visible child is the first one.
						this._visibleChild = this.children[0];
					}
					return sup.apply(this, [dest, params]);
				};
			}),

			_setAfterTransitionHandlers: function (node, event, deferred) {
				var self = this, endProps = {
					node: node,
					handle: function () { self._afterTransitionHandle(endProps); },
					props: event,
					deferred: deferred
				};

				domClass.add(this, "-d-view-stack-transition");
				node.addEventListener("webkitTransitionEnd", endProps.handle);
				node.addEventListener("transitionend", endProps.handle); // IE10 + FF
			},

			_afterTransitionHandle: function (item) {
				// Defensive approach
				// We should work only on item.node but transitionEnd events can be dropped on aggressive interactions
				for (var i = 0; i < this.children.length; i++) {
					setVisibility(this.children[i], this._visibleChild === this.children[i]);
				}
				cleanCSS(item.node);
				item.node.removeEventListener("webkitTransitionEnd", item.handle);
				item.node.removeEventListener("transitionend", item.handle);
				if (item.deferred) {
					domClass.remove(this, "-d-view-stack-transition");
					item.deferred.resolve();
				}
			}
		});
	});

<|endoftext|>


<commit_before>/**
 * Created by lewiskit on 15/7/7.
 * 邮件审核
 */

var proxy = require('../proxy');
var MailProxy = proxy.Mail;
var moment = require('moment');
var validator = require('validator');
var async = require('async');
var mailTool = require('../common/mail');
var mailConfig = proxy.MailConfig;

exports.getUnCheckList = function (req, res, next) {
    var user = req.user;
    var page = req.query.page;

    var query = {checkMan: user._id, isChecked: 'unchecked'};

    MailProxy.getCheckMailList(query, page, function (err, results, pageCount, itemCount) {
        if (err) return next(err);

        if (!results) {
            res.reply(101, '没有邮件');
            return;
        }

        var data = {};
        data['pageCount'] = pageCount;

        var list = [];
        console.log(results);
        for (var i = 0; i < results.length; i++) {
            var item = results[i];

            console.log(item);
            list.push({
                mailId: item._id,
                title: item.subject,
                receiver: item.to,
                receiveTime: item.date,
                fromNow: moment(item.date).locale('zh-cn').toNow()
            });
        }
        data.list = list;

        res.reply(0, 'success', data);

    });

};

exports.getCheckedList = function (req, res, next) {
    var user = req.user;
    var page = req.query.page;

    var query = {checkMan: user._id, isChecked: {"$in": ['checked', 'returned']}};

    MailProxy.getCheckMailList(query, page, function (err, results, pageCount, itemCount) {
        if (err) return next(err);

        if (!results) {
            res.reply(101, '没有邮件');
            return;
        }
        console.log(results);
        var data = {};
        data['pageCount'] = pageCount;

        var list = [];

        for (var i = 0; i < results.length; i++) {

            var item = results[i];

            list.push({
                mailId: item._id,
                title: item.subject,
                receiver: item.to,
                receiveTime: item.date,
                fromNow: moment(item.date).locale('zh-cn').toNow(),
                isChecked: item.isChecked
            });
        }

        data.list = list;

        res.reply(0, 'success', data);
    });

};

exports.setCheckStatus = function (req, res, next) {
    var mailId = req.body.mailId;
    var check = req.body.check;

    if (check == 'passed') {  //审核通过
        async.waterfall([

            function (callback) {

                MailProxy.findMailById(mailId, function (err, mail) {
                    if (err) return callback(err);

                    mail.isChecked = 'checked';
                    mail.save();

                    callback(null, JSON.stringify(mail));
                });

            },

            function (arg1, callback) {

                mailConfig.getConfig(function (err, data) {
                    if (err) return callback(err);
                    console.log(JSON.parse(data));
                    callback(null, arg1, data);
                });
            },

            function (arg1, arg2, callback) {

                var mail = JSON.parse(arg1);
                console.log(mail);

                var sendMail = {
                    from: mail.from[0].address,
                    html: mail.html,
                    text: mail.text,
                    subject: mail.subject,
                    to: mail.to[0].address
                };

                if (mail.hasOwnProperty('attachment')) {
                    sendMail.attachment = mail.attachment;
                }

                var mailQueue = MailProxy.mailQueue;

                mailQueue.push({
                    name: sendMail.subject, run: function () {
                        var data = JSON.parse(arg2);

                        console.log('The task is doing! %s', JSON.stringify(data));

                        var mailInstance = new mailTool(data);

                        mailInstance.sendMail(sendMail, function (err, info) {
                            if (err) {
                                console.log("there is some err");
                                return;
                            }
                            //  console.log(info);
                            console.log("send email successfully");

                        });
                    }
                }, function (err) {
                    if (err)
                        console.log('hello is bad! %s', err);
                    else
                        console.log("The task execute successfully");

                });
                callback(null, 'done');

            }

        ], function (err, result) {
            if (err) return next(err);

            console.log(result);

            res.reply(0, '发送成功');
        });

    } else if (check == 'failed') {    //审核未通过

        var checkContent = validator.trim(req.body.checkContent) || '';

        var ups = {isChecked: "returned"};

        if (checkContent) ups['checkContent'] = checkContent;

        MailProxy.updateMailById(mailId, ups, function (err) {
            if (err) return next(err);
            res.reply(0, '退回成功');

        });

    }

};
<commit_msg>删除无用log<commit_after>/**
 * Created by lewiskit on 15/7/7.
 * 邮件审核
 */

var proxy = require('../proxy');
var MailProxy = proxy.Mail;
var moment = require('moment');
var validator = require('validator');
var async = require('async');
var mailTool = require('../common/mail');
var mailConfig = proxy.MailConfig;

exports.getUnCheckList = function (req, res, next) {
    var user = req.user;
    var page = req.query.page;

    var query = {checkMan: user._id, isChecked: 'unchecked'};

    MailProxy.getCheckMailList(query, page, function (err, results, pageCount, itemCount) {
        if (err) return next(err);

        if (!results) {
            res.reply(101, '没有邮件');
            return;
        }

        var data = {};
        data['pageCount'] = pageCount;

        var list = [];
        console.log(results);
        for (var i = 0; i < results.length; i++) {
            var item = results[i];

            console.log(item);
            list.push({
                mailId: item._id,
                title: item.subject,
                receiver: item.to,
                receiveTime: item.date,
                fromNow: moment(item.date).locale('zh-cn').toNow()
            });
        }
        data.list = list;

        res.reply(0, 'success', data);

    });

};

exports.getCheckedList = function (req, res, next) {
    var user = req.user;
    var page = req.query.page;

    var query = {checkMan: user._id, isChecked: {"$in": ['checked', 'returned']}};

    MailProxy.getCheckMailList(query, page, function (err, results, pageCount, itemCount) {
        if (err) return next(err);

        if (!results) {
            res.reply(101, '没有邮件');
            return;
        }
        console.log(results);
        var data = {};
        data['pageCount'] = pageCount;

        var list = [];

        for (var i = 0; i < results.length; i++) {

            var item = results[i];

            list.push({
                mailId: item._id,
                title: item.subject,
                receiver: item.to,
                receiveTime: item.date,
                fromNow: moment(item.date).locale('zh-cn').toNow(),
                isChecked: item.isChecked
            });
        }

        data.list = list;

        res.reply(0, 'success', data);
    });

};

exports.setCheckStatus = function (req, res, next) {
    var mailId = req.body.mailId;
    var check = req.body.check;

    if (check == 'passed') {  //审核通过
        async.waterfall([

            function (callback) {

                MailProxy.findMailById(mailId, function (err, mail) {
                    if (err) return callback(err);

                    mail.isChecked = 'checked';
                    mail.save();

                    callback(null, JSON.stringify(mail));
                });

            },

            function (arg1, callback) {

                mailConfig.getConfig(function (err, data) {
                    if (err) return callback(err);
                    console.log(JSON.parse(data));
                    callback(null, arg1, data);
                });
            },

            function (arg1, arg2, callback) {

                var mail = JSON.parse(arg1);
                console.log(mail);

                var sendMail = {
                    from: mail.from[0].address,
                    html: mail.html,
                    text: mail.text,
                    subject: mail.subject,
                    to: mail.to[0].address
                };

                if (mail.hasOwnProperty('attachment')) {
                    sendMail.attachment = mail.attachment;
                }

                var mailQueue = MailProxy.mailQueue;

                mailQueue.push({
                    name: sendMail.subject, run: function () {
                        var data = JSON.parse(arg2);

                        var mailInstance = new mailTool(data);

                        mailInstance.sendMail(sendMail, function (err, info) {
                            if (err) {
                                console.log("there is some err");
                                return;
                            }
                            //  console.log(info);
                            console.log("send email successfully");

                        });
                    }
                }, function (err) {
                    if (err)
                        console.log('hello is bad! %s', err);
                    else
                        console.log("The task execute successfully");

                });
                callback(null, 'done');

            }

        ], function (err, result) {
            if (err) return next(err);

            console.log(result);

            res.reply(0, '发送成功');
        });

    } else if (check == 'failed') {    //审核未通过

        var checkContent = validator.trim(req.body.checkContent) || '';

        var ups = {isChecked: "returned"};

        if (checkContent) ups['checkContent'] = checkContent;

        MailProxy.updateMailById(mailId, ups, function (err) {
            if (err) return next(err);
            res.reply(0, '退回成功');

        });

    }

};
<|endoftext|>


<commit_before>var Class = require('std/Class'),
	Publisher = require('std/Publisher'),
	extend = require('std/extend'),
	slice = require('std/slice'),
	remove = require('std/remove'),
	bind = require('std/bind'),
	browser = require('std/browser')

module.exports = Class(Publisher, function(supr) {

	this._elTag = 'div'
	this._elType = null
	this._class = null

	var defaults = {
		'class': null
	}
	this._init = function(opts) {
		supr(this, '_init', arguments)
		opts = extend(opts, defaults)
		if (typeof opts['class'] == 'string') { this._class = opts['class'] }
		this._events = {}
	}

	this.getElement = function() {
		if (this._el) { return this._el }
		this._el = this.dom({ tag:this._elTag, type:this._elType, 'class':this._class })
		if (this._createContent) { this._createContent() }
		return this._el
	}

	/* Dom nodes
	 ***********/
	var domDefaults = {
		tag: 'div'
	}
	this.dom = function(opts) {
		opts = extend(opts, domDefaults)
		var el = document.createElement(opts.tag)
		if (opts.type) { el.type = opts.type }
		if (opts.html) { el.innerHTML = opts.html }
		if (opts['class']) { el.className = opts['class'] }
		if (opts.style) { this.style(el, opts.style) }
		if (opts.value) { el.value = opts.value }
		return el
	}
	this._dom = this.dom // deprecated

	this.html = function(el, html1 /*, ..., htmlN */) {
		if (typeof html1 != 'string') {
			this.getElement().innerHTML = el
		} else {
			el.innerHTML = slice(arguments, 1).join('')
		}
		return this
	}

	this.appendTo = function(el) {
		if (typeof el.getElement == 'function') { el = el.getElement() }
		el.appendChild(this.getElement())
		return this
	}

	this.append = function(el) {
		if (typeof el.getElement == 'function') { el = el.getElement() }
		this.getElement().appendChild(el)
		return el
	}

	/* Styles
	 ********/
	this.style = function(el, styleProps) {
		if (!styleProps) {
			styleProps = el
			el = this.getElement()
		}
		var elStyle = el.style
		for (var key in styleProps) {
			var value = styleProps[key]
			if (typeof value == 'number') { value += 'px' }
			elStyle[key] = value
		}
		return this
	}

	this.remove = function(el) {
		el = el || this._el
		if (!el || !el.parentNode) { return this }
		el.parentNode.removeChild(el)
		return this
	}

	this.display = function(el, doShow) {
		if (doShow === undefined) {
			doShow = el
			el = this.getElement()
		}
		el.style.display = doShow ? 'block' : 'none'
		return this
	}

	this.show = function(el) { return this.display(el instanceof Element ? el : true, el instanceof Element ? true : undefined) }
	this.hide = function(el) { return this.display(el instanceof Element ? el : false, el instanceof Element ? false : undefined) }

	/* Class names
	 *************/
	this.addClass = function(el, className) {
		if (typeof el == 'string') {
			className = el
			el = this.getElement()
		}
		if (!(' ' + el.className + ' ').match(' ' + className + ' ')) {
			el.className += ' ' + className + ' '
		}
		return this
	}

	this.removeClass = function(el, className) {
		if (typeof el == 'string') {
			className = el
			el = this.getElement()
		}
		if (el.className) {
			className += ' '
			var current = el.className
			var index = current.indexOf(className)
			if (index != -1) {
				el.className = current.slice(0, index) + current.slice(index + className.length)
			}
		}
		return this
	}

	/*
		Example usage:

			this.toggleClass('highlight')
			this.toggleClass('highlight', false)
			this.toggleClass(el, 'highlight')
			this.toggleClass(el, 'highlight', false)
	*/
	this.toggleClass = function(el, className, shouldHave) {
		if (typeof el == 'string') {
			shouldHave = className
			className = el
			el = this.getElement()
		}
		if (shouldHave === undefined) { shouldHave = !this.hasClass(el, className) }
		if (shouldHave == this.hasClass(el, className)) { return this }
		if (shouldHave) { this.addClass(el, className) }
		else { this.removeClass(el, className) }
		return this
	}

	this.hasClass = function(el, className) {
		if (arguments.length == 1) {
			className = el
			el = this.getElement()
		}
		return !!el.className.match(' ' + className + ' ')
	}

	/* Events
	 ********/
	// this._on('click', function(e){})
	// this._on(el, 'click', function(e){})
	this._on = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}

		var handlers = this._events[eventName]
		if (handlers) {
			handlers.push(handler)
		} else {
			this._events[eventName] = [handler]
			var trueHandler = this._events[eventName + '__handler__'] = bind(this, '_onEvent', eventName)
			if (el.addEventListener) {
				el.addEventListener(browser.isFirefox ? 'MozMousePixelScroll' : eventName, trueHandler, false)
			} else if (el.attachEvent) {
				el.attachEvent("on"+eventName, trueHandler)
			}
		}
		return this
	}

	this._onEvent = function(eventName, e) {
		e = e || event
		var eventObj = { keyCode: e.keyCode, metaKey: e.metaKey,
			target: e.target || e.srcElement }

		if (eventName == 'mousewheel') {
			// http://adomas.org/javascript-mouse-wheel/
			// https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
			if (typeof e.wheelDeltaX == 'number') {
				eventObj.dx = -e.wheelDeltaX
				eventObj.dy = -e.wheelDeltaY
			} else if (e.wheelDelta) {
				eventObj.dy = -e.wheelDelta
			} else if (e.detail) {
				if (e.axis == e.HORIZONTAL_AXIS) { eventObj.dx = e.detail }
				if (e.axis == e.VERTICAL_AXIS) { eventObj.dy = e.detail }
			}
		}

		if (typeof e.pageX == 'number')   {
			eventObj.x = e.pageX
			eventObj.y = e.pageY
		} else if (typeof e.clientX == 'number') {
			eventObj.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft
			eventObj.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop
		}

		eventObj.cancel = function() {
			if (e.preventDefault) { e.preventDefault() }
			else { e.returnValue = false }
		}

		if (e.type == 'keypress') {
			eventObj.charCode = (eventObj.charCode == 13 && eventObj.keyCode == 13)
			? 0 // in Webkit, return gives a charCode as well as a keyCode. Should only be a keyCode
			: e.charCode
		}

		var handlers = this._events[eventName]
		for (var i=0; i<handlers.length; i++) {
			handlers[i](eventObj)
		}
	}

	this._off = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}

		if (handler) {
			remove(this._events[eventName], handler)
		} else {
			var trueHandler = this._events[eventName + '__handler__']
			delete this._events[eventName]
			delete this._events[eventName + '__handler__']
			if (el.removeEventListener) {
				el.removeEventListener(eventName, trueHandler, false)
			} else if (el.detachEvent) {
				el.detachEvent("on"+eventName, trueHandler)
			}
		}
		return this
	}

	this._delegateOn = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}
		this._on(el, eventName, bind(this, '_onDelegatedEvent', handler))
	}

	this._onDelegatedEvent = function(handler, e) {
		var target = e.target
		while(target) {
			if (!target.delegateID) {
				target = target.parentNode
				continue
			}
			handler(target.delegateID, target)
			return
		}
	}

	/* Positioning
	 *************/
	// dom offset code adopted from jQuery JavaScript Library v1.3.2
	/*!
	 * jQuery JavaScript Library v1.3.2
	 * http://jquery.com/
	 *
	 * Copyright (c) 2009 John Resig
	 * Dual licensed under the MIT and GPL licenses.
	 * http://docs.jquery.com/License
	 *
	 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
	 * Revision: 6246
	 */
	this.layout = function(el) {
		if (!el) { el = this._el }
		var win = window;

		if (el.getBoundingClientRect) {
			var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, docElem = doc.documentElement,
				clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
				top  = box.top  + (win.pageYOffset || docElem.scrollTop  || body.scrollTop ) - clientTop,
				left = box.left + (win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
			return { y: top, x: left, w: box.right - box.left, h: box.bottom - box.top };

		} else {
			var offset = arguments.callee.offset;
			if (!offset) {
				var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
					html = '

';

				rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
				for (prop in rules) container.style[prop] = rules[prop];

				container.innerHTML = html;
				body.insertBefore(container, body.firstChild);
				innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

				var offset = {};
				offset.doesNotAddBorder = (checkDiv.offsetTop !== 5);
				offset.doesAddBorderForTableAndCells = (td.offsetTop === 5);

				innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
				offset.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

				body.style.marginTop = '1px';
				offset.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
				body.style.marginTop = bodyMarginTop;

				body.removeChild(container);
				arguments.callee.offset = offset;
			}

			var height = el.offsetHeight;
			var width = el.offsetWidth;

			var offsetParent = el.offsetParent, prevOffsetParent = el,
				doc = el.ownerDocument, computedStyle, docElem = doc.documentElement,
				body = doc.body, defaultView = doc.defaultView,
				prevComputedStyle = defaultView.getComputedStyle(el, null),
				top = el.offsetTop, left = el.offsetLeft;

			while ((el = el.parentNode) && el !== body && el !== docElem) {
				computedStyle = defaultView.getComputedStyle(el, null);
				top -= el.scrollTop, left -= el.scrollLeft;
				if (el === offsetParent) {
					top += el.offsetTop, left += el.offsetLeft;
					if (offset.doesNotAddBorder && !(offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(el.tagName))) {
						top += parseInt(computedStyle.borderTopWidth, 10) || 0;
						left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
					}
					prevOffsetParent = offsetParent;
					offsetParent = el.offsetParent;
				}
				if (offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible") {
					top += parseInt(computedStyle.borderTopWidth, 10) || 0;
					left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
				}
				prevComputedStyle = computedStyle;
			}

			if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static") {
				top += body.offsetTop;
				left += body.offsetLeft;
			}

			if (prevComputedStyle.position === "fixed") {
				top  += Math.max(docElem.scrollTop, body.scrollTop);
				left += Math.max(docElem.scrollLeft, body.scrollLeft);
			}

			return { y: top, x: left, w: width, h: height };
		}
	}
	// end jQuery positioning code

	/* Drag and drop
	 ***************/
	var defaults = { threshold:5 }
	this._makeDraggable = function(opts) {
		opts = extend(opts, defaults)
		this._on('mousedown', bind(this, '_onDragMouseDown', opts))
		return this
	}

	this._onDragMouseDown = function(opts, e) {
		this._drag = { x:e.x, y:e.y, pastThreshold:false }
		this._dragMouseMoveHandler = bind(this, '_onDragMouseMove', opts)
		this._dragMouseUpHandler = bind(this, '_onDragMouseUp')
		this
			._on(document, 'mousemove', this._dragMouseMoveHandler)
			._on(document, 'mouseup', this._dragMouseUpHandler)
	}

	this._onDragMouseMove = function(opts, e) {
		var data = this._getDragData(e)
		if (this._drag.pastThreshold) {
			this._publish('drag', data)
		} else {
			if (data.dx^2 + data.dy^2 > opts.threshold^2) {
				this._drag.pastThreshold = true
				this._publish('drag', data)
			}
		}
	}

	this._onDragMouseUp = function(e) {
		var data = this._getDragData(e)
		delete this._drag
		this
			._off(document, 'mousemove', this._dragMouseMoveHandler)
			._off(document, 'mouseup', this._dragMouseUpHandler)
	}

	this._getDragData = function(e) {
		var drag = this._drag
		return { dstX:e.x, dstY:e.y, dx:drag.x - e.x, dy:drag.y - e.y }
	}
})
<commit_msg>Cancel the event for drag mousedown<commit_after>var Class = require('std/Class'),
	Publisher = require('std/Publisher'),
	extend = require('std/extend'),
	slice = require('std/slice'),
	remove = require('std/remove'),
	bind = require('std/bind'),
	browser = require('std/browser')

module.exports = Class(Publisher, function(supr) {

	this._elTag = 'div'
	this._elType = null
	this._class = null

	var defaults = {
		'class': null
	}
	this._init = function(opts) {
		supr(this, '_init', arguments)
		opts = extend(opts, defaults)
		if (typeof opts['class'] == 'string') { this._class = opts['class'] }
		this._events = {}
	}

	this.getElement = function() {
		if (this._el) { return this._el }
		this._el = this.dom({ tag:this._elTag, type:this._elType, 'class':this._class })
		if (this._createContent) { this._createContent() }
		return this._el
	}

	/* Dom nodes
	 ***********/
	var domDefaults = {
		tag: 'div'
	}
	this.dom = function(opts) {
		opts = extend(opts, domDefaults)
		var el = document.createElement(opts.tag)
		if (opts.type) { el.type = opts.type }
		if (opts.html) { el.innerHTML = opts.html }
		if (opts['class']) { el.className = opts['class'] }
		if (opts.style) { this.style(el, opts.style) }
		if (opts.value) { el.value = opts.value }
		return el
	}
	this._dom = this.dom // deprecated

	this.html = function(el, html1 /*, ..., htmlN */) {
		if (typeof html1 != 'string') {
			this.getElement().innerHTML = el
		} else {
			el.innerHTML = slice(arguments, 1).join('')
		}
		return this
	}

	this.appendTo = function(el) {
		if (typeof el.getElement == 'function') { el = el.getElement() }
		el.appendChild(this.getElement())
		return this
	}

	this.append = function(el) {
		if (typeof el.getElement == 'function') { el = el.getElement() }
		this.getElement().appendChild(el)
		return el
	}

	/* Styles
	 ********/
	this.style = function(el, styleProps) {
		if (!styleProps) {
			styleProps = el
			el = this.getElement()
		}
		var elStyle = el.style
		for (var key in styleProps) {
			var value = styleProps[key]
			if (typeof value == 'number') { value += 'px' }
			elStyle[key] = value
		}
		return this
	}

	this.remove = function(el) {
		el = el || this._el
		if (!el || !el.parentNode) { return this }
		el.parentNode.removeChild(el)
		return this
	}

	this.display = function(el, doShow) {
		if (doShow === undefined) {
			doShow = el
			el = this.getElement()
		}
		el.style.display = doShow ? 'block' : 'none'
		return this
	}

	this.show = function(el) { return this.display(el instanceof Element ? el : true, el instanceof Element ? true : undefined) }
	this.hide = function(el) { return this.display(el instanceof Element ? el : false, el instanceof Element ? false : undefined) }

	/* Class names
	 *************/
	this.addClass = function(el, className) {
		if (typeof el == 'string') {
			className = el
			el = this.getElement()
		}
		if (!(' ' + el.className + ' ').match(' ' + className + ' ')) {
			el.className += ' ' + className + ' '
		}
		return this
	}

	this.removeClass = function(el, className) {
		if (typeof el == 'string') {
			className = el
			el = this.getElement()
		}
		if (el.className) {
			className += ' '
			var current = el.className
			var index = current.indexOf(className)
			if (index != -1) {
				el.className = current.slice(0, index) + current.slice(index + className.length)
			}
		}
		return this
	}

	/*
		Example usage:

			this.toggleClass('highlight')
			this.toggleClass('highlight', false)
			this.toggleClass(el, 'highlight')
			this.toggleClass(el, 'highlight', false)
	*/
	this.toggleClass = function(el, className, shouldHave) {
		if (typeof el == 'string') {
			shouldHave = className
			className = el
			el = this.getElement()
		}
		if (shouldHave === undefined) { shouldHave = !this.hasClass(el, className) }
		if (shouldHave == this.hasClass(el, className)) { return this }
		if (shouldHave) { this.addClass(el, className) }
		else { this.removeClass(el, className) }
		return this
	}

	this.hasClass = function(el, className) {
		if (arguments.length == 1) {
			className = el
			el = this.getElement()
		}
		return !!el.className.match(' ' + className + ' ')
	}

	/* Events
	 ********/
	// this._on('click', function(e){})
	// this._on(el, 'click', function(e){})
	this._on = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}

		var handlers = this._events[eventName]
		if (handlers) {
			handlers.push(handler)
		} else {
			this._events[eventName] = [handler]
			var trueHandler = this._events[eventName + '__handler__'] = bind(this, '_onEvent', eventName)
			if (el.addEventListener) {
				el.addEventListener(browser.isFirefox ? 'MozMousePixelScroll' : eventName, trueHandler, false)
			} else if (el.attachEvent) {
				el.attachEvent("on"+eventName, trueHandler)
			}
		}
		return this
	}

	this._onEvent = function(eventName, e) {
		e = e || event
		var eventObj = { keyCode: e.keyCode, metaKey: e.metaKey,
			target: e.target || e.srcElement }

		if (eventName == 'mousewheel') {
			// http://adomas.org/javascript-mouse-wheel/
			// https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
			if (typeof e.wheelDeltaX == 'number') {
				eventObj.dx = -e.wheelDeltaX
				eventObj.dy = -e.wheelDeltaY
			} else if (e.wheelDelta) {
				eventObj.dy = -e.wheelDelta
			} else if (e.detail) {
				if (e.axis == e.HORIZONTAL_AXIS) { eventObj.dx = e.detail }
				if (e.axis == e.VERTICAL_AXIS) { eventObj.dy = e.detail }
			}
		}

		if (typeof e.pageX == 'number')   {
			eventObj.x = e.pageX
			eventObj.y = e.pageY
		} else if (typeof e.clientX == 'number') {
			eventObj.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft
			eventObj.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop
		}

		eventObj.cancel = function() {
			if (e.preventDefault) { e.preventDefault() }
			else { e.returnValue = false }
		}

		if (e.type == 'keypress') {
			eventObj.charCode = (eventObj.charCode == 13 && eventObj.keyCode == 13)
			? 0 // in Webkit, return gives a charCode as well as a keyCode. Should only be a keyCode
			: e.charCode
		}

		var handlers = this._events[eventName]
		for (var i=0; i<handlers.length; i++) {
			handlers[i](eventObj)
		}
	}

	this._off = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}

		if (handler) {
			remove(this._events[eventName], handler)
		} else {
			var trueHandler = this._events[eventName + '__handler__']
			delete this._events[eventName]
			delete this._events[eventName + '__handler__']
			if (el.removeEventListener) {
				el.removeEventListener(eventName, trueHandler, false)
			} else if (el.detachEvent) {
				el.detachEvent("on"+eventName, trueHandler)
			}
		}
		return this
	}

	this._delegateOn = function(el, eventName, handler) {
		if (arguments.length == 2) {
			handler = eventName
			eventName = el
			el = this._el
		}
		this._on(el, eventName, bind(this, '_onDelegatedEvent', handler))
	}

	this._onDelegatedEvent = function(handler, e) {
		var target = e.target
		while(target) {
			if (!target.delegateID) {
				target = target.parentNode
				continue
			}
			handler(target.delegateID, target)
			return
		}
	}

	/* Positioning
	 *************/
	// dom offset code adopted from jQuery JavaScript Library v1.3.2
	/*!
	 * jQuery JavaScript Library v1.3.2
	 * http://jquery.com/
	 *
	 * Copyright (c) 2009 John Resig
	 * Dual licensed under the MIT and GPL licenses.
	 * http://docs.jquery.com/License
	 *
	 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
	 * Revision: 6246
	 */
	this.layout = function(el) {
		if (!el) { el = this._el }
		var win = window;

		if (el.getBoundingClientRect) {
			var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, docElem = doc.documentElement,
				clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
				top  = box.top  + (win.pageYOffset || docElem.scrollTop  || body.scrollTop ) - clientTop,
				left = box.left + (win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
			return { y: top, x: left, w: box.right - box.left, h: box.bottom - box.top };

		} else {
			var offset = arguments.callee.offset;
			if (!offset) {
				var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
					html = '

';

				rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
				for (prop in rules) container.style[prop] = rules[prop];

				container.innerHTML = html;
				body.insertBefore(container, body.firstChild);
				innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

				var offset = {};
				offset.doesNotAddBorder = (checkDiv.offsetTop !== 5);
				offset.doesAddBorderForTableAndCells = (td.offsetTop === 5);

				innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
				offset.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

				body.style.marginTop = '1px';
				offset.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
				body.style.marginTop = bodyMarginTop;

				body.removeChild(container);
				arguments.callee.offset = offset;
			}

			var height = el.offsetHeight;
			var width = el.offsetWidth;

			var offsetParent = el.offsetParent, prevOffsetParent = el,
				doc = el.ownerDocument, computedStyle, docElem = doc.documentElement,
				body = doc.body, defaultView = doc.defaultView,
				prevComputedStyle = defaultView.getComputedStyle(el, null),
				top = el.offsetTop, left = el.offsetLeft;

			while ((el = el.parentNode) && el !== body && el !== docElem) {
				computedStyle = defaultView.getComputedStyle(el, null);
				top -= el.scrollTop, left -= el.scrollLeft;
				if (el === offsetParent) {
					top += el.offsetTop, left += el.offsetLeft;
					if (offset.doesNotAddBorder && !(offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(el.tagName))) {
						top += parseInt(computedStyle.borderTopWidth, 10) || 0;
						left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
					}
					prevOffsetParent = offsetParent;
					offsetParent = el.offsetParent;
				}
				if (offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible") {
					top += parseInt(computedStyle.borderTopWidth, 10) || 0;
					left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
				}
				prevComputedStyle = computedStyle;
			}

			if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static") {
				top += body.offsetTop;
				left += body.offsetLeft;
			}

			if (prevComputedStyle.position === "fixed") {
				top  += Math.max(docElem.scrollTop, body.scrollTop);
				left += Math.max(docElem.scrollLeft, body.scrollLeft);
			}

			return { y: top, x: left, w: width, h: height };
		}
	}
	// end jQuery positioning code

	/* Drag and drop
	 ***************/
	var defaults = { threshold:5 }
	this._makeDraggable = function(opts) {
		opts = extend(opts, defaults)
		this._on('mousedown', bind(this, '_onDragMouseDown', opts))
		return this
	}

	this._onDragMouseDown = function(opts, e) {
		e.cancel()
		this._drag = {
			pastThreshold:false,
			start:{ x:e.x, y:e.y },
			last: { x:e.x, y:e.y }
		}
		this._dragMouseMoveHandler = bind(this, '_onDragMouseMove', opts)
		this._dragMouseUpHandler = bind(this, '_onDragMouseUp')
		this
			._on(document, 'mousemove', this._dragMouseMoveHandler)
			._on(document, 'mouseup', this._dragMouseUpHandler)
	}

	this._onDragMouseMove = function(opts, e) {
		var data = this._getDragData(e)
		if (this._drag.pastThreshold) {
			this._publish('drag', data)
		} else {
			if (data.dx^2 + data.dy^2 > opts.threshold^2) {
				this._drag.pastThreshold = true
				this._publish('drag', data)
			}
		}
	}

	this._onDragMouseUp = function(e) {
		var data = this._getDragData(e)
		delete this._drag
		this
			._off(document, 'mousemove', this._dragMouseMoveHandler)
			._off(document, 'mouseup', this._dragMouseUpHandler)
	}

	this._getDragData = function(e) {
		var drag = this._drag
		return { dstX:e.x, dstY:e.y, dx:drag.x - e.x, dy:drag.y - e.y }
	}
})
<|endoftext|>


<commit_before>'use strict';

const request = require("request");
const url = require("url");

function getfavicon (webpage) {
  return new Promise((resolve, reject) => {
    request(webpage, function(err, res, body) {
      let faviconArrayA = /<link[\w\s="]*rel="shortcut icon" href="([\w._-]*)"/.exec(body);
      let faviconArrayB = /<link[\w\s="]* href="([\w._-]*)"[\w\s._-]*rel="shortcut icon" /.exec(body);

      if (faviconArrayA != null && faviconArrayA.length >= 2) {
        resolve(url.resolve(webpage, faviconArrayA[1]));
      }
      else if (faviconArrayB != null && faviconArrayB.length >= 2) {
        resolve(url.resolve(webpage, faviconArrayB[1]));
      }
      else {
        resolve(null);
      }
    });
  });
};

module.exports = getfavicon;
<commit_msg>issue #1: New RegExp<commit_after>'use strict';

const request = require("request");
const url = require("url");

function getfavicon (webpage) {
  return new Promise((resolve, reject) => {
    request(webpage, function(err, res, body) {
      let faviconArray = /[rel="shortcut icon"|rel="icon"|rel=icon]?[.]*[^>]href="([\w/._-]*)"[.]*[^>](rel="shortcut icon"|rel="icon"|rel=icon)?[.]*[^>](type="([-\w\/]*)")?/gui.exec(body);

      if (faviconArray != null && faviconArray.length >= 2) {
        resolve(url.resolve(webpage, faviconArray[1]));
      }
    });
  });
}

module.exports = getfavicon;
<|endoftext|>