<commit_before>/*
Requires parameters so load https://megjlow.github.io/extensionloader.js and use that block to load this one.
Parameters are:
name - 	If you have a router set up which will assign the same IP address to a tile every time and will do DNS then the tile can be addressed
		by name e.g. http://SUN/XXX will work if SUN resolves to the IP address of a tile e.g. https://megjlow.github.io/extension2.js?name=SUN
ip -	If you don't have a router set up to assign the same IP address to a tile every time or you don't have DNS which will resolve the tile
		name then use the IP parameter e.g. https://megjlow.github.io/extension2.js?ip=10.0.0.1 will load the tile extension which communicates
		with a tile at the IP address 10.0.0.1

If both name and ip are supplied then name will be used before ip.
Digital pins 1, 2 and 3 map to the Feather Huzzah pins 12, 13 and 14
Pwm pins 1 and 2 map to the Feather Huzza pins 4 and 5
*/

new (function() {
	var ext = this;
	ext.isReady = false;
	ext.socket = null;
	ext.messageQueue = {};

 	var getUrlParameter = function getUrlParameter(sParam) {
	    var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]),
	        sURLVariables = sPageURL.split('&'),
	        sParameterName,
	        i;

	    for (i = 0; i < sURLVariables.length; i++) {
	        sParameterName = sURLVariables[i].split('=');

	        if (sParameterName[0] === sParam) {
	            return sParameterName[1] === undefined ? true : sParameterName[1];
	        }
	    }
	};

	ext.name = getUrlParameter('name');
	ext.ip = getUrlParameter('ip');

	if(ext.name != undefined) {
		// we'll use the name supplied by preference
		ext.url = "http://" + ext.name;
		console.log('got name');
	}
	else {
		// no name supplied so use the IP address
		ext.url = "http://" + ext.ip;
		console.log("didn't get name");
	}

	console.log('name ' + ext.name);
	console.log('ip ' + ext.ip);
	console.log('using url ' + ext.url);

	var descriptor = {
    	blocks: [
      		[' ', ext.name + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
      		[' ', ext.name + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
      		[' ', ext.name + ': digital pin %m.pin get', 'getDigital', '1'],
      		[' ', ext.name + ': pwm pin %m.ppin get', 'getPwm', '1']
    	],
    	'menus': {
      		'pin': ['1', '2', '3'],
      		'dsetting': ['on', 'off'],
      		'ppin': ['1', '2']
     	},
    	url: 'http://www.warwick.ac.uk/tilesfortales'
  	};

  	if(ext.name == undefined) {
  		var descriptor = {
	    	blocks: [
				[' ', ext.ip + ': connect', 'connect'],
				[' ', ext.ip + ': disconnect', 'disconnect'],
				['b', ext.ip + ': isConnected', 'isConnected'],
				[' ', ext.ip + ': setPinMode %m.pin %m.io %m.ioMode', 'setPinMode', 0, 'output', 'digital'],
	      		[' ', ext.ip + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
	      		[' ', ext.ip + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
	      		['R', ext.ip + ': digital pin %m.pin get', 'getDigital', '1'],
	      		[' ', ext.ip + ': pwm pin %m.ppin get', 'getPwm', '1']
	    	],
	    	'menus': {
	      		'pin': ['1', '2', '3'],
	      		'dsetting': ['on', 'off'],
	      		'ppin': ['1', '2'],
				'io': ['output', 'input'],
				'ioMode': ['digital', 'pwm']
	     	},
	    	url: 'http://www.warwick.ac.uk/tilesfortales'
	  	};
  	}

  ext._shutdown = function() {};

  ext.setPinMode = function(pin, mode) {
    console.log("setPinMode " + pin);
    console.log("setPinMode " + mode);
    var bytearray = new Uint8Array(3);
    /*
    bytearray[0] = 0xF0;
    bytearray[1] = 0x69;
    bytearray[2] = 0xF7;
    ext.socket.send(bytearray.buffer);
    */

    bytearray[0] = 0xF4;// PIN_MODE;
    bytearray[1] = pin;
    bytearray[2] = 0x01; // output
    ext.socket.send(bytearray.buffer);

    console.log("sent");

  }

  ext.isConnected = function() {
    var retval = false;
    if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
      retval = true;
    }
    return retval;
  }

  ext.disconnect = function() {
    if(ext.socket != null) {
      ext.socket.close();
      ext.socket = null;
    }
  }

  ext.onMessage = function(evt)
  {
    var dv = new DataView(evt.data);
    var r = "received message: ";
    for(var i=0; i<dv.byteLength; i++) {
    	r = r + " " + dv.getUint8(i).toString(16);
    }

    if(dv.byteLength > 0) {
    	var op = dv.getUint8(0);
    	/*
    	if(dv.getUint8(0) == 0xFO) { // start sysex
    		if(dv.getUint8(1) == 0x6E) { // pin state response
    			// 2 will be pin number, 3 will be state
    			var pin = dv.getUint8(2);
    			var state = dv.getUint8(3);
    			if(ext.messageQueue["pin-state-" + pin] != undefined) {
    				console.log("got handler");
    			}
    		}
    	}
    	*/
    }

    // 6e PIN_STATE_RESPONSE

   	console.log(r);
  }

  ext.doSend = function(message)
  {
    console.log("SENT: " + message);
    ext.socket.send(message);
  }

  ext.onOpen = function(evt)
  {
    console.log("Connected");
    ext.doSend("WebSocket rocks");
  }

  ext.onClose = function(evt) {
    ext.socket = null;
  }

  ext._getStatus = function() {
    var retval = {status: 1, msg: 'Not Connected'};
    if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
      retval = {status: 2, msg: 'Device connected'};
    }
    return retval;
  };

  ext.connect = function() {
    if(ext.socket == null) {
      ext.socket = new WebSocket("ws://" + ext.ip, 'firmata');
      ext.socket.binaryType = "arraybuffer";
      ext.socket.onopen = function(evt) {ext.onOpen(evt)};
      ext.socket.onmessage = function(evt) {ext.onMessage(evt)};
      ext.socket.onclose = function(evt) {ext.onClose(evt)};
    }
    else {
      if(ext.socket.readyState == ext.socket.CLOSING || ext.socket.readyState == ext.socket.CLOSED) {
	ext.socket = null;
        ext.connect();
      }
    }
    // if socket is in open or connecting state we're not going to do anything
  }

  ext.getPwm = function(pin) {
  };
  ext.setPwm = function(pin, setting) {
    var p = 4;
    if(pin == 2) {
      p = 5;
    }
    var url = ext.url + '/gpio' + p + '/' + setting;
    $.ajax({
      type: 'POST',
      url: url,
      success: function(response) {
      }
    });
    setTimeout(function(){ }, 10);
  };

  	ext.getDigital = function(pin, callback) {
  		var bytearray = new Uint8Array(4);
  		bytearray[0] = 0xF0; // Start sysex
  		bytearray[1] = 0x6D; // PIN_STATE_QUERY
  		bytearray[2] = pin;
  		bytearray[3] = 0xF7; // end sysex
  		ext.socket.send(bytearray);

		ext.messageQueue["pin-state-" + pin] = callback;
		console.log("ext.getDigital");
		setTimeout(() => { ext.messageQueue["pin-state-" + pin](10); }, 2000);
		console.log("ext.getDigital complete");
		//setTimeout(() => { callback(10); }, 2000);
	};

	ext.setDigital = function(pin, setting) {
	    var s = 1;
	    if(setting == 'off') {
	      s = 0;
	    }
	    var bytearray = new Uint8Array(3);
	    bytearray[0] = 0xF5; // set digital pin value
	    bytearray[1] = pin;
	    bytearray[2] = s;

	    ext.socket.send(bytearray);

	    console.log("setDigital");
	};

	if(ext.name != undefined) {
		ScratchExtensions.register(ext.name, descriptor, ext);
	}
	else {
		ScratchExtensions.register(ext.ip, descriptor, ext);
	}

})();
<commit_msg>getDigital<commit_after>/*
Requires parameters so load https://megjlow.github.io/extensionloader.js and use that block to load this one.
Parameters are:
name - 	If you have a router set up which will assign the same IP address to a tile every time and will do DNS then the tile can be addressed
		by name e.g. http://SUN/XXX will work if SUN resolves to the IP address of a tile e.g. https://megjlow.github.io/extension2.js?name=SUN
ip -	If you don't have a router set up to assign the same IP address to a tile every time or you don't have DNS which will resolve the tile
		name then use the IP parameter e.g. https://megjlow.github.io/extension2.js?ip=10.0.0.1 will load the tile extension which communicates
		with a tile at the IP address 10.0.0.1

If both name and ip are supplied then name will be used before ip.
Digital pins 1, 2 and 3 map to the Feather Huzzah pins 12, 13 and 14
Pwm pins 1 and 2 map to the Feather Huzza pins 4 and 5
*/

new (function() {
	var ext = this;
	ext.isReady = false;
	ext.socket = null;
	ext.messageQueue = {};

 	var getUrlParameter = function getUrlParameter(sParam) {
	    var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]),
	        sURLVariables = sPageURL.split('&'),
	        sParameterName,
	        i;

	    for (i = 0; i < sURLVariables.length; i++) {
	        sParameterName = sURLVariables[i].split('=');

	        if (sParameterName[0] === sParam) {
	            return sParameterName[1] === undefined ? true : sParameterName[1];
	        }
	    }
	};

	ext.name = getUrlParameter('name');
	ext.ip = getUrlParameter('ip');

	if(ext.name != undefined) {
		// we'll use the name supplied by preference
		ext.url = "http://" + ext.name;
		console.log('got name');
	}
	else {
		// no name supplied so use the IP address
		ext.url = "http://" + ext.ip;
		console.log("didn't get name");
	}

	console.log('name ' + ext.name);
	console.log('ip ' + ext.ip);
	console.log('using url ' + ext.url);

	var descriptor = {
    	blocks: [
      		[' ', ext.name + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
      		[' ', ext.name + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
      		[' ', ext.name + ': digital pin %m.pin get', 'getDigital', '1'],
      		[' ', ext.name + ': pwm pin %m.ppin get', 'getPwm', '1']
    	],
    	'menus': {
      		'pin': ['1', '2', '3'],
      		'dsetting': ['on', 'off'],
      		'ppin': ['1', '2']
     	},
    	url: 'http://www.warwick.ac.uk/tilesfortales'
  	};

  	if(ext.name == undefined) {
  		var descriptor = {
	    	blocks: [
				[' ', ext.ip + ': connect', 'connect'],
				[' ', ext.ip + ': disconnect', 'disconnect'],
				['b', ext.ip + ': isConnected', 'isConnected'],
				[' ', ext.ip + ': setPinMode %m.pin %m.io %m.ioMode', 'setPinMode', 0, 'output', 'digital'],
	      		[' ', ext.ip + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
	      		[' ', ext.ip + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
	      		['R', ext.ip + ': digital pin %m.pin get', 'getDigital', '1'],
	      		[' ', ext.ip + ': pwm pin %m.ppin get', 'getPwm', '1']
	    	],
	    	'menus': {
	      		'pin': ['1', '2', '3'],
	      		'dsetting': ['on', 'off'],
	      		'ppin': ['1', '2'],
				'io': ['output', 'input'],
				'ioMode': ['digital', 'pwm']
	     	},
	    	url: 'http://www.warwick.ac.uk/tilesfortales'
	  	};
  	}

  ext._shutdown = function() {};

  ext.setPinMode = function(pin, mode) {
    console.log("setPinMode " + pin);
    console.log("setPinMode " + mode);
    var bytearray = new Uint8Array(3);
    /*
    bytearray[0] = 0xF0;
    bytearray[1] = 0x69;
    bytearray[2] = 0xF7;
    ext.socket.send(bytearray.buffer);
    */

    bytearray[0] = 0xF4;// PIN_MODE;
    bytearray[1] = pin;
    bytearray[2] = 0x01; // output
    ext.socket.send(bytearray.buffer);

    console.log("sent");

  }

  ext.isConnected = function() {
    var retval = false;
    if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
      retval = true;
    }
    return retval;
  }

  ext.disconnect = function() {
    if(ext.socket != null) {
      ext.socket.close();
      ext.socket = null;
    }
  }

  ext.onMessage = function(evt)
  {
    var dv = new DataView(evt.data);
    var r = "received message: ";
    for(var i=0; i<dv.byteLength; i++) {
    	r = r + " " + dv.getUint8(i).toString(16);
    }

    if(dv.byteLength > 0) {
    	if(dv.getUint8(0) == 0xF0) { // start sysex
    		if(dv.getUint8(1) == 0x6E) { // pin state response
    			// 2 will be pin number, 3 will be state
    			var pin = dv.getUint8(2);
    			var state = dv.getUint8(3);
    			if(ext.messageQueue["pin-state-" + pin] != undefined) {
    				console.log("got handler");
    			}
    		}
    	}
    }

    // 6e PIN_STATE_RESPONSE

   	console.log(r);
  }

  ext.doSend = function(message)
  {
    console.log("SENT: " + message);
    ext.socket.send(message);
  }

  ext.onOpen = function(evt)
  {
    console.log("Connected");
    ext.doSend("WebSocket rocks");
  }

  ext.onClose = function(evt) {
    ext.socket = null;
  }

  ext._getStatus = function() {
    var retval = {status: 1, msg: 'Not Connected'};
    if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
      retval = {status: 2, msg: 'Device connected'};
    }
    return retval;
  };

  ext.connect = function() {
    if(ext.socket == null) {
      ext.socket = new WebSocket("ws://" + ext.ip, 'firmata');
      ext.socket.binaryType = "arraybuffer";
      ext.socket.onopen = function(evt) {ext.onOpen(evt)};
      ext.socket.onmessage = function(evt) {ext.onMessage(evt)};
      ext.socket.onclose = function(evt) {ext.onClose(evt)};
    }
    else {
      if(ext.socket.readyState == ext.socket.CLOSING || ext.socket.readyState == ext.socket.CLOSED) {
	ext.socket = null;
        ext.connect();
      }
    }
    // if socket is in open or connecting state we're not going to do anything
  }

  ext.getPwm = function(pin) {
  };
  ext.setPwm = function(pin, setting) {
    var p = 4;
    if(pin == 2) {
      p = 5;
    }
    var url = ext.url + '/gpio' + p + '/' + setting;
    $.ajax({
      type: 'POST',
      url: url,
      success: function(response) {
      }
    });
    setTimeout(function(){ }, 10);
  };

  	ext.getDigital = function(pin, callback) {
  		var bytearray = new Uint8Array(4);
  		bytearray[0] = 0xF0; // Start sysex
  		bytearray[1] = 0x6D; // PIN_STATE_QUERY
  		bytearray[2] = pin;
  		bytearray[3] = 0xF7; // end sysex
  		ext.socket.send(bytearray);

		ext.messageQueue["pin-state-" + pin] = callback;
		console.log("ext.getDigital");
		setTimeout(() => { ext.messageQueue["pin-state-" + pin](10); }, 2000);
		console.log("ext.getDigital complete");
		//setTimeout(() => { callback(10); }, 2000);
	};

	ext.setDigital = function(pin, setting) {
	    var s = 1;
	    if(setting == 'off') {
	      s = 0;
	    }
	    var bytearray = new Uint8Array(3);
	    bytearray[0] = 0xF5; // set digital pin value
	    bytearray[1] = pin;
	    bytearray[2] = s;

	    ext.socket.send(bytearray);

	    console.log("setDigital");
	};

	if(ext.name != undefined) {
		ScratchExtensions.register(ext.name, descriptor, ext);
	}
	else {
		ScratchExtensions.register(ext.ip, descriptor, ext);
	}

})();
<|endoftext|>


<commit_before>/* eslint no-param-reassign: 0 */
// This config is for building dist files
const chalk = require('chalk');
const getWebpackConfig = require('@ant-design/tools/lib/getWebpackConfig');
const RemovePlugin = require('remove-files-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const darkVars = require('./scripts/dark-vars');
const compactVars = require('./scripts/compact-vars');

function injectLessVariables(config, variables) {
  (Array.isArray(config) ? config : [config]).forEach(conf => {
    conf.module.rules.forEach(rule => {
      // filter less rule
      if (rule.test instanceof RegExp && rule.test.test('.less')) {
        const lessRule = rule.use[rule.use.length - 1];
        if (lessRule.options.lessOptions) {
          lessRule.options.lessOptions.modifyVars = {
            ...lessRule.options.lessOptions.modifyVars,
            ...variables,
          };
        } else {
          lessRule.options.modifyVars = {
            ...lessRule.options.modifyVars,
            ...variables,
          };
        }
      }
    });
  });

  return config;
}

function addLocales(webpackConfig) {
  let packageName = 'antd-with-locales';
  if (webpackConfig.entry['antd.min']) {
    packageName += '.min';
  }
  webpackConfig.entry[packageName] = './index-with-locales.js';
  webpackConfig.output.filename = '[name].js';
}

function injectWarningCondition(config) {
  config.module.rules.forEach(rule => {
    // Remove devWarning if needed
    if (rule.test.test('test.tsx')) {
      rule.use = [
        ...rule.use,
        {
          loader: 'string-replace-loader',
          options: {
            search: 'devWarning(',
            replace: "if (process.env.NODE_ENV !== 'production') devWarning(",
          },
        },
      ];
    }
  });
}

function processWebpackThemeConfig(themeConfig, theme, vars) {
  themeConfig.forEach(config => {
    // rename default entry to ${theme} entry
    Object.keys(config.entry).forEach(entryName => {
      const originPath = config.entry[entryName];
      let replacedPath = [...originPath];

      // We will replace `./index` to `./index-style-only` since theme dist only use style file
      if (originPath.length === 1 && originPath[0] === './index') {
        replacedPath = ['./index-style-only'];
      } else {
        // eslint-disable-next-line no-console
        console.log(chalk.red('🆘 Seems entry has changed! It should be `./index`'));
      }

      config.entry[entryName.replace('antd', `antd.${theme}`)] = replacedPath;
      delete config.entry[entryName];
    });

    // apply ${theme} less variables
    injectLessVariables(config, vars);

    // ignore emit ${theme} entry js & js.map file
    config.plugins.push(
      new RemovePlugin({
        after: {
          root: './dist',
          include: [
            `antd.${theme}.js`,
            `antd.${theme}.js.map`,
            `antd.${theme}.min.js`,
            `antd.${theme}.min.js.map`,
          ],
          log: false,
          logWarning: false,
        },
      }),
    );
  });
}

const legacyEntryVars = {
  'root-entry-name': 'default',
};
const webpackConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackDarkConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackCompactConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackVariableConfig = injectLessVariables(getWebpackConfig(false), {
  'root-entry-name': 'variable',
});

webpackConfig.forEach(config => {
  injectWarningCondition(config);
});

if (process.env.RUN_ENV === 'PRODUCTION') {
  webpackConfig.forEach(config => {
    addLocales(config);
    // Reduce non-minified dist files size
    config.optimization.usedExports = true;
    // use esbuild
    if (process.env.ESBUILD || process.env.CSB_REPO) {
      config.optimization.minimizer[0] = new ESBuildMinifyPlugin({
        target: 'es2015',
        css: true,
      });
    }

    config.plugins.push(
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false,
        reportFilename: '../report.html',
      }),
    );

    if (!process.env.NO_DUP_CHECK) {
      config.plugins.push(
        new DuplicatePackageCheckerPlugin({
          verbose: true,
          emitError: true,
        }),
      );
    }
  });

  processWebpackThemeConfig(webpackDarkConfig, 'dark', darkVars);
  processWebpackThemeConfig(webpackCompactConfig, 'compact', compactVars);
  processWebpackThemeConfig(webpackVariableConfig, 'variable', {});
}

module.exports = [
  ...webpackConfig,
  ...webpackDarkConfig,
  ...webpackCompactConfig,
  ...webpackVariableConfig,
];
<commit_msg>update test<commit_after>/* eslint no-param-reassign: 0 */
// This config is for building dist files
const chalk = require('chalk');
const getWebpackConfig = require('@ant-design/tools/lib/getWebpackConfig');
const RemovePlugin = require('remove-files-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const darkVars = require('./scripts/dark-vars');
const compactVars = require('./scripts/compact-vars');

function injectLessVariables(config, variables) {
  (Array.isArray(config) ? config : [config]).forEach(conf => {
    conf.module.rules.forEach(rule => {
      // filter less rule
      if (rule.test instanceof RegExp && rule.test.test('.less')) {
        const lessRule = rule.use[rule.use.length - 1];
        if (lessRule.options.lessOptions) {
          lessRule.options.lessOptions.modifyVars = {
            ...lessRule.options.lessOptions.modifyVars,
            ...variables,
          };
        } else {
          lessRule.options.modifyVars = {
            ...lessRule.options.modifyVars,
            ...variables,
          };
        }
      }
    });
  });

  return config;
}

function addLocales(webpackConfig) {
  let packageName = 'antd-with-locales';
  if (webpackConfig.entry['antd.min']) {
    packageName += '.min';
  }
  webpackConfig.entry[packageName] = './index-with-locales.js';
  webpackConfig.output.filename = '[name].js';
}

function injectWarningCondition(config) {
  config.module.rules.forEach(rule => {
    // Remove devWarning if needed
    if (rule.test.test('test.tsx')) {
      rule.use = [
        ...rule.use,
        {
          loader: 'string-replace-loader',
          options: {
            search: 'devWarning(',
            replace: "if (process.env.NODE_ENV !== 'production') devWarning(",
          },
        },
      ];
    }
  });
}

function externalDayjs(config) {
  config.externals.dayjs = {
    root: 'dayjs',
    commonjs2: 'dayjs',
    commonjs: 'dayjs',
    amd: 'dayjs',
  };
}

function processWebpackThemeConfig(themeConfig, theme, vars) {
  themeConfig.forEach(config => {
    // rename default entry to ${theme} entry
    Object.keys(config.entry).forEach(entryName => {
      const originPath = config.entry[entryName];
      let replacedPath = [...originPath];

      // We will replace `./index` to `./index-style-only` since theme dist only use style file
      if (originPath.length === 1 && originPath[0] === './index') {
        replacedPath = ['./index-style-only'];
      } else {
        // eslint-disable-next-line no-console
        console.log(chalk.red('🆘 Seems entry has changed! It should be `./index`'));
      }

      config.entry[entryName.replace('antd', `antd.${theme}`)] = replacedPath;
      delete config.entry[entryName];
    });

    // apply ${theme} less variables
    injectLessVariables(config, vars);

    // ignore emit ${theme} entry js & js.map file
    config.plugins.push(
      new RemovePlugin({
        after: {
          root: './dist',
          include: [
            `antd.${theme}.js`,
            `antd.${theme}.js.map`,
            `antd.${theme}.min.js`,
            `antd.${theme}.min.js.map`,
          ],
          log: false,
          logWarning: false,
        },
      }),
    );
  });
}

const legacyEntryVars = {
  'root-entry-name': 'default',
};
const webpackConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackDarkConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackCompactConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars);
const webpackVariableConfig = injectLessVariables(getWebpackConfig(false), {
  'root-entry-name': 'variable',
});

webpackConfig.forEach(config => {
  injectWarningCondition(config);
});

if (process.env.RUN_ENV === 'PRODUCTION') {
  webpackConfig.forEach(config => {
    addLocales(config);
    externalDayjs(config);
    // Reduce non-minified dist files size
    config.optimization.usedExports = true;
    // use esbuild
    if (process.env.ESBUILD || process.env.CSB_REPO) {
      config.optimization.minimizer[0] = new ESBuildMinifyPlugin({
        target: 'es2015',
        css: true,
      });
    }

    config.plugins.push(
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false,
        reportFilename: '../report.html',
      }),
    );

    if (!process.env.NO_DUP_CHECK) {
      config.plugins.push(
        new DuplicatePackageCheckerPlugin({
          verbose: true,
          emitError: true,
        }),
      );
    }
  });

  processWebpackThemeConfig(webpackDarkConfig, 'dark', darkVars);
  processWebpackThemeConfig(webpackCompactConfig, 'compact', compactVars);
  processWebpackThemeConfig(webpackVariableConfig, 'variable', {});
}

module.exports = [
  ...webpackConfig,
  ...webpackDarkConfig,
  ...webpackCompactConfig,
  ...webpackVariableConfig,
];
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import styles from './index.module.scss';
import cssModules from 'react-css-modules';
import LoadingImageSrc from './200.gif';

const LoadingIndicator = ({
  isLoading,
}) => (

    {isLoading ?

Loading...

    :

    }

);

LoadingIndicator.propTypes = {
  isLoading: PropTypes.bool,
};

export default cssModules(LoadingIndicator, styles);
<commit_msg>Feat: add new loading indicator<commit_after>import React, { PropTypes } from 'react';
import styles from './index.module.scss';
import cssModules from 'react-css-modules';
import LoadingImageSrc from './200.gif';

const LoadingIndicator = ({
  isLoading,
}) => (

    {isLoading ?

Loading...

    :

    }

);

LoadingIndicator.propTypes = {
  isLoading: PropTypes.bool,
};

export default cssModules(LoadingIndicator, styles);
<|endoftext|>


<commit_before>
(function (plugin, core, scene) {

    var DEFAULTS = {
        specular: new THREE.Color('#505050'),
        emissive: new THREE.Color('#404040'),
        shininess: 15.0,
        lights: true,
        shading: THREE.FlatShading
    };

    var PHONG = {
        uniforms: THREE.UniformsUtils.merge([
            THREE.UniformsLib[ "common" ],
            THREE.UniformsLib[ "bump" ],
            THREE.UniformsLib[ "normalmap" ],
            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "lights" ],
            THREE.UniformsLib[ "shadowmap" ],
            {
                "emissive": {type: "c", value: DEFAULTS.emissive},
                "specular": {type: "c", value: DEFAULTS.specular},
                "shininess": {type: "f", value: DEFAULTS.shininess},
                "lights": {type: "i", value: DEFAULTS.lights},
                "wrapRGB": {type: "v3", value: new THREE.Vector3(1, 1, 1)},
            }

        ]),
        vertexShader: [
            "#define PHONG",
            "varying vec3 vViewPosition;",
            "uniform int shading;",
            "#ifndef FLAT_SHADED",
            "	varying vec3 vNormal;",
            "#endif",
            THREE.ShaderChunk[ "common" ],
            THREE.ShaderChunk[ "map_pars_vertex" ],
            THREE.ShaderChunk[ "lightmap_pars_vertex" ],
            THREE.ShaderChunk[ "envmap_pars_vertex" ],
            THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
            THREE.ShaderChunk[ "color_pars_vertex" ],
            THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
            THREE.ShaderChunk[ "skinning_pars_vertex" ],
            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
            THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
            "void main() {",
            THREE.ShaderChunk[ "map_vertex" ],
            THREE.ShaderChunk[ "lightmap_vertex" ],
            THREE.ShaderChunk[ "color_vertex" ],
            THREE.ShaderChunk[ "morphnormal_vertex" ],
            THREE.ShaderChunk[ "skinbase_vertex" ],
            THREE.ShaderChunk[ "skinnormal_vertex" ],
            THREE.ShaderChunk[ "defaultnormal_vertex" ],
            "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
            "	vNormal = normalize( transformedNormal );",
            "#endif",
            THREE.ShaderChunk[ "morphtarget_vertex" ],
            THREE.ShaderChunk[ "skinning_vertex" ],
            THREE.ShaderChunk[ "default_vertex" ],
            THREE.ShaderChunk[ "logdepthbuf_vertex" ],
            "	vViewPosition = -mvPosition.xyz;",
            THREE.ShaderChunk[ "worldpos_vertex" ],
            THREE.ShaderChunk[ "envmap_vertex" ],
            THREE.ShaderChunk[ "lights_phong_vertex" ],
            THREE.ShaderChunk[ "shadowmap_vertex" ],
            "}"

        ].join("\n"),
        fragmentShader: [
            "#define PHONG",
            "uniform vec3 diffuse;",
            "uniform vec3 emissive;",
            "uniform vec3 specular;",
            "uniform float shininess;",
            "uniform float opacity;",
            "uniform int lights;",
            THREE.ShaderChunk[ "common" ],
            THREE.ShaderChunk[ "color_pars_fragment" ],
            THREE.ShaderChunk[ "map_pars_fragment" ],
            THREE.ShaderChunk[ "alphamap_pars_fragment" ],
            THREE.ShaderChunk[ "lightmap_pars_fragment" ],
            THREE.ShaderChunk[ "envmap_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
            THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
            THREE.ShaderChunk[ "normalmap_pars_fragment" ],
            THREE.ShaderChunk[ "specularmap_pars_fragment" ],
            THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
            "void main() {",
            "	vec3 outgoingLight = vec3( 0.0 );",
            "	vec4 diffuseColor = vec4( diffuse, opacity );",
            THREE.ShaderChunk[ "logdepthbuf_fragment" ],
            THREE.ShaderChunk[ "map_fragment" ],
            THREE.ShaderChunk[ "color_fragment" ],
            THREE.ShaderChunk[ "alphamap_fragment" ],
            THREE.ShaderChunk[ "alphatest_fragment" ],
            THREE.ShaderChunk[ "specularmap_fragment" ],
            THREE.ShaderChunk[ "lights_phong_fragment" ],
            THREE.ShaderChunk[ "lightmap_fragment" ],
            THREE.ShaderChunk[ "envmap_fragment" ],
            THREE.ShaderChunk[ "shadowmap_fragment" ],
            THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
            THREE.ShaderChunk[ "fog_fragment" ],
            " if(lights == 0) ",
            "   gl_FragColor = diffuseColor;",
            " else",
            "	gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
            "}"

        ].join("\n")

    };

    var plug = new plugin.Rendering({
        name: "Filled",
        tooltip: "Tooltip",
        icon: "img/icons/flat.png",
        toggle: true,
        on: true
    }, DEFAULTS);

    var lightingWidget, shadingWidget, shininessWidget,
            specularColor, emissiveColor;
    plug._init = function (guiBuilder) {
        specularColor = guiBuilder.Color({
            label: "Specular",
            tooltip: "Specular color of the material, i.e. how shiny the material is and the color of its shine. Setting this the same color as the diffuse value (times some intensity) makes the material more metallic-looking; setting this to some gray makes the material look more plastic",
            color: "#" + DEFAULTS.specular.getHexString(),
            bindTo: "specular"
        });

        emissiveColor = guiBuilder.Color({
            label: "Emissive",
            tooltip: "Emissive (light) color of the material, essentially a solid color unaffected by other lighting",
            color: "#" + DEFAULTS.emissive.getHexString(),
            bindTo: "emissive"
        });

        shininessWidget = guiBuilder.Integer({
            label: "Shininess",
            tooltip: "How shiny the specular highlight is. A higher value gives a sharper highlight",
            min: 0, max: 100, step: 1,
            defval: DEFAULTS.shininess,
            bindTo: "shininess"
        });

        shadingWidget = guiBuilder.Choice({
            label: "Shading",
            tooltip: "How the triangles of a curved surface are rendered: as a smooth surface, as flat separate facets, or no shading at all",
            options: [
                {content: "Flat", value: THREE.FlatShading, selected: true},
                {content: "Smooth", value: THREE.SmoothShading}
            ],
            bindTo: "shading"
        });

        lightingWidget = guiBuilder.Choice({
            label: "Lighting",
            tooltip: "Enable/disable lighting",
            options: [
                {content: "on", value: true, selected: true},
                {content: "off", value: false}
            ],
            bindTo: "lights"
        });

//        shininessWidget.onChange(function (val) {
////            var meshFile = scene.getSelectedLayer();
////            meshFile.material.setShininess(val);
//        });

//        shadingWidget.onChange(function (shading) {
////            var meshFile = scene.getSelectedLayer();
////
////            //Set material shading parameter
////            meshFile.material.parameters.shading = shading;
////
////            //The mesh file is no rendered
////            if (!meshFile.isRendered()) {
////                return;
////            }
////
////            if (meshFile.material.parameters.lighting !== true) {
////                meshFile.material.parameters.updateGeometry = true;
////                return;
////            }
////
////            var material = new PhongMaterial(meshFile.material.parameters);
////            //Update material and geometry
////            meshFile.updateMaterial(material, true);
//        });

        lightingWidget.onChange(function (on) {
            var meshFile = scene.getSelectedLayer();
            plug._applyTo(meshFile,false);
            plug._applyTo(meshFile,true);
        });
    };

    plug._applyTo = function (meshFile, on) {

        if (on) {
            var geom = meshFile.getThreeMesh().geometry.clone();

            var uniforms = THREE.UniformsUtils.clone(PHONG.uniforms);
            var params = meshFile.overlaysParams.getByKey(plug.getName());

            uniforms.emissive.value = params.emissive;
            uniforms.specular.value = params.specular;
            uniforms.lights.value = params.lights;

            var parameters = {
                fragmentShader: PHONG.fragmentShader,
                vertexShader: PHONG.vertexShader,
                uniforms: uniforms,
                shading: THREE.FlatShading,
                lights: true,
                side: THREE.DoubleSide
            };

            var mat = new THREE.ShaderMaterial(parameters);
            var filled = new THREE.Mesh(geom, mat);

            scene.addOverlayLayer(meshFile, plug.getName(), filled);

        } else {
            scene.removeOverlayLayer(meshFile, plug.getName());
        }

    };

    plugin.Manager.install(plug);

})(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);<commit_msg>Filled code refactored to use the new approach to load and define shader programs<commit_after>
(function (plugin, core, scene) {

    var DEFAULTS = {
        specular: new THREE.Color('#505050'),
        emissive: new THREE.Color('#404040'),
        shininess: 15.0,
        lights: true,
        shading: THREE.FlatShading
    };

    var PHONG = {
        uniforms: THREE.UniformsUtils.merge([
            THREE.UniformsLib[ "common" ],
            THREE.UniformsLib[ "lights" ],
            {
                "shading": {type: "i", value: DEFAULTS.shading},
                "diffuse": {type: "c", value: {}},
                "emissive": {type: "c", value: DEFAULTS.emissive},
                "specular": {type: "c", value: DEFAULTS.specular},
                "shininess": {type: "f", value: DEFAULTS.shininess},
                "lights": {type: "i", value: DEFAULTS.lights},
                "wrapRGB": {type: "v3", value: new THREE.Vector3(1, 1, 1)}
            }

        ])
    };

    var plug = new plugin.Rendering({
        name: "Filled",
        tooltip: "Tooltip",
        icon: "img/icons/flat.png",
        toggle: true,
        on: true,
        loadShader: ["PhongFragment.glsl","PhongVertex.glsl"]
    }, DEFAULTS);

    var lightingWidget, shadingWidget, shininessWidget,
            specularColor, emissiveColor;
    plug._init = function (guiBuilder) {
        specularColor = guiBuilder.Color({
            label: "Specular",
            tooltip: "Specular color of the material, i.e. how shiny the material is and the color of its shine. Setting this the same color as the diffuse value (times some intensity) makes the material more metallic-looking; setting this to some gray makes the material look more plastic",
            color: "#" + DEFAULTS.specular.getHexString(),
            bindTo: "specular"
        });

        emissiveColor = guiBuilder.Color({
            label: "Emissive",
            tooltip: "Emissive (light) color of the material, essentially a solid color unaffected by other lighting",
            color: "#" + DEFAULTS.emissive.getHexString(),
            bindTo: "emissive"
        });

        shininessWidget = guiBuilder.Integer({
            label: "Shininess",
            tooltip: "How shiny the specular highlight is. A higher value gives a sharper highlight",
            min: 0, max: 100, step: 1,
            defval: DEFAULTS.shininess,
            bindTo: "shininess"
        });

        shadingWidget = guiBuilder.Choice({
            label: "Shading",
            tooltip: "How the triangles of a curved surface are rendered: as a smooth surface, as flat separate facets, or no shading at all",
            options: [
                {content: "Flat", value: THREE.FlatShading, selected: true},
                {content: "Smooth", value: THREE.SmoothShading}
            ],
            bindTo: "shading"
        });

        lightingWidget = guiBuilder.Choice({
            label: "Lighting",
            tooltip: "Enable/disable lighting",
            options: [
                {content: "on", value: true, selected: true},
                {content: "off", value: false}
            ],
            bindTo: "lights"
        });

    };

    plug._applyTo = function (meshFile, on) {

        if (on) {
            var geom = meshFile.getThreeMesh().geometry.clone();
            geom.computeFaceNormals();
            geom.computeVertexNormals();

            var uniforms = THREE.UniformsUtils.clone(PHONG.uniforms);
            var params = meshFile.overlaysParams.getByKey(plug.getName());
            var colorParams = meshFile.overlaysParams.getByKey("ColorWheel");

            uniforms.emissive.value = params.emissive;
            uniforms.specular.value = params.specular;
            uniforms.lights.value = params.lights;
            uniforms.shading.value = params.shading;
            uniforms.diffuse.value = colorParams.diffuse;

            var parameters = {
                fragmentShader: this.shaders.getByKey("PhongFragment.glsl"),
                vertexShader: this.shaders.getByKey("PhongVertex.glsl"),
                uniforms: uniforms,
                lights: true,
                side: THREE.DoubleSide
            };

            var mat = new THREE.ShaderMaterial(parameters);
            var filled = new THREE.Mesh(geom, mat);

            scene.addOverlayLayer(meshFile, plug.getName(), filled);

        } else {
            scene.removeOverlayLayer(meshFile, plug.getName());
        }

    };

    plugin.Manager.install(plug);

})(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var stat = require('tchannel/lib/stat');

var DEFAULT_SERVICE_RPS_LIMIT = 100;
var DEFAULT_TOTAL_RPS_LIMIT = 1000;
var DEFAULT_BUCKET_NUMBER = 20;

function RateLimiterCounter(options) {
    if (!(this instanceof RateLimiterCounter)) {
        return new RateLimiterCounter(options);
    }

    var self = this;
    self.index = 0;
    self.rps = 0;
    self.numOfBuckets = options.numOfBuckets;
    self.buckets = [];

    // self.buckets is read/written in refresh,
    // where read is always after write on a bucket.
    self.buckets[0] = 0;
    self.rpsLimit = options.rpsLimit;
}

RateLimiterCounter.prototype.refresh =
function refresh() {
    var self = this;

    // update the sliding window
    var next = (self.index + 1) % self.numOfBuckets;
    if (self.buckets[next]) {
        // offset the bucket being moved out
        self.rps -= self.buckets[next];
    }

    assert(self.rps >= 0, 'rps should always be larger equal to 0');
    self.index = next;
    self.buckets[self.index] = 0;
};

RateLimiterCounter.prototype.increment =
function increment() {
    var self = this;
    self.buckets[self.index] += 1;
    self.rps += 1;
};

function RateLimiter(options) {
    if (!(this instanceof RateLimiter)) {
        return new RateLimiter(options);
    }
    var self = this;

    // stats
    self.channel = options.channel;
    assert(self.channel && !self.channel.topChannel, 'RateLimiter requires top channel');

    self.timers = self.channel.timers;

    self.numOfBuckets = options.numOfBuckets || DEFAULT_BUCKET_NUMBER;
    assert(self.numOfBuckets > 0 && self.numOfBuckets <= 1000, 'counter numOfBuckets should between (0 1000]');
    self.cycle = self.numOfBuckets;

    self.defaultServiceRpsLimit = options.defaultServiceRpsLimit || DEFAULT_SERVICE_RPS_LIMIT;
    self.defaultTotalRpsLimit = DEFAULT_TOTAL_RPS_LIMIT;
    self.totalRpsLimit = options.totalRpsLimit;
    if (typeof self.totalRpsLimit !== 'number') {
        self.totalRpsLimit = self.defaultTotalRpsLimit;
    }
    self.rpsLimitForServiceName = options.rpsLimitForServiceName || Object.create(null);
    self.exemptServices = options.exemptServices || [];
    self.serviceCounters = Object.create(null);
    self.edgeCounters = Object.create(null);
    self.totalRequestCounter = RateLimiterCounter({
        numOfBuckets: self.numOfBuckets,
        rpsLimit: self.totalRpsLimit
    });

    self.refreshDelay = 1000 / self.numOfBuckets;
    self.refresh();

    self.destroyed = false;
}

RateLimiter.prototype.type = 'tchannel.rate-limiting';

RateLimiter.prototype.refresh =
function refresh() {
    var self = this;

    if (self.cycle === self.numOfBuckets) {
        if (self.totalRequestCounter.rps) {
            self.channel.emitFastStat(self.channel.buildStat(
                'tchannel.rate-limiting.total-rps',
                'counter',
                self.totalRequestCounter.rps,
                new stat.RateLimiterEmptyTags()
            ));
        }

        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.total-rps-limit',
            'gauge',
            self.totalRequestCounter.rpsLimit,
            new stat.RateLimiterEmptyTags()
        ));
    }

    self.totalRequestCounter.refresh();

    var serviceNames = Object.keys(self.serviceCounters);
    var i;
    var counter;
    for (i = 0; i < serviceNames.length; i++) {
        counter = self.serviceCounters[serviceNames[i]];
        if (self.cycle === self.numOfBuckets) {
            var statsTag = new stat.RateLimiterServiceTags(serviceNames[i]);
            if (counter.rps) {
                self.channel.emitFastStat(self.channel.buildStat(
                    'tchannel.rate-limiting.service-rps',
                    'counter',
                    counter.rps,
                    statsTag
                ));
            }

            self.channel.emitFastStat(self.channel.buildStat(
                'tchannel.rate-limiting.service-rps-limit',
                'gauge',
                counter.rpsLimit,
                statsTag
            ));
        }
        counter.refresh();
    }

    var edges = Object.keys(self.edgeCounters);
    for (i = 0; i < edges.length; i++) {
        counter = self.edgeCounters[edges[i]];
        if (self.cycle === self.numOfBuckets) {
            if (counter.rps) {
                self.channel.emitFastStat(self.channel.buildStat(
                    'tchannel.rate-limiting.edge-rps',
                    'counter',
                    counter.rps,
                    new stat.RateLimiterEdgeTags(edges[i])
                ));
            }
        }
        counter.refresh();
    }

    self.cycle--;
    if (self.cycle <= 0) {
        self.cycle = self.numOfBuckets;
    }

    self.refreshTimer = self.timers.setTimeout(
        function refresh() {
            self.refresh();
        },
        self.refreshDelay
    );
};

RateLimiter.prototype.removeServiceCounter =
function removeServiceCounter(serviceName) {
    var self = this;
    delete self.serviceCounters[serviceName];
};

RateLimiter.prototype.updateExemptServices =
function updateExemptServices(exemptServices) {
    var self = this;
    self.exemptServices = exemptServices;
};

RateLimiter.prototype.getRpsLimitForService =
function getRpsLimitForService(serviceName) {
    var self = this;
    var limit = self.rpsLimitForServiceName[serviceName];
    if (typeof limit !== 'number') {
        limit = self.defaultServiceRpsLimit;
    }

    return limit;
};

RateLimiter.prototype.updateRpsLimitForAllServices =
function updateRpsLimitForAllServices(rpsLimitForServiceName) {
    var self = this;

    var name;
    var limit;

    // for removed or updated services
    var keys = Object.keys(self.rpsLimitForServiceName);
    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        limit = rpsLimitForServiceName[name];
        if (typeof limit !== 'number') {
            limit = 'default';
            delete self.rpsLimitForServiceName[name];
        }
        self.updateServiceLimit(name, limit);
    }

    // for new services
    keys = Object.keys(rpsLimitForServiceName);
    for (i = 0; i < keys.length; i++) {
        name = keys[i];
        limit = self.rpsLimitForServiceName[name];
        if (typeof limit !== 'number') {
            limit = rpsLimitForServiceName[name];
            self.updateServiceLimit(name, limit);
        }
    }
};

RateLimiter.prototype.updateServiceLimit =
function updateServiceLimit(serviceName, limit) {
    var self = this;

    if (limit === 'default') {
        delete self.rpsLimitForServiceName[serviceName];
        limit = self.defaultServiceRpsLimit;
    } else {
        self.rpsLimitForServiceName[serviceName] = limit;
    }

    // update counter
    var counter = self.serviceCounters[serviceName];
    if (counter) {
        counter.rpsLimit = limit;
    }
};

RateLimiter.prototype.updateTotalLimit =
function updateTotalLimit(limit) {
    var self = this;
    self.totalRpsLimit = limit;
    self.totalRequestCounter.rpsLimit = limit;
};

RateLimiter.prototype.createServiceCounter =
function createServiceCounter(serviceName) {
    var self = this;
    var counter;

    assert(serviceName, 'createServiceCounter requires the serviceName');

    if (self.exemptServices.indexOf(serviceName) !== -1) {
        return null;
    }

    // if this is an existing service counter
    counter = self.serviceCounters[serviceName];
    // creating a new service counter
    if (!counter) {
        var limit = self.rpsLimitForServiceName[serviceName];
        if (typeof limit !== 'number') {
            limit = self.defaultServiceRpsLimit;
        }
        counter = RateLimiterCounter({
            numOfBuckets: self.numOfBuckets,
            rpsLimit: limit
        });
        self.serviceCounters[serviceName] = counter;
    }

    return counter;
};

RateLimiter.prototype.incrementServiceCounter =
function incrementServiceCounter(serviceName) {
    var self = this;
    var counter = self.createServiceCounter(serviceName);

    if (counter) {
        // increment the service counter
        counter.increment();
    }
};

RateLimiter.prototype.incrementEdgeCounter =
function incrementEdgeCounter(name) {
    var self = this;
    var counter = self.edgeCounters[name];
    if (!counter) {
        counter = RateLimiterCounter({
            numOfBuckets: self.numOfBuckets,
            rpsLimit: 0
        });
        self.edgeCounters[name] = counter;
    }

    counter.increment();
};

RateLimiter.prototype.incrementTotalCounter =
function incrementTotalCounter(serviceName) {
    var self = this;
    if (!serviceName || self.exemptServices.indexOf(serviceName) === -1) {
        self.totalRequestCounter.increment();
    }
};

RateLimiter.prototype.shouldRateLimitService =
function shouldRateLimitService(serviceName) {
    var self = this;
    if (self.exemptServices.indexOf(serviceName) !== -1) {
        return false;
    }
    var counter = self.serviceCounters[serviceName];
    assert(counter, 'cannot find counter for ' + serviceName);
    var result = counter.rps > counter.rpsLimit;
    if (result) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.service-busy',
            'counter',
            1,
            new stat.RateLimiterServiceTags(serviceName)
        ));
    }
    return result;
};

RateLimiter.prototype.shouldRateLimitTotalRequest =
function shouldRateLimitTotalRequest(serviceName) {
    var self = this;
    var result;
    if (!serviceName || self.exemptServices.indexOf(serviceName) === -1) {
        result = self.totalRequestCounter.rps > self.totalRequestCounter.rpsLimit;
    } else {
        result = false;
    }

    if (result) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.total-busy',
            'counter',
            1,
            new stat.RateLimiterServiceTags(serviceName)
        ));
    }

    return result;
};

RateLimiter.prototype.destroy =
function destroy() {
    var self = this;
    self.destroyed = true;
    self.timers.clearTimeout(self.refreshTimer);
};

module.exports = RateLimiter;
<commit_msg>fix lint<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* eslint max-statements: [2, 40] */
var assert = require('assert');
var stat = require('tchannel/lib/stat');

var DEFAULT_SERVICE_RPS_LIMIT = 100;
var DEFAULT_TOTAL_RPS_LIMIT = 1000;
var DEFAULT_BUCKET_NUMBER = 20;

function RateLimiterCounter(options) {
    if (!(this instanceof RateLimiterCounter)) {
        return new RateLimiterCounter(options);
    }

    var self = this;
    self.index = 0;
    self.rps = 0;
    self.numOfBuckets = options.numOfBuckets;
    self.buckets = [];

    // self.buckets is read/written in refresh,
    // where read is always after write on a bucket.
    self.buckets[0] = 0;
    self.rpsLimit = options.rpsLimit;
}

RateLimiterCounter.prototype.refresh =
function refresh() {
    var self = this;

    // update the sliding window
    var next = (self.index + 1) % self.numOfBuckets;
    if (self.buckets[next]) {
        // offset the bucket being moved out
        self.rps -= self.buckets[next];
    }

    assert(self.rps >= 0, 'rps should always be larger equal to 0');
    self.index = next;
    self.buckets[self.index] = 0;
};

RateLimiterCounter.prototype.increment =
function increment() {
    var self = this;
    self.buckets[self.index] += 1;
    self.rps += 1;
};

function RateLimiter(options) {
    if (!(this instanceof RateLimiter)) {
        return new RateLimiter(options);
    }
    var self = this;

    // stats
    self.channel = options.channel;
    assert(self.channel && !self.channel.topChannel, 'RateLimiter requires top channel');

    self.timers = self.channel.timers;

    self.numOfBuckets = options.numOfBuckets || DEFAULT_BUCKET_NUMBER;
    assert(self.numOfBuckets > 0 && self.numOfBuckets <= 1000, 'counter numOfBuckets should between (0 1000]');
    self.cycle = self.numOfBuckets;

    self.defaultServiceRpsLimit = options.defaultServiceRpsLimit || DEFAULT_SERVICE_RPS_LIMIT;
    self.defaultTotalRpsLimit = DEFAULT_TOTAL_RPS_LIMIT;
    self.totalRpsLimit = options.totalRpsLimit;
    if (typeof self.totalRpsLimit !== 'number') {
        self.totalRpsLimit = self.defaultTotalRpsLimit;
    }
    self.rpsLimitForServiceName = options.rpsLimitForServiceName || Object.create(null);
    self.exemptServices = options.exemptServices || [];
    self.serviceCounters = Object.create(null);
    self.edgeCounters = Object.create(null);
    self.totalRequestCounter = RateLimiterCounter({
        numOfBuckets: self.numOfBuckets,
        rpsLimit: self.totalRpsLimit
    });

    self.refreshDelay = 1000 / self.numOfBuckets;
    self.refresh();

    self.destroyed = false;
}

RateLimiter.prototype.type = 'tchannel.rate-limiting';

RateLimiter.prototype.refresh =
function refresh() {
    var self = this;

    if (self.cycle === self.numOfBuckets) {
        if (self.totalRequestCounter.rps) {
            self.channel.emitFastStat(self.channel.buildStat(
                'tchannel.rate-limiting.total-rps',
                'counter',
                self.totalRequestCounter.rps,
                new stat.RateLimiterEmptyTags()
            ));
        }

        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.total-rps-limit',
            'gauge',
            self.totalRequestCounter.rpsLimit,
            new stat.RateLimiterEmptyTags()
        ));
    }

    self.totalRequestCounter.refresh();

    var serviceNames = Object.keys(self.serviceCounters);
    var i;
    var counter;
    for (i = 0; i < serviceNames.length; i++) {
        counter = self.serviceCounters[serviceNames[i]];
        if (self.cycle === self.numOfBuckets) {
            var statsTag = new stat.RateLimiterServiceTags(serviceNames[i]);
            if (counter.rps) {
                self.channel.emitFastStat(self.channel.buildStat(
                    'tchannel.rate-limiting.service-rps',
                    'counter',
                    counter.rps,
                    statsTag
                ));
            }

            self.channel.emitFastStat(self.channel.buildStat(
                'tchannel.rate-limiting.service-rps-limit',
                'gauge',
                counter.rpsLimit,
                statsTag
            ));
        }
        counter.refresh();
    }

    var edges = Object.keys(self.edgeCounters);
    for (i = 0; i < edges.length; i++) {
        counter = self.edgeCounters[edges[i]];
        if (self.cycle === self.numOfBuckets) {
            if (counter.rps) {
                self.channel.emitFastStat(self.channel.buildStat(
                    'tchannel.rate-limiting.edge-rps',
                    'counter',
                    counter.rps,
                    new stat.RateLimiterEdgeTags(edges[i])
                ));
            }
        }
        counter.refresh();
    }

    self.cycle--;
    if (self.cycle <= 0) {
        self.cycle = self.numOfBuckets;
    }

    self.refreshTimer = self.timers.setTimeout(
        function refresh() {
            self.refresh();
        },
        self.refreshDelay
    );
};

RateLimiter.prototype.removeServiceCounter =
function removeServiceCounter(serviceName) {
    var self = this;
    delete self.serviceCounters[serviceName];
};

RateLimiter.prototype.updateExemptServices =
function updateExemptServices(exemptServices) {
    var self = this;
    self.exemptServices = exemptServices;
};

RateLimiter.prototype.getRpsLimitForService =
function getRpsLimitForService(serviceName) {
    var self = this;
    var limit = self.rpsLimitForServiceName[serviceName];
    if (typeof limit !== 'number') {
        limit = self.defaultServiceRpsLimit;
    }

    return limit;
};

RateLimiter.prototype.updateRpsLimitForAllServices =
function updateRpsLimitForAllServices(rpsLimitForServiceName) {
    var self = this;

    var name;
    var limit;

    // for removed or updated services
    var keys = Object.keys(self.rpsLimitForServiceName);
    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        limit = rpsLimitForServiceName[name];
        if (typeof limit !== 'number') {
            limit = 'default';
            delete self.rpsLimitForServiceName[name];
        }
        self.updateServiceLimit(name, limit);
    }

    // for new services
    keys = Object.keys(rpsLimitForServiceName);
    for (i = 0; i < keys.length; i++) {
        name = keys[i];
        limit = self.rpsLimitForServiceName[name];
        if (typeof limit !== 'number') {
            limit = rpsLimitForServiceName[name];
            self.updateServiceLimit(name, limit);
        }
    }
};

RateLimiter.prototype.updateServiceLimit =
function updateServiceLimit(serviceName, limit) {
    var self = this;

    if (limit === 'default') {
        delete self.rpsLimitForServiceName[serviceName];
        limit = self.defaultServiceRpsLimit;
    } else {
        self.rpsLimitForServiceName[serviceName] = limit;
    }

    // update counter
    var counter = self.serviceCounters[serviceName];
    if (counter) {
        counter.rpsLimit = limit;
    }
};

RateLimiter.prototype.updateTotalLimit =
function updateTotalLimit(limit) {
    var self = this;
    self.totalRpsLimit = limit;
    self.totalRequestCounter.rpsLimit = limit;
};

RateLimiter.prototype.createServiceCounter =
function createServiceCounter(serviceName) {
    var self = this;
    var counter;

    assert(serviceName, 'createServiceCounter requires the serviceName');

    if (self.exemptServices.indexOf(serviceName) !== -1) {
        return null;
    }

    // if this is an existing service counter
    counter = self.serviceCounters[serviceName];
    // creating a new service counter
    if (!counter) {
        var limit = self.rpsLimitForServiceName[serviceName];
        if (typeof limit !== 'number') {
            limit = self.defaultServiceRpsLimit;
        }
        counter = RateLimiterCounter({
            numOfBuckets: self.numOfBuckets,
            rpsLimit: limit
        });
        self.serviceCounters[serviceName] = counter;
    }

    return counter;
};

RateLimiter.prototype.incrementServiceCounter =
function incrementServiceCounter(serviceName) {
    var self = this;
    var counter = self.createServiceCounter(serviceName);

    if (counter) {
        // increment the service counter
        counter.increment();
    }
};

RateLimiter.prototype.incrementEdgeCounter =
function incrementEdgeCounter(name) {
    var self = this;
    var counter = self.edgeCounters[name];
    if (!counter) {
        counter = RateLimiterCounter({
            numOfBuckets: self.numOfBuckets,
            rpsLimit: 0
        });
        self.edgeCounters[name] = counter;
    }

    counter.increment();
};

RateLimiter.prototype.incrementTotalCounter =
function incrementTotalCounter(serviceName) {
    var self = this;
    if (!serviceName || self.exemptServices.indexOf(serviceName) === -1) {
        self.totalRequestCounter.increment();
    }
};

RateLimiter.prototype.shouldRateLimitService =
function shouldRateLimitService(serviceName) {
    var self = this;
    if (self.exemptServices.indexOf(serviceName) !== -1) {
        return false;
    }
    var counter = self.serviceCounters[serviceName];
    assert(counter, 'cannot find counter for ' + serviceName);
    var result = counter.rps > counter.rpsLimit;
    if (result) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.service-busy',
            'counter',
            1,
            new stat.RateLimiterServiceTags(serviceName)
        ));
    }
    return result;
};

RateLimiter.prototype.shouldRateLimitTotalRequest =
function shouldRateLimitTotalRequest(serviceName) {
    var self = this;
    var result;
    if (!serviceName || self.exemptServices.indexOf(serviceName) === -1) {
        result = self.totalRequestCounter.rps > self.totalRequestCounter.rpsLimit;
    } else {
        result = false;
    }

    if (result) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.rate-limiting.total-busy',
            'counter',
            1,
            new stat.RateLimiterServiceTags(serviceName)
        ));
    }

    return result;
};

RateLimiter.prototype.destroy =
function destroy() {
    var self = this;
    self.destroyed = true;
    self.timers.clearTimeout(self.refreshTimer);
};

module.exports = RateLimiter;
<|endoftext|>


<commit_before><commit_msg>removed tangram from webpack flow<commit_after><|endoftext|>


<commit_before>var x11 = require('../lib');
var should = require('should');

var TEST_PROPERTY = 'My Test Property';

describe('ChangeProperty', function() {
    before(function(done) {
        var self = this;
        var client = x11.createClient(function(err, dpy) {
            should.not.exist(err);
            self.X = dpy.client;
            self.wid = self.X.AllocID();
            self.wid_helper = self.X.AllocID();
            self.X.CreateWindow(self.wid, dpy.screen[0].root, 0, 0, 1, 1); // 1x1 pixel window
            self.X.QueryTree(dpy.screen[0].root, function(err, list) {
                should.not.exist(err);
                list.children.indexOf(self.wid).should.not.equal(-1);
                done();
            });
        });

        client.on('error', done);
    });

    it('should add a new WINDOW property with length 1', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(4);
            raw.writeUInt32LE(self.wid, 0);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.WINDOW, 32, raw);
            self.X.GetProperty(0, self.wid, atom, self.X.atoms.WINDOW, 0, 1000000000, function(err, prop) {
                should.not.exist(err);
                prop.data.readUInt32LE(0).should.equal(self.wid);
                done();
            });
        });
    });

    it('should add a new WINDOW property with length 2', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(new Array(8));
            raw.writeUInt32LE(self.wid, 0);
            raw.writeUInt32LE(self.wid_helper, 4);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.ATOM, 32, raw);
            self.X.GetProperty(0, self.wid, atom, self.X.atoms.ATOM, 0, 1000000000, function(err, prop) {
                should.not.exist(err);
                prop.data.readUInt32LE(0).should.equal(self.wid);
                prop.data.readUInt32LE(4).should.equal(self.wid_helper);
                done();
            });
        });
    });

    it('should replace a the WINDOW property with length 0', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(0);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.WINDOW, 32, raw);
            self.X.GetProperty(0, self.wid, atom, self.X.atoms.WINDOW, 0, 1000000000, function(err, prop) {
                should.not.exist(err);
                prop.data.length.should.equal(0);
                done();
            });
        });
    });

    after(function(done) {
        this.X.DestroyWindow(this.wid);
        this.X.terminate();
        this.X.on('end', done);
    });
});

<commit_msg>Improve change-property test<commit_after>var x11 = require('../lib');
var should = require('should');

var TEST_PROPERTY = 'My Test Property';

describe('ChangeProperty', function() {
    before(function(done) {
        var self = this;
        var client = x11.createClient(function(err, dpy) {
            should.not.exist(err);
            self.X = dpy.client;
            self.wid = self.X.AllocID();
            self.wid_helper = self.X.AllocID();
            self.X.CreateWindow(self.wid, dpy.screen[0].root, 0, 0, 1, 1); // 1x1 pixel window
            self.X.QueryTree(dpy.screen[0].root, function(err, list) {
                should.not.exist(err);
                list.children.indexOf(self.wid).should.not.equal(-1);
                self.X.ChangeWindowAttributes(self.wid, { eventMask: x11.eventMask.PropertyChange });
                done();
            });
        });

        client.on('error', done);
    });

    it('should add a new WINDOW property with length 1', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(4);
            raw.writeUInt32LE(self.wid, 0);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.WINDOW, 32, raw);
            self.X.once('event', function(ev) {
                ev.type.should.equal(28);
                ev.atom.should.equal(atom);
                ev.window.should.equal(self.wid);
                self.X.GetProperty(0, self.wid, atom, self.X.atoms.WINDOW, 0, 1000000000, function(err, prop) {
                    should.not.exist(err);
                    prop.data.readUInt32LE(0).should.equal(self.wid);
                    done();
                });
            });
        });
    });

    it('should add a new WINDOW property with length 2', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(new Array(8));
            raw.writeUInt32LE(self.wid, 0);
            raw.writeUInt32LE(self.wid_helper, 4);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.ATOM, 32, raw);
            self.X.once('event', function(ev) {
                ev.type.should.equal(28);
                ev.atom.should.equal(atom);
                ev.window.should.equal(self.wid);
                self.X.GetProperty(0, self.wid, atom, self.X.atoms.ATOM, 0, 1000000000, function(err, prop) {
                    should.not.exist(err);
                    prop.data.readUInt32LE(0).should.equal(self.wid);
                    prop.data.readUInt32LE(4).should.equal(self.wid_helper);
                    done();
                });
            });
        });
    });

    it('should replace a the WINDOW property with length 0', function(done) {
        var self = this;
        this.X.InternAtom(false, TEST_PROPERTY, function(err, atom) {
            should.not.exist(err);
            var raw = new Buffer(0);
            self.X.ChangeProperty(0, self.wid, atom, self.X.atoms.WINDOW, 32, raw);
            self.X.once('event', function(ev) {
                ev.type.should.equal(28);
                ev.atom.should.equal(atom);
                ev.window.should.equal(self.wid);
                self.X.GetProperty(0, self.wid, atom, self.X.atoms.WINDOW, 0, 1000000000, function(err, prop) {
                    should.not.exist(err);
                    prop.data.length.should.equal(0);
                    done();
                });
            });
        });
    });

    after(function(done) {
        this.X.DestroyWindow(this.wid);
        this.X.terminate();
        this.X.on('end', done);
    });
});

<|endoftext|>


<commit_before>var minify = (function(undefined) {

	var exec = require('child_process').exec,
			_fs = require('fs');

	var minify = function(options) {
		this.type = options.type;
		this.tempFile = new Date().getTime().toString();

		if(options.type == 'gcc' && typeof options.fileIn === 'string') {
			this.fileIn = [options.fileIn];
		}
		else if(typeof options.fileIn === 'string') {
			this.fileIn = options.fileIn;
		}

		if(typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type != 'gcc') {
			var out = options.fileIn.map(function(path) {
				return _fs.readFileSync(path, 'utf8');
			});

			_fs.writeFileSync(this.tempFile, out.join('\n'), 'utf8');

			this.fileIn = this.tempFile;
		}
		else if(typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type == 'gcc') {
			this.fileIn = options.fileIn;
		}

		this.fileOut = options.fileOut;
		this.options = options.options || [];
		this.buffer = options.buffer || 1000 * 1024;
		if (typeof options.callback !== 'undefined') {
			this.callback = options.callback;
		}

		this.compress();
	};

	minify.prototype = minify.fn = {
		type: null,
		fileIn: null,
		fileOut: null,
		callback: null,
		buffer: null, // with larger files you will need a bigger buffer for closure compiler
		compress: function() {
			var self = this, command;

			switch (this.type) {
				case 'yui-css':
					command = 'java -jar -Xss2048k "' + __dirname + '/yuicompressor-2.4.7.jar" "' + this.fileIn + '" -o "' + this.fileOut + '" --type css ' + this.options.join(' ');
					break;
				case 'yui':
				case 'yui-js':
					command = 'java -jar -Xss2048k "' + __dirname + '/yuicompressor-2.4.7.jar" "' + this.fileIn + '" -o "' + this.fileOut + '" --type js ' + this.options.join(' ');
					break;
				case 'gcc':
					var fileInCommand = this.fileIn.map(function(file) {
						return '--js="' + file + '"';
					});
					command = 'java -jar "' + __dirname + '/google_closure_compiler-r1810.jar" ' + fileInCommand.join(' ') + ' --js_output_file="' + this.fileOut + '" ' + this.options.join(' ');
					break;
				case 'uglifyjs':
					command = '"' + __dirname  + '/../node_modules/uglify-js/bin/uglifyjs" --output "' + this.fileOut + '" --no-copyright "' + this.fileIn + '" ' + this.options.join(' ');
					break;
			}

			exec(command, { maxBuffer: this.buffer }, function (err, stdout, stderr) {
				//console.log(err);
				//console.log(stdout);
				//console.log(stderr);

				if(self.fileIn === self.tempFile) {
					// remove the temp concat file here
					_fs.unlinkSync(self.tempFile);
				}

				if(self.callback){
					if (err) {
						self.callback(err);
					} else {
						self.callback(null);
					}
				}
			});
		}
	};

	return minify;

})();

exports.version = '0.3.9';
exports.minify = minify;<commit_msg>Revert default<commit_after>var minify = (function(undefined) {

	var exec = require('child_process').exec,
			_fs = require('fs');

	var minify = function(options) {
		this.type = options.type;
		this.tempFile = new Date().getTime().toString();

		if(options.type == 'gcc' && typeof options.fileIn === 'string') {
			this.fileIn = [options.fileIn];
		}
		else if(typeof options.fileIn === 'string') {
			this.fileIn = options.fileIn;
		}

		if(typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type != 'gcc') {
			var out = options.fileIn.map(function(path) {
				return _fs.readFileSync(path, 'utf8');
			});

			_fs.writeFileSync(this.tempFile, out.join('\n'), 'utf8');

			this.fileIn = this.tempFile;
		}
		else if(typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type == 'gcc') {
			this.fileIn = options.fileIn;
		}

		this.fileOut = options.fileOut;
		this.options = options.options || [];
		this.buffer = options.buffer || 1000 * 1024;
		if (typeof options.callback !== 'undefined') {
			this.callback = options.callback;
		}

		this.compress();
	};

	minify.prototype = minify.fn = {
		type: null,
		fileIn: null,
		fileOut: null,
		callback: null,
		buffer: null, // with larger files you will need a bigger buffer for closure compiler
		compress: function() {
			var self = this, command;

			switch (this.type) {
				case 'yui':
				case 'yui-css':
					command = 'java -jar -Xss2048k "' + __dirname + '/yuicompressor-2.4.7.jar" "' + this.fileIn + '" -o "' + this.fileOut + '" --type css ' + this.options.join(' ');
					break;
				case 'yui-js':
					command = 'java -jar -Xss2048k "' + __dirname + '/yuicompressor-2.4.7.jar" "' + this.fileIn + '" -o "' + this.fileOut + '" --type js ' + this.options.join(' ');
					break;
				case 'gcc':
					var fileInCommand = this.fileIn.map(function(file) {
						return '--js="' + file + '"';
					});
					command = 'java -jar "' + __dirname + '/google_closure_compiler-r1810.jar" ' + fileInCommand.join(' ') + ' --js_output_file="' + this.fileOut + '" ' + this.options.join(' ');
					break;
				case 'uglifyjs':
					command = '"' + __dirname  + '/../node_modules/uglify-js/bin/uglifyjs" --output "' + this.fileOut + '" --no-copyright "' + this.fileIn + '" ' + this.options.join(' ');
					break;
			}

			exec(command, { maxBuffer: this.buffer }, function (err, stdout, stderr) {
				//console.log(err);
				//console.log(stdout);
				//console.log(stderr);

				if(self.fileIn === self.tempFile) {
					// remove the temp concat file here
					_fs.unlinkSync(self.tempFile);
				}

				if(self.callback){
					if (err) {
						self.callback(err);
					} else {
						self.callback(null);
					}
				}
			});
		}
	};

	return minify;

})();

exports.version = '0.3.9';
exports.minify = minify;<|endoftext|>


<commit_before>/* Global vars */
var gV = {
  radius: 512/ 2,

  room_number: 50,
  max_room_w: 16,
  min_room_w: 2,
  max_room_h: 16,
  min_room_h: 2,

  grid: 10, // Pixels

  x: 0,
  y: 0,

  average_area: 0,

  // Areas over the average by this factor
  // Define the main rooms of the dungeos
  average_area_limit: 2.8,

  overlapping: true
},
rooms = [],
cz1;

$(document).ready(function() {

  cz1 = new Canvaz('#cnvz');
  cz1.fullScreen();

  // Clear canvas
  cz1.clear = function() {
    this.fS = '#242424';
    this.ctx.beginPath();
    this.ctx.rect(- cz1.w / 2, - cz1.h / 2, cz1.w, cz1.h);
    this.ctx.fill();
  };

  // ----------------------------------
  // ----------------------------------
  // ----------------------------------
  cz1.beforeStart = function() {

    cz1.fS = '#f00';
    cz1.ctx.translate(cz1.w / 2, cz1.h / 2);

    // Create rooms
    for (var i = 0; i < gV.room_number; i++) {
      var
        // p1 = getRandomPointInEllipse (0, 0, gV.radius / 2, gV.radius / 2);
        p1 = pDG.fn.getRandomPointInEllipse(0, 0, 64, 64, gV.grid),
        room = {
          'x': p1[0],
          'y': p1[1],
          'w': gV.min_room_w + Math.round(Math.random() * (gV.max_room_w - gV.min_room_w)),
          'h': gV.min_room_h + Math.round(Math.random() * (gV.max_room_h - gV.min_room_h)),
          'id': Math.random().toString(36).substr(2, 8),
          'idx': i
        };

      room.x -= ( room.w );
      room.y -= ( room.h );

      room.cx = room.x + ( room.w / 2 * gV.grid );
      room.cy = room.y + ( room.h / 2 * gV.grid );

      room.area = room.w * room.h;
      gV.average_area += room.area;
      rooms.push( room );
    }

    // Not iot realli the average
    gV.average_area = gV.average_area / gV.room_number;
    console.log( rooms );
  };

  // ----------------------------------
  // ----------------------------------
  // ----------------------------------
  cz1.beforeDraw = function() {
    // cz1.clear();
  };

  cz1.draw = function() {

    cz1.clear();

    pDG.fn.draw.grid( cz1, gV.grid );

    spaceRooms( rooms );

    // Draw all rooms
    var color = 'rgba(45, 93, 180, 0.75)';
    for (var i = 0, len = rooms.length; i < len; i++) {
      var
        room = rooms[i];
      if  ( room.area > gV.average_area * gV.average_area_limit ) {
        color = 'rgba(180, 93, 45, 0.75)'; // Redish
      }
      pDG.fn.draw.room( cz1, room, gV.grid, color );
    }

    pDG.fn.draw.axis( cz1 );

  };

  cz1.start();

});

function spaceRooms ( rooms ) {

  for (var i = 0, len = rooms.length; i < len; i++) {
    var
      r1 = rooms[i];
    r1.x = Math.round(r1.x);
    r1.y = Math.round(r1.y);
    for (var j = 0; j < len; j++) {
      if (i !== j) {
        var
          r2 = rooms[j];

        // If rooms overlap
        if ( pDG.fn.roomsOverlap(r1, r2, gV.grid) ) {

          var
            d = pDG.fn.dist(r1.cx, r1.cy, r2.cx, r2.cy),
            dx = r2.cx - r1.cx,
            dy = r2.cy - r1.cy,
            normal = {},
            midpoint = {};

          if ( d === 0 ) {
            normal.x = 0;
            normal.y = 0;
          } else {
            normal.x = dx / d;
            normal.y = dy / d;
          }
          midpoint.x = (r1.x + r2.x) / 2;
          midpoint.y = (r1.y + r2.y) / 2;

          r2.cx += ( normal.x * gV.grid * 1.0 );
          r2.cy += ( normal.y * gV.grid * 1.0 );
          r1.cx -= ( normal.x * gV.grid * 1.0 );
          r1.cy -= ( normal.y * gV.grid * 1.0 );

          r2.x = pDG.fn.snapToGrid( r2.cx - r2.w / 2 * gV.grid, gV.grid );
          r2.y = pDG.fn.snapToGrid( r2.cy - r2.h / 2 * gV.grid, gV.grid );
          r1.x = pDG.fn.snapToGrid( r1.cx - r1.w / 2 * gV.grid, gV.grid );
          r1.y = pDG.fn.snapToGrid( r1.cy - r1.h / 2 * gV.grid, gV.grid );

          r2.cx = r2.x + ( r2.w * gV.grid / 2 );
          r2.cy = r2.y + ( r2.h * gV.grid / 2 );
          r1.cx = r1.x + ( r1.w * gV.grid / 2 );
          r1.cy = r1.y + ( r1.h * gV.grid / 2 );

        }
      }
    }
  }
}

<commit_msg>Something is wrong with the average area :-/<commit_after>/* Global vars */
var gV = {
  radius: 512/ 2,

  room_number: 50,
  max_room_w: 16,
  min_room_w: 2,
  max_room_h: 16,
  min_room_h: 2,

  grid: 10, // Pixels

  x: 0,
  y: 0,

  average_area: 0,

  // Areas over the average by this factor
  // Define the main rooms of the dungeos
  average_area_limit: 2.8,

  overlapping: true
},
rooms = [],
cz1;

$(document).ready(function() {

  cz1 = new Canvaz('#cnvz');
  cz1.fullScreen();

  // Clear canvas
  cz1.clear = function() {
    this.fS = '#242424';
    this.ctx.beginPath();
    this.ctx.rect(- cz1.w / 2, - cz1.h / 2, cz1.w, cz1.h);
    this.ctx.fill();
  };

  // ----------------------------------
  // ----------------------------------
  // ----------------------------------
  cz1.beforeStart = function() {

    cz1.fS = '#f00';
    cz1.ctx.translate(cz1.w / 2, cz1.h / 2);

    // Create rooms
    for (var i = 0; i < gV.room_number; i++) {
      var
        // p1 = getRandomPointInEllipse (0, 0, gV.radius / 2, gV.radius / 2);
        p1 = pDG.fn.getRandomPointInEllipse(0, 0, 64, 64, gV.grid),
        room = {
          'x': p1[0],
          'y': p1[1],
          'w': gV.min_room_w + Math.round(Math.random() * (gV.max_room_w - gV.min_room_w)),
          'h': gV.min_room_h + Math.round(Math.random() * (gV.max_room_h - gV.min_room_h)),
          'id': Math.random().toString(36).substr(2, 8),
          'idx': i
        };

      room.x -= ( room.w );
      room.y -= ( room.h );

      room.cx = room.x + ( room.w / 2 * gV.grid );
      room.cy = room.y + ( room.h / 2 * gV.grid );

      room.area = room.w * room.h;
      gV.average_area += room.area;
      rooms.push( room );
    }

    // Not iot realli the average
    gV.average_area = gV.average_area / gV.room_number;
    console.log( rooms );
  };

  // ----------------------------------
  // ----------------------------------
  // ----------------------------------
  cz1.beforeDraw = function() {
    // cz1.clear();
  };

  cz1.draw = function() {

    cz1.clear();

    pDG.fn.draw.grid( cz1, gV.grid );

    spaceRooms( rooms );

    // Draw all rooms
    var color = 'rgba(45, 93, 180, 0.75)';
    for (var i = 0, len = rooms.length; i < len; i++) {
      var
        room = rooms[i];
      if  ( room.area > gV.average_area * gV.average_area_limit ) {
        color = 'rgba(180, 93, 45, 0.75)'; // Redish
      }
      pDG.fn.draw.room( cz1, room, gV.grid, color );
    }

    pDG.fn.draw.axis( cz1 );

  };

  cz1.start();

});

function spaceRooms ( rooms ) {

  for (var i = 0, len = rooms.length; i < len; i++) {
    var
      r1 = rooms[i];
    for (var j = 0; j < len; j++) {
      if (i !== j) { // Not checking againt itself
        var
          r2 = rooms[j];

        // If rooms overlap
        if ( pDG.fn.roomsOverlap(r1, r2, gV.grid) ) {

          var
            d = pDG.fn.dist(r1.cx, r1.cy, r2.cx, r2.cy),
            dx = r2.cx - r1.cx,
            dy = r2.cy - r1.cy,
            normal = {},
            midpoint = {};

          if ( d === 0 ) {
            normal.x = 0;
            normal.y = 0;
          } else {
            normal.x = dx / d;
            normal.y = dy / d;
          }
          midpoint.x = (r1.x + r2.x) / 2;
          midpoint.y = (r1.y + r2.y) / 2;

          r2.cx += ( normal.x * gV.grid * 1.0 );
          r2.cy += ( normal.y * gV.grid * 1.0 );
          r1.cx -= ( normal.x * gV.grid * 1.0 );
          r1.cy -= ( normal.y * gV.grid * 1.0 );

          r2.x = pDG.fn.snapToGrid( r2.cx - r2.w / 2 * gV.grid, gV.grid );
          r2.y = pDG.fn.snapToGrid( r2.cy - r2.h / 2 * gV.grid, gV.grid );
          r1.x = pDG.fn.snapToGrid( r1.cx - r1.w / 2 * gV.grid, gV.grid );
          r1.y = pDG.fn.snapToGrid( r1.cy - r1.h / 2 * gV.grid, gV.grid );

          r2.cx = r2.x + ( r2.w * gV.grid / 2 );
          r2.cy = r2.y + ( r2.h * gV.grid / 2 );
          r1.cx = r1.x + ( r1.w * gV.grid / 2 );
          r1.cy = r1.y + ( r1.h * gV.grid / 2 );

        }
      }
    }
  }
}

<|endoftext|>


<commit_before>Meteor.publish('allHomes', function () {
  // All homes publication
  return Homes.find();
});

Meteor.publish('homesBelongingToGroup', function (groupId) {
  // All homes publication
  return Homes.find({groupId: groupId});
});
<commit_msg>Add singleHome publication; comments<commit_after>Meteor.publish('allHomes', function () {
  // All homes publication
  return Homes.find();
});

Meteor.publish('singleHome', function (homeId) {
  // Publish a single home
  return Homes.find(homeId);
});

Meteor.publish('homesBelongingToGroup', function (groupId) {
  // Publish homes belonging to group
  return Homes.find({groupId: groupId});
});
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const env = process.env.NODE_ENV;
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const PATHS = {
    "static": path.resolve(__dirname, 'src/encoded/static'),
    "build" : path.resolve(__dirname, 'src/encoded/static/build'),
};

const mode = (env === 'production' ? 'production' : 'development');

const plugins = [];

// don't include momentjs locales (large)
plugins.push(
    new webpack.IgnorePlugin({
        resourceRegExp: /^\.\/locale$/,
        contextRegExp: /moment$/
    })
);

let chunkFilename = '[name].js';
let devTool = 'source-map'; // Default, slowest.

if (mode === 'production') {
    // add chunkhash to chunk names for production only (it's slower)
    chunkFilename = '[name].[chunkhash].js';
    devTool = 'source-map';
} else if (env === 'quick') {
    devTool = 'eval'; // Fastest
} else if (env === 'development') {
    devTool = 'inline-source-map';
}

var rules = [
    // Strip @jsx pragma in react-forms, which makes babel abort
    {
        test: /\.js$/,
        loader: 'string-replace-loader',
        enforce: 'pre',
        query: {
            search: '@jsx',
            replace: 'jsx',
        }
    },
    // add babel to load .js files as ES6 and transpile JSX
    {
        test: /\.(js|jsx)$/,
        include: [
            path.resolve(__dirname, 'src/encoded/static'),
        ],
        use: [
            {
                loader: 'babel-loader'
            }
        ]
    }
];

var resolve = {
    extensions : [".webpack.js", ".web.js", ".js", ".json", '.jsx']
};

var optimization = {
    minimize: mode === "production",
    minimizer: [
        //new UglifyJsPlugin({
        //    parallel: true,
        //    sourceMap: true
        //})
        new TerserPlugin({
            parallel: true,
            terserOptions:{
                compress: true,
                mangle: true,
                sourceMap: true
            }
        })
    ]
};

const webPlugins = plugins.slice(0);
const serverPlugins = plugins.slice(0);

// Inform our React code of what build we're on.
// This works via a find-replace.
webPlugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(env),
    'SERVERSIDE' : JSON.stringify(false),
    'BUILDTYPE' : JSON.stringify(env)
}));

serverPlugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(env),
    'SERVERSIDE' : JSON.stringify(true),
    'BUILDTYPE' : JSON.stringify(env)
}));

if (mode === 'development'){
    webPlugins.push(
        new BundleAnalyzerPlugin({
            "analyzerMode" : "static",
            "openAnalyzer" : false,
            "logLevel" : "warn",
            "reportFilename" : "report-web-bundle.html"
        })
    );
    serverPlugins.push(
        new BundleAnalyzerPlugin({
            "analyzerMode" : "static",
            "openAnalyzer" : false,
            "logLevel" : "warn",
            "reportFilename" : "report-server-renderer.html"
        })
    );
}

module.exports = [
    // for browser
    {
        mode: mode,
        entry: {
            "bundle"    : PATHS.static + '/browser'
        },
        target: "web",
        output: {
            path: PATHS.build,
            publicPath: '/static/build/',
            filename: '[name].js',          // TODO: Eventually we can change this to be chunkFilename as well, however this can only occur after we refactor React to only render <body> element and then we can use
                                            // this library, https://www.npmjs.com/package/chunkhash-replace-webpack-plugin, to replace the <script> tag's src attribute.
                                            // For now, to prevent caching JS, we append a timestamp to JS request.
            chunkFilename: chunkFilename,

            libraryTarget: "umd",
            library: "App",
            umdNamedDefine: true
        },
        // https://github.com/hapijs/joi/issues/665
        // stub modules on client side depended on by joi (a dependency of jwt)
        node: {
            net: "empty",
            tls: "empty",
            dns: "empty",
        },
        externals: [
            {'xmlhttprequest' : '{XMLHttpRequest:XMLHttpRequest}'}
        ],
        module: {
            rules: rules
        },
        optimization: optimization,
        resolve : resolve,
        resolveLoader : resolve,
        devtool: devTool,
        plugins: webPlugins
    },
    // for server-side rendering
    ///*
    {
        mode: mode,
        entry: {
            renderer: PATHS.static + '/server',
        },
        target: 'node',
        // make sure compiled modules can use original __dirname
        node: {
            __dirname: true,
        },
        externals: [ // Anything which is not to be used server-side may be excluded
            'brace',
            'brace/mode/json',
            'brace/theme/solarized_light',
            'd3',
            'dagre-d3',
            '@babel/register', // avoid bundling babel transpiler, which is not used at runtime
            { 'higlass/dist/hglib' : '{HiGlassComponent:{}}' },
            'higlass',
            'auth0-lock',
            'aws-sdk',
            'src/encoded/static/components/utils/aws'
        ],
        output: {
            path: PATHS.build,
            filename: '[name].js',
            libraryTarget: 'umd',
            chunkFilename: chunkFilename,
        },
        module: {
            rules: rules.concat([
                { parser: { requireEnsure: false } }
            ])
        },
        optimization: optimization,
        resolve : resolve,
        resolveLoader : resolve,
        devtool: devTool, // No way to debug/log serverside JS currently, so may as well speed up builds for now.
        plugins: serverPlugins
    }
    //*/
];
<commit_msg>Enable sourcemap in production builds (fix)<commit_after>const path = require('path');
const webpack = require('webpack');
const env = process.env.NODE_ENV;
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const PATHS = {
    "static": path.resolve(__dirname, 'src/encoded/static'),
    "build" : path.resolve(__dirname, 'src/encoded/static/build'),
};

const mode = (env === 'production' ? 'production' : 'development');

const plugins = [];

// don't include momentjs locales (large)
plugins.push(
    new webpack.IgnorePlugin({
        resourceRegExp: /^\.\/locale$/,
        contextRegExp: /moment$/
    })
);

let chunkFilename = '[name].js';
let devTool = 'source-map'; // Default, slowest.

if (mode === 'production') {
    // add chunkhash to chunk names for production only (it's slower)
    chunkFilename = '[name].[chunkhash].js';
    devTool = 'source-map';
} else if (env === 'quick') {
    devTool = 'eval'; // Fastest
} else if (env === 'development') {
    devTool = 'inline-source-map';
}

var rules = [
    // Strip @jsx pragma in react-forms, which makes babel abort
    {
        test: /\.js$/,
        loader: 'string-replace-loader',
        enforce: 'pre',
        query: {
            search: '@jsx',
            replace: 'jsx',
        }
    },
    // add babel to load .js files as ES6 and transpile JSX
    {
        test: /\.(js|jsx)$/,
        include: [
            path.resolve(__dirname, 'src/encoded/static'),
        ],
        use: [
            {
                loader: 'babel-loader'
            }
        ]
    }
];

var resolve = {
    extensions : [".webpack.js", ".web.js", ".js", ".json", '.jsx']
};

var optimization = {
    minimize: mode === "production",
    minimizer: [
        //new UglifyJsPlugin({
        //    parallel: true,
        //    sourceMap: true
        //})
        new TerserPlugin({
            parallel: true,
            sourceMap: true,
            terserOptions:{
                compress: true,
                mangle: true
            }
        })
    ]
};

const webPlugins = plugins.slice(0);
const serverPlugins = plugins.slice(0);

// Inform our React code of what build we're on.
// This works via a find-replace.
webPlugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(env),
    'SERVERSIDE' : JSON.stringify(false),
    'BUILDTYPE' : JSON.stringify(env)
}));

serverPlugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(env),
    'SERVERSIDE' : JSON.stringify(true),
    'BUILDTYPE' : JSON.stringify(env)
}));

if (mode === 'development'){
    webPlugins.push(
        new BundleAnalyzerPlugin({
            "analyzerMode" : "static",
            "openAnalyzer" : false,
            "logLevel" : "warn",
            "reportFilename" : "report-web-bundle.html"
        })
    );
    serverPlugins.push(
        new BundleAnalyzerPlugin({
            "analyzerMode" : "static",
            "openAnalyzer" : false,
            "logLevel" : "warn",
            "reportFilename" : "report-server-renderer.html"
        })
    );
}

module.exports = [
    // for browser
    {
        mode: mode,
        entry: {
            "bundle"    : PATHS.static + '/browser'
        },
        target: "web",
        output: {
            path: PATHS.build,
            publicPath: '/static/build/',
            filename: '[name].js',          // TODO: Eventually we can change this to be chunkFilename as well, however this can only occur after we refactor React to only render <body> element and then we can use
                                            // this library, https://www.npmjs.com/package/chunkhash-replace-webpack-plugin, to replace the <script> tag's src attribute.
                                            // For now, to prevent caching JS, we append a timestamp to JS request.
            chunkFilename: chunkFilename,

            libraryTarget: "umd",
            library: "App",
            umdNamedDefine: true
        },
        // https://github.com/hapijs/joi/issues/665
        // stub modules on client side depended on by joi (a dependency of jwt)
        node: {
            net: "empty",
            tls: "empty",
            dns: "empty",
        },
        externals: [
            {'xmlhttprequest' : '{XMLHttpRequest:XMLHttpRequest}'}
        ],
        module: {
            rules: rules
        },
        optimization: optimization,
        resolve : resolve,
        resolveLoader : resolve,
        devtool: devTool,
        plugins: webPlugins
    },
    // for server-side rendering
    ///*
    {
        mode: mode,
        entry: {
            renderer: PATHS.static + '/server',
        },
        target: 'node',
        // make sure compiled modules can use original __dirname
        node: {
            __dirname: true,
        },
        externals: [ // Anything which is not to be used server-side may be excluded
            'brace',
            'brace/mode/json',
            'brace/theme/solarized_light',
            'd3',
            'dagre-d3',
            '@babel/register', // avoid bundling babel transpiler, which is not used at runtime
            { 'higlass/dist/hglib' : '{HiGlassComponent:{}}' },
            'higlass',
            'auth0-lock',
            'aws-sdk',
            'src/encoded/static/components/utils/aws'
        ],
        output: {
            path: PATHS.build,
            filename: '[name].js',
            libraryTarget: 'umd',
            chunkFilename: chunkFilename,
        },
        module: {
            rules: rules.concat([
                { parser: { requireEnsure: false } }
            ])
        },
        optimization: optimization,
        resolve : resolve,
        resolveLoader : resolve,
        devtool: devTool, // No way to debug/log serverside JS currently, so may as well speed up builds for now.
        plugins: serverPlugins
    }
    //*/
];
<|endoftext|>