<commit_before>// https://github.com/vuejs/vue-cli/blob/master/lib/generate.js

var path = require('path')
var fs = require('fs')
var _ = require('lodash')
var axios = require('axios')
var Metalsmith = require('metalsmith')

var logger = require('./logger')

var config
var projectPath
var templatePath

function compareProjectIds (source, obj) {
  var di = _.xor(source, obj)
  if (!_.isEmpty(di)) {
    logger.log('"%s" 生成失败，请检查 ID 是否正确.', di.join(','))
    // 同步过滤配置项
    config.projects = config.projects.filter(o => !_.includes(di, o.id))
  }
}

function filterAPI (apis) {
  Object.keys(apis).forEach((projectId) => {
    var api = apis[projectId]
    var confProject = _.find(config.projects, ['id', projectId])

    if (!confProject) return

    var whiteList = confProject.white
    var blackList = confProject.black

    api.mocks = api.mocks.filter((mock) => {
      if (!_.isEmpty(whiteList)) {
        return _.includes(whiteList, mock.url)
      } else if (!_.isEmpty(blackList)) {
        return !_.includes(blackList, mock.url)
      }
      return true
    })
  })
}

function init (apis, cb) {
  var projectIds = Object.keys(apis)
  var helperPath = path.resolve(templatePath, '../helper/index.js')
  var helper = fs.existsSync(helperPath) ? require(helperPath) : {}

  projectIds.forEach((projectId) => {
    var api = apis[projectId]
    var confProject = _.find(config.projects, ['id', projectId])

    if (!confProject) return

    var dest = path.join(config.output, confProject.name)
    var data = {
      data: api,
      config: config,
      _: _,
      $$: Object.assign({}, helper, {
        relative: function (targetFile) {
          var relative = path.relative(dest, config.output)
          return path.join(relative, targetFile)
        }
      })
    }

    build(data, 'cover', dest, cb)
    if (fs.existsSync(path.join(templatePath, 'init'))) build(data, 'init', dest, cb, true)
  })

  if (fs.existsSync(path.join(templatePath, 'common'))) {
    build({
      config: config,
      _: _,
      $$: helper
    }, 'common', config.output, cb, true)
  }
}

function build (data, source, dest, cb, ignore) {
  var metalsmith = Metalsmith(templatePath)
      .use(renderTemplateFiles(data))
      .clean(false)
      .source(source)
      .destination(dest)

  if (ignore) {
    metalsmith.ignore(filePath => {
      filePath = filePath.replace(path.join(templatePath, source), '')
      filePath = path.join(dest, filePath)
      return fs.existsSync(filePath)
    })
  }

  return metalsmith.build((error, files) => {
    if (error) logger.fatal(error)
    var f = Object.keys(files)
      .filter(o => fs.existsSync(path.join(dest, o)))
      .map(o => path.join(dest, o))
    cb(error, f)
  })
}

function renderTemplateFiles (data) {
  return function (files) {
    Object.keys(files).forEach((fileName) => {
      var file = files[fileName]
      file.contents = _.template(file.contents, {
        interpolate: /\{\{(.+?)\}\}/g
      })(data)
    })
  }
}

module.exports = function (_projectPath, _templatePath, _config, cb) {
  config = _config
  projectPath = _projectPath

  templatePath = path.join(_templatePath, 'template')
  config.output = path.resolve(projectPath, config.output || 'easy-mock-api')

  if (_.isEmpty(config.projects)) return
  if (!_.isArray(config.projects)) logger.fatal('请正确配置项目列表.')

  var projectIds = config.projects
    .filter(o => _.has(o, 'id') && _.has(o, 'name'))
    .map(project => project.id)

  if (projectIds.length !== config.projects.length) logger.fatal('缺少字段，请正确配置项目列表.')

  config.host = config.host || 'https://www.easy-mock.com'

  var api = config.host.slice(-1) === '/'
  ? `${config.host}api/mock/by_projects`
  : `${config.host}/api/mock/by_projects`

  axios
    .get(api, {
      params: {
        project_ids: projectIds.join(',')
      }
    })
    .then((res) => {
      var data = res.data.data
      if (data) {
        filterAPI(data)
        compareProjectIds(projectIds, Object.keys(data))
        init(data, cb)
      } else {
        compareProjectIds(projectIds, [])
      }
    })
    .catch(error => {
      if (error.response) {
        logger.fatal(error.response.data)
      } else {
        logger.fatal(error)
      }
    })
}
<commit_msg>fix: path posix<commit_after>// https://github.com/vuejs/vue-cli/blob/master/lib/generate.js

var path = require('path')
var fs = require('fs')
var _ = require('lodash')
var axios = require('axios')
var Metalsmith = require('metalsmith')

var logger = require('./logger')

var config
var projectPath
var templatePath

function compareProjectIds (source, obj) {
  var di = _.xor(source, obj)
  if (!_.isEmpty(di)) {
    logger.log('"%s" 生成失败，请检查 ID 是否正确.', di.join(','))
    // 同步过滤配置项
    config.projects = config.projects.filter(o => !_.includes(di, o.id))
  }
}

function filterAPI (apis) {
  Object.keys(apis).forEach((projectId) => {
    var api = apis[projectId]
    var confProject = _.find(config.projects, ['id', projectId])

    if (!confProject) return

    var whiteList = confProject.white
    var blackList = confProject.black

    api.mocks = api.mocks.filter((mock) => {
      if (!_.isEmpty(whiteList)) {
        return _.includes(whiteList, mock.url)
      } else if (!_.isEmpty(blackList)) {
        return !_.includes(blackList, mock.url)
      }
      return true
    })
  })
}

function init (apis, cb) {
  var projectIds = Object.keys(apis)
  var helperPath = path.resolve(templatePath, '../helper/index.js')
  var helper = fs.existsSync(helperPath) ? require(helperPath) : {}

  projectIds.forEach((projectId) => {
    var api = apis[projectId]
    var confProject = _.find(config.projects, ['id', projectId])

    if (!confProject) return

    var dest = path.join(config.output, confProject.name)
    var data = {
      data: api,
      config: config,
      _: _,
      $$: Object.assign({}, helper, {
        relative: function (targetFile) {
          var relative = path.posix.relative(dest, config.output)
          return path.posix.join(relative, targetFile)
        }
      })
    }

    build(data, 'cover', dest, cb)
    if (fs.existsSync(path.join(templatePath, 'init'))) build(data, 'init', dest, cb, true)
  })

  if (fs.existsSync(path.join(templatePath, 'common'))) {
    build({
      config: config,
      _: _,
      $$: helper
    }, 'common', config.output, cb, true)
  }
}

function build (data, source, dest, cb, ignore) {
  var metalsmith = Metalsmith(templatePath)
      .use(renderTemplateFiles(data))
      .clean(false)
      .source(source)
      .destination(dest)

  if (ignore) {
    metalsmith.ignore(filePath => {
      filePath = filePath.replace(path.join(templatePath, source), '')
      filePath = path.join(dest, filePath)
      return fs.existsSync(filePath)
    })
  }

  return metalsmith.build((error, files) => {
    if (error) logger.fatal(error)
    var f = Object.keys(files)
      .filter(o => fs.existsSync(path.join(dest, o)))
      .map(o => path.join(dest, o))
    cb(error, f)
  })
}

function renderTemplateFiles (data) {
  return function (files) {
    Object.keys(files).forEach((fileName) => {
      var file = files[fileName]
      file.contents = _.template(file.contents, {
        interpolate: /\{\{(.+?)\}\}/g
      })(data)
    })
  }
}

module.exports = function (_projectPath, _templatePath, _config, cb) {
  config = _config
  projectPath = _projectPath

  templatePath = path.join(_templatePath, 'template')
  config.output = path.resolve(projectPath, config.output || 'easy-mock-api')

  if (_.isEmpty(config.projects)) return
  if (!_.isArray(config.projects)) logger.fatal('请正确配置项目列表.')

  var projectIds = config.projects
    .filter(o => _.has(o, 'id') && _.has(o, 'name'))
    .map(project => project.id)

  if (projectIds.length !== config.projects.length) logger.fatal('缺少字段，请正确配置项目列表.')

  config.host = config.host || 'https://www.easy-mock.com'

  var api = config.host.slice(-1) === '/'
  ? `${config.host}api/mock/by_projects`
  : `${config.host}/api/mock/by_projects`

  axios
    .get(api, {
      params: {
        project_ids: projectIds.join(',')
      }
    })
    .then((res) => {
      var data = res.data.data
      if (data) {
        filterAPI(data)
        compareProjectIds(projectIds, Object.keys(data))
        init(data, cb)
      } else {
        compareProjectIds(projectIds, [])
      }
    })
    .catch(error => {
      if (error.response) {
        logger.fatal(error.response.data)
      } else {
        logger.fatal(error)
      }
    })
}
<|endoftext|>


<commit_before>//(C) 2012 Anton Zemlyanov

//This module describes Betfair price
//see Sports API documentation on http://bdp.betfair.com

exports.newBetfairPrice = function(size) {
    return new BetfairPrice(size);
}

var epsilon=0.001;

function BetfairPrice(size) {
    if(!size)
        size = 1.01;

    this.setStake(size);
}

BetfairPrice.prototype.setStake = function(size) {
    if(!size)
        size = 1.01;
    if(typeof(size)==='string')
        size = parseFloat(size);

    if(size<1.01)
        size = 1.01;
    else if (size<2)
        size = Math.round(size*100.0)/100.0;
    else if (size<3)
        size = Math.round(size*50.0)/50.0;
    else if (size<4)
        size = Math.round(size*20.0)/20.0;
    else if (size<6)
        size = Math.round(size*10.0)/10.0;
    else if (size<10)
        size = Math.round(size*5.0)/5.0;
    else if (size<20)
        size = Math.round(size*2.0)/2.0;
    else if (size<30)
        size = Math.round(size*1.0)/1.0;
    else if (size<50)
        size = Math.round(size*0.5)/0.5;
    else if (size<100)
        size = Math.round(size*0.2)/0.2;
    else if (size<1000)
        size = Math.round(size*0.1)/0.1;
    else
        size = 1000.0;

    this.size = size;
    return;
}

BetfairPrice.prototype.toString = function(size) {
   var str = this.size.toFixed(2);
   if( str.charAt(str.length-1)==='0' )
       str = this.size.toFixed(1);
   if( str.charAt(str.length-1)==='0' )
       str = this.size.toFixed();
   return str;
}

BetfairPrice.prototype.increasePrice = function() {
    var size = this.size;

    if(size<(2.0-epsilon))
        size += 0.01;
    else if(size<(3.0-epsilon))
        size += 0.02;
    else if(size<(4.0-epsilon))
        size += 0.05;
    else if(size<(6.0-epsilon))
        size += 0.1;
    else if(size<(10.0-epsilon))
        size += 0.2;
    else if(size<(20.0-epsilon))
        size += 0.5;
    else if(size<(30.0-epsilon))
        size += 1.0;
    else if(size<(50.0-epsilon))
        size += 2.0;
    else if(size<(100.0-epsilon))
        size += 5.0;
    else if(size<(1000.0-epsilon))
        size += 10.0;
    else
        size = 1000.0;

    this.size = size;
    return this;
}

BetfairPrice.prototype.decreasePrice = function() {
    var size = this.size;

    if(size>(100.0+epsilon))
        size -= 10.0;
    else if(size>(50.0+epsilon))
        size -= 5.0;
    else if(size>(30.0+epsilon))
        size -= 2.0;
    else if(size>(20.0+epsilon))
        size -= 1.0;
    else if(size>(10.0+epsilon))
        size -= 0.5;
    else if(size>(6.0+epsilon))
        size -= 0.2;
    else if(size>(4.0+epsilon))
        size -= 0.1;
    else if(size>(3.0+epsilon))
        size -= 0.05;
    else if(size>(2.0+epsilon))
        size -= 0.02;
    else if(size>(1.01+epsilon))
        size -= 0.01;
    else
        size = 1.01;

    this.size = size;
    return this;
}

<commit_msg>bf price optimized<commit_after>//(C) 2012 Anton Zemlyanov

//This module describes Betfair price
//see Sports API documentation on http://bdp.betfair.com

exports.newBetfairPrice = function(size) {
    return new BetfairPrice(size);
}

var epsilon=0.001;

function BetfairPrice(size) {
    if(!size)
        size = 1.01;

    this.setStake(size);
}

BetfairPrice.prototype.setStake = function(size) {
    if(!size)
        size = 1.01;
    if(typeof(size)==='string')
        size = parseFloat(size);

    if(size<1.01)
        size = 1.01;
    else if (size<2)
        size = Math.round(size*100.0)/100.0;
    else if (size<3)
        size = Math.round(size*50.0)/50.0;
    else if (size<4)
        size = Math.round(size*20.0)/20.0;
    else if (size<6)
        size = Math.round(size*10.0)/10.0;
    else if (size<10)
        size = Math.round(size*5.0)/5.0;
    else if (size<20)
        size = Math.round(size*2.0)/2.0;
    else if (size<30)
        size = Math.round(size*1.0)/1.0;
    else if (size<50)
        size = Math.round(size*0.5)/0.5;
    else if (size<100)
        size = Math.round(size*0.2)/0.2;
    else if (size<1000)
        size = Math.round(size*0.1)/0.1;
    else
        size = 1000.0;

    this.size = size;
    return;
}

BetfairPrice.prototype.toString = function(size) {
   var str = this.size.toFixed(2);
   if( str.charAt(str.length-1)==='0' )
          str = str.substr(0, str.length-1);
   if( str.charAt(str.length-1)==='0' )
          str = str.substr(0, str.length-2);
   return str;
}

BetfairPrice.prototype.increasePrice = function() {
    var size = this.size;

    if(size<(2.0-epsilon))
        size += 0.01;
    else if(size<(3.0-epsilon))
        size += 0.02;
    else if(size<(4.0-epsilon))
        size += 0.05;
    else if(size<(6.0-epsilon))
        size += 0.1;
    else if(size<(10.0-epsilon))
        size += 0.2;
    else if(size<(20.0-epsilon))
        size += 0.5;
    else if(size<(30.0-epsilon))
        size += 1.0;
    else if(size<(50.0-epsilon))
        size += 2.0;
    else if(size<(100.0-epsilon))
        size += 5.0;
    else if(size<(1000.0-epsilon))
        size += 10.0;
    else
        size = 1000.0;

    this.size = size;
    return this;
}

BetfairPrice.prototype.decreasePrice = function() {
    var size = this.size;

    if(size>(100.0+epsilon))
        size -= 10.0;
    else if(size>(50.0+epsilon))
        size -= 5.0;
    else if(size>(30.0+epsilon))
        size -= 2.0;
    else if(size>(20.0+epsilon))
        size -= 1.0;
    else if(size>(10.0+epsilon))
        size -= 0.5;
    else if(size>(6.0+epsilon))
        size -= 0.2;
    else if(size>(4.0+epsilon))
        size -= 0.1;
    else if(size>(3.0+epsilon))
        size -= 0.05;
    else if(size>(2.0+epsilon))
        size -= 0.02;
    else if(size>(1.01+epsilon))
        size -= 0.01;
    else
        size = 1.01;

    this.size = size;
    return this;
}

<|endoftext|>


<commit_before>var generics;

var inverseTable = {
	'AdminStatus':              'AdminStatusArray',
	'AdminUpdateType':          'AdminUpdateTypeArray',
	'AdminUpdateFrequency':     'AdminUpdateFrequencyArray',
	'AdminCompanyRemoveReason': 'AdminCompanyRemoveReasonArray',
	'Colour':                   'ColourArray',
	'DestType':                 'DestTypeArray',
	'Landscape':                'LandscapeArray',
	'NetworkAction':            'NetworkActionArray',
	'NetworkErrorCode':         'NetworkErrorCodeArray',
	'NetworkLanguage':          'NetworkLanguageArray',
	'VehicleType':              'VehicleTypeArray'
};

module.exports = generics = {};

// Protocol data

// Swaps keys with values
generics.getInversedObject = function(object) {
	var result = {};

	for (var i in object) {
		result[object[i]] = i;
	}

	return result;
};

generics.spec = require("../data/protocol")
for (var i in inverseTable) {
	generics.spec[inverseTable[i]] = generics.getInversedObject(generics.spec[i]);
}

// Date handling

generics.isLeapYear = function(year) {
	return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};

generics.daysInMonth = function(month, year) {
	return [31, this.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

generics.getQuarter = function(month) {
	return Math.floor(month / 3);
};

// Year calculation based on
// http://dev.openttdcoop.org/projects/joan/repository/entry/src/main/java/org/openttd/GameDate.java
generics.gameDateToDate = function(date) {
	var rem, year, month = -1, days = 0;

	// There are 97 leap years in 400 years
	year = 400 * Math.floor(date / (365 * 400 + 97));
	rem  = date % (365 * 400 + 97);

	// There are 24 leap years in 100 years
	year += 100 * Math.floor(rem / (365 * 100 + 24));
	rem  %= 365 * 100 + 24;

	// There is 1 leap year every 4 years
	year += 4 * Math.floor(rem / (365 * 4 + 1));
	rem  %= 365 * 4 + 1;

	// Finish year calculation
	while (rem >= (this.isLeapYear(year) ? 366 : 365)) {
		rem -= this.isLeapYear(year) ? 366 : 365;
		year++;
	}

	// Get month
	do {
		month++;
		rem -=  days;
		days = this.daysInMonth(month, year);
	} while (rem > days);

	// Rem should be day in the month
	return {year: year, month: month, day: rem + 1, quarter: this.getQuarter(month)};
};

// Network stuff

generics.typeTableSend = {
	"uint8":    function(input) {var buffer=new Buffer(1);buffer.writeUInt8   (input, 0); return buffer;},
	"int8":     function(input) {var buffer=new Buffer(1);buffer.writeInt8    (input, 0); return buffer;},
	"uint16be": function(input) {var buffer=new Buffer(2);buffer.writeUInt16BE(input, 0); return buffer;},
	"uint16le": function(input) {var buffer=new Buffer(2);buffer.writeUInt16LE(input, 0); return buffer;},
	"int16be":  function(input) {var buffer=new Buffer(2);buffer.writeInt16BE (input, 0); return buffer;},
	"int16le":  function(input) {var buffer=new Buffer(2);buffer.writeInt16LE (input, 0); return buffer;},
	"uint32be": function(input) {var buffer=new Buffer(4);buffer.writeUInt32BE(input, 0); return buffer;},
	"uint32le": function(input) {var buffer=new Buffer(4);buffer.writeUInt32LE(input, 0); return buffer;},
	"int32be":  function(input) {var buffer=new Buffer(4);buffer.writeInt32BE (input, 0); return buffer;},
	"int32le":  function(input) {var buffer=new Buffer(4);buffer.writeInt32LE (input, 0); return buffer;},
	"floatbe":  function(input) {var buffer=new Buffer(4);buffer.writeFloatBE (input, 0); return buffer;},
	"floatle":  function(input) {var buffer=new Buffer(4);buffer.writeFloatLE (input, 0); return buffer;},
	"doublebe": function(input) {var buffer=new Buffer(8);buffer.writeDoubleBE(input, 0); return buffer;},
	"doublele": function(input) {var buffer=new Buffer(8);buffer.writeDoubleLE(input, 0); return buffer;},
	"bool":     function(input) {var buffer=new Buffer(1);buffer.writeUInt8(input ? 1 : 0, 0); return buffer;},
	"utf8":     function(input) {return new Buffer(input.replace("\u0000", "") + "\u0000", 'utf8');}
};

generics.typeTableReceive = {
	"bool":     function(buffer, offset) {return [buffer.readUInt8(offset) === 1, 1];},
	"uint8":    function(buffer, offset) {return [buffer.readUInt8(offset),       1];},
	"int8":     function(buffer, offset) {return [buffer.readInt8(offset),        1];},
	"uint16be": function(buffer, offset) {return [buffer.readUInt16BE(offset),    2];},
	"uint16le": function(buffer, offset) {return [buffer.readUInt16LE(offset),    2];},
	"int16be":  function(buffer, offset) {return [buffer.readInt16BE(offset),     2];},
	"int16le":  function(buffer, offset) {return [buffer.readInt16LE(offset),     2];},
	"uint32be": function(buffer, offset) {return [buffer.readUInt32BE(offset),    4];},
	"uint32le": function(buffer, offset) {return [buffer.readUInt32LE(offset),    4];},
	"int32be":  function(buffer, offset) {return [buffer.readInt32BE(offset),     4];},
	"int32le":  function(buffer, offset) {return [buffer.readInt32LE(offset),     4];},
	"floatbe":  function(buffer, offset) {return [buffer.readFloatBE(offset),     4];},
	"floatle":  function(buffer, offset) {return [buffer.readFloatLE(offset),     4];},
	"doublebe": function(buffer, offset) {return [buffer.readDoubleBE(offset),    8];},
	"doublele": function(buffer, offset) {return [buffer.readDoubleLE(offset),    8];},
	"uint64be": function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"uint64le": function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"int64be":  function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"int64le":  function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"utf8":     function(buffer, offset) {
		var pos = offset;
		for (;buffer[pos] !== 0x00; pos++) {}
		return [buffer.toString('utf8', offset, pos), pos - offset + 1];
	},
	"protocol": function(buffer, offset) {
		var pos = offset, result = [];
		while (buffer.readUInt8(pos) === 1) {
			result[result.length] = [buffer.readUInt16LE(pos + 1), buffer.readUInt16LE(pos + 3)];
			pos += 5;
		}
		return [result, pos - offset];
	},
	"cmdnames": function(buffer, offset) {
		var pos = offset, pos2, result = [];
		while (buffer.readUInt8(pos) === 1) {
			result[result.length] = [buffer.readUInt16LE(pos + 1)];
			for (pos += 3, pos2 = pos; buffer[pos] !== 0x00; pos++) {}
			result[result.length -1][1] = buffer.toString('utf8', pos2, pos);
			pos++;
		}
		return [result, pos - offset];
	}
};

generics.preparePacket = function(type, format, data) {
	// First 3 bytes represents packet length and type
	var buffer = [new Buffer(3)];

	// Format data in buffers and merge them to the package format
	for (var i = 0, length = Math.min(format.length, data.length); i < length; i++) {
		if (generics.typeTableSend[format[i].type] === null)
			throw "Type " + format[i].type + " not known in send table";

		buffer.push(generics.typeTableSend[format[i].type.toLowerCase()](data[i]));
	}

	buffer = Buffer.concat(buffer);

	// Length check
	if (buffer.length > 1460)
		throw "Message too long";

	// Pre-append length and packet type
	buffer.writeUInt8(type, 2);
	buffer.writeUInt16LE(buffer.length, 0);

	return buffer;
};

generics.extractContent = function(format, content) {
	var data = [], result, offset = 0, type;

	// Extract data given the package format
	for (var i = 0; i < format.length; i++) {
		type = format[i].type.toLowerCase();

		if (generics.typeTableReceive[type] === null)
			throw "unknown data type " + type;

		result = generics.typeTableReceive[type](content, offset);
		data[data.length] = result[0];
		offset           += result[1];
	}

	return data;
};<commit_msg>Fix utf8 filtering in typeTableSend<commit_after>var generics;

var inverseTable = {
	'AdminStatus':              'AdminStatusArray',
	'AdminUpdateType':          'AdminUpdateTypeArray',
	'AdminUpdateFrequency':     'AdminUpdateFrequencyArray',
	'AdminCompanyRemoveReason': 'AdminCompanyRemoveReasonArray',
	'Colour':                   'ColourArray',
	'DestType':                 'DestTypeArray',
	'Landscape':                'LandscapeArray',
	'NetworkAction':            'NetworkActionArray',
	'NetworkErrorCode':         'NetworkErrorCodeArray',
	'NetworkLanguage':          'NetworkLanguageArray',
	'VehicleType':              'VehicleTypeArray'
};

module.exports = generics = {};

// Protocol data

// Swaps keys with values
generics.getInversedObject = function(object) {
	var result = {};

	for (var i in object) {
		result[object[i]] = i;
	}

	return result;
};

generics.spec = require("../data/protocol")
for (var i in inverseTable) {
	generics.spec[inverseTable[i]] = generics.getInversedObject(generics.spec[i]);
}

// Date handling

generics.isLeapYear = function(year) {
	return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};

generics.daysInMonth = function(month, year) {
	return [31, this.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

generics.getQuarter = function(month) {
	return Math.floor(month / 3);
};

// Year calculation based on
// http://dev.openttdcoop.org/projects/joan/repository/entry/src/main/java/org/openttd/GameDate.java
generics.gameDateToDate = function(date) {
	var rem, year, month = -1, days = 0;

	// There are 97 leap years in 400 years
	year = 400 * Math.floor(date / (365 * 400 + 97));
	rem  = date % (365 * 400 + 97);

	// There are 24 leap years in 100 years
	year += 100 * Math.floor(rem / (365 * 100 + 24));
	rem  %= 365 * 100 + 24;

	// There is 1 leap year every 4 years
	year += 4 * Math.floor(rem / (365 * 4 + 1));
	rem  %= 365 * 4 + 1;

	// Finish year calculation
	while (rem >= (this.isLeapYear(year) ? 366 : 365)) {
		rem -= this.isLeapYear(year) ? 366 : 365;
		year++;
	}

	// Get month
	do {
		month++;
		rem -=  days;
		days = this.daysInMonth(month, year);
	} while (rem > days);

	// Rem should be day in the month
	return {year: year, month: month, day: rem + 1, quarter: this.getQuarter(month)};
};

// Network stuff

generics.typeTableSend = {
	"uint8":    function(input) {var buffer=new Buffer(1);buffer.writeUInt8   (input, 0); return buffer;},
	"int8":     function(input) {var buffer=new Buffer(1);buffer.writeInt8    (input, 0); return buffer;},
	"uint16be": function(input) {var buffer=new Buffer(2);buffer.writeUInt16BE(input, 0); return buffer;},
	"uint16le": function(input) {var buffer=new Buffer(2);buffer.writeUInt16LE(input, 0); return buffer;},
	"int16be":  function(input) {var buffer=new Buffer(2);buffer.writeInt16BE (input, 0); return buffer;},
	"int16le":  function(input) {var buffer=new Buffer(2);buffer.writeInt16LE (input, 0); return buffer;},
	"uint32be": function(input) {var buffer=new Buffer(4);buffer.writeUInt32BE(input, 0); return buffer;},
	"uint32le": function(input) {var buffer=new Buffer(4);buffer.writeUInt32LE(input, 0); return buffer;},
	"int32be":  function(input) {var buffer=new Buffer(4);buffer.writeInt32BE (input, 0); return buffer;},
	"int32le":  function(input) {var buffer=new Buffer(4);buffer.writeInt32LE (input, 0); return buffer;},
	"floatbe":  function(input) {var buffer=new Buffer(4);buffer.writeFloatBE (input, 0); return buffer;},
	"floatle":  function(input) {var buffer=new Buffer(4);buffer.writeFloatLE (input, 0); return buffer;},
	"doublebe": function(input) {var buffer=new Buffer(8);buffer.writeDoubleBE(input, 0); return buffer;},
	"doublele": function(input) {var buffer=new Buffer(8);buffer.writeDoubleLE(input, 0); return buffer;},
	"bool":     function(input) {var buffer=new Buffer(1);buffer.writeUInt8(input ? 1 : 0, 0); return buffer;},
	"utf8":     function(input) {return new Buffer(input.replace(/\u0000/g, "") + "\u0000", 'utf8');}
};

generics.typeTableReceive = {
	"bool":     function(buffer, offset) {return [buffer.readUInt8(offset) === 1, 1];},
	"uint8":    function(buffer, offset) {return [buffer.readUInt8(offset),       1];},
	"int8":     function(buffer, offset) {return [buffer.readInt8(offset),        1];},
	"uint16be": function(buffer, offset) {return [buffer.readUInt16BE(offset),    2];},
	"uint16le": function(buffer, offset) {return [buffer.readUInt16LE(offset),    2];},
	"int16be":  function(buffer, offset) {return [buffer.readInt16BE(offset),     2];},
	"int16le":  function(buffer, offset) {return [buffer.readInt16LE(offset),     2];},
	"uint32be": function(buffer, offset) {return [buffer.readUInt32BE(offset),    4];},
	"uint32le": function(buffer, offset) {return [buffer.readUInt32LE(offset),    4];},
	"int32be":  function(buffer, offset) {return [buffer.readInt32BE(offset),     4];},
	"int32le":  function(buffer, offset) {return [buffer.readInt32LE(offset),     4];},
	"floatbe":  function(buffer, offset) {return [buffer.readFloatBE(offset),     4];},
	"floatle":  function(buffer, offset) {return [buffer.readFloatLE(offset),     4];},
	"doublebe": function(buffer, offset) {return [buffer.readDoubleBE(offset),    8];},
	"doublele": function(buffer, offset) {return [buffer.readDoubleLE(offset),    8];},
	"uint64be": function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"uint64le": function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"int64be":  function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"int64le":  function(buffer, offset) {var newBuffer=new Buffer(8);buffer.copy(newBuffer,0,offset,offset+8);return [newBuffer, 8];},
	"utf8":     function(buffer, offset) {
		var pos = offset;
		for (;buffer[pos] !== 0x00; pos++) {}
		return [buffer.toString('utf8', offset, pos), pos - offset + 1];
	},
	"protocol": function(buffer, offset) {
		var pos = offset, result = [];
		while (buffer.readUInt8(pos) === 1) {
			result[result.length] = [buffer.readUInt16LE(pos + 1), buffer.readUInt16LE(pos + 3)];
			pos += 5;
		}
		return [result, pos - offset];
	},
	"cmdnames": function(buffer, offset) {
		var pos = offset, pos2, result = [];
		while (buffer.readUInt8(pos) === 1) {
			result[result.length] = [buffer.readUInt16LE(pos + 1)];
			for (pos += 3, pos2 = pos; buffer[pos] !== 0x00; pos++) {}
			result[result.length -1][1] = buffer.toString('utf8', pos2, pos);
			pos++;
		}
		return [result, pos - offset];
	}
};

generics.preparePacket = function(type, format, data) {
	// First 3 bytes represents packet length and type
	var buffer = [new Buffer(3)];

	// Format data in buffers and merge them to the package format
	for (var i = 0, length = Math.min(format.length, data.length); i < length; i++) {
		if (generics.typeTableSend[format[i].type] === null)
			throw "Type " + format[i].type + " not known in send table";

		buffer.push(generics.typeTableSend[format[i].type.toLowerCase()](data[i]));
	}

	buffer = Buffer.concat(buffer);

	// Length check
	if (buffer.length > 1460)
		throw "Message too long";

	// Pre-append length and packet type
	buffer.writeUInt8(type, 2);
	buffer.writeUInt16LE(buffer.length, 0);

	return buffer;
};

generics.extractContent = function(format, content) {
	var data = [], result, offset = 0, type;

	// Extract data given the package format
	for (var i = 0; i < format.length; i++) {
		type = format[i].type.toLowerCase();

		if (generics.typeTableReceive[type] === null)
			throw "unknown data type " + type;

		result = generics.typeTableReceive[type](content, offset);
		data[data.length] = result[0];
		offset           += result[1];
	}

	return data;
};<|endoftext|>


<commit_before>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var ObjectId = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Opportunity = require("./opportunity_model");
var User = require("./user_model");
var Track = require("./track_model");
var Task = require("./task_model");

var TaskSchema   = new Schema({
	name: String,
	category: { type: String, validate: /init|call|email|follow_up|meeting|milestone|site_visit/, index: true, default: "email" },
	due_after_task: { type: ObjectId, ref: "Task" },
	due_after_days: Number,
	user_id: { type: ObjectId, ref: "User", index: true },
	opportunity_id: { type: ObjectId, ref: "Opportunity", index: true },
	track_id: { type: ObjectId, ref: "Track", index: true },
	date_completed: Date,
	completed: { type: Boolean, default: false, index: true },
	notes: [{
		note: String,
		date_created: { type: Date, default: Date.now },
		user_id: { type: ObjectId, ref: "User" }
	}],
	data: { type: Mixed },
	date_created: { type: Date, default: Date.now },
	_owner_id: ObjectId
});

TaskSchema.set("_perms", {
	admin: "crud",
	owner: "cr",
	user: ""
});

module.exports = mongoose.model('Task', TaskSchema);<commit_msg>Add some rules<commit_after>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var ObjectId = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Opportunity = require("./opportunity_model");
var User = require("./user_model");
var Track = require("./track_model");
var Task = require("./task_model");

var TaskSchema   = new Schema({
	name: String,
	category: { type: String, validate: /init|call|email|follow_up|meeting|milestone|site_visit/, index: true, default: "email", required: true },
	due_after_task: { type: ObjectId, ref: "Task" },
	due_after_days: Number,
	user_id: { type: ObjectId, ref: "User", index: true, required: true },
	opportunity_id: { type: ObjectId, ref: "Opportunity", index: true, required: true },
	track_id: { type: ObjectId, ref: "Track", index: true },
	date_completed: Date,
	completed: { type: Boolean, default: false, index: true },
	notes: [{
		note: String,
		date_created: { type: Date, default: Date.now },
		user_id: { type: ObjectId, ref: "User" }
	}],
	data: { type: Mixed },
	date_created: { type: Date, default: Date.now },
	_owner_id: ObjectId
});

TaskSchema.set("_perms", {
	admin: "crud",
	owner: "cr",
	user: ""
});

module.exports = mongoose.model('Task', TaskSchema);<|endoftext|>


<commit_before>'use strict';

export default (array1, array2) => {
  return array1.filter(item => array2.indexOf(item) != -1).length > 0;
}
<commit_msg>Control parameters values in `intersect` method<commit_after>'use strict';

export default (array1 = [], array2 = []) => {
  return array1.filter(item => array2.indexOf(item) != -1).length > 0;
}
<|endoftext|>


<commit_before>var db 					= require('../init_db');
var model 				= require('./jiragation');
var Sequelize 			= db.Sequelize;
var sequelize 			= db.sequelize;

var TimeSheet = function() {

};

// Pull Time Sheet
TimeSheet.getTimeSheet = function(req, callback) {
	// console.log('model - accout');
	var queryString = "SELECT * FROM time_sheet ts WHERE ts.user_id ="+req.decoded.id;

	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
		throw err;
	});

};

TimeSheet.logTaskTime = function(req, callback) {
	sequelize.transaction(function(t){
		return model.jiraAccounts.find({
			where:{
				url:req.body.account_url
			},
			transaction:t
		}).then(function(account){
			return model.timeSheet.create({
				task_id: req.body.task_id,
				account_id: account.id,
				start_time: req.body.start_time,
				end_time: req.body.end_time,
				user_id: req.decoded.id
			},{transaction:t}).then(function(results) {
				return
			}, function(err){
				throw err;
			});
		});
	}).then(function(results){
		return callback(results);
	}).catch(function(error){
		console.log(error);
		return callback(error);
	});
};

//pull time log for specific task_id
TimeSheet.getTaskTime = function(req, callback) {

	var queryString =  " SELECT "
		queryString += " ts.task_id as task_id, ";
		queryString += " ts.start_time as start_time, ";
		queryString += " ts.end_time as end_time, ";
		queryString += " ts.account_id as account_id, ";
		queryString += " ac.user_name as user_name, ";
		queryString += " ac.url as url, ";
		queryString += " ac.account_email as account_email, ";
		queryString += " ac.protocal as protocal ";
		queryString += " FROM time_sheet ts "
		queryString += " JOIN jira_accounts ac ON ac.id = ts.account_id"
		queryString += " WHERE ts.task_id = '" + req.query.task_id + "' "
		queryString += " AND ts.user_id="+req.decoded.id;
	console.log(queryString);

	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
  		// console.log(err);
  		throw err;
  	});
};

TimeSheet.getTrackedTime = function(req, callback) {
	// var earlier_Date =  new Date( res.earlier_time);
	// var later_Date  new Date ( res.later_time);
	var queryString  = " SELECT "
		queryString += " ts.task_id as task_id, ";
		queryString += " ts.start_time as start_time, ";
		queryString += " ts.end_time as end_time, ";
		queryString += " ts.account_id as account_id, ";
		queryString += " ac.user_name as user_name, ";
		queryString += " ac.url as url, ";
		queryString += " ac.account_email as account_email, ";
		queryString += " ac.protocal as protocal ";
		queryString += " FROM time_sheet ts ";
		queryString += " JOIN jira_accounts ac ON ac.id = ts.account_id"
		queryString += " WHERE ts.start_time >= '" + new Date(req.query.earlier_time).getTime() + "' ";
		queryString += " AND ts.start_time <= '" + new Date(req.query.later_time).getTime() + "' ";
		queryString += " AND ts.user_id ="+req.decoded.id;
		console.log(queryString);
	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
  		// console.log(err);
  		throw err;
  	});
};

module.exports = TimeSheet;<commit_msg>Home Udpate: remove console logs in models<commit_after>var db 					= require('../init_db');
var model 				= require('./jiragation');
var Sequelize 			= db.Sequelize;
var sequelize 			= db.sequelize;

var TimeSheet = function() {

};

// Pull Time Sheet
TimeSheet.getTimeSheet = function(req, callback) {
	// console.log('model - accout');
	var queryString = "SELECT * FROM time_sheet ts WHERE ts.user_id ="+req.decoded.id;

	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
		throw err;
	});

};

TimeSheet.logTaskTime = function(req, callback) {
	sequelize.transaction(function(t){
		return model.jiraAccounts.find({
			where:{
				url:req.body.account_url
			},
			transaction:t
		}).then(function(account){
			return model.timeSheet.create({
				task_id: req.body.task_id,
				account_id: account.id,
				start_time: req.body.start_time,
				end_time: req.body.end_time,
				user_id: req.decoded.id
			},{transaction:t}).then(function(results) {
				return
			}, function(err){
				throw err;
			});
		});
	}).then(function(results){
		return callback(results);
	}).catch(function(error){
		console.log(error);
		return callback(error);
	});
};

//pull time log for specific task_id
TimeSheet.getTaskTime = function(req, callback) {

	var queryString =  " SELECT "
		queryString += " ts.task_id as task_id, ";
		queryString += " ts.start_time as start_time, ";
		queryString += " ts.end_time as end_time, ";
		queryString += " ts.account_id as account_id, ";
		queryString += " ac.user_name as user_name, ";
		queryString += " ac.url as url, ";
		queryString += " ac.account_email as account_email, ";
		queryString += " ac.protocal as protocal ";
		queryString += " FROM time_sheet ts "
		queryString += " JOIN jira_accounts ac ON ac.id = ts.account_id"
		queryString += " WHERE ts.task_id = '" + req.query.task_id + "' "
		queryString += " AND ts.user_id="+req.decoded.id;

	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
  		// console.log(err);
  		throw err;
  	});
};

TimeSheet.getTrackedTime = function(req, callback) {
	// var earlier_Date =  new Date( res.earlier_time);
	// var later_Date  new Date ( res.later_time);
	var queryString  = " SELECT "
		queryString += " ts.task_id as task_id, ";
		queryString += " ts.start_time as start_time, ";
		queryString += " ts.end_time as end_time, ";
		queryString += " ts.account_id as account_id, ";
		queryString += " ac.user_name as user_name, ";
		queryString += " ac.url as url, ";
		queryString += " ac.account_email as account_email, ";
		queryString += " ac.protocal as protocal ";
		queryString += " FROM time_sheet ts ";
		queryString += " JOIN jira_accounts ac ON ac.id = ts.account_id"
		queryString += " WHERE ts.start_time >= '" + new Date(req.query.earlier_time).getTime() + "' ";
		queryString += " AND ts.start_time <= '" + new Date(req.query.later_time).getTime() + "' ";
		queryString += " AND ts.user_id ="+req.decoded.id;
	sequelize.query(queryString, { type: Sequelize.QueryTypes.SELECT }).then(function(results){
		callback(results);
		// console.log(results);
	}).catch(function(err){
  		// console.log(err);
  		throw err;
  	});
};

module.exports = TimeSheet;<|endoftext|>


<commit_before>/**
 * Riot public api
 */

// share methods for other riot parts, e.g. compiler
riot.util = { brackets: brackets, tmpl: tmpl }

/**
 * Create a mixin that could be globally shared across all the tags
 */
riot.mixin = (function() {
  var mixins = {},
    globals = mixins[GLOBAL_MIXIN] = {},
    _id = 0

  /**
   * Create/Return a mixin by its name
   * @param   { String }  name - mixin name (global mixin if object)
   * @param   { Object }  mixin - mixin logic
   * @param   { Boolean } g - is global?
   * @returns { Object }  the mixin logic
   */
  return function(name, mixin, g) {
    // Unnamed global
    if (isObject(name)) {
      riot.mixin('__unnamed_'+_id++, name, true)
      return
    }

    var store = g ? globals : mixins

    // Getter
    if (!mixin) return store[name]
    // Setter
    store[name] = extend(store[name] || {}, mixin)
  }

})()

/**
 * Create a new riot tag implementation
 * @param   { String }   name - name/id of the new riot tag
 * @param   { String }   html - tag template
 * @param   { String }   css - custom tag css
 * @param   { String }   attrs - root tag attributes
 * @param   { Function } fn - user function
 * @returns { String } name/id of the tag just created
 */
riot.tag = function(name, html, css, attrs, fn) {
  if (isFunction(attrs)) {
    fn = attrs
    if (/^[\w\-]+\s?=/.test(css)) {
      attrs = css
      css = ''
    } else attrs = ''
  }
  if (css) {
    if (isFunction(css)) fn = css
    else styleManager.add(css)
  }
  name = name.toLowerCase()
  __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
  return name
}

/**
 * Create a new riot tag implementation (for use by the compiler)
 * @param   { String }   name - name/id of the new riot tag
 * @param   { String }   html - tag template
 * @param   { String }   css - custom tag css
 * @param   { String }   attrs - root tag attributes
 * @param   { Function } fn - user function
 * @returns { String } name/id of the tag just created
 */
riot.tag2 = function(name, html, css, attrs, fn) {
  if (css) styleManager.add(css)
  //if (bpair) riot.settings.brackets = bpair
  __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
  return name
}

/**
 * Mount a tag using a specific tag implementation
 * @param   { String } selector - tag DOM selector
 * @param   { String } tagName - tag implementation name
 * @param   { Object } opts - tag logic
 * @returns { Array } new tags instances
 */
riot.mount = function(selector, tagName, opts) {

  var els,
    allTags,
    tags = []

  // helper functions

  function addRiotTags(arr) {
    var list = ''
    each(arr, function (e) {
      if (!/[^-\w]/.test(e)) {
        e = e.trim().toLowerCase()
        list += ',[' + RIOT_TAG_IS + '="' + e + '"],[' + RIOT_TAG + '="' + e + '"]'
      }
    })
    return list
  }

  function selectAllTags() {
    var keys = Object.keys(__tagImpl)
    return keys + addRiotTags(keys)
  }

  function pushTags(root) {
    if (root.tagName) {
      var riotTag = getAttr(root, RIOT_TAG_IS) || getAttr(root, RIOT_TAG)

      // have tagName? force riot-tag to be the same
      if (tagName && riotTag !== tagName) {
        riotTag = tagName
        setAttr(root, RIOT_TAG_IS, tagName)
        setAttr(root, RIOT_TAG, tagName) // this will be removed in riot 3.0.0
      }
      var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts)

      if (tag) tags.push(tag)
    } else if (root.length) {
      each(root, pushTags)   // assume nodeList
    }
  }

  // ----- mount code -----

  // inject styles into DOM
  styleManager.inject()

  if (isObject(tagName)) {
    opts = tagName
    tagName = 0
  }

  // crawl the DOM to find the tag
  if (typeof selector === T_STRING) {
    if (selector === '*')
      // select all the tags registered
      // and also the tags found with the riot-tag attribute set
      selector = allTags = selectAllTags()
    else
      // or just the ones named like the selector
      selector += addRiotTags(selector.split(/, */))

    // make sure to pass always a selector
    // to the querySelectorAll function
    els = selector ? $$(selector) : []
  }
  else
    // probably you have passed already a tag or a NodeList
    els = selector

  // select all the registered and mount them inside their root elements
  if (tagName === '*') {
    // get all custom tags
    tagName = allTags || selectAllTags()
    // if the root els it's just a single tag
    if (els.tagName)
      els = $$(tagName, els)
    else {
      // select all the children for all the different root elements
      var nodeList = []
      each(els, function (_el) {
        nodeList.push($$(tagName, _el))
      })
      els = nodeList
    }
    // get rid of the tagName
    tagName = 0
  }

  pushTags(els)

  return tags
}

/**
 * Update all the tags instances created
 * @returns { Array } all the tags instances
 */
riot.update = function() {
  return each(__virtualDom, function(tag) {
    tag.update()
  })
}

/**
 * Export the Virtual DOM
 */
riot.vdom = __virtualDom

/**
 * Export the Tag constructor
 */
riot.Tag = Tag
<commit_msg>Throw error when referencing an unregistered mixin<commit_after>/**
 * Riot public api
 */

// share methods for other riot parts, e.g. compiler
riot.util = { brackets: brackets, tmpl: tmpl }

/**
 * Create a mixin that could be globally shared across all the tags
 */
riot.mixin = (function() {
  var mixins = {},
    globals = mixins[GLOBAL_MIXIN] = {},
    _id = 0

  /**
   * Create/Return a mixin by its name
   * @param   { String }  name - mixin name (global mixin if object)
   * @param   { Object }  mixin - mixin logic
   * @param   { Boolean } g - is global?
   * @returns { Object }  the mixin logic
   */
  return function(name, mixin, g) {
    // Unnamed global
    if (isObject(name)) {
      riot.mixin('__unnamed_'+_id++, name, true)
      return
    }

    var store = g ? globals : mixins

    // Getter
    if (!mixin) {
      if (typeof store[name] === T_UNDEF) {
        throw new Error('Unregistered mixin: ' + name)
      }
      return store[name]
    }
    // Setter
    store[name] = extend(store[name] || {}, mixin)
  }

})()

/**
 * Create a new riot tag implementation
 * @param   { String }   name - name/id of the new riot tag
 * @param   { String }   html - tag template
 * @param   { String }   css - custom tag css
 * @param   { String }   attrs - root tag attributes
 * @param   { Function } fn - user function
 * @returns { String } name/id of the tag just created
 */
riot.tag = function(name, html, css, attrs, fn) {
  if (isFunction(attrs)) {
    fn = attrs
    if (/^[\w\-]+\s?=/.test(css)) {
      attrs = css
      css = ''
    } else attrs = ''
  }
  if (css) {
    if (isFunction(css)) fn = css
    else styleManager.add(css)
  }
  name = name.toLowerCase()
  __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
  return name
}

/**
 * Create a new riot tag implementation (for use by the compiler)
 * @param   { String }   name - name/id of the new riot tag
 * @param   { String }   html - tag template
 * @param   { String }   css - custom tag css
 * @param   { String }   attrs - root tag attributes
 * @param   { Function } fn - user function
 * @returns { String } name/id of the tag just created
 */
riot.tag2 = function(name, html, css, attrs, fn) {
  if (css) styleManager.add(css)
  //if (bpair) riot.settings.brackets = bpair
  __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
  return name
}

/**
 * Mount a tag using a specific tag implementation
 * @param   { String } selector - tag DOM selector
 * @param   { String } tagName - tag implementation name
 * @param   { Object } opts - tag logic
 * @returns { Array } new tags instances
 */
riot.mount = function(selector, tagName, opts) {

  var els,
    allTags,
    tags = []

  // helper functions

  function addRiotTags(arr) {
    var list = ''
    each(arr, function (e) {
      if (!/[^-\w]/.test(e)) {
        e = e.trim().toLowerCase()
        list += ',[' + RIOT_TAG_IS + '="' + e + '"],[' + RIOT_TAG + '="' + e + '"]'
      }
    })
    return list
  }

  function selectAllTags() {
    var keys = Object.keys(__tagImpl)
    return keys + addRiotTags(keys)
  }

  function pushTags(root) {
    if (root.tagName) {
      var riotTag = getAttr(root, RIOT_TAG_IS) || getAttr(root, RIOT_TAG)

      // have tagName? force riot-tag to be the same
      if (tagName && riotTag !== tagName) {
        riotTag = tagName
        setAttr(root, RIOT_TAG_IS, tagName)
        setAttr(root, RIOT_TAG, tagName) // this will be removed in riot 3.0.0
      }
      var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts)

      if (tag) tags.push(tag)
    } else if (root.length) {
      each(root, pushTags)   // assume nodeList
    }
  }

  // ----- mount code -----

  // inject styles into DOM
  styleManager.inject()

  if (isObject(tagName)) {
    opts = tagName
    tagName = 0
  }

  // crawl the DOM to find the tag
  if (typeof selector === T_STRING) {
    if (selector === '*')
      // select all the tags registered
      // and also the tags found with the riot-tag attribute set
      selector = allTags = selectAllTags()
    else
      // or just the ones named like the selector
      selector += addRiotTags(selector.split(/, */))

    // make sure to pass always a selector
    // to the querySelectorAll function
    els = selector ? $$(selector) : []
  }
  else
    // probably you have passed already a tag or a NodeList
    els = selector

  // select all the registered and mount them inside their root elements
  if (tagName === '*') {
    // get all custom tags
    tagName = allTags || selectAllTags()
    // if the root els it's just a single tag
    if (els.tagName)
      els = $$(tagName, els)
    else {
      // select all the children for all the different root elements
      var nodeList = []
      each(els, function (_el) {
        nodeList.push($$(tagName, _el))
      })
      els = nodeList
    }
    // get rid of the tagName
    tagName = 0
  }

  pushTags(els)

  return tags
}

/**
 * Update all the tags instances created
 * @returns { Array } all the tags instances
 */
riot.update = function() {
  return each(__virtualDom, function(tag) {
    tag.update()
  })
}

/**
 * Export the Virtual DOM
 */
riot.vdom = __virtualDom

/**
 * Export the Tag constructor
 */
riot.Tag = Tag
<|endoftext|>


<commit_before>define(["Tone/core/Tone"], function(Tone){

	"use strict";

	/**
	 *  @class  Buffer loading and storage. Tone.Buffer will load and store the buffers
	 *          in the same data structure they were given in the argument. If given
	 *          a string, this._buffer will equal an AudioBuffer. If constructed
	 *          with an array, the samples will be placed in an array in the same
	 *          order.
	 *
	 *  @constructor
	 *  @param {AudioBuffer|string} url the url to load, or the audio buffer to set
	 */
	Tone.Buffer = function(){

		var options = this.optionsObject(arguments, ["url", "onload"], Tone.Buffer.defaults);

		/**
		 *  stores the loaded AudioBuffer
		 *  @type {AudioBuffer}
		 *  @private
		 */
		this._buffer = null;

		/**
		 *  the url of the buffer. `undefined` if it was
		 *  constructed with a buffer
		 *  @type {string}
		 *  @readOnly
		 */
		this.url = undefined;

		/**
		 *  the callback to invoke when everything is loaded
		 *  @type {function}
		 */
		this.onload = options.onload;

		if (options.url instanceof AudioBuffer){
			this._buffer.set(options.url);
			this.onload(this);
		} else if (typeof options.url === "string"){
			this.url = options.url;
			Tone.Buffer._addToQueue(options.url, this);
		}
	};

	Tone.extend(Tone.Buffer);

	/**
	 *  the default parameters
	 *
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.Buffer.defaults = {
		"url" : undefined,
		"onload" : function(){},
	};

	/**
	 *  set the buffer
	 *  @param {AudioBuffer|Tone.Buffer} buffer the buffer
	 *  @returns {Tone.Buffer} `this`
	 */
	Tone.Buffer.prototype.set = function(buffer){
		if (buffer instanceof Tone.Buffer){
			this._buffer = buffer.get();
		} else {
			this._buffer = buffer;
		}
		return this;
	};

	/**
	 *  @return {AudioBuffer} the audio buffer
	 */
	Tone.Buffer.prototype.get = function(){
		return this._buffer;
	};

	/**
	 *  @param {string} url the url to load
	 *  @param {function=} callback the callback to invoke on load.
	 *                              don't need to set if `onload` is
	 *                              already set.
	 *  @returns {Tone.Buffer} `this`
	 */
	Tone.Buffer.prototype.load = function(url, callback){
		this.url = url;
		this.onload = this.defaultArg(callback, this.onload);
		Tone.Buffer._addToQueue(url, this);
		return this;
	};

	/**
	 *  dispose and disconnect
	 *  @private
	 */
	Tone.Buffer.prototype._dispose = function(){
		Tone.Buffer._removeFromQueue(this);
		this._buffer = null;
		this.onload = null;
	};

	/**
	 * the duration of the buffer
	 * @memberOf Tone.Buffer#
	 * @type {number}
	 * @name duration
	 * @readOnly
	 */
	Object.defineProperty(Tone.Buffer.prototype, "duration", {
		get : function(){
			if (this._buffer){
				return this._buffer.duration;
			} else {
				return 0;
			}
		},
	});

	///////////////////////////////////////////////////////////////////////////
	// STATIC METHODS
	///////////////////////////////////////////////////////////////////////////

	/**
	 *  the static queue for all of the xhr requests
	 *  @type {Array}
	 *  @private
	 */
	Tone.Buffer._queue = [];

	/**
	 *  the array of current downloads
	 *  @type {Array}
	 *  @private
	 */
	Tone.Buffer._currentDownloads = [];

	/**
	 *  the total number of downloads
	 *  @type {number}
	 *  @private
	 */
	Tone.Buffer._totalDownloads = 0;

	/**
	 *  the maximum number of simultaneous downloads
	 *  @static
	 *  @type {number}
	 */
	Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS = 6;

	/**
	 *  Adds a file to be loaded to the loading queue
	 *  @param   {string}   url      the url to load
	 *  @param   {function} callback the callback to invoke once it's loaded
	 *  @private
	 */
	Tone.Buffer._addToQueue = function(url, buffer){
		Tone.Buffer._queue.push({
			url : url,
			Buffer : buffer,
			progress : 0,
			xhr : null
		});
		this._totalDownloads++;
		Tone.Buffer._next();
	};

	/**
	 *  Remove an object from the queue's (if it's still there)
	 *  Abort the XHR if it's in progress
	 *  @param {Tone.Buffer} buffer the buffer to remove
	 *  @private
	 */
	Tone.Buffer._removeFromQueue = function(buffer){
		var i;
		for (i = 0; i < Tone.Buffer._queue.length; i++){
			var q = Tone.Buffer._queue[i];
			if (q.Buffer === buffer){
				Tone.Buffer._queue.splice(i, 1);
			}
		}
		for (i = 0; i < Tone.Buffer._currentDownloads.length; i++){
			var dl = Tone.Buffer._currentDownloads[i];
			if (dl.Buffer === buffer){
				Tone.Buffer._currentDownloads.splice(i, 1);
				dl.xhr.abort();
				dl.xhr.onprogress = null;
				dl.xhr.onload = null;
				dl.xhr.onerror = null;
			}
		}
	};

	/**
	 *  load the next buffer in the queue
	 *  @private
	 */
	Tone.Buffer._next = function(){
		if (Tone.Buffer._queue.length > 0){
			if (Tone.Buffer._currentDownloads.length < Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS){
				var next = Tone.Buffer._queue.shift();
				Tone.Buffer._currentDownloads.push(next);
				next.xhr = Tone.Buffer.load(next.url, function(buffer){
					//remove this one from the queue
					var index = Tone.Buffer._currentDownloads.indexOf(next);
					Tone.Buffer._currentDownloads.splice(index, 1);
					next.Buffer.set(buffer);
					next.Buffer.onload(next.Buffer);
					Tone.Buffer._onprogress();
					Tone.Buffer._next();
				});
				next.xhr.onprogress = function(event){
					next.progress = event.loaded / event.total;
					Tone.Buffer._onprogress();
				};
				next.xhr.onerror = Tone.Buffer.onerror;
			}
		} else if (Tone.Buffer._currentDownloads.length === 0){
			Tone.Buffer.onload();
			//reset the downloads
			Tone.Buffer._totalDownloads = 0;
		}
	};

	/**
	 *  internal progress event handler
	 *  @private
	 */
	Tone.Buffer._onprogress = function(){
		var curretDownloadsProgress = 0;
		var currentDLLen = Tone.Buffer._currentDownloads.length;
		var inprogress = 0;
		if (currentDLLen > 0){
			for (var i = 0; i < currentDLLen; i++){
				var dl = Tone.Buffer._currentDownloads[i];
				curretDownloadsProgress += dl.progress;
			}
			inprogress = curretDownloadsProgress;
		}
		var currentDownloadProgress = currentDLLen - inprogress;
		var completed = Tone.Buffer._totalDownloads - Tone.Buffer._queue.length - currentDownloadProgress;
		Tone.Buffer.onprogress(completed / Tone.Buffer._totalDownloads);
	};

	/**
	 *  makes an xhr reqest for the selected url
	 *  Load the audio file as an audio buffer.
	 *  Decodes the audio asynchronously and invokes
	 *  the callback once the audio buffer loads.
	 *  @param {string} url the url of the buffer to load.
	 *                      filetype support depends on the
	 *                      browser.
	 *  @param {function} callback function
	 *  @returns {XMLHttpRequest} returns the XHR
	 */
	Tone.Buffer.load = function(url, callback){
		var request = new XMLHttpRequest();
		request.open("GET", url, true);
		request.responseType = "arraybuffer";
		// decode asynchronously
		request.onload = function() {
			Tone.context.decodeAudioData(request.response, function(buff) {
				if(!buff){
					throw new Error("could not decode audio data:" + url);
				}
				callback(buff);
			});
		};
		//send the request
		request.send();
		return request;
	};

	/**
	 *  callback when all of the buffers in the queue have loaded
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onload = function(){};

	/**
	 *  callback with the progress of all of the loads in the queue
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onprogress = function(){};

	/**
	 *  callback if one of the buffers in the queue encounters an error
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onerror = function(){};

	return Tone.Buffer;
});<commit_msg>loaded flag<commit_after>define(["Tone/core/Tone"], function(Tone){

	"use strict";

	/**
	 *  @class  Buffer loading and storage. Tone.Buffer will load and store the buffers
	 *          in the same data structure they were given in the argument. If given
	 *          a string, this._buffer will equal an AudioBuffer. If constructed
	 *          with an array, the samples will be placed in an array in the same
	 *          order.
	 *
	 *  @constructor
	 *  @param {AudioBuffer|string} url the url to load, or the audio buffer to set
	 */
	Tone.Buffer = function(){

		var options = this.optionsObject(arguments, ["url", "onload"], Tone.Buffer.defaults);

		/**
		 *  stores the loaded AudioBuffer
		 *  @type {AudioBuffer}
		 *  @private
		 */
		this._buffer = null;

		/**
		 *  the url of the buffer. `undefined` if it was
		 *  constructed with a buffer
		 *  @type {string}
		 *  @readOnly
		 */
		this.url = undefined;

		/**
		 *  indicates if the buffer is loaded or not
		 *  @type {boolean}
		 *  @readOnly
		 */
		this.loaded = false;

		/**
		 *  the callback to invoke when everything is loaded
		 *  @type {function}
		 */
		this.onload = function(arg){
			this.loaded = true;
			options.onload(arg);
		}.bind(this);

		if (options.url instanceof AudioBuffer){
			this._buffer.set(options.url);
			this.onload(this);
		} else if (typeof options.url === "string"){
			this.url = options.url;
			Tone.Buffer._addToQueue(options.url, this);
		}
	};

	Tone.extend(Tone.Buffer);

	/**
	 *  the default parameters
	 *
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.Buffer.defaults = {
		"url" : undefined,
		"onload" : function(){},
	};

	/**
	 *  set the buffer
	 *  @param {AudioBuffer|Tone.Buffer} buffer the buffer
	 *  @returns {Tone.Buffer} `this`
	 */
	Tone.Buffer.prototype.set = function(buffer){
		if (buffer instanceof Tone.Buffer){
			this._buffer = buffer.get();
		} else {
			this._buffer = buffer;
		}
		return this;
	};

	/**
	 *  @return {AudioBuffer} the audio buffer
	 */
	Tone.Buffer.prototype.get = function(){
		return this._buffer;
	};

	/**
	 *  @param {string} url the url to load
	 *  @param {function=} callback the callback to invoke on load.
	 *                              don't need to set if `onload` is
	 *                              already set.
	 *  @returns {Tone.Buffer} `this`
	 */
	Tone.Buffer.prototype.load = function(url, callback){
		this.url = url;
		this.onload = this.defaultArg(callback, this.onload);
		Tone.Buffer._addToQueue(url, this);
		return this;
	};

	/**
	 *  dispose and disconnect
	 *  @private
	 */
	Tone.Buffer.prototype._dispose = function(){
		Tone.Buffer._removeFromQueue(this);
		this._buffer = null;
		this.onload = null;
	};

	/**
	 * the duration of the buffer
	 * @memberOf Tone.Buffer#
	 * @type {number}
	 * @name duration
	 * @readOnly
	 */
	Object.defineProperty(Tone.Buffer.prototype, "duration", {
		get : function(){
			if (this._buffer){
				return this._buffer.duration;
			} else {
				return 0;
			}
		},
	});

	///////////////////////////////////////////////////////////////////////////
	// STATIC METHODS
	///////////////////////////////////////////////////////////////////////////

	/**
	 *  the static queue for all of the xhr requests
	 *  @type {Array}
	 *  @private
	 */
	Tone.Buffer._queue = [];

	/**
	 *  the array of current downloads
	 *  @type {Array}
	 *  @private
	 */
	Tone.Buffer._currentDownloads = [];

	/**
	 *  the total number of downloads
	 *  @type {number}
	 *  @private
	 */
	Tone.Buffer._totalDownloads = 0;

	/**
	 *  the maximum number of simultaneous downloads
	 *  @static
	 *  @type {number}
	 */
	Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS = 6;

	/**
	 *  Adds a file to be loaded to the loading queue
	 *  @param   {string}   url      the url to load
	 *  @param   {function} callback the callback to invoke once it's loaded
	 *  @private
	 */
	Tone.Buffer._addToQueue = function(url, buffer){
		Tone.Buffer._queue.push({
			url : url,
			Buffer : buffer,
			progress : 0,
			xhr : null
		});
		this._totalDownloads++;
		Tone.Buffer._next();
	};

	/**
	 *  Remove an object from the queue's (if it's still there)
	 *  Abort the XHR if it's in progress
	 *  @param {Tone.Buffer} buffer the buffer to remove
	 *  @private
	 */
	Tone.Buffer._removeFromQueue = function(buffer){
		var i;
		for (i = 0; i < Tone.Buffer._queue.length; i++){
			var q = Tone.Buffer._queue[i];
			if (q.Buffer === buffer){
				Tone.Buffer._queue.splice(i, 1);
			}
		}
		for (i = 0; i < Tone.Buffer._currentDownloads.length; i++){
			var dl = Tone.Buffer._currentDownloads[i];
			if (dl.Buffer === buffer){
				Tone.Buffer._currentDownloads.splice(i, 1);
				dl.xhr.abort();
				dl.xhr.onprogress = null;
				dl.xhr.onload = null;
				dl.xhr.onerror = null;
			}
		}
	};

	/**
	 *  load the next buffer in the queue
	 *  @private
	 */
	Tone.Buffer._next = function(){
		if (Tone.Buffer._queue.length > 0){
			if (Tone.Buffer._currentDownloads.length < Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS){
				var next = Tone.Buffer._queue.shift();
				Tone.Buffer._currentDownloads.push(next);
				next.xhr = Tone.Buffer.load(next.url, function(buffer){
					//remove this one from the queue
					var index = Tone.Buffer._currentDownloads.indexOf(next);
					Tone.Buffer._currentDownloads.splice(index, 1);
					next.Buffer.set(buffer);
					next.Buffer.onload(next.Buffer);
					Tone.Buffer._onprogress();
					Tone.Buffer._next();
				});
				next.xhr.onprogress = function(event){
					next.progress = event.loaded / event.total;
					Tone.Buffer._onprogress();
				};
				next.xhr.onerror = Tone.Buffer.onerror;
			}
		} else if (Tone.Buffer._currentDownloads.length === 0){
			Tone.Buffer.onload();
			//reset the downloads
			Tone.Buffer._totalDownloads = 0;
		}
	};

	/**
	 *  internal progress event handler
	 *  @private
	 */
	Tone.Buffer._onprogress = function(){
		var curretDownloadsProgress = 0;
		var currentDLLen = Tone.Buffer._currentDownloads.length;
		var inprogress = 0;
		if (currentDLLen > 0){
			for (var i = 0; i < currentDLLen; i++){
				var dl = Tone.Buffer._currentDownloads[i];
				curretDownloadsProgress += dl.progress;
			}
			inprogress = curretDownloadsProgress;
		}
		var currentDownloadProgress = currentDLLen - inprogress;
		var completed = Tone.Buffer._totalDownloads - Tone.Buffer._queue.length - currentDownloadProgress;
		Tone.Buffer.onprogress(completed / Tone.Buffer._totalDownloads);
	};

	/**
	 *  makes an xhr reqest for the selected url
	 *  Load the audio file as an audio buffer.
	 *  Decodes the audio asynchronously and invokes
	 *  the callback once the audio buffer loads.
	 *  @param {string} url the url of the buffer to load.
	 *                      filetype support depends on the
	 *                      browser.
	 *  @param {function} callback function
	 *  @returns {XMLHttpRequest} returns the XHR
	 */
	Tone.Buffer.load = function(url, callback){
		var request = new XMLHttpRequest();
		request.open("GET", url, true);
		request.responseType = "arraybuffer";
		// decode asynchronously
		request.onload = function() {
			Tone.context.decodeAudioData(request.response, function(buff) {
				if(!buff){
					throw new Error("could not decode audio data:" + url);
				}
				callback(buff);
			});
		};
		//send the request
		request.send();
		return request;
	};

	/**
	 *  callback when all of the buffers in the queue have loaded
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onload = function(){};

	/**
	 *  callback with the progress of all of the loads in the queue
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onprogress = function(){};

	/**
	 *  callback if one of the buffers in the queue encounters an error
	 *  @static
	 *  @type {function}
	 */
	Tone.Buffer.onerror = function(){};

	return Tone.Buffer;
});<|endoftext|>


<commit_before>import backendServices from 'platform/user/profile/constants/backendServices';

import { VET360_INITIALIZATION_STATUS, INIT_VET360_ID } from './constants';

import { isVet360Configured } from './util/local-vet360';

import { isFailedTransaction, isPendingTransaction } from './util/transactions';

export function selectIsVet360AvailableForUser(state) {
  if (!isVet360Configured()) return true; // returns true if on localhost
  return state.user.profile.services.includes(backendServices.VET360);
}

export function selectVet360Field(state, fieldName) {
  return state.user.profile.vet360[fieldName];
}

export function selectVet360Transaction(state, fieldName) {
  const {
    vet360: {
      transactions,
      fieldTransactionMap: { [fieldName]: transactionRequest = null },
    },
  } = state;

  let transaction = null;

  if (transactionRequest && transactionRequest.transactionId) {
    transaction = transactions.find(
      t => t.data.attributes.transactionId === transactionRequest.transactionId,
    );
  }

  return {
    transactionRequest,
    transaction,
  };
}

export function selectVet360FailedTransactions(state) {
  return state.vet360.transactions.filter(isFailedTransaction);
}

export function selectMostRecentErroredTransaction(state) {
  const {
    vet360: {
      transactions,
      metadata: { mostRecentErroredTransactionId },
    },
  } = state;

  let transaction = null;
  if (mostRecentErroredTransactionId) {
    transaction = transactions.find(
      t => t.data.attributes.transactionId === mostRecentErroredTransactionId,
    );
  }
  return transaction;
}

export function selectVet360PendingCategoryTransactions(state, type) {
  const {
    vet360: { transactions, fieldTransactionMap },
  } = state;

  const existsWithinFieldTransactionMap = transaction => {
    const transactionId = transaction.data.attributes.transactionId;

    return Object.keys(fieldTransactionMap).some(fieldName => {
      const transactionRequest = fieldTransactionMap[fieldName];
      return transactionRequest.transactionId === transactionId;
    });
  };

  return transactions
    .filter(
      transaction =>
        // Do the actual category-type filter.
        transaction.data.attributes.type === type,
    )
    .filter(transaction =>
      // Filter to transaction with the pending status
      isPendingTransaction(transaction),
    )
    .filter(
      transaction =>
        // If the transaction has corresponding transaction information in the fieldTransactionMap,
        // then we know which field that transaction belongs. In this case, we ignore it at the
        // category-level.
        !existsWithinFieldTransactionMap(transaction),
    );
}

export function selectEditedFormField(state, fieldName) {
  return state.vet360.formFields[fieldName];
}

export function selectCurrentlyOpenEditModal(state) {
  return state.vet360.modal;
}

export function selectAddressValidation(state) {
  return state.vet360?.addressValidation || {};
}

export function selectAddressValidationType(state) {
  return selectAddressValidation(state).addressValidationType;
}

export function selectVet360InitializationStatus(state) {
  let status = VET360_INITIALIZATION_STATUS.UNINITIALIZED;

  const { transaction, transactionRequest } = selectVet360Transaction(
    state,
    INIT_VET360_ID,
  );
  const isReady = selectIsVet360AvailableForUser(state);
  let isPending = false;
  let isFailure = false;

  if (transactionRequest) {
    isPending =
      transactionRequest.isPending || isPendingTransaction(transaction);
    isFailure = transactionRequest.isFailed || isFailedTransaction(transaction);
  }

  if (isReady) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZED;
  } else if (isPending) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZING;
  } else if (isFailure) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZATION_FAILURE;
  }

  return {
    status,
    transaction,
    transactionRequest,
  };
}
<commit_msg>Use selectors (#14363)<commit_after>import backendServices from 'platform/user/profile/constants/backendServices';

import { selectAvailableServices, selectVet360 } from 'platform/user/selectors';
import { VET360_INITIALIZATION_STATUS, INIT_VET360_ID } from './constants';

import { isVet360Configured } from './util/local-vet360';

import { isFailedTransaction, isPendingTransaction } from './util/transactions';

export function selectIsVet360AvailableForUser(state) {
  if (!isVet360Configured()) return true; // returns true if on localhost
  return selectAvailableServices(state).includes(backendServices.VET360);
}

export function selectVet360Field(state, fieldName) {
  return selectVet360(state)[fieldName];
}

export function selectVet360Transaction(state, fieldName) {
  const {
    vet360: {
      transactions,
      fieldTransactionMap: { [fieldName]: transactionRequest = null },
    },
  } = state;

  let transaction = null;

  if (transactionRequest && transactionRequest.transactionId) {
    transaction = transactions.find(
      t => t.data.attributes.transactionId === transactionRequest.transactionId,
    );
  }

  return {
    transactionRequest,
    transaction,
  };
}

export function selectVet360FailedTransactions(state) {
  return state.vet360.transactions.filter(isFailedTransaction);
}

export function selectMostRecentErroredTransaction(state) {
  const {
    vet360: {
      transactions,
      metadata: { mostRecentErroredTransactionId },
    },
  } = state;

  let transaction = null;
  if (mostRecentErroredTransactionId) {
    transaction = transactions.find(
      t => t.data.attributes.transactionId === mostRecentErroredTransactionId,
    );
  }
  return transaction;
}

export function selectVet360PendingCategoryTransactions(state, type) {
  const {
    vet360: { transactions, fieldTransactionMap },
  } = state;

  const existsWithinFieldTransactionMap = transaction => {
    const transactionId = transaction.data.attributes.transactionId;

    return Object.keys(fieldTransactionMap).some(fieldName => {
      const transactionRequest = fieldTransactionMap[fieldName];
      return transactionRequest.transactionId === transactionId;
    });
  };

  return transactions
    .filter(
      transaction =>
        // Do the actual category-type filter.
        transaction.data.attributes.type === type,
    )
    .filter(transaction =>
      // Filter to transaction with the pending status
      isPendingTransaction(transaction),
    )
    .filter(
      transaction =>
        // If the transaction has corresponding transaction information in the fieldTransactionMap,
        // then we know which field that transaction belongs. In this case, we ignore it at the
        // category-level.
        !existsWithinFieldTransactionMap(transaction),
    );
}

export function selectEditedFormField(state, fieldName) {
  return state.vet360.formFields[fieldName];
}

export function selectCurrentlyOpenEditModal(state) {
  return state.vet360.modal;
}

export function selectAddressValidation(state) {
  return state.vet360?.addressValidation || {};
}

export function selectAddressValidationType(state) {
  return selectAddressValidation(state).addressValidationType;
}

export function selectVet360InitializationStatus(state) {
  let status = VET360_INITIALIZATION_STATUS.UNINITIALIZED;

  const { transaction, transactionRequest } = selectVet360Transaction(
    state,
    INIT_VET360_ID,
  );
  const isReady = selectIsVet360AvailableForUser(state);
  let isPending = false;
  let isFailure = false;

  if (transactionRequest) {
    isPending =
      transactionRequest.isPending || isPendingTransaction(transaction);
    isFailure = transactionRequest.isFailed || isFailedTransaction(transaction);
  }

  if (isReady) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZED;
  } else if (isPending) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZING;
  } else if (isFailure) {
    status = VET360_INITIALIZATION_STATUS.INITIALIZATION_FAILURE;
  }

  return {
    status,
    transaction,
    transactionRequest,
  };
}
<|endoftext|>


<commit_before>'use strict';

var lint = require('./_lint');

//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('empty line between blocks - scss', function () {
  it('without comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(3, data.warningCount);
      done();
    });
  });

  it('without comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(22, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(8, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(9, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(25, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(26, data.warningCount);
      done();
    });
  });
});

//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('empty line between blocks - sass', function () {
  it('without comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(9, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(9, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(23, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(23, data.warningCount);
      done();
    });
  });
});
<commit_msg>:bug: Correct tests for empty-line-between-blocks rule<commit_after>'use strict';

var lint = require('./_lint');

//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('empty line between blocks - scss', function () {
  it('without comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(3, data.warningCount);
      done();
    });
  });

  it('without comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(22, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(8, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(9, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(25, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.scss');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(26, data.warningCount);
      done();
    });
  });
});

//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('empty line between blocks - sass', function () {
  it('without comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(6, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('without comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-between-blocks.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(17, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': 1
    }, function (data) {
      lint.assert.equal(10, data.warningCount);
      done();
    });
  });

  it('with comments - [include: true, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': true,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(10, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: true]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': true
        }
      ]
    }, function (data) {
      lint.assert.equal(23, data.warningCount);
      done();
    });
  });

  it('with comments - [include: false, allow-single-line-rulesets: false]', function (done) {
    var file = lint.file('empty-line-with-comments.sass');

    lint.test(file, {
      'empty-line-between-blocks': [
        1,
        {
          'include': false,
          'allow-single-line-rulesets': false
        }
      ]
    }, function (data) {
      lint.assert.equal(23, data.warningCount);
      done();
    });
  });
});
<|endoftext|>


<commit_before>var Handlebars = require('handlebars')
var fs = require('fs')
var glob = require('glob')

var layout = fs.readFileSync(__dirname + '/layout.hbs').toString()
var thefiles = []

// Take in a language type if any
var lang = process.argv[2]
var rawFiles = __dirname + (lang ? '/raw-content-' + lang + '/' : '/raw-content/')
var builtContent = __dirname + (lang ? '/challenges-' + lang + '/' : '/challenges/')

// I can probably use glob better to avoid
// finding the right files within the files
glob("*.html", {cwd: rawFiles}, function (err, files) {
  thefiles = files
  if (err) return console.log(err)
  // var matches = files.map(function(file) {
  //   if (file.match('guide/raw-content/')) {
  //     return file
  //   }
  // })
  buildPage(files)
})

function buildPage(files) {
  files.forEach(function(file) {
    // shouldn't have to do this if my
    // mapping were correct
    if (!file) return
    var content = {
      header: buildHeader(file),
      footer: buildFooter(file),
      body: fs.readFileSync(rawFiles + file).toString()
    }
    var shortname = makeShortname(file)
    var template = Handlebars.compile(layout)
    var final = template(content)
    fs.writeFileSync(builtContent + shortname + 'html', final)
  })
  // hard coded right now because, reasons
  console.log("Built!")
}

function makeShortname(filename) {
  // FROM guide/raw-content/10_merge_tada.html
  // TO merge_tada.
    return filename.split('/').pop().split('_')
      .slice(1).join('_').replace('html', '')
}

function makeTitleName(filename) {
  var short = makeShortname(filename).split('_')
    .join(' ').replace('.', '')
  return grammarize(short)
}

function buildHeader(filename) {
  var num = filename.split('/').pop().split('_')[0]
  var title = makeTitleName(filename)
  var source = fs.readFileSync(__dirname + '/partials/header.html').toString()
  var template = Handlebars.compile(source)
  var content = {
    challengetitle: title,
    challengenumber: num
    lang: lang ? '-' + lang : ''
  }
  return template(content)
}

function grammarize(name) {
  var correct = name
  var wrongWords = ['arent', 'githubbin', 'its']
  var rightWords = ["aren't", "GitHubbin", "it's"]

  wrongWords.forEach(function(word, i) {
    if (name.match(word)) {
      correct = name.replace(word, rightWords[i])
    }
  })
  return correct
}

function buildFooter(file) {
  var num = file.split('/').pop().split('_')[0]
  var data = getPrevious(num)
  data.lang = lang ? '-' + lang : ''
  var source = fs.readFileSync(__dirname + '/partials/footer.html').toString()
  var template = Handlebars.compile(source)
  return template(data)
}

function getPrevious(num) {
  var pre = parseInt(num) - 1
  var next = parseInt(num) + 1
  var preurl = ''
  var prename = ''
  var nexturl = ''
  var nextname = ''
  thefiles.forEach(function(file) {
    if (pre === 0) {
      prename = "All Challenges"
      preurl = "../index.html"
    } else if (file.match(pre)) {
      prename = makeTitleName(file)
      var getridof = pre + '_'
      preurl = file.replace(getridof, '')
    }
    if (next === 12) {
      nextname = "Done!"
      nexturl = '../index.html'
    } else if (file.match(next)) {
      nextname = makeTitleName(file)
      var getridof = next + '_'
      nexturl = file.replace(getridof, '')
    }
  })
  return {prename: prename, preurl: preurl,
      nextname: nextname, nexturl: nexturl}
}
<commit_msg>fix index link in pre/next on lang pages<commit_after>var Handlebars = require('handlebars')
var fs = require('fs')
var glob = require('glob')

var layout = fs.readFileSync(__dirname + '/layout.hbs').toString()
var thefiles = []

// Take in a language type if any
var lang = process.argv[2]
var rawFiles = __dirname + (lang ? '/raw-content-' + lang + '/' : '/raw-content/')
var builtContent = __dirname + (lang ? '/challenges-' + lang + '/' : '/challenges/')

// I can probably use glob better to avoid
// finding the right files within the files
glob("*.html", {cwd: rawFiles}, function (err, files) {
  thefiles = files
  if (err) return console.log(err)
  // var matches = files.map(function(file) {
  //   if (file.match('guide/raw-content/')) {
  //     return file
  //   }
  // })
  buildPage(files)
})

function buildPage(files) {
  files.forEach(function(file) {
    // shouldn't have to do this if my
    // mapping were correct
    if (!file) return
    var content = {
      header: buildHeader(file),
      footer: buildFooter(file),
      body: fs.readFileSync(rawFiles + file).toString()
    }
    var shortname = makeShortname(file)
    var template = Handlebars.compile(layout)
    var final = template(content)
    fs.writeFileSync(builtContent + shortname + 'html', final)
  })
  // hard coded right now because, reasons
  console.log("Built!")
}

function makeShortname(filename) {
  // FROM guide/raw-content/10_merge_tada.html
  // TO merge_tada.
    return filename.split('/').pop().split('_')
      .slice(1).join('_').replace('html', '')
}

function makeTitleName(filename) {
  var short = makeShortname(filename).split('_')
    .join(' ').replace('.', '')
  return grammarize(short)
}

function buildHeader(filename) {
  var num = filename.split('/').pop().split('_')[0]
  var title = makeTitleName(filename)
  var source = fs.readFileSync(__dirname + '/partials/header.html').toString()
  var template = Handlebars.compile(source)
  var content = {
    challengetitle: title,
    challengenumber: num
    lang: lang ? '-' + lang : ''
  }
  return template(content)
}

function grammarize(name) {
  var correct = name
  var wrongWords = ['arent', 'githubbin', 'its']
  var rightWords = ["aren't", "GitHubbin", "it's"]

  wrongWords.forEach(function(word, i) {
    if (name.match(word)) {
      correct = name.replace(word, rightWords[i])
    }
  })
  return correct
}

function buildFooter(file) {
  var num = file.split('/').pop().split('_')[0]
  var data = getPrevious(num)
  data.lang = lang ? '-' + lang : ''
  var source = fs.readFileSync(__dirname + '/partials/footer.html').toString()
  var template = Handlebars.compile(source)
  return template(data)
}

function getPrevious(num) {
  var pre = parseInt(num) - 1
  var next = parseInt(num) + 1
  var preurl = ''
  var prename = ''
  var nexturl = ''
  var nextname = ''
  thefiles.forEach(function(file) {
    if (pre === 0) {
      prename = "All Challenges"
      preurl = lang ? '../index-' + lang + '.html' : '../index.html'
    } else if (file.match(pre)) {
      prename = makeTitleName(file)
      var getridof = pre + '_'
      preurl = file.replace(getridof, '')
    }
    if (next === 12) {
      nextname = "Done!"
      nexturl = lang ? '../index-' + lang + '.html' : '../index.html'
    } else if (file.match(next)) {
      nextname = makeTitleName(file)
      var getridof = next + '_'
      nexturl = file.replace(getridof, '')
    }
  })
  return {prename: prename, preurl: preurl,
      nextname: nextname, nexturl: nexturl}
}
<|endoftext|>


<commit_before>var path       = require('path');
var urlHelper  = require("url");
var fs         = require('fs');
var connect    = require('connect')
var http       = require('http');
var config     = require("./config");
var dispatcher = require('./dispatcher');

//icecream exports
var icecream = module.exports = {
    //Server
    createServer : function(){
        this.init();

        dispatcher.context = this;
        //this.server = http.createServer(dispatcher.run);
        this.server = connect();
        return this;
    },
    init : function(){
        this.engines    = {};
        this.config     = {};
        this.viewCaches = {};

        //add jade engine
        this.engine('jade', require('jade').renderFile);
        this.engine('ejs', require('ejs').renderFile);
    },
    use : function(func){
        this.server.use(func);
        return this;
    },
    listen : function(port){
        this.server.use(dispatcher.run);
        this.server.listen(port);
        return this;
    },
    //Configurations
    get : function(key){
        return this.config[key];
    },
    set : function(key,val){
        this.config[key] = val;
    },
    engine : function(ext,engine){
        this.engines[ext] = engine;
    }
}

//addtions to prototype
require('./request');
require('./response');
<commit_msg>update<commit_after>var path       = require('path');
var urlHelper  = require("url");
var fs         = require('fs');
var connect    = require('connect')
var http       = require('http');
var config     = require("./config");
var dispatcher = require('./dispatcher');

//icecream exports
var icecream = module.exports = {
    //Server
    createServer : function(){
        this.init();

        dispatcher.context = this;
        //this.server = http.createServer(dispatcher.run);
        this.server = connect();
        return this;
    },
    init : function(){
        this.engines    = {};
        this.config     = {};
        this.viewCaches = {};

        //add jade engine
        this.engine('jade', require('jade').renderFile);
        this.engine('ejs', require('ejs').renderFile);
    },
    use : function(func){
        this.server.use(func);
        return this;
    },
    listen : function(port){
        var cluster = require('cluster');
        this.server.use(dispatcher.run);
        cluster(this.server).listen(port);
        return this;
    },
    //Configurations
    get : function(key){
        return this.config[key];
    },
    set : function(key,val){
        this.config[key] = val;
    },
    engine : function(ext,engine){
        this.engines[ext] = engine;
    }
}

//addtions to prototype
require('./request');
require('./response');
<|endoftext|>