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

'use strict';

var errors = require('./errors');

function RelayRequest(channel, inreq, buildRes) {
    var self = this;
    self.channel = channel;
    self.inreq = inreq;
    self.inres = null;
    self.outres = null;
    self.outreq = null;
    self.buildRes = buildRes;
}

RelayRequest.prototype.createOutRequest = function createOutRequest() {
    var self = this;

    self.outreq = self.channel.request({
        streamed: self.inreq.streamed,
        ttl: self.inreq.ttl,
        service: self.inreq.service,
        headers: self.inreq.headers,
        retryFlags: self.inreq.retryFlags
    });
    self.outreq.on('response', onResponse);
    self.outreq.on('error', onError);

    if (self.outreq.streamed) {
        // TODO: frame-at-a-time rather than re-streaming?
        self.inreq.arg1.pipe(self.outreq.arg1);
        self.inreq.arg2.pipe(self.outreq.arg2);
        self.inreq.arg3.pipe(self.outreq.arg3);
    } else {
        self.outreq.send(self.inreq.arg1, self.inreq.arg2, self.inreq.arg3);
    }

    return self.outreq;

    function onResponse(res) {
        self.onResponse(res);
    }

    function onError(err) {
        self.onError(err);
    }
};

RelayRequest.prototype.createOutResponse = function createOutResponse(options) {
    var self = this;
    if (self.outres) {
        self.channel.logger.warn('relay request already responded', {
            // TODO: better context
            remoteAddr: self.inreq.remoteAddr,
            id: self.inreq.id
        });
        return;
    }
    self.outres = self.buildRes(options);
    return self.outres;
};

RelayRequest.prototype.onResponse = function onResponse(res) {
    var self = this;

    self.inres = res;

    if (!self.createOutResponse({
        streamed: self.inres.streamed,
        code: self.inres.code
    })) return;

    if (self.outres.streamed) {
        self.outres.arg1.end();
        self.inres.arg2.pipe(self.outres.arg2);
        self.inres.arg3.pipe(self.outres.arg3);
    } else {
        self.outres.send(self.inres.arg2, self.inres.arg3);
    }
};

RelayRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.createOutResponse()) return;
    var codeName = errors.classify(err);
    if (codeName) {
        self.outres.sendError(codeName, err.message);
    } else {
        self.outres.sendError('UnexpectedError', err.message);
        self.channel.logger.error('unexpected error while forwarding', {
            error: err
            // TODO context
        });
    }

    // TODO: stat in some cases, e.g. declined / peer not available
};

function RelayHandler(channel) {
    var self = this;
    self.channel = channel;
}

RelayHandler.prototype.type = 'tchannel.relay-handler';

RelayHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;
    var rereq = new RelayRequest(self.channel, req, buildRes);
    rereq.createOutRequest();
};

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

'use strict';

var errors = require('./errors');

function RelayRequest(channel, inreq, buildRes) {
    var self = this;
    self.channel = channel;
    self.inreq = inreq;
    self.inres = null;
    self.outres = null;
    self.outreq = null;
    self.buildRes = buildRes;
}

RelayRequest.prototype.createOutRequest = function createOutRequest() {
    var self = this;

    self.outreq = self.channel.request({
        streamed: self.inreq.streamed,
        ttl: self.inreq.ttl,
        service: self.inreq.service,
        headers: self.inreq.headers,
        retryFlags: self.inreq.retryFlags
    });
    self.outreq.on('response', onResponse);
    self.outreq.on('error', onError);

    if (self.outreq.streamed) {
        // TODO: frame-at-a-time rather than re-streaming?
        self.inreq.arg1.pipe(self.outreq.arg1);
        self.inreq.arg2.pipe(self.outreq.arg2);
        self.inreq.arg3.pipe(self.outreq.arg3);
    } else {
        self.outreq.send(self.inreq.arg1, self.inreq.arg2, self.inreq.arg3);
    }

    return self.outreq;

    function onResponse(res) {
        self.onResponse(res);
    }

    function onError(err) {
        self.onError(err);
    }
};

RelayRequest.prototype.createOutResponse = function createOutResponse(options) {
    var self = this;
    if (self.outres) {
        self.channel.logger.warn('relay request already responded', {
            // TODO: better context
            remoteAddr: self.inreq.remoteAddr,
            id: self.inreq.id
        });
        return;
    }
    self.outres = self.buildRes(options);
    return self.outres;
};

RelayRequest.prototype.onResponse = function onResponse(res) {
    var self = this;

    if (self.inres) {
        self.channel.logger.warn('relay request got more than one response callback', {
            // TODO: better context
            remoteAddr: res.remoteAddr,
            id: res.id
        });
        return;
    }
    self.inres = res;

    if (!self.createOutResponse({
        streamed: self.inres.streamed,
        code: self.inres.code
    })) return;

    if (self.outres.streamed) {
        self.outres.arg1.end();
        self.inres.arg2.pipe(self.outres.arg2);
        self.inres.arg3.pipe(self.outres.arg3);
    } else {
        self.outres.send(self.inres.arg2, self.inres.arg3);
    }
};

RelayRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.createOutResponse()) return;
    var codeName = errors.classify(err);
    if (codeName) {
        self.outres.sendError(codeName, err.message);
    } else {
        self.outres.sendError('UnexpectedError', err.message);
        self.channel.logger.error('unexpected error while forwarding', {
            error: err
            // TODO context
        });
    }

    // TODO: stat in some cases, e.g. declined / peer not available
};

function RelayHandler(channel) {
    var self = this;
    self.channel = channel;
}

RelayHandler.prototype.type = 'tchannel.relay-handler';

RelayHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;
    var rereq = new RelayRequest(self.channel, req, buildRes);
    rereq.createOutRequest();
};

module.exports = RelayHandler;
<|endoftext|>


<commit_before>// App bootstrap
// Code to run before launching the app
//
// Make sure you call cb() when you're finished.
var redis = require("redis");

module.exports.bootstrap = function (cb) {
  setTimeout(function(){ require('../api/providers/'); }, 1000);
  //Cache.redis = redis.createClient();
	cb();
};
<commit_msg>redis is ready<commit_after>// App bootstrap
// Code to run before launching the app
//
// Make sure you call cb() when you're finished.
var redis = require("redis");

module.exports.bootstrap = function (cb) {
  setTimeout(function(){ require('../api/providers/'); }, 1000);
  Cache.redis = redis.createClient();
	cb();
};
<|endoftext|>


<commit_before>/**
 * Bootstrap
 * (sails.config.bootstrap)
 *
 * An asynchronous bootstrap function that runs before your Sails app gets lifted.
 * This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
 *
 * For more information on bootstrapping your app, check out:
 * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html
 */

module.exports.bootstrap = function(cb) {

  // It's very important to trigger this callback method when you are finished
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
  Statistics.query('ALTER TABLE `statistics` ADD UNIQUE `unique_index`(`team`, `player`, `season`, `week`);', function(err, result) {
    console.log(err);
    console.log(result);
    if (err) {
      cb(err);
    } else {
      cb();
    }
  });
};
<commit_msg>Prevent adding custom index multiple times<commit_after>/**
 * Bootstrap
 * (sails.config.bootstrap)
 *
 * An asynchronous bootstrap function that runs before your Sails app gets lifted.
 * This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
 *
 * For more information on bootstrapping your app, check out:
 * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html
 */

module.exports.bootstrap = function(cb) {

  // It's very important to trigger this callback method when you are finished
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
  Statistics.query("SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS " +
                    "WHERE table_schema=DATABASE() AND table_name='statistics' AND index_name='unique_index';", function(err, result) {
    if (err) {
      cb(err);
    } else if (result.IndexIsThere !== 0) {
      cb();
    } else {
      Statistics.query('ALTER TABLE `statistics` ADD UNIQUE `unique_index`(`team`, `player`, `season`, `week`);', function(err, result) {
        if (err) {
          cb(err);
        } else {
          cb();
        }
      });
    }
  });
};
<|endoftext|>


<commit_before>import { render as preactRender, cloneElement as preactCloneElement, createRef, h, Component, options, toChildArray, createContext, Fragment } from 'preact';
import * as hooks from 'preact/hooks';
export * from 'preact/hooks';
import { assign } from '../../src/util';

const version = '16.8.0'; // trick libraries to think we are react

/* istanbul ignore next */
const REACT_ELEMENT_TYPE = (typeof Symbol!=='undefined' && Symbol.for && Symbol.for('react.element')) || 0xeac7;

const CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vector|vert|word|writing|x)[A-Z]/;

let oldEventHook = options.event;
options.event = e => {
	/* istanbul ignore next */
	if (oldEventHook) e = oldEventHook(e);
	e.persist = () => {};
	return e.nativeEvent = e;
};

/**
 * Legacy version of createElement.
 * @param {import('./internal').VNode["type"]} type The node name or Component constructor
 */
function createFactory(type) {
	return createElement.bind(null, type);
}

/**
 * Normalize DOM vnode properties.
 * @param {import('./internal').VNode} vnode The vnode to normalize props of
 * @param {object | null | undefined} props props to normalize
 */
function handleElementVNode(vnode, props) {
	let shouldSanitize, attrs, i;
	for (i in props) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
	if (shouldSanitize) {
		attrs = vnode.props = {};
		for (i in props) {
			attrs[CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i] = props[i];
		}
	}
}

/**
 * Proxy render() since React returns a Component reference.
 * @param {import('./internal').VNode} vnode VNode tree to render
 * @param {import('./internal').PreactElement} parent DOM node to render vnode tree into
 * @param {() => void} [callback] Optional callback that will be called after rendering
 * @returns {import('./internal').Component | null} The root component reference or null
 */
function render(vnode, parent, callback) {
	preactRender(vnode, parent);
	if (typeof callback==='function') callback();

	return vnode!=null ? vnode._component : null;
}

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

/**
 * Portal component
 * @param {object | null | undefined} props
 */
function Portal(props) {
	let wrap = h(ContextProvider, { context: this.context }, props.vnode);
	render(wrap, props.container);
	this.componentWillUnmount = () => {
		render(null, props.container);
	};
	return null;
}

/**
 * Create a `Portal` to continue rendering the vnode tree at a different DOM node
 * @param {import('./internal').VNode} vnode The vnode to render
 * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.
 */
function createPortal(vnode, container) {
	return h(Portal, { vnode, container });
}

const mapFn = (children, fn) => {
	if (children == null) return null;
	children = toChildArray(children);
	return children.map(fn);
};

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map: mapFn,
	forEach: mapFn,
	count(children) {
		return children ? toChildArray(children).length : 0;
	},
	only(children) {
		children = toChildArray(children);
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray: toChildArray
};

/**
 * Wrap `createElement` to apply various vnode normalizations.
 * @param {import('./internal').VNode["type"]} type The node name or Component constructor
 * @param {object | null | undefined} [props] The vnode's properties
 * @param {Array<import('./internal').ComponentChildren>} [children] The vnode's children
 * @returns {import('./internal').VNode}
 */
function createElement(...args) {
	let vnode = h(...args);

	let type = vnode.type, props = vnode.props;
	if (typeof type!='function') {
		if (props.defaultValue) {
			if (!props.value && props.value!==0) {
				props.value = props.defaultValue;
			}
			delete props.defaultValue;
		}

		if (Array.isArray(props.value) && props.multiple && type==='select') {
			toChildArray(props.children).forEach((child) => {
				if (props.value.indexOf(child.props.value)!==-1) {
					child.props.selected = true;
				}
			});
			delete props.value;
		}
		handleElementVNode(vnode, props);
	}

	vnode.preactCompatNormalized = false;
	return normalizeVNode(vnode);
}

/**
 * Normalize a vnode
 * @param {import('./internal').VNode} vnode
 */
function normalizeVNode(vnode) {
	vnode.preactCompatNormalized = true;
	applyClassName(vnode);
	return vnode;
}

/**
 * Wrap `cloneElement` to abort if the passed element is not a valid element and apply
 * all vnode normalizations.
 * @param {import('./internal').VNode} element The vnode to clone
 * @param {object} props Props to add when cloning
 * @param {Array<import('./internal').ComponentChildren} rest Optional component children
 */
function cloneElement(element) {
	if (!isValidElement(element)) return element;
	let vnode = normalizeVNode(preactCloneElement.apply(null, arguments));
	vnode.$$typeof = REACT_ELEMENT_TYPE;
	return vnode;
}

/**
 * Check if the passed element is a valid (p)react node.
 * @param {*} element The element to check
 * @returns {boolean}
 */
function isValidElement(element) {
	return element!=null && element.$$typeof===REACT_ELEMENT_TYPE;
}

/**
 * Normalize event handlers like react does. Most famously it uses `onChange` for any input element.
 * @param {import('./internal').VNode} vnode The vnode to normalize events on
 */
function applyEventNormalization({ type, props }) {
	if (!props || typeof type!=='string') return;
	let newProps = {};
	for (let i in props) {
		newProps[i.toLowerCase()] = i;
	}
	if (newProps.ondoubleclick) {
		props.ondblclick = props[newProps.ondoubleclick];
		delete props[newProps.ondoubleclick];
	}
	if (newProps.onbeforeinput) {
		props.onbeforeinput = props[newProps.onbeforeinput];
		delete props[newProps.onbeforeinput];
	}
	// for *textual inputs* (incl textarea), normalize `onChange` -> `onInput`:
	if (newProps.onchange && (type==='textarea' || (type.toLowerCase()==='input' && !/^fil|che|rad/i.test(props.type)))) {
		let normalized = newProps.oninput || 'oninput';
		if (!props[normalized]) {
			props[normalized] = props[newProps.onchange];
			delete props[newProps.onchange];
		}
	}
}

/**
 * Remove a component tree from the DOM, including state and event handlers.
 * @param {Element | Document | ShadowRoot | DocumentFragment} container
 * @returns {boolean}
 */
function unmountComponentAtNode(container) {
	if (container._prevVNode!=null) {
		preactRender(null, container);
		return true;
	}
	return false;
}

/**
 * Alias `class` prop to `className` if available
 * @param {import('./internal').VNode} vnode
 */
function applyClassName(vnode) {
	let a = vnode.props;
	if (a.class || a.className) {
		classNameDescriptor.enumerable = 'className' in a;
		if (a.className) a.class = a.className;
		Object.defineProperty(a, 'className', classNameDescriptor);
	}
}

let classNameDescriptor = {
	configurable: true,
	get() { return this.class; }
};

/**
 * Check if two objects have a different shape
 * @param {object} a
 * @param {object} b
 * @returns {boolean}
 */
function shallowDiffers(a, b) {
	for (let i in a) if (!(i in b)) return true;
	for (let i in b) if (a[i]!==b[i]) return true;
	return false;
}

/**
 * Get the matching DOM node for a component
 * @param {import('./internal').Component} component
 * @returns {import('./internal').PreactElement | null}
 */
function findDOMNode(component) {
	return component && (component.base || component.nodeType === 1 && component) || null;
}

/**
 * Component class with a predefined `shouldComponentUpdate` implementation
 */
class PureComponent extends Component {
	constructor(props) {
		super(props);
		// Some third-party libraries check if this property is present
		this.isPureReactComponent = true;
	}

	shouldComponentUpdate(props, state) {
		return shallowDiffers(this.props, props) || shallowDiffers(this.state, state);
	}
}

// Some libraries like `react-virtualized` explicitely check for this.
Component.prototype.isReactComponent = {};

/**
 * Memoize a component, so that it only updates when the props actually have
 * changed. This was previously known as `React.pure`.
 * @param {import('./internal').FunctionalComponent} c functional component
 * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function
 * @returns {import('./internal').FunctionalComponent}
 */
function memo(c, comparer) {
	function shouldUpdate(nextProps) {
		let ref = this.props.ref;
		let updateRef = ref==nextProps.ref;
		if (!updateRef) {
			ref.call ? ref(null) : (ref.current = null);
		}
		return (comparer==null
			? shallowDiffers(this.props, nextProps)
			: !comparer(this.props, nextProps)) || !updateRef;
	}

	function Memoed(props) {
		this.shouldComponentUpdate = shouldUpdate;
		return h(c, assign({}, props));
	}
	Memoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';
	Memoed._forwarded = true;
	return Memoed;
}

// Patch in `UNSAFE_*` lifecycle hooks
function setUnsafeDescriptor(obj, key) {
	Object.defineProperty(obj.prototype, 'UNSAFE_' + key, {
		configurable: true,
		get() { return this[key]; },
		set(v) { this[key] = v; }
	});
}

setUnsafeDescriptor(Component, 'componentWillMount');
setUnsafeDescriptor(Component, 'componentWillReceiveProps');
setUnsafeDescriptor(Component, 'componentWillUpdate');

/**
 * Pass ref down to a child. This is mainly used in libraries with HOCs that
 * wrap components. Using `forwardRef` there is an easy way to get a reference
 * of the wrapped component instead of one of the wrapper itself.
 * @param {import('./internal').ForwardFn} fn
 * @returns {import('./internal').FunctionalComponent}
 */
function forwardRef(fn) {
	function Forwarded(props) {
		let ref = props.ref;
		delete props.ref;
		return fn(props, ref);
	}
	Forwarded._forwarded = true;
	Forwarded.displayName = 'ForwardRef(' + (fn.displayName || fn.name) + ')';
	return Forwarded;
}

let oldVNodeHook = options.vnode;
options.vnode = vnode => {
	vnode.$$typeof = REACT_ELEMENT_TYPE;

	applyEventNormalization(vnode);
	let type = vnode.type;
	if (type!=null && type._forwarded && vnode.ref!=null) {
		vnode.props.ref = vnode.ref;
		vnode.ref = null;
	}
	/* istanbul ignore next */
	if (oldVNodeHook) oldVNodeHook(vnode);
};

/**
 * Deprecated way to control batched rendering inside the reconciler, but we
 * already schedule in batches inside our rendering code
 * @param {(a) => void} callback function that triggers the updatd
 * @param {*} [arg] Optional argument that can be passed to the callback
 */
// eslint-disable-next-line camelcase
function unstable_batchedUpdates(callback, arg) {
	callback(arg);
}

export {
	version,
	Children,
	render,
	render as hydrate,
	unmountComponentAtNode,
	createPortal,
	createElement,
	createContext,
	createFactory,
	cloneElement,
	createRef,
	Fragment,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent,
	memo,
	forwardRef,
	// eslint-disable-next-line camelcase
	unstable_batchedUpdates
};

// React copies the named exports to the default one.
export default assign({
	version,
	Children,
	render,
	hydrate: render,
	unmountComponentAtNode,
	createPortal,
	createElement,
	createContext,
	createFactory,
	cloneElement,
	createRef,
	Fragment,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent,
	memo,
	forwardRef,
	unstable_batchedUpdates
}, hooks);
<commit_msg>one step to childArray -2B<commit_after>import { render as preactRender, cloneElement as preactCloneElement, createRef, h, Component, options, toChildArray, createContext, Fragment } from 'preact';
import * as hooks from 'preact/hooks';
export * from 'preact/hooks';
import { assign } from '../../src/util';

const version = '16.8.0'; // trick libraries to think we are react

/* istanbul ignore next */
const REACT_ELEMENT_TYPE = (typeof Symbol!=='undefined' && Symbol.for && Symbol.for('react.element')) || 0xeac7;

const CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vector|vert|word|writing|x)[A-Z]/;

let oldEventHook = options.event;
options.event = e => {
	/* istanbul ignore next */
	if (oldEventHook) e = oldEventHook(e);
	e.persist = () => {};
	return e.nativeEvent = e;
};

/**
 * Legacy version of createElement.
 * @param {import('./internal').VNode["type"]} type The node name or Component constructor
 */
function createFactory(type) {
	return createElement.bind(null, type);
}

/**
 * Normalize DOM vnode properties.
 * @param {import('./internal').VNode} vnode The vnode to normalize props of
 * @param {object | null | undefined} props props to normalize
 */
function handleElementVNode(vnode, props) {
	let shouldSanitize, attrs, i;
	for (i in props) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
	if (shouldSanitize) {
		attrs = vnode.props = {};
		for (i in props) {
			attrs[CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i] = props[i];
		}
	}
}

/**
 * Proxy render() since React returns a Component reference.
 * @param {import('./internal').VNode} vnode VNode tree to render
 * @param {import('./internal').PreactElement} parent DOM node to render vnode tree into
 * @param {() => void} [callback] Optional callback that will be called after rendering
 * @returns {import('./internal').Component | null} The root component reference or null
 */
function render(vnode, parent, callback) {
	preactRender(vnode, parent);
	if (typeof callback==='function') callback();

	return vnode!=null ? vnode._component : null;
}

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

/**
 * Portal component
 * @param {object | null | undefined} props
 */
function Portal(props) {
	let wrap = h(ContextProvider, { context: this.context }, props.vnode);
	render(wrap, props.container);
	this.componentWillUnmount = () => {
		render(null, props.container);
	};
	return null;
}

/**
 * Create a `Portal` to continue rendering the vnode tree at a different DOM node
 * @param {import('./internal').VNode} vnode The vnode to render
 * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.
 */
function createPortal(vnode, container) {
	return h(Portal, { vnode, container });
}

const mapFn = (children, fn) => {
	if (children == null) return null;
	return toChildArray(children).map(fn);
};

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map: mapFn,
	forEach: mapFn,
	count(children) {
		return children ? toChildArray(children).length : 0;
	},
	only(children) {
		children = toChildArray(children);
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray: toChildArray
};

/**
 * Wrap `createElement` to apply various vnode normalizations.
 * @param {import('./internal').VNode["type"]} type The node name or Component constructor
 * @param {object | null | undefined} [props] The vnode's properties
 * @param {Array<import('./internal').ComponentChildren>} [children] The vnode's children
 * @returns {import('./internal').VNode}
 */
function createElement(...args) {
	let vnode = h(...args);

	let type = vnode.type, props = vnode.props;
	if (typeof type!='function') {
		if (props.defaultValue) {
			if (!props.value && props.value!==0) {
				props.value = props.defaultValue;
			}
			delete props.defaultValue;
		}

		if (Array.isArray(props.value) && props.multiple && type==='select') {
			toChildArray(props.children).forEach((child) => {
				if (props.value.indexOf(child.props.value)!==-1) {
					child.props.selected = true;
				}
			});
			delete props.value;
		}
		handleElementVNode(vnode, props);
	}

	vnode.preactCompatNormalized = false;
	return normalizeVNode(vnode);
}

/**
 * Normalize a vnode
 * @param {import('./internal').VNode} vnode
 */
function normalizeVNode(vnode) {
	vnode.preactCompatNormalized = true;
	applyClassName(vnode);
	return vnode;
}

/**
 * Wrap `cloneElement` to abort if the passed element is not a valid element and apply
 * all vnode normalizations.
 * @param {import('./internal').VNode} element The vnode to clone
 * @param {object} props Props to add when cloning
 * @param {Array<import('./internal').ComponentChildren} rest Optional component children
 */
function cloneElement(element) {
	if (!isValidElement(element)) return element;
	let vnode = normalizeVNode(preactCloneElement.apply(null, arguments));
	vnode.$$typeof = REACT_ELEMENT_TYPE;
	return vnode;
}

/**
 * Check if the passed element is a valid (p)react node.
 * @param {*} element The element to check
 * @returns {boolean}
 */
function isValidElement(element) {
	return element!=null && element.$$typeof===REACT_ELEMENT_TYPE;
}

/**
 * Normalize event handlers like react does. Most famously it uses `onChange` for any input element.
 * @param {import('./internal').VNode} vnode The vnode to normalize events on
 */
function applyEventNormalization({ type, props }) {
	if (!props || typeof type!=='string') return;
	let newProps = {};
	for (let i in props) {
		newProps[i.toLowerCase()] = i;
	}
	if (newProps.ondoubleclick) {
		props.ondblclick = props[newProps.ondoubleclick];
		delete props[newProps.ondoubleclick];
	}
	if (newProps.onbeforeinput) {
		props.onbeforeinput = props[newProps.onbeforeinput];
		delete props[newProps.onbeforeinput];
	}
	// for *textual inputs* (incl textarea), normalize `onChange` -> `onInput`:
	if (newProps.onchange && (type==='textarea' || (type.toLowerCase()==='input' && !/^fil|che|rad/i.test(props.type)))) {
		let normalized = newProps.oninput || 'oninput';
		if (!props[normalized]) {
			props[normalized] = props[newProps.onchange];
			delete props[newProps.onchange];
		}
	}
}

/**
 * Remove a component tree from the DOM, including state and event handlers.
 * @param {Element | Document | ShadowRoot | DocumentFragment} container
 * @returns {boolean}
 */
function unmountComponentAtNode(container) {
	if (container._prevVNode!=null) {
		preactRender(null, container);
		return true;
	}
	return false;
}

/**
 * Alias `class` prop to `className` if available
 * @param {import('./internal').VNode} vnode
 */
function applyClassName(vnode) {
	let a = vnode.props;
	if (a.class || a.className) {
		classNameDescriptor.enumerable = 'className' in a;
		if (a.className) a.class = a.className;
		Object.defineProperty(a, 'className', classNameDescriptor);
	}
}

let classNameDescriptor = {
	configurable: true,
	get() { return this.class; }
};

/**
 * Check if two objects have a different shape
 * @param {object} a
 * @param {object} b
 * @returns {boolean}
 */
function shallowDiffers(a, b) {
	for (let i in a) if (!(i in b)) return true;
	for (let i in b) if (a[i]!==b[i]) return true;
	return false;
}

/**
 * Get the matching DOM node for a component
 * @param {import('./internal').Component} component
 * @returns {import('./internal').PreactElement | null}
 */
function findDOMNode(component) {
	return component && (component.base || component.nodeType === 1 && component) || null;
}

/**
 * Component class with a predefined `shouldComponentUpdate` implementation
 */
class PureComponent extends Component {
	constructor(props) {
		super(props);
		// Some third-party libraries check if this property is present
		this.isPureReactComponent = true;
	}

	shouldComponentUpdate(props, state) {
		return shallowDiffers(this.props, props) || shallowDiffers(this.state, state);
	}
}

// Some libraries like `react-virtualized` explicitely check for this.
Component.prototype.isReactComponent = {};

/**
 * Memoize a component, so that it only updates when the props actually have
 * changed. This was previously known as `React.pure`.
 * @param {import('./internal').FunctionalComponent} c functional component
 * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function
 * @returns {import('./internal').FunctionalComponent}
 */
function memo(c, comparer) {
	function shouldUpdate(nextProps) {
		let ref = this.props.ref;
		let updateRef = ref==nextProps.ref;
		if (!updateRef) {
			ref.call ? ref(null) : (ref.current = null);
		}
		return (comparer==null
			? shallowDiffers(this.props, nextProps)
			: !comparer(this.props, nextProps)) || !updateRef;
	}

	function Memoed(props) {
		this.shouldComponentUpdate = shouldUpdate;
		return h(c, assign({}, props));
	}
	Memoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';
	Memoed._forwarded = true;
	return Memoed;
}

// Patch in `UNSAFE_*` lifecycle hooks
function setUnsafeDescriptor(obj, key) {
	Object.defineProperty(obj.prototype, 'UNSAFE_' + key, {
		configurable: true,
		get() { return this[key]; },
		set(v) { this[key] = v; }
	});
}

setUnsafeDescriptor(Component, 'componentWillMount');
setUnsafeDescriptor(Component, 'componentWillReceiveProps');
setUnsafeDescriptor(Component, 'componentWillUpdate');

/**
 * Pass ref down to a child. This is mainly used in libraries with HOCs that
 * wrap components. Using `forwardRef` there is an easy way to get a reference
 * of the wrapped component instead of one of the wrapper itself.
 * @param {import('./internal').ForwardFn} fn
 * @returns {import('./internal').FunctionalComponent}
 */
function forwardRef(fn) {
	function Forwarded(props) {
		let ref = props.ref;
		delete props.ref;
		return fn(props, ref);
	}
	Forwarded._forwarded = true;
	Forwarded.displayName = 'ForwardRef(' + (fn.displayName || fn.name) + ')';
	return Forwarded;
}

let oldVNodeHook = options.vnode;
options.vnode = vnode => {
	vnode.$$typeof = REACT_ELEMENT_TYPE;

	applyEventNormalization(vnode);
	let type = vnode.type;
	if (type!=null && type._forwarded && vnode.ref!=null) {
		vnode.props.ref = vnode.ref;
		vnode.ref = null;
	}
	/* istanbul ignore next */
	if (oldVNodeHook) oldVNodeHook(vnode);
};

/**
 * Deprecated way to control batched rendering inside the reconciler, but we
 * already schedule in batches inside our rendering code
 * @param {(a) => void} callback function that triggers the updatd
 * @param {*} [arg] Optional argument that can be passed to the callback
 */
// eslint-disable-next-line camelcase
function unstable_batchedUpdates(callback, arg) {
	callback(arg);
}

export {
	version,
	Children,
	render,
	render as hydrate,
	unmountComponentAtNode,
	createPortal,
	createElement,
	createContext,
	createFactory,
	cloneElement,
	createRef,
	Fragment,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent,
	memo,
	forwardRef,
	// eslint-disable-next-line camelcase
	unstable_batchedUpdates
};

// React copies the named exports to the default one.
export default assign({
	version,
	Children,
	render,
	hydrate: render,
	unmountComponentAtNode,
	createPortal,
	createElement,
	createContext,
	createFactory,
	cloneElement,
	createRef,
	Fragment,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent,
	memo,
	forwardRef,
	unstable_batchedUpdates
}, hooks);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011  JTalks.org Team
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

/**
 * This script provides interactive UI for contact management in user profile.
 */

/**
 * Application base path with trailing slash. Must be defined somewhere within the global scope.
 */
var baseUrl = $root;

/**
 * Namespace for this file.
 */
var AddContact = {};

/** Currently selected contact type */
AddContact.selectedContactType = null;

/** Aall contact types */
AddContact.contactTypes = null;

/** if entered contact is valid */
AddContact.isValueValid = true;

function deleteContactHandler() {
    var element = $(this).parent();
    var contactId = $(this).parent().find("#contactId:hidden").attr("value");
    var contactOwnerId = $(this).parent().find("#contactOwnerId:hidden").attr("value");

    var footerContent = ' \
            <button id="remove-contact-cancel" class="btn">' + $labelCancel + '</button> \
            <button id="remove-contact-ok" class="btn btn-primary">' + $labelOk + '</button>'

    var submitFunc = function (e) {
        e.preventDefault();
        $.ajax({
            url: baseUrl + '/contacts/remove/' + contactOwnerId + '/' + contactId,
            // this is the way Spring MVC represents HTTP DELETE for better browser compatibility
            type: "POST",
            data: {'_method': 'DELETE'},
            success: function () {
                element.fadeOut();
                jDialog.closeDialog();
            },
            error: function () {
                jDialog.createDialog({
                    type: jDialog.alertType,
                    bodyMessage: $labelDeleteContactFailture
                });
            }
        });
    };

    jDialog.createDialog({
        type: jDialog.confirmType,
        bodyMessage: $labelDeleteContactConfirmation,
        firstFocus: false,
        footerContent: footerContent,
        maxWidth: 300,
        tabNavigation: ['#remove-contact-ok', '#remove-contact-cancel'],
        handlers: {
            '#remove-contact-ok': {'click': submitFunc},
            '#remove-contact-cancel': {'static':'close'}
        }
    });

    $('#remove-contact-ok').focus();
}

/**
 * Binds click handler for "X" buttons (delete contact)
 */
function bindDeleteHandler() {
    $("#contacts").find(".contact").find("a.button").each(function () {
        this.onclick = deleteContactHandler;
    });
}

/**
 *  Returns HTML code for new contact populated with data
 * @param data user contact
 */
function getContactHtml(data) {
    //HTML template for single contact. Should be in sync with corresponding JSP.
    var template =
        '
'
            + '		<input type="hidden" value="${contactId}"/>'
            + '		'
            + '			'
            + '     '
            + '		'
            + '     	'
            + '         ${value}'
            + '     '
            + '
';

    var contactTypeInfo = AddContact.getContactType($('#contact_type').val(), AddContact.contactTypes);
    var actualValue = contactTypeInfo.displayPattern.replace(new RegExp('%s', 'gi'), $('#contact').val());

    var html = template;
    html = html.replace('${icon}', baseUrl + contactTypeInfo.icon);
    html = html.replace('${typeName}', contactTypeInfo.typeName);
    html = html.replace('${contactId}', data.id);
    html = html.replace('${buttonId}', data.id);
    html = html.replace('${value}', actualValue);

    return html;
}

/**
 * Find contact type with given id in given array and return it
 */
AddContact.getContactType = function (id, contactTypes) {
    var result = null;

    if (id !== undefined && contactTypes !== undefined) {
        $.each(contactTypes, function (i, obj) {
            if (obj.id == id) {
                result = obj;
                return;
            }
        });
    }

    return result;
}

/**
 * Reset all variables. Used when new popup is displayed
 */
AddContact.resetVariables = function () {
    AddContact.isValueValid = true;
    AddContact.contactTypes = null;
    AddContact.selectedContactType = null;
}

$(document).ready(function () {

    $('body').on('keyup', '#contact', function () {
        var value = $(this).val();
        if (value.length > 0 && !value.match(new RegExp(AddContact.selectedContactType.validationPattern))) {
            if (AddContact.isValueValid) {
                ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                AddContact.isValueValid = false;
            }
        } else {
            ErrorUtils.removeErrorMessage('#contact');
            AddContact.isValueValid = true;
        }
    });

    // when user selects other contact type
    $('body').on('change', '#contact_type', function () {
        var contactId = $(this).val();
        AddContact.selectedContactType = AddContact.getContactType(contactId, AddContact.contactTypes);
        $('#contact').attr('placeholder', AddContact.selectedContactType.mask);
        $('#contact').keyup();
    });

    //"Add contact" button handler
    $("#add_contact").on("click", function () {

        AddContact.resetVariables();

        $.getJSON(baseUrl + "/contacts/types", function (json) {

            AddContact.contactTypes = json;
            AddContact.selectedContactType = json[0];

            // select
            var bodyContent = '
'
                + '' + $labelContactType + ''
                + '
'
                +   '<select name="contact_type" id="contact_type" class="first dialog-input">';

            $.each(json, function (i, obj) {
                bodyContent += '<option value="' + obj.id + '">' + obj.typeName + '</option>';
            });
            bodyContent += '</select>

';

            // text input
            bodyContent += '
'
            bodyContent += '	' + $labelContactValue + '';
            bodyContent += '
';
            bodyContent += '		<input type="text" name="contact" id="contact" placeholder="'
                + AddContact.selectedContactType.mask + '" />';
            bodyContent += '
';
            bodyContent += '	' + $labelContactValueInfo + '';
            bodyContent += '
';

            var footerContent = ' \
            <button id="add-contact-cancel" class="btn">' + $labelCancel + '</button> \
            <button id="add-contact-ok" class="btn btn-primary">' + $labelOk + '</button>';

            var submitFunc = function (e) {
                e.preventDefault();
               if (AddContact.isValueValid && $('#contact').val() != '' && $('#contact').length > 0) {
                    var ownerId = $("#editedUserId").val();

                    var contact = {
                        ownerId: ownerId,
                        value: $('#contact').val(),
                        typeId: $('#contact_type').val()
                    };

                    $.ajax({
                        url: baseUrl + '/contacts/add',
                        type: "POST",
                        contentType: "application/json",
                        async: false,
                        data: JSON.stringify(contact),
                        success: function (data) {
                            if(data.status === 'SUCCESS'){
                                //populate contact template and append to page
                                $("#contacts").append(getContactHtml(data.result));
                                bindDeleteHandler();
                                jDialog.closeDialog();
                            }else{
                                ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                                AddContact.isValueValid = false;
                            }
                        },
                        error: function (data) {
                            ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                            AddContact.isValueValid = false;
                        }
                    });
                }else{
                   ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                   AddContact.isValueValid = false;
               }
            }

            jDialog.createDialog({
                dialogId: 'add-contact-dialog',
                title: $labelContactsAddDialog,
                bodyContent: bodyContent,
                footerContent: footerContent,
                maxWidth: 350,
                maxHeight: 350,
                tabNavigation: ['#contact_type', '#contact', '#add-contact-ok', '#add-contact-cancel'],
                handlers: {
                    '#add-contact-ok': {'click': submitFunc},
                    '#add-contact-cancel': {'static':'close'}
                }
            });
        });
    });

    bindDeleteHandler();
});
<commit_msg>JC-1538<commit_after>/*
 * Copyright (C) 2011  JTalks.org Team
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

/**
 * This script provides interactive UI for contact management in user profile.
 */

/**
 * Application base path with trailing slash. Must be defined somewhere within the global scope.
 */
var baseUrl = $root;

/**
 * Namespace for this file.
 */
var AddContact = {};

/** Currently selected contact type */
AddContact.selectedContactType = null;

/** Aall contact types */
AddContact.contactTypes = null;

/** if entered contact is valid */
AddContact.isValueValid = true;

function deleteContactHandler() {
    var element = $(this).parent();
    var contactId = $(this).parent().find("#contactId:hidden").attr("value");
    var contactOwnerId = $(this).parent().find("#contactOwnerId:hidden").attr("value");

    var footerContent = ' \
            <button id="remove-contact-cancel" class="btn">' + $labelCancel + '</button> \
            <button id="remove-contact-ok" class="btn btn-primary">' + $labelOk + '</button>'

    var submitFunc = function (e) {
        e.preventDefault();
        $.ajax({
            url: baseUrl + '/contacts/remove/' + contactOwnerId + '/' + contactId,
            // this is the way Spring MVC represents HTTP DELETE for better browser compatibility
            type: "POST",
            data: {'_method': 'DELETE'},
            success: function () {
                element.fadeOut();
                jDialog.closeDialog();
            },
            error: function () {
                jDialog.createDialog({
                    type: jDialog.alertType,
                    bodyMessage: $labelDeleteContactFailture
                });
            }
        });
    };

    jDialog.createDialog({
        type: jDialog.confirmType,
        bodyMessage: $labelDeleteContactConfirmation,
        firstFocus: false,
        footerContent: footerContent,
        maxWidth: 300,
        tabNavigation: ['#remove-contact-ok', '#remove-contact-cancel'],
        handlers: {
            '#remove-contact-ok': {'click': submitFunc},
            '#remove-contact-cancel': {'static':'close'}
        }
    });

    $('#remove-contact-ok').focus();
}

/**
 * Binds click handler for "X" buttons (delete contact)
 */
function bindDeleteHandler() {
    $("#contacts").find(".contact").find("a.button").each(function () {
        this.onclick = deleteContactHandler;
    });
}

/**
 *  Returns HTML code for new contact populated with data
 * @param data user contact
 */
function getContactHtml(data) {
    //HTML template for single contact. Should be in sync with corresponding JSP.
    var template =
        '
'
            + '		<input type="hidden" value="${contactId}"/>'
            + '		'
            + '			'
            + '     '
            + '		'
            + '     	'
            + '         ${value}'
            + '     '
            + '
';

    var contactTypeInfo = AddContact.getContactType($('#contact_type').val(), AddContact.contactTypes);
    var actualValue = contactTypeInfo.displayPattern.replace(new RegExp('%s', 'gi'), $('#contact').val());

    var html = template;
    html = html.replace('${icon}', baseUrl + contactTypeInfo.icon);
    html = html.replace('${typeName}', contactTypeInfo.typeName);
    html = html.replace('${contactId}', data.id);
    html = html.replace('${buttonId}', data.id);
    html = html.replace('${value}', actualValue);

    return html;
}

/**
 * Find contact type with given id in given array and return it
 */
AddContact.getContactType = function (id, contactTypes) {
    var result = null;

    if (id !== undefined && contactTypes !== undefined) {
        $.each(contactTypes, function (i, obj) {
            if (obj.id == id) {
                result = obj;
                return;
            }
        });
    }

    return result;
}

/**
 * Reset all variables. Used when new popup is displayed
 */
AddContact.resetVariables = function () {
    AddContact.isValueValid = true;
    AddContact.contactTypes = null;
    AddContact.selectedContactType = null;
}

$(document).ready(function () {

    $('body').on('keyup', '#contact', function () {
        var value = $(this).val();
        if (value.length > 0 && !value.match(new RegExp(AddContact.selectedContactType.validationPattern))) {
            if (AddContact.isValueValid) {
                ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                AddContact.isValueValid = false;
            }
        } else {
            ErrorUtils.removeErrorMessage('#contact');
            AddContact.isValueValid = true;
        }
    });

    // when user selects other contact type
    $('body').on('change', '#contact_type', function () {
        var contactId = $(this).val();
        AddContact.selectedContactType = AddContact.getContactType(contactId, AddContact.contactTypes);
        $('#contact').attr('placeholder', AddContact.selectedContactType.mask);
        $('#contact').keyup();
    });

    //"Add contact" button handler
    $("#add_contact").on("click", function () {

        AddContact.resetVariables();

        $.getJSON(baseUrl + "/contacts/types", function (json) {

            AddContact.contactTypes = json;
            AddContact.selectedContactType = json[0];

            // select
            var bodyContent = '
'
                + '' + $labelContactType + ''
                + '
'
                +   '<select name="contact_type" id="contact_type" class="first dialog-input">';

            $.each(json, function (i, obj) {
                bodyContent += '<option value="' + obj.id + '">' + obj.typeName + '</option>';
            });
            bodyContent += '</select>

';

            // text input
            bodyContent += '
'
            bodyContent += '	' + $labelContactValue + '';
            bodyContent += '
';
            bodyContent += '		<input type="text" name="contact" id="contact" placeholder="'
                + AddContact.selectedContactType.mask + '" />';
            bodyContent += '
';
            bodyContent += '	' + $labelContactValueInfo + '';
            bodyContent += '
';

            var footerContent = ' \
            <button id="add-contact-cancel" class="btn">' + $labelCancel + '</button> \
            <button id="add-contact-ok" class="btn btn-primary">' + $labelOk + '</button>';

            var submitFunc = function (e) {
                e.preventDefault();
               if (AddContact.isValueValid && $('#contact').val() != '' && $('#contact').length > 0) {
                    var ownerId = $("#editedUserId").val();

                    var contact = {
                        ownerId: ownerId,
                        value: $('#contact').val(),
                        typeId: $('#contact_type').val()
                    };

                    $.ajax({
                        url: baseUrl + '/contacts/add',
                        type: "POST",
                        contentType: "application/json",
                        async: false,
                        data: JSON.stringify(contact),
                        success: function (data) {
                            if(data.status === 'SUCCESS'){
                                //populate contact template and append to page
                                $("#contacts").append(getContactHtml(data.result));
                                bindDeleteHandler();
                                jDialog.closeDialog();
                            }else{
                                ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                                AddContact.isValueValid = false;
                            }
                        },
                        error: function (data) {
                            ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                            AddContact.isValueValid = false;
                        }
                    });
                }else{
                   ErrorUtils.addErrorMessage('#contact', $labelValidationUsercontactNotMatch);
                   AddContact.isValueValid = false;
               }
                jQuery('.contact').tooltip({placement: 'right'});
            }

            jDialog.createDialog({
                dialogId: 'add-contact-dialog',
                title: $labelContactsAddDialog,
                bodyContent: bodyContent,
                footerContent: footerContent,
                maxWidth: 350,
                maxHeight: 350,
                tabNavigation: ['#contact_type', '#contact', '#add-contact-ok', '#add-contact-cancel'],
                handlers: {
                    '#add-contact-ok': {'click': submitFunc},
                    '#add-contact-cancel': {'static':'close'}
                }
            });
        });
    });

    bindDeleteHandler();
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const models = require('./index');

/**
 * The compute resource properties for managed integration runtime.
 *
 */
class IntegrationRuntimeComputeProperties {
  /**
   * Create a IntegrationRuntimeComputeProperties.
   * @member {string} [location] The location for managed integration runtime.
   * The supported regions could be found on
   * https://docs.microsoft.com/en-us/azure/data-factory/data-factory-data-movement-activities
   * @member {string} [nodeSize] The node size requirement to managed
   * integration runtime.
   * @member {number} [numberOfNodes] The required number of nodes for managed
   * integration runtime.
   * @member {number} [maxParallelExecutionsPerNode] Maximum parallel
   * executions count per node for managed integration runtime.
   * @member {object} [vNetProperties] VNet properties for managed integration
   * runtime.
   * @member {string} [vNetProperties.vNetId] The ID of the VNet that this
   * integration runtime will join.
   * @member {string} [vNetProperties.subnet] The name of the subnet this
   * integration runtime will join.
   */
  constructor() {
  }

  /**
   * Defines the metadata of IntegrationRuntimeComputeProperties
   *
   * @returns {object} metadata of IntegrationRuntimeComputeProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'IntegrationRuntimeComputeProperties',
      type: {
        name: 'Composite',
        additionalProperties: {
          type: {
            name: 'Dictionary',
            value: {
                required: false,
                serializedName: 'ObjectElementType',
                type: {
                  name: 'Object'
                }
            }
          }
        },
        className: 'IntegrationRuntimeComputeProperties',
        modelProperties: {
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          nodeSize: {
            required: false,
            serializedName: 'nodeSize',
            type: {
              name: 'String'
            }
          },
          numberOfNodes: {
            required: false,
            serializedName: 'numberOfNodes',
            constraints: {
              InclusiveMinimum: 1
            },
            type: {
              name: 'Number'
            }
          },
          maxParallelExecutionsPerNode: {
            required: false,
            serializedName: 'maxParallelExecutionsPerNode',
            constraints: {
              InclusiveMaximum: 8,
              InclusiveMinimum: 1
            },
            type: {
              name: 'Number'
            }
          },
          vNetProperties: {
            required: false,
            serializedName: 'vNetProperties',
            type: {
              name: 'Composite',
              additionalProperties: {
                type: {
                  name: 'Dictionary',
                  value: {
                      required: false,
                      serializedName: 'ObjectElementType',
                      type: {
                        name: 'Object'
                      }
                  }
                }
              },
              className: 'IntegrationRuntimeVNetProperties'
            }
          }
        }
      }
    };
  }
}

module.exports = IntegrationRuntimeComputeProperties;
<commit_msg>Generated from 932f3adb13821639c173dc647dd024875372238a (#3000)<commit_after>/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const models = require('./index');

/**
 * The compute resource properties for managed integration runtime.
 *
 */
class IntegrationRuntimeComputeProperties {
  /**
   * Create a IntegrationRuntimeComputeProperties.
   * @member {string} [location] The location for managed integration runtime.
   * The supported regions could be found on
   * https://docs.microsoft.com/en-us/azure/data-factory/data-factory-data-movement-activities
   * @member {string} [nodeSize] The node size requirement to managed
   * integration runtime.
   * @member {number} [numberOfNodes] The required number of nodes for managed
   * integration runtime.
   * @member {number} [maxParallelExecutionsPerNode] Maximum parallel
   * executions count per node for managed integration runtime.
   * @member {object} [vNetProperties] VNet properties for managed integration
   * runtime.
   * @member {string} [vNetProperties.vNetId] The ID of the VNet that this
   * integration runtime will join.
   * @member {string} [vNetProperties.subnet] The name of the subnet this
   * integration runtime will join.
   */
  constructor() {
  }

  /**
   * Defines the metadata of IntegrationRuntimeComputeProperties
   *
   * @returns {object} metadata of IntegrationRuntimeComputeProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'IntegrationRuntimeComputeProperties',
      type: {
        name: 'Composite',
        additionalProperties: {
          type: {
            name: 'Dictionary',
            value: {
                required: false,
                serializedName: 'ObjectElementType',
                type: {
                  name: 'Object'
                }
            }
          }
        },
        className: 'IntegrationRuntimeComputeProperties',
        modelProperties: {
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          nodeSize: {
            required: false,
            serializedName: 'nodeSize',
            type: {
              name: 'String'
            }
          },
          numberOfNodes: {
            required: false,
            serializedName: 'numberOfNodes',
            constraints: {
              InclusiveMinimum: 1
            },
            type: {
              name: 'Number'
            }
          },
          maxParallelExecutionsPerNode: {
            required: false,
            serializedName: 'maxParallelExecutionsPerNode',
            constraints: {
              InclusiveMinimum: 1
            },
            type: {
              name: 'Number'
            }
          },
          vNetProperties: {
            required: false,
            serializedName: 'vNetProperties',
            type: {
              name: 'Composite',
              additionalProperties: {
                type: {
                  name: 'Dictionary',
                  value: {
                      required: false,
                      serializedName: 'ObjectElementType',
                      type: {
                        name: 'Object'
                      }
                  }
                }
              },
              className: 'IntegrationRuntimeVNetProperties'
            }
          }
        }
      }
    };
  }
}

module.exports = IntegrationRuntimeComputeProperties;
<|endoftext|>


<commit_before>
const React = require('react');
const { PureComponent, PropTypes } = React;
const { Store } = require('stas');

function connect(TargetComponent, mapToProps = defaultMapToProps) {
  class ConnectComponent extends PureComponent {
    static propTypes = {
    }

    static contextTypes = {
      store: PropTypes.instanceOf(Store).isRequired,
    }

    constructor(props, context) {
      super(props, context);

      const { store } = context;
      this.state = { ...this.getMapProps(store.state) };

      this._unsubscribe = store.subscribe((newState) => {
        this.setState({ ...this.getMapProps(newState) });
      });
    }

    componentWillUnmount() {
      if (this._unsubscribe) {
        this._unsubscribe();
        this._unsubscribe = null;
      }
    }

    getMapProps(state) {
      const dispatch = this.context.store.dispatch;
      const mprops = mapToProps(state, dispatch);
      if (!mprops) return { state, dispatch };
      if (!mprops.dispatch) mprops.dispatch = dispatch;
      return mprops;
    }

    render() {
      return <TargetComponent {...this.props} {...this.state} />;
    }
  }

  return ConnectComponent;
}

function defaultMapToProps(state, dispatch) {
  return { state, dispatch };
}

module.exports = connect;
<commit_msg>Fix: wrong characteristic of connect() in react-stas<commit_after>
const React = require('react');
const { PureComponent, PropTypes } = React;
const { Store } = require('stas');

function connect(mapToProps = defaultMapToProps) {
  return (TargetComponent) => {
    class ConnectComponent extends PureComponent {
      static propTypes = {
      }

      static contextTypes = {
        store: PropTypes.instanceOf(Store).isRequired,
      }

      constructor(props, context) {
        super(props, context);

        const { store } = context;
        this.state = { ...this.getMapProps(store.state) };

        this._unsubscribe = store.subscribe((newState) => {
          this.setState({ ...this.getMapProps(newState) });
        });
      }

      componentWillUnmount() {
        if (this._unsubscribe) {
          this._unsubscribe();
          this._unsubscribe = null;
        }
      }

      getMapProps(state) {
        const dispatch = this.context.store.dispatch;
        const mprops = mapToProps(state, dispatch);
        if (!mprops) return { state, dispatch };
        if (!mprops.dispatch) mprops.dispatch = dispatch;
        return mprops;
      }

      render() {
        return <TargetComponent {...this.props} {...this.state} />;
      }
    }
    return ConnectComponent;
  };
}

function defaultMapToProps(state, dispatch) {
  return { state, dispatch };
}

module.exports = connect;
<|endoftext|>


<commit_before>import React from 'react'

import { COLORS } from '../lib/constants'

const Input = React.forwardRef(
  (
    {
      accept,
      color = COLORS.SECONDARY,
      name,
      onChange = () => {},
      placeholder,
      title,
      type,
      value,
      align = 'right',
      maxLength
    },
    ref
  ) => {
    return (
      <React.Fragment>
        <input
          ref={ref}
          type={type}
          accept={accept}
          title={title}
          placeholder={placeholder}
          value={value}
          name={name}
          onChange={onChange}
          maxLength={maxLength}
        />
        <style jsx>
          {`
            input {
              width: 100%;
              font-size: 12px;
              color: ${color};
              background: transparent;
              border: none;
              outline: none;
              text-align: ${align};
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }

            input::placeholder {
              color: ${color};
              opacity: 0.4;
            }

            input[type='file'] {
              cursor: pointer;
              outline: none;
            }
          `}
        </style>
      </React.Fragment>
    )
  }
)

export default Input
<commit_msg>pass all props through to <input /><commit_after>import React from 'react'

import { COLORS } from '../lib/constants'

const Input = React.forwardRef(({ color = COLORS.SECONDARY, align = 'right', ...props }, ref) => (
  <React.Fragment>
    <input ref={ref} {...props} />
    <style jsx>
      {`
        input {
          width: 100%;
          font-size: 12px;
          color: ${color};
          background: transparent;
          border: none;
          outline: none;
          text-align: ${align};
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        input::placeholder {
          color: ${color};
          opacity: 0.4;
        }

        input[type='file'] {
          cursor: pointer;
          outline: none;
        }
      `}
    </style>
  </React.Fragment>
))

export default Input
<|endoftext|>


<commit_before>/*!
 * Description: Books stateless function component
 *
 * The component displaying either the books fetched or a spinner.
 * To decide which one, we checking currentStatus from the props.
 *
 *
 * Author:  Henrik Grönvall
 * File:
 * Version: 0.0.1
 * Created on 2016-10-16
 */
// Module dependencies
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

// Import the Book stateless function component
import Book from './book.js';

/**
 * Books stateless function component
 * @param books
 * @param displayMode
 * @param currentStatus
 * @returns {XML}
 * @constructor
 */
const Books = ({books,displayMode,currentStatus}) => {
  const styles = {
    container: {
      width: '100%',
    },
    spinner: {
      textAlign: 'center',
      width: '100%',
    },
  };

  // Spinner helper function
  const Spinner = () => (

  );

  // Helper function to create xml markup for the books
  const bookMarkup = () => {
    let components = null;
    let bookItems = (No items!);

    if (books.length > 0) {
      components = books.map(item => {
        if (item.volumeInfo.imageLinks) {

          // Need different keys for different display modes
          // to trigger <ReactCSSTransitionGroup> animations
          const key = displayMode === 'THUMBNAIL' ?
                                       item.id + 1 :
                                       item.id;
          bookItems = (
            <Book item={item}
              displayMode={displayMode}
              key={key} />);
        }
        return bookItems;
      });
    }
    return components;
  };

  /**
   * Render the component
   */
  return (

      { currentStatus !== 'Fetching...' ?  null : <Spinner /> }

        <ReactCSSTransitionGroup transitionName="books"
          transitionLeaveTimeout={1}
          transitionEnterTimeout={1000}>
          {bookMarkup()}
        </ReactCSSTransitionGroup>

  );
};

/**
 * Books stateless function component props
 * @type {{books: *, currentStatus: *, displayMode: *}}
 */
Books.propTypes = {
  books: React.PropTypes.array.isRequired,
  currentStatus: React.PropTypes.string.isRequired,
  displayMode: React.PropTypes.string.isRequired,
};

/**
 * Export the Books stateless function component
 */
export default Books;
<commit_msg>Updated documentation<commit_after>/*!
 * Description: Books stateless function component
 *
 * The component displaying either the books fetched or a spinner.
 * To decide which one, we checking currentStatus from the props.
 *
 * The app component hierarchy looks like this:
 *
 * App
 *  - ControlsContainer
 *   - TopicSelectorContainer
 *    - TopicSelector
 *   - DisplayModeContainer
 *    - DisplayMode
 *   - HistoryContainer
 *    - History
 *  - BooksContainer
 *   - Books (*)
 *    - Book
 *    - Book
 *    - ...
 *  - StateViewerContainer
 *
 * The component gets props from the BooksContainer component;
 * - books, array of book data.
 * - currentStatus, status of the last fetch
 * - displayMode, value indicating how the books should be rendered.
 *
 *
 * Author:  Henrik Grönvall
 * File:
 * Version: 0.0.1
 * Created on 2016-10-16
 */
// Module dependencies
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

// Import the Book stateless function component
import Book from './book.js';

/**
 * Books stateless function component
 * @param books
 * @param displayMode
 * @param currentStatus
 * @returns {XML}
 * @constructor
 */
const Books = ({books,displayMode,currentStatus}) => {
  const styles = {
    container: {
      width: '100%',
    },
    spinner: {
      textAlign: 'center',
      width: '100%',
    },
  };

  // Spinner helper function
  const Spinner = () => (

  );

  // Helper function to create xml markup for the books
  const bookMarkup = () => {
    let components = null;
    let bookItems = (No items!);

    if (books.length > 0) {
      components = books.map(item => {
        if (item.volumeInfo.imageLinks) {

          // Need different keys for different display modes
          // to trigger <ReactCSSTransitionGroup> animations
          const key = displayMode === 'THUMBNAIL' ?
                                       item.id + 1 :
                                       item.id;
          bookItems = (
            <Book item={item}
              displayMode={displayMode}
              key={key} />);
        }
        return bookItems;
      });
    }
    return components;
  };

  /**
   * Render the component
   */
  return (

      { currentStatus !== 'Fetching...' ?  null : <Spinner /> }

        <ReactCSSTransitionGroup transitionName="books"
          transitionLeaveTimeout={1}
          transitionEnterTimeout={1000}>
          {bookMarkup()}
        </ReactCSSTransitionGroup>

  );
};

/**
 * Books stateless function component props
 * @type {{books: *, currentStatus: *, displayMode: *}}
 */
Books.propTypes = {
  books: React.PropTypes.array.isRequired,
  currentStatus: React.PropTypes.string.isRequired,
  displayMode: React.PropTypes.string.isRequired,
};

/**
 * Export the Books stateless function component
 */
export default Books;
<|endoftext|>


<commit_before>function cast(target, type, data) {
    switch (arguments.length) {
        case 2:
            data = type;
            type = "default";
            break;
        case 3:
            if (!isString(type) && isString(data)) {
                var temp = type;
                type = data;
                data = temp;
            }
            break;
        case 1:
            data = target;
            target = this;
            type = "default";
            break;
        default:
            throw new Error("参数数量不正确");
    }
    if (!isObject(target)) return;

    var datakey = `cast(${type})`;
    type = `care(${type})`;
    if (target[type] instanceof Array) {
        target[type].forEach(function (listener) {
            if (listener instanceof Function) {
                listener.call(target, data, target[datakey]);
            }
        });
        target[datakey] = data;
    }
}<commit_msg>cast传参过程中新触发的传参，参数不立即传递，而是追加到队列尾部<commit_after>function cast(target, type, data) {
    switch (arguments.length) {
        case 2:
            data = type;
            type = "default";
            break;
        case 3:
            if (!isString(type) && isString(data)) {
                var temp = type;
                type = data;
                data = temp;
            }
            break;
        case 1:
            data = target;
            target = this;
            type = "default";
            break;
        default:
            throw new Error("参数数量不正确");
    }
    if (!isObject(target)) return;

    var datakey = `cast(${type})`;
    type = `care(${type})`;
    if (target[type] instanceof Array) {
        var listeners = target[type];
        if (!listeners.datas) listeners.datas = [];
        var datas = listeners.datas;
        datas.push(data);
        if (datas.length === 1) {
            while (datas.length) target[type].forEach(function (listener) {
                if (listener instanceof Function) {
                    listener.call(target, datas[0], target[datakey]);
                }
            }), target[datakey] = datas.shift();
        }
    }
}<|endoftext|>