<commit_before>/* global require, exports, console */
/** Manages framescripts and communication with those scripts

    Likely the only function you'll use is `callScript()`
    */
const { getBrowserForTab } = require('sdk/tabs/utils');
const { defer } = require('sdk/core/promise');
const { viewFor } = require("sdk/view/core");
const { setTimeout, clearTimeout } = require("sdk/timers");

let DEBUG = false;
let loadedTimestamp = Date.now();

/** call setDebug(true) to get debug information on the console */
exports.setDebug = function (val) {
  DEBUG = val;
};

function logDebug() {
  if (! DEBUG) {
    return;
  }
  let args = [];
  for (var i=0; i<arguments.length; i++) {
    if (typeof arguments[i] == "object" &&
      JSON.stringify(arguments[i]).length > 100) {
        args.push("[Object keys: " + JSON.stringify(Object.keys(arguments[i])) + "]");
    } else {
      args.push(arguments[i]);
    }
  }
  console.info.apply(console, args);
}

/** Gets the XUL browser object for a given tab (XUL tab or SDK tab) */
function getBrowser(tab) {
  if (tab && tab.attach) {
    // Convert from SDK tab to XUL tab
    tab = viewFor(tab);
  }
  return getBrowserForTab(tab);
}

/** Ensures a script is attached to a given tab

    Framescripts are long-lived, and live longer than any one page that is
    loaded.  This attaches tracking attributes to the browser to see which
    scripts have been attached. */
exports.addScript = function (tab, script) {
  let browser = getBrowser(tab);
  let scripts = browser.framescripterEnabledScripts;
  if (! scripts) {
    scripts = browser.framescripterEnabledScripts = {};
  }
  if (! scripts[script]) {
    logDebug("Adding script:", script);
    let browserMM = browser.messageManager;
    if (! browserMM) {
      console.error("Could not get messageManager from " + browser);
      throw new Error("Could not get messageManager");
    }
    browserMM.loadFrameScript(script + "?bust=" + loadedTimestamp, false);
    scripts[script] = {};
  } else {
    logDebug("Script already loaded:", script);
  }
};

exports.unload = function () {
  for (let tab of require("sdk/tabs")) {
    let browser = getBrowser(tab);
    let scripts = browser.framescripterEnabledScripts;
    if (! scripts) {
      continue;
    }
    let browserMM = browser.messageManager;
    browserMM.sendAsyncMessage("pageshot@disable");
    delete browser.framescripterEnabledScripts;
  }
};

// Used to match up incoming with outgoing messages
let idCounter = 1;

function makeId() {
  return idCounter++;
}

const pendingDeferreds = {};
const pendingTimeouts = {};

/** Adds the script to the given tab

    Adds listeners to handle the two messages: a message with the name
    `message + ":call"` is sent to the framescript, and we expect a message
    with the name `message + ":return"`.  Each will include `callId` in the
    payload, to match up a call with a return.

    The payload includes any arguments to send to the framescript.

    Returns a promise that resolves when the return message is sent.
    */
exports.callScript = function (tab, script, message, payload, timeout) {
  if (timeout === undefined) {
    timeout = 7000;
  }
  exports.addScript(tab, script);
  let browser = getBrowser(tab);
  let messages = browser.framescripterEnabledScripts[script];
  let browserMM = browser.messageManager;
  if (! messages[message]) {
    browserMM.addMessageListener(message + ":return", callScriptReturner);
    messages[message] = true;
    logDebug("Adding frame listener for:", message + ":return");
  }
  let deferred = defer();
  let id = makeId();
  pendingDeferreds[id] = deferred;
  payload.callId = id;
  logDebug("Sending [" + message + ":call]/" + id + " with payload:", payload);
  browserMM.sendAsyncMessage(message + ":call", payload);
  if (timeout) {
    pendingTimeouts[id] = setTimeout(function () {
      if (pendingDeferreds[id]) {
        // The promise has not yet completed
        var deferred = pendingDeferreds[id];
        delete pendingDeferreds[id];
        delete pendingTimeouts[id];
        logDebug("Script timed out:", script, message, "after:", timeout);
        deferred.reject(new Error("Timeout after " + timeout + "ms"));
      } else {
        logDebug("Timeout ran despite deferred being completed, for:", script, message);
      }
    }, timeout);
  }
  return deferred.promise;
};

// Handler for a specific event type, used to resolve promises:
function callScriptReturner(event) {
  let deferred = pendingDeferreds[event.data.callId];
  if (! deferred) {
    console.error("Got deferred that has expired:", event.data.callId);
    throw new Error("Expired deferred");
  }
  delete pendingDeferreds[event.data.callId];
  if (pendingTimeouts[event.data.callId]) {
    clearTimeout(pendingTimeouts[event.data.callId]);
    delete pendingTimeouts[event.data.callId];
  }
  logDebug("Received /" + event.data.callId + " with payload:", event.data);
  if (event.data.error) {
    deferred.reject(event.data.error);
  } else {
    delete event.data.callId;
    deferred.resolve(event.data);
  }
}
<commit_msg>Include name of message that timed out in framescripter error message<commit_after>/* global require, exports, console */
/** Manages framescripts and communication with those scripts

    Likely the only function you'll use is `callScript()`
    */
const { getBrowserForTab } = require('sdk/tabs/utils');
const { defer } = require('sdk/core/promise');
const { viewFor } = require("sdk/view/core");
const { setTimeout, clearTimeout } = require("sdk/timers");

let DEBUG = false;
let loadedTimestamp = Date.now();

/** call setDebug(true) to get debug information on the console */
exports.setDebug = function (val) {
  DEBUG = val;
};

function logDebug() {
  if (! DEBUG) {
    return;
  }
  let args = [];
  for (var i=0; i<arguments.length; i++) {
    if (typeof arguments[i] == "object" &&
      JSON.stringify(arguments[i]).length > 100) {
        args.push("[Object keys: " + JSON.stringify(Object.keys(arguments[i])) + "]");
    } else {
      args.push(arguments[i]);
    }
  }
  console.info.apply(console, args);
}

/** Gets the XUL browser object for a given tab (XUL tab or SDK tab) */
function getBrowser(tab) {
  if (tab && tab.attach) {
    // Convert from SDK tab to XUL tab
    tab = viewFor(tab);
  }
  return getBrowserForTab(tab);
}

/** Ensures a script is attached to a given tab

    Framescripts are long-lived, and live longer than any one page that is
    loaded.  This attaches tracking attributes to the browser to see which
    scripts have been attached. */
exports.addScript = function (tab, script) {
  let browser = getBrowser(tab);
  let scripts = browser.framescripterEnabledScripts;
  if (! scripts) {
    scripts = browser.framescripterEnabledScripts = {};
  }
  if (! scripts[script]) {
    logDebug("Adding script:", script);
    let browserMM = browser.messageManager;
    if (! browserMM) {
      console.error("Could not get messageManager from " + browser);
      throw new Error("Could not get messageManager");
    }
    browserMM.loadFrameScript(script + "?bust=" + loadedTimestamp, false);
    scripts[script] = {};
  } else {
    logDebug("Script already loaded:", script);
  }
};

exports.unload = function () {
  for (let tab of require("sdk/tabs")) {
    let browser = getBrowser(tab);
    let scripts = browser.framescripterEnabledScripts;
    if (! scripts) {
      continue;
    }
    let browserMM = browser.messageManager;
    browserMM.sendAsyncMessage("pageshot@disable");
    delete browser.framescripterEnabledScripts;
  }
};

// Used to match up incoming with outgoing messages
let idCounter = 1;

function makeId() {
  return idCounter++;
}

const pendingDeferreds = {};
const pendingTimeouts = {};

/** Adds the script to the given tab

    Adds listeners to handle the two messages: a message with the name
    `message + ":call"` is sent to the framescript, and we expect a message
    with the name `message + ":return"`.  Each will include `callId` in the
    payload, to match up a call with a return.

    The payload includes any arguments to send to the framescript.

    Returns a promise that resolves when the return message is sent.
    */
exports.callScript = function (tab, script, message, payload, timeout) {
  if (timeout === undefined) {
    timeout = 7000;
  }
  exports.addScript(tab, script);
  let browser = getBrowser(tab);
  let messages = browser.framescripterEnabledScripts[script];
  let browserMM = browser.messageManager;
  if (! messages[message]) {
    browserMM.addMessageListener(message + ":return", callScriptReturner);
    messages[message] = true;
    logDebug("Adding frame listener for:", message + ":return");
  }
  let deferred = defer();
  let id = makeId();
  pendingDeferreds[id] = deferred;
  payload.callId = id;
  logDebug("Sending [" + message + ":call]/" + id + " with payload:", payload);
  browserMM.sendAsyncMessage(message + ":call", payload);
  if (timeout) {
    pendingTimeouts[id] = setTimeout(function () {
      if (pendingDeferreds[id]) {
        // The promise has not yet completed
        var deferred = pendingDeferreds[id];
        delete pendingDeferreds[id];
        delete pendingTimeouts[id];
        logDebug("Script timed out:", script, message, "after:", timeout);
        deferred.reject(new Error("Timeout after " + timeout + "ms in " + message));
      } else {
        logDebug("Timeout ran despite deferred being completed, for:", script, message);
      }
    }, timeout);
  }
  return deferred.promise;
};

// Handler for a specific event type, used to resolve promises:
function callScriptReturner(event) {
  let deferred = pendingDeferreds[event.data.callId];
  if (! deferred) {
    console.error("Got deferred that has expired:", event.data.callId);
    throw new Error("Expired deferred");
  }
  delete pendingDeferreds[event.data.callId];
  if (pendingTimeouts[event.data.callId]) {
    clearTimeout(pendingTimeouts[event.data.callId]);
    delete pendingTimeouts[event.data.callId];
  }
  logDebug("Received /" + event.data.callId + " with payload:", event.data);
  if (event.data.error) {
    deferred.reject(event.data.error);
  } else {
    delete event.data.callId;
    deferred.resolve(event.data);
  }
}
<|endoftext|>


<commit_before>
var fs = require('fs');
var path = require('path');
var semver = require('semver');

var optimist = require('optimist')

var updater = require('../app/lib/updater.js');
var _ = require('../app/lib/third/underscore.js');

// What files to update. Relative to project root.
var UPDATE_FILES = ['app/lib/updater.js', 'admin/install-s3.sh',
                    ['admin/manifest.json', 'g']];

// Files to update for dev_bundle
var BUNDLE_FILES = ['admin/generate-dev-bundle.sh', 'meteor'];

var opt = require('optimist')
  .alias('dev_bundle', 'd')
  .boolean('dev_bundle')
  .describe('dev_bundle', 'Update the dev_bundle version, not the main version.')
  .alias('new_version', 'n')
  .describe('new_version', 'A new version number. Default is to increment patch number.')
  .usage('Usage: $0 [options]')
;
var argv = opt.argv;
if (argv.help) {
  process.stdout.write(opt.help());
  process.exit(1);
}

var CURRENT_VERSION = updater.CURRENT_VERSION;
var files = UPDATE_FILES;

if (argv.dev_bundle) {
  var version_path = path.join(__dirname, '..', 'meteor');
  var version_data = fs.readFileSync(version_path, 'utf8');
  var version_match = /BUNDLE_VERSION=([\d\.]+)/.exec(version_data);
  CURRENT_VERSION = version_match[1];
  files = BUNDLE_FILES;
}

var NEW_VERSION = argv.new_version || semver.inc(CURRENT_VERSION, 'patch');

console.log("Updating from " + CURRENT_VERSION + " to " + NEW_VERSION);

_.each(files, function (file) {
  var flags = '';
  if (file instanceof Array) {
    flags = file[1];
    file = file[0];
  }
  var fp = path.join(__dirname, '..', file);
  var text = fs.readFileSync(fp, 'utf8');
  var new_text = text.replace(new RegExp(CURRENT_VERSION, flags), NEW_VERSION);
  fs.writeFileSync(fp, new_text, 'utf8');

  console.log("updated file: " + fp);
});

console.log("Complete");
<commit_msg>Update script to bump docs as well.<commit_after>
var fs = require('fs');
var path = require('path');
var semver = require('semver');

var optimist = require('optimist');

var updater = require('../app/lib/updater.js');
var _ = require('../app/lib/third/underscore.js');

// What files to update. Relative to project root.
var UPDATE_FILES = ['app/lib/updater.js',
                    'admin/install-s3.sh',
                    'docs/client/docs.html',
                    ['admin/manifest.json', 'g']];

// Files to update for dev_bundle
var BUNDLE_FILES = ['admin/generate-dev-bundle.sh', 'meteor'];

var opt = require('optimist')
  .alias('dev_bundle', 'd')
  .boolean('dev_bundle')
  .describe('dev_bundle', 'Update the dev_bundle version, not the main version.')
  .alias('new_version', 'n')
  .describe('new_version', 'A new version number. Default is to increment patch number.')
  .usage('Usage: $0 [options]')
;
var argv = opt.argv;
if (argv.help) {
  process.stdout.write(opt.help());
  process.exit(1);
}

var CURRENT_VERSION = updater.CURRENT_VERSION;
var files = UPDATE_FILES;

if (argv.dev_bundle) {
  var version_path = path.join(__dirname, '..', 'meteor');
  var version_data = fs.readFileSync(version_path, 'utf8');
  var version_match = /BUNDLE_VERSION=([\d\.]+)/.exec(version_data);
  CURRENT_VERSION = version_match[1];
  files = BUNDLE_FILES;
}

var NEW_VERSION = argv.new_version || semver.inc(CURRENT_VERSION, 'patch');

console.log("Updating from " + CURRENT_VERSION + " to " + NEW_VERSION);

_.each(files, function (file) {
  var flags = '';
  if (file instanceof Array) {
    flags = file[1];
    file = file[0];
  }
  var fp = path.join(__dirname, '..', file);
  var text = fs.readFileSync(fp, 'utf8');
  var new_text = text.replace(new RegExp(CURRENT_VERSION, flags), NEW_VERSION);
  fs.writeFileSync(fp, new_text, 'utf8');

  console.log("updated file: " + fp);
});

console.log("Complete");
<|endoftext|>


<commit_before>import { StorageAuthentication as StorageAuth } from './StorageAuthentication'
import { ValidationError } from './errors'
import logger from 'winston'

export class HubServer {
  constructor(driver: Object, proofChecker: Object,
              config: { whitelist: Array<string> }) {
    this.driver = driver
    this.proofChecker = proofChecker
    this.whitelist = config.whitelist
  }

  // throws exception on validation error
  //   otherwise returns void.
  validate(address: string, requestHeaders: { authorization: string }) {
    if (this.whitelist && !(this.whitelist.includes(address))) {
      throw new ValidationError('Address not authorized for writes')
    }

    let authObject = null
    try {
      authObject = StorageAuth.fromAuthHeader(requestHeaders.authorization)
    } catch (err) {
      logger.error(err)
    }

    if (!authObject) {
      throw new ValidationError('Failed to parse authentication header.')
    }

    authObject.isAuthenticationValid(address, true)
  }

  handleRequest(address: string, path: string,
                requestHeaders: {},
                stream: stream.Readable) {
    this.validate(address, requestHeaders)

    let contentType = requestHeaders['content-type']

    if (contentType === null || contentType === undefined) {
      contentType = 'application/octet-stream'
    }

    const writeCommand = { storageTopLevel: address,
                           path, stream, contentType,
                           contentLength: requestHeaders['content-length'] }

    return this.proofChecker.checkProofs(this.req)
      .then(() => this.driver.performWrite(writeCommand))
  }
}
<commit_msg>fix bug in calling to the proof checker<commit_after>import { StorageAuthentication as StorageAuth } from './StorageAuthentication'
import { ValidationError } from './errors'
import logger from 'winston'

export class HubServer {
  constructor(driver: Object, proofChecker: Object,
              config: { whitelist: Array<string> }) {
    this.driver = driver
    this.proofChecker = proofChecker
    this.whitelist = config.whitelist
  }

  // throws exception on validation error
  //   otherwise returns void.
  validate(address: string, requestHeaders: { authorization: string }) {
    if (this.whitelist && !(this.whitelist.includes(address))) {
      throw new ValidationError('Address not authorized for writes')
    }

    let authObject = null
    try {
      authObject = StorageAuth.fromAuthHeader(requestHeaders.authorization)
    } catch (err) {
      logger.error(err)
    }

    if (!authObject) {
      throw new ValidationError('Failed to parse authentication header.')
    }

    authObject.isAuthenticationValid(address, true)
  }

  handleRequest(address: string, path: string,
                requestHeaders: {},
                stream: stream.Readable) {
    this.validate(address, requestHeaders)

    let contentType = requestHeaders['content-type']

    if (contentType === null || contentType === undefined) {
      contentType = 'application/octet-stream'
    }

    const writeCommand = { storageTopLevel: address,
                           path, stream, contentType,
                           contentLength: requestHeaders['content-length'] }

    return this.proofChecker.checkProofs(address, path)
      .then(() => this.driver.performWrite(writeCommand))
  }
}
<|endoftext|>


<commit_before>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define){
define(function() {
"use strict";

	var undef;

	/**
	 * Creates an object by either invoking ctor as a function and returning the result,
	 * or by calling new ctor().  It uses a simple heuristic to try to guess which approach
	 * is the "right" one.
	 *
	 * @param ctor {Function} function or constructor to invoke
	 * @param args {Array} array of arguments to pass to ctor in either case
	 *
	 * @return The result of invoking ctor with args, with or without new, depending on
	 * the strategy selected.
	 */
	return function createComponent(ctor, args, forceConstructor) {

		var begotten;

		if (forceConstructor || isConstructor(ctor)) {
			begotten = Object.create(ctor.prototype);
			defineConstructorIfPossible(begotten, ctor);
			ctor.apply(begotten, args);

		} else {
			begotten = ctor.apply(undef, args);

		}

		return begotten === undef ? null : begotten;
	};

	/**
	 * Carefully sets the instance's constructor property to the supplied
	 * constructor, using Object.defineProperty if available.  If it can't
	 * set the constructor in a safe way, it will do nothing.
	 *
	 * @param instance {Object} component instance
	 * @param ctor {Function} constructor
	 */
	function defineConstructorIfPossible(instance, ctor) {
		try {
			Object.defineProperty(instance, 'constructor', {
				value: ctor,
				enumerable: false
			});
		} catch(e) {
			// If we can't define a constructor, oh well.
			// This can happen if in envs where Object.defineProperty is not
			// available, or when using cujojs/poly or other ES5 shims
		}
	}

	/**
	 * Determines whether the supplied function should be invoked directly or
	 * should be invoked using new in order to create the object to be wired.
	 *
	 * @param func {Function} determine whether this should be called using new or not
	 *
	 * @returns {Boolean} true iff func should be invoked using new, false otherwise.
	 */
	function isConstructor(func) {
		var is = false, p;
		for (p in func.prototype) {
			if (p !== undef) {
				is = true;
				break;
			}
		}

		return is;
	}

});
})(typeof define == 'function'
	// AMD
	? define
	// CommonJS
	: function(factory) {
		module.exports = factory();
	}
);<commit_msg>Handle constructors that may return an object that is different from its context<commit_after>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define){
define(function() {
"use strict";

	var undef;

	/**
	 * Creates an object by either invoking ctor as a function and returning the result,
	 * or by calling new ctor().  It uses a simple heuristic to try to guess which approach
	 * is the "right" one.
	 *
	 * @param ctor {Function} function or constructor to invoke
	 * @param args {Array} array of arguments to pass to ctor in either case
	 *
	 * @return The result of invoking ctor with args, with or without new, depending on
	 * the strategy selected.
	 */
	return function createComponent(ctor, args, forceConstructor) {

		var begotten, ctorResult;

		if (forceConstructor || isConstructor(ctor)) {
			begotten = Object.create(ctor.prototype);
			defineConstructorIfPossible(begotten, ctor);
			ctorResult = ctor.apply(begotten, args);
			if(ctorResult !== undef) {
				begotten = ctorResult;
			}

		} else {
			begotten = ctor.apply(undef, args);

		}

		return begotten === undef ? null : begotten;
	};

	/**
	 * Carefully sets the instance's constructor property to the supplied
	 * constructor, using Object.defineProperty if available.  If it can't
	 * set the constructor in a safe way, it will do nothing.
	 *
	 * @param instance {Object} component instance
	 * @param ctor {Function} constructor
	 */
	function defineConstructorIfPossible(instance, ctor) {
		try {
			Object.defineProperty(instance, 'constructor', {
				value: ctor,
				enumerable: false
			});
		} catch(e) {
			// If we can't define a constructor, oh well.
			// This can happen if in envs where Object.defineProperty is not
			// available, or when using cujojs/poly or other ES5 shims
		}
	}

	/**
	 * Determines whether the supplied function should be invoked directly or
	 * should be invoked using new in order to create the object to be wired.
	 *
	 * @param func {Function} determine whether this should be called using new or not
	 *
	 * @returns {Boolean} true iff func should be invoked using new, false otherwise.
	 */
	function isConstructor(func) {
		var is = false, p;
		for (p in func.prototype) {
			if (p !== undef) {
				is = true;
				break;
			}
		}

		return is;
	}

});
})(typeof define == 'function'
	// AMD
	? define
	// CommonJS
	: function(factory) {
		module.exports = factory();
	}
);<|endoftext|>


<commit_before>var fs = require('fs')

var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())

exports.VERSION = pkg.version

exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'

// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'

// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%p [%c]: %m'

// Default console appender
exports.CONSOLE_APPENDER = {
  type: 'console',
  layout: {
    type: 'pattern',
    pattern: exports.COLOR_PATTERN
  }
}

exports.EXIT_CODE = '\x1FEXIT'
<commit_msg>feat(logger): Add date/time stamp to log output<commit_after>var fs = require('fs')

var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())

exports.VERSION = pkg.version

exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'

// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'

// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%d{DATE}:%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%d{DATE}:%p [%c]: %m'

// Default console appender
exports.CONSOLE_APPENDER = {
  type: 'console',
  layout: {
    type: 'pattern',
    pattern: exports.COLOR_PATTERN
  }
}

exports.EXIT_CODE = '\x1FEXIT'
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleBuilder = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if (creep.memory.building && creep.carry.energy == 0) {
            creep.memory.building = false;
            creep.say('harvesting');
        }
        if (!creep.memory.building && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE)) && creep.carry.energy > 0)) {
            creep.memory.building = true;
            creep.say('building');
        }

        if (creep.memory.building) {
            if (creep.room.find(FIND_CONSTRUCTION_SITES)) {
                var target = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
                if (creep.build(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                var repairThem = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_WALL &&
                    (structure.hits < 80000) &&
                    (structure.hits > 0));
                    }
                })

                if (creep.room.find(repairThem)) {
                    var target = creep.pos.findClosestByPath(repairThem);
                    if (creep.build(target) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(target);
                        creep.say("Repair wall")
                    }
                }
            }
        }

        else {
            var target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
            if (target) {
                if(creep.harvest(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                //do something else
            }
        }
    }
};

module.exports = roleBuilder;<commit_msg>adding idling location for builders<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleBuilder = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var activeSources = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
        if (creep.memory.building && creep.carry.energy == 0 && activeSources) {
            creep.memory.building = false;
            creep.memory.idling = false;
            creep.say('harvesting');
        } else if (!creep.memory.building && creep.carry.energy == creep.carryCapacity || ((!activeSources) && creep.carry.energy > 0)) {
            creep.memory.building = true;
            creep.memory.idling = false;
            creep.say('building');
        } else {
            creep.memory.idling = true;
            creep.say('H-idling')
        }

        if (creep.memory.building) {
            if (creep.room.find(FIND_CONSTRUCTION_SITES)) {
                var target = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
                if (creep.build(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                var repairThem = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_WALL &&
                    (structure.hits < 80000) &&
                    (structure.hits > 0));
                    }
                })

                if (creep.room.find(repairThem)) {
                    var target = creep.pos.findClosestByPath(repairThem);
                    if (creep.build(target) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(target);
                        creep.say("Repair wall")
                    }
                }
            }
        }

        else if (!creep.memory.idling) {
            var target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
            if (target) {
                if(creep.harvest(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                //do something else
            }

        } else {
            var target = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(target);
        }
    }
};

module.exports = roleBuilder;<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleBuilder = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var activeSource = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
        //console.log(activeSource);
        if (creep.memory.building && creep.carry.energy == 0 && (activeSource !== null)) {
            creep.memory.building = false;
            creep.memory.idling = false;
            creep.say('harvesting');
        } else if (!creep.memory.building && (creep.carry.energy == creep.carryCapacity || ((activeSource === null) && creep.carry.energy > 0))) {
            creep.memory.building = true;
            creep.memory.idling = false;
            creep.say('building');
        } else {
            creep.memory.idling = true;
            creep.say('B-idling')
        }

        if (creep.memory.building) {
            if (creep.room.find(FIND_CONSTRUCTION_SITES)) {
                var target = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
                if (creep.build(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                var repairThem = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_WALL &&
                    (structure.hits < 80000) &&
                    (structure.hits > 0));
                    }
                })

                if (creep.room.find(repairThem)) {
                    var target = creep.pos.findClosestByPath(repairThem);
                    if (creep.build(target) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(target);
                        creep.say("Repair wall")
                    }
                }
            }
        }

        else if (!creep.memory.idling) {
            var target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
            if (target) {
                if(creep.harvest(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                //do something else
            }

        } else {
            var target = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(target);
        }
    }
};

module.exports = roleBuilder;<commit_msg>debugging builder idle code<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleBuilder = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var activeSource = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
        //console.log(activeSource);
        if (creep.memory.building && creep.carry.energy == 0 && activeSource !== null) {
            creep.memory.building = false;
            creep.memory.idling = false;
            creep.say('harvesting');
        } else if (!creep.memory.building && (creep.carry.energy == creep.carryCapacity || ((activeSource === null) && creep.carry.energy > 0))) {
            creep.memory.building = true;
            creep.memory.idling = false;
            creep.say('building');
        } else if (activeSource === null) {
            creep.memory.idling = true;
            creep.say('B-idling')
        }

        if (creep.memory.building) {
            if (creep.room.find(FIND_CONSTRUCTION_SITES)) {
                var target = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
                if (creep.build(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                var repairThem = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_WALL &&
                    (structure.hits < 80000) &&
                    (structure.hits > 0));
                    }
                })

                if (creep.room.find(repairThem)) {
                    var target = creep.pos.findClosestByPath(repairThem);
                    if (creep.build(target) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(target);
                        creep.say("Repair wall")
                    }
                }
            }
        }

        else if (!creep.memory.idling) {
            var target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
            if (target) {
                if(creep.harvest(target) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }
            } else {
                //do something else
            }

        } else {
            var target = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(target);
        }
    }
};

module.exports = roleBuilder;<|endoftext|>


<commit_before>$(function () {
  var Fulfil = {
    csrfToken: "{{ csrf_token() }}",
    urls: {},
    form: {},
    cart: {},
    user: {},
    ux: {},
    product: {},
    address: {}
  };

  // All the URLs this file needs to know
  Fulfil.urls.view_cart = "{{ url_for('cart.view_cart') }}";
  Fulfil.urls.remove_from_cart = "{{ url_for('cart.remove_from_cart') }}";
  Fulfil.urls.getVariations = "{{ url_for('products.get_variations') }}";

  /**
   * Helper method to change formSubmission to ajax
   *
   * @param formElement HTMLElement
   * @param options Object with successCallback, errorCallback,
   *                alwaysCallback, onSubmit as keys
   */
  Fulfil.form.ajaxSubmit = function (formElement, options) {
    var form = $(formElement);

    options = options || {}

    form.on('submit', function (event) {
      event.preventDefault();

      // Call onSubmit if function
      if ($.isFunction(options.onSubmit)) {
        options.onSubmit(event);
      }

      $.ajax({
        'url': form.attr("action"),
        'type': form.attr('method') || 'GET',
        'data': form.serialize(),
        'dataType': "json"
      })
        .done(options.successCallback)
        .fail(options.errorCallback)
        .always(options.alwaysCallback);
    });
  };

  /**
   * Method to show errors in form
   */
  Fulfil.form.showErrors = function (formElement, errorsObj) {
    var form = $(formElement);

    $.each(errorsObj, function (key, value) {
      // TODO: show errors
    });
  };

  /**
   * Helper method to initialize login form
   */
  Fulfil.form.initLoginForm =  function (formElement) {
    var errorContainer = formElement.find('.error-message');

    // by default hide error container
    errorContainer.html('').hide();

    var options = {
      onSubmit: function () {
        errorContainer.html('').hide();
      },
      successCallback: function (result) {
        location.reload();
      },
      errorCallback: function (error) {
        if (error.status == 400) {
          if (!error.responseJSON.errors) {
            console.error("No 'errors' in response on bad request.");
          }

          var errors = [];
          $.each(error.responseJSON.errors, function (key, value) {
            errors = errors.concat(value);
          });

          // Show errors in error container
          errorContainer.html(errors.join(',')).show();
          return;
        }
        console.log(error.statusText);
      }
    };

    Fulfil.form.ajaxSubmit(formElement, options);
  };

  /*
   *
   * Cart related logic
   * ==================
   *
   */

   /*
    * Refreshes the cart and updates Fulfil.cart.current_cart
    * Also returns the request promise.
    *
    */
   Fulfil.cart.refresh = function() {
    console.debug("Refreshing Cart");
    return $.ajax({
      cache: false,
      url: Fulfil.urls.view_cart,
      dataType: "json",
      success: function(data){
        Fulfil.cart.current_cart = data.cart;
      }
    })
   };

   /*
    * Delete a item from the cart.
    *
    */
   Fulfil.cart.deleteItem = function(lineId) {
    console.debug("Removing Line from Cart");
    return $.ajax({
      url: Fulfil.urls.remove_from_cart,
      method: "POST",
      data: {
        "line_id": lineId,
        "csrf_token": Fulfil.csrfToken
       },
       dataType: "json",
       success: function() {
         Fulfil.cart.refresh();
       }
    });
   }

  /*
   *
   * Product related logic
   * =====================
   *
   */

  /*
   *
   * Fetch variation data for a product template
   *
   */
  Fulfil.product.getVariations = function(templateId) {
    return $.ajax({
      url: Fulfil.urls.getVariations,
      method: "GET",
      data: {
        "template": templateId
       },
       dataType: "json",
       success: function(data) {
         Fulfil.product.loadVariations(data);
       }
    });
  };

  /*
   * Load the variation data locally to serve more
   * requests.
   */
  Fulfil.product.loadVariations = function(variationData) {
    Fulfil.product.variationData = variationData;
  };

  /*
   * Given a set of attributes, return a variant
   * that fits the attributes
   *
   */
  Fulfil.product.findMatchingVariant = function(attributeSelection) {
    return _.find(Fulfil.product.variationData['variants'], function(variant) {
      return _.isEqual(variant.attributes, attributeSelection)
    });
  };

  /*
   * Return the data of the variant with id
   *
   */
  Fulfil.product.getVariant = function(variantId) {
    return _.find(Fulfil.product.variationData['variants'], function(variant) {
      return (variant.id == variantId) ;
    });
  };

  /*
   *
   * Address related logic
   * =====================
   *
   */

  /*
   * Return list of all available countries
   */
  Fulfil.address.getCountries = function() {
    return $.getJSON('{{ url_for("public.get_countries") }}');
  };

  /*
   * Helper method to fill country options in select field
   */
  Fulfil.address.fillCountriesOpts = function(selectField, currentValue) {
    selectField.html('');
    return Fulfil.address.getCountries()
      .success(function (data) {
        var optionsHtml = '';
        $.each(data.result, function(i, country){
          optionsHtml +=
            '<option value="'+ country.id +'">' + country.name + '</option>';
        });
        selectField.html(optionsHtml);

        if (currentValue) {
          $(selectField).val(currentValue).change();
        }
      });
  };

  /*
   * Return a list of all addresses of the user
   */
   Fulfil.address.getAddresses = function() {
     return $.getJSON(
       '{{ url_for("user.addresses") }}',
       {csrf_token: Fulfil.csrfToken}
     );
   };

   Fulfil.ux.notify = function(message, level, title) {
      if (!level) {
        level = 'info'
      };
      if (toastr) {
        toastr[level](message, title);
      }
   }

  /*
   *
   * User related logic
   * ==================
   *
   */

  window.Fulfil = Fulfil;
});
<commit_msg>Add js functions for creating charging card<commit_after>$(function () {
  var Fulfil = {
    csrfToken: "{{ csrf_token() }}",
    urls: {},
    form: {},
    cart: {"stripe": {}},
    user: {},
    ux: {},
    product: {},
    address: {}
  };

  // All the URLs this file needs to know
  Fulfil.urls.view_cart = "{{ url_for('cart.view_cart') }}";
  Fulfil.urls.remove_from_cart = "{{ url_for('cart.remove_from_cart') }}";
  Fulfil.urls.getVariations = "{{ url_for('products.get_variations') }}";
  Fulfil.urls.payUsingProfile = "{{ url_for('checkout.payment') }}";

  /**
   * Helper method to change formSubmission to ajax
   *
   * @param formElement HTMLElement
   * @param options Object with successCallback, errorCallback,
   *                alwaysCallback, onSubmit as keys
   */
  Fulfil.form.ajaxSubmit = function (formElement, options) {
    var form = $(formElement);

    options = options || {}

    form.on('submit', function (event) {
      event.preventDefault();

      // Call onSubmit if function
      if ($.isFunction(options.onSubmit)) {
        options.onSubmit(event);
      }

      $.ajax({
        'url': form.attr("action"),
        'type': form.attr('method') || 'GET',
        'data': form.serialize(),
        'dataType': "json"
      })
        .done(options.successCallback)
        .fail(options.errorCallback)
        .always(options.alwaysCallback);
    });
  };

  /**
   * Method to show errors in form
   */
  Fulfil.form.showErrors = function (formElement, errorsObj) {
    var form = $(formElement);

    $.each(errorsObj, function (key, value) {
      // TODO: show errors
    });
  };

  /**
   * Helper method to initialize login form
   */
  Fulfil.form.initLoginForm =  function (formElement) {
    var errorContainer = formElement.find('.error-message');

    // by default hide error container
    errorContainer.html('').hide();

    var options = {
      onSubmit: function () {
        errorContainer.html('').hide();
      },
      successCallback: function (result) {
        location.reload();
      },
      errorCallback: function (error) {
        if (error.status == 400) {
          if (!error.responseJSON.errors) {
            console.error("No 'errors' in response on bad request.");
          }

          var errors = [];
          $.each(error.responseJSON.errors, function (key, value) {
            errors = errors.concat(value);
          });

          // Show errors in error container
          errorContainer.html(errors.join(',')).show();
          return;
        }
        console.log(error.statusText);
      }
    };

    Fulfil.form.ajaxSubmit(formElement, options);
  };

  /*
   *
   * Cart related logic
   * ==================
   *
   */

   /*
    * Refreshes the cart and updates Fulfil.cart.current_cart
    * Also returns the request promise.
    *
    */
   Fulfil.cart.refresh = function() {
    console.debug("Refreshing Cart");
    return $.ajax({
      cache: false,
      url: Fulfil.urls.view_cart,
      dataType: "json",
      success: function(data){
        Fulfil.cart.current_cart = data.cart;
      }
    })
   };

   /*
    * Delete a item from the cart.
    *
    */
   Fulfil.cart.deleteItem = function(lineId) {
    console.debug("Removing Line from Cart");
    return $.ajax({
      url: Fulfil.urls.remove_from_cart,
      method: "POST",
      data: {
        "line_id": lineId,
        "csrf_token": Fulfil.csrfToken
       },
       dataType: "json",
       success: function() {
         Fulfil.cart.refresh();
       }
    });
   }

  /*
   *
   * Product related logic
   * =====================
   *
   */

  /*
   *
   * Fetch variation data for a product template
   *
   */
  Fulfil.product.getVariations = function(templateId) {
    return $.ajax({
      url: Fulfil.urls.getVariations,
      method: "GET",
      data: {
        "template": templateId
       },
       dataType: "json",
       success: function(data) {
         Fulfil.product.loadVariations(data);
       }
    });
  };

  /*
   * Load the variation data locally to serve more
   * requests.
   */
  Fulfil.product.loadVariations = function(variationData) {
    Fulfil.product.variationData = variationData;
  };

  /*
   * Given a set of attributes, return a variant
   * that fits the attributes
   *
   */
  Fulfil.product.findMatchingVariant = function(attributeSelection) {
    return _.find(Fulfil.product.variationData['variants'], function(variant) {
      return _.isEqual(variant.attributes, attributeSelection)
    });
  };

  /*
   * Return the data of the variant with id
   *
   */
  Fulfil.product.getVariant = function(variantId) {
    return _.find(Fulfil.product.variationData['variants'], function(variant) {
      return (variant.id == variantId) ;
    });
  };

  /*
   *
   * Address related logic
   * =====================
   *
   */

  /*
   * Return list of all available countries
   */
  Fulfil.address.getCountries = function() {
    return $.getJSON('{{ url_for("public.get_countries") }}');
  };

  /*
   * Helper method to fill country options in select field
   */
  Fulfil.address.fillCountriesOpts = function(selectField, currentValue) {
    selectField.html('');
    return Fulfil.address.getCountries()
      .success(function (data) {
        var optionsHtml = '';
        $.each(data.result, function(i, country){
          optionsHtml +=
            '<option value="'+ country.id +'">' + country.name + '</option>';
        });
        selectField.html(optionsHtml);

        if (currentValue) {
          $(selectField).val(currentValue).change();
        }
      });
  };

  /*
   * Return a list of all addresses of the user
   */
   Fulfil.address.getAddresses = function() {
     return $.getJSON(
       '{{ url_for("user.addresses") }}',
       {csrf_token: Fulfil.csrfToken}
     );
   };

   /*
   * Create a stripe token using card data and address
   */
   Fulfil.cart.stripe.createToken = function(card, address, callback) {
     if (typeof Stripe === 'undefined') {
       console.debug("Stripe.js is not added");
       return;
     }
     Stripe.setPublishableKey("{{ current_channel.payment_gateway.stripe_publishable_key }}");
     Stripe.card.createToken({
       'number': card.number,
       'cvc': card.cvc,
       'exp_month': card.exp_month,
       'exp_year': card.exp_year,
       'name': card.name,
       'address_zip': address.zip,
       'address_line1': address.street,
       'address_line2': address.streetbis,
       'address_city': address.city,
       'address_state': address.subdivision,
       'address_country': address.country
     }, callback);
   };

   /*
   * Pay using stripe payment profile or token
   */
   Fulfil.cart.payUsingProfile = function(profile, amount) {
    return $.ajax({
      url: Fulfil.urls.payUsingProfile,
      method: "POST",
      data: {
        "payment_profile_id": profile.payment_profile_id,
        "stripe_token": profile.stripe_token,
        "amount": amount,
        "csrf_token": Fulfil.csrfToken
       },
       dataType: "json"
    });
   };

   Fulfil.ux.notify = function(message, level, title) {
      if (!level) {
        level = 'info'
      };
      if (toastr) {
        toastr[level](message, title);
      }
   }

  /*
   *
   * User related logic
   * ==================
   *
   */

  window.Fulfil = Fulfil;
});
<|endoftext|>


<commit_before>

var Game = (function() {
    function Game(p, w, h, cs) {
        this._parent = p;
        this._canvas = p.canvas;
        this._context = p.context;

        this._cellSize = cs;
        this._width = w;
        this._height = h;

        this._grid = new Grid(this, w, h, cs);
        this._grid.add(new Snake(this, (w/2)|0, (h/2)|0, cs, Grid.Facing.LEFT));
    }

    function step() {
        this._grid.step();
    }

    function run() {
        this.step();
        this.draw();
    }

    function draw() {
        this._grid.draw();
    }

    Game.prototype = PrototypeFactory.makeApplicationObject({
        run: run,
        draw: draw,
        step: step
    });

    return Game;
}());
<commit_msg>Putting the run loop in the Game object and not the application object<commit_after>

var Game = (function() {
    function Game(p, d, g) {
        this._parent = p;
        this._canvas = p.canvas;
        this._context = p.context;

        this._display = d;

        this._grid = g;
        this._cellSize = g._cellSize;
        this._width = g._width;
        this._height = g._height;
        //this._grid = new Grid(this, w, h, cs);

    }

    Game.State = {
        NULL: 0,
        RUNNING: 1,
        WIN: 2,
        LOST: 3
    };

    function step() {
        this._display.step();
        this._grid.step();
    }

    function sub_runner() {
        switch (this._state) {
        case Game.State.NULL:
            this._parent.callEvent('error', 'Null game state');
            break;
        case Game.State.RUNNING:
            this.step();
            this.draw();
            window.setTimeout(sub_runner.bind(this), 250);
            break;
        case Game.State.WIN:
            this._parent.callEvent('game-win');
            break;
        case Game.State.LOST:
            this._parent.callEvent('game-lose');
            break;
        }
    }

    function run() {
        this._state = Game.State.RUNNING;
        this.draw();
        window.setTimeout(sub_runner.bind(this), 0);
        return this;
    }

    function draw() {
        this._display.draw();
        this._grid.draw();
    }

    Game.prototype = PrototypeFactory.makeApplicationObject({
        run: run,
        draw: draw,
        step: step
    });

    return Game;
}());
<|endoftext|>


<commit_before>exports.Cluster = require('./cluster');
exports.Bucket = require('./bucket');
exports.Scope = require('./scope');
exports.Collection = require('./collection');
exports.DesignDocument = require('./designdocument');
exports.LookupInSpec = require('./lookupinspec');
exports.MutateInSpec = require('./mutateinspec');

// Move all the enums into the package scope
var enums = require('./enums');
for (var i in enums) {
  if (enums.hasOwnProperty(i)) {
    exports[i] = enums[i];
  }
}

// Move all the errors into the package scope
var errors = require('./errors');
for (var i in errors) {
  if (errors.hasOwnProperty(i)) {
    exports[i] = errors[i];
  }
}

/**
 * @typedef {function(Error, Cluster)} ConnectCallback
 */
/**
 * Creates a new Cluster object for interacting with a Couchbase
 * cluster and performing operations.
 *
 * @param {*} connStr
 * The connection string of your cluster
 * @param {*} [options]
 * @param {number} [options.username]
 * The RBAC username to use when connecting to the cluster.
 * @param {string} [options.password]
 * The RBAC password to use when connecting to the cluster
 * @param {string} [options.clientCertificate]
 * A client certificate to use for authentication with the server.  Specifying
 * this certificate along with any other authentication method (such as username
 * and password) is an error.
 * @param {string} [options.certificateChain]
 * A certificate chain to use for validating the clusters certificates.
 * @param {ConnectCallback} [callback]
 * @returns {Promise<Cluster>}
 */
exports.connect = async function connect() {
  return await exports.Cluster.connect.apply(null, arguments);
};
<commit_msg>JSCBC-655: Fixed search query constructors not being exported.<commit_after>exports.Cluster = require('./cluster');
exports.Bucket = require('./bucket');
exports.Scope = require('./scope');
exports.Collection = require('./collection');
exports.DesignDocument = require('./designdocument');
exports.LookupInSpec = require('./lookupinspec');
exports.MutateInSpec = require('./mutateinspec');
exports.SearchQuery = require('./searchquery');
exports.SearchFacet = require('./searchfacet');
exports.SearchSort = require('./searchsort');

// Move all the enums into the package scope
var enums = require('./enums');
for (var i in enums) {
  if (enums.hasOwnProperty(i)) {
    exports[i] = enums[i];
  }
}

// Move all the errors into the package scope
var errors = require('./errors');
for (var i in errors) {
  if (errors.hasOwnProperty(i)) {
    exports[i] = errors[i];
  }
}

/**
 * @typedef {function(Error, Cluster)} ConnectCallback
 */
/**
 * Creates a new Cluster object for interacting with a Couchbase
 * cluster and performing operations.
 *
 * @param {*} connStr
 * The connection string of your cluster
 * @param {*} [options]
 * @param {number} [options.username]
 * The RBAC username to use when connecting to the cluster.
 * @param {string} [options.password]
 * The RBAC password to use when connecting to the cluster
 * @param {string} [options.clientCertificate]
 * A client certificate to use for authentication with the server.  Specifying
 * this certificate along with any other authentication method (such as username
 * and password) is an error.
 * @param {string} [options.certificateChain]
 * A certificate chain to use for validating the clusters certificates.
 * @param {ConnectCallback} [callback]
 * @returns {Promise<Cluster>}
 */
exports.connect = async function connect() {
  return await exports.Cluster.connect.apply(null, arguments);
};
<|endoftext|>


<commit_before>var util = require('util')
  , tools = require('./tools');

// Data Table query fields
var QUERY_PAGE_START = 'iDisplayStart';
var QUERY_PAGE_SIZE = 'iDisplayLength';
var QUERY_FIELD_PREFIX = 'mDataProp_';
var QUERY_SEARCHABLE_PREFIX = 'bSearchable_';
var QUERY_SORTING_COLUMNS = 'iSortingCols';
var QUERY_SORTABLE_PREFIX = 'bSortable_';
var QUERY_SORT_COLUMN_PREFIX = 'iSortCol_';
var QUERY_SORT_DIRECTION_PREFIX = 'sSortDir_';
var QUERY_SEARCH = 'sSearch';
var QUERY_SEARCH_PREFIX = 'sSearch_';
var QUERY_SEARCH_REGEXP = 'bRegex';
var QUERY_SEARCH_REGEXP_PREFIX = 'bRegex_';
var QUERY_CHUNK_SEARCH = 'bChunkSearch';

// Regexp
var FIELD_REGEXP = new RegExp("^" + QUERY_FIELD_PREFIX + "(\\d+)$");

// Data Table
var DATA_ECHO = 'sEcho';
var DATA_TOTAL_RECORDS = 'iTotalRecords';
var DATA_TOTAL_FILTERED_RECORDS = 'iTotalDisplayRecords';
var DATA_RECORDS = 'aaData';

// Find Criteria
var CRITERIA_QUERY = 'query';
var CRITERIA_LOCALE = 'locale';
var CRITERIA_PAGE_START = 'pageStart';
var CRITERIA_PAGE_SIZE = 'pageSize';
var CRITERIA_SCHEMA_FIELDS = 'schemaFields';
var CRITERIA_CONDITIONS = 'conditions';
var CRITERIA_FIELDS = 'fields';
var CRITERIA_SORT = 'sort';

// Chunk search regexp
var SEARCH_CHUNK_TMPL = "@%s:(?:(\\w+)\|\"((?:\\w\|[ ]\|\\\\\")+)\")[ ]*"
var SEARCH_CHUNK = new RegExp("@(\\w+):(?:(\\w+)\|\"((?:\\w\|[ ]\|\\\\\")+)\")[ ]*", 'g');

// Mongoose schema DataTable options
var SELECTABLE_OPTION = 'select';
var SELECTABLE_DATA_TABLE_OPTION = 'dataTableSelect';

var config = {
  conditionHandler: {
    String: buildStringCondition,
  },
  debug: false,
  verbose: false
};

module.exports.configure = function(options) {
  if ('object' == typeof options) {
    tools.extend(config, options);
  }
}

module.exports.enableVerbose = function(enabled) {
  config.verbose = enabled === true ? true : false;
}

module.exports.enableDebug = function(enabled) {
  config.debug = enabled === true ? true : false;
}

module.exports.init = function(schema, options) {
  schema.statics.dataTable = dataTable;
}

function dataTable(query, locale, callback) {
  debug("Query:", query);
  var self = this;
  if ('function' == typeof locale) {
    callback = locale;
    locale = undefined;
  }
  if ('function' != typeof callback) throw new Error("Missing callback !");
  if ('object'!= typeof query) return callback(new Error("Invalid query !"));
  var criteria = buildCriteria(query, locale);
  var data = buildData(query);
  countAllRecords.call(self, criteria, data, function(err, criteria, data) {
    if (err) return callback(err);
    countFilteredRecords.call(self, criteria, data, function(err, criteria, data) {
      if (err) return callback(err);
      retrieveData.call(self, criteria, data, function(err, criteria, data) {
        if (err) return callback(err);
        callback(null, data);
      });
    });
  });
}

function buildCriteria(query, locale) {
  var criteria = {};
  criteria[CRITERIA_QUERY] = query;
  criteria[CRITERIA_LOCALE] = locale;
  return criteria;
}

function buildData(query) {
  var data = {};
  data[DATA_ECHO] = query[DATA_ECHO];
  return data;
}

function countAllRecords(criteria, data, callback) {
  this.count(function(err, countAll) {
    if (err) return callback(err);
    data[DATA_TOTAL_RECORDS] = countAll;
    return callback(null, criteria, data);
  });
}

function countFilteredRecords(criteria, data, callback) {
  var query = criteria[CRITERIA_QUERY];
  var locale = criteria[CRITERIA_LOCALE];
  var schemaFields = criteria[CRITERIA_SCHEMA_FIELDS] =
    getSchemaFields(this.schema, query);
  debug("Schema fields:", schemaFields);
  var conditions = criteria[CRITERIA_CONDITIONS] =
    getConditions(locale, query, schemaFields);
  debug("Conditions:", conditions);
  this.count(conditions, function(err, countFiltered) {
    if (err) return callback(err);
    data[DATA_TOTAL_FILTERED_RECORDS] = countFiltered;
    return callback(null, criteria, data);
  });
}

function retrieveData(criteria, data, callback) {
  var schemaFields = criteria[CRITERIA_SCHEMA_FIELDS];
  var fields = criteria[CRITERIA_FIELDS] = getFields(schemaFields);
  debug("Fields:", fields);
  var query = criteria[CRITERIA_QUERY];
  var sort = criteria[CRITERIA_SORT] = getSort(query, schemaFields);
  debug("Sort:", sort);
  var conditions = criteria[CRITERIA_CONDITIONS];
  var pageStart = criteria[CRITERIA_QUERY][QUERY_PAGE_START];
  var pageSize = criteria[CRITERIA_QUERY][QUERY_PAGE_SIZE];
  this.find(conditions, fields).skip(pageStart).limit(pageSize).sort(sort)
    .exec(function(err, values) {
      if (err) return callback(err);
      data[DATA_RECORDS] = values;
      callback(null, criteria, data);
    });
}

function getSchemaFields(schema, query) {
  var fields = [];
  var field;
  for (key in query)
    if (FIELD_REGEXP.test(key) && query[key]) {
      field = schema.path(query[key]);
      if (isSelectable(field)) fields[RegExp.$1] = field;
    }
  return fields;
}

function isSelectable(field) {
  if ((field.options[SELECTABLE_OPTION] == undefined ||
        field.options[SELECTABLE_OPTION] === true) &&
      (field.options[SELECTABLE_DATA_TABLE_OPTION] == undefined ||
       field.options[SELECTABLE_DATA_TABLE_OPTION] === true))
    return true;
  return false;
}

function getFields(schemaFields) {
  var fields = "";
  for(var index = 0; index < schemaFields.length; ++index) {
    if (schemaFields[index]) fields += schemaFields[index].path + ' ';
  }
  return fields;
}

function getSort(query, schemaFields) {
  var sort = {};
  var nbSortingCols = parseInt(query[QUERY_SORTING_COLUMNS]);
  for (var index = 0; index < nbSortingCols; ++index) {
    var indice = query[QUERY_SORT_COLUMN_PREFIX + index];
    if (query[QUERY_SORTABLE_PREFIX + indice] == 'true') {
      sort[schemaFields[indice].path] =
        query[QUERY_SORT_DIRECTION_PREFIX + index];
    }
  }
  return sort;
}

function getConditions(locale, query, schemaFields) {
  var conditions = {};
  var chunckSearch;
  var search;
  if (query[QUERY_CHUNK_SEARCH] == 'true') {
    chunckSearch = query[QUERY_SEARCH] || '';
    search = chunckSearch.replace(SEARCH_CHUNK, '');
  } else search = query[QUERY_SEARCH] || '';
  var disj;
  if (search.length > 0) disj = [];
  for(var index = 0; index < schemaFields.length; ++index) {
    if (schemaFields[index] && isSearchable(query, index)) {
      if (chunckSearch && chunckSearch.length > 0) {
        addSearchChunkCondition(locale, conditions, chunckSearch,
            isRegexp(query), schemaFields[index]);
      }
      if (query[QUERY_SEARCH_PREFIX + index]) {
        addCondition(locale, conditions, query[QUERY_SEARCH_PREFIX + index],
            isRegexp(query, index), schemaFields[index]);
      }
      if (disj) {
        addDisjunctionCondition(locale, disj, search,
            isRegexp(query), schemaFields[index]);
      }
    }
  }
  if (disj && disj.length > 0) conditions['$or'] = disj;
  return conditions;
}

function isSearchable(query, index) {
  if (query[QUERY_SEARCHABLE_PREFIX + index] == 'true') return true;
  return false;
}

function isRegexp(query, index) {
  if (index && query[QUERY_SEARCH_REGEXP_PREFIX + index] == 'true') return true;
  if (!index && query[QUERY_SEARCH_REGEXP] == 'true') return true;
  return false;
}

function addSearchChunkCondition(locale, conditions, search, regexp, field) {
  var searchChunk = new RegExp(util.format(SEARCH_CHUNK_TMPL, field.path), 'g');
  var captures;
  while ((captures = searchChunk.exec(search))) {
    var search = captures[1] || captures[2];
    var condition = buildCondition(locale, field, search, regexp);
    if (condition != undefined) conditions[field.path] = condition;
  }
}

function addCondition(locale, conditions, search, regexp, field) {
  var condition = buildCondition(locale, field, search, regexp);
  if (condition != undefined) conditions[field.path] = condition;
}

function addDisjunctionCondition(locale, disj, search, regexp, field) {
  var condition = buildCondition(locale, field, search, regexp);
  if (condition != undefined) {
    var disjCondition = {};
    disjCondition[field.path] = condition;
    disj.push(disjCondition);
  }
}

function buildCondition(locale, field, search, regexp) {
  var handlers = config.conditionHandler;
  if (!handlers || 'object' != typeof handlers)
    return buildUnknownCondition(field);
  var handler = handlers[field.options.type.name] ||
    handlers.default;
  if (!handler || 'function' != typeof handler) {
    return buildUnknownCondition(field);
  }
  return handler(locale, field, search, regexp);
}

function buildStringCondition(locale, field, search, regexp) {
  if (regexp) return new RegExp(search);
  return new RegExp(search, 'i');
}

function buildUnknownCondition(field) {
  verbose("Unmanaged field condition type:", field.options.type.name);
}

function debug() {
  if (config.debug === true) {
    console.log.apply(console, arguments);
  }
}

function verbose() {
  if (config.verbose === true) {
    console.log.apply(console, arguments);
  }
}
<commit_msg>Undefined field<commit_after>var util = require('util')
  , tools = require('./tools');

// Data Table query fields
var QUERY_PAGE_START = 'iDisplayStart';
var QUERY_PAGE_SIZE = 'iDisplayLength';
var QUERY_FIELD_PREFIX = 'mDataProp_';
var QUERY_SEARCHABLE_PREFIX = 'bSearchable_';
var QUERY_SORTING_COLUMNS = 'iSortingCols';
var QUERY_SORTABLE_PREFIX = 'bSortable_';
var QUERY_SORT_COLUMN_PREFIX = 'iSortCol_';
var QUERY_SORT_DIRECTION_PREFIX = 'sSortDir_';
var QUERY_SEARCH = 'sSearch';
var QUERY_SEARCH_PREFIX = 'sSearch_';
var QUERY_SEARCH_REGEXP = 'bRegex';
var QUERY_SEARCH_REGEXP_PREFIX = 'bRegex_';
var QUERY_CHUNK_SEARCH = 'bChunkSearch';

// Regexp
var FIELD_REGEXP = new RegExp("^" + QUERY_FIELD_PREFIX + "(\\d+)$");

// Data Table
var DATA_ECHO = 'sEcho';
var DATA_TOTAL_RECORDS = 'iTotalRecords';
var DATA_TOTAL_FILTERED_RECORDS = 'iTotalDisplayRecords';
var DATA_RECORDS = 'aaData';

// Find Criteria
var CRITERIA_QUERY = 'query';
var CRITERIA_LOCALE = 'locale';
var CRITERIA_PAGE_START = 'pageStart';
var CRITERIA_PAGE_SIZE = 'pageSize';
var CRITERIA_SCHEMA_FIELDS = 'schemaFields';
var CRITERIA_CONDITIONS = 'conditions';
var CRITERIA_FIELDS = 'fields';
var CRITERIA_SORT = 'sort';

// Chunk search regexp
var SEARCH_CHUNK_TMPL = "@%s:(?:(\\w+)\|\"((?:\\w\|[ ]\|\\\\\")+)\")[ ]*"
var SEARCH_CHUNK = new RegExp("@(\\w+):(?:(\\w+)\|\"((?:\\w\|[ ]\|\\\\\")+)\")[ ]*", 'g');

// Mongoose schema DataTable options
var SELECTABLE_OPTION = 'select';
var SELECTABLE_DATA_TABLE_OPTION = 'dataTableSelect';

var config = {
  conditionHandler: {
    String: buildStringCondition,
  },
  debug: false,
  verbose: false
};

module.exports.configure = function(options) {
  if ('object' == typeof options) {
    tools.extend(config, options);
  }
}

module.exports.enableVerbose = function(enabled) {
  config.verbose = enabled === true ? true : false;
}

module.exports.enableDebug = function(enabled) {
  config.debug = enabled === true ? true : false;
}

module.exports.init = function(schema, options) {
  schema.statics.dataTable = dataTable;
}

function dataTable(query, locale, callback) {
  debug("Query:", query);
  var self = this;
  if ('function' == typeof locale) {
    callback = locale;
    locale = undefined;
  }
  if ('function' != typeof callback) throw new Error("Missing callback !");
  if ('object'!= typeof query) return callback(new Error("Invalid query !"));
  var criteria = buildCriteria(query, locale);
  var data = buildData(query);
  countAllRecords.call(self, criteria, data, function(err, criteria, data) {
    if (err) return callback(err);
    countFilteredRecords.call(self, criteria, data, function(err, criteria, data) {
      if (err) return callback(err);
      retrieveData.call(self, criteria, data, function(err, criteria, data) {
        if (err) return callback(err);
        callback(null, data);
      });
    });
  });
}

function buildCriteria(query, locale) {
  var criteria = {};
  criteria[CRITERIA_QUERY] = query;
  criteria[CRITERIA_LOCALE] = locale;
  return criteria;
}

function buildData(query) {
  var data = {};
  data[DATA_ECHO] = query[DATA_ECHO];
  return data;
}

function countAllRecords(criteria, data, callback) {
  this.count(function(err, countAll) {
    if (err) return callback(err);
    data[DATA_TOTAL_RECORDS] = countAll;
    return callback(null, criteria, data);
  });
}

function countFilteredRecords(criteria, data, callback) {
  var query = criteria[CRITERIA_QUERY];
  var locale = criteria[CRITERIA_LOCALE];
  var schemaFields = criteria[CRITERIA_SCHEMA_FIELDS] =
    getSchemaFields(this.schema, query);
  debug("Schema fields:", schemaFields);
  var conditions = criteria[CRITERIA_CONDITIONS] =
    getConditions(locale, query, schemaFields);
  debug("Conditions:", conditions);
  this.count(conditions, function(err, countFiltered) {
    if (err) return callback(err);
    data[DATA_TOTAL_FILTERED_RECORDS] = countFiltered;
    return callback(null, criteria, data);
  });
}

function retrieveData(criteria, data, callback) {
  var schemaFields = criteria[CRITERIA_SCHEMA_FIELDS];
  var fields = criteria[CRITERIA_FIELDS] = getFields(schemaFields);
  debug("Fields:", fields);
  var query = criteria[CRITERIA_QUERY];
  var sort = criteria[CRITERIA_SORT] = getSort(query, schemaFields);
  debug("Sort:", sort);
  var conditions = criteria[CRITERIA_CONDITIONS];
  var pageStart = criteria[CRITERIA_QUERY][QUERY_PAGE_START];
  var pageSize = criteria[CRITERIA_QUERY][QUERY_PAGE_SIZE];
  this.find(conditions, fields).skip(pageStart).limit(pageSize).sort(sort)
    .exec(function(err, values) {
      if (err) return callback(err);
      data[DATA_RECORDS] = values;
      callback(null, criteria, data);
    });
}

function getSchemaFields(schema, query) {
  var fields = [];
  var field;
  for (key in query)
    if (FIELD_REGEXP.test(key) && query[key]) {
      field = schema.path(query[key]);
      if (field && isSelectable(field)) fields[RegExp.$1] = field;
    }
  return fields;
}

function isSelectable(field) {
  if ((field.options[SELECTABLE_OPTION] == undefined ||
        field.options[SELECTABLE_OPTION] === true) &&
      (field.options[SELECTABLE_DATA_TABLE_OPTION] == undefined ||
       field.options[SELECTABLE_DATA_TABLE_OPTION] === true))
    return true;
  return false;
}

function getFields(schemaFields) {
  var fields = "";
  for(var index = 0; index < schemaFields.length; ++index) {
    if (schemaFields[index]) fields += schemaFields[index].path + ' ';
  }
  return fields;
}

function getSort(query, schemaFields) {
  var sort = {};
  var nbSortingCols = parseInt(query[QUERY_SORTING_COLUMNS]);
  for (var index = 0; index < nbSortingCols; ++index) {
    var indice = query[QUERY_SORT_COLUMN_PREFIX + index];
    if (query[QUERY_SORTABLE_PREFIX + indice] == 'true') {
      sort[schemaFields[indice].path] =
        query[QUERY_SORT_DIRECTION_PREFIX + index];
    }
  }
  return sort;
}

function getConditions(locale, query, schemaFields) {
  var conditions = {};
  var chunckSearch;
  var search;
  if (query[QUERY_CHUNK_SEARCH] == 'true') {
    chunckSearch = query[QUERY_SEARCH] || '';
    search = chunckSearch.replace(SEARCH_CHUNK, '');
  } else search = query[QUERY_SEARCH] || '';
  var disj;
  if (search.length > 0) disj = [];
  for(var index = 0; index < schemaFields.length; ++index) {
    if (schemaFields[index] && isSearchable(query, index)) {
      if (chunckSearch && chunckSearch.length > 0) {
        addSearchChunkCondition(locale, conditions, chunckSearch,
            isRegexp(query), schemaFields[index]);
      }
      if (query[QUERY_SEARCH_PREFIX + index]) {
        addCondition(locale, conditions, query[QUERY_SEARCH_PREFIX + index],
            isRegexp(query, index), schemaFields[index]);
      }
      if (disj) {
        addDisjunctionCondition(locale, disj, search,
            isRegexp(query), schemaFields[index]);
      }
    }
  }
  if (disj && disj.length > 0) conditions['$or'] = disj;
  return conditions;
}

function isSearchable(query, index) {
  if (query[QUERY_SEARCHABLE_PREFIX + index] == 'true') return true;
  return false;
}

function isRegexp(query, index) {
  if (index && query[QUERY_SEARCH_REGEXP_PREFIX + index] == 'true') return true;
  if (!index && query[QUERY_SEARCH_REGEXP] == 'true') return true;
  return false;
}

function addSearchChunkCondition(locale, conditions, search, regexp, field) {
  var searchChunk = new RegExp(util.format(SEARCH_CHUNK_TMPL, field.path), 'g');
  var captures;
  while ((captures = searchChunk.exec(search))) {
    var search = captures[1] || captures[2];
    var condition = buildCondition(locale, field, search, regexp);
    if (condition != undefined) conditions[field.path] = condition;
  }
}

function addCondition(locale, conditions, search, regexp, field) {
  var condition = buildCondition(locale, field, search, regexp);
  if (condition != undefined) conditions[field.path] = condition;
}

function addDisjunctionCondition(locale, disj, search, regexp, field) {
  var condition = buildCondition(locale, field, search, regexp);
  if (condition != undefined) {
    var disjCondition = {};
    disjCondition[field.path] = condition;
    disj.push(disjCondition);
  }
}

function buildCondition(locale, field, search, regexp) {
  var handlers = config.conditionHandler;
  if (!handlers || 'object' != typeof handlers)
    return buildUnknownCondition(field);
  var handler = handlers[field.options.type.name] ||
    handlers.default;
  if (!handler || 'function' != typeof handler) {
    return buildUnknownCondition(field);
  }
  return handler(locale, field, search, regexp);
}

function buildStringCondition(locale, field, search, regexp) {
  if (regexp) return new RegExp(search);
  return new RegExp(search, 'i');
}

function buildUnknownCondition(field) {
  verbose("Unmanaged field condition type:", field.options.type.name);
}

function debug() {
  if (config.debug === true) {
    console.log.apply(console, arguments);
  }
}

function verbose() {
  if (config.verbose === true) {
    console.log.apply(console, arguments);
  }
}
<|endoftext|>


<commit_before>let AutomaticComponent = require('./AutomaticComponent');

class Notifications extends AutomaticComponent {
    /**
     * webpack plugins to be appended to the master config.
     */
    webpackPlugins() {
        if (Mix.isUsing('notifications')) {
            let WebpackNotifierPlugin = require('webpack-notifier');

            return new WebpackNotifierPlugin({
                title: 'Laravel Mix',
                alwaysNotify: Config.notifications.onSuccess,
                hint:
                    process.platform === 'linux'
                        ? 'int:transient:1'
                        : undefined,
		timeout: 2,
                contentImage: Mix.paths.root(
                    'node_modules/laravel-mix/icons/laravel.png'
                )
            });
        }
    }
}

module.exports = Notifications;
<commit_msg>Remove notification timeout, fixes #2161 (#2179)<commit_after>let AutomaticComponent = require('./AutomaticComponent');

class Notifications extends AutomaticComponent {
    /**
     * webpack plugins to be appended to the master config.
     */
    webpackPlugins() {
        if (Mix.isUsing('notifications')) {
            let WebpackNotifierPlugin = require('webpack-notifier');

            return new WebpackNotifierPlugin({
                title: 'Laravel Mix',
                alwaysNotify: Config.notifications.onSuccess,
                hint:
                    process.platform === 'linux'
                        ? 'int:transient:1'
                        : undefined,
                contentImage: Mix.paths.root(
                    'node_modules/laravel-mix/icons/laravel.png'
                )
            });
        }
    }
}

module.exports = Notifications;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import styles from './Search.less'
import { Input, Select, Button, Icon } from 'antd'

class Search extends React.Component {
  state = {
    clearVisible: false,
    selectValue: (this.props.select && this.props.selectProps) ? this.props.selectProps.defaultValue : '',
  }
  handleSearch = () => {
    const data = {
      keyword: ReactDOM.findDOMNode(this.refs.searchInput).value,
    }
    if (this.props.select) {
      data.field = this.state.selectValue
    }
    if (this.props.onSearch) this.props.onSearch(data)
  }
  handleInputChange = e => {
    this.setState({
      ...this.state,
      clearVisible: e.target.value !== '',
    })
  }
  handeleSelectChange = value => {
    this.setState({
      ...this.state,
      selectValue: value,
    })
  }
  handleClearInput = () => {
    ReactDOM.findDOMNode(this.refs.searchInput).value = ''
    this.setState({
      clearVisible: false,
    })
    this.handleSearch()
  }
  render () {
    const { size, select, selectOptions, selectProps, style, keyword } = this.props
    const { clearVisible } = this.state
    return (
      <Input.Group compact size={size} className={styles.search} style={style}>
        {select && <Select ref="searchSelect" onChange={this.handeleSelectChange} size={size} {...selectProps}>
          {selectOptions && selectOptions.map((item, key) => <Select.Option value={item.value} key={key}>{item.name || item.value}</Select.Option>)}
        </Select>}
        <Input ref="searchInput" size={size} onChange={this.handleInputChange} onPressEnter={this.handleSearch} defaultValue={keyword} />
        <Button size={size} type="primary" onClick={this.handleSearch}>搜索</Button>
        {clearVisible && <Icon type="cross" onClick={this.handleClearInput} />}
      </Input.Group>
    )
  }
}

Search.propTypes = {
  size: PropTypes.string,
  select: PropTypes.bool,
  selectProps: PropTypes.object,
  onSearch: PropTypes.func,
  selectOptions: PropTypes.array,
  style: PropTypes.object,
  keyword: PropTypes.string,
}

export default Search
<commit_msg>Search.js has a mistake var name<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import styles from './Search.less'
import { Input, Select, Button, Icon } from 'antd'

class Search extends React.Component {
  state = {
    clearVisible: false,
    selectValue: (this.props.select && this.props.selectProps) ? this.props.selectProps.defaultValue : '',
  }
  handleSearch = () => {
    const data = {
      keyword: ReactDOM.findDOMNode(this.refs.searchInput).value,
    }
    if (this.props.select) {
      data.field = this.state.selectValue
    }
    if (this.props.onSearch) this.props.onSearch(data)
  }
  handleInputChange = e => {
    this.setState({
      ...this.state,
      clearVisible: e.target.value !== '',
    })
  }
  handleSelectChange = value => {
    this.setState({
      ...this.state,
      selectValue: value,
    })
  }
  handleClearInput = () => {
    ReactDOM.findDOMNode(this.refs.searchInput).value = ''
    this.setState({
      clearVisible: false,
    })
    this.handleSearch()
  }
  render () {
    const { size, select, selectOptions, selectProps, style, keyword } = this.props
    const { clearVisible } = this.state
    return (
      <Input.Group compact size={size} className={styles.search} style={style}>
        {select && <Select ref="searchSelect" onChange={this.handleSelectChange} size={size} {...selectProps}>
          {selectOptions && selectOptions.map((item, key) => <Select.Option value={item.value} key={key}>{item.name || item.value}</Select.Option>)}
        </Select>}
        <Input ref="searchInput" size={size} onChange={this.handleInputChange} onPressEnter={this.handleSearch} defaultValue={keyword} />
        <Button size={size} type="primary" onClick={this.handleSearch}>搜索</Button>
        {clearVisible && <Icon type="cross" onClick={this.handleClearInput} />}
      </Input.Group>
    )
  }
}

Search.propTypes = {
  size: PropTypes.string,
  select: PropTypes.bool,
  selectProps: PropTypes.object,
  onSearch: PropTypes.func,
  selectOptions: PropTypes.array,
  style: PropTypes.object,
  keyword: PropTypes.string,
}

export default Search
<|endoftext|>


<commit_before>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import { TypingText } from '../Intro'
import {MobileHide} from '../MobileHide'
import Footer from '../Footer'

const Sidebar = ({ className, color, bgColor }) => (

    <LogoContainer>
      <Link to="/">
        <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
      </Link>
    </LogoContainer>

    <MobileHide>

    </MobileHide>

)

const LogoContainer = styled.div`
  @media(min-width: 560px){
    text-align: center;
    position: fixed;
    width: 15.5%;
    min-width: 250px;
    max-width: 320px;
  }
`;

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  height: 100%;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  p {
    color: ${props => props.color ? props.color : '#000000'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<commit_msg>changed logo width<commit_after>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import { TypingText } from '../Intro'
import {MobileHide} from '../MobileHide'
import Footer from '../Footer'

const Sidebar = ({ className, color, bgColor }) => (

    <LogoContainer>
      <Link to="/">
        <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
      </Link>
    </LogoContainer>

    <MobileHide>

    </MobileHide>

)

const LogoContainer = styled.div`
  @media(min-width: 560px){
    text-align: center;
    position: fixed;
    width: 17%;
    min-width: 250px;
    max-width: 320px;
  }
`;

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  height: 100%;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  p {
    color: ${props => props.color ? props.color : '#000000'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import { tabTitleComponents, entitySets } from '../../lib/configuration.js'
import style from './Tabs.scss'

class TabTitle extends Component {
  constructor (props) {
    super(props)
    this.setNode = this.setNode.bind(this)
    this.handleChromeAuxClick = this.handleChromeAuxClick.bind(this)
  }

  componentDidMount () {
    // workaround for chrome not handling middle click on normal "onClick" listener
    const isChrome = !!window.chrome

    if (isChrome && this.node) {
      this.node.addEventListener('auxclick', this.handleChromeAuxClick)
    }
  }

  componentWillUnmount () {
    // workaround for chrome not handling middle click on normal "onClick" listener
    const isChrome = !!window.chrome && !!window.chrome.webstore

    if (isChrome && this.node) {
      this.node.removeEventListener('auxclick', this.handleChromeAuxClick)
    }
  }

  setNode (el) {
    this.node = el
  }

  handleChromeAuxClick (e) {
    if (e.which === 2) {
      return this.props.onClick(e, this.props.tab)
    }
  }

  render () {
    const { tab, active, contextMenu, complementTitle, resolveEntityPath, onClick, onContextMenu, onClose } = this.props
    let tabTooltip

    if (tab.entity) {
      tabTooltip = resolveEntityPath(tab.entity, { parents: true, self: false })
    }

    return (

 onClick(e, tab)}
        onContextMenu={(e) => onContextMenu(e, tab)}
      >

          {tab.tab.titleComponentKey ? (
            React.createElement(tabTitleComponents[tab.tab.titleComponentKey], {
              entity: tab.entity,
              complementTitle,
              tab: tab.tab
            })
          ) : (
            [
              {tab.tab.title || (tab.entity[entitySets[tab.entity.__entitySet].nameAttribute] + (tab.entity.__isDirty ? '*' : ''))},
              (complementTitle != null && (
                 {`- ${complementTitle}`}
              ))
            ]
          )}

 { e.stopPropagation(); onClose(tab.tab.key) }}>

        {contextMenu != null ? contextMenu :
}

    )
  }
}

export default TabTitle
<commit_msg>fix react key warning<commit_after>import React, {Component} from 'react'
import { tabTitleComponents, entitySets } from '../../lib/configuration.js'
import style from './Tabs.scss'

class TabTitle extends Component {
  constructor (props) {
    super(props)
    this.setNode = this.setNode.bind(this)
    this.handleChromeAuxClick = this.handleChromeAuxClick.bind(this)
  }

  componentDidMount () {
    // workaround for chrome not handling middle click on normal "onClick" listener
    const isChrome = !!window.chrome

    if (isChrome && this.node) {
      this.node.addEventListener('auxclick', this.handleChromeAuxClick)
    }
  }

  componentWillUnmount () {
    // workaround for chrome not handling middle click on normal "onClick" listener
    const isChrome = !!window.chrome && !!window.chrome.webstore

    if (isChrome && this.node) {
      this.node.removeEventListener('auxclick', this.handleChromeAuxClick)
    }
  }

  setNode (el) {
    this.node = el
  }

  handleChromeAuxClick (e) {
    if (e.which === 2) {
      return this.props.onClick(e, this.props.tab)
    }
  }

  render () {
    const { tab, active, contextMenu, complementTitle, resolveEntityPath, onClick, onContextMenu, onClose } = this.props
    let tabTooltip

    if (tab.entity) {
      tabTooltip = resolveEntityPath(tab.entity, { parents: true, self: false })
    }

    return (

 onClick(e, tab)}
        onContextMenu={(e) => onContextMenu(e, tab)}
      >

          {tab.tab.titleComponentKey ? (
            React.createElement(tabTitleComponents[tab.tab.titleComponentKey], {
              entity: tab.entity,
              complementTitle,
              tab: tab.tab
            })
          ) : (
            [
              {tab.tab.title || (tab.entity[entitySets[tab.entity.__entitySet].nameAttribute] + (tab.entity.__isDirty ? '*' : ''))},
              (complementTitle != null && (
                 {`- ${complementTitle}`}
              ))
            ]
          )}

 { e.stopPropagation(); onClose(tab.tab.key) }}>

        {contextMenu != null ? contextMenu :
}

    )
  }
}

export default TabTitle
<|endoftext|>


<commit_before>var fs = require("fs");

function DummyApiError(msg) {
    var self = this;

    self.toString = function () {
        return "<DummyApiError " + self.msg + ">";
    };
}

function DummyApi() {
    var self = this;

    // test hooks

    self.reset = function() {
        self.kv_store = {};
        self.config_store = {};
        self.metrics = {};
        self.http_get = {};
        self.http_post = {};
        self.outbound_sends = [];
        self.logs = [];
        self.request_calls = [];
        self.waiting_replies = [];
        self.done_calls = 0;
    };
    self.reset();

    self.add_reply = function(reply) {
        self.waiting_replies.push(reply);
    };

    self.load_http_fixture = function(filename) {
        var data = fs.readFileSync(filename);
        var fixture = JSON.parse(data);
        self.add_http_fixture(fixture);
    };

    self._http_post_key = function(url, data) {
        try {
            var json = JSON.parse(data);
            var keys = Object.keys(json).sort();
            var frags = keys.map(function (k) {
                return '"' + k + '":' + JSON.stringify(json[k]);
            });
            data = "{" + frags.join(",") + "}";
        }
        catch (e) {}
        return url + "|" + data;
    };

    self.add_http_fixture = function(fixture) {
        if (fixture.method == "POST") {
            var key = self._http_post_key(fixture.url,
                                          JSON.stringify(fixture.data));
            self.http_post[key] = JSON.stringify(fixture.body);
        }
        else {
            self.http_get[fixture.url] = JSON.stringify(fixture.body);
        }
    };

    self._dispatch_command = function(cmd, reply) {
        var handler_name = ("_handle_" +
                            cmd.cmd.replace('.', '_').replace('-', '_'));
        var handler = self[handler_name];
        if (!handler) {
            throw new DummyApiError("Unknown command " + cmd.cmd);
        }
        if (handler) {
            handler.call(self, cmd, reply);
        }
    };

    self._populate_reply = function(orig_cmd, reply) {
        reply.cmd = orig_cmd.cmd;
        return reply;
    };

    self._handle_kv_get = function(cmd, reply) {
        var value = self.kv_store[cmd.key];
        reply(self._populate_reply(cmd, {
            success: true,
            value: value
        }));
    };

    self._handle_kv_set = function(cmd, reply) {
        self.kv_store[cmd.key] = cmd.value;
        reply(self._populate_reply(cmd, {
            success: true
        }));
    };

    self._handle_config_get = function(cmd, reply) {
        var value = self.config_store[cmd.key];
        reply(self._populate_reply(cmd, {
            success: true,
            value: value
        }));
    };

    self._record_metric = function (store_name, metric_name, value, agg) {
        var store = self.metrics[store_name];
        if (typeof store == 'undefined') {
            self.metrics[store_name] = store = {};
        }
        var metric = store[metric_name];
        if (typeof metric == 'undefined') {
            store[metric_name] = metric = {'agg': agg};
        }
        if (metric.agg != agg) return false;
        metric[metric.length] = value;
        return true;
    };

    self._handle_metrics_fire = function(cmd, reply) {
        var success = self._record_metric(cmd.store, cmd.metric, cmd.value,
                                          cmd.agg);
        reply(self._populate_reply(cmd, {
            success: success
        }));
    };

    self._handle_http_method = function(method, key, cmd, reply) {
        var store = (method == "POST") ? self.http_post : self.http_get;
        var reply_data = {};
        var data = store[key];
        if (typeof data != 'undefined') {
            reply_data.success = true;
            reply_data.body = data;
            reply_data.code = 200;
        }
        else {
            reply_data.success = false;
            reply_data.reason = method + " from unknown key: " + key;
            console.log(reply_data.reason);
        }
        reply(self._populate_reply(cmd, reply_data));
    };

    self._handle_http_get = function(cmd, reply) {
        self._handle_http_method("GET", cmd.url, cmd, reply);
    };

    self._handle_http_post = function(cmd, reply) {
        var key = self._http_post_key(cmd.url, cmd.data);
        self._handle_http_method("POST", key, cmd, reply);
    };

    self._handle_outbound_reply_to = function(cmd, reply) {
         self.request_calls.push(cmd);
         reply(self.waiting_replies.shift());
    };

    self._handle_outbound_send_to_tag = function(cmd, reply) {
        self.outbound_sends.push(cmd);
        reply(self._populate_reply(cmd, {success: true}));
    };

    // original api

    self.populate_command = function(cmd_name, cmd) {
        cmd.cmd = cmd_name;
        return cmd;
    };

    self.request = function(cmd_name, cmd_data, reply) {
        var cmd = self.populate_command(cmd_name, cmd_data);
        self._dispatch_command(cmd, reply);
    };

    self.log_info = function(msg) {
        self.logs.push(msg);
    };

    self.done = function() {
        self.done_calls += 1;
    };
}

// exports
this.DummyApi = DummyApi;
<commit_msg>Add support for kv.incr in dummy api.<commit_after>var fs = require("fs");

function DummyApiError(msg) {
    var self = this;

    self.toString = function () {
        return "<DummyApiError " + self.msg + ">";
    };
}

function DummyApi() {
    var self = this;

    // test hooks

    self.reset = function() {
        self.kv_store = {};
        self.config_store = {};
        self.metrics = {};
        self.http_get = {};
        self.http_post = {};
        self.outbound_sends = [];
        self.logs = [];
        self.request_calls = [];
        self.waiting_replies = [];
        self.done_calls = 0;
    };
    self.reset();

    self.add_reply = function(reply) {
        self.waiting_replies.push(reply);
    };

    self.load_http_fixture = function(filename) {
        var data = fs.readFileSync(filename);
        var fixture = JSON.parse(data);
        self.add_http_fixture(fixture);
    };

    self._http_post_key = function(url, data) {
        try {
            var json = JSON.parse(data);
            var keys = Object.keys(json).sort();
            var frags = keys.map(function (k) {
                return '"' + k + '":' + JSON.stringify(json[k]);
            });
            data = "{" + frags.join(",") + "}";
        }
        catch (e) {}
        return url + "|" + data;
    };

    self.add_http_fixture = function(fixture) {
        if (fixture.method == "POST") {
            var key = self._http_post_key(fixture.url,
                                          JSON.stringify(fixture.data));
            self.http_post[key] = JSON.stringify(fixture.body);
        }
        else {
            self.http_get[fixture.url] = JSON.stringify(fixture.body);
        }
    };

    self._dispatch_command = function(cmd, reply) {
        var handler_name = ("_handle_" +
                            cmd.cmd.replace('.', '_').replace('-', '_'));
        var handler = self[handler_name];
        if (!handler) {
            throw new DummyApiError("Unknown command " + cmd.cmd);
        }
        if (handler) {
            handler.call(self, cmd, reply);
        }
    };

    self._populate_reply = function(orig_cmd, reply) {
        reply.cmd = orig_cmd.cmd;
        return reply;
    };

    self._handle_kv_get = function(cmd, reply) {
        var value = self.kv_store[cmd.key];
        reply(self._populate_reply(cmd, {
            success: true,
            value: value
        }));
    };

    self._handle_kv_set = function(cmd, reply) {
        self.kv_store[cmd.key] = cmd.value;
        reply(self._populate_reply(cmd, {
            success: true
        }));
    };

    self._handle_kv_incr = function(cmd, reply) {
        var orig_value = self.kv_store[cmd.key];
        orig_value = (typeof orig_value == 'undefined') ? 0 : orig_value;
        orig_value = Number(orig_value);
        var amount = cmd.amount;
        amount = (typeof amount == 'undefied') ? 1 : amount;
        self.kv_store[cmd.key] = orig_value + amount;
        reply(self._populate_reply(cmd, {
            success: true,
            value: self.kv_store[cmd.key]
        }));
    };

    self._handle_config_get = function(cmd, reply) {
        var value = self.config_store[cmd.key];
        reply(self._populate_reply(cmd, {
            success: true,
            value: value
        }));
    };

    self._record_metric = function (store_name, metric_name, value, agg) {
        var store = self.metrics[store_name];
        if (typeof store == 'undefined') {
            self.metrics[store_name] = store = {};
        }
        var metric = store[metric_name];
        if (typeof metric == 'undefined') {
            store[metric_name] = metric = {'agg': agg};
        }
        if (metric.agg != agg) return false;
        metric[metric.length] = value;
        return true;
    };

    self._handle_metrics_fire = function(cmd, reply) {
        var success = self._record_metric(cmd.store, cmd.metric, cmd.value,
                                          cmd.agg);
        reply(self._populate_reply(cmd, {
            success: success
        }));
    };

    self._handle_http_method = function(method, key, cmd, reply) {
        var store = (method == "POST") ? self.http_post : self.http_get;
        var reply_data = {};
        var data = store[key];
        if (typeof data != 'undefined') {
            reply_data.success = true;
            reply_data.body = data;
            reply_data.code = 200;
        }
        else {
            reply_data.success = false;
            reply_data.reason = method + " from unknown key: " + key;
            console.log(reply_data.reason);
        }
        reply(self._populate_reply(cmd, reply_data));
    };

    self._handle_http_get = function(cmd, reply) {
        self._handle_http_method("GET", cmd.url, cmd, reply);
    };

    self._handle_http_post = function(cmd, reply) {
        var key = self._http_post_key(cmd.url, cmd.data);
        self._handle_http_method("POST", key, cmd, reply);
    };

    self._handle_outbound_reply_to = function(cmd, reply) {
         self.request_calls.push(cmd);
         reply(self.waiting_replies.shift());
    };

    self._handle_outbound_send_to_tag = function(cmd, reply) {
        self.outbound_sends.push(cmd);
        reply(self._populate_reply(cmd, {success: true}));
    };

    // original api

    self.populate_command = function(cmd_name, cmd) {
        cmd.cmd = cmd_name;
        return cmd;
    };

    self.request = function(cmd_name, cmd_data, reply) {
        var cmd = self.populate_command(cmd_name, cmd_data);
        self._dispatch_command(cmd, reply);
    };

    self.log_info = function(msg) {
        self.logs.push(msg);
    };

    self.done = function() {
        self.done_calls += 1;
    };
}

// exports
this.DummyApi = DummyApi;
<|endoftext|>