<commit_before>import { ATTR_KEY, TEXT_CONTENT, UNDEFINED_ELEMENT, EMPTY } from '../constants';
import { hasOwnProperty, toArray, empty, toLowerCase, isString, isFunction } from '../util';
import { hook, deepHook } from '../hooks';
import { isSameNodeType } from '.';
import { isFunctionalComponent, buildFunctionalComponent } from './functional-component';
import { buildComponentFromVNode } from './component';
import { appendChildren, getAccessor, setAccessor, getNodeAttributes, getNodeType } from '../dom';
import { unmountComponent } from './component';
import { createNode, collectNode } from '../dom/recycler';

/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
 *	@param {Element} [dom=null]		A DOM node to mutate into the shape of the `vnode`
 *	@param {VNode} vnode			A VNode (with descendants forming a tree) representing the desired DOM structure
 *	@returns {Element} dom			The created/mutated element
 *	@private
 */
export default function diff(dom, vnode, context) {
	let originalAttributes = vnode.attributes;

	while (isFunctionalComponent(vnode)) {
		vnode = buildFunctionalComponent(vnode, context);
	}

	if (isFunction(vnode.nodeName)) {
		return buildComponentFromVNode(dom, vnode, context);
	}

	if (isString(vnode)) {
		if (dom) {
			let type = getNodeType(dom);
			if (type===3) {
				dom[TEXT_CONTENT] = vnode;
				return dom;
			}
			else if (type===1) {
				collectNode(dom);
			}
		}
		return document.createTextNode(vnode);
	}

	// return diffNode(dom, vnode, context);
// }

/** Morph a DOM node to look like the given VNode. Creates DOM if it doesn't exist. */
// function diffNode(dom, vnode, context) {
	let out = dom,
		nodeName = vnode.nodeName || UNDEFINED_ELEMENT;

	if (!dom) {
		out = createNode(nodeName);
	}
	else if (toLowerCase(dom.nodeName)!==nodeName) {
		out = createNode(nodeName);
		// move children into the replacement node
		appendChildren(out, toArray(dom.childNodes));
		// reclaim element nodes
		recollectNodeTree(dom);
	}

	innerDiffNode(out, vnode, context);

	if (originalAttributes && originalAttributes.ref) {
		(out[ATTR_KEY].ref = originalAttributes.ref)(out);
	}

	return out;
}

/** Apply child and attribute changes between a VNode and a DOM Node to the DOM. */
function innerDiffNode(dom, vnode, context) {
	let children,
		keyed,
		keyedLen = 0,
		len = dom.childNodes.length,
		childrenLen = 0;
	if (len) {
		children = [];
		for (let i=0; i<len; i++) {
			let child = dom.childNodes[i],
				props = child._component && child._component.props,
				key = props ? props.key : getAccessor(child, 'key');
			if (!empty(key)) {
				if (!keyed) keyed = {};
				keyed[key] = child;
				keyedLen++;
			}
			else {
				children[childrenLen++] = child;
			}
		}
	}

	let vchildren = vnode.children,
		vlen = vchildren && vchildren.length,
		min = 0;
	if (vlen) {
		for (let i=0; i<vlen; i++) {
			let vchild = vchildren[i],
				child;

			// if (isFunctionalComponent(vchild)) {
			// 	vchild = buildFunctionalComponent(vchild);
			// }

			// attempt to find a node based on key matching
			if (keyedLen) {
				let attrs = vchild.attributes,
					key = attrs && attrs.key;
				if (!empty(key) && hasOwnProperty.call(keyed, key)) {
					child = keyed[key];
					keyed[key] = null;
					keyedLen--;
				}
			}

			// attempt to pluck a node of the same type from the existing children
			if (!child && min<childrenLen) {
				for (let j=min; j<childrenLen; j++) {
					let c = children[j];
					if (c && isSameNodeType(c, vchild)) {
						child = c;
						children[j] = null;
						if (j===childrenLen-1) childrenLen--;
						if (j===min) min++;
						break;
					}
				}
			}

			// morph the matched/found/created DOM child to match vchild (deep)
			child = diff(child, vchild, context);

			if (dom.childNodes[i]!==child) {
				let c = child.parentNode!==dom && child._component,
					next = dom.childNodes[i+1];
				if (c) deepHook(c, 'componentWillMount');
				if (next) {
					dom.insertBefore(child, next);
				}
				else {
					dom.appendChild(child);
				}
				if (c) deepHook(c, 'componentDidMount');
			}
		}
	}

	if (keyedLen) {
		/*eslint guard-for-in:0*/
		for (let i in keyed) if (hasOwnProperty.call(keyed, i) && keyed[i]) {
			children[min=childrenLen++] = keyed[i];
		}
	}

	// remove orphaned children
	if (min<childrenLen) {
		removeOrphanedChildren(children);
	}

	diffAttributes(dom, vnode);
}

/** Reclaim children that were unreferenced in the desired VTree */
export function removeOrphanedChildren(children, unmountOnly) {
	for (let i=children.length; i--; ) {
		let child = children[i];
		if (child) {
			recollectNodeTree(child, unmountOnly);
		}
	}
}

/** Reclaim an entire tree of nodes, starting at the root. */
export function recollectNodeTree(node, unmountOnly) {
	// @TODO: Need to make a call on whether Preact should remove nodes not created by itself.
	// Currently it *does* remove them. Discussion: https://github.com/developit/preact/issues/39
	//if (!node[ATTR_KEY]) return;

	let attrs = node[ATTR_KEY];
	if (attrs) hook(attrs, 'ref', null);

	let component = node._component;
	if (component) {
		unmountComponent(node, component, !unmountOnly);
	}
	else {
		if (!unmountOnly) {
			if (getNodeType(node)!==1) {
				let p = node.parentNode;
				if (p) p.removeChild(node);
				return;
			}

			collectNode(node);
		}

		let c = node.childNodes;
		if (c && c.length) {
			removeOrphanedChildren(c, unmountOnly);
		}
	}
}

/** Apply differences in attributes from a VNode to the given DOM Node. */
function diffAttributes(dom, vnode) {
	let old = getNodeAttributes(dom) || EMPTY,
		attrs = vnode.attributes || EMPTY,
		name, value;

	// removed
	for (name in old) {
		if (empty(attrs[name])) {
			setAccessor(dom, name, null);
		}
	}

	// new & updated
	if (attrs!==EMPTY) {
		for (name in attrs) {
			if (hasOwnProperty.call(attrs, name)) {
				value = attrs[name];
				if (!empty(value) && value!=getAccessor(dom, name)) {
					setAccessor(dom, name, value);
				}
			}
		}
	}
}
<commit_msg>Easy to understand<commit_after>import { ATTR_KEY, TEXT_CONTENT, UNDEFINED_ELEMENT, EMPTY } from '../constants';
import { hasOwnProperty, toArray, empty, toLowerCase, isString, isFunction } from '../util';
import { hook, deepHook } from '../hooks';
import { isSameNodeType } from '.';
import { isFunctionalComponent, buildFunctionalComponent } from './functional-component';
import { buildComponentFromVNode } from './component';
import { appendChildren, getAccessor, setAccessor, getNodeAttributes, getNodeType } from '../dom';
import { unmountComponent } from './component';
import { createNode, collectNode } from '../dom/recycler';

/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
 *	@param {Element} [dom=null]		A DOM node to mutate into the shape of the `vnode`
 *	@param {VNode} vnode			A VNode (with descendants forming a tree) representing the desired DOM structure
 *	@returns {Element} dom			The created/mutated element
 *	@private
 */
export default function diff(dom, vnode, context) {
	let originalAttributes = vnode.attributes;

	while (isFunctionalComponent(vnode)) {
		vnode = buildFunctionalComponent(vnode, context);
	}

	if (isFunction(vnode.nodeName)) {
		return buildComponentFromVNode(dom, vnode, context);
	}

	if (isString(vnode)) {
		if (dom) {
			let type = getNodeType(dom);
			if (type===3) {
				dom[TEXT_CONTENT] = vnode;
				return dom;
			}
			else if (type===1) {
				collectNode(dom);
			}
		}
		return document.createTextNode(vnode);
	}

	// return diffNode(dom, vnode, context);
// }

/** Morph a DOM node to look like the given VNode. Creates DOM if it doesn't exist. */
// function diffNode(dom, vnode, context) {
	let out = dom,
		nodeName = vnode.nodeName || UNDEFINED_ELEMENT;

	if (!dom) {
		out = createNode(nodeName);
	}
	else if (toLowerCase(dom.nodeName)!==nodeName) {
		out = createNode(nodeName);
		// move children into the replacement node
		appendChildren(out, toArray(dom.childNodes));
		// reclaim element nodes
		recollectNodeTree(dom);
	}

	innerDiffNode(out, vnode, context);
	diffAttributes(out, vnode);

	if (originalAttributes && originalAttributes.ref) {
		(out[ATTR_KEY].ref = originalAttributes.ref)(out);
	}

	return out;
}

/** Apply child and attribute changes between a VNode and a DOM Node to the DOM. */
function innerDiffNode(dom, vnode, context) {
	let children,
		keyed,
		keyedLen = 0,
		len = dom.childNodes.length,
		childrenLen = 0;
	if (len) {
		children = [];
		for (let i=0; i<len; i++) {
			let child = dom.childNodes[i],
				props = child._component && child._component.props,
				key = props ? props.key : getAccessor(child, 'key');
			if (!empty(key)) {
				if (!keyed) keyed = {};
				keyed[key] = child;
				keyedLen++;
			}
			else {
				children[childrenLen++] = child;
			}
		}
	}

	let vchildren = vnode.children,
		vlen = vchildren && vchildren.length,
		min = 0;
	if (vlen) {
		for (let i=0; i<vlen; i++) {
			let vchild = vchildren[i],
				child;

			// if (isFunctionalComponent(vchild)) {
			// 	vchild = buildFunctionalComponent(vchild);
			// }

			// attempt to find a node based on key matching
			if (keyedLen) {
				let attrs = vchild.attributes,
					key = attrs && attrs.key;
				if (!empty(key) && hasOwnProperty.call(keyed, key)) {
					child = keyed[key];
					keyed[key] = null;
					keyedLen--;
				}
			}

			// attempt to pluck a node of the same type from the existing children
			if (!child && min<childrenLen) {
				for (let j=min; j<childrenLen; j++) {
					let c = children[j];
					if (c && isSameNodeType(c, vchild)) {
						child = c;
						children[j] = null;
						if (j===childrenLen-1) childrenLen--;
						if (j===min) min++;
						break;
					}
				}
			}

			// morph the matched/found/created DOM child to match vchild (deep)
			child = diff(child, vchild, context);

			if (dom.childNodes[i]!==child) {
				let c = child.parentNode!==dom && child._component,
					next = dom.childNodes[i+1];
				if (c) deepHook(c, 'componentWillMount');
				if (next) {
					dom.insertBefore(child, next);
				}
				else {
					dom.appendChild(child);
				}
				if (c) deepHook(c, 'componentDidMount');
			}
		}
	}

	if (keyedLen) {
		/*eslint guard-for-in:0*/
		for (let i in keyed) if (hasOwnProperty.call(keyed, i) && keyed[i]) {
			children[min=childrenLen++] = keyed[i];
		}
	}

	// remove orphaned children
	if (min<childrenLen) {
		removeOrphanedChildren(children);
	}
}

/** Reclaim children that were unreferenced in the desired VTree */
export function removeOrphanedChildren(children, unmountOnly) {
	for (let i=children.length; i--; ) {
		let child = children[i];
		if (child) {
			recollectNodeTree(child, unmountOnly);
		}
	}
}

/** Reclaim an entire tree of nodes, starting at the root. */
export function recollectNodeTree(node, unmountOnly) {
	// @TODO: Need to make a call on whether Preact should remove nodes not created by itself.
	// Currently it *does* remove them. Discussion: https://github.com/developit/preact/issues/39
	//if (!node[ATTR_KEY]) return;

	let attrs = node[ATTR_KEY];
	if (attrs) hook(attrs, 'ref', null);

	let component = node._component;
	if (component) {
		unmountComponent(node, component, !unmountOnly);
	}
	else {
		if (!unmountOnly) {
			if (getNodeType(node)!==1) {
				let p = node.parentNode;
				if (p) p.removeChild(node);
				return;
			}

			collectNode(node);
		}

		let c = node.childNodes;
		if (c && c.length) {
			removeOrphanedChildren(c, unmountOnly);
		}
	}
}

/** Apply differences in attributes from a VNode to the given DOM Node. */
function diffAttributes(dom, vnode) {
	let old = getNodeAttributes(dom) || EMPTY,
		attrs = vnode.attributes || EMPTY,
		name, value;

	// removed
	for (name in old) {
		if (empty(attrs[name])) {
			setAccessor(dom, name, null);
		}
	}

	// new & updated
	if (attrs!==EMPTY) {
		for (name in attrs) {
			if (hasOwnProperty.call(attrs, name)) {
				value = attrs[name];
				if (!empty(value) && value!=getAccessor(dom, name)) {
					setAccessor(dom, name, value);
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {join} from 'path'

const FIXTURE_PATH = join(__dirname, '__fixture__')

// This module exists.
const FOO_MODULE = join(FIXTURE_PATH, 'foo')

// This module does not exist.
const BAR_MODULE = join(FIXTURE_PATH, 'bar')

jest.doMock('../../paths', () => ({
  MODULES_DIR: FIXTURE_PATH,
}))

describe('Module helpers', () => {
  describe('Module exists', () => {
    describe('assertModuleExists()', () => {
      test('Do nothing', () => {
        let {assertModuleExists} = require('../../modules')
        assertModuleExists('foo')
      })
    })

    describe('Babel plugin helpers', () => {
      const OPTIONS = {a: 1, b: 2, c: 3}
      const PLUGIN = join(FIXTURE_PATH, '@babel/plugin-foo')
      const PROPOSAL = join(FIXTURE_PATH, '@babel/plugin-proposal-foo')
      const SYNTAX = join(FIXTURE_PATH, '@babel/plugin-syntax-foo')
      const TRANSFORM = join(FIXTURE_PATH, '@babel/plugin-transform-foo')

      describe('babelPlugin()', () => {
        test('Returns the full path to the plugin', () => {
          let {babelPlugin} = require('../../modules')
          expect(babelPlugin('foo')).toBe(PLUGIN)
        })

        test('Returns the path and options in a array', () => {
          let {babelPlugin} = require('../../modules')
          expect(babelPlugin('foo', OPTIONS)).toEqual([PLUGIN, OPTIONS])
        })
      })

      describe('babelProposalPlugin()', () => {
        test('Returns the full path to the plugin', () => {
          let {babelProposalPlugin} = require('../../modules')
          expect(babelProposalPlugin('foo')).toBe(PROPOSAL)
        })

        test('Returns the path and options in a array', () => {
          let {babelProposalPlugin} = require('../../modules')
          expect(babelProposalPlugin('foo', OPTIONS))
            .toEqual([PROPOSAL, OPTIONS])
        })
      })

      describe('babelSyntaxPlugin()', () => {
        test('Returns the full path to the plugin', () => {
          let {babelSyntaxPlugin} = require('../../modules')
          expect(babelSyntaxPlugin('foo')).toBe(SYNTAX)
        })

        test('Returns the path and options in a array', () => {
          let {babelSyntaxPlugin} = require('../../modules')
          expect(babelSyntaxPlugin('foo', OPTIONS)).toEqual([SYNTAX, OPTIONS])
        })
      })

      describe('babelTransformPlugin()', () => {
        test('Returns the full path to the plugin', () => {
          let {babelTransformPlugin} = require('../../modules')
          expect(babelTransformPlugin('foo')).toBe(TRANSFORM)
        })

        test('Returns the path and options in a array', () => {
          let {babelTransformPlugin} = require('../../modules')
          expect(babelTransformPlugin('foo', OPTIONS))
            .toEqual([TRANSFORM, OPTIONS])
        })
      })
    })

    describe('getBinaryPath()', () => {
      test('Returns the full path', () => {
        let {getModulePath} = require('../../modules')
        expect(getModulePath('foo')).toBe(FOO_MODULE)
      })
    })

    describe('getModulePackageJson()', () => {
      test('Returns the “package.json” from the module', () => {
        let {getModulePackageJson} = require('../../modules')
        expect(getModulePackageJson('foo')).toEqual({
          name: 'foo',
          version: 42,
        })
      })
    })

    describe('getModuleNameVersion()', () => {
      test('Returns the name and version from the module', () => {
        let {
          getModuleNameVersion,
          getModulePackageJson,
        } = require('../../modules')
        let json = getModulePackageJson('foo')
        expect(getModuleNameVersion('foo')).toEqual(`foo (v${json.version})`)
      })
    })
  })

  describe('Module does not exist', () => {
    describe('assertModuleExists()', () => {
      test('Throws an exception', () => {
        let {assertModuleExists} = require('../../modules')
        expect(() => assertModuleExists('bar')).toThrow()
      })
    })

    describe('getBinaryPath()', () => {
      test('Returns the full path', () => {
        let {getModulePath} = require('../../modules')
        expect(getModulePath('bar')).toBe(BAR_MODULE)
      })
    })
  })
})
<commit_msg>Reorganize module tests<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {join} from 'path'

const FIXTURE_PATH = join(__dirname, '__fixture__')

// This module exists.
const FOO_MODULE = join(FIXTURE_PATH, 'foo')

// This module does not exist.
const BAR_MODULE = join(FIXTURE_PATH, 'bar')

jest.doMock('../../paths', () => ({
  MODULES_DIR: FIXTURE_PATH,
}))

describe('Module helpers', () => {
  describe('Module exists', () => {
    describe('assertModuleExists()', () => {
      test('Do nothing', () => {
        let {assertModuleExists} = require('../../modules')
        assertModuleExists('foo')
      })
    })

    describe('getBinaryPath()', () => {
      test('Returns the full path', () => {
        let {getModulePath} = require('../../modules')
        expect(getModulePath('foo')).toBe(FOO_MODULE)
      })
    })

    describe('getModulePackageJson()', () => {
      test('Returns the “package.json” from the module', () => {
        let {getModulePackageJson} = require('../../modules')
        expect(getModulePackageJson('foo')).toEqual({
          name: 'foo',
          version: 42,
        })
      })
    })

    describe('getModuleNameVersion()', () => {
      test('Returns the name and version from the module', () => {
        let {
          getModuleNameVersion,
          getModulePackageJson,
        } = require('../../modules')
        let json = getModulePackageJson('foo')
        expect(getModuleNameVersion('foo')).toEqual(`foo (v${json.version})`)
      })
    })
  })

  describe('Module does not exist', () => {
    describe('assertModuleExists()', () => {
      test('Throws an exception', () => {
        let {assertModuleExists} = require('../../modules')
        expect(() => assertModuleExists('bar')).toThrow()
      })
    })

    describe('getBinaryPath()', () => {
      test('Returns the full path', () => {
        let {getModulePath} = require('../../modules')
        expect(getModulePath('bar')).toBe(BAR_MODULE)
      })
    })
  })
})

describe('Babel plugin helpers', () => {
  const OPTIONS = {a: 1, b: 2, c: 3}
  const PLUGIN = join(FIXTURE_PATH, '@babel/plugin-foo')
  const PROPOSAL = join(FIXTURE_PATH, '@babel/plugin-proposal-foo')
  const SYNTAX = join(FIXTURE_PATH, '@babel/plugin-syntax-foo')
  const TRANSFORM = join(FIXTURE_PATH, '@babel/plugin-transform-foo')

  describe('babelPlugin()', () => {
    test('Returns the full path to the plugin', () => {
      let {babelPlugin} = require('../../modules')
      expect(babelPlugin('foo')).toBe(PLUGIN)
    })

    test('Returns the path and options in a array', () => {
      let {babelPlugin} = require('../../modules')
      expect(babelPlugin('foo', OPTIONS)).toEqual([PLUGIN, OPTIONS])
    })
  })

  describe('babelProposalPlugin()', () => {
    test('Returns the full path to the plugin', () => {
      let {babelProposalPlugin} = require('../../modules')
      expect(babelProposalPlugin('foo')).toBe(PROPOSAL)
    })

    test('Returns the path and options in a array', () => {
      let {babelProposalPlugin} = require('../../modules')
      expect(babelProposalPlugin('foo', OPTIONS))
        .toEqual([PROPOSAL, OPTIONS])
    })
  })

  describe('babelSyntaxPlugin()', () => {
    test('Returns the full path to the plugin', () => {
      let {babelSyntaxPlugin} = require('../../modules')
      expect(babelSyntaxPlugin('foo')).toBe(SYNTAX)
    })

    test('Returns the path and options in a array', () => {
      let {babelSyntaxPlugin} = require('../../modules')
      expect(babelSyntaxPlugin('foo', OPTIONS)).toEqual([SYNTAX, OPTIONS])
    })
  })

  describe('babelTransformPlugin()', () => {
    test('Returns the full path to the plugin', () => {
      let {babelTransformPlugin} = require('../../modules')
      expect(babelTransformPlugin('foo')).toBe(TRANSFORM)
    })

    test('Returns the path and options in a array', () => {
      let {babelTransformPlugin} = require('../../modules')
      expect(babelTransformPlugin('foo', OPTIONS))
        .toEqual([TRANSFORM, OPTIONS])
    })
  })
})
<|endoftext|>


<commit_before>// ** I18N Afrikaans
Calendar._DN = new Array
("Sondag",
 "Maandag",
 "Dinsdag",
 "Woensdag",
 "Donderdag",
 "Vrydag",
 "Saterdag",
 "Sondag");
Calendar._MN = new Array
("Januarie",
 "Februarie",
 "Maart",
 "April",
 "Mei",
 "Junie",
 "Julie",
 "Augustus",
 "September",
 "Oktober",
 "November",
 "Desember");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Verander eerste dag van die week";
Calendar._TT["PREV_YEAR"] = "Vorige jaar (hou vir keuselys)";
Calendar._TT["PREV_MONTH"] = "Vorige maand (hou vir keuselys)";
Calendar._TT["GO_TODAY"] = "Gaan na vandag";
Calendar._TT["NEXT_MONTH"] = "Volgende maand (hou vir keuselys)";
Calendar._TT["NEXT_YEAR"] = "Volgende jaar (hou vir keuselys)";
Calendar._TT["SEL_DATE"] = "Kies datum";
Calendar._TT["DRAG_TO_MOVE"] = "Sleep om te skuif";
Calendar._TT["PART_TODAY"] = " (vandag)";
Calendar._TT["MON_FIRST"] = "Vertoon Maandag eerste";
Calendar._TT["SUN_FIRST"] = "Display Sunday first";
Calendar._TT["CLOSE"] = "Sluiten";
Calendar._TT["TODAY"] = "Vandaag";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Tijd:";<commit_msg>[ 1408960 ] fix calendar-af.js for datepicker patch provided by Latie - hirodes<commit_after>// ** I18N Afrikaans
Calendar._DN = new Array
("Sondag",
 "Maandag",
 "Dinsdag",
 "Woensdag",
 "Donderdag",
 "Vrydag",
 "Saterdag",
 "Sondag");
Calendar._MN = new Array
("Januarie",
 "Februarie",
 "Maart",
 "April",
 "Mei",
 "Junie",
 "Julie",
 "Augustus",
 "September",
 "Oktober",
 "November",
 "Desember");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Verander eerste dag van die week";
Calendar._TT["PREV_YEAR"] = "Vorige jaar (hou vir keuselys)";
Calendar._TT["PREV_MONTH"] = "Vorige maand (hou vir keuselys)";
Calendar._TT["GO_TODAY"] = "Gaan na vandag";
Calendar._TT["NEXT_MONTH"] = "Volgende maand (hou vir keuselys)";
Calendar._TT["NEXT_YEAR"] = "Volgende jaar (hou vir keuselys)";
Calendar._TT["SEL_DATE"] = "Kies datum";
Calendar._TT["DRAG_TO_MOVE"] = "Kliek en skuif";
Calendar._TT["PART_TODAY"] = " (vandag)";
Calendar._TT["MON_FIRST"] = "Vertoon Maandag eerste";
Calendar._TT["SUN_FIRST"] = "Vertoon Sondag eerste";
Calendar._TT["CLOSE"] = "Maak toe";
Calendar._TT["TODAY"] = "Vandag";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Vertoon %s eerste";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Tijd:";<|endoftext|>


<commit_before>import OpenSeadragon from 'OpenSeadragon';
import inject from '../context/inject';

export default {

    @inject('state', 'draw', 'controls', 'overlay')
    initialize(state, draw, controls, overlay, options) {
        this.overlay = overlay.initialize();
        this.state = Object.create(state).initialize();
        this.controls = controls.initialize({
            imagePath: options.imagePath,
            controls: [
                { name: 'move', action: setState.bind(null, this, state) },
                { name: 'draw', action: setState.bind(null, this, draw) }
            ]
        }).activate('move');
    window.gas = this;
        return this;
    },

    import(data) {
        this.overlay.import(data);
    },

    export() {
        return this.overlay.export();
    },

    reset() {
        return this.overlay.reset();
    }

};

function setState(annotations, state) {
    if (annotations.state) { annotations.state.close(); }
    annotations.state = Object.create(state).initialize();
}
<commit_msg>Remove a remainder<commit_after>import OpenSeadragon from 'OpenSeadragon';
import inject from '../context/inject';

export default {

    @inject('state', 'draw', 'controls', 'overlay')
    initialize(state, draw, controls, overlay, options) {
        this.overlay = overlay.initialize();
        this.state = Object.create(state).initialize();
        this.controls = controls.initialize({
            imagePath: options.imagePath,
            controls: [
                { name: 'move', action: setState.bind(null, this, state) },
                { name: 'draw', action: setState.bind(null, this, draw) }
            ]
        }).activate('move');
        return this;
    },

    import(data) {
        this.overlay.import(data);
    },

    export() {
        return this.overlay.export();
    },

    reset() {
        return this.overlay.reset();
    }

};

function setState(annotations, state) {
    if (annotations.state) { annotations.state.close(); }
    annotations.state = Object.create(state).initialize();
}
<|endoftext|>


<commit_before>import rp from 'request-promise';

const key = require('../keys/google.json');

export default async function create(options) {
  const { longURL } = options;

  const postOptions = {
    method: 'POST',
    uri: `https://www.googleapis.com/urlshortener/v1/url?key=${key.api_key}`,
    body: {
      longUrl: longURL,
    },
    json: true, // Automatically stringifies the body to JSON
  };

  return rp(postOptions);
}
<commit_msg>moving from google shortlink to bitly<commit_after>import rp from 'request-promise';

const { bitly_token } = require('../keys/google.json');

export default async function create(options) {
  const { longURL } = options;

  const postOptions = {
    method: 'POST',
    headers: {
      // eslint-disable-next-line camelcase
      Authorization: `Bearer ${bitly_token}`,
    },
    uri: `https://api-ssl.bitly.com/v4/bitlinks`,
    body: {
      long_url: longURL,
    },
    json: true, // Automatically stringifies the body to JSON
  };

  return rp(postOptions);
}
<|endoftext|>


<commit_before>/**
 * @fileoverview No inline styles defined in javascript files
 * @author Aaron Greenwald
 */

'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const rule = require('../../../lib/rules/no-inline-styles');
const RuleTester = require('eslint').RuleTester;

require('babel-eslint');

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = new RuleTester();

const tests = {

  valid: [
    {
      code: [
        'const styles = StyleSheet.create({',
        '    style1: {',
        '        color: \'red\',',
        '    },',
        '    style2: {',
        '        color: \'blue\',',
        '    }',
        '});',
        'export default class MyComponent extends Component {',
        '    static propTypes = {',
        '        isDanger: PropTypes.bool',
        '    };',
        '    render() {',
        '        return <View style={this.props.isDanger ? styles.style1 : styles.style2} />;',
        '    }',
        '}',
      ].join('\n'),
    },
    {
      code: [
        'const styles = StyleSheet.create({',
        '    style1: {',
        '        color: \'red\',',
        '    },',
        '    style2: {',
        '        color: \'blue\',',
        '    }',
        '});',
        'export default class MyComponent extends Component {',
        '    render() {',
        '        const trueColor = \'#fff\'; const falseColor = \'#000\' ',
        '        return <View ',
        '           style={[style1, ',
        '                   this.state.isDanger && styles.style1, ',
        '                   {color: someBoolean ? trueColor : falseColor }]} ',
        '                />;',
        '    }',
        '}',
      ].join('\n'),
    },
  ],
  invalid: [
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    return <Text style={{backgroundColor: \'#FFFFFF\', opacity: 0.5}}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\', opacity: 0.5 }',
      }],
    },
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    return <Text style={{backgroundColor: \'#FFFFFF\', opacity: this.state.opacity}}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    return <Text style={{opacity: this.state.opacity, height: 12}}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { height: 12 }',
      }],
    },
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    return <Text style={{marginLeft: -7, height: +12}}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { marginLeft: -7, height: 12 }',
      }],
    },
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    return <Text style={[styles.text, {backgroundColor: \'#FFFFFF\'}]}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: [
        'const Hello = React.createClass({',
        '  render: function() {',
        '    const someBoolean = false; ',
        '    return <Text style={[styles.text, someBoolean && {backgroundColor: \'#FFFFFF\'}]}>',
        '      Hello {this.props.name}',
        '     </Text>;',
        '  }',
        '});',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: [
        'const styles = StyleSheet.create({',
        '    style1: {',
        '        color: \'red\',',
        '    },',
        '    style2: {',
        '        color: \'blue\',',
        '    }',
        '});',
        'export default class MyComponent extends Component {',
        '    render() {',
        '        return <View ',
        '           style={[style1, ',
        '                   this.state.isDanger && styles.style1, ',
        '                   {backgroundColor: someBoolean ? \'#fff\' : \'#000\'}]} ',
        '                />;',
        '    }',
        '}',
      ].join('\n'),
      errors: [{
        message: 'Inline style: { backgroundColor: \'someBoolean ? \\\'#fff\\\' : \\\'#000\\\'\' }', //eslint-disable-line
      }],
    },
  ],
};

const config = {
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      classes: true,
      jsx: true,
    },
  },
};

tests.valid.forEach(t => Object.assign(t, config));
tests.invalid.forEach(t => Object.assign(t, config));

ruleTester.run('no-inline-styles', rule, tests);
<commit_msg>Rewrite no-inline-styles to use template literal syntax<commit_after>/**
 * @fileoverview No inline styles defined in javascript files
 * @author Aaron Greenwald
 */

'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const rule = require('../../../lib/rules/no-inline-styles');
const RuleTester = require('eslint').RuleTester;

require('babel-eslint');

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = new RuleTester();

const tests = {

  valid: [
    {
      code: `
        const styles = StyleSheet.create({
            style1: {
                color: 'red',
            },
            style2: {
                color: 'blue',
            }
        });
        export default class MyComponent extends Component {
            static propTypes = {
                isDanger: PropTypes.bool
            };
            render() {
                return <View style={this.props.isDanger ? styles.style1 : styles.style2} />;
            }
        }
      `,
    },
    {
      code: `
        const styles = StyleSheet.create({
            style1: {
                color: 'red',
            },
            style2: {
                color: 'blue',
            }
        });
        export default class MyComponent extends Component {
            render() {
                const trueColor = '#fff'; const falseColor = '#000'
                return <View
                   style={[style1,
                           this.state.isDanger && styles.style1,
                           {color: someBoolean ? trueColor : falseColor }]}
                        />;
            }
        }
      `,
    },
  ],
  invalid: [
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            return <Text style={{backgroundColor: '#FFFFFF', opacity: 0.5}}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\', opacity: 0.5 }',
      }],
    },
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            return <Text style={{backgroundColor: '#FFFFFF', opacity: this.state.opacity}}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            return <Text style={{opacity: this.state.opacity, height: 12}}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { height: 12 }',
      }],
    },
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            return <Text style={{marginLeft: -7, height: +12}}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { marginLeft: -7, height: 12 }',
      }],
    },
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            return <Text style={[styles.text, {backgroundColor: '#FFFFFF'}]}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: `
        const Hello = React.createClass({
          render: function() {
            const someBoolean = false;
            return <Text style={[styles.text, someBoolean && {backgroundColor: '#FFFFFF'}]}>
              Hello {this.props.name}
             </Text>;
          }
        });
      `,
      errors: [{
        message: 'Inline style: { backgroundColor: \'#FFFFFF\' }',
      }],
    },
    {
      code: `
        const styles = StyleSheet.create({
            style1: {
                color: 'red',
            },
            style2: {
                color: 'blue',
            }
        });
        export default class MyComponent extends Component {
            render() {
                return <View
                   style={[style1,
                           this.state.isDanger && styles.style1,
                           {backgroundColor: someBoolean ? '#fff' : '#000'}]}
                        />;
            }
        }
      `,
      errors: [{
        message: 'Inline style: { backgroundColor: \'someBoolean ? \\\'#fff\\\' : \\\'#000\\\'\' }', //eslint-disable-line
      }],
    },
  ],
};

const config = {
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      classes: true,
      jsx: true,
    },
  },
};

tests.valid.forEach(t => Object.assign(t, config));
tests.invalid.forEach(t => Object.assign(t, config));

ruleTester.run('no-inline-styles', rule, tests);
<|endoftext|>


<commit_before>define(['app/topology/topology.module'], function(topology) {

  topology.register.factory('TopologyRestangular', function(Restangular, ENV) {
    return Restangular.withConfig(function(RestangularConfig) {
      RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
    });
  });

  topology.register.factory('NetworkTopologySvc', function(TopologyRestangular) {
      var svc = {
          base: function() {
              return TopologyRestangular.one('restconf').one('operational').one('network-topology:network-topology');
          },
          data: null,
          TOPOLOGY_CONST: {
              HT_SERVICE_ID:"host-tracker-service:id",
              IP:"ip",
              HT_SERVICE_ATTPOINTS:"host-tracker-service:attachment-points",
              HT_SERVICE_TPID:"host-tracker-service:tp-id",
              NODE_ID:"node-id",
              SOURCE_NODE:"source-node",
              DEST_NODE:"dest-node",
              SOURCE_TP:"source-tp",
              DEST_TP:"dest-tp",
              ADDRESSES:"addresses",
              HT_SERVICE_ADDS:"host-tracker-service:addresses",
              HT_SERVICE_IP:"host-tracker-service:ip"
          }
      };
      svc.getCurrentData = function() {
          return svc.data;
      };
      svc.getAllNodes = function() {
          svc.data = svc.base().getList();
          return svc.data;
      };
      svc.getNode = function(node,cb) { // TODO Change into returning static topology
          //Determines the node id from the nodes array corresponding to the text passed
          var getNodeIdByText = function getNodeIdByText(inNodes, text) {
              var nodes = inNodes.filter(function(item, index) {
                      return item.label === text;
                  }),
                  nodeId;

              if(nodes && nodes[0]) {
                  nodeId = nodes[0].id;
              }else{
                  return null;
              }

              return nodeId;
          };
          //Checks if the edge is present in the links map or not so we show single edge link between switches
          var isEdgePresent = function(inLinks,srcId,dstId){
              if( inLinks[srcId+":"+dstId] === undefined && inLinks[dstId+":"+srcId] === undefined) {
                  return false;
              }
              else {
                  return true;
              }
          };
          return svc.base().one("topology", node).get().then(function(ntData){

              var nodes = [];
              var links = [];
              var linksMap = {};

              if(ntData.topology && ntData.topology[0]){
                  //Loop over the nodes
                  angular.forEach(ntData.topology[0].node, function(nodeData) {
                    var groupType = "", nodeTitle = "", nodeLabel = "";
                    var nodeId = nodeData[svc.TOPOLOGY_CONST.NODE_ID];
                    var level = 3;
                      if(nodeId!==undefined && nodeId.indexOf("host")>=0){
                        groupType = "host";
                        var ht_serviceadd = nodeData[svc.TOPOLOGY_CONST.ADDRESSES];
                          if(ht_serviceadd===undefined){
                              ht_serviceadd = nodeData[svc.TOPOLOGY_CONST.HT_SERVICE_ADDS];
                          }
                          if(ht_serviceadd!==undefined){
                              var ip;
                            //get title info
                            for(var i=0;i<ht_serviceadd.length;i++){
                                ip = ht_serviceadd[i][svc.TOPOLOGY_CONST.IP];
                                if(ip===undefined){
                                    ip = ht_serviceadd[i][svc.TOPOLOGY_CONST.HT_SERVICE_IP];
                                }
                                nodeTitle += 'IP: ' + ip + '
';
                            }
                          }
                        nodeTitle += 'Type: Host';
                      }
                      else{
                        groupType = "switch";
                        nodeTitle = 'Name: ' + nodeId + '
Type: Switch';
                        if (nodeId!==undefined && nodeId.indexOf("openflow:201") >= 0) {
                          level = 0;
                        } else if (nodeId!==undefined && nodeId.indexOf("openflow:202") >= 0) {
                          level = 1;
                        } else if (nodeId!==undefined && nodeId.indexOf("openflow:1") >= 0) {
                          level = 2;
                        }
                      }

                    nodeLabel = nodeData[svc.TOPOLOGY_CONST.NODE_ID];
                    nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: groupType,
                        value: 20,
                        title: nodeTitle
                    });
                  });
                  //Loops over the links
                  angular.forEach(ntData.topology[0].link, function(linkData) {
                      var srcId = getNodeIdByText(nodes, linkData.source[svc.TOPOLOGY_CONST.SOURCE_NODE]),
                          dstId = getNodeIdByText(nodes, linkData.destination[svc.TOPOLOGY_CONST.DEST_NODE]),
                          srcPort = linkData.source[svc.TOPOLOGY_CONST.SOURCE_TP],
                          dstPort = linkData.destination[svc.TOPOLOGY_CONST.DEST_TP],
                          linkId = links.length.toString();
                      if(srcId!=null && dstId!=null && !isEdgePresent(linksMap,srcId,dstId)){
                          links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Source Port: ' + srcPort + '
Dest Port: '+dstPort+''});
                          linksMap[srcId+":"+dstId]=linkId;
                      }
                  });
              }

              var nodeLabel;

              var srcId;
              var dstId;
              var linkId;

              for (var pod = 1; pod < 3; pod++) {
                for (var plane = 1; plane < 3; plane++) {
                  nodeLabel = "openflow:20" + plane.toString() + "0" + pod.toString();
                  if (getNodeIdByText(nodes, nodeLabel) == null) {
                      nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: "switch",
                        value: 20,
                        title: 'Name: ' + nodeLabel + '
Type: Switch',
                        level: plane - 1
                      });
                  }
                  srcId = getNodeIdByText(nodes, "openflow:20" + plane.toString() + "01");
                  dstId = getNodeIdByText(nodes, "openflow:20" + plane.toString() + "02");
                  if (pod == 2 && srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                  )) {
                    linkId = links.length.toString();
                    links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                    linksMap[srcId+":"+dstId]=linkId;
                  }

                  srcId = getNodeIdByText(nodes, "openflow:2010" + pod.toString());
                  dstId = getNodeIdByText(nodes, "openflow:2020" + pod.toString());

                  if (plane == 2 && srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                  )) {
                    linkId = links.length.toString();
                    links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                    linksMap[srcId+":"+dstId]=linkId;
                  }
                }
              }

              for (var pod2 = 1; pod2 < 3; pod2++) {
                for (var tor = 1; tor < 5; tor++) {
                  nodeLabel = "openflow:10" + pod2.toString() + "0" + tor.toString();
                  if (getNodeIdByText(nodes, nodeLabel) == null) {
                      nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: "switch",
                        value: 20,
                        title: 'Name: ' + nodeLabel + '
Type: Switch',
                        level: 2
                      });
                  }
                  for (var plane2 = 1; plane2 < 3; plane2++) {
                    srcId = getNodeIdByText(nodes, "openflow:10" + pod2.toString() + "0" + tor.toString());
                    dstId = getNodeIdByText(nodes, "openflow:20" + plane2.toString() + "0" + pod2.toString());
                    if (srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                    )) {
                      linkId = links.length.toString();
                      links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                      linksMap[srcId+":"+dstId]=linkId;
                    }
                  }
                }
              }

              var data = {
                  "nodes" : nodes,
                  "links" : links
              };
              cb(data);
          },function(response) {
              console.log("Error with status code", response.status);
          });
      };
      return svc;
  });

});
<commit_msg>DLUX: disabled dynamic topology<commit_after>define(['app/topology/topology.module'], function(topology) {

  topology.register.factory('TopologyRestangular', function(Restangular, ENV) {
    return Restangular.withConfig(function(RestangularConfig) {
      RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
    });
  });

  topology.register.factory('NetworkTopologySvc', function(TopologyRestangular) {
      var svc = {
          base: function() {
              return TopologyRestangular.one('restconf').one('operational').one('network-topology:network-topology');
          },
          data: null,
          TOPOLOGY_CONST: {
              HT_SERVICE_ID:"host-tracker-service:id",
              IP:"ip",
              HT_SERVICE_ATTPOINTS:"host-tracker-service:attachment-points",
              HT_SERVICE_TPID:"host-tracker-service:tp-id",
              NODE_ID:"node-id",
              SOURCE_NODE:"source-node",
              DEST_NODE:"dest-node",
              SOURCE_TP:"source-tp",
              DEST_TP:"dest-tp",
              ADDRESSES:"addresses",
              HT_SERVICE_ADDS:"host-tracker-service:addresses",
              HT_SERVICE_IP:"host-tracker-service:ip"
          }
      };
      svc.getCurrentData = function() {
          return svc.data;
      };
      svc.getAllNodes = function() {
          svc.data = svc.base().getList();
          return svc.data;
      };
      svc.getNode = function(node,cb) { // TODO Change into returning static topology
          //Determines the node id from the nodes array corresponding to the text passed
          var getNodeIdByText = function getNodeIdByText(inNodes, text) {
              var nodes = inNodes.filter(function(item, index) {
                      return item.label === text;
                  }),
                  nodeId;

              if(nodes && nodes[0]) {
                  nodeId = nodes[0].id;
              }else{
                  return null;
              }

              return nodeId;
          };
          //Checks if the edge is present in the links map or not so we show single edge link between switches
          var isEdgePresent = function(inLinks,srcId,dstId){
              if( inLinks[srcId+":"+dstId] === undefined && inLinks[dstId+":"+srcId] === undefined) {
                  return false;
              }
              else {
                  return true;
              }
          };
          return svc.base().one("topology", node).get().then(function(ntData){

              var nodes = [];
              var links = [];
              var linksMap = {};

              /*if(ntData.topology && ntData.topology[0]){
                  //Loop over the nodes
                  angular.forEach(ntData.topology[0].node, function(nodeData) {
                    var groupType = "", nodeTitle = "", nodeLabel = "";
                    var nodeId = nodeData[svc.TOPOLOGY_CONST.NODE_ID];
                    var level = 3;
                      if(nodeId!==undefined && nodeId.indexOf("host")>=0){
                        groupType = "host";
                        var ht_serviceadd = nodeData[svc.TOPOLOGY_CONST.ADDRESSES];
                          if(ht_serviceadd===undefined){
                              ht_serviceadd = nodeData[svc.TOPOLOGY_CONST.HT_SERVICE_ADDS];
                          }
                          if(ht_serviceadd!==undefined){
                              var ip;
                            //get title info
                            for(var i=0;i<ht_serviceadd.length;i++){
                                ip = ht_serviceadd[i][svc.TOPOLOGY_CONST.IP];
                                if(ip===undefined){
                                    ip = ht_serviceadd[i][svc.TOPOLOGY_CONST.HT_SERVICE_IP];
                                }
                                nodeTitle += 'IP: ' + ip + '
';
                            }
                          }
                        nodeTitle += 'Type: Host';
                      }
                      else{
                        groupType = "switch";
                        nodeTitle = 'Name: ' + nodeId + '
Type: Switch';
                        if (nodeId!==undefined && nodeId.indexOf("openflow:201") >= 0) {
                          level = 0;
                        } else if (nodeId!==undefined && nodeId.indexOf("openflow:202") >= 0) {
                          level = 1;
                        } else if (nodeId!==undefined && nodeId.indexOf("openflow:1") >= 0) {
                          level = 2;
                        }
                      }

                    nodeLabel = nodeData[svc.TOPOLOGY_CONST.NODE_ID];
                    nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: groupType,
                        value: 20,
                        title: nodeTitle
                    });
                  });
                  //Loops over the links
                  angular.forEach(ntData.topology[0].link, function(linkData) {
                      var srcId = getNodeIdByText(nodes, linkData.source[svc.TOPOLOGY_CONST.SOURCE_NODE]),
                          dstId = getNodeIdByText(nodes, linkData.destination[svc.TOPOLOGY_CONST.DEST_NODE]),
                          srcPort = linkData.source[svc.TOPOLOGY_CONST.SOURCE_TP],
                          dstPort = linkData.destination[svc.TOPOLOGY_CONST.DEST_TP],
                          linkId = links.length.toString();
                      if(srcId!=null && dstId!=null && !isEdgePresent(linksMap,srcId,dstId)){
                          links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Source Port: ' + srcPort + '
Dest Port: '+dstPort+''});
                          linksMap[srcId+":"+dstId]=linkId;
                      }
                  });
              }*/

              var nodeLabel;

              var srcId;
              var dstId;
              var linkId;

              for (var pod = 1; pod < 3; pod++) {
                for (var plane = 1; plane < 3; plane++) {
                  nodeLabel = "openflow:20" + plane.toString() + "0" + pod.toString();
                  if (getNodeIdByText(nodes, nodeLabel) == null) {
                      nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: "switch",
                        value: 20,
                        title: 'Name: ' + nodeLabel + '
Type: Switch',
                        level: plane - 1
                      });
                  }
                  srcId = getNodeIdByText(nodes, "openflow:20" + plane.toString() + "01");
                  dstId = getNodeIdByText(nodes, "openflow:20" + plane.toString() + "02");
                  if (pod == 2 && srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                  )) {
                    linkId = links.length.toString();
                    links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                    linksMap[srcId+":"+dstId]=linkId;
                  }

                  srcId = getNodeIdByText(nodes, "openflow:2010" + pod.toString());
                  dstId = getNodeIdByText(nodes, "openflow:2020" + pod.toString());

                  if (plane == 2 && srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                  )) {
                    linkId = links.length.toString();
                    links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                    linksMap[srcId+":"+dstId]=linkId;
                  }
                }
              }

              for (var pod2 = 1; pod2 < 3; pod2++) {
                for (var tor = 1; tor < 5; tor++) {
                  nodeLabel = "openflow:10" + pod2.toString() + "0" + tor.toString();
                  if (getNodeIdByText(nodes, nodeLabel) == null) {
                      nodes.push({
                        'id': nodes.length.toString(),
                        'label': nodeLabel,
                        group: "switch",
                        value: 20,
                        title: 'Name: ' + nodeLabel + '
Type: Switch',
                        level: 2
                      });
                  }
                  for (var plane2 = 1; plane2 < 3; plane2++) {
                    srcId = getNodeIdByText(nodes, "openflow:10" + pod2.toString() + "0" + tor.toString());
                    dstId = getNodeIdByText(nodes, "openflow:20" + plane2.toString() + "0" + pod2.toString());
                    if (srcId!=null && dstId!=null && !isEdgePresent(
                      linksMap,
                      srcId,
                      dstId
                    )) {
                      linkId = links.length.toString();
                      links.push({id: linkId, 'from' : srcId, 'to': dstId, title:'Placeholder link'});
                      linksMap[srcId+":"+dstId]=linkId;
                    }
                  }
                }
              }

              var data = {
                  "nodes" : nodes,
                  "links" : links
              };
              cb(data);
          },function(response) {
              console.log("Error with status code", response.status);
          });
      };
      return svc;
  });

});
<|endoftext|>


<commit_before>define([
	"Ember",
	"nwjs/nwGui",
	"nwjs/nwWindow",
	"nwjs/nwScreen"
], function(
	Ember,
	nwGui,
	nwWindow,
	nwScreen
) {

	var get = Ember.get,
	    set = Ember.setProperties,
	    debounce = Ember.run.debounce;

	var manifest = nwGui.App.manifest;

	var concat = [].concat;

	var isWin = process.platform === "win32";

	var timeEvent  = 1000,
	    timeIgnore = 2000,
	    ignore     = false;

	function deferEvent( thisArg, fn ) {
		var args = [ thisArg, fn ];
		return function() {
			// Ember.run.debounce( thisArg, fn, arguments..., time );
			debounce.apply( null, concat.apply( args, arguments ).concat( timeEvent ) );
		};
	}

	function save( params ) {
		set( this, params );
		this.save();
	}

	function onResize( width, height ) {
		if ( ignore ) { return; }
		// validate window position
		if ( !isWindowFullyVisible() ) { return; }
		save.call( this, {
			width : width,
			height: height
		});
	}

	function onMove( x, y ) {
		if ( ignore ) { return; }
		// double check: NW.js moves the window to
		// [    -8,    -8] when maximizing...
		// [-32000,-32000] when minimizing...
		if ( isWin && ( x === -8 && y === -8 || x === -32000 && x === -32000 ) ) { return; }
		// validate window position
		if ( !isWindowFullyVisible() ) { return; }
		save.call( this, {
			x: x,
			y: y
		});
	}

	function ignoreNextEvent() {
		ignore = true;
		debounce( unignoreNextEvent, timeIgnore );
	}

	function unignoreNextEvent() {
		ignore = false;
	}

	function restoreWindow() {
		var width  = get( this, "width" ),
		    height = get( this, "height" );
		if ( width !== null && height !== null ) {
			nwWindow.resizeTo( width, height );
		}

		var x = get( this, "x" ),
		    y = get( this, "y" );
		if ( x !== null && y !== null ) {
			nwWindow.moveTo( x, y );
		}
	}

	function resetWindow() {
		save.call( this, {
			width : null,
			height: null,
			x     : null,
			y     : null
		});
	}

	function resetWindowPosition() {
		// use the DE's main screen and the minimum window size
		var screen = nwScreen.screens[0].bounds;
		var w = manifest.window.width;
		var h = manifest.window.height;
		// center the window and don't forget the screen offset
		nwWindow.width  = w;
		nwWindow.height = h;
		nwWindow.x = Math.round( screen.x + ( screen.width  - w ) / 2 );
		nwWindow.y = Math.round( screen.y + ( screen.height - h ) / 2 );
		// also reset the saved window position
		resetWindow.call( this );
	}

	function onDisplayBoundsChanged() {
		// validate window position and reset if it's invalid
		if ( !isWindowFullyVisible() ) {
			resetWindowPosition.call( this );
		}
	}

	function isWindowFullyVisible() {
		var x = nwWindow.x;
		var y = nwWindow.y;
		var w = nwWindow.width;
		var h = nwWindow.height;

		// the window needs to be fully visible on one screen
		return nwScreen.screens.some(function( screenObj ) {
			var bounds = screenObj.bounds;
			// substract screen offset from window position
			var posX = x - bounds.x;
			var posY = y - bounds.y;
			// check boundaries
			return posX >= 0
				&& posY >= 0
				&& posX + w <= bounds.width
				&& posY + h <= bounds.height;
		});
	}

	Ember.Application.instanceInitializer({
		name: "window",
		after: [ "ember-data", "nwjs" ],

		initialize: function( application ) {
			var container = application.container;
			var store = container.lookup( "store:main" );

			store.find( "window" )
				.then(function( records ) {
					return records.content.length
						? records.objectAt( 0 )
						: store.createRecord( "window", { id: 1 } ).save();
				})
				.then(function( Window ) {
					// reset window
					if ( nwGui.App.fullArgv.indexOf( "--reset-window" ) >= 0 ) {
						resetWindow.call( Window );
					} else {
						restoreWindow.call( Window );
						// validate restored window position and reset if it's invalid
						if ( !isWindowFullyVisible() ) {
							resetWindowPosition.call( Window );
						}
					}

					// listen for screen changes
					nwScreen.on( "displayBoundsChanged", onDisplayBoundsChanged.bind( Window ) );

					// also listen for the maximize events
					// we don't want to save the window size+pos after these events
					nwWindow.on(   "maximize", ignoreNextEvent );
					nwWindow.on( "unmaximize", ignoreNextEvent );
					nwWindow.on(   "minimize", ignoreNextEvent );
					nwWindow.on(    "restore", ignoreNextEvent );

					// resize and move events need to be defered
					// the maximize events are triggered afterwards
					nwWindow.on( "resize", deferEvent( Window, onResize ) );
					nwWindow.on(   "move", deferEvent( Window, onMove   ) );
				});
		}
	});

});
<commit_msg>The application store is registered as a service<commit_after>define([
	"Ember",
	"nwjs/nwGui",
	"nwjs/nwWindow",
	"nwjs/nwScreen"
], function(
	Ember,
	nwGui,
	nwWindow,
	nwScreen
) {

	var get = Ember.get,
	    set = Ember.setProperties,
	    debounce = Ember.run.debounce;

	var manifest = nwGui.App.manifest;

	var concat = [].concat;

	var isWin = process.platform === "win32";

	var timeEvent  = 1000,
	    timeIgnore = 2000,
	    ignore     = false;

	function deferEvent( thisArg, fn ) {
		var args = [ thisArg, fn ];
		return function() {
			// Ember.run.debounce( thisArg, fn, arguments..., time );
			debounce.apply( null, concat.apply( args, arguments ).concat( timeEvent ) );
		};
	}

	function save( params ) {
		set( this, params );
		this.save();
	}

	function onResize( width, height ) {
		if ( ignore ) { return; }
		// validate window position
		if ( !isWindowFullyVisible() ) { return; }
		save.call( this, {
			width : width,
			height: height
		});
	}

	function onMove( x, y ) {
		if ( ignore ) { return; }
		// double check: NW.js moves the window to
		// [    -8,    -8] when maximizing...
		// [-32000,-32000] when minimizing...
		if ( isWin && ( x === -8 && y === -8 || x === -32000 && x === -32000 ) ) { return; }
		// validate window position
		if ( !isWindowFullyVisible() ) { return; }
		save.call( this, {
			x: x,
			y: y
		});
	}

	function ignoreNextEvent() {
		ignore = true;
		debounce( unignoreNextEvent, timeIgnore );
	}

	function unignoreNextEvent() {
		ignore = false;
	}

	function restoreWindow() {
		var width  = get( this, "width" ),
		    height = get( this, "height" );
		if ( width !== null && height !== null ) {
			nwWindow.resizeTo( width, height );
		}

		var x = get( this, "x" ),
		    y = get( this, "y" );
		if ( x !== null && y !== null ) {
			nwWindow.moveTo( x, y );
		}
	}

	function resetWindow() {
		save.call( this, {
			width : null,
			height: null,
			x     : null,
			y     : null
		});
	}

	function resetWindowPosition() {
		// use the DE's main screen and the minimum window size
		var screen = nwScreen.screens[0].bounds;
		var w = manifest.window.width;
		var h = manifest.window.height;
		// center the window and don't forget the screen offset
		nwWindow.width  = w;
		nwWindow.height = h;
		nwWindow.x = Math.round( screen.x + ( screen.width  - w ) / 2 );
		nwWindow.y = Math.round( screen.y + ( screen.height - h ) / 2 );
		// also reset the saved window position
		resetWindow.call( this );
	}

	function onDisplayBoundsChanged() {
		// validate window position and reset if it's invalid
		if ( !isWindowFullyVisible() ) {
			resetWindowPosition.call( this );
		}
	}

	function isWindowFullyVisible() {
		var x = nwWindow.x;
		var y = nwWindow.y;
		var w = nwWindow.width;
		var h = nwWindow.height;

		// the window needs to be fully visible on one screen
		return nwScreen.screens.some(function( screenObj ) {
			var bounds = screenObj.bounds;
			// substract screen offset from window position
			var posX = x - bounds.x;
			var posY = y - bounds.y;
			// check boundaries
			return posX >= 0
				&& posY >= 0
				&& posX + w <= bounds.width
				&& posY + h <= bounds.height;
		});
	}

	Ember.Application.instanceInitializer({
		name: "window",
		after: [ "ember-data", "nwjs" ],

		initialize: function( application ) {
			var container = application.container;
			var store = container.lookup( "service:store" );

			store.find( "window" )
				.then(function( records ) {
					return records.content.length
						? records.objectAt( 0 )
						: store.createRecord( "window", { id: 1 } ).save();
				})
				.then(function( Window ) {
					// reset window
					if ( nwGui.App.fullArgv.indexOf( "--reset-window" ) >= 0 ) {
						resetWindow.call( Window );
					} else {
						restoreWindow.call( Window );
						// validate restored window position and reset if it's invalid
						if ( !isWindowFullyVisible() ) {
							resetWindowPosition.call( Window );
						}
					}

					// listen for screen changes
					nwScreen.on( "displayBoundsChanged", onDisplayBoundsChanged.bind( Window ) );

					// also listen for the maximize events
					// we don't want to save the window size+pos after these events
					nwWindow.on(   "maximize", ignoreNextEvent );
					nwWindow.on( "unmaximize", ignoreNextEvent );
					nwWindow.on(   "minimize", ignoreNextEvent );
					nwWindow.on(    "restore", ignoreNextEvent );

					// resize and move events need to be defered
					// the maximize events are triggered afterwards
					nwWindow.on( "resize", deferEvent( Window, onResize ) );
					nwWindow.on(   "move", deferEvent( Window, onMove   ) );
				});
		}
	});

});
<|endoftext|>


<commit_before>'use strict';

angular.module('spotmop.settings', [])

/**
 * Routing
 **/
.config(function($stateProvider) {

	$stateProvider
		.state('settings', {
			url: "/settings",
			templateUrl: "app/settings/template.html"
		})
		.state('testing', {
			url: "/testing",
			templateUrl: "app/settings/testing.template.html"
		});
})

/**
 * Main controller
 **/
.controller('SettingsController', function SettingsController( $scope, $http, $rootScope, $timeout, MopidyService, SpotifyService, SettingsService, NotifyService, PusherService ){

	// load our current settings into the template
	$scope.version;
	$scope.storage = SettingsService.getSettings();
	$scope.currentSubpage = 'mopidy';
	$scope.subpageNavigate = function( subpage ){
		$scope.currentSubpage = subpage;
	};
	$scope.authorizeSpotify = function(){
		SpotifyService.authorize();
	};
    $scope.refreshSpotifyToken = function(){
		NotifyService.notify( 'Refreshing token' );
        SpotifyService.refreshToken().then( function(){});
    };
    $scope.spotifyLogout = function(){
        SpotifyService.logout();
    };
	$scope.upgradeCheck = function(){
		NotifyService.notify( 'Checking for updates' );
		SettingsService.upgradeCheck()
			.then( function(response){
				SettingsService.setSetting('version.latest', response);
				if( SettingsService.getSetting('version.installed') < response ){
					SettingsService.setSetting('version.upgradeAvailable',true);
					NotifyService.notify( 'Upgrade is available!' );
				}else{
					SettingsService.setSetting('version.upgradeAvailable',false);
					NotifyService.notify( 'You\'re already running the latest version' );
				}
			});
	}
	$scope.upgrade = function(){
		NotifyService.notify( 'Upgrade started' );
		SettingsService.upgrade()
			.then( function(response){
				if( response.status == 'error' ){
					NotifyService.error( response.message );
				}else{
					NotifyService.notify( response.message );
					SettingsService.setSetting('version.upgradeAvailable', false);
				}
			});
	}
	$scope.resetSettings = function(){
		NotifyService.notify( 'All settings reset... reloading' );
		localStorage.clear();
		location.reload();
	};

	SettingsService.getVersion()
		.then( function(response){
			if( response.status != 'error' ){
				SettingsService.setSetting('version.installed',response.currentVersion);
				SettingsService.setSetting('version.root',response.root);
			}
		});

	// save the fields to the localStorage
	// this is fired when an input field is blurred
	$scope.saveField = function( event ){
		SettingsService.setSetting( $(event.target).attr('name'), $(event.target).val() );
	};

	var oldPusherName = SettingsService.setSetting( 'pusher.name' );
	$scope.savePusherName = function( name ){

		// update our setting storage
		SettingsService.setSetting( 'pusher.name', name );
		oldPusherName = name;

		// and go tell the server to update
		PusherService.send({
			type: 'client_updated',
			data: {
				attribute: 'name',
				oldVal: oldPusherName,
				newVal: name
			}
		});
	};

    function updatePusherConnections(){
        PusherService.getConnections()
            .then( function(connections){
                $scope.pusherConnections = connections;
            });
    }

    // update whenever setup is completed, or another client opens a connection
    updatePusherConnections();
    $rootScope.$on('spotmop:pusher:client_connected', function(event, data){ updatePusherConnections(); });
    $rootScope.$on('spotmop:pusher:client_disconnected', function(event, data){ updatePusherConnections(); });
    $rootScope.$on('spotmop:pusher:client_updated', function(event, data){ updatePusherConnections(); });
})

/**
 * Testing controller
 * Accessed only by direct URL (/testing) for testing the system
 **/
.controller('TestingController', function SettingsController( $scope, $http, $rootScope, $timeout, MopidyService, SpotifyService, SettingsService, NotifyService, PusherService ){

	$scope.mopidyTest = {
			method: 'mopidy.library.browse',
			payload: '{"uri":"local:artist:md5:2cbd40f39c692153d24a3a3a5fe8c04a"}',
			run: function(){
				console.info('Testing method: '+$scope.mopidyTest.method);
				MopidyService.testMethod( $scope.mopidyTest.method, JSON.parse( $scope.mopidyTest.payload ) )
					.then( function(response){
						console.table(response);
						$scope.response = response;
					});
			}
		}

	$scope.pusherTest = {
			payload: '{"type":"notification","recipients":["'+SettingsService.getSetting('pusher.id')+'"], "data":{ "title":"Title","body":"Test notification","icon":"http://lorempixel.com/100/100/nature/"}}',
			run: function(){
				PusherService.send( JSON.parse($scope.pusherTest.payload) );
				$scope.response = {status: 'sent', payload: JSON.parse($scope.pusherTest.payload) };
			}
		}

});
<commit_msg>Handle client_changed events<commit_after>'use strict';

angular.module('spotmop.settings', [])

/**
 * Routing
 **/
.config(function($stateProvider) {

	$stateProvider
		.state('settings', {
			url: "/settings",
			templateUrl: "app/settings/template.html"
		})
		.state('testing', {
			url: "/testing",
			templateUrl: "app/settings/testing.template.html"
		});
})

/**
 * Main controller
 **/
.controller('SettingsController', function SettingsController( $scope, $http, $rootScope, $timeout, MopidyService, SpotifyService, SettingsService, NotifyService, PusherService ){

	// load our current settings into the template
	$scope.version;
	$scope.storage = SettingsService.getSettings();
	$scope.currentSubpage = 'mopidy';
	$scope.subpageNavigate = function( subpage ){
		$scope.currentSubpage = subpage;
	};
	$scope.authorizeSpotify = function(){
		SpotifyService.authorize();
	};
    $scope.refreshSpotifyToken = function(){
		NotifyService.notify( 'Refreshing token' );
        SpotifyService.refreshToken().then( function(){});
    };
    $scope.spotifyLogout = function(){
        SpotifyService.logout();
    };
	$scope.upgradeCheck = function(){
		NotifyService.notify( 'Checking for updates' );
		SettingsService.upgradeCheck()
			.then( function(response){
				SettingsService.setSetting('version.latest', response);
				if( SettingsService.getSetting('version.installed') < response ){
					SettingsService.setSetting('version.upgradeAvailable',true);
					NotifyService.notify( 'Upgrade is available!' );
				}else{
					SettingsService.setSetting('version.upgradeAvailable',false);
					NotifyService.notify( 'You\'re already running the latest version' );
				}
			});
	}
	$scope.upgrade = function(){
		NotifyService.notify( 'Upgrade started' );
		SettingsService.upgrade()
			.then( function(response){
				if( response.status == 'error' ){
					NotifyService.error( response.message );
				}else{
					NotifyService.notify( response.message );
					SettingsService.setSetting('version.upgradeAvailable', false);
				}
			});
	}
	$scope.resetSettings = function(){
		NotifyService.notify( 'All settings reset... reloading' );
		localStorage.clear();
		location.reload();
	};

	SettingsService.getVersion()
		.then( function(response){
			if( response.status != 'error' ){
				SettingsService.setSetting('version.installed',response.currentVersion);
				SettingsService.setSetting('version.root',response.root);
			}
		});

	// save the fields to the localStorage
	// this is fired when an input field is blurred
	$scope.saveField = function( event ){
		SettingsService.setSetting( $(event.target).attr('name'), $(event.target).val() );
	};

	var oldPusherName = SettingsService.getSetting( 'pusher.name' );
	$scope.savePusherName = function( name ){

		// update our setting storage
		SettingsService.setSetting( 'pusher.name', name );

		// and go tell the server to update
		PusherService.send({
			type: 'client_updated',
			data: {
				attribute: 'name',
				oldVal: oldPusherName,
				newVal: name
			}
		});

		// and now update our old one
		oldPusherName = name;
	};

    function updatePusherConnections(){
        PusherService.getConnections()
            .then( function(connections){
                $scope.pusherConnections = connections;
            });
    }

    // update whenever setup is completed, or another client opens a connection
    updatePusherConnections();
    $rootScope.$on('spotmop:pusher:client_connected', function(event, data){ updatePusherConnections(); });
    $rootScope.$on('spotmop:pusher:client_disconnected', function(event, data){ updatePusherConnections(); });
    $rootScope.$on('spotmop:pusher:client_updated', function(event, data){ updatePusherConnections(); });
})

/**
 * Testing controller
 * Accessed only by direct URL (/testing) for testing the system
 **/
.controller('TestingController', function SettingsController( $scope, $http, $rootScope, $timeout, MopidyService, SpotifyService, SettingsService, NotifyService, PusherService ){

	$scope.mopidyTest = {
			method: 'mopidy.library.browse',
			payload: '{"uri":"local:artist:md5:2cbd40f39c692153d24a3a3a5fe8c04a"}',
			run: function(){
				console.info('Testing method: '+$scope.mopidyTest.method);
				MopidyService.testMethod( $scope.mopidyTest.method, JSON.parse( $scope.mopidyTest.payload ) )
					.then( function(response){
						console.table(response);
						$scope.response = response;
					});
			}
		}

	$scope.pusherTest = {
			payload: '{"type":"notification","recipients":["'+SettingsService.getSetting('pusher.id')+'"], "data":{ "title":"Title","body":"Test notification","icon":"http://lorempixel.com/100/100/nature/"}}',
			run: function(){
				PusherService.send( JSON.parse($scope.pusherTest.payload) );
				$scope.response = {status: 'sent', payload: JSON.parse($scope.pusherTest.payload) };
			}
		}

});
<|endoftext|>


<commit_before>import $ from 'jquery';
import I18n from 'i18n-js';
import Marionette from 'backbone.marionette';
import _ from 'underscore';

import {inputView} from 'pageflow/ui';

import styles from './EditSectionTransitionEffectView.module.css';

export const EditSectionTransitionEffectView = Marionette.ItemView.extend({
  mixins: [inputView],

  template: () => `

    `,

  events: {
    'change': 'save'
  },

  ui: {
    label: 'label',
    container: ".transitions_container"
  },

  initialize: function() {
    if (!this.options.texts) {
        if (!this.options.translationKeys) {
            var translationKeyPrefix = this.options.attributeTranslationKeyPrefixes;
            this.options.translationKeys = _.map(this.options.values, function(value) {
                return translationKeyPrefix + '.transition.values.' + value;
            }, this);
        }

        this.options.texts = _.map(this.options.translationKeys, function(key) {
          return I18n.t(key);
        });
    }

    if (!this.options.groups) {
      this.options.groups = _.map(this.options.groupTanslationKeys, function(key) {
        return I18n.t(key);
      });
    }
  },

  onRender: function() {
    this.ui.label.attr('for', this.cid);
    this.appendOptions();
    this.load();
    this.listenTo(this.model, 'change:' + this.options.propertyName, this.load);
  },

  appendOptions: function () {
    _.each(this.options.values, function(value, index) {
      var option = `

A

B

                          <input type='radio' name='transitions' value='${value}' id='${value}' ${this.options.optionDisabled(value) ? 'disabled' : ''}/>
                          ${this.options.texts[index]}

                    `;
      this.ui.container.append($(option));
    }, this);
  },

  save: function() {
    var configured = {};
    _.each(this.ui.container.find('input'), function(input) {
        if ($(input).is(':checked')) {
            configured = $(input);
        }
    });
    this.model.set(this.options.propertyName, configured.attr('value'));
  },

  load: function() {
    if (!this.isClosed) {
      var value = this.model.get(this.options.propertyName);

      if (this.model.has(this.options.propertyName) &&
          this.ui.container.find('input[value=' + value +']:not([checked])').length) {

        var select = {};
        _.each(this.ui.container.find('div'), function(div) {
                if (div.classList.contains(styles[value])) {
                    select = $(div);
                }
                else {
                    $(div).context.parentElement.classList.remove(styles.active);
                }
            });
        select.context.parentElement.classList.add(styles.active);
      }
    }
  }
});
<commit_msg>Fix percy issue<commit_after>import $ from 'jquery';
import I18n from 'i18n-js';
import Marionette from 'backbone.marionette';
import _ from 'underscore';

import {inputView} from 'pageflow/ui';

import styles from './EditSectionTransitionEffectView.module.css';

export const EditSectionTransitionEffectView = Marionette.ItemView.extend({
  mixins: [inputView],

  template: () => `

    `,

  events: {
    'change': 'save'
  },

  ui: {
    label: 'label',
    container: ".transitions_container"
  },

  initialize: function() {
    if (!this.options.texts) {
        if (!this.options.translationKeys) {
            var translationKeyPrefix = this.options.attributeTranslationKeyPrefixes;
            this.options.translationKeys = _.map(this.options.values, function(value) {
                return translationKeyPrefix + '.transition.values.' + value;
            }, this);
        }

        this.options.texts = _.map(this.options.translationKeys, function(key) {
          return I18n.t(key);
        });
    }

    if (!this.options.groups) {
      this.options.groups = _.map(this.options.groupTanslationKeys, function(key) {
        return I18n.t(key);
      });
    }
  },

  onRender: function() {
    this.ui.label.attr('for', this.cid);
    this.appendOptions();
    this.load();
    this.listenTo(this.model, 'change:' + this.options.propertyName, this.load);
  },

  appendOptions: function () {
    _.each(this.options.values, function(value, index) {
      var option = `

A

B

                          <input type='radio' name='transitions' value='${value}' id='${value}' ${this.options.optionDisabled(value) ? 'disabled' : ''}/>
                          ${this.options.texts[index]}

                    `;
      this.ui.container.append($(option));
    }, this);
  },

  save: function() {
    var configured = {};
    _.each(this.ui.container.find('input'), function(input) {
        if ($(input).is(':checked')) {
            configured = $(input);
        }
    });
    this.model.set(this.options.propertyName, configured.attr('value'));
  },

  load: function() {
    if (!this.isClosed) {
      var value = this.model.get(this.options.propertyName);

      if (this.model.has(this.options.propertyName) &&
          this.ui.container.find('input[value="' + value +'"]:not([checked])').length) {

        var select = {};
        _.each(this.ui.container.find('div'), function(div) {
                if (div.classList.contains(styles[value])) {
                    select = $(div);
                }
                else {
                    $(div).context.parentElement.classList.remove(styles.active);
                }
            });
        select.context.parentElement.classList.add(styles.active);
      }
    }
  }
});
<|endoftext|>