<commit_before>let async = require('async');
const utils = require('../../utils/utils.js');
const constants = require('../../constants');

require('ejs');
const Templates = {
  vanilla_contract: require('./code_templates/vanilla-contract.js.ejs'),
  embarkjs_contract: require('./code_templates/embarkjs-contract.js.ejs'),
  exec_when_ready: require('./code_templates/exec-when-ready.js.ejs'),
  load_manager: require('./code_templates/load-manager.js.ejs'),
  define_when_env_loaded: require('./code_templates/define-when-env-loaded.js.ejs'),
  main_context: require('./code_templates/main-context.js.ejs'),
  do_when_loaded: require('./code_templates/do-when-loaded.js.ejs'),
  exec_when_env_loaded: require('./code_templates/exec-when-env-loaded.js.ejs')
};

class CodeGenerator {
  constructor(embark, options) {
    this.blockchainConfig = embark.config.blockchainConfig || {};
    this.embarkConfig = embark.config.embarkConfig;
    this.fs = embark.fs;
    this.dappConfigs = {};
    this.logger = embark.logger;
    this.rpcHost = this.blockchainConfig.rpcHost || '';
    this.rpcPort = this.blockchainConfig.rpcPort || '';
    this.contractsConfig = embark.config.contractsConfig || {};
    this.storageConfig = embark.config.storageConfig || {};
    this.communicationConfig = embark.config.communicationConfig || {};
    this.namesystemConfig = embark.config.namesystemConfig || {};
    this.webServerConfig = embark.config.webServerConfig || {};
    this.env = options.env || 'development';
    this.plugins = options.plugins;
    this.events = embark.events;

    this.listenToCommands();

    const self = this;
    this.events.setCommandHandler("code-generator:embarkjs:build", (cb) => {
      self.buildEmbarkJS(cb);
    });
  }

  listenToCommands() {
    this.events.on('config:load:contracts', this.generateContractConfig.bind(this));
    this.events.on('config:load:storage', this.generateStorageConfig.bind(this));
    this.events.on('config:load:communication', this.generateCommunicationConfig.bind(this));

    this.events.setCommandHandler('code', (cb) => {
      this.events.request("contracts:list", (_err, contractsList) => {
        let embarkJSABI = this.generateABI(contractsList, {useEmbarkJS: true});
        let contractsJSON = this.generateContractsJSON(contractsList);
        cb(embarkJSABI, contractsJSON);
      });
    });

    this.events.setCommandHandler('code-generator:web3js', this.buildWeb3JS.bind(this));

    this.events.setCommandHandler('code-generator:contract', (contractName, cb) => {
      this.events.request('contracts:contract', contractName, (contract) => {
        this.buildContractJS(contractName, this.generateContractJSON(contract, contract), cb);
      });
    });

    this.events.setCommandHandler('code-generator:contract:vanilla', (contract, gasLimit, cb) => {
      cb(this.generateContractCode(contract, gasLimit));
    });

    this.events.setCommandHandler('code-generator:contract:custom', (contract, cb) => {
      const customCode = this.generateCustomContractCode(contract);
      if (!customCode) {
        // Fallback to generate code from vanilla contract generator.
        //
        // TODO: can be moved into a afterDeploy event
        // just need to figure out the gasLimit coupling issue
        return cb(this.generateContractCode(contract, contract._gasLimit || false));
      }
      cb(customCode);
    });

    this.events.setCommandHandler('code-generator:embarkjs:provider-code', (cb) => {
      cb(this.getEmbarkJsProviderCode());
    });

    this.events.setCommandHandler('code-generator:embarkjs:init-provider-code', (cb) => {
      cb(this.getInitProviderCode());
    });
  }

  generateContracts(contractsList, useEmbarkJS, isDeployment, useLoader) {
    let self = this;
    let result = "\n";
    let contractsPlugins;

    if (useLoader === false) {
      for (let contract of contractsList) {
        let abi = JSON.stringify(contract.abiDefinition);
        result += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: constants.codeGenerator.gasLimit});
      }
      return result;
    }

    if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) {
      return "";
    }

    if (this.plugins) {
      contractsPlugins = this.plugins.getPluginsFor('contractGeneration');
    }

    if (this.plugins && contractsPlugins.length > 0) {
      contractsPlugins.forEach(function (plugin) {
        result += plugin.generateContracts({contracts: contractsList});
      });
    } else {
      for (let contract of contractsList) {
        let abi = JSON.stringify(contract.abiDefinition);
        let gasEstimates = JSON.stringify(contract.gasEstimates);

        let block = "";

        if (useEmbarkJS) {
           let contractAddress = contract.deployedAddress ? ("'" + contract.deployedAddress + "'") : "undefined";
          block += Templates.embarkjs_contract({className: contract.className, abi: abi, contract: contract, contractAddress: contractAddress, gasEstimates: gasEstimates});
        } else {
          block += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: (isDeployment ? constants.codeGenerator.gasLimit : false)});
        }
        result += Templates.exec_when_ready({block: block});

      }
    }

    return result;
  }

  checkIfNeedsUpdate(file, newOutput, callback) {
    this.fs.readFile(file, (err, content) => {
      if (err) {
        return callback(null, true);
      }
      callback(null, content.toString() !== newOutput);
    });
  }

  generateContractConfig(contractConfig) {
    this.dappConfigs.blockchain = {
      dappConnection: contractConfig.dappConnection,
      dappAutoEnable: contractConfig.dappAutoEnable,
      warnIfMetamask: this.blockchainConfig.isDev,
      blockchainClient: this.blockchainConfig.ethereumClientName
    };
    this.generateArtifact(this.dappConfigs.blockchain, constants.dappConfig.blockchain, constants.dappConfig.dir);
  }

  generateStorageConfig(storageConfig) {
    this.dappConfigs.storage = {
      dappConnection: storageConfig.dappConnection
    };
    this.generateArtifact(this.dappConfigs.storage, constants.dappConfig.storage, constants.dappConfig.dir);
  }

  generateCommunicationConfig(communicationConfig) {
    this.dappConfigs.communication = {
      connection: communicationConfig.connection
    };
    this.generateArtifact(this.dappConfigs.communication, constants.dappConfig.communication, constants.dappConfig.dir);
  }

  generateArtifact(artifactInput, fileName, dirName, cb = () => {}) {
    const dir = utils.joinPath(this.embarkConfig.generationDir, dirName);
    const filePath = utils.joinPath(dir, fileName);
    if (typeof artifactInput !== 'string') {
      artifactInput = JSON.stringify(artifactInput, null, 2);
    }
    async.waterfall([
      (next) => {
        this.fs.mkdirp(dir, next);
      },
      (_dir, next) => {
        this.checkIfNeedsUpdate(filePath, artifactInput, next);
      },
      (needsUpdate, next) => {
        if (!needsUpdate) {
          return next();
        }
        this.fs.writeFile(filePath, artifactInput, next);
      }
    ], (err) => {
      if (err) {
        this.logger.error(err.message || err);
      }
      cb(err, filePath);
    });
  }

  generateContractCode(contract, gasLimit) {
    let abi = JSON.stringify(contract.abiDefinition);

    let block = "";
    block += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: gasLimit});
    return block;
  }

  generateCustomContractCode(contract) {
    const customContractGeneratorPlugin = this.plugins.getPluginsFor('customContractGeneration').splice(-1)[0];
    if (!customContractGeneratorPlugin) {
      return null;
    }
    return customContractGeneratorPlugin.generateCustomContractCode(contract);
  }

  generateNamesInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.namesystemConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('names', this.namesystemConfig);

    return result;
  }

  generateStorageInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.storageConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('storage', this.storageConfig);

    return result;
  }

  generateCommunicationInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.communicationConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('communication', this.communicationConfig);

    return result;
  }

   _getInitCode(codeType, config) {
    let result = "";
    let pluginsWithCode = this.plugins.getPluginsFor('initCode');
    for (let plugin of pluginsWithCode) {
      let initCodes = plugin.embarkjs_init_code[codeType] || [];
      for (let initCode of initCodes) {
        let [block, shouldInit] = initCode;
        if (shouldInit.call(plugin, config)) {
          result += Templates.exec_when_env_loaded({block: block});
        }
      }
    }
    return result;
  }

  generateABI(contractsList, options) {
    let result = "";

    result += this.generateContracts(contractsList, options.useEmbarkJS, options.deployment, true);
    result += this.generateStorageInitialization(options.useEmbarkJS);
    result += this.generateCommunicationInitialization(options.useEmbarkJS);
    result += this.generateNamesInitialization(options.useEmbarkJS);

    return result;
  }

  generateContractJSON(className, contract) {
    let contractJSON = {};

    contractJSON.contract_name = className;
    contractJSON.address = contract.deployedAddress;
    contractJSON.code = contract.code;
    contractJSON.runtime_bytecode = contract.runtimeBytecode;
    contractJSON.real_runtime_bytecode = contract.realRuntimeBytecode;
    contractJSON.swarm_hash = contract.swarmHash;
    contractJSON.gas_estimates = contract.gasEstimates;
    contractJSON.function_hashes = contract.functionHashes;
    contractJSON.abi = contract.abiDefinition;

    return contractJSON;
  }

  generateContractsJSON(contractsList) {
    let contracts = {};

    for (let contract of contractsList) {
      contracts[contract.className] = this.generateContractJSON(contract.className, contract);
    }

    return contracts;
  }

  buildEmbarkJS(cb) {
    const self = this;
    let embarkjsCode = "import EmbarkJS from 'embarkjs';";
    embarkjsCode += "\nexport default EmbarkJS;";
    embarkjsCode += "\nglobal.EmbarkJS = EmbarkJS";
    let code = "";

    async.waterfall([
      function getImports(next) {
        code += "\nimport IpfsApi from 'ipfs-api';\n";

        next();
      },
      function getJSCode(next) {
        code += "\n" + embarkjsCode + "\n";

        code += self.getEmbarkJsProviderCode();
        code += self.generateCommunicationInitialization(true);
        code += self.generateStorageInitialization(true);
        code += self.generateNamesInitialization(true);
        code += self.getReloadPageCode();

        next();
      },
      function writeFile(next) {
        self.generateArtifact(code, constants.dappConfig.embarkjs, '', next);
      }
    ], function(_err, _result) {
      cb();
    });
  }

  getReloadPageCode() {
    return this.env === 'development' ? this.fs.readFileSync(require('path').join(__dirname,'/code/reload-on-change.js'), 'utf8') : '';
  }

  getEmbarkJsProviderCode() {
    return this.plugins.getPluginsFor('embarkjsCode').reduce((code, plugin) => (
      code += plugin.embarkjs_code.join('\n')
    ), '');
  }

  getInitProviderCode() {
    const codeTypes = {
      blockchain: this.blockchainConfig || {},
      communication: this.communicationConfig || {},
      names: this.namesystemConfig || {},
      storage: this.storageConfig || {}
    };

    return this.plugins.getPluginsFor("initConsoleCode").reduce((acc, plugin) => {
      Object.keys(codeTypes).forEach((codeTypeName) => {
        (plugin.embarkjs_init_console_code[codeTypeName] || []).forEach((initCode) => {
          const [block, shouldInit] = initCode;
          if (shouldInit.call(plugin, codeTypes[codeTypeName])) {
            acc += block;
          }
        });
      });
      return acc;
    }, "");
  }

  buildContractJS(contractName, contractJSON, cb) {
    let contractCode = "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += `let ${contractName}JSONConfig = ${JSON.stringify(contractJSON)};\n`;
    contractCode += `let ${contractName} = new EmbarkJS.Blockchain.Contract(${contractName}JSONConfig);\n`;

    contractCode += "export default " + contractName + ";\n";

    this.generateArtifact(contractCode, contractName + '.js', constants.dappConfig.contractsJs, cb);
  }
}

module.exports = CodeGenerator;
<commit_msg>fix errors in code_generator<commit_after>let async = require('async');
const utils = require('../../utils/utils.js');
const constants = require('../../constants');

require('ejs');
const Templates = {
  vanilla_contract: require('./code_templates/vanilla-contract.js.ejs'),
  embarkjs_contract: require('./code_templates/embarkjs-contract.js.ejs'),
  exec_when_ready: require('./code_templates/exec-when-ready.js.ejs'),
  load_manager: require('./code_templates/load-manager.js.ejs'),
  define_when_env_loaded: require('./code_templates/define-when-env-loaded.js.ejs'),
  main_context: require('./code_templates/main-context.js.ejs'),
  do_when_loaded: require('./code_templates/do-when-loaded.js.ejs'),
  exec_when_env_loaded: require('./code_templates/exec-when-env-loaded.js.ejs')
};

class CodeGenerator {
  constructor(embark, options) {
    this.blockchainConfig = embark.config.blockchainConfig || {};
    this.embarkConfig = embark.config.embarkConfig;
    this.fs = embark.fs;
    this.dappConfigs = {};
    this.logger = embark.logger;
    this.rpcHost = this.blockchainConfig.rpcHost || '';
    this.rpcPort = this.blockchainConfig.rpcPort || '';
    this.contractsConfig = embark.config.contractsConfig || {};
    this.storageConfig = embark.config.storageConfig || {};
    this.communicationConfig = embark.config.communicationConfig || {};
    this.namesystemConfig = embark.config.namesystemConfig || {};
    this.webServerConfig = embark.config.webServerConfig || {};
    this.env = options.env || 'development';
    this.plugins = options.plugins;
    this.events = embark.events;

    this.listenToCommands();

    const self = this;
    this.events.setCommandHandler("code-generator:embarkjs:build", (cb) => {
      self.buildEmbarkJS(cb);
    });
  }

  listenToCommands() {
    this.events.on('config:load:contracts', this.generateContractConfig.bind(this));
    this.events.on('config:load:storage', this.generateStorageConfig.bind(this));
    this.events.on('config:load:communication', this.generateCommunicationConfig.bind(this));

    this.events.setCommandHandler('code', (cb) => {
      this.events.request("contracts:list", (_err, contractsList) => {
        let embarkJSABI = this.generateABI(contractsList, {useEmbarkJS: true});
        let contractsJSON = this.generateContractsJSON(contractsList);
        cb(embarkJSABI, contractsJSON);
      });
    });

    this.events.setCommandHandler('code-generator:contract', (contractName, cb) => {
      this.events.request('contracts:contract', contractName, (contract) => {
        this.buildContractJS(contractName, this.generateContractJSON(contract, contract), cb);
      });
    });

    this.events.setCommandHandler('code-generator:contract:vanilla', (contract, gasLimit, cb) => {
      cb(this.generateContractCode(contract, gasLimit));
    });

    this.events.setCommandHandler('code-generator:contract:custom', (contract, cb) => {
      const customCode = this.generateCustomContractCode(contract);
      if (!customCode) {
        // Fallback to generate code from vanilla contract generator.
        //
        // TODO: can be moved into a afterDeploy event
        // just need to figure out the gasLimit coupling issue
        return cb(this.generateContractCode(contract, contract._gasLimit || false));
      }
      cb(customCode);
    });

    this.events.setCommandHandler('code-generator:embarkjs:provider-code', (cb) => {
      cb(this.getEmbarkJsProviderCode());
    });

    this.events.setCommandHandler('code-generator:embarkjs:init-provider-code', (cb) => {
      cb(this.getInitProviderCode());
    });
  }

  generateContracts(contractsList, useEmbarkJS, isDeployment, useLoader) {
    let self = this;
    let result = "\n";
    let contractsPlugins;

    if (useLoader === false) {
      for (let contract of contractsList) {
        let abi = JSON.stringify(contract.abiDefinition);
        result += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: constants.codeGenerator.gasLimit});
      }
      return result;
    }

    if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) {
      return "";
    }

    if (this.plugins) {
      contractsPlugins = this.plugins.getPluginsFor('contractGeneration');
    }

    if (this.plugins && contractsPlugins.length > 0) {
      contractsPlugins.forEach(function (plugin) {
        result += plugin.generateContracts({contracts: contractsList});
      });
    } else {
      for (let contract of contractsList) {
        let abi = JSON.stringify(contract.abiDefinition);
        let gasEstimates = JSON.stringify(contract.gasEstimates);

        let block = "";

        if (useEmbarkJS) {
           let contractAddress = contract.deployedAddress ? ("'" + contract.deployedAddress + "'") : "undefined";
          block += Templates.embarkjs_contract({className: contract.className, abi: abi, contract: contract, contractAddress: contractAddress, gasEstimates: gasEstimates});
        } else {
          block += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: (isDeployment ? constants.codeGenerator.gasLimit : false)});
        }
        result += Templates.exec_when_ready({block: block});

      }
    }

    return result;
  }

  checkIfNeedsUpdate(file, newOutput, callback) {
    this.fs.readFile(file, (err, content) => {
      if (err) {
        return callback(null, true);
      }
      callback(null, content.toString() !== newOutput);
    });
  }

  generateContractConfig(contractConfig) {
    this.dappConfigs.blockchain = {
      dappConnection: contractConfig.dappConnection,
      dappAutoEnable: contractConfig.dappAutoEnable,
      warnIfMetamask: this.blockchainConfig.isDev,
      blockchainClient: this.blockchainConfig.ethereumClientName
    };
    this.generateArtifact(this.dappConfigs.blockchain, constants.dappConfig.blockchain, constants.dappConfig.dir);
  }

  generateStorageConfig(storageConfig) {
    this.dappConfigs.storage = {
      dappConnection: storageConfig.dappConnection
    };
    this.generateArtifact(this.dappConfigs.storage, constants.dappConfig.storage, constants.dappConfig.dir);
  }

  generateCommunicationConfig(communicationConfig) {
    this.dappConfigs.communication = {
      connection: communicationConfig.connection
    };
    this.generateArtifact(this.dappConfigs.communication, constants.dappConfig.communication, constants.dappConfig.dir);
  }

  generateArtifact(artifactInput, fileName, dirName, cb = () => {}) {
    const dir = utils.joinPath(this.embarkConfig.generationDir, dirName);
    const filePath = utils.joinPath(dir, fileName);
    if (typeof artifactInput !== 'string') {
      artifactInput = JSON.stringify(artifactInput, null, 2);
    }
    async.waterfall([
      (next) => {
        this.fs.mkdirp(dir, next);
      },
      (_dir, next) => {
        this.checkIfNeedsUpdate(filePath, artifactInput, next);
      },
      (needsUpdate, next) => {
        if (!needsUpdate) {
          return next();
        }
        this.fs.writeFile(filePath, artifactInput, next);
      }
    ], (err) => {
      if (err) {
        this.logger.error(err.message || err);
      }
      cb(err, filePath);
    });
  }

  generateContractCode(contract, gasLimit) {
    let abi = JSON.stringify(contract.abiDefinition);

    let block = "";
    block += Templates.vanilla_contract({className: contract.className, abi: abi, contract: contract, gasLimit: gasLimit});
    return block;
  }

  generateCustomContractCode(contract) {
    const customContractGeneratorPlugin = this.plugins.getPluginsFor('customContractGeneration').splice(-1)[0];
    if (!customContractGeneratorPlugin) {
      return null;
    }
    return customContractGeneratorPlugin.generateCustomContractCode(contract);
  }

  generateNamesInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.namesystemConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('names', this.namesystemConfig);

    return result;
  }

  generateStorageInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.storageConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('storage', this.storageConfig);

    return result;
  }

  generateCommunicationInitialization(useEmbarkJS) {
    if (!useEmbarkJS || this.communicationConfig === {}) return "";

    let result = "\n";
    result += Templates.define_when_env_loaded();
    result += this._getInitCode('communication', this.communicationConfig);

    return result;
  }

   _getInitCode(codeType, config) {
    let result = "";
    let pluginsWithCode = this.plugins.getPluginsFor('initCode');
    for (let plugin of pluginsWithCode) {
      let initCodes = plugin.embarkjs_init_code[codeType] || [];
      for (let initCode of initCodes) {
        let [block, shouldInit] = initCode;
        if (shouldInit.call(plugin, config)) {
          result += Templates.exec_when_env_loaded({block: block});
        }
      }
    }
    return result;
  }

  generateABI(contractsList, options) {
    let result = "";

    result += this.generateContracts(contractsList, options.useEmbarkJS, options.deployment, true);
    result += this.generateStorageInitialization(options.useEmbarkJS);
    result += this.generateCommunicationInitialization(options.useEmbarkJS);
    result += this.generateNamesInitialization(options.useEmbarkJS);

    return result;
  }

  generateContractJSON(className, contract) {
    let contractJSON = {};

    contractJSON.contract_name = className;
    contractJSON.address = contract.deployedAddress;
    contractJSON.code = contract.code;
    contractJSON.runtime_bytecode = contract.runtimeBytecode;
    contractJSON.real_runtime_bytecode = contract.realRuntimeBytecode;
    contractJSON.swarm_hash = contract.swarmHash;
    contractJSON.gas_estimates = contract.gasEstimates;
    contractJSON.function_hashes = contract.functionHashes;
    contractJSON.abi = contract.abiDefinition;

    return contractJSON;
  }

  generateContractsJSON(contractsList) {
    let contracts = {};

    for (let contract of contractsList) {
      contracts[contract.className] = this.generateContractJSON(contract.className, contract);
    }

    return contracts;
  }

  buildEmbarkJS(cb) {
    const self = this;
    let embarkjsCode = "import EmbarkJS from 'embarkjs';";
    embarkjsCode += "\nexport default EmbarkJS;";
    embarkjsCode += "\nglobal.EmbarkJS = EmbarkJS";
    let code = "";

    async.waterfall([
      function getImports(next) {
        code += "\nimport IpfsApi from 'ipfs-api';\n";

        next();
      },
      function getJSCode(next) {
        code += "\n" + embarkjsCode + "\n";

        code += self.getEmbarkJsProviderCode();
        code += self.generateCommunicationInitialization(true);
        code += self.generateStorageInitialization(true);
        code += self.generateNamesInitialization(true);
        code += self.getReloadPageCode();

        next();
      },
      function writeFile(next) {
        self.generateArtifact(code, constants.dappConfig.embarkjs, '', next);
      }
    ], function(_err, _result) {
      cb();
    });
  }

  getReloadPageCode() {
    return this.env === 'development' ? this.fs.readFileSync(require('path').join(__dirname,'/code/reload-on-change.js'), 'utf8') : '';
  }

  getEmbarkJsProviderCode() {
    return this.plugins.getPluginsFor('embarkjsCode').reduce((code, plugin) => (
      code += plugin.embarkjs_code.join('\n')
    ), '');
  }

  getInitProviderCode() {
    const codeTypes = {
      blockchain: this.blockchainConfig || {},
      communication: this.communicationConfig || {},
      names: this.namesystemConfig || {},
      storage: this.storageConfig || {}
    };

    return this.plugins.getPluginsFor("initConsoleCode").reduce((acc, plugin) => {
      Object.keys(codeTypes).forEach((codeTypeName) => {
        (plugin.embarkjs_init_console_code[codeTypeName] || []).forEach((initCode) => {
          const [block, shouldInit] = initCode;
          if (shouldInit.call(plugin, codeTypes[codeTypeName])) {
            acc += block;
          }
        });
      });
      return acc;
    }, "");
  }

  buildContractJS(contractName, contractJSON, cb) {
    let contractCode = "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += `let ${contractName}JSONConfig = ${JSON.stringify(contractJSON)};\n`;
    contractCode += `let ${contractName} = new EmbarkJS.Blockchain.Contract(${contractName}JSONConfig);\n`;

    contractCode += "export default " + contractName + ";\n";

    this.generateArtifact(contractCode, contractName + '.js', constants.dappConfig.contractsJs, cb);
  }
}

module.exports = CodeGenerator;
<|endoftext|>


<commit_before>import $url from 'url'

export class UrlGenerator {
	app = null
	defaultUrl = null

	constructor(app) {
		this.app = app

		let defaultUrl = null

		if(this.app.port === 443) {
			defaultUrl = 'https://localhost'
		} else if(this.app.port === 80) {
			defaultUrl = 'http://localhost'
		} else {
			defaultUrl = `http://localhost:${this.app.port}`
		}

		this.defaultUrl = $url.parse(app.config.get('app.url', defaultUrl))

		if(!this.defaultUrl.path.isNil && this.defaultUrl.path !== '' && this.defaultUrl.path !== '/') {
			throw new Error('`app.url` can not contain a path.')
		}
	}

	route(name, parameters, req, secure = null) {
		const route = this.app.routes.namedRoutes[name]

		if(route.isNil) {
			throw new Error(`Undefined route name: ${name}`)
		}

		if(!Array.isArray(parameters)) {
			parameters = [ parameters ]
		}

		const numberOfParameters = parameters.length
		let isObject = false

		if(numberOfParameters === 1 && typeof parameters[0] === 'object') {
			isObject = true
			parameters = parameters[0]
		}

		let index = 0
		const path = route.path.replace(/:([a-z0-0_\-\.]+)(?:\(([^\)]+)\))?(\?)?/g, (_, name) => {
			if(isObject) {
				const value = parameters[name] || ''
				delete parameters[name]
				return value
			}

			if(numberOfParameters < index) {
				return ''
			}

			return parameters[index++]
		})

		if(!isObject) {
			parameters = null
		}

		return this.make({
			pathname: path,
			query: { }
		}, parameters, req, secure)
	}

	make(url, parameters, req, secure = null) {
		if(typeof url === 'string') {
			if(url.indexOf('://') >= 0) {
				return url
			}

			url = { pathname: url }
		}

		if(!parameters.isNil) {
			if(url.query.isNil) {
				url.query = parameters
			} else {
				url.query = Object.assign({ }, url.query, parameters)
			}
		}

		if(!req.isNil) {
			url.protocol = req.protocol
			url.host = req.get('Host')
		} else {
			url = Object.assign({ }, this.defaultUrl, url)
		}

		if(secure === true) {
			url.protocol = 'https'
		} else if(secure === false) {
			url.protocol = 'http'
		}

		return $url.format(url)
	}

}
<commit_msg>Improved UrlGenerator.make: * Added UrlGenerator.getProtocol(req, secure) which streamlines protocol detection and will now read from req.secure to detect https * Added UrlGenerator.getHost(req)<commit_after>import URL from 'url'

export class UrlGenerator {
	app = null
	defaultUrl = null

	constructor(app) {
		this.app = app

		let defaultUrl = null

		if(this.app.port === 443) {
			defaultUrl = 'https://localhost'
		} else if(this.app.port === 80) {
			defaultUrl = 'http://localhost'
		} else {
			defaultUrl = `http://localhost:${this.app.port}`
		}

		this.defaultUrl = URL.parse(app.config.get('app.url', defaultUrl))

		if(!this.defaultUrl.path.isNil && this.defaultUrl.path !== '' && this.defaultUrl.path !== '/') {
			throw new Error('`app.url` can not contain a path.')
		}
	}

	route(name, parameters, req, secure = null) {
		const route = this.app.routes.namedRoutes[name]

		if(route.isNil) {
			throw new Error(`Undefined route name: ${name}`)
		}

		if(!Array.isArray(parameters)) {
			parameters = [ parameters ]
		}

		const numberOfParameters = parameters.length
		let isObject = false

		if(numberOfParameters === 1 && typeof parameters[0] === 'object') {
			isObject = true
			parameters = parameters[0]
		}

		let index = 0
		const path = route.path.replace(/:([a-z0-0_\-\.]+)(?:\(([^\)]+)\))?(\?)?/g, (_, name) => {
			if(isObject) {
				const value = parameters[name] || ''
				delete parameters[name]
				return value
			}

			if(numberOfParameters < index) {
				return ''
			}

			return parameters[index++]
		})

		if(!isObject) {
			parameters = null
		}

		return this.make({
			pathname: path,
			query: { }
		}, parameters, req, secure)
	}

	make(url, parameters, req, secure = null) {
		if(typeof url === 'string') {
			if(url.indexOf('://') >= 0) {
				return url
			}

			url = { pathname: url }
		}

		if(!parameters.isNil) {
			if(url.query.isNil) {
				url.query = parameters
			} else {
				url.query = Object.assign({ }, url.query, parameters)
			}
		}

		url.protocol = this.getProtocol(req, secure)
		url.host = this.getHost(req)

		return URL.format(url)
	}

	getProtocol(req = null, secure = null) {
		if(secure === true) {
			return 'https:'
		} else if(secure === false) {
			return 'http:'
		}

		if(req.isNil) {
			return this.defaultUrl.protocol || 'http:'
		}

		if(req.secure) {
			return 'https:'
		}

		return 'http:'
	}

	getHost(req = null) {
		if(req.isNil) {
			return this.defaultUrl.host || 'localhost'
		}

		return req.get('Host')
	}

}
<|endoftext|>


<commit_before>var CronJob = require('cron').CronJob;
var moment = require('moment');

var updateData = require('./updateData');
var cleanData = require('./cleanData');
//var time = '0 */1 * * * *';
var twoHours = '0 */2 * * *';//2 hours
var sixHours = '0 */6 * * *'; // 6 hours
//var time = '00 30 3 * * *';

var clean = function() {
  console.log('cleaning', moment().toDate());
  cleanData.start();
};

var update = function() {
	console.log('updateData', moment().toDate());
	updateData.start();
};

var cleaner = new CronJob({
  cronTime: sixHours,
  onTick: clean
})

var updater = new CronJob({
  cronTime: twoHours,
  onTick: update
})

clean(function() {
  update();
})

updater.start();
cleaner.start();

<commit_msg>update on start<commit_after>var CronJob = require('cron').CronJob;
var moment = require('moment');

var updateData = require('./updateData');
var cleanData = require('./cleanData');
//var time = '0 */1 * * * *';
var twoHours = '0 */2 * * *';//2 hours
var sixHours = '0 */6 * * *'; // 6 hours
//var time = '00 30 3 * * *';

var clean = function() {
  console.log('cleaning', moment().toDate());
  cleanData.start();
};

var update = function() {
	console.log('updateData', moment().toDate());
	updateData.start();
};

var cleaner = new CronJob({
  cronTime: sixHours,
  onTick: clean
})

var updater = new CronJob({
  cronTime: twoHours,
  onTick: update
})

clean();
update();

updater.start();
cleaner.start();

<|endoftext|>


<commit_before>/**
 *
 * @name LineChart
 * @constructor
 * @classdesc This class constructs a c3 line chart.
 * @memberOf dex.charts.c3
 * @implements {dex/component}
 *
 * @example {@lang javascript}
 * var areachart = new dex.charts.c3.AreaChart({
 *   'parent' : "#AreaChart",
 *   'id'     : "AreaChart"
 *   'csv'    : { header : [ "X", "Y", "Z" ],
 *                data   : [[ 1, 2, 3 ], [4, 5, 6], [7, 8, 9]]}
 * });
 *
 * @param {object} userConfig - A user supplied configuration object which will override the defaults.
 * @param {string} userConfig.parent - The parent node to which this Axis will be attached.  Ex: #MyParent
 * will attach to a node with an id = "MyParent".
 * @param {string} [userConfig.id=Axis] - The id of this axis.
 * @param {string} [userConfig.class=Axis] - The class of this axis.
 * @param {csv} userConfig.csv - The user's CSV data.
 *
 * @inherit module:dex/component
 *
 */

var linechart = function (userConfig) {
    var chart;

    var defaults =
    {
        // The parent container of this chart.
        'parent': '#LineChart',
        // Set these when you need to CSS style components independently.
        'id': 'LineChart',
        'class': 'LineChart',
        'resizable': true,
        'csv': {
            'header': [],
            'data': []
        },
        'linktype' : 'area',
        'width': "100%",
        'height': "100%"
    };

    var chart = new dex.component(userConfig, defaults);
    var internalChart;
    var selectedColumns = [];

    chart.resize = function resize() {
        dex.console.log("PARENT: '" + chart.config.parent + "'");
        if (chart.config.resizable) {
            var width = $("" + chart.config.parent).width();
            var height = $("" + chart.config.parent).height();
            dex.console.log("RESIZE: " + width + "x" + height);
            chart.attr("width", width)
              .attr("height", height)
              .update();
        }
        else {
            chart.update();
        }
    };

    chart.render = function render() {

        //var chart = this;
        var config = chart.config;
        var csv = config.csv;
        window.onresize = this.resize;

        d3.select(config.parent).selectAll("*").remove();
        var gtypes = dex.csv.guessTypes(csv);
        selectedColumns = dex.csv.getNumericIndices(csv);
        if (gtypes[0] == "string")
        {
            selectedColumns.unshift(0);
        }
        else if (gtypes[0] == "date")
        {
            selectedColumns.unshift(0);
        }

        var ncsv = dex.csv.columnSlice(csv, selectedColumns);

        var columns = dex.csv.transpose(ncsv);

        for (var ci = 0; ci < columns.header.length; ci++) {
            columns.data[ci].unshift(columns.header[ci]);
        }

        var types = {};
        dex.range(1, ncsv.header.length)
          .map(function(hi) { types[ncsv.header[hi-1]] = config.linktype; });

        var c3config = {
            'bindto' : config.parent,
            'data': {
                'x' : columns.header[0],
                'columns' : columns.data,
                'types' : types
            },
            subchart: {
                show: true
            },
            zoom: {
                enabled: true
            },
            legend: {
                position : 'right'
            },
            groups: config.groups
        };

        //dex.console.log("TYPES:", gtypes);

        if (gtypes[0] == "string")
        {
            c3config["axis"] = {
                "x": {
                    "type": "category",
                    "categories": [].concat.apply([],
                      dex.matrix.uniques(dex.matrix.slice(csv.data, [0]))).sort()
                }
            }
        }
        else if (gtypes[0] == "date")
        {
            //dex.console.log("DEALING WITH A DATE...");
            c3config["axis"] = {
                "x": {
                    "type": "timeseries",
                    "tick": {
                        format: '%Y-%m-%d'
                    }
                }
            }
        }

        //dex.console.log("RENDER C3CONFIG", c3config);

        //dex.console.log("CATEGORIES", c3config);
        internalChart = c3.generate(c3config);
    };

    chart.update = function () {
        var chart = this;
        var config = chart.config;
        var csv = config.csv;

        var gtypes = dex.csv.guessTypes(csv);

        var ncsv = dex.csv.columnSlice(csv, selectedColumns);
        var columns = dex.csv.transpose(ncsv);

        for (var ci = 0; ci < columns.header.length; ci++) {
            columns.data[ci].unshift(columns.header[ci]);
        }

        var types = {};
        dex.range(1, ncsv.header.length)
          .map(function(hi) { types[ncsv.header[hi-1]] = config.linktype; });

        var c3config = {
            'columns' : columns.data
        };

        //dex.console.log("C3CONFIG", c3config);

        //internalChart.groups(config.groups);
        internalChart.load(c3config);
    };

    $(document).ready(function () {
        // Make the entire chart draggable.
        //$(chart.config.parent).draggable();
    });

    return chart;
};

module.exports = linechart;<commit_msg>Changed default linktype to line.<commit_after>/**
 *
 * @name LineChart
 * @constructor
 * @classdesc This class constructs a c3 line chart.
 * @memberOf dex.charts.c3
 * @implements {dex/component}
 *
 * @example {@lang javascript}
 * var areachart = new dex.charts.c3.AreaChart({
 *   'parent' : "#AreaChart",
 *   'id'     : "AreaChart"
 *   'csv'    : { header : [ "X", "Y", "Z" ],
 *                data   : [[ 1, 2, 3 ], [4, 5, 6], [7, 8, 9]]}
 * });
 *
 * @param {object} userConfig - A user supplied configuration object which will override the defaults.
 * @param {string} userConfig.parent - The parent node to which this Axis will be attached.  Ex: #MyParent
 * will attach to a node with an id = "MyParent".
 * @param {string} [userConfig.id=Axis] - The id of this axis.
 * @param {string} [userConfig.class=Axis] - The class of this axis.
 * @param {csv} userConfig.csv - The user's CSV data.
 *
 * @inherit module:dex/component
 *
 */

var linechart = function (userConfig) {
    var chart;

    var defaults =
    {
        // The parent container of this chart.
        'parent': '#LineChart',
        // Set these when you need to CSS style components independently.
        'id': 'LineChart',
        'class': 'LineChart',
        'resizable': true,
        'csv': {
            'header': [],
            'data': []
        },
        'linktype' : 'line',
        'width': "100%",
        'height': "100%"
    };

    var chart = new dex.component(userConfig, defaults);
    var internalChart;
    var selectedColumns = [];

    chart.resize = function resize() {
        dex.console.log("PARENT: '" + chart.config.parent + "'");
        if (chart.config.resizable) {
            var width = $("" + chart.config.parent).width();
            var height = $("" + chart.config.parent).height();
            dex.console.log("RESIZE: " + width + "x" + height);
            chart.attr("width", width)
              .attr("height", height)
              .update();
        }
        else {
            chart.update();
        }
    };

    chart.render = function render() {

        //var chart = this;
        var config = chart.config;
        var csv = config.csv;
        window.onresize = this.resize;

        d3.select(config.parent).selectAll("*").remove();
        var gtypes = dex.csv.guessTypes(csv);
        selectedColumns = dex.csv.getNumericIndices(csv);
        if (gtypes[0] == "string")
        {
            selectedColumns.unshift(0);
        }
        else if (gtypes[0] == "date")
        {
            selectedColumns.unshift(0);
        }

        var ncsv = dex.csv.columnSlice(csv, selectedColumns);

        var columns = dex.csv.transpose(ncsv);

        for (var ci = 0; ci < columns.header.length; ci++) {
            columns.data[ci].unshift(columns.header[ci]);
        }

        var types = {};
        dex.range(1, ncsv.header.length)
          .map(function(hi) { types[ncsv.header[hi-1]] = config.linktype; });

        var c3config = {
            'bindto' : config.parent,
            'data': {
                'x' : columns.header[0],
                'columns' : columns.data,
                'types' : types
            },
            subchart: {
                show: true
            },
            zoom: {
                enabled: true
            },
            legend: {
                position : 'right'
            },
            groups: config.groups
        };

        //dex.console.log("TYPES:", gtypes);

        if (gtypes[0] == "string")
        {
            c3config["axis"] = {
                "x": {
                    "type": "category",
                    "categories": [].concat.apply([],
                      dex.matrix.uniques(dex.matrix.slice(csv.data, [0]))).sort()
                }
            }
        }
        else if (gtypes[0] == "date")
        {
            //dex.console.log("DEALING WITH A DATE...");
            c3config["axis"] = {
                "x": {
                    "type": "timeseries",
                    "tick": {
                        format: '%Y-%m-%d'
                    }
                }
            }
        }

        //dex.console.log("RENDER C3CONFIG", c3config);

        //dex.console.log("CATEGORIES", c3config);
        internalChart = c3.generate(c3config);
    };

    chart.update = function () {
        var chart = this;
        var config = chart.config;
        var csv = config.csv;

        var gtypes = dex.csv.guessTypes(csv);

        var ncsv = dex.csv.columnSlice(csv, selectedColumns);
        var columns = dex.csv.transpose(ncsv);

        for (var ci = 0; ci < columns.header.length; ci++) {
            columns.data[ci].unshift(columns.header[ci]);
        }

        var types = {};
        dex.range(1, ncsv.header.length)
          .map(function(hi) { types[ncsv.header[hi-1]] = config.linktype; });

        var c3config = {
            'columns' : columns.data
        };

        //dex.console.log("C3CONFIG", c3config);

        //internalChart.groups(config.groups);
        internalChart.load(c3config);
    };

    $(document).ready(function () {
        // Make the entire chart draggable.
        //$(chart.config.parent).draggable();
    });

    return chart;
};

module.exports = linechart;<|endoftext|>


<commit_before>"use strict";

const fs = require( "fs" );
const del = require( "del" );

const gulp = require( "gulp" );
const util = require( "gulp-util" );
const runSequence = require( "run-sequence" );

const sourcemaps = require( "gulp-sourcemaps" );
const ts = require( "gulp-typescript" );

const dts = require( "dts-generator" );
const glob = require( "glob" );
const minimatch = require( "minimatch" );
const jeditor = require( "gulp-json-editor" );

const tslint = require( "gulp-tslint" );

let config = {
	source: {
		typescript: [
			"src/**/*.ts",
			"!src/**/*.spec.ts",
		]
	},
	dist: {
		tsOutput: "dist",
		all: "dist/**/*"
	}
};

gulp.task( "default", [ "build" ] );

gulp.task( "build", [ "clean:dist" ], ( done ) => {
	runSequence(
		"clean:dist",
		[ "compile:typescript", "prepare-npm-package" ],
		done
	);
} );

gulp.task( "compile:typescript", () => {
	let tsProject = ts.createProject( "tsconfig.json", {
		"declaration": true
	} );

	let tsResults = gulp.src( config.source.typescript )
		.pipe( sourcemaps.init() )
		.pipe( tsProject() );

	tsResults.dts
		.pipe( gulp.dest( config.dist.tsOutput ) )
	;

	return tsResults.js
		.pipe( sourcemaps.write( "." ) )
		.pipe( gulp.dest( config.dist.tsOutput ) )
		;
} );

gulp.task( "clean:dist", ( done ) => {
	return del( config.dist.all, done );
} );

gulp.task( "lint", [ "lint:typescript" ] );

gulp.task( "lint:typescript", () => {
	return gulp.src( config.source.typescript )
		.pipe( tslint( {
			tslint: require( "tslint" )
		} ) )
		.pipe( tslint.report( "prose" ) )
		;
} );

gulp.task( "prepare-npm-package", ( done ) => {
	runSequence(
		[ "prepare-npm-package:copy-docs", "prepare-npm-package:copy-package-json" ],
		done
	);
} );

gulp.task( "prepare-npm-package:copy-docs", () => {
	return gulp.src( [
		"README.md",
		"CHANGELOG.md",
		"LICENSE",
	] ).pipe( gulp.dest( config.dist.tsOutput ) );
} );

gulp.task( "prepare-npm-package:copy-package-json", () => {
	return gulp.src( "package.json" )
		.pipe( jeditor( ( json ) => {
			delete json.private;
			delete json.scripts;
			delete json.devDependencies;

			json.main = json.main.replace( "dist/", "" );
			json.typings = json.typings.replace( "dist/", "" );

			return json;
		} ) )
		.pipe( gulp.dest( config.dist.tsOutput ) );
} );

gulp.task( "watch", ( done ) => {
	runSequence(
		[ "compile:styles", "compile:templates", "compile:typescript" ],
		[ "watch:styles", "watch:templates", "watch:typescript" ],
		done
	);
} );

gulp.task( "watch:typescript", () => {
	return gulp.watch( config.source.typescript, [ "compile:typescript" ] );
} );

<commit_msg>Add compile:typescript:aot task. Remove unnecessary tasks from watch task<commit_after>"use strict";

const fs = require( "fs" );
const del = require( "del" );

const gulp = require( "gulp" );
const util = require( "gulp-util" );
const runSequence = require( "run-sequence" );

const sourcemaps = require( "gulp-sourcemaps" );
const ts = require( "gulp-typescript" );

const dts = require( "dts-generator" );
const glob = require( "glob" );
const minimatch = require( "minimatch" );
const jeditor = require( "gulp-json-editor" );

const tslint = require( "gulp-tslint" );
const exec = require( "child_process" ).exec;

let config = {
	source: {
		typescript: [
			"src/**/*.ts",
			"!src/**/*.spec.ts",
		]
	},
	dist: {
		tsOutput: "dist",
		all: "dist/**/*"
	}
};

gulp.task( "default", [ "build" ] );

gulp.task( "build", [ "clean:dist" ], ( done ) => {
	runSequence(
		[ "clean:dist", "clean:compiled" ],
		[ "compile:typescript:aot", "prepare-npm-package" ],
		done
	);
} );

gulp.task( "compile:typescript", () => {
	let tsProject = ts.createProject( "tsconfig.json", {
		"declaration": true
	} );

	let tsResults = gulp.src( config.source.typescript )
		.pipe( sourcemaps.init() )
		.pipe( tsProject() );

	tsResults.dts
		.pipe( gulp.dest( config.dist.tsOutput ) )
	;

	return tsResults.js
		.pipe( sourcemaps.write( "." ) )
		.pipe( gulp.dest( config.dist.tsOutput ) )
		;
} );

gulp.task( "compile:typescript:aot", function( cb ) {
	exec( "node_modules/.bin/ngc -p tsconfig.json", function( err, stdout, stderr ) {
		cb( err );
	} );
} );

gulp.task( "clean:dist", ( done ) => {
	return del( config.dist.all, done );
} );

gulp.task( "lint", [ "lint:typescript" ] );

gulp.task( "lint:typescript", () => {
	return gulp.src( config.source.typescript )
		.pipe( tslint( {
			tslint: require( "tslint" )
		} ) )
		.pipe( tslint.report( "prose" ) )
		;
} );

gulp.task( "prepare-npm-package", ( done ) => {
	runSequence(
		[ "prepare-npm-package:copy-docs", "prepare-npm-package:copy-package-json" ],
		done
	);
} );

gulp.task( "prepare-npm-package:copy-docs", () => {
	return gulp.src( [
		"README.md",
		"CHANGELOG.md",
		"LICENSE",
	] ).pipe( gulp.dest( config.dist.tsOutput ) );
} );

gulp.task( "prepare-npm-package:copy-package-json", () => {
	return gulp.src( "package.json" )
		.pipe( jeditor( ( json ) => {
			delete json.private;
			delete json.scripts;
			delete json.devDependencies;

			json.main = json.main.replace( "dist/", "" );
			json.typings = json.typings.replace( "dist/", "" );

			return json;
		} ) )
		.pipe( gulp.dest( config.dist.tsOutput ) );
} );

gulp.task( "watch", ( done ) => {
	runSequence(
		[ "compile:typescript:aot" ],
		[ "watch:typescript" ],
		done
	);
} );

gulp.task( "watch:typescript", () => {
	return gulp.watch( config.source.typescript, [ "compile:typescript:aot" ] );
} );

<|endoftext|>


<commit_before>var util = require('../../../utils/MyUtil');
module.exports = {

	process : function(ctx, step, next) {
		var options = [];
		for(var i = 0; i < step.options.length; i++) {
			var opt = {};
			opt.text = step.options[i];
			options.push(opt);
		}
		util.showOptionDialog(options, {doneResult:function(result, selectedOption) {
			ctx.vars[step.result] = result;
			if(selectedOption && selectedOption.id && step.selectedId) {
				ctx.vars[step.selectedId] = selectedOption.id;
			}
			setTimeout(next, global.STEP_TIMEOUT);
		}});
	}
}<commit_msg>showOptionDialog to support specify id and other custom object<commit_after>var util = require('../../../utils/MyUtil');
module.exports = {

	process : function(ctx, step, next) {
		var options = [];
		for(var i = 0; i < step.options.length; i++) {
			var option = step.options;
			if(typeof option == 'string') {
				var opt = {};
				opt.text = step.options[i];
				options.push(opt);
			}
			else {
				options.push(option);
			}
		}
		util.showOptionDialog(options, {doneResult:function(result, selectedOption) {
			ctx.vars[step.result] = result;
			if(selectedOption && selectedOption.id && step.selectedId) {
				ctx.vars[step.selectedId] = selectedOption.id;
			}
			setTimeout(next, global.STEP_TIMEOUT);
		}});
	}
}<|endoftext|>


<commit_before>const {config} = require('node-config-ts');

module.exports = {
  ...require('./common.js'),
  optional_permissions: ['tabs'],
  applications: {
    gecko: {
      id: config.FirefoxId,
      strict_min_version: '52.0',
    },
  },
};
<commit_msg>put a more recent strict_min_version<commit_after>const {config} = require('node-config-ts');

module.exports = {
  ...require('./common.js'),
  optional_permissions: ['tabs'],
  applications: {
    gecko: {
      id: config.FirefoxId,
      strict_min_version: '84.0',
    },
  },
};
<|endoftext|>


<commit_before>window.extractToken = (hash) => {
  const match = hash.match(/access_token=(\w+)/);
  let token = !!match && match[1];
  if (!token) {
    token = localStorage.getItem('ello_access_token');
  }
  return token;
}

window.checkAuth = () => {
  const token = extractToken(document.location.hash);
  window.history.replaceState(window.history.state, document.title, window.location.pathname)
  document.location.hash = '' // this is a fallback for IE < 10
  if (token) {
    localStorage.setItem('ello_access_token', token)
  } else {
    // TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
    const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
      '?response_type=token' +
      '&scope=web_app' +
      '&client_id='    + ENV.AUTH_CLIENT_ID +
      '&redirect_uri=' + ENV.AUTH_REDIRECT_URI;
    window.location.href = url;
  }
}

window.resetAuth = () => {
  const token = localStorage.getItem('ello_access_token');
  if (token) {
    localStorage.removeItem('ello_access_token');
    window.checkAuth()
  }
}

window.checkAuth()
<commit_msg>Add a check for history and replaceState.<commit_after>window.extractToken = (hash) => {
  const match = hash.match(/access_token=(\w+)/);
  let token = !!match && match[1];
  if (!token) {
    token = localStorage.getItem('ello_access_token');
  }
  return token;
}

window.checkAuth = () => {
  const token = extractToken(document.location.hash);
  if (window.history && window.history.replaceState) {
    window.history.replaceState(window.history.state, document.title, window.location.pathname)
  } else {
    document.location.hash = '' // this is a fallback for IE < 10
  }
  if (token) {
    localStorage.setItem('ello_access_token', token)
  } else {
    // TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
    const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
      '?response_type=token' +
      '&scope=web_app' +
      '&client_id='    + ENV.AUTH_CLIENT_ID +
      '&redirect_uri=' + ENV.AUTH_REDIRECT_URI;
    window.location.href = url;
  }
}

window.resetAuth = () => {
  const token = localStorage.getItem('ello_access_token');
  if (token) {
    localStorage.removeItem('ello_access_token');
    window.checkAuth()
  }
}

window.checkAuth()
<|endoftext|>


<commit_before>var NAME = "Crazy Penguins";
module.exports = {

  VERSION: "0.0.6",

  bet_request: function (game_state, bet) {
    var player = game_state.players[game_state.in_action];
    var maxbet = game_state.players.reduce(function (p, n) { return n.bet > p ? n.bet : p }, 0);

    if (player.hole_cards[0] && player.hole_cards[1] && player.hole_cards[0].rank == player.hole_cards[1].rank) {
      bet(maxbet + game_state.minimum_raise);
    } else {
      bet(game_state.minimum_raise);
    }
  },

  showdown: function (game_state) {

  }
};
<commit_msg>add bet strategy<commit_after>var NAME = "Crazy Penguins";
module.exports = {

  VERSION: "0.0.6",

  bet_request: function (game_state, bet) {
    var player = game_state.players[game_state.in_action];
    var maxbet = game_state.players.reduce(function (p, n) { return n.bet > p ? n.bet : p }, 0);

    if (player.hole_cards[0] && player.hole_cards[1] && player.hole_cards[0].rank == player.hole_cards[1].rank) {
      bet(player.stack);
    } else if (maxbet < player.stack / 10) {
      bet(maxbet + game_state.minimum_raise);
    } else {
      bet(game_state.minimum_raise);
    }
  },

  showdown: function (game_state) {

  }
};
<|endoftext|>


<commit_before>var assert = require('assert');

var tcx = require('../lib/tcx-parser.js');
var vows = require('vows');
var nock = require('nock');

/* For testing url based gpx data */
var http = require('http');
var fs = require('fs');
var HOST = 'http://fakedomain.tld';
fs.readFile('./tests/data/data.tcx', function(err, data) {
	if(err) {
		throw err;
	}
	nock(HOST)
	.get('/data.tcx')
	.reply(200, data, {
		'Content-Type' : 'application/xml'
	});
});
nock(HOST)
.get('/bad.tcx')
.reply(404, 'Hey bad request!',{
	'Content-Type' : 'text/html'
});

nock(HOST)
.get('/soft404.tcx')
.reply(200, 'This is a soft 404 which has 200 as status code',{
	'Content-Type' : 'text/xml'
});

nock(HOST)
.get('/broken.tcx')
.reply(200, '<?xml version="1.0" encoding="UTF-8"?><TrainingCenterDatabase><Activities><Activity Sport="Running"></TrainingCenterDatabase>',{
	'Content-Type' : 'text/xml'
});

fs.readFile('./tests/data/loading.gif', function(err, data) {
	if(err) {
		throw err;
	}
	nock(HOST)
	.get('/image.tcx')
	.reply(200, data,{
		'Content-Type' : 'application/xml'
	});
});

vows.describe('Test suite for parsing tcx').addBatch({
	'Parse broken tcx data' : {
		topic : function() {
			tcx.tcxParse('<?xml version="1.0" encoding="UTF-8"?><TrainingCenterDatabase><Activities><Activity Sport="Running"></TrainingCenterDatabase>', this.callback);
		},
		'should return an error' : function(err, result) {
			assert.equal(err != null, true);
			assert.equal(result == null, true);
		}
	},
	'Parse valid xml but wrong format' : {
		topic : function() {
			tcx.tcxParse('<?xml version="1.0" encoding="UTF-8"?><gpx></gpx>', this.callback);
		},
		'should return an error' : function(err, result) {
			assert.equal(err != null, true);
			assert.equal(result == null, true);
		}
	},
	'Parse tcx file data.tcx' : {
		'topic' : function() {
			tcx.tcxParseFile('./tests/data/data.tcx', this.callback);
		},
		'Should return an array of three tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : 1.9600000381469729,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);

		}
	},
	'Parse tcx file data_missing_ext.tcx' : {
		'topic' : function() {
			tcx.tcxParseFile('./tests/data/data_missing_ext.tcx', this.callback);
		},
		'Should return an array of three tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : null,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);

		}
	},
	'Parse a image file' : {
		topic : function() {
			 tcx.tcxParseFile('./tests/data/loading.gif', this.callback);
		},
		'Should return an error ': function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse tcx URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/data.tcx', this.callback);
		},
		'Should return an array of two tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : 1.9600000381469729,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);
		}
	},
	'Parse bad tcx URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/bad.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse bad tcx URL which returns a soft 404' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/soft404.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse tcx URL which returns a broken xml' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/broken.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse image URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/image.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
			assert.equal(/Non-whitespace before first tag/.test(err.message), true);
		}
	}
}).export(module)
<commit_msg>#9 just assert there is an error<commit_after>var assert = require('assert');

var tcx = require('../lib/tcx-parser.js');
var vows = require('vows');
var nock = require('nock');

/* For testing url based gpx data */
var http = require('http');
var fs = require('fs');
var HOST = 'http://fakedomain.tld';
fs.readFile('./tests/data/data.tcx', function(err, data) {
	if(err) {
		throw err;
	}
	nock(HOST)
	.get('/data.tcx')
	.reply(200, data, {
		'Content-Type' : 'application/xml'
	});
});
nock(HOST)
.get('/bad.tcx')
.reply(404, 'Hey bad request!',{
	'Content-Type' : 'text/html'
});

nock(HOST)
.get('/soft404.tcx')
.reply(200, 'This is a soft 404 which has 200 as status code',{
	'Content-Type' : 'text/xml'
});

nock(HOST)
.get('/broken.tcx')
.reply(200, '<?xml version="1.0" encoding="UTF-8"?><TrainingCenterDatabase><Activities><Activity Sport="Running"></TrainingCenterDatabase>',{
	'Content-Type' : 'text/xml'
});

fs.readFile('./tests/data/loading.gif', function(err, data) {
	if(err) {
		throw err;
	}
	nock(HOST)
	.get('/image.tcx')
	.reply(200, data,{
		'Content-Type' : 'application/xml'
	});
});

vows.describe('Test suite for parsing tcx').addBatch({
	'Parse broken tcx data' : {
		topic : function() {
			tcx.tcxParse('<?xml version="1.0" encoding="UTF-8"?><TrainingCenterDatabase><Activities><Activity Sport="Running"></TrainingCenterDatabase>', this.callback);
		},
		'should return an error' : function(err, result) {
			assert.equal(err != null, true);
			assert.equal(result == null, true);
		}
	},
	'Parse valid xml but wrong format' : {
		topic : function() {
			tcx.tcxParse('<?xml version="1.0" encoding="UTF-8"?><gpx></gpx>', this.callback);
		},
		'should return an error' : function(err, result) {
			assert.equal(err != null, true);
			assert.equal(result == null, true);
		}
	},
	'Parse tcx file data.tcx' : {
		'topic' : function() {
			tcx.tcxParseFile('./tests/data/data.tcx', this.callback);
		},
		'Should return an array of three tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : 1.9600000381469729,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);

		}
	},
	'Parse tcx file data_missing_ext.tcx' : {
		'topic' : function() {
			tcx.tcxParseFile('./tests/data/data_missing_ext.tcx', this.callback);
		},
		'Should return an array of three tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : null,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);

		}
	},
	'Parse a image file' : {
		topic : function() {
			 tcx.tcxParseFile('./tests/data/loading.gif', this.callback);
		},
		'Should return an error ': function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse tcx URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/data.tcx', this.callback);
		},
		'Should return an array of two tracking points' : function(err, result) {
			assert.deepEqual(result, [{
				distance : 0,
				lat : null,
				lng : null,
				speed : 1.7480000257492068,
				time : new Date('2013-01-16T18:54:46.000Z'),
				altitude : 48.400001525878906
			}, {
				distance : 10.600000381469727,
				lat : 59.19330538250506,
				lng : 17.662933934479952,
				speed : 1.9600000381469729,
				time : new Date('2013-01-16T18:54:52.000Z'),
				altitude : 68.4000015258789
			}, {
				distance : 29.540000915527344,
				lat : 59.19347486458719,
				lng : 17.662943825125694,
				speed : 2.598000049591064,
				time : new Date('2013-01-16T18:54:58.000Z'),
				altitude : 68.4000015258789
			}]);
		}
	},
	'Parse bad tcx URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/bad.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse bad tcx URL which returns a soft 404' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/soft404.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse tcx URL which returns a broken xml' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/broken.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	},
	'Parse image URL' : {
		'topic' : function() {
			tcx.tcxParseURL(HOST + '/image.tcx', this.callback);
		},
		'Should return an error' : function(err, result) {
			assert.equal(err != null, true);
		}
	}
}).export(module)
<|endoftext|>


<commit_before>"enable aexpr";

import HaloItem from 'src/components/halo/lively-halo-item.js';
import {pt} from 'src/client/graphics.js';
import ContextMenu from "src/client/contextmenu.js";

export default class LivelyHaloConnectorsItem extends HaloItem {

  async initialize() {
    this.windowTitle = "LivelyHaloConnectorsItem";

    this.registerEvent('click', 'onClick');

    this.expressions = [];
  }

  onClick(evt) {
      this.source = window.that;

      this.showStartingConnectorsMenuFor(evt);

      this.hideHalo();
    }

  async showMenu(evt, menuItems){
    const menu = await ContextMenu.openIn(document.body, evt, undefined, document.body, menuItems);
  }

  async showStartingConnectorsMenuFor(evt) {

    const menuItems = [[
      'Connections',
      () => this.showConnections(),
      'Opens all created connections',
      ''
      ], [
      'New Connection',
        [['On custom...', () => this.startCreatingConnectionCustom(evt)],
          ['On value', () => this.startCreatingConnectionFor(evt, 'value')],
         ['On other thing', () => this.startCreatingConnectionFor(evt, 'other')]],
      'Creates a new connection',
      ''
    ]];

    this.showMenu(evt, menuItems);
  }

  async showFinishingConnectorsMenuFor(evt, morph){
    const menuItems = [[
      'On custom...',
      () => this.finishCreatingConnectionCustom()
    ],[
      'On width',
      () => this.finishCreatingConnection(morph, 'width')
    ],[
      'On height',
      () => this.finishCreatingConnection(morph, 'height')
    ]];

    this.showMenu(evt, menuItems);
  }

  elementUnderHand(evt) {
    var path = evt.composedPath().slice(evt.composedPath().indexOf(evt.srcElement))
    return path[0]
  }

  onPointerMove(evt) {
    //lively.showPoint(pt(evt.clientX, evt.clientY))
    //lively.notify('move')

    if (this.dropIndicator) this.dropIndicator.remove()
    this.dropTarget = this.elementUnderHand(evt)
    if (this.dropTarget) {
      this.dropIndicator = lively.showElement(this.dropTarget)
      this.dropIndicator.style.border = "3px dashed rgba(0,100,0,0.5)"
      this.dropIndicator.innerHTML = ""
    }
  }

  onPointerUp(evt) {
    //lively.notify('up')
    lively.removeEventListener("Connectors")

    if (this.dropIndicator) this.dropIndicator.remove()
    var morph = this.elementUnderHand(evt)

    this.showFinishingConnectorsMenuFor(evt, morph);
  }

   showConnections(){
    lively.openInspector(this.expressions);
  }

  async startCreatingConnectionCustom(evt){
    var userinput = await lively.prompt("Enter something", "value");
    this.startCreatingConnectionFor(evt, userinput);
  }

  startCreatingConnectionFor(evt, property){
    this.sourceProperty = property;

        lively.addEventListener("Connectors", document.body.parentElement, "pointermove",
      e => this.onPointerMove(e), { capture: true });
    lively.addEventListener("Connectors", document.body.parentElement, "pointerup",
      e => this.onPointerUp(e), { capture: true });
  }

  finishCreatingConnectionCustom(){
     lively.prompt("Enter something", "width")
  }

  finishCreatingConnection(target, targetProperty){
    //let ae = aexpr(() => code.boundEval(sourceObject));
    //ae.onChange(svalue => target.style.width= svalue+"pt");

    let ae = aexpr(() => this.source[this.sourceProperty]);
    ae.onChange(svalue => target.style[targetProperty]= svalue+"pt");

    this.expressions.push(ae);
  }

}<commit_msg>small stuff<commit_after>"enable aexpr";

import HaloItem from 'src/components/halo/lively-halo-item.js';
import {pt} from 'src/client/graphics.js';
import ContextMenu from "src/client/contextmenu.js";

export default class LivelyHaloConnectorsItem extends HaloItem {

  async initialize() {
    this.windowTitle = "LivelyHaloConnectorsItem";

    this.registerEvent('click', 'onClick');

    this.expressions = [];
  }

  onClick(evt) {
      this.source = window.that;

      this.showStartingConnectorsMenuFor(evt);

      this.hideHalo();
    }

  async showMenu(evt, menuItems){
    const menu = await ContextMenu.openIn(document.body, evt, undefined, document.body, menuItems);
  }

  async showStartingConnectorsMenuFor(evt) {

    const menuItems = [[
      'Connections',
      () => this.showConnections(),
      'Opens all created connections',
      ''
      ], [
      'New Connection',
        [['On custom...', () => this.startCreatingConnectionCustom(evt)],
          ['On value', () => this.startCreatingConnectionFor(evt, 'value')],
         ['On other thing', () => this.startCreatingConnectionFor(evt, 'other')],
         ['Click', () => this.clickExample()]],
      'Creates a new connection',
      ''
    ]];

    this.showMenu(evt, menuItems);
  }

  async showFinishingConnectorsMenuFor(evt, morph){
    const menuItems = [[
      'On custom...',
      () => this.finishCreatingConnectionCustom()
    ],[
      'On width',
      () => this.finishCreatingConnection(morph, 'width')
    ],[
      'On height',
      () => this.finishCreatingConnection(morph, 'height')
    ]];

    this.showMenu(evt, menuItems);
  }

  elementUnderHand(evt) {
    var path = evt.composedPath().slice(evt.composedPath().indexOf(evt.srcElement))
    return path[0]
  }

  onPointerMove(evt) {
    //lively.showPoint(pt(evt.clientX, evt.clientY))
    //lively.notify('move')

    if (this.dropIndicator) this.dropIndicator.remove()
    this.dropTarget = this.elementUnderHand(evt)
    if (this.dropTarget) {
      this.dropIndicator = lively.showElement(this.dropTarget)
      this.dropIndicator.style.border = "3px dashed rgba(0,100,0,0.5)"
      this.dropIndicator.innerHTML = ""
    }
  }

  onPointerUp(evt) {
    //lively.notify('up')
    lively.removeEventListener("Connectors")

    if (this.dropIndicator) this.dropIndicator.remove()
    var morph = this.elementUnderHand(evt)

    this.showFinishingConnectorsMenuFor(evt, morph);
  }

   showConnections(){
    lively.openInspector(this.expressions);
  }

  async startCreatingConnectionCustom(evt){
    var userinput = await lively.prompt("Enter something", "value");
    this.startCreatingConnectionFor(evt, userinput);
  }

  startCreatingConnectionFor(evt, property){
    this.sourceProperty = property;

        lively.addEventListener("Connectors", document.body.parentElement, "pointermove",
      e => this.onPointerMove(e), { capture: true });
    lively.addEventListener("Connectors", document.body.parentElement, "pointerup",
      e => this.onPointerUp(e), { capture: true });
  }

  finishCreatingConnectionCustom(){
     lively.prompt("Enter something", "width")
  }

  finishCreatingConnection(target, targetProperty){
    //let ae = aexpr(() => code.boundEval(sourceObject));
    //ae.onChange(svalue => target.style.width= svalue+"pt");

    let ae = aexpr(() => this.source[this.sourceProperty]);
    ae.onChange(svalue => target.style[targetProperty]= svalue+"pt");

    this.expressions.push(ae);
  }

  clickExample(){
    this.source.addEventListener('click', event => lively.notify('la' + event))
  }

  //TODO DELETE
  /*
  let foo = '"width"'
  var code = `1+3`
  code.boundEval()
  */
}<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define(function() {
	"use strict";

	/**
	 * Font-Icon renderer.
	 * @namespace
	 * @alias sap.ui.core.IconRenderer
	 */
	var IconRenderer = {};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
	 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
	 */
	IconRenderer.render = function(oRm, oControl) {
		// write the HTML into the render manager
		var oIconInfo = sap.ui.core.IconPool.getIconInfo(oControl.getSrc()),
			sWidth = oControl.getWidth(),
			sHeight = oControl.getHeight(),
			sColor = oControl.getColor(),
			sBackgroundColor = oControl.getBackgroundColor(),
			sSize = oControl.getSize(),
			sTooltip = oControl.getTooltip_AsString(),
			bUseIconTooltip = oControl.getUseIconTooltip(),
			bNoTabStop = oControl.getNoTabStop();

		oRm.write("<span");
		oRm.writeControlData(oControl);
		oRm.writeAccessibilityState(oControl, oControl._getAccessibilityAttributes());

		if (sTooltip || (bUseIconTooltip && oIconInfo)) {
			oRm.writeAttribute("title", sTooltip || oIconInfo.text || oIconInfo.name);
		}

		if (oControl.hasListeners("press") && !bNoTabStop) {
			oRm.writeAttribute("tabindex", 0);
		}

		if (oIconInfo) {
			oRm.writeAttribute("data-sap-ui-icon-content", oIconInfo.content);
			oRm.addStyle("font-family", "'" + oIconInfo.fontFamily + "'");
		}

		if (sWidth) {
			oRm.addStyle("width", sWidth);
		}

		if (sHeight) {
			oRm.addStyle("height", sHeight);
			oRm.addStyle("line-height", sHeight);
		}

		if (!(sColor in sap.ui.core.IconColor)) {
			oRm.addStyle("color", sColor);
		}

		if (!(sBackgroundColor in sap.ui.core.IconColor)) {
			oRm.addStyle("background-color", sBackgroundColor);
		}

		if (sSize) {
			oRm.addStyle("font-size", sSize);
		}

		oRm.addClass("sapUiIcon");

		if (oIconInfo && !oIconInfo.suppressMirroring) {
			oRm.addClass("sapUiIconMirrorInRTL");
		}

		if (oControl.hasListeners("press")) {
			oRm.addClass("sapUiIconPointer");
		}

		oRm.writeClasses();
		oRm.writeStyles();

		oRm.write(">");
	};

	return IconRenderer;

}, /* bExport= */ true);
<commit_msg>[INTERNAL][FIX] Icon rendering<commit_after>/*!
 * ${copyright}
 */
sap.ui.define(function() {
	"use strict";

	/**
	 * Font-Icon renderer.
	 * @namespace
	 * @alias sap.ui.core.IconRenderer
	 */
	var IconRenderer = {};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
	 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
	 */
	IconRenderer.render = function(oRm, oControl) {
		// write the HTML into the render manager
		var oIconInfo = sap.ui.core.IconPool.getIconInfo(oControl.getSrc()),
			sWidth = oControl.getWidth(),
			sHeight = oControl.getHeight(),
			sColor = oControl.getColor(),
			sBackgroundColor = oControl.getBackgroundColor(),
			sSize = oControl.getSize(),
			sTooltip = oControl.getTooltip_AsString(),
			bUseIconTooltip = oControl.getUseIconTooltip(),
			bNoTabStop = oControl.getNoTabStop();

		oRm.write("<span");
		oRm.writeControlData(oControl);
		oRm.writeAccessibilityState(oControl, oControl._getAccessibilityAttributes());

		if (sTooltip || (bUseIconTooltip && oIconInfo)) {
			oRm.writeAttributeEscaped("title", sTooltip || oIconInfo.text || oIconInfo.name);
		}

		if (oControl.hasListeners("press") && !bNoTabStop) {
			oRm.writeAttribute("tabindex", 0);
		}

		if (oIconInfo) {
			oRm.writeAttribute("data-sap-ui-icon-content", oIconInfo.content);
			oRm.addStyle("font-family", "'" + oIconInfo.fontFamily + "'");
		}

		if (sWidth) {
			oRm.addStyle("width", sWidth);
		}

		if (sHeight) {
			oRm.addStyle("height", sHeight);
			oRm.addStyle("line-height", sHeight);
		}

		if (!(sColor in sap.ui.core.IconColor)) {
			oRm.addStyle("color", sColor);
		}

		if (!(sBackgroundColor in sap.ui.core.IconColor)) {
			oRm.addStyle("background-color", sBackgroundColor);
		}

		if (sSize) {
			oRm.addStyle("font-size", sSize);
		}

		oRm.addClass("sapUiIcon");

		if (oIconInfo && !oIconInfo.suppressMirroring) {
			oRm.addClass("sapUiIconMirrorInRTL");
		}

		if (oControl.hasListeners("press")) {
			oRm.addClass("sapUiIconPointer");
		}

		oRm.writeClasses();
		oRm.writeStyles();

		oRm.write(">");
	};

	return IconRenderer;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>/**
* jQuery Overview - A viewport/content length overview
* ====================================================
* jQuery Overview displays two rectangles representing each one the content and the viewport.
*
* Licensed under The MIT License
*
* @version   0.1
* @since     11.27.2010
* @author    Jose Rui Santos
*
*
* Input parameter  Default value  Remarks
* ================ =============  ===============================================================================================
* viewport:        window         The element being monitored by the plug-in.
* center:          true           Whether to center the rendering of the inner DIVs relatively to the outer DIV.
* autoHide:        false          Whether to hide the plug-in when the content has the same size or is smaller than the viewport.
* scrollSpeed:     'slow'         Speed used by the browser to move a selected canvas position
*
*
* Usage with default values:
* ==========================
* $('#overview').rsOverview();
*
*

*

*

*

*
* #overview {
*     position: fixed;
*     width: 200px;
*     height: 300px;
* }
*
* #overview div {
*     position: absolute;
* }
*
*/
(function ($) {
    $.fn.rsOverview = function (options) {
        var coef;           // cache used to scale graphically
        var content = {     // the content element being monitoried. By default, content is the whole document
            obj: null,
            sizeX: 0,
            sizeY: 0,
            resized: function (object) {
                this.sizeX = object.width();
                this.sizeY = object.height();
            }
        };
        var viewport = {    // the viewport element being monitoried. By default, viewport is the browser window
            obj: null,
            sizeX: 0,
            sizeY: 0,
            resized: function () {
                this.sizeX = this.obj.width();
                this.sizeY = this.obj.height();
            }
        };

        // defaults input parameters
        var defaults = {
            viewport: window,
            center: true,
            autoHide: false,
            scrollSpeed: 'medium'
        },

        onResize =
            function (event) {
                if (defaults.viewport === window) {
                    content.resized(content.obj);
                } else {
                    // get the overflowed content
                    var overflowedHtml = content.obj.html();
                    try {
                        // hidden div used to calculate the dimensions of an overflowed div
                        content.obj.prepend('

');
                        var calc = $("div:eq(0)", content.obj); // selects the div created above
                        calc.html(overflowedHtml); // place the content in this temp div
                        content.resized(calc); // use this temp div to calculate the content size
                    } finally {
                        content.obj.html(overflowedHtml);
                    }
                }
                viewport.resized(viewport.obj);

                if (defaults.autoHide) {
                    if (content.sizeX <= viewport.sizeX && content.sizeY <= viewport.sizeY) {
                        $(this).hide();
                        return;
                    }
                    $(this).show();
                }

                $(this).trigger('rsOverview.render');
            },

        onRender =
            function (event) {
                var overviewCtrl = $(this);
                var coefX = content.sizeX / overviewCtrl.width();
                var coefY = content.sizeY / overviewCtrl.height();
                var scrollbarPixels = defaults.viewport === window ? 0 : scrollbarWidth();
                coef = coefX > coefY ? coefX : coefY;
                coefX = (viewport.sizeX - scrollbarPixels) / overviewCtrl.width();
                coefY = (viewport.sizeY - scrollbarPixels) / overviewCtrl.height();
                coef = coefX > coefY ? (coefX > coef ? coefX : coef) : (coefY > coef ? coefY : coef);

                // compute inner DIV size that corresponds to the size of the content being monitored
                var calcWidth = content.sizeX / coef;
                var calcHeight = content.sizeY / coef;
                var innerContentDiv = $('div:eq(0)', this).width(calcWidth).height(calcHeight);
                if (defaults.center) {
                    innerContentDiv.
                        css('left', (overviewCtrl.width() - calcWidth) / 2).
                        css('top', (overviewCtrl.height() - calcHeight) / 2);
                }

                // compute inner DIV size and position that corresponds to the size and position of the viewport monitored
                calcWidth = (viewport.sizeX - scrollbarPixels) / coef;
                calcHeight = (viewport.sizeY - scrollbarPixels) / coef;
                $('div:eq(1)', this).
                    width(calcWidth).
                    height(calcHeight).
                    css('left', (viewport.obj.scrollLeft() / coef) + (defaults.center ? innerContentDiv.position().left : 0)).
                    css('top', (viewport.obj.scrollTop() / coef) + (defaults.center ? innerContentDiv.position().top : 0));
            },

        // returns the width of a vertical scroll bar in pixels (same as height of an horizontal scroll bar)
        scrollbarWidth =
            function () {
                // create a div with overflow: scroll (which forces scrollbars to appear)
                var calcDiv = $("

");
                // place it in DOM
                $("body").append(calcDiv);
                try {
                    return 100 - calcDiv[0].clientWidth;
                } finally {
                    calcDiv.remove();
                }
            };

        return this.each(function () {
            var overviewCtrl = $(this);

            // if options is not empty, then merge with the default settings
            if (options) {
                $.extend(defaults, options);
            }

            // elements being monitorized for scroll and resize events
            viewport.obj = $(defaults.viewport);
            if (defaults.viewport === window) {
                content.obj = $(document);
            } else {
                content.obj = viewport.obj;
            }

            // when the viewport is scrolled or when is resized, the plugin is updated
            viewport.obj.scroll(function () {
                overviewCtrl.trigger('rsOverview.render');
            }).resize(function () {
                overviewCtrl.trigger('rsOverview.resize');
            });

            // div:eq(0) selects the content
            // div:eq(1) selects the viewport
            $("div:eq(1)", overviewCtrl).mousedown(function (e) {
                var dragInfo = {
                    initPos: $(this).offset(),
                    initClickX: e.pageX,
                    initClickY: e.pageY
                };

                // prevents text selection during drag
                this.onselectstart = function () {
                    return false;
                };

                $(this).bind('mousemove', function (e) {
                    var innerDIVcontent = $("div:eq(0)", overviewCtrl);
                    viewport.obj.
                        scrollLeft(coef * (e.pageX - dragInfo.initClickX + dragInfo.initPos.left - overviewCtrl.position().left - innerDIVcontent.position().left)).
                        scrollTop(coef * (e.pageY - dragInfo.initClickY + dragInfo.initPos.top - overviewCtrl.position().top - innerDIVcontent.position().top));
                });
                e.preventDefault();
            });

            // the mouseup event might happen outside the plugin, so to make sure the unbind always runs, it must done on body level
            $("body").mouseup(function () {
                $("div:eq(1)", overviewCtrl).unbind('mousemove');
            });

            // mouse click on the content: scroll jumps directly to that position
            $("div:eq(0)", overviewCtrl).mousedown(function (e) {
                (defaults.viewport === window ? $("body, html") : viewport.obj).animate({
                    scrollLeft: coef * (e.pageX - overviewCtrl.position().left - $(this).position().left),
                    scrollTop: coef * (e.pageY - overviewCtrl.position().top - $(this).position().top)
                }, defaults.scrollSpeed);
                e.preventDefault();
            });

            overviewCtrl.bind('rsOverview.resize', onResize);
            overviewCtrl.bind('rsOverview.render', onRender);

            // graphical initialization when plugin is called (after page and DOM are loaded)
            overviewCtrl.trigger('rsOverview.resize');
        });
    };
})(jQuery);
<commit_msg>correction to the comments<commit_after>/**
* jQuery Overview - A viewport/content length overview
* ====================================================
* jQuery Overview displays two rectangles representing each one the content and the viewport.
*
* Licensed under The MIT License
*
* @version   0.1
* @since     11.27.2010
* @author    Jose Rui Santos
*
*
* Input parameter  Default value  Remarks
* ================ =============  ===============================================================================================
* viewport:        window         The element being monitored by the plug-in.
* center:          true           Whether to center the rendering of the inner DIVs relatively to the outer DIV.
* autoHide:        false          Whether to hide the plug-in when the content has the same size or is smaller than the viewport.
* scrollSpeed:     'medium'       Speed used by the browser to move a selected canvas position
*
*
* Usage with default values:
* ==========================
* $('#overview').rsOverview();
*
*

*

*

*

*
* #overview {
*     position: fixed;
*     width: 200px;
*     height: 300px;
* }
*
* #overview div {
*     position: absolute;
* }
*
*/
(function ($) {
    $.fn.rsOverview = function (options) {
        var coef;           // cache used to scale graphically
        var content = {     // the content element being monitoried. By default, content is the whole document
            obj: null,
            sizeX: 0,
            sizeY: 0,
            resized: function (object) {
                this.sizeX = object.width();
                this.sizeY = object.height();
            }
        };
        var viewport = {    // the viewport element being monitoried. By default, viewport is the browser window
            obj: null,
            sizeX: 0,
            sizeY: 0,
            resized: function () {
                this.sizeX = this.obj.width();
                this.sizeY = this.obj.height();
            }
        };

        // defaults input parameters
        var defaults = {
            viewport: window,
            center: true,
            autoHide: false,
            scrollSpeed: 'medium'
        },

        onResize =
            function (event) {
                if (defaults.viewport === window) {
                    content.resized(content.obj);
                } else {
                    // get the overflowed content
                    var overflowedHtml = content.obj.html();
                    try {
                        // hidden div used to calculate the dimensions of an overflowed div
                        content.obj.prepend('

');
                        var calc = $("div:eq(0)", content.obj); // selects the div created above
                        calc.html(overflowedHtml); // place the content in this temp div
                        content.resized(calc); // use this temp div to calculate the content size
                    } finally {
                        content.obj.html(overflowedHtml);
                    }
                }
                viewport.resized(viewport.obj);

                if (defaults.autoHide) {
                    if (content.sizeX <= viewport.sizeX && content.sizeY <= viewport.sizeY) {
                        $(this).hide();
                        return;
                    }
                    $(this).show();
                }

                $(this).trigger('rsOverview.render');
            },

        onRender =
            function (event) {
                var overviewCtrl = $(this);
                var coefX = content.sizeX / overviewCtrl.width();
                var coefY = content.sizeY / overviewCtrl.height();
                var scrollbarPixels = defaults.viewport === window ? 0 : scrollbarWidth();
                coef = coefX > coefY ? coefX : coefY;
                coefX = (viewport.sizeX - scrollbarPixels) / overviewCtrl.width();
                coefY = (viewport.sizeY - scrollbarPixels) / overviewCtrl.height();
                coef = coefX > coefY ? (coefX > coef ? coefX : coef) : (coefY > coef ? coefY : coef);

                // compute inner DIV size that corresponds to the size of the content being monitored
                var calcWidth = content.sizeX / coef;
                var calcHeight = content.sizeY / coef;
                var innerContentDiv = $('div:eq(0)', this).width(calcWidth).height(calcHeight);
                if (defaults.center) {
                    innerContentDiv.
                        css('left', (overviewCtrl.width() - calcWidth) / 2).
                        css('top', (overviewCtrl.height() - calcHeight) / 2);
                }

                // compute inner DIV size and position that corresponds to the size and position of the viewport monitored
                calcWidth = (viewport.sizeX - scrollbarPixels) / coef;
                calcHeight = (viewport.sizeY - scrollbarPixels) / coef;
                $('div:eq(1)', this).
                    width(calcWidth).
                    height(calcHeight).
                    css('left', (viewport.obj.scrollLeft() / coef) + (defaults.center ? innerContentDiv.position().left : 0)).
                    css('top', (viewport.obj.scrollTop() / coef) + (defaults.center ? innerContentDiv.position().top : 0));
            },

        // returns the width of a vertical scroll bar in pixels (same as height of an horizontal scroll bar)
        scrollbarWidth =
            function () {
                // create a div with overflow: scroll (which forces scrollbars to appear)
                var calcDiv = $("

");
                // place it in DOM
                $("body").append(calcDiv);
                try {
                    return 100 - calcDiv[0].clientWidth;
                } finally {
                    calcDiv.remove();
                }
            };

        return this.each(function () {
            var overviewCtrl = $(this);

            // if options is not empty, then merge with the default settings
            if (options) {
                $.extend(defaults, options);
            }

            // elements being monitorized for scroll and resize events
            viewport.obj = $(defaults.viewport);
            if (defaults.viewport === window) {
                content.obj = $(document);
            } else {
                content.obj = viewport.obj;
            }

            // when the viewport is scrolled or when is resized, the plugin is updated
            viewport.obj.scroll(function () {
                overviewCtrl.trigger('rsOverview.render');
            }).resize(function () {
                overviewCtrl.trigger('rsOverview.resize');
            });

            // div:eq(0) selects the content
            // div:eq(1) selects the viewport
            $("div:eq(1)", overviewCtrl).mousedown(function (e) {
                var dragInfo = {
                    initPos: $(this).offset(),
                    initClickX: e.pageX,
                    initClickY: e.pageY
                };

                // prevents text selection during drag
                this.onselectstart = function () {
                    return false;
                };

                $(this).bind('mousemove', function (e) {
                    var innerDIVcontent = $("div:eq(0)", overviewCtrl);
                    viewport.obj.
                        scrollLeft(coef * (e.pageX - dragInfo.initClickX + dragInfo.initPos.left - overviewCtrl.position().left - innerDIVcontent.position().left)).
                        scrollTop(coef * (e.pageY - dragInfo.initClickY + dragInfo.initPos.top - overviewCtrl.position().top - innerDIVcontent.position().top));
                });
                e.preventDefault();
            });

            // the mouseup event might happen outside the plugin, so to make sure the unbind always runs, it must done on body level
            $("body").mouseup(function () {
                $("div:eq(1)", overviewCtrl).unbind('mousemove');
            });

            // mouse click on the content: scroll jumps directly to that position
            $("div:eq(0)", overviewCtrl).mousedown(function (e) {
                (defaults.viewport === window ? $("body, html") : viewport.obj).animate({
                    scrollLeft: coef * (e.pageX - overviewCtrl.position().left - $(this).position().left),
                    scrollTop: coef * (e.pageY - overviewCtrl.position().top - $(this).position().top)
                }, defaults.scrollSpeed);
                e.preventDefault();
            });

            overviewCtrl.bind('rsOverview.resize', onResize);
            overviewCtrl.bind('rsOverview.render', onRender);

            // graphical initialization when plugin is called (after page and DOM are loaded)
            overviewCtrl.trigger('rsOverview.resize');
        });
    };
})(jQuery);
<|endoftext|>