<commit_before>
/**
  REQ_CONTEX
        1000 -> signup
        2000 -> signin
        3000 -> account_verify
        4000 -> recovery_password

  REQ_ACTION
        1000:1010 -> createNewUser

        2000:2010 -> login
        2000:2020 -> logout

        3000:3010 -> checkAccount
        3000:3020 -> validateAccountEmail
        3000:3030 -> validateAccountCode

        4000:4010 -> recoveryPasswordEmail
        4000:4020 -> recoveryPasswordCode
        4000:4030 -> recoveryPasswordReset

 */

const AuthenticationController = require('./AuthenticationController')
const AccountPolicy = require('../policies/AccountPolicy')
const main = this
main['httpRequest'] = null
main['httpResponse'] = null
main['REQ_CONTEX'] = 0
main['REQ_ACTION'] = 0
main['REQ_INPUTS'] = {}

function preparams () {
  let msg = null
  if (!main.httpRequest) { msg = 'Error [Http] [missing httpRequest]' }
  if (!main.httpResponse) { msg = 'Error [Http] [missing httpResponse]' }
  const body = main.httpRequest.body
  const {REQ_CONTEX, REQ_ACTION, REQ_INPUTS} = body
  if (!REQ_CONTEX) { msg = 'Error [Parameter] [missing REQ_CONTEXT]' }
  if (!REQ_ACTION) { msg = 'Error [Parameter] [missing REQ_ACTION]' }
  if (!REQ_INPUTS) { msg = 'Error [Parameter] [missing REQ_INPUTS]' }
  if (msg) { return {isok: false, error: msg} }
  main.REQ_CONTEX = REQ_CONTEX
  main.REQ_ACTION = REQ_ACTION
  main.REQ_INPUTS = REQ_INPUTS
  /** use debug mode */
  console.log(main.REQ_CONTEX, main.REQ_ACTION, main.REQ_INPUTS)
  return {isok: true, error: msg}
}
function validateSignInAndUp () { return AccountPolicy.validateSignInAndUp(main.REQ_INPUTS) }
function accountRecovery (mode) { return AccountPolicy.accountRecovery(mode, main.REQ_INPUTS) }
module.exports = {
  async execute (req, res) {
    console.log('Account Management execute')
    main.httpRequest = req
    main.httpResponse = res
    const paramValidator = preparams()
    let checkpoint = null
    if (paramValidator.isok) {
      // checkAccountStatus API
      if (main.REQ_CONTEX === AuthenticationController.options.CHECKACCOUNTSTATUS) {
        if (main.REQ_ACTION === AuthenticationController.options.onCheckAccountStatus) {
          accountStatus()
        } else if (main.REQ_ACTION === AuthenticationController.options.onGenerateAccountCode) {
          generateAccountCode()
        } else if (main.REQ_ACTION === AuthenticationController.options.onGenerateAccountCode) {
          validateAccountCode()
        } else {
          responseSender({status: 400, output: {error: 'REQ_ACTION not found.', isok: false}})
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.ACCOUNT_RECOVERY) {
        let mode = null
        if (main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_EMAIL) {
          mode = 'email'
        }
        if (main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_RESET) {
          mode = 'reset'
        }
        if (mode) {
          checkpoint = accountRecovery(mode)
        }
        if ((checkpoint && checkpoint.isok) || main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_CODE) {
          passwordRecovery()
        } else {
          responseSender({status: 400, output: checkpoint})
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.SIGNUP) {
        if (main.REQ_ACTION === AuthenticationController.options.NEW_SIGNUP) {
          checkpoint = validateSignInAndUp()
          if (checkpoint.isok) {
            signup()
          } else {
            responseSender({status: 400, output: checkpoint})
          }
          return true
        }
      }
      if (main.REQ_CONTEX === AuthenticationController.options.SIGNIN) {
        if (main.REQ_ACTION === AuthenticationController.options.ON_SIGNIN) {
          checkpoint = validateSignInAndUp()
          if (checkpoint.isok) {
            signin()
          } else {
            responseSender({status: 400, output: checkpoint})
          }
        } else if (main.REQ_ACTION === AuthenticationController.options.ON_SIGNOUT) {
          signout()
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.backoffice) {
        if (main.REQ_ACTION === AuthenticationController.options.backoffice_hardReset) {
          const _res = backOfficeHardReset()
          if (_res) {
            console.log(_res)
          }
        }
      }
    }
    const error = (paramValidator.error && paramValidator.error.length !== 0) ? paramValidator.error : 'Não foi possivel concluir o pedido requerido. Por favor tente mais tarde. Obrigado.'
    responseSender({status: 500, output: {error: error}})
  }
}

async function signup () {
  try {
    const result = await AuthenticationController.signup(main.REQ_INPUTS)
    responseSender(result)
  } catch (error) {
    console.log(error)
  }
}

async function signin () {
  try {
    const result = await AuthenticationController.signin(main.REQ_INPUTS)
    responseSender(result)
  } catch (error) {
    console.log(error)
  }
}

async function signout () {
  const result = await AuthenticationController.signout(main)
  responseSender(result)
}

async function passwordRecovery () {
  const result = await AuthenticationController.passwordRecovery(main)
  responseSender(result)
}

async function accountStatus () {
  const result = await AuthenticationController.accountStatus(main)
  responseSender(result)
}

async function generateAccountCode () {
  const result = await AuthenticationController.generateAccountCode(main)
  responseSender(result)
}

async function validateAccountCode () {
  const result = await AuthenticationController.validateAccountCode(main)
  responseSender(result)
}

async function backOfficeHardReset () {
  const result = await AuthenticationController.backOfficeHardReset()
  responseSender(result)
}

function responseSender (result) {
  main.httpResponse.status(result.status).send(result.output)
}
<commit_msg>testes reset account<commit_after>
/**
  REQ_CONTEX
        1000 -> signup
        2000 -> signin
        3000 -> account_verify
        4000 -> recovery_password

  REQ_ACTION
        1000:1010 -> createNewUser

        2000:2010 -> login
        2000:2020 -> logout

        3000:3010 -> checkAccount
        3000:3020 -> validateAccountEmail
        3000:3030 -> validateAccountCode

        4000:4010 -> recoveryPasswordEmail
        4000:4020 -> recoveryPasswordCode
        4000:4030 -> recoveryPasswordReset

 */

const AuthenticationController = require('./AuthenticationController')
const AccountPolicy = require('../policies/AccountPolicy')
const main = this
main['httpRequest'] = null
main['httpResponse'] = null
main['REQ_CONTEX'] = 0
main['REQ_ACTION'] = 0
main['REQ_INPUTS'] = {}

function preparams () {
  let msg = null
  if (!main.httpRequest) { msg = 'Error [Http] [missing httpRequest]' }
  if (!main.httpResponse) { msg = 'Error [Http] [missing httpResponse]' }
  const body = main.httpRequest.body
  const {REQ_CONTEX, REQ_ACTION, REQ_INPUTS} = body
  if (!REQ_CONTEX) { msg = 'Error [Parameter] [missing REQ_CONTEXT]' }
  if (!REQ_ACTION) { msg = 'Error [Parameter] [missing REQ_ACTION]' }
  if (!REQ_INPUTS) { msg = 'Error [Parameter] [missing REQ_INPUTS]' }
  if (msg) { return {isok: false, error: msg} }
  main.REQ_CONTEX = REQ_CONTEX
  main.REQ_ACTION = REQ_ACTION
  main.REQ_INPUTS = REQ_INPUTS
  /** use debug mode */
  console.log(main.REQ_CONTEX, main.REQ_ACTION, main.REQ_INPUTS)
  return {isok: true, error: msg}
}
function validateSignInAndUp () { return AccountPolicy.validateSignInAndUp(main.REQ_INPUTS) }
function accountRecovery (mode) { return AccountPolicy.accountRecovery(mode, main.REQ_INPUTS) }
module.exports = {
  async execute (req, res) {
    console.log('Account Management execute')
    main.httpRequest = req
    main.httpResponse = res
    const paramValidator = preparams()
    let checkpoint = null
    if (paramValidator.isok) {
      // checkAccountStatus API
      if (main.REQ_CONTEX === AuthenticationController.options.CHECKACCOUNTSTATUS) {
        if (main.REQ_ACTION === AuthenticationController.options.onCheckAccountStatus) {
          accountStatus()
        } else if (main.REQ_ACTION === AuthenticationController.options.onGenerateAccountCode) {
          generateAccountCode()
        } else if (main.REQ_ACTION === AuthenticationController.options.onGenerateAccountCode) {
          validateAccountCode()
        } else {
          responseSender({status: 400, output: {error: 'REQ_ACTION not found.', isok: false}})
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.ACCOUNT_RECOVERY) {
        let mode = null
        if (main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_EMAIL) {
          mode = 'email'
        }
        if (main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_RESET) {
          mode = 'reset'
        }
        if (mode) {
          checkpoint = accountRecovery(mode)
        }
        if ((checkpoint && checkpoint.isok) || main.REQ_ACTION === AuthenticationController.options.ACCOUNT_RECOVERY_CODE) {
          passwordRecovery()
        } else {
          responseSender({status: 400, output: checkpoint})
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.SIGNUP) {
        if (main.REQ_ACTION === AuthenticationController.options.NEW_SIGNUP) {
          checkpoint = validateSignInAndUp()
          if (checkpoint.isok) {
            signup()
          } else {
            responseSender({status: 400, output: checkpoint})
          }
          return true
        }
      }
      if (main.REQ_CONTEX === AuthenticationController.options.SIGNIN) {
        if (main.REQ_ACTION === AuthenticationController.options.ON_SIGNIN) {
          checkpoint = validateSignInAndUp()
          if (checkpoint.isok) {
            signin()
          } else {
            responseSender({status: 400, output: checkpoint})
          }
        } else if (main.REQ_ACTION === AuthenticationController.options.ON_SIGNOUT) {
          signout()
        }
        return true
      }
      if (main.REQ_CONTEX === AuthenticationController.options.backoffice) {
        if (main.REQ_ACTION === AuthenticationController.options.backoffice_hardReset) {
          const _res = await backOfficeHardReset()
          if (_res) {
            console.log(_res)
          }
        }
      }
      return true
    }
    const error = (paramValidator.error && paramValidator.error.length !== 0) ? paramValidator.error : 'Não foi possivel concluir o pedido requerido. Por favor tente mais tarde. Obrigado.'
    responseSender({status: 500, output: {error: error}})
  }
}

async function signup () {
  try {
    const result = await AuthenticationController.signup(main.REQ_INPUTS)
    responseSender(result)
  } catch (error) {
    console.log(error)
  }
}

async function signin () {
  try {
    const result = await AuthenticationController.signin(main.REQ_INPUTS)
    responseSender(result)
  } catch (error) {
    console.log(error)
  }
}

async function signout () {
  const result = await AuthenticationController.signout(main)
  responseSender(result)
}

async function passwordRecovery () {
  const result = await AuthenticationController.passwordRecovery(main)
  responseSender(result)
}

async function accountStatus () {
  const result = await AuthenticationController.accountStatus(main)
  responseSender(result)
}

async function generateAccountCode () {
  const result = await AuthenticationController.generateAccountCode(main)
  responseSender(result)
}

async function validateAccountCode () {
  const result = await AuthenticationController.validateAccountCode(main)
  responseSender(result)
}

async function backOfficeHardReset () {
  const result = await AuthenticationController.backOfficeHardReset()
  responseSender(result)
}

function responseSender (result) {
  main.httpResponse.status(result.status).send(result.output)
}
<|endoftext|>


<commit_before>
"use strict";

const colors  	 	= require('colors');
const express 	 	= require('express');
const bodyParser 	= require('body-parser');
const path    	 	= require('path');
const fs     	 	= require('fs');
const cors   		= require('cors')
const router 		= express.Router()
const extend 	 	= require('util')._extend;
const join   	 	= require('path').join;
const session 		= require('express-session');
const url 			= require('url');
const mo 			= require('method-override');
const eh 			= require('errorhandler');
const multer 		= require('multer');
const _ 			= require("underscore");
const osTmpdir 		= require('os-tmpdir');
const dmn      		= require('domain').create();

process.on('uncaughtException', function (err) {
  console.log(err);
});

dmn.on('error', function(error,r){
	console.log(error);
});

//Create APP
const app    	= express();
const http      = require('http').Server(app);
const io        = require('socket.io')(http);

// Routes
// ----------------------------------------------
const connections 	= require( join(fs.realpathSync('config/',{}), '/connections.js'));
const model  		= require('./lib/'.concat(connections[connections.default].adapter,'.js'));
const routes 		= require( join(fs.realpathSync('config/',{}), '/routes.js'));
const local 		= require( join(fs.realpathSync('config/',{}), '/local.js'));
const sessconf 		= require( join(fs.realpathSync('config/',{}), '/sessions.js')).session;
const auth 			= sessconf.auth;
const polices 		= require('./lib/polices.js');

// Configuration
// ----------------------------------------------
const port    		= local.port || 9991;
const socketport	= local.socketport || 9992;

// Create application/json parser
app.use(bodyParser.json({limit: '50mb'}))
//upload limit
var upload_limit = typeof(local.upload_limit) == 'undefined' ? '50mb' : local.upload_limit;

// Use the body-parser package in our application
app.use(bodyParser.urlencoded({ extended: true, limit: upload_limit, parameterLimit:50000 }));

//multer for files
app.use(multer({dest:osTmpdir()}).any());

// Allow Cors
app.use(cors());

// Enable Trust Proxy
app.enable('trust proxy', 1);

// Auth Middleware
// ----------------------------------------------
app.use(function (req, res, next) {

	var ip     = (req.headers['x-forwarded-for'] || '').split(',')[0] || req.connection.remoteAddress.split(':').slice(-1)[0];
	var origin = req.headers.origin;
	var token  = req.headers.token;
	var secret = req.headers.secret;
	if( auth ){
		switch( auth.type ){
	  		case 'token':
		  		polices.token(token,secret,ip,origin,function(r,data){
		  		  if(r){
		  		  	this.account = data;
				    next();
				  } else {
				    return res.status(401).json({status:401,msg:'Unauthorized, invalid token or missing'})
				  }
		  		})
			break;
			case 'userlogin':
				// TO-DO
		  	break;
		}
	}else{
		next();
	}
});

// Dynamically include routes (Controller)
// ----------------------------------------------
fs.readdirSync(fs.realpathSync('controllers',{})).forEach(function (file) {
    var route = require(fs.realpathSync('controllers',{}) +'/'+ file);
    for( x in route){
        var action     = route[x];
        var uriname    = x.replace('index','');
        var uriname    = uriname.replace(/[A-Z]/g, function(s){ return "-" + s; }).toLowerCase();
        var xfile      = file.replace('.js','') ;
        var xfile      = xfile == 'index' && uriname.length == 0 ? xfile.replace('index','') : xfile ;
        var uri        = join('/',xfile,uriname);
        if( typeof( routes[uri] ) != 'undefined' ){
          app[routes[uri].method](uri,action);
        }else{
          app.all(uri,action);
        }
  	}
});

// Dynamically require models (models)
// ----------------------------------------------
fs.readdirSync(fs.realpathSync('models',{})).forEach(function(file,i) {
      var name            = file.replace('.js','') ;
      var modelname       = name.charAt(0).toUpperCase() + name.slice(1);
      //require file
      this[modelname] = require(join(fs.realpathSync('models',{}),'/', file));
      //attributes
      this[modelname].collection = name;
      //extendig model
      this[modelname] = _.extend({}, model, this[modelname]);
});

app.use(function(req, res, next) {
  var err = new Error();
  //console.log(err);
  res.status(400).json({status:400,msg:'Bad Request'});
});

global.tenant  		= { config:local, io:io, app:app };

// Run server
// ----------------------------------------------
module.exports.run = function(options){

	// Run Socket Server
	http.listen(port, dmn.bind(function () {
	 // set port
	 // var port = typeof options === 'undefined' ? port : options.port;
	  console.log( (' Tenant Socket Services running at port '+port + ' ').bgGreen.black);
	  console.log( ('--------------------------------------------------').gray);
	}));
}
<commit_msg>services connections<commit_after>const colors  	 	= require('colors');
const express 	 	= require('express');
const bodyParser 	= require('body-parser');
const path    	 	= require('path');
const fs     	 	= require('fs');
const cors   		= require('cors')
const router 		= express.Router()
const extend 	 	= require('util')._extend;
const join   	 	= require('path').join;
const session 		= require('express-session');
const url 			= require('url');
const mo 			= require('method-override');
const eh 			= require('errorhandler');
const multer 		= require('multer');
const _ 			= require("underscore");
const osTmpdir 		= require('os-tmpdir');
const dmn      		= require('domain').create();

"use strict";

process.on('uncaughtException', function (err) {
  console.log(err);
});

dmn.on('error', function(error,r){
	console.log(error);
});

//Create APP
const app    	= express();
const http      = require('http').Server(app);
const io        = require('socket.io')(http);

// Routes
// ----------------------------------------------
const connections 	= require( join(fs.realpathSync('config/',{}), '/connections.js'));
const model  		= require('./lib/'.concat(connections[connections.default].adapter,'.js'));
const routes 		= require( join(fs.realpathSync('config/',{}), '/routes.js'));
const local 		= require( join(fs.realpathSync('config/',{}), '/local.js'));
const sessconf 		= require( join(fs.realpathSync('config/',{}), '/sessions.js')).session;
const auth 			= sessconf.auth;
const polices 		= require('./lib/polices.js');

// Configuration
// ----------------------------------------------
const port    		= local.port || 9991;
const socketport	= local.socketport || 9992;

// Create application/json parser
app.use(bodyParser.json({limit: '50mb'}))
//upload limit
var upload_limit = typeof(local.upload_limit) == 'undefined' ? '50mb' : local.upload_limit;

// Use the body-parser package in our application
app.use(bodyParser.urlencoded({ extended: true, limit: upload_limit, parameterLimit:50000 }));

//multer for files
app.use(multer({dest:osTmpdir()}).any());

// Allow Cors
app.use(cors());

// Enable Trust Proxy
app.enable('trust proxy', 1);

// Auth Middleware
// ----------------------------------------------
app.use(function (req, res, next) {

	var ip     = (req.headers['x-forwarded-for'] || '').split(',')[0] || req.connection.remoteAddress.split(':').slice(-1)[0];
	var origin = req.headers.origin;
	var token  = req.headers.token;
	var secret = req.headers.secret;
	if( auth ){
		switch( auth.type ){
	  		case 'token':
		  		polices.token(token,secret,ip,origin,function(r,data){
		  		  if(r){
		  		  	this.account = data;
				    next();
				  } else {
				    return res.status(401).json({status:401,msg:'Unauthorized, invalid token or missing'})
				  }
		  		})
			break;
			case 'userlogin':
				// TO-DO
		  	break;
		}
	}else{
		next();
	}
});

// Dynamically include routes (Controller)
// ----------------------------------------------
fs.readdirSync(fs.realpathSync('controllers',{})).forEach(function (file) {
    var route = require(fs.realpathSync('controllers',{}) +'/'+ file);
    for( x in route){
        var action     = route[x];
        var uriname    = x.replace('index','');
        var uriname    = uriname.replace(/[A-Z]/g, function(s){ return "-" + s; }).toLowerCase();
        var xfile      = file.replace('.js','') ;
        var xfile      = xfile == 'index' && uriname.length == 0 ? xfile.replace('index','') : xfile ;
        var uri        = join('/',xfile,uriname);
        if( typeof( routes[uri] ) != 'undefined' ){
          app[routes[uri].method](uri,action);
        }else{
          app.all(uri,action);
        }
  	}
});

// Dynamically require models (models)
// ----------------------------------------------
fs.readdirSync(fs.realpathSync('models',{})).forEach(function(file,i) {
      var name            = file.replace('.js','') ;
      var modelname       = name.charAt(0).toUpperCase() + name.slice(1);
      //require file
      this[modelname] = require(join(fs.realpathSync('models',{}),'/', file));
      //attributes
      this[modelname].collection = name;
      //extendig model
      this[modelname] = _.extend({}, model, this[modelname]);
});

app.use(function(req, res, next) {
  var err = new Error();
  //console.log(err);
  res.status(400).json({status:400,msg:'Bad Request'});
});

global.tenant  		= { config:local, io:io, app:app };

// Run server
// ----------------------------------------------
module.exports.run = function(options){

	// Run Socket Server
	http.listen(port, dmn.bind(function () {
	 // set port
	 // var port = typeof options === 'undefined' ? port : options.port;
	  console.log( (' Tenant Socket Services running at port '+port + ' ').bgGreen.black);
	  console.log( ('--------------------------------------------------').gray);
	}));
}
<|endoftext|>


<commit_before>var events = require('events');
var util = require('util');
var childProcess = require("child_process");
var byline = require("byline");

function Subprocess(title) {
    events.EventEmitter.call(this);

    this.title = title;
    this.output = [];
}
util.inherits(Subprocess, events.EventEmitter);

Subprocess.prototype.exec = function (cmd, opts) {
    if (this.childProcess) throw { message: "Subprocess already running" };

    this.cmd = cmd;

    opts || (opts = {});
    var env = {};
    for (var key in (process.env || {})) env[key] = process.env[key];
    env['TERM'] = "xterm-color";
    for (var key in (opts.env || {})) env[key] = opts.env[key];

    this.childProcess = childProcess.spawn(cmd[0], cmd.slice(1), { cwd: opts.cwd, env: env });
    this.pid = this.childProcess.pid;

    var self = this;

    ['stdout', 'stderr'].forEach(function (stream) {
        byline(self.childProcess[stream]).on('data', function (line) {
            var lineSpec = { stream: stream, line: line };
            self.output.push(lineSpec);
            self.emit('line', lineSpec);
        });
    });

    this.childProcess.on('close', function (code, signal) {
        self.exitCode = signal || code;
        self.emit('close', code, signal);
    });
};

Subprocess.prototype.signal = function (signal) {
    if (this.exitCode) throw new Error("Can not send signal to finished process");
    this.childProcess.kill(signal);
    this.output.push({ stream: "process-control", line: "Sent the subprocess " + signal });
};

module.exports = Subprocess;
<commit_msg>Detach child processes so they create their own process groups<commit_after>var events = require('events');
var util = require('util');
var childProcess = require("child_process");
var byline = require("byline");

function Subprocess(title) {
    events.EventEmitter.call(this);

    this.title = title;
    this.output = [];
}
util.inherits(Subprocess, events.EventEmitter);

Subprocess.prototype.exec = function (cmd, opts) {
    if (this.childProcess) throw { message: "Subprocess already running" };

    this.cmd = cmd;

    opts || (opts = {});
    var env = {};
    for (var key in (process.env || {})) env[key] = process.env[key];
    env['TERM'] = "xterm-color";
    for (var key in (opts.env || {})) env[key] = opts.env[key];

    this.childProcess = childProcess.spawn(cmd[0], cmd.slice(1), { cwd: opts.cwd, env: env, detached: true });
    this.pid = this.childProcess.pid;

    var self = this;

    ['stdout', 'stderr'].forEach(function (stream) {
        byline(self.childProcess[stream]).on('data', function (line) {
            var lineSpec = { stream: stream, line: line };
            self.output.push(lineSpec);
            self.emit('line', lineSpec);
        });
    });

    this.childProcess.on('close', function (code, signal) {
        self.exitCode = signal || code;
        self.emit('close', code, signal);
    });
};

Subprocess.prototype.signal = function (signal) {
    if (this.exitCode) throw new Error("Can not send signal to finished process");
    this.childProcess.kill(signal);
    this.output.push({ stream: "process-control", line: "Sent the subprocess " + signal });
};

module.exports = Subprocess;
<|endoftext|>


<commit_before>goog.provide('ol.layer.Heatmap');

goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.math');
goog.require('ol.Object');
goog.require('ol.dom');
goog.require('ol.layer.Vector');
goog.require('ol.render.EventType');
goog.require('ol.style.Icon');
goog.require('ol.style.Style');

/**
 * @enum {string}
 */
ol.layer.HeatmapLayerProperty = {
  GRADIENT: 'gradient'
};

/**
 * @constructor
 * @extends {ol.layer.Vector}
 * @fires {@link ol.render.Event} ol.render.Event
 * @param {olx.layer.HeatmapOptions=} opt_options Options.
 * @todo stability experimental
 */
ol.layer.Heatmap = function(opt_options) {
  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this, /** @type {olx.layer.VectorOptions} */ (options));

  /**
   * @private
   * @type {Uint8ClampedArray}
   */
  this.gradient_ = null;

  goog.events.listen(this,
      ol.Object.getChangeEventType(ol.layer.HeatmapLayerProperty.GRADIENT),
      this.handleGradientChanged_, false, this);

  this.setGradient(goog.isDef(options.gradient) ?
      options.gradient : ol.layer.Heatmap.DEFAULT_GRADIENT);

  var circle = ol.layer.Heatmap.createCircle_(
      goog.isDef(options.radius) ? options.radius : 8,
      goog.isDef(options.blur) ? options.blur : 15,
      goog.isDef(options.shadow) ? options.shadow : 250);

  /**
   * @type {Array.<Array.<ol.style.Style>>}
   */
  var styleCache = new Array(256);

  var weight = goog.isDef(options.weight) ? options.weight : 'weight';
  var weightFunction;
  if (goog.isString(weight)) {
    weightFunction = function(feature) {
      return feature.get(weight);
    };
  } else {
    weightFunction = weight;
  }
  goog.asserts.assert(goog.isFunction(weightFunction));

  this.setStyle(function(feature, resolution) {
    var weight = weightFunction(feature);
    var opacity = goog.isDef(weight) ? goog.math.clamp(weight, 0, 1) : 1;
    // cast to 8 bits
    var index = (255 * opacity) | 0;
    var style = styleCache[index];
    if (!goog.isDef(style)) {
      style = [
        new ol.style.Style({
          image: new ol.style.Icon({
            opacity: opacity,
            src: circle
          })
        })
      ];
      styleCache[index] = style;
    }
    return style;
  });

  goog.events.listen(this, ol.render.EventType.RENDER,
      this.handleRender_, false, this);

};
goog.inherits(ol.layer.Heatmap, ol.layer.Vector);

/**
 * @const
 * @type {Array.<string>}
 */
ol.layer.Heatmap.DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00'];

/**
 * @param {Array.<string>} colors
 * @return {Uint8ClampedArray}
 * @private
 */
ol.layer.Heatmap.createGradient_ = function(colors) {
  var width = 1;
  var height = 256;
  var context = ol.dom.createCanvasContext2D(width, height);

  var gradient = context.createLinearGradient(0, 0, width, height);
  var step = 1 / (colors.length - 1);
  for (var i = 0, ii = colors.length; i < ii; ++i) {
    gradient.addColorStop(i * step, colors[i]);
  }

  context.fillStyle = gradient;
  context.fillRect(0, 0, width, height);

  return context.getImageData(0, 0, width, height).data;
};

/**
 * @param {number} radius Radius size in pixel.
 * @param {number} blur Blur size in pixel.
 * @param {number} shadow Shadow offset size in pixel.
 * @return {string}
 * @private
 */
ol.layer.Heatmap.createCircle_ = function(radius, blur, shadow) {
  var halfSize = radius + blur + 1;
  var size = 2 * halfSize;
  var context = ol.dom.createCanvasContext2D(size, size);
  context.shadowOffsetX = context.shadowOffsetY = shadow;
  context.shadowBlur = blur;
  context.shadowColor = '#000';
  context.beginPath();
  var center = halfSize - shadow;
  context.arc(center, center, radius, 0, Math.PI * 2, true);
  context.fill();
  return context.canvas.toDataURL();
};

/**
 * @return {Array.<string>} Colors.
 */
ol.layer.Heatmap.prototype.getGradient = function() {
  return /** @type {Array.<string>} */ (
      this.get(ol.layer.HeatmapLayerProperty.GRADIENT));
};
goog.exportProperty(
    ol.layer.Heatmap.prototype,
    'getGradient',
    ol.layer.Heatmap.prototype.getGradient);

/**
 * @private
 */
ol.layer.Heatmap.prototype.handleGradientChanged_ = function() {
  this.gradient_ = ol.layer.Heatmap.createGradient_(this.getGradient());
};

/**
 * @param {ol.render.Event} event Post compose event
 * @private
 */
ol.layer.Heatmap.prototype.handleRender_ = function(event) {
  goog.asserts.assert(event.type == ol.render.EventType.RENDER);
  var context = event.context;
  var canvas = context.canvas;
  var image = context.getImageData(0, 0, canvas.width, canvas.height);
  var view8 = image.data;
  var i, ii, alpha, offset;
  for (i = 0, ii = view8.length; i < ii; i += 4) {
    alpha = view8[i + 3] * 4;
    if (alpha) {
      view8[i] = this.gradient_[alpha];
      view8[i + 1] = this.gradient_[alpha + 1];
      view8[i + 2] = this.gradient_[alpha + 2];
    }
  }
  context.putImageData(image, 0, 0);
};

/**
 * @param {Array.<string>} colors Gradient.
 */
ol.layer.Heatmap.prototype.setGradient = function(colors) {
  this.set(ol.layer.HeatmapLayerProperty.GRADIENT, colors);
};
goog.exportProperty(
    ol.layer.Heatmap.prototype,
    'setGradient',
    ol.layer.Heatmap.prototype.setGradient);
<commit_msg>Set render order to null in ol.layer.Heatmap<commit_after>goog.provide('ol.layer.Heatmap');

goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.math');
goog.require('ol.Object');
goog.require('ol.dom');
goog.require('ol.layer.Vector');
goog.require('ol.render.EventType');
goog.require('ol.style.Icon');
goog.require('ol.style.Style');

/**
 * @enum {string}
 */
ol.layer.HeatmapLayerProperty = {
  GRADIENT: 'gradient'
};

/**
 * @constructor
 * @extends {ol.layer.Vector}
 * @fires {@link ol.render.Event} ol.render.Event
 * @param {olx.layer.HeatmapOptions=} opt_options Options.
 * @todo stability experimental
 */
ol.layer.Heatmap = function(opt_options) {
  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this, /** @type {olx.layer.VectorOptions} */ (options));

  /**
   * @private
   * @type {Uint8ClampedArray}
   */
  this.gradient_ = null;

  goog.events.listen(this,
      ol.Object.getChangeEventType(ol.layer.HeatmapLayerProperty.GRADIENT),
      this.handleGradientChanged_, false, this);

  this.setGradient(goog.isDef(options.gradient) ?
      options.gradient : ol.layer.Heatmap.DEFAULT_GRADIENT);

  var circle = ol.layer.Heatmap.createCircle_(
      goog.isDef(options.radius) ? options.radius : 8,
      goog.isDef(options.blur) ? options.blur : 15,
      goog.isDef(options.shadow) ? options.shadow : 250);

  /**
   * @type {Array.<Array.<ol.style.Style>>}
   */
  var styleCache = new Array(256);

  var weight = goog.isDef(options.weight) ? options.weight : 'weight';
  var weightFunction;
  if (goog.isString(weight)) {
    weightFunction = function(feature) {
      return feature.get(weight);
    };
  } else {
    weightFunction = weight;
  }
  goog.asserts.assert(goog.isFunction(weightFunction));

  this.setStyle(function(feature, resolution) {
    var weight = weightFunction(feature);
    var opacity = goog.isDef(weight) ? goog.math.clamp(weight, 0, 1) : 1;
    // cast to 8 bits
    var index = (255 * opacity) | 0;
    var style = styleCache[index];
    if (!goog.isDef(style)) {
      style = [
        new ol.style.Style({
          image: new ol.style.Icon({
            opacity: opacity,
            src: circle
          })
        })
      ];
      styleCache[index] = style;
    }
    return style;
  });

  // For performance reasons, don't sort the features before rendering.
  // The render order is not relevant for a heatmap representation.
  this.setRenderOrder(null);

  goog.events.listen(this, ol.render.EventType.RENDER,
      this.handleRender_, false, this);

};
goog.inherits(ol.layer.Heatmap, ol.layer.Vector);

/**
 * @const
 * @type {Array.<string>}
 */
ol.layer.Heatmap.DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00'];

/**
 * @param {Array.<string>} colors
 * @return {Uint8ClampedArray}
 * @private
 */
ol.layer.Heatmap.createGradient_ = function(colors) {
  var width = 1;
  var height = 256;
  var context = ol.dom.createCanvasContext2D(width, height);

  var gradient = context.createLinearGradient(0, 0, width, height);
  var step = 1 / (colors.length - 1);
  for (var i = 0, ii = colors.length; i < ii; ++i) {
    gradient.addColorStop(i * step, colors[i]);
  }

  context.fillStyle = gradient;
  context.fillRect(0, 0, width, height);

  return context.getImageData(0, 0, width, height).data;
};

/**
 * @param {number} radius Radius size in pixel.
 * @param {number} blur Blur size in pixel.
 * @param {number} shadow Shadow offset size in pixel.
 * @return {string}
 * @private
 */
ol.layer.Heatmap.createCircle_ = function(radius, blur, shadow) {
  var halfSize = radius + blur + 1;
  var size = 2 * halfSize;
  var context = ol.dom.createCanvasContext2D(size, size);
  context.shadowOffsetX = context.shadowOffsetY = shadow;
  context.shadowBlur = blur;
  context.shadowColor = '#000';
  context.beginPath();
  var center = halfSize - shadow;
  context.arc(center, center, radius, 0, Math.PI * 2, true);
  context.fill();
  return context.canvas.toDataURL();
};

/**
 * @return {Array.<string>} Colors.
 */
ol.layer.Heatmap.prototype.getGradient = function() {
  return /** @type {Array.<string>} */ (
      this.get(ol.layer.HeatmapLayerProperty.GRADIENT));
};
goog.exportProperty(
    ol.layer.Heatmap.prototype,
    'getGradient',
    ol.layer.Heatmap.prototype.getGradient);

/**
 * @private
 */
ol.layer.Heatmap.prototype.handleGradientChanged_ = function() {
  this.gradient_ = ol.layer.Heatmap.createGradient_(this.getGradient());
};

/**
 * @param {ol.render.Event} event Post compose event
 * @private
 */
ol.layer.Heatmap.prototype.handleRender_ = function(event) {
  goog.asserts.assert(event.type == ol.render.EventType.RENDER);
  var context = event.context;
  var canvas = context.canvas;
  var image = context.getImageData(0, 0, canvas.width, canvas.height);
  var view8 = image.data;
  var i, ii, alpha, offset;
  for (i = 0, ii = view8.length; i < ii; i += 4) {
    alpha = view8[i + 3] * 4;
    if (alpha) {
      view8[i] = this.gradient_[alpha];
      view8[i + 1] = this.gradient_[alpha + 1];
      view8[i + 2] = this.gradient_[alpha + 2];
    }
  }
  context.putImageData(image, 0, 0);
};

/**
 * @param {Array.<string>} colors Gradient.
 */
ol.layer.Heatmap.prototype.setGradient = function(colors) {
  this.set(ol.layer.HeatmapLayerProperty.GRADIENT, colors);
};
goog.exportProperty(
    ol.layer.Heatmap.prototype,
    'setGradient',
    ol.layer.Heatmap.prototype.setGradient);
<|endoftext|>


<commit_before>modules.define('i-bem__dom', function(provide, DOM) {

DOM.decl('input', {
    onSetMod : {
        'js' : {
            'inited' : function() {
                this.__base.apply(this, arguments);

                this
                    .on('change', this._updateClear)
                    ._updateClear();
            }
        }
    },

    /**
     * Обработчик нажатия на кнопку очистки инпута
     * Очищает значение в поле ввода
     * @private
     * @return {Object} экземпляр блока input
     */
    _onClearClick : function() {
        return this
            .val('', { source : 'clear' })
            .setMod('focused', 'yes');
    },

    /**
     * Переключает значение модификатора visibility для элемента clear
     * в зависимости от наличия значения в поле ввода
     * @private
     * @return {Object} экземпляр блока input
     */
    _updateClear : function() {
        return this.toggleMod(this.elem('clear'), 'visibility', 'visible', !!this._val);
    }
}, {
    live : function() {
        this.liveBindTo('clear', 'pointerclick', function() {
            this._onClearClick();
        });
    }
});

provide(DOM);

});
<commit_msg>fix tests for input<commit_after>modules.define('i-bem__dom', function(provide, DOM) {

DOM.decl('input', {
    onSetMod : {
        'js' : {
            'inited' : function() {
                this.__base.apply(this, arguments);

                this
                    .on('change', this._updateClear)
                    ._updateClear();
            }
        }
    },

    /**
     * Обработчик нажатия на кнопку очистки инпута
     * Очищает значение в поле ввода
     * @private
     * @return {Object} экземпляр блока input
     */
    _onClearClick : function() {
        return this
            .val('', { source : 'clear' })
            .setMod('focused', 'yes');
    },

    /**
     * Переключает значение модификатора visibility для элемента clear
     * в зависимости от наличия значения в поле ввода
     * @private
     * @return {Object} экземпляр блока input
     */
    _updateClear : function() {
        return this.toggleMod(this.elem('clear'), 'visibility', 'visible', !!this._val);
    }
}, {
    live : function() {
        this.liveBindTo('clear', 'pointerclick', function() {
            this._onClearClick();
        });

        return this.__base.apply(this, arguments);
    }
});

provide(DOM);

});
<|endoftext|>


<commit_before>define(
	[
		"dojo/on",
		"dojo/keys",
		"dojo/dom-construct",
		"dojo/dom-style",
		"dojo/domReady!"
	],
	function (on, keys, domConstruct, domStyle) {
		"use strict";

		var
			mode = null,
			pageNode = null,
			fsElement = null,
			listeners = [],
			escapeKeyListener = null,
			infoDomNode = null,
			infoTimeout = null
		;

		if (document.documentElement.requestFullscreen) {
			mode = "w3c";
		} else if (document.documentElement.webkitRequestFullscreen) {
			mode = "webkit";
		} else if (document.documentElement.mozRequestFullScreen) {
			mode = "moz";
		} else if (document.documentElement.msRequestFullscreen) {
			mode = "ms";
		}
		console.debug("Full screen mode support: " + (mode ? mode : "none"));

		var fullScreen = {
			setPageNode: function (node) {
				pageNode = node;
			},

			isSupported: function () {
				return !!mode;
			},

			isEnabled: function () {
				return this.isSupported() && (document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);
			},

			isActive: function () {
				if ((document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement)
					|| (fsElement && !this.isEnabled())
				) {
					return true;
				}

				return false;
			},

			request: function (element) {
				/* For compatibility reasons requestFullscreen is always called
				 * for document.documentElement instead of the specific element */
				var doc = document.documentElement;
				if (!element) {
					fsElement = doc;
				} else {
					fsElement = element;
					domStyle.set(pageNode, "display", "none");
					domStyle.set(fullScreenNode, "display", "block");
					domConstruct.place(element, fullScreenNode);
				}

				switch (mode) {
				case "w3c":
					doc.requestFullscreen();
					break;
				case "webkit":
					doc.webkitRequestFullScreen();
					break;
				case "moz":
					doc.mozRequestFullScreen();
					break;
				case "ms":
					doc.msRequestFullscreen();
					break;
				default:
					/* call onChange listeners manually */
					for (var i = 0; i < listeners.length; i++) {
						listeners[i](null, true);
					}
					startEscapeKeyListener();
					break;
				}
			},

			exit: function () {
				domStyle.set(fullScreenNode, "display", "none");
				domStyle.set(pageNode, "display", "block");
				if (escapeKeyListener) {
					escapeKeyListener.remove();
					for (var i = 0; i < listeners.length; i++) {
						listeners[i](null, false);
					}
				}
				fsElement = null;

				switch (mode) {
				case "w3c":
					document.exitFullscreen();
					break;
				case "webkit":
					document.webkitCancelFullScreen();
					break;
				case "moz":
					document.mozCancelFullScreen();
					break;
				case "ms":
					document.msCancelFullscreen();
					break;
				default:
					return false;
				}

				return true;
			},

			toggle: function (element) {
				return this.isActive() ? this.exit() : this.request(element);
			},

			onChange: function (listener) {
				var self = this;

				on(document, "fullscreenchange, webkitfullscreenchange, mozfullscreenchange, msfullscreenchange", function (event) {
					listener(event, self.isActive());
				});
				listeners.push(listener);
			},

			onError: function (listener) {
				on(document, "fullscreenerror, webkitfullscreenerror, mozfullscreenerror, msfullscreenerror", function (event) {
					listener(event);
				});
			},
		};

		var fullScreenNode = domConstruct.create("div", {id: "fullScreenWrapper"}, document.body);
		domStyle.set(fullScreenNode, "display", "none");
		domStyle.set(fullScreenNode, "width", "100%");
		domStyle.set(fullScreenNode, "height", "100%");

		infoDomNode = domConstruct.create("div", {id: "fullScreenInfo", innerHTML: "Full screen mode activated. Press ESC (or double tap) to exit."}, document.body);
		domStyle.set(infoDomNode, "display", "none");

		fullScreen.onChange(function (event, isActive) {
			if (!isActive) {
				domStyle.set(fullScreenNode, "display", "none");
				domStyle.set(pageNode, "display", "block");
				domStyle.set(infoDomNode, "display", "none");
				if (infoTimeout) {
					clearTimeout(infoTimeout);
				}
				fsElement = null;
			}
		});

		fullScreen.onError(function () {
			/* call onChange listeners manually */
			for (var i = 0; i < listeners.length; i++) {
				listeners[i](null, true);
			}
			startEscapeKeyListener();
			showFullScreenInfo();
		});

		on(fullScreenNode, "dblclick", function () {
			fullScreen.exit();
		});

		var startEscapeKeyListener = function () {
			if (escapeKeyListener) {
				escapeKeyListener.remove();
			}
			escapeKeyListener = on(document, "keydown", function (event) {
				if (keys.ESCAPE === event.keyCode) {
					fullScreen.exit();
				}
			});
		};

		var showFullScreenInfo = function () {
			domStyle.set(infoDomNode, "display", "block");
			infoTimeout = setTimeout(function () {
				domStyle.set(infoDomNode, "display", "none");
			}, 5000);
		};

		return fullScreen;
	}
);
<commit_msg>Remove trailing comma in object literal<commit_after>define(
	[
		"dojo/on",
		"dojo/keys",
		"dojo/dom-construct",
		"dojo/dom-style",
		"dojo/domReady!"
	],
	function (on, keys, domConstruct, domStyle) {
		"use strict";

		var
			mode = null,
			pageNode = null,
			fsElement = null,
			listeners = [],
			escapeKeyListener = null,
			infoDomNode = null,
			infoTimeout = null
		;

		if (document.documentElement.requestFullscreen) {
			mode = "w3c";
		} else if (document.documentElement.webkitRequestFullscreen) {
			mode = "webkit";
		} else if (document.documentElement.mozRequestFullScreen) {
			mode = "moz";
		} else if (document.documentElement.msRequestFullscreen) {
			mode = "ms";
		}
		console.debug("Full screen mode support: " + (mode ? mode : "none"));

		var fullScreen = {
			setPageNode: function (node) {
				pageNode = node;
			},

			isSupported: function () {
				return !!mode;
			},

			isEnabled: function () {
				return this.isSupported() && (document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);
			},

			isActive: function () {
				if ((document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement)
					|| (fsElement && !this.isEnabled())
				) {
					return true;
				}

				return false;
			},

			request: function (element) {
				/* For compatibility reasons requestFullscreen is always called
				 * for document.documentElement instead of the specific element */
				var doc = document.documentElement;
				if (!element) {
					fsElement = doc;
				} else {
					fsElement = element;
					domStyle.set(pageNode, "display", "none");
					domStyle.set(fullScreenNode, "display", "block");
					domConstruct.place(element, fullScreenNode);
				}

				switch (mode) {
				case "w3c":
					doc.requestFullscreen();
					break;
				case "webkit":
					doc.webkitRequestFullScreen();
					break;
				case "moz":
					doc.mozRequestFullScreen();
					break;
				case "ms":
					doc.msRequestFullscreen();
					break;
				default:
					/* call onChange listeners manually */
					for (var i = 0; i < listeners.length; i++) {
						listeners[i](null, true);
					}
					startEscapeKeyListener();
					break;
				}
			},

			exit: function () {
				domStyle.set(fullScreenNode, "display", "none");
				domStyle.set(pageNode, "display", "block");
				if (escapeKeyListener) {
					escapeKeyListener.remove();
					for (var i = 0; i < listeners.length; i++) {
						listeners[i](null, false);
					}
				}
				fsElement = null;

				switch (mode) {
				case "w3c":
					document.exitFullscreen();
					break;
				case "webkit":
					document.webkitCancelFullScreen();
					break;
				case "moz":
					document.mozCancelFullScreen();
					break;
				case "ms":
					document.msCancelFullscreen();
					break;
				default:
					return false;
				}

				return true;
			},

			toggle: function (element) {
				return this.isActive() ? this.exit() : this.request(element);
			},

			onChange: function (listener) {
				var self = this;

				on(document, "fullscreenchange, webkitfullscreenchange, mozfullscreenchange, msfullscreenchange", function (event) {
					listener(event, self.isActive());
				});
				listeners.push(listener);
			},

			onError: function (listener) {
				on(document, "fullscreenerror, webkitfullscreenerror, mozfullscreenerror, msfullscreenerror", function (event) {
					listener(event);
				});
			}
		};

		var fullScreenNode = domConstruct.create("div", {id: "fullScreenWrapper"}, document.body);
		domStyle.set(fullScreenNode, "display", "none");
		domStyle.set(fullScreenNode, "width", "100%");
		domStyle.set(fullScreenNode, "height", "100%");

		infoDomNode = domConstruct.create("div", {id: "fullScreenInfo", innerHTML: "Full screen mode activated. Press ESC (or double tap) to exit."}, document.body);
		domStyle.set(infoDomNode, "display", "none");

		fullScreen.onChange(function (event, isActive) {
			if (!isActive) {
				domStyle.set(fullScreenNode, "display", "none");
				domStyle.set(pageNode, "display", "block");
				domStyle.set(infoDomNode, "display", "none");
				if (infoTimeout) {
					clearTimeout(infoTimeout);
				}
				fsElement = null;
			}
		});

		fullScreen.onError(function () {
			/* call onChange listeners manually */
			for (var i = 0; i < listeners.length; i++) {
				listeners[i](null, true);
			}
			startEscapeKeyListener();
			showFullScreenInfo();
		});

		on(fullScreenNode, "dblclick", function () {
			fullScreen.exit();
		});

		var startEscapeKeyListener = function () {
			if (escapeKeyListener) {
				escapeKeyListener.remove();
			}
			escapeKeyListener = on(document, "keydown", function (event) {
				if (keys.ESCAPE === event.keyCode) {
					fullScreen.exit();
				}
			});
		};

		var showFullScreenInfo = function () {
			domStyle.set(infoDomNode, "display", "block");
			infoTimeout = setTimeout(function () {
				domStyle.set(infoDomNode, "display", "none");
			}, 5000);
		};

		return fullScreen;
	}
);
<|endoftext|>


<commit_before>module.exports = {
  parser: 'babel-eslint',
  rules: {
    // Allow anonymous functions
    'func-names': [0],

    // Allow short identifiers
    'id-length': [0],

    // Enforce indentation of switch/case statements
    // See: https://github.com/airbnb/javascript/issues/470#issuecomment-145066890
    indent: [2, 2, { SwitchCase: 1 }],

    // Enforce using all arguments
    // Allow ignoring arguments with underscore prefix
    'no-unused-vars': [2, { args: 'all', argsIgnorePattern: '^_' }],

    // Enforce curly spacing in object literals and destructuring
    'object-curly-spacing': [2, 'always'],

    // Allow padded blocks
    'padded-blocks': [0]
  }
};
<commit_msg>Warn for anonymous functions<commit_after>module.exports = {
  parser: 'babel-eslint',
  rules: {
    // Allow short identifiers
    'id-length': [0],

    // Enforce indentation of switch/case statements
    // See: https://github.com/airbnb/javascript/issues/470#issuecomment-145066890
    indent: [2, 2, { SwitchCase: 1 }],

    // Enforce using all arguments
    // Allow ignoring arguments with underscore prefix
    'no-unused-vars': [2, { args: 'all', argsIgnorePattern: '^_' }],

    // Enforce curly spacing in object literals and destructuring
    'object-curly-spacing': [2, 'always'],

    // Allow padded blocks
    'padded-blocks': [0]
  }
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var events = require('../controllers/events');
var enemies = require('../models/enemies');

// Ship build
var enemyDefeats = function (startingValues) {
    this.enemyDefeats = startingValues || {};
};

enemyDefeats.prototype.get = function () {
    return this.enemyDefeats;
};

enemyDefeats.prototype.adjustCount = function (enemyShipXws, amount) {
    var existingNumber = this.enemyDefeats[enemyShipXws] || 0;
    var newCount = existingNumber + amount;
    if (newCount > 0) {
        this.enemyDefeats[enemyShipXws] = newCount;
    } else {
        delete this.enemyDefeats[enemyShipXws];
    }
    events.trigger('model.enemies.change', this);
};

enemyDefeats.prototype.exportString = function () {
    var exportValues = [];
    _.forEach(this.enemyDefeats, function (count, xws) {
        var enemyShip = _.find(enemies, {
            xws: xws
        });
        var exportValue = enemyShip.id + '=' + count;
        exportValues.push(exportValue);
    });
    var exportString = exportValues.join(':');
    return exportString;
};

enemyDefeats.prototype.parseUrlString = function (string) {
    var enemiesDefeated = {};

    if (string) {
        var itemValues = string.split(':');

        itemValues.forEach(function (itemString) {
            var splitParts = itemString.split('=');
            var shipId = parseInt(splitParts[0], 10);
            var count = parseInt(splitParts[1], 10);
            var enemyModel = _.find(enemies, {
                id: shipId
            });
            if (enemyModel.xws && count) {
                enemiesDefeated[enemyModel.xws] = count;
            }
        });

    }

    this.enemyDefeats = enemiesDefeated;
};

module.exports = enemyDefeats;

<commit_msg>use consistent var for export character<commit_after>'use strict';

var _ = require('lodash');
var events = require('../controllers/events');
var enemies = require('../models/enemies');

var exportSplitCharacter = ':';

// Ship build
var enemyDefeats = function (startingValues) {
    this.enemyDefeats = startingValues || {};
};

enemyDefeats.prototype.get = function () {
    return this.enemyDefeats;
};

enemyDefeats.prototype.adjustCount = function (enemyShipXws, amount) {
    var existingNumber = this.enemyDefeats[enemyShipXws] || 0;
    var newCount = existingNumber + amount;
    if (newCount > 0) {
        this.enemyDefeats[enemyShipXws] = newCount;
    } else {
        delete this.enemyDefeats[enemyShipXws];
    }
    events.trigger('model.enemies.change', this);
};

enemyDefeats.prototype.exportString = function () {
    var exportValues = [];
    _.forEach(this.enemyDefeats, function (count, xws) {
        var enemyShip = _.find(enemies, {
            xws: xws
        });
        var exportValue = enemyShip.id + '=' + count;
        exportValues.push(exportValue);
    });
    var exportString = exportValues.join(exportSplitCharacter);
    return exportString;
};

enemyDefeats.prototype.parseUrlString = function (string) {
    var enemiesDefeated = {};

    if (string) {
        var itemValues = string.split(exportSplitCharacter);

        itemValues.forEach(function (itemString) {
            var splitParts = itemString.split('=');
            var shipId = parseInt(splitParts[0], 10);
            var count = parseInt(splitParts[1], 10);
            var enemyModel = _.find(enemies, {
                id: shipId
            });
            if (enemyModel.xws && count) {
                enemiesDefeated[enemyModel.xws] = count;
            }
        });

    }

    this.enemyDefeats = enemiesDefeated;
};

module.exports = enemyDefeats;

<|endoftext|>


<commit_before>// Copyright 2016 Endless Mobile, Inc.

/* exported DynamicBackground */

const EosKnowledgePrivate = imports.gi.EosKnowledgePrivate;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;

const DominantColor = imports.app.dominantColor;
const HistoryStore = imports.app.historyStore;
const Module = imports.app.interfaces.module;
const Utils = imports.app.utils;

const DEFAULT_COLOR = '#BBBCB6';
const DEFAULT_HEIGHT = 100;

const THRESHOLD_SMALL = 960;
const THRESHOLD_MEDIUM = 1360;
const THRESHOLD_LARGE = 1600;

const DEFAULT_IMAGE = 'resource:///com/endlessm/knowledge/data/images/background.png';

const _cssTemplate = '.LayoutDynamicBackground {\
    background-image: linear-gradient(@{bottom}), linear-gradient(alpha(black, 0.3)), linear-gradient(alpha(@{overlay}, 0.4)), url("@{image}");\
    background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;\
    background-size: auto, auto, auto, 100% auto;\
    background-position: 0px @{height}px, 0px 0px, 0px 0px, 0px 0px;\
}';

/**
 * Class: DynamicBackground
 * Module for displaying a background
 *
 * The background is composed of three layers, a blurred image that goes
 * on the top, a tinted semi-transparent overlay that covers the image
 * and a beige overlay that covers the bottom.
 *
 * The tinted overlay color is extracted from thumbnail image of a
 * <ContentObjectModel>.
 */
const DynamicBackground = new Module.Class({
    Name: 'Layout.DynamicBackground',
    Extends: Gtk.Frame,

    StyleProperties: {
        'background-height': GObject.ParamSpec.int('background-height',
            'Background height', 'Background height in pixels',
            GObject.ParamFlags.READABLE, 0, GLib.MAXINT32, DEFAULT_HEIGHT),
    },

    Slots: {
        /**
         * Slot: content
         * A template module
         */
        'content': {},
    },
    References: {
        'selection': {},  // type: Selection
    },

    _init: function (props={}) {
        this.parent(props);
        this.add(this.create_submodule('content'));

        this._css_class = '';
        this._model = null;
        this._overlay_color = DEFAULT_COLOR;
        this._image_uri = DEFAULT_IMAGE;
        this._background_height = DEFAULT_HEIGHT;
        this._background_color = DEFAULT_COLOR;
        this._css_provider = new Gtk.CssProvider();

        let context = this.get_style_context();
        context.add_provider(this._css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);

        this.reference_module('selection', selection => {
            selection.connect('models-changed',
                this._on_selection_models_changed.bind(this));
        });

        this._idle_id = 0;
        this.connect_after('size-allocate', () => {
            if (this._idle_id) {
                return;
            }
            this._idle_id = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
                this._update_css_class();
                this._idle_id = 0;
            });
        });

        this.connect('style-set', this._update_custom_style.bind(this));
        this.connect('style-updated', this._update_custom_style.bind(this));
    },

    _update_custom_style: function () {
        let context = this.get_style_context();

        let height = EosKnowledgePrivate.style_context_get_custom_int(
            context, 'background-height');
        let rgba = context.get_background_color(Gtk.StateFlags.NORMAL);
        let color = Utils._rgba_to_markup_color(rgba);

        if (this._background_height === height && this._background_color === color)
            return;

        this._background_height = height;
        this._background_color = color;
        this._update_background();
    },

    _update_css_class: function () {
        let css_class = 'large';
        let alloc = this.get_allocation();

        if (alloc.width <=  THRESHOLD_SMALL) {
            css_class = 'small';
        } else if (alloc.width <= THRESHOLD_MEDIUM) {
            css_class = 'medium';
        }

        if (css_class === this._css_class)
            return;

        let context = this.get_style_context();
        context.remove_class(this._css_class);
        context.add_class(css_class);
        this._css_class = css_class;
        this._update_custom_style();
    },

    _on_selection_models_changed: function (selection) {
        let models = selection.get_models();

        if (models.length === 0) {
            let item = HistoryStore.get_default().get_current_item();
            if (!item || !item.model)
                return;
            this._model = item.model;
        } else if (this._model === models[0]) {
            return;
        } else {
            this._model = models[0];
        }

        try {
            this._overlay_color = DominantColor.get_dominant_color(this._model);
            this._image_uri = this._model.thumbnail_uri;
        } catch (error) {
            logError(error);
            this._overlay_color = DEFAULT_COLOR;
            this._image_uri = DEFAULT_IMAGE;
        }
        this._update_background();
    },

    _update_background: function () {
        let css_data = _cssTemplate.replace('@{overlay}', this._overlay_color);
        css_data = css_data.replace('@{bottom}', this._background_color);
        css_data = css_data.replace('@{image}', this._image_uri);
        css_data = css_data.replace('@{height}', this._background_height);
        this._css_provider.load_from_data(css_data);
    },
});
<commit_msg>Layout.DynamicBackground: Allow CSS overrides<commit_after>// Copyright 2016 Endless Mobile, Inc.

/* exported DynamicBackground */

const EosKnowledgePrivate = imports.gi.EosKnowledgePrivate;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;

const DominantColor = imports.app.dominantColor;
const HistoryStore = imports.app.historyStore;
const Module = imports.app.interfaces.module;
const Utils = imports.app.utils;

const DEFAULT_COLOR = '#BBBCB6';
const DEFAULT_HEIGHT = 100;

const THRESHOLD_SMALL = 960;
const THRESHOLD_MEDIUM = 1360;
const THRESHOLD_LARGE = 1600;

const DEFAULT_IMAGE = 'resource:///com/endlessm/knowledge/data/images/background.png';

const _cssTemplate = '.LayoutDynamicBackground {\
    background-image: linear-gradient(@{bottom}), linear-gradient(alpha(black, 0.3)), linear-gradient(alpha(@{overlay}, 0.4)), url("@{image}");\
    background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;\
    background-size: auto, auto, auto, 100% auto;\
    background-position: 0px @{height}px, 0px 0px, 0px 0px, 0px 0px;\
}';

/**
 * Class: DynamicBackground
 * Module for displaying a background
 *
 * The background is composed of three layers, a blurred image that goes
 * on the top, a tinted semi-transparent overlay that covers the image
 * and a beige overlay that covers the bottom.
 *
 * The tinted overlay color is extracted from thumbnail image of a
 * <ContentObjectModel>.
 */
const DynamicBackground = new Module.Class({
    Name: 'Layout.DynamicBackground',
    Extends: Gtk.Frame,

    StyleProperties: {
        'background-height': GObject.ParamSpec.int('background-height',
            'Background height', 'Background height in pixels',
            GObject.ParamFlags.READABLE, 0, GLib.MAXINT32, DEFAULT_HEIGHT),
    },

    Slots: {
        /**
         * Slot: content
         * A template module
         */
        'content': {},
    },
    References: {
        'selection': {},  // type: Selection
    },

    _init: function (props={}) {
        this.parent(props);
        this.add(this.create_submodule('content'));

        this._css_class = '';
        this._model = null;
        this._overlay_color = DEFAULT_COLOR;
        this._image_uri = DEFAULT_IMAGE;
        this._background_height = DEFAULT_HEIGHT;
        this._background_color = DEFAULT_COLOR;
        this._css_provider = new Gtk.CssProvider();

        let context = this.get_style_context();
        context.add_provider(this._css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION - 1);

        this.reference_module('selection', selection => {
            selection.connect('models-changed',
                this._on_selection_models_changed.bind(this));
        });

        this._idle_id = 0;
        this.connect_after('size-allocate', () => {
            if (this._idle_id) {
                return;
            }
            this._idle_id = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
                this._update_css_class();
                this._idle_id = 0;
            });
        });

        this.connect('style-set', this._update_custom_style.bind(this));
        this.connect('style-updated', this._update_custom_style.bind(this));
    },

    _update_custom_style: function () {
        let context = this.get_style_context();

        let height = EosKnowledgePrivate.style_context_get_custom_int(
            context, 'background-height');
        let rgba = context.get_background_color(Gtk.StateFlags.NORMAL);
        let color = Utils._rgba_to_markup_color(rgba);

        if (this._background_height === height && this._background_color === color)
            return;

        this._background_height = height;
        this._background_color = color;
        this._update_background();
    },

    _update_css_class: function () {
        let css_class = 'large';
        let alloc = this.get_allocation();

        if (alloc.width <=  THRESHOLD_SMALL) {
            css_class = 'small';
        } else if (alloc.width <= THRESHOLD_MEDIUM) {
            css_class = 'medium';
        }

        if (css_class === this._css_class)
            return;

        let context = this.get_style_context();
        context.remove_class(this._css_class);
        context.add_class(css_class);
        this._css_class = css_class;
        this._update_custom_style();
    },

    _on_selection_models_changed: function (selection) {
        let models = selection.get_models();

        if (models.length === 0) {
            let item = HistoryStore.get_default().get_current_item();
            if (!item || !item.model)
                return;
            this._model = item.model;
        } else if (this._model === models[0]) {
            return;
        } else {
            this._model = models[0];
        }

        try {
            this._overlay_color = DominantColor.get_dominant_color(this._model);
            this._image_uri = this._model.thumbnail_uri;
        } catch (error) {
            logError(error);
            this._overlay_color = DEFAULT_COLOR;
            this._image_uri = DEFAULT_IMAGE;
        }
        this._update_background();
    },

    _update_background: function () {
        let css_data = _cssTemplate.replace('@{overlay}', this._overlay_color);
        css_data = css_data.replace('@{bottom}', this._background_color);
        css_data = css_data.replace('@{image}', this._image_uri);
        css_data = css_data.replace('@{height}', this._background_height);
        this._css_provider.load_from_data(css_data);
    },
});
<|endoftext|>


<commit_before>/**
 * guy
 * @class BI.BasicButton
 * @extends BI.Single
 *
 * 一般的button父级
 */
BI.BasicButton = BI.inherit(BI.Single, {
    _defaultConfig: function () {
        var conf = BI.BasicButton.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            _baseCls: (conf._baseCls || "") + " bi-basic-button" + (conf.invalid ? "" : " cursor-pointer") + ((BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""),
            // el: {} // 可以通过el来创建button元素
            value: "",
            stopEvent: false,
            stopPropagation: false,
            selected: false,
            once: false, // 点击一次选中有效,再点无效
            forceSelected: false, // 点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发
            forceNotSelected: false, // 无论怎么点击都不会被选中
            disableSelected: false, // 使能选中

            shadow: false,
            isShadowShowingOnSelected: false,  // 选中状态下是否显示阴影
            trigger: null,
            handler: BI.emptyFn,
            bubble: null
        });
    },

    _init: function () {
        BI.BasicButton.superclass._init.apply(this, arguments);
        var self = this;
        var opts = this.options;
        opts.selected = BI.isFunction(opts.selected) ? this.__watch(opts.selected, function (context, newValue) {
            self.setSelected(newValue);
        }) : opts.selected;

        if (opts.shadow) {
            this._createShadow();
        }
        if (opts.level) {
            this.element.addClass("button-" + opts.level);
        }
    },

    _initRef: function () {
        if (this.options.selected === true) {
            this.setSelected(true);
        }
        // 延迟绑定事件，这样可以将自己绑定的事情优先执行
        BI.nextTick(this.bindEvent.bind(this));
        BI.BasicButton.superclass._initRef.apply(this, arguments);
    },

    // 默认render方法
    render: function () {
        return this.options.el;
    },

    _createShadow: function () {
        var self = this, o = this.options;

        var assertMask = function () {
            if (!self.$mask) {
                self.$mask = BI.createWidget(BI.isObject(o.shadow) ? o.shadow : {}, {
                    type: "bi.layout",
                    cls: "bi-button-mask"
                });
                self.$mask.invisible();
                BI.createWidget({
                    type: "bi.absolute",
                    element: self,
                    items: [{
                        el: self.$mask,
                        left: 0,
                        right: 0,
                        top: 0,
                        bottom: 0
                    }]
                });
            }
        };

        this.element.mouseup(function () {
            if (!self._hover && !o.isShadowShowingOnSelected) {
                assertMask();
                self.$mask.invisible();
            }
        });
        this.element.on("mouseenter." + this.getName(), function (e) {
            if (self.element.__isMouseInBounds__(e)) {
                if (self.isEnabled() && !self._hover && (o.isShadowShowingOnSelected || !self.isSelected())) {
                    assertMask();
                    self.$mask.visible();
                }
            }
        });
        this.element.on("mousemove." + this.getName(), function (e) {
            if (!self.element.__isMouseInBounds__(e)) {
                if (self.isEnabled() && !self._hover) {
                    assertMask();
                    self.$mask.invisible();
                }
            }
        });
        this.element.on("mouseleave." + this.getName(), function () {
            if (self.isEnabled() && !self._hover) {
                assertMask();
                self.$mask.invisible();
            }
        });
    },

    bindEvent: function () {
        var self = this;
        var o = this.options, hand = this.handle();
        if (!hand) {
            return;
        }
        hand = hand.element;
        var triggerArr = (o.trigger || "").split(",");
        BI.each(triggerArr, function (idx, trigger) {
            switch (trigger) {
                case "mouseup":
                    var mouseDown = false;
                    hand.mousedown(function () {
                        mouseDown = true;
                    });
                    hand.mouseup(function (e) {
                        if (mouseDown === true) {
                            clk(e);
                        }
                        mouseDown = false;
                        ev(e);
                    });
                    break;
                case "mousedown":
                    var mouseDown = false;
                    var selected = false;
                    hand.mousedown(function (e) {
                        // if (e.button === 0) {
                        BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function (e) {
                            // if (e.button === 0) {
                            if (BI.DOM.isExist(self) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) {
                                // self.setSelected(!self.isSelected());
                                self._trigger();
                            }
                            mouseDown = false;
                            BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                            // }
                        });
                        if (mouseDown === true) {
                            return;
                        }
                        if (self.isSelected()) {
                            selected = true;
                        } else {
                            clk(e);
                        }
                        mouseDown = true;
                        ev(e);
                        // }
                    });
                    hand.mouseup(function (e) {
                        // if (e.button === 0) {
                        if (BI.DOM.isExist(self) && mouseDown === true && selected === true) {
                            clk(e);
                        }
                        mouseDown = false;
                        selected = false;
                        BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                        // }
                    });
                    break;
                case "dblclick":
                    hand.dblclick(clk);
                    break;
                case "lclick":
                    var mouseDown = false;
                    var interval;
                    hand.mousedown(function (e) {
                        BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function (e) {
                            interval && clearInterval(interval);
                            interval = null;
                            mouseDown = false;
                            BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                        });
                        if (mouseDown === true) {
                            return;
                        }
                        if (!self.isEnabled() || (self.isOnce() && self.isSelected())) {
                            return;
                        }
                        interval = setInterval(function () {
                            if (self.isEnabled()) {
                                self.doClick();
                            }
                        }, 180);
                        mouseDown = true;
                        ev(e);
                    });
                    break;
                default:
                    if (o.stopEvent || o.stopPropagation) {
                        hand.mousedown(function (e) {
                            ev(e);
                        });
                    }
                    hand.click(clk);
                    // enter键等同于点击
                    o.attributes && o.attributes.zIndex >= 0 && hand.keyup(function (e) {
                        if (e.keyCode === BI.KeyCode.ENTER) {
                           clk(e);
                        }
                    });
                    break;
            }
        });

        // 之后的300ms点击无效
        var onClick = BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, {
            "leading": true,
            "trailing": false
        });

        function ev (e) {
            if (o.stopEvent) {
                e.stopEvent();
            }
            if (o.stopPropagation) {
                e.stopPropagation();
            }
        }

        function clk (e) {
            ev(e);
            if (!self.isEnabled() || (self.isOnce() && self.isSelected())) {
                return;
            }
            if (BI.isKey(o.bubble) || BI.isFunction(o.bubble)) {
                if (BI.isNull(self.combo)) {
                    var popup;
                    BI.createWidget({
                        type: "bi.absolute",
                        element: self,
                        items: [{
                            el: {
                                type: "bi.bubble_combo",
                                trigger: "",
                                // bubble的提示不需要一直存在在界面上
                                destroyWhenHide: true,
                                ref: function () {
                                    self.combo = this;
                                },
                                el: {
                                    type: "bi.layout",
                                    height: "100%"
                                },
                                popup: {
                                    type: "bi.text_bubble_bar_popup_view",
                                    text: getBubble(),
                                    ref: function () {
                                        popup = this;
                                    },
                                    listeners: [{
                                        eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON,
                                        action: function (v) {
                                            self.combo.hideView();
                                            if (v) {
                                                onClick.apply(self, arguments);
                                            }
                                        }
                                    }]
                                },
                                listeners: [{
                                    eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW,
                                    action: function () {
                                        popup.populate(getBubble());
                                    }
                                }]
                            },
                            left: 0,
                            right: 0,
                            bottom: 0,
                            top: 0
                        }]
                    });
                }
                if (self.combo.isViewVisible()) {
                    self.combo.hideView();
                } else {
                    self.combo.showView();
                }
                return;
            }
            onClick.apply(self, arguments);
        }

        function getBubble () {
            var bubble = self.options.bubble;
            if (BI.isFunction(bubble)) {
                return bubble();
            }
            return bubble;
        }
    },

    _trigger: function (e) {
        var o = this.options;
        if (!this.isEnabled()) {
            return;
        }
        if (!this.isDisableSelected()) {
            this.isForceSelected() ? this.setSelected(true) :
                (this.isForceNotSelected() ? this.setSelected(false) :
                    this.setSelected(!this.isSelected()));
        }
        if (this.isValid()) {
            var v = this.getValue();
            o.handler.call(this, v, this, e);
            this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, v, this, e);
            this.fireEvent(BI.BasicButton.EVENT_CHANGE, v, this);
            if (o.action) {
                BI.Actions.runAction(o.action, "click", o, this);
            }
            BI.Actions.runGlobalAction("click", o, this);
        }
    },

    _doClick: function (e) {
        if (this.isValid()) {
            this.beforeClick(e);
        }
        this._trigger(e);
        if (this.isValid()) {
            this.doClick(e);
        }
    },

    beforeClick: function () {

    },

    doClick: function () {

    },

    handle: function () {
        return this;
    },

    hover: function () {
        this._hover = true;
        this.handle().element.addClass("hover");
        if (this.options.shadow) {
            this.$mask && this.$mask.setVisible(true);
        }
    },

    dishover: function () {
        this._hover = false;
        this.handle().element.removeClass("hover");
        if (this.options.shadow) {
            this.$mask && this.$mask.setVisible(false);
        }
    },

    setSelected: function (b) {
        var o = this.options;
        o.selected = b;
        if (b) {
            this.handle().element.addClass("active");
        } else {
            this.handle().element.removeClass("active");
        }
        if (o.shadow && !o.isShadowShowingOnSelected) {
            this.$mask && this.$mask.setVisible(false);
        }
        this.options.setSelected && this.options.setSelected.call(this, b);
    },

    isSelected: function () {
        return this.options.selected;
    },

    isOnce: function () {
        return this.options.once;
    },

    isForceSelected: function () {
        return this.options.forceSelected;
    },

    isForceNotSelected: function () {
        return this.options.forceNotSelected;
    },

    isDisableSelected: function () {
        return this.options.disableSelected;
    },

    setText: function (text) {
        this.options.text = text;
        this.options.setText && this.options.setText.call(this, text);
    },

    getText: function () {
        return this.options.text;
    },

    _setEnable: function (enable) {
        BI.BasicButton.superclass._setEnable.apply(this, arguments);
        if (enable === true) {
            this.element.removeClass("base-disabled disabled");
        } else if (enable === false) {
            this.element.addClass("base-disabled disabled");
        }
        if (!enable) {
            if (this.options.shadow) {
                this.$mask && this.$mask.setVisible(false);
            }
        }
    },

    empty: function () {
        BI.Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName());
        BI.BasicButton.superclass.empty.apply(this, arguments);
    }
});
BI.BasicButton.EVENT_CHANGE = "BasicButton.EVENT_CHANGE";
BI.shortcut("bi.basic_button", BI.BasicButton);
<commit_msg>无JIRA selected也支持响应式<commit_after>/**
 * guy
 * @class BI.BasicButton
 * @extends BI.Single
 *
 * 一般的button父级
 */
BI.BasicButton = BI.inherit(BI.Single, {
    _defaultConfig: function () {
        var conf = BI.BasicButton.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            _baseCls: (conf._baseCls || "") + " bi-basic-button" + (conf.invalid ? "" : " cursor-pointer") + ((BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""),
            // el: {} // 可以通过el来创建button元素
            value: "",
            stopEvent: false,
            stopPropagation: false,
            selected: false,
            once: false, // 点击一次选中有效,再点无效
            forceSelected: false, // 点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发
            forceNotSelected: false, // 无论怎么点击都不会被选中
            disableSelected: false, // 使能选中

            shadow: false,
            isShadowShowingOnSelected: false,  // 选中状态下是否显示阴影
            trigger: null,
            handler: BI.emptyFn,
            bubble: null
        });
    },

    _init: function () {
        var self = this;
        var opts = this.options;
        opts.selected = BI.isFunction(opts.selected) ? this.__watch(opts.selected, function (context, newValue) {
            self.setSelected(newValue);
        }) : opts.selected;
        BI.BasicButton.superclass._init.apply(this, arguments);

        if (opts.shadow) {
            this._createShadow();
        }
        if (opts.level) {
            this.element.addClass("button-" + opts.level);
        }
    },

    _initRef: function () {
        if (this.options.selected === true) {
            this.setSelected(true);
        }
        // 延迟绑定事件，这样可以将自己绑定的事情优先执行
        BI.nextTick(this.bindEvent.bind(this));
        BI.BasicButton.superclass._initRef.apply(this, arguments);
    },

    // 默认render方法
    render: function () {
        return this.options.el;
    },

    _createShadow: function () {
        var self = this, o = this.options;

        var assertMask = function () {
            if (!self.$mask) {
                self.$mask = BI.createWidget(BI.isObject(o.shadow) ? o.shadow : {}, {
                    type: "bi.layout",
                    cls: "bi-button-mask"
                });
                self.$mask.invisible();
                BI.createWidget({
                    type: "bi.absolute",
                    element: self,
                    items: [{
                        el: self.$mask,
                        left: 0,
                        right: 0,
                        top: 0,
                        bottom: 0
                    }]
                });
            }
        };

        this.element.mouseup(function () {
            if (!self._hover && !o.isShadowShowingOnSelected) {
                assertMask();
                self.$mask.invisible();
            }
        });
        this.element.on("mouseenter." + this.getName(), function (e) {
            if (self.element.__isMouseInBounds__(e)) {
                if (self.isEnabled() && !self._hover && (o.isShadowShowingOnSelected || !self.isSelected())) {
                    assertMask();
                    self.$mask.visible();
                }
            }
        });
        this.element.on("mousemove." + this.getName(), function (e) {
            if (!self.element.__isMouseInBounds__(e)) {
                if (self.isEnabled() && !self._hover) {
                    assertMask();
                    self.$mask.invisible();
                }
            }
        });
        this.element.on("mouseleave." + this.getName(), function () {
            if (self.isEnabled() && !self._hover) {
                assertMask();
                self.$mask.invisible();
            }
        });
    },

    bindEvent: function () {
        var self = this;
        var o = this.options, hand = this.handle();
        if (!hand) {
            return;
        }
        hand = hand.element;
        var triggerArr = (o.trigger || "").split(",");
        BI.each(triggerArr, function (idx, trigger) {
            switch (trigger) {
                case "mouseup":
                    var mouseDown = false;
                    hand.mousedown(function () {
                        mouseDown = true;
                    });
                    hand.mouseup(function (e) {
                        if (mouseDown === true) {
                            clk(e);
                        }
                        mouseDown = false;
                        ev(e);
                    });
                    break;
                case "mousedown":
                    var mouseDown = false;
                    var selected = false;
                    hand.mousedown(function (e) {
                        // if (e.button === 0) {
                        BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function (e) {
                            // if (e.button === 0) {
                            if (BI.DOM.isExist(self) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) {
                                // self.setSelected(!self.isSelected());
                                self._trigger();
                            }
                            mouseDown = false;
                            BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                            // }
                        });
                        if (mouseDown === true) {
                            return;
                        }
                        if (self.isSelected()) {
                            selected = true;
                        } else {
                            clk(e);
                        }
                        mouseDown = true;
                        ev(e);
                        // }
                    });
                    hand.mouseup(function (e) {
                        // if (e.button === 0) {
                        if (BI.DOM.isExist(self) && mouseDown === true && selected === true) {
                            clk(e);
                        }
                        mouseDown = false;
                        selected = false;
                        BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                        // }
                    });
                    break;
                case "dblclick":
                    hand.dblclick(clk);
                    break;
                case "lclick":
                    var mouseDown = false;
                    var interval;
                    hand.mousedown(function (e) {
                        BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function (e) {
                            interval && clearInterval(interval);
                            interval = null;
                            mouseDown = false;
                            BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName());
                        });
                        if (mouseDown === true) {
                            return;
                        }
                        if (!self.isEnabled() || (self.isOnce() && self.isSelected())) {
                            return;
                        }
                        interval = setInterval(function () {
                            if (self.isEnabled()) {
                                self.doClick();
                            }
                        }, 180);
                        mouseDown = true;
                        ev(e);
                    });
                    break;
                default:
                    if (o.stopEvent || o.stopPropagation) {
                        hand.mousedown(function (e) {
                            ev(e);
                        });
                    }
                    hand.click(clk);
                    // enter键等同于点击
                    o.attributes && o.attributes.zIndex >= 0 && hand.keyup(function (e) {
                        if (e.keyCode === BI.KeyCode.ENTER) {
                           clk(e);
                        }
                    });
                    break;
            }
        });

        // 之后的300ms点击无效
        var onClick = BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, {
            "leading": true,
            "trailing": false
        });

        function ev (e) {
            if (o.stopEvent) {
                e.stopEvent();
            }
            if (o.stopPropagation) {
                e.stopPropagation();
            }
        }

        function clk (e) {
            ev(e);
            if (!self.isEnabled() || (self.isOnce() && self.isSelected())) {
                return;
            }
            if (BI.isKey(o.bubble) || BI.isFunction(o.bubble)) {
                if (BI.isNull(self.combo)) {
                    var popup;
                    BI.createWidget({
                        type: "bi.absolute",
                        element: self,
                        items: [{
                            el: {
                                type: "bi.bubble_combo",
                                trigger: "",
                                // bubble的提示不需要一直存在在界面上
                                destroyWhenHide: true,
                                ref: function () {
                                    self.combo = this;
                                },
                                el: {
                                    type: "bi.layout",
                                    height: "100%"
                                },
                                popup: {
                                    type: "bi.text_bubble_bar_popup_view",
                                    text: getBubble(),
                                    ref: function () {
                                        popup = this;
                                    },
                                    listeners: [{
                                        eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON,
                                        action: function (v) {
                                            self.combo.hideView();
                                            if (v) {
                                                onClick.apply(self, arguments);
                                            }
                                        }
                                    }]
                                },
                                listeners: [{
                                    eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW,
                                    action: function () {
                                        popup.populate(getBubble());
                                    }
                                }]
                            },
                            left: 0,
                            right: 0,
                            bottom: 0,
                            top: 0
                        }]
                    });
                }
                if (self.combo.isViewVisible()) {
                    self.combo.hideView();
                } else {
                    self.combo.showView();
                }
                return;
            }
            onClick.apply(self, arguments);
        }

        function getBubble () {
            var bubble = self.options.bubble;
            if (BI.isFunction(bubble)) {
                return bubble();
            }
            return bubble;
        }
    },

    _trigger: function (e) {
        var o = this.options;
        if (!this.isEnabled()) {
            return;
        }
        if (!this.isDisableSelected()) {
            this.isForceSelected() ? this.setSelected(true) :
                (this.isForceNotSelected() ? this.setSelected(false) :
                    this.setSelected(!this.isSelected()));
        }
        if (this.isValid()) {
            var v = this.getValue();
            o.handler.call(this, v, this, e);
            this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, v, this, e);
            this.fireEvent(BI.BasicButton.EVENT_CHANGE, v, this);
            if (o.action) {
                BI.Actions.runAction(o.action, "click", o, this);
            }
            BI.Actions.runGlobalAction("click", o, this);
        }
    },

    _doClick: function (e) {
        if (this.isValid()) {
            this.beforeClick(e);
        }
        this._trigger(e);
        if (this.isValid()) {
            this.doClick(e);
        }
    },

    beforeClick: function () {

    },

    doClick: function () {

    },

    handle: function () {
        return this;
    },

    hover: function () {
        this._hover = true;
        this.handle().element.addClass("hover");
        if (this.options.shadow) {
            this.$mask && this.$mask.setVisible(true);
        }
    },

    dishover: function () {
        this._hover = false;
        this.handle().element.removeClass("hover");
        if (this.options.shadow) {
            this.$mask && this.$mask.setVisible(false);
        }
    },

    setSelected: function (b) {
        var o = this.options;
        o.selected = b;
        if (b) {
            this.handle().element.addClass("active");
        } else {
            this.handle().element.removeClass("active");
        }
        if (o.shadow && !o.isShadowShowingOnSelected) {
            this.$mask && this.$mask.setVisible(false);
        }
        this.options.setSelected && this.options.setSelected.call(this, b);
    },

    isSelected: function () {
        return this.options.selected;
    },

    isOnce: function () {
        return this.options.once;
    },

    isForceSelected: function () {
        return this.options.forceSelected;
    },

    isForceNotSelected: function () {
        return this.options.forceNotSelected;
    },

    isDisableSelected: function () {
        return this.options.disableSelected;
    },

    setText: function (text) {
        this.options.text = text;
        this.options.setText && this.options.setText.call(this, text);
    },

    getText: function () {
        return this.options.text;
    },

    _setEnable: function (enable) {
        BI.BasicButton.superclass._setEnable.apply(this, arguments);
        if (enable === true) {
            this.element.removeClass("base-disabled disabled");
        } else if (enable === false) {
            this.element.addClass("base-disabled disabled");
        }
        if (!enable) {
            if (this.options.shadow) {
                this.$mask && this.$mask.setVisible(false);
            }
        }
    },

    empty: function () {
        BI.Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName());
        BI.BasicButton.superclass.empty.apply(this, arguments);
    }
});
BI.BasicButton.EVENT_CHANGE = "BasicButton.EVENT_CHANGE";
BI.shortcut("bi.basic_button", BI.BasicButton);
<|endoftext|>


<commit_before>/* jshint node: true */
/* jshint esnext: true */
'use strict';

const Q = require('q');
const moment = require('moment');
const race = require('../service/race');

let timeCalculator = {};

timeCalculator.timestamp = function(timestring) {
  const deferred = Q.defer();
  race.startTime()
    .then( starttime => {
      let timestamp = moment(starttime,'X');
      timestamp.hours(timestring.split(':')[0]);
      timestamp.minutes(timestring.split(':')[1]);
      timestamp.seconds(timestring.split(':')[2]);
      deferred.resolve(timestamp.unix());
    });
  return deferred.promise;
};

module.exports = timeCalculator;
<commit_msg>As the IT for the participant service is failing on the CI and we cannot see exactly why, it shows that we need more robust 'error' handling when working with promises -> please use fail/catch/reject.<commit_after>/* jshint node: true */
/* jshint esnext: true */
'use strict';

const Q = require('q');
const moment = require('moment');
const race = require('../service/race');

let timeCalculator = {};

timeCalculator.timestamp = function(timestring) {
  const deferred = Q.defer();
  race.startTime()
    .then( starttime => {
      let timestamp = moment(starttime,'X');
      timestamp.hours(timestring.split(':')[0]);
      timestamp.minutes(timestring.split(':')[1]);
      timestamp.seconds(timestring.split(':')[2]);
      deferred.resolve(timestamp.unix());
    })
    .fail(deferred.reject);
  return deferred.promise;
};

module.exports = timeCalculator;
<|endoftext|>


<commit_before>/*  crypto.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    9 September, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Return current price of a given crypto-currency in $US
*/
const GlassBot = require('../bot.js')
const request = require('request')

GlassBot.registerCommand('crypto', 'default', (message, bot) => {
  let address = 'http://www.coincap.io/page/' + message.content.toUpperCase()
  request(address, function (error, response, body) {
    if (error) {
      //  error is always null, but put this here for jstandard: (Expected error to be handled.)
      message.channel.send('Not a valied crypto currency, try BTC.')
      return
    }
    try {
      let btcBody = JSON.parse(body)
      let str = btcBody.price_usd.toString()
      let price = str.slice(0, str.indexOf('.') + 3)
      message.channel.send('The current price for 1 **' + message.content + '** is $**' + price + '** USD.').catch(err => console.log(err.stack))
    } catch (error) {
      message.channel.send('<:doggo:328259712963313665>' + ' Not a valid crypto-currency, try BTC or ETH.')
    }
  })
}, ['crypt', 'price'], 'Get latest crypto currency price.', '[]')
<commit_msg>Output currency always upper case<commit_after>/*  crypto.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    9 September, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Return current price of a given crypto-currency in $US
*/
const GlassBot = require('../bot.js')
const request = require('request')

GlassBot.registerCommand('crypto', 'default', (message, bot) => {
  let address = 'http://www.coincap.io/page/' + message.content.toUpperCase()
  request(address, function (error, response, body) {
    if (error) {
      //  error is always null, but put this here for jstandard: (Expected error to be handled.)
      message.channel.send('Not a valied crypto currency, try BTC.')
      return
    }
    try {
      let btcBody = JSON.parse(body)
      let str = btcBody.price_usd.toString()
      let price = str.slice(0, str.indexOf('.') + 3)
      message.channel.send('The current price for 1 **' + message.content.toUpperCase() + '** is $**' + price + '** USD.').catch(err => console.log(err.stack))
    } catch (error) {
      message.channel.send('<:doggo:328259712963313665>' + ' Not a valid crypto-currency, try BTC or ETH.')
    }
  })
}, ['crypt', 'price'], 'Get latest crypto currency price.', '[]')
<|endoftext|>


<commit_before>// Copyright (c) 2010 Romain Vallet
// Licensed under the MIT license, read license.txt

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
	name: 'Photobucket',
	version: '0.1',
	prepareImgLinks: function(callback) {
		var res = [];
		hoverZoom.urlReplace(res,
			'a div.thumb',
			'/th_',
			'/'
		);
		callback($(res));
	}
});<commit_msg>Fixed Photobucket plugin.<commit_after>// Copyright (c) 2010 Romain Vallet
// Licensed under the MIT license, read license.txt

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
	name: 'Photobucket',
	version: '0.1',
	prepareImgLinks: function(callback) {
		var res = [];
		hoverZoom.urlReplace(res,
			'img[src*="th_"]',
			['//th', '/th_'],
			['//i', '/'],
			':first'
		);
		callback($(res));
	}
});<|endoftext|>