<commit_before>import * as firebase from 'firebase';
import {
  db as firebaseDB
} from 'firebaseConfig';
import Validator from 'validator';

const defaultRef = firebaseDB.ref('data/');
const usersRef = defaultRef.child('users');

 function writeNewItem(collectionId, name, href, description ) {
     const _name = name || '';
     const _href = href || '';
     const _description = description || '';
     var itemData = {
         uid: firebase.auth().currentUser.uid,
         name: _name,
         href: _href,
         description: _description
     };

     var newItemKey = firebase.database().ref('/collections/' + collectionId + '/').child('items').push().key;

     var updates = {};
     updates['/collections/' + collectionId + '/items/' + newItemKey] = itemData;

     return firebase.database().ref().update(updates);
 }

 function writeNewCollection( items, type, description ) {
     const _items = items || [];
     if (_items.length === 0 ) {
         _items.push( 'init' );
     }
     const _type = type || '';
     const _description = description || '';
     var timestamp = new Date();
     timestamp = timestamp.getTime();
     var collectionData = {
         uid: firebase.auth().currentUser.uid,
         items: _items,
         colType: _type,
         description: _description,
         isPrivate: true,
         timestamp: timestamp,
         author: firebase.auth().currentUser.email.split('@')[0]
     };

     var newCollectionKey = firebase.database().ref().child('collections').push().key;

     var updates = {};
     updates['/collections/' + newCollectionKey] = collectionData;

     return firebase.database().ref().update(updates);
 }

 function getMyItems() {
     const myId = firebase.auth().currentUser.uid;
     const items = [];
     const query = firebase.database().ref("items").orderByChild("uid").equalTo( myId );
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     const childData = childSnapshot.val();
                     items.push({
                         key: childSnapshot.key,
                         image: childData.image,
                         href: childData.href,
                         description: childData.description,
                         rating: childData.rating
                     })
                 });
                 resolve(items);
             })
             .catch((error) => reject(error));
     });
 }

 function getMyCollections() {
     const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections").orderByChild("uid").equalTo( myId );
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description,
                                     rating: item.rating
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp
                             })
                         })
                         .catch((error) => reject(error));
                 });
                 resolve(collections);
             })
             .catch((error) => reject(error));
     });
 }

 function getCollectionByKey(key) {
     //const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections").orderByKey().equalTo(key);
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp
                             })
                         })
                         .catch((error) => reject(error));
                 });
                 resolve(collections);
             })
             .catch((error) => reject(error));
     });
 }

 function getAllCollections() {
     const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections");
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     if (childData.uid != myId && childData.isPrivate) {
                         return;
                     }
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description,
                                     rating: item.rating
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp,
                                 author: childData.author
                             })
                         })
                         .catch( (error) => reject(error) )
                 });
                 resolve(collections);
             })
             .catch( (error) => reject(error) );
     });
 }

function updateData( key , values ) {
    Validator.validateUpdateData( key, values );
    const reference = values.dataType + '/' + key;
    const ref = firebase.database().ref( reference );
    return new Promise( ( resolve, reject ) => {
        ref.once('value')
            .then( (snapshot) => {
                const keysNotFound = [];
                const update = {};
                for (let key in values) {
                    if (key === 'dataType') {
                        continue;
                    }
                    if (!snapshot.child(key).exists()) {
                        keysNotFound.push( key );
                    }
                    update[key] = values[key];
                }
                if (keysNotFound.length > 0) {
                    reject( 'Following keys: ' + keysNotFound.join(', ') + ' not found!')
                }
                ref.set(update)
                    .then( () => resolve() )
                    .catch( (error) => reject(error) );

            })
            .catch( (error) => reject(error) );
    });
}

 export {
     writeNewItem,
     writeNewCollection,
     getMyItems,
     getMyCollections,
     getAllCollections,
     updateData,
     getCollectionByKey
     };<commit_msg>updated writeNewItem<commit_after>import * as firebase from 'firebase';
import {
  db as firebaseDB
} from 'firebaseConfig';
import Validator from 'validator';

const defaultRef = firebaseDB.ref('data/');
const usersRef = defaultRef.child('users');

function writeNewItem(collectionId, name, href, description ) {
     const _name = name || '';
     const _href = href || '';
     const _description = description || '';
     var itemData = {
         uid: firebase.auth().currentUser.uid,
         name: _name,
         href: _href,
         description: _description
     };

     var newItemKey = firebase.database().ref().child('items').push().key;

     var updates = {};
     updates['/items/' + newItemKey] = itemData;

     return new Promise( ( resolve, reject ) => {
         firebase.database().ref().update(updates)
             .then( () => {
                 const collectionRef = firebase.database().ref('collections/' + collectionId );
                 collectionRef.once("value")
                     .then((snapshot) => {
                         const collection = snapshot.val();
                         collection.items.push( newItemKey );
                         collectionRef.set( collection )
                            .then( (result) => resolve(result) )
                            .catch( (error) => reject(error) );
                     })
                 .catch( (error) => reject(error) )
             })
         .catch( (error) => reject(error) );
     })
 }

function writeNewCollection( items, type, description ) {
     const _items = items || [];
     if (_items.length === 0 ) {
         _items.push( 'init' );
     }
     const _type = type || '';
     const _description = description || '';
     var timestamp = new Date();
     timestamp = timestamp.getTime();
     var collectionData = {
         uid: firebase.auth().currentUser.uid,
         items: _items,
         colType: _type,
         description: _description,
         isPrivate: true,
         timestamp: timestamp,
         author: firebase.auth().currentUser.email.split('@')[0]
     };

     var newCollectionKey = firebase.database().ref().child('collections').push().key;

     var updates = {};
     updates['/collections/' + newCollectionKey] = collectionData;

     return firebase.database().ref().update(updates);
 }

function getMyItems() {
     const myId = firebase.auth().currentUser.uid;
     const items = [];
     const query = firebase.database().ref("items").orderByChild("uid").equalTo( myId );
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     const childData = childSnapshot.val();
                     items.push({
                         key: childSnapshot.key,
                         image: childData.image,
                         href: childData.href,
                         description: childData.description,
                         rating: childData.rating
                     })
                 });
                 resolve(items);
             })
             .catch((error) => reject(error));
     });
 }

function getMyCollections() {
     const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections").orderByChild("uid").equalTo( myId );
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description,
                                     rating: item.rating
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp
                             })
                         })
                         .catch((error) => reject(error));
                 });
                 resolve(collections);
             })
             .catch((error) => reject(error));
     });
 }

function getCollectionByKey(key) {
     //const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections").orderByKey().equalTo(key);
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp
                             })
                         })
                         .catch((error) => reject(error));
                 });
                 resolve(collections);
             })
             .catch((error) => reject(error));
     });
 }

function getAllCollections() {
     const myId = firebase.auth().currentUser.uid;
     const collections = [];
     const query = firebase.database().ref("collections");
     return new Promise( (resolve, reject) => {
         query.once("value")
             .then(function (snapshot) {
                 snapshot.forEach(function (childSnapshot) {
                     var childData = childSnapshot.val();
                     if (childData.uid != myId && childData.isPrivate) {
                         return;
                     }
                     var items = [];
                     const itemPromises = [];
                     let references = childData.items;
                     if (!references) {
                         references = [];
                     }
                     for (let i = 0, len = references.length; i < len; i += 1) {
                         if (references[i] === 'init') {
                             continue;
                         }
                         const reference = "/items/" + references[i];
                         const itemPromise = firebase.database().ref(reference);
                         itemPromise.once("value").
                             then((snapshot) => {
                                 const item = snapshot.val();
                                 if (!item) {
                                     return;
                                 }
                                 items.push({
                                     key: snapshot.key,
                                     image: item.image,
                                     href: item.href,
                                     description: item.description,
                                     rating: item.rating
                                 });
                             });
                         itemPromises.push(itemPromise);
                     }
                     Promise.all(itemPromises)
                         .then(() => {
                             collections.push({
                                 key: childSnapshot.key,
                                 items: items,
                                 colType: childData.colType,
                                 description: childData.description,
                                 isPrivate: childData.isPrivate,
                                 timestamp: childData.timestamp,
                                 author: childData.author
                             })
                         })
                         .catch( (error) => reject(error) )
                 });
                 resolve(collections);
             })
             .catch( (error) => reject(error) );
     });
 }

function updateData( key , values ) {
    Validator.validateUpdateData( key, values );
    const reference = values.dataType + '/' + key;
    const ref = firebase.database().ref( reference );
    return new Promise( ( resolve, reject ) => {
        ref.once('value')
            .then( (snapshot) => {
                const keysNotFound = [];
                const update = snapshot.val();
                for (let key in values) {
                    if (key === 'dataType') {
                        continue;
                    }
                    if (!snapshot.child(key).exists()) {
                        keysNotFound.push( key );
                    }
                    update[key] = values[key];
                }
                if (keysNotFound.length > 0) {
                    reject( 'Following keys: ' + keysNotFound.join(', ') + ' not found!')
                }
                ref.set(update)
                    .then( () => resolve() )
                    .catch( (error) => reject(error) );

            })
            .catch( (error) => reject(error) );
    });
}

 export {
     writeNewItem,
     writeNewCollection,
     getMyItems,
     getMyCollections,
     getAllCollections,
     updateData,
     getCollectionByKey
     };<|endoftext|>


<commit_before>const path = require('path');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const globalConfig = require('../global-config');

module.exports = (gulp, options) => {
  const filename = path.basename(options.out);
  const filepath = path.dirname(options.out);

  let webpackOptions = {
    devtool: "source-map",
    output: {
      filename: filename,
    },
    resolve: {
      // Add '.ts' and '.tsx' as a resolvable extension.
      extensions: ['*', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
    },
    module: {
      rules: [{
        test: /\.js$/,
        loader: 'babel-loader',
        options: {
          presets: [['es2015', {modules: false}]],
          cacheDirectory: '.tmp/js',
        },
      },
        {
          loader: 'ts-loader?compiler=typescript&+useCache&+useBabel&module=common'
        }],
      // loaders: [
      //   {test: /\.ts$/, loader: 'ts-loader?compiler=typescript&+useCache&+useBabel&module=common'}
      // ]
    },
    plugins: []
  };
  if (!globalConfig.devmode) {
    webpackOptions.plugins.push(
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: false,
          drop_console: false,
        }
      })
    );
    // webpackOptions.plugins.push(filesize());
  }

  return gulp.src(options.entry)
    .pipe(webpackStream(webpackOptions, webpack))
    .pipe(gulp.dest(filepath));
};
<commit_msg>remove comments<commit_after>const path = require('path');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const globalConfig = require('../global-config');

module.exports = (gulp, options) => {
  const filename = path.basename(options.out);
  const filepath = path.dirname(options.out);

  let webpackOptions = {
    devtool: "source-map",
    output: {
      filename: filename,
    },
    resolve: {
      // Add '.ts' and '.tsx' as a resolvable extension.
      extensions: ['*', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
    },
    module: {
      rules: [{
        test: /\.js$/,
        loader: 'babel-loader',
        options: {
          presets: [['es2015', {modules: false}]],
          cacheDirectory: '.tmp/js',
        },
      },
        {
          loader: 'ts-loader?compiler=typescript&+useCache&+useBabel&module=common'
        }]
    },
    plugins: []
  };
  if (!globalConfig.devmode) {
    webpackOptions.plugins.push(
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: false,
          drop_console: false,
        }
      })
    );
  }

  return gulp.src(options.entry)
    .pipe(webpackStream(webpackOptions, webpack))
    .pipe(gulp.dest(filepath));
};
<|endoftext|>


<commit_before>/**
 changed methods from mootools
 - styleNumber: never return rounded value
 - getOffsets: never return rounded value

 license: MIT-style license.

 credits:
  - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
  - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
 */

NR.define(function(K, require){

// ---------- mootools.dimensions start ----------

var

DOC = document,
HTML = DOC.documentElement,
WIN = K.__HOST,

DOM = K.DOM,

COMPACT_ELEMENT = !DOC.compatMode || DOC.compatMode == 'CSS1Compat' ? HTML : DOC.body,

FIXED = 'fixed', STATIC = 'static', SCROLL = 'scroll',

brokenOffsetParent = function(){
	var element = document.createElement('div'),
		child = document.createElement('div'),
		ret;
	element.style.height = '0';
	element.appendChild(child);
	ret = child.offsetParent === element;
	element = child = null;

	return ret;
}(),

styleString = K.DOM.feature.curCSS;

function styleNumber(element, style){
	return parseFloat( styleString(element, style) ) || 0;
};

function borderBox(element){
	return styleString(element, '-moz-box-sizing') == 'border-box';
};

function topBorder(element){
	return styleNumber(element, 'border-top-width');
};

function leftBorder(element){
	return styleNumber(element, 'border-left-width');
};

function isBody(element){
	return (/^(?:body|html)$/i).test(element.tagName);
};

function isContainer(element){
	return element === WIN || element === DOC || (/^(?:body|html)$/i).test(element.tagName);
};

function isOffset(el){
	return styleString(el, 'position') != 'static' || isBody(el);
};

function isOffsetStatic(el){
	return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
};

function getNativeElement(el){
	return DOM(el).get(0);
};

/**
 *
 * ---------------------------------------------------------- */

function createMethod(filter, meta){
	var method = function(element){
		return filter(element) ? method.doc(getNativeElement(element)) : method.normal(getNativeElement(element));
	};

	method.doc    = meta.doc;    delete meta.doc;
	method.normal = meta.normal; delete meta.normal;

	return method;
};

var getSize = createMethod(isContainer, {
	doc: function(){
		var wrap = COMPACT_ELEMENT;
		return {
			width	: wrap.clientWidth,
			height	: wrap.clientHeight
		}
	},

	normal: function(element){
		return {
			width	: element.offsetWidth,
			height	: element.offsetHeight
		};
	}
}),

/*
// TODO:

// fix webkit scrollHeight
getScrollSize = createMethod(isContainer, {
	doc: function(element){
		var wrap 	= COMPACT_ELEMENT,
			min  	= getSize.doc(element),
			body 	= DOC.body;

		return {
			width	: Math.max(wrap.scrollWidth,  body.scrollWidth,  min.width  ),
			height	: Math.max(wrap.scrollHeight, body.scrollHeight, min.height )
		};
	},

	normal: function(element){
		return {
			width	: element.scrollWidth,
			height	: element.scrollHeight
		};
	}
}),
*/

getPosition = createMethod(isContainer, {
	doc: function(){
		return {
			left: 0,
			top: 0
		};
	},

	normal: function(element, relative){
		var offset = getOffsets(element),
			scroll = getScrolls(element);
			position = {
				left	: offset.left - scroll.left,
				top		: offset.top  - scroll.top
			};

		if (relative && (relative = document.id(relative))){
			var rel_pos = getPosition(relative);

			position.left -= rel_pos.left - leftBorder(relative);
			position.top  -= rel_pos.top  - topBorder(relative);
		}

		return position;
	}
}),

getScroll = createMethod(isContainer, {
	doc: function(){
		var win  = WIN,
			wrap = COMPACT_ELEMENT;
		return {
			left	: win.pageXOffset || wrap.scrollLeft,
			top		: win.pageYOffset || wrap.scrollTop
		};
	},

	normal: function(element){
		return {
			left	: element.scrollLeft,
			top		: element.scrollTop
		};
	}
});

function getScrolls(element){
	var left = 0,
		top = 0;

	while( (element = element.parentNode) && !isBody(element) ){
		left += element.scrollLeft;
		top  += element.scrollTop;
	}

	return {
		left	: left,
		top		: top
	}
};

function getOffsets(element){
	var position = {left: 0, top: 0},
		is_firefox = K.UA.firefox,
		walk = element,
		parent;

	if (element.getBoundingClientRect && !K.UA.ios){
		var bound = element.getBoundingClientRect(),
			html = HTML,
			htmlScroll = styleString(element, 'position') === FIXED ? {left:0, top:0} : getScroll(html),
			elemScrolls = getScrolls(element);

		return {
			left	: bound.left + elemScrolls.left + htmlScroll.left - html.clientLeft,
			top		: bound.top  + elemScrolls.top  + htmlScroll.top  - html.clientTop
		};
	}

	if (!isBody(element)){
		do {
			parent = walk.parentNode;

			position.left += walk.offsetLeft;
			position.top  += walk.offsetTop;

			if (is_firefox){
				if (!borderBox(walk)){
					position.left += leftBorder(walk);
					position.top  += topBorder(walk);
				}

				if (parent && styleString(parent, 'overflow') != 'visible'){
					position.left += leftBorder(parent);
					position.top  += topBorder(parent);
				}
			} else if (walk !== element && K.UA.safari){
				position.left += leftBorder(walk);
				position.top  += topBorder(walk);
			}

		} while( (walk = parent) && !isBody(walk) );

		if (is_firefox && !borderBox(element)){
			position.left -= leftBorder(element);
			position.top  -= topBorder(element);
		}
	}

	return position;
};

// ---------- / mootools.dimensions end ----------

return {
	// no setter
	offset: getPosition,

	/**
	 * @param {DOMElement} element
	 * @param {string=} type
	 * @returns if type === 'scroll', returns scroll size, else returns normal size
	 */
	size: function(element){
		return getSize(getNativeElement(element));
	},

	scroll: getScroll,

	offsetParent: brokenOffsetParent ?
		function(element){
			element = getNativeElement(element);

			var position = styleString(element, 'position'),
				parent = HTML,
				offsetCheck;

			if (!isBody(element) && position !== FIXED){
				offsetCheck = position === STATIC ? isOffsetStatic : isOffset;

				while ((element = element.parentNode)){
					if (offsetCheck(element)){
						parent = element;
						break;
					}
				}
			}

			return parent;
		}
	:
		function(element){
			element = getNativeElement(element);

			var parent = HTML;

			if (!isBody(element) && styleString(element, 'position') !== FIXED){
				try {
					parent = element.offsetParent;
				} catch(e) {}
			}

			return parent;
		}
};

});

/**
 change log:

 2012-09-08  Kael:
 - remove getScrollSize method

 2011-01-31  Kael:
 - all dimension methods could accept NR.DOM object;

 */
<commit_msg>dom/dimension: fix a bug when fetching offset of an element, 'parentNode' -> 'offsetParent'<commit_after>/**
 changed methods from mootools
 - styleNumber: never return rounded value
 - getOffsets: never return rounded value

 license: MIT-style license.

 credits:
  - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
  - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
 */

NR.define(function(K, require){

// ---------- mootools.dimensions start ----------

var

DOC = document,
HTML = DOC.documentElement,
WIN = K.__HOST,

DOM = K.DOM,

COMPACT_ELEMENT = !DOC.compatMode || DOC.compatMode == 'CSS1Compat' ? HTML : DOC.body,

FIXED = 'fixed', STATIC = 'static', SCROLL = 'scroll',

brokenOffsetParent = function(){
	var element = document.createElement('div'),
		child = document.createElement('div'),
		ret;
	element.style.height = '0';
	element.appendChild(child);
	ret = child.offsetParent === element;
	element = child = null;

	return ret;
}(),

styleString = K.DOM.feature.curCSS;

function styleNumber(element, style){
	return parseFloat( styleString(element, style) ) || 0;
};

function borderBox(element){
	return styleString(element, '-moz-box-sizing') == 'border-box';
};

function topBorder(element){
	return styleNumber(element, 'border-top-width');
};

function leftBorder(element){
	return styleNumber(element, 'border-left-width');
};

function isBody(element){
	return (/^(?:body|html)$/i).test(element.tagName);
};

function isContainer(element){
	return element === WIN || element === DOC || (/^(?:body|html)$/i).test(element.tagName);
};

function isOffset(el){
	return styleString(el, 'position') != 'static' || isBody(el);
};

function isOffsetStatic(el){
	return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
};

function getNativeElement(el){
	return DOM(el).get(0);
};

/**
 *
 * ---------------------------------------------------------- */

function createMethod(filter, meta){
	var method = function(element){
		return filter(element) ? method.doc(getNativeElement(element)) : method.normal(getNativeElement(element));
	};

	method.doc    = meta.doc;    delete meta.doc;
	method.normal = meta.normal; delete meta.normal;

	return method;
};

var getSize = createMethod(isContainer, {
	doc: function(){
		var wrap = COMPACT_ELEMENT;
		return {
			width	: wrap.clientWidth,
			height	: wrap.clientHeight
		}
	},

	normal: function(element){
		return {
			width	: element.offsetWidth,
			height	: element.offsetHeight
		};
	}
}),

/*
// TODO:

// fix webkit scrollHeight
getScrollSize = createMethod(isContainer, {
	doc: function(element){
		var wrap 	= COMPACT_ELEMENT,
			min  	= getSize.doc(element),
			body 	= DOC.body;

		return {
			width	: Math.max(wrap.scrollWidth,  body.scrollWidth,  min.width  ),
			height	: Math.max(wrap.scrollHeight, body.scrollHeight, min.height )
		};
	},

	normal: function(element){
		return {
			width	: element.scrollWidth,
			height	: element.scrollHeight
		};
	}
}),
*/

getPosition = createMethod(isContainer, {
	doc: function(){
		return {
			left: 0,
			top: 0
		};
	},

	normal: function(element, relative){
		var offset = getOffsets(element),
			scroll = getScrolls(element);
			position = {
				left	: offset.left - scroll.left,
				top		: offset.top  - scroll.top
			};

		if (relative && (relative = document.id(relative))){
			var rel_pos = getPosition(relative);

			position.left -= rel_pos.left - leftBorder(relative);
			position.top  -= rel_pos.top  - topBorder(relative);
		}

		return position;
	}
}),

getScroll = createMethod(isContainer, {
	doc: function(){
		var win  = WIN,
			wrap = COMPACT_ELEMENT;
		return {
			left	: win.pageXOffset || wrap.scrollLeft,
			top		: win.pageYOffset || wrap.scrollTop
		};
	},

	normal: function(element){
		return {
			left	: element.scrollLeft,
			top		: element.scrollTop
		};
	}
});

function getScrolls(element){
	var left = 0,
		top = 0;

	while( (element = element.parentNode) && !isBody(element) ){
		left += element.scrollLeft;
		top  += element.scrollTop;
	}

	return {
		left	: left,
		top		: top
	}
};

function getOffsets(element){
	var position = {left: 0, top: 0},
		is_firefox = K.UA.firefox,
		walk = element,
		parent;

	if (element.getBoundingClientRect && !K.UA.ios){
		var bound = element.getBoundingClientRect(),
			html = HTML,
			htmlScroll = styleString(element, 'position') === FIXED ? {left:0, top:0} : getScroll(html),
			elemScrolls = getScrolls(element);

		return {
			left	: bound.left + elemScrolls.left + htmlScroll.left - html.clientLeft,
			top		: bound.top  + elemScrolls.top  + htmlScroll.top  - html.clientTop
		};
	}

	if (!isBody(element)){
		do {
			parent = walk.offsetParent;

			position.left += walk.offsetLeft;
			position.top  += walk.offsetTop;

			if (is_firefox){
				if (!borderBox(walk)){
					position.left += leftBorder(walk);
					position.top  += topBorder(walk);
				}

				if (parent && styleString(parent, 'overflow') != 'visible'){
					position.left += leftBorder(parent);
					position.top  += topBorder(parent);
				}
			} else if (walk !== element && K.UA.safari){
				position.left += leftBorder(walk);
				position.top  += topBorder(walk);
			}

		} while( (walk = parent) && !isBody(walk) );

		if (is_firefox && !borderBox(element)){
			position.left -= leftBorder(element);
			position.top  -= topBorder(element);
		}
	}

	return position;
};

// ---------- / mootools.dimensions end ----------

return {
	// no setter
	offset: getPosition,

	/**
	 * @param {DOMElement} element
	 * @param {string=} type
	 * @returns if type === 'scroll', returns scroll size, else returns normal size
	 */
	size: function(element){
		return getSize(getNativeElement(element));
	},

	scroll: getScroll,

	offsetParent: brokenOffsetParent ?
		function(element){
			element = getNativeElement(element);

			var position = styleString(element, 'position'),
				parent = HTML,
				offsetCheck;

			if (!isBody(element) && position !== FIXED){
				offsetCheck = position === STATIC ? isOffsetStatic : isOffset;

				while ((element = element.parentNode)){
					if (offsetCheck(element)){
						parent = element;
						break;
					}
				}
			}

			return parent;
		}
	:
		function(element){
			element = getNativeElement(element);

			var parent = HTML;

			if (!isBody(element) && styleString(element, 'position') !== FIXED){
				try {
					parent = element.offsetParent;
				} catch(e) {}
			}

			return parent;
		}
};

});

/**
 change log:

 2012-09-08  Kael:
 - remove getScrollSize method

 2011-01-31  Kael:
 - all dimension methods could accept NR.DOM object;

 */
<|endoftext|>


<commit_before>// 75: Promise - basics
// To do: make all tests pass, leave the assert lines unchanged!

describe('a Promise represents an operation that hasn`t completed yet, but is expected in the future', function() {

  it('`Promise` is a global function', function() {
    const expectedType = '???';
    assert.equal(typeof Promise, expectedType);
  });

  describe('the constructor', function() {

    it('instantiating it without params throws', function() {
      const fn = () => { Promise }
      assert.throws(fn);
    });

    it('expects a function', function() {
      const param = null;
      assert.doesNotThrow(() => { new Promise(param); });
    });

  });

  describe('simplest promises', function() {

    it('resolve a promise by calling the `resolve` function given as first parameter', function(done) {
      let promise = new Promise((resolve) => {
      });

      promise
        .then(() => done())
        .catch(() => done(new Error('The promise is expected to resolve.')));
    });

    it('the `resolve` function can return a value, that is consumed by the `promise.then()` callback', function(done) {
      let promise = new Promise((resolve) => {
        resolve();
      });

      promise
        .then(value => {assert.equal(value, 42); done(); })
        .catch(() => done(new Error('The promise is expected to resolve.')));
    });

    it('rejecting a promise is done by calling the callback given as 2nd parameter', function(done) {
      let promise = new Promise(() => {
      });

      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });

  });

  describe('an asynchronous promise', function() {

    it('can resolve later, also by calling the first callback', function(done) {
      let promise = new Promise(() => {
        setTimeout(() => resolve(), 100);
      });

      promise
        .then(() => done())
        .catch(() => done(new Error('The promise is expected to resolve.')));
    });

    it('reject it at some later point in time, calling the 2nd callback', function(done) {
      let promise = new Promise((reject) => {
        setTimeout(() => reject(), 100);
      });

      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });

  });

  describe('test library (mocha here) support for promises', function() {

    it('just returning the promise makes the test library check that the promise resolves', function() {
      let promise = new Promise((reject, resolve) => {
        resolve();
      });

      // return the promise to mocha, it has the checking for promise resolving built in, when it receives a promise
      return promise;
    });

  });
});
<commit_msg>Make the error message better.<commit_after>// 75: Promise - basics
// To do: make all tests pass, leave the assert lines unchanged!

describe('a Promise represents an operation that hasn`t completed yet, but is expected in the future', function() {

  it('`Promise` is a global function', function() {
    const expectedType = '???';
    assert.equal(typeof Promise, expectedType);
  });

  describe('the constructor', function() {

    it('instantiating it without params throws', function() {
      const fn = () => { Promise }
      assert.throws(fn);
    });

    it('expects a function', function() {
      const param = null;
      assert.doesNotThrow(() => { new Promise(param); });
    });

  });

  describe('simplest promises', function() {

    it('resolve a promise by calling the `resolve` function given as first parameter', function(done) {
      let promise = new Promise((resolve) => {
      });

      promise
        .then(() => done())
        .catch(() => done(new Error('The promise is expected to resolve.')));
    });

    it('the `resolve` function can return a value, that is consumed by the `promise.then()` callback', function(done) {
      let promise = new Promise((resolve) => {
        resolve();
      });

      promise
        .then(value => {assert.equal(value, 42); done(); })
        .catch(() => done(new Error('The promise is expected to resolve with 42!')));
    });

    it('rejecting a promise is done by calling the callback given as 2nd parameter', function(done) {
      let promise = new Promise(() => {
      });

      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });

  });

  describe('an asynchronous promise', function() {

    it('can resolve later, also by calling the first callback', function(done) {
      let promise = new Promise(() => {
        setTimeout(() => resolve(), 100);
      });

      promise
        .then(() => done())
        .catch(() => done(new Error('The promise is expected to resolve.')));
    });

    it('reject it at some later point in time, calling the 2nd callback', function(done) {
      let promise = new Promise((reject) => {
        setTimeout(() => reject(), 100);
      });

      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });

  });

  describe('test library (mocha here) support for promises', function() {

    it('just returning the promise makes the test library check that the promise resolves', function() {
      let promise = new Promise((reject, resolve) => {
        resolve();
      });

      // return the promise to mocha, it has the checking for promise resolving built in, when it receives a promise
      return promise;
    });

  });
});
<|endoftext|>


<commit_before>import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import ReactHighcharts from 'react-highcharts'
// import Dropdown from 'react-toolbox/lib/dropdown'
// import {Button, IconButton} from 'react-toolbox/lib/button'
import { Panel, Modal, Glyphicon, Button, FormControl, HelpBlock, FormGroup, ControlLabel, Grid, Row, Col, Media } from 'react-bootstrap';

class VoteDetail extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      camp: null,
      commenters: null,
      upvoters: null,
      downvoters: null,
      showChart: false,
      showModal: false
    }
  }

  toggleModal(e){
    this.setState({
      showModal: !this.state.showModal
    })
  }

  getData() {
  var campId = this.props.campId
  axios.get(`/analytics/${campId}/${this.state.demographic}`)
    .then(function(response) {
      console.log('response from getData', response)
      var people = response.data
      let demographic = this.state.demographic
      var commentDataObj = {}
      var upvoteDataObj = {}
      var downvoteDataObj = {}
      console.log('people -----------', people)
      people.forEach(person => {
        if(!commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
          commentDataObj[person[demographic]] = 1;
        } else if(commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
          commentDataObj[person[demographic]] += 1;
        } else if(!downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
          downvoteDataObj[person[demographic]] = 1;
        } else if(downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
          downvoteDataObj[person[demographic]] += 1;
        } else if(!upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
          upvoteDataObj[person[demographic]] = 1;
        } else if(upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
          upvoteDataObj[person[demographic]] += 1;
        }
      }) //dataObj now has the count for each property - for example the number of politically centrist responders to a commonground
      console.log('dataObj -----------', commentDataObj)
      console.log('commentdataobj keys keys', Object.keys(commentDataObj))
      console.log('upvotedataObj -----------', upvoteDataObj)
      console.log('upvoteDataobj keys keys', Object.keys(upvoteDataObj))
      console.log('downvotedataObj -----------', downvoteDataObj)
      console.log('downvoteDataobj keys keys', Object.keys(downvoteDataObj))
      var commentDataArr = []
      for(let demo in commentDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = commentDataObj[demo]
        commentDataArr.push(tuple)
      }
      var upvoteDataArr = []
      for(let demo in upvoteDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = upvoteDataObj[demo]
        upvoteDataArr.push(tuple)
      }
      var downvoteDataArr = []
      for(let demo in downvoteDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = downvoteDataObj[demo]
        downvoteDataArr.push(tuple)
      }
      console.log('comment arr ~~~~~~~~~~~~~~~', commentDataArr)
      console.log('updata arr ~~~~~~~~~~~~~~~', upvoteDataArr)
      console.log('downdata arr ~~~~~~~~~~~~~~~', downvoteDataArr)
      this.setState({
        commenters: commentDataArr,
        upvoters: upvoteDataArr,
        downvoters: downvoteDataArr,
        showChart: true
      })
      console.log('this this', this)
    }.bind(this))
  }

  render() {

    return (

      <Modal bsSize="large" aria-labelledby="contained-modal-title-lg" show={this.state.showModal}>
        <Modal.Header closeButton onClick={this.toggleModal.bind(this)}>
          <Modal.Title id="contained-modal-title-lg">Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>

            <Panel header="Upvoters">
              Panel content
            </Panel>
            <Panel header="Downvoters">
              Panel content
            </Panel>

        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.toggleModal.bind(this)}>Close</Button>
        </Modal.Footer>
      </Modal>

      {this.props.children}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    campList: state.campGet.commongrounds
  }
}

export default connect(mapStateToProps)(VoteDetail)<commit_msg>Finish styling front page<commit_after>import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import ReactHighcharts from 'react-highcharts'
// import Dropdown from 'react-toolbox/lib/dropdown'
// import {Button, IconButton} from 'react-toolbox/lib/button'
import { Panel, Modal, Glyphicon, Button, FormControl, HelpBlock, FormGroup, ControlLabel, Grid, Row, Col, Media } from 'react-bootstrap';

class VoteDetail extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      camp: null,
      commenters: null,
      upvoters: null,
      downvoters: null,
      showChart: false,
      showModal: false
    }
  }

  toggleModal(e){
    this.setState({
      showModal: !this.state.showModal
    })
  }

  getData() {
  var campId = this.props.campId
  axios.get(`/analytics/${campId}/${this.state.demographic}`)
    .then(function(response) {
      console.log('response from getData', response)
      var people = response.data
      let demographic = this.state.demographic
      var commentDataObj = {}
      var upvoteDataObj = {}
      var downvoteDataObj = {}
      console.log('people -----------', people)
      people.forEach(person => {
        if(!commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
          commentDataObj[person[demographic]] = 1;
        } else if(commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
          commentDataObj[person[demographic]] += 1;
        } else if(!downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
          downvoteDataObj[person[demographic]] = 1;
        } else if(downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
          downvoteDataObj[person[demographic]] += 1;
        } else if(!upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
          upvoteDataObj[person[demographic]] = 1;
        } else if(upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
          upvoteDataObj[person[demographic]] += 1;
        }
      }) //dataObj now has the count for each property - for example the number of politically centrist responders to a commonground
      console.log('dataObj -----------', commentDataObj)
      console.log('commentdataobj keys keys', Object.keys(commentDataObj))
      console.log('upvotedataObj -----------', upvoteDataObj)
      console.log('upvoteDataobj keys keys', Object.keys(upvoteDataObj))
      console.log('downvotedataObj -----------', downvoteDataObj)
      console.log('downvoteDataobj keys keys', Object.keys(downvoteDataObj))
      var commentDataArr = []
      for(let demo in commentDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = commentDataObj[demo]
        commentDataArr.push(tuple)
      }
      var upvoteDataArr = []
      for(let demo in upvoteDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = upvoteDataObj[demo]
        upvoteDataArr.push(tuple)
      }
      var downvoteDataArr = []
      for(let demo in downvoteDataObj) {
        let tuple = []
        tuple[0] = parseInt(demo)
        tuple[1] = downvoteDataObj[demo]
        downvoteDataArr.push(tuple)
      }
      console.log('comment arr ~~~~~~~~~~~~~~~', commentDataArr)
      console.log('updata arr ~~~~~~~~~~~~~~~', upvoteDataArr)
      console.log('downdata arr ~~~~~~~~~~~~~~~', downvoteDataArr)
      this.setState({
        commenters: commentDataArr,
        upvoters: upvoteDataArr,
        downvoters: downvoteDataArr,
        showChart: true
      })
      console.log('this this', this)
    }.bind(this))
  }

  render() {

    return (

      <Modal bsSize="large" aria-labelledby="contained-modal-title-lg" show={this.state.showModal}>
        <Modal.Header closeButton onClick={this.toggleModal.bind(this)}>
          <Modal.Title id="contained-modal-title-lg">Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>

            <Panel header="Upvoters">
              COMING SOON!
            </Panel>
            <Panel header="Downvoters">
              COMING SOON!
            </Panel>

        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.toggleModal.bind(this)}>Close</Button>
        </Modal.Footer>
      </Modal>

      {this.props.children}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    campList: state.campGet.commongrounds
  }
}

export default connect(mapStateToProps)(VoteDetail)<|endoftext|>


<commit_before>JAR.register({
    MID: 'jar.async.Deferred',
    deps: ['.Promise', '..lang.Class']
}, function(Promise, Class) {
    'use strict';

	var Deferred = Class('Deferred', {
        $: {
            construct: function() {
                var deferred = this,
                    promise;

                promise = deferred._$promise = new Promise(null, true);

                deferred._$handles = this.$proxy(promise, proxiedGetPromiseHandles);
            },

            getPromise: function() {
                return this._$promise;
            },

            resolve: function(value) {
                this._$handles.resolve(value);

                return this;
            },

            reject: function(reason) {
                this._$handles.reject(reason);

                return this;
            },

            notify: function(info) {
                this._$handles.notify(info);

                return this;
            }
        },

        _$: {
            handles: null,

            promise: null
        }
    });

    function proxiedGetPromiseHandles() {
        return this._$handles;
    }

    Deferred.addDestructor(function() {
        this.reject('The Deferred: ' + this.getHash() + ' was destructed!');
    });

    return Deferred;
});<commit_msg>Fixed rejecting promise with error when destructed<commit_after>JAR.register({
    MID: 'jar.async.Deferred',
    deps: ['.Promise', '..lang.Class']
}, function(Promise, Class) {
    'use strict';

	var Deferred = Class('Deferred', {
        $: {
            construct: function() {
                var deferred = this,
                    promise;

                promise = deferred._$promise = new Promise(null, true);

                deferred._$handles = this.$proxy(promise, proxiedGetPromiseHandles);
            },

            getPromise: function() {
                return this._$promise;
            },

            resolve: function(value) {
                this._$handles.resolve(value);

                return this;
            },

            reject: function(reason) {
                this._$handles.reject(reason);

                return this;
            },

            notify: function(info) {
                this._$handles.notify(info);

                return this;
            }
        },

        _$: {
            handles: null,

            promise: null
        }
    });

    function proxiedGetPromiseHandles() {
        /*jslint validthis: true */
        return this._$handles;
    }

    Deferred.addDestructor(function() {
        this.reject(new Error('The Deferred: ' + this.getHash() + ' was destructed!'));
    });

    return Deferred;
});<|endoftext|>


<commit_before>/**
 * Element class is used to represent the object that you want to add into the DOM tree.
 * @namespace Element
 *
 * @example
 *var elem = new Element({
 *  $text:{
 *    $val:"simple div"
 *  }
 *})
 * It will be rendered in dom as a simple div element with "simple div text"
 */
"use strict";

var Observable = require( 'vjs/lib/observable' )
var derivedObservable = Observable.prototype.$generateConstructor()
var Element

var elementPrototype = new Observable( {
  $inject:require( '../events' ),
  $define: {
    $trackInstances:false,
    _$key: {
      set: function( val ) {
        var node = this._$node
        if( node ) {
          this.$setNodeKey(node, val)
        }
        this.__$key = val
      },
      get: function() {
        return this.__$key
      }
    },
    /**
     * Use remove to remove a child Element from his parent.
     * @function remove
     * @memberOf Element
     *
     * @example
     *
     * var elem = new Element({
     *  otherElement:{
     *    $css:"style"
     *  }
     *})
     * elem.otherElement.remove(); //elem.otherElement === null
     */
    remove: function( event ) {
      var node = this.$node
      var parentNode = node.parentNode
      var parent = this
      if( parentNode ) {
        parentNode.removeChild( node )
      }
      return Observable.prototype.remove.apply( this, arguments )
    },
    $generateConstructor: function() {
      return (function DerivedElement( val, event, parent, key ) {
        if( this._$node ) {
          var checkNode
          var key
          var node
          var childNodes
          var originElement

          if( parent ) {
            checkNode = parent._$node

            if( checkNode ){
              originElement = Object.getPrototypeOf( this )

              if( parent instanceof originElement._$parent._$Constructor ) {
                key = originElement._$key
                childNodes = checkNode.childNodes

                for( var i = 0, l = childNodes.length; i < l; i++ ) {
                  checkNode = childNodes[ i ]
                  if(checkNode.nodeType !== 3){
                    if( this.$getNodeKey(checkNode) === key) {
                      node = checkNode
                      break
                    }
                  }
                }
              }
            }
          }

          if(!node){
            node = this._$node.cloneNode( true )
          }

          node.$base = this
          this._$node = node
        }
        return derivedObservable.apply( this, arguments )
      })
    },

    /**
     * This returns the node element of the Element.
     * @memberOf Element
     * @type {Element}
     *
     * @example
     *
     *var elem = new Element({
     *  element:{
     *    $css:"style"
     *  }
     *})
     *
     * //This element will be a

 by default.
     *
     * console.log(element.$node) //

    */
    $node: {
      get: function() {
        var node = this._$node
        var context
        var parent
        var nextNode
        var key
        var path
        var length
        var childNodes

        if( !node ) {
          node = document.createElement( 'div' )
          node.$base = this

          if( key = this._$key ) {
            this.$setNodeKey(node, key)
          }

          this._$node = node

        } else if( context = this._$context ) {

          path = this.$path
          length = path.length
          node = context._$node
          childNodes = node.childNodes

          for( var i = length - this._$contextLevel - 1; i < length; i++ ) {
            for( var j = childNodes.length - 1; j >= 0; j-- ) {
              node = childNodes[ j ]

              if(node.nodeType !== 3){
                if( this.$getNodeKey(node) === path[ i ] ) {
                  childNodes = node.childNodes
                  break
                }
              }
            }
          }
        }
        return node
      }
    },
    $setNodeKey:function( node, key ){
      if( this.$css ){
        node.setAttribute('data-key',key)
      }else{
        node.className = key
      }
    },
    $getNodeKey:function( node ){
      if( this.$css ){
        return node.getAttribute('data-key')
      }else{
        return node.className
      }
    }
  },

  $flags: {
    /**
     * This is a $node flag, and it allows you to specify the node type that you want to create.
     * The default element will be a

     * @memberOf Element
     * @function {$node}
     *
     * @example
     *
     *var elem = new Element({
     *  $node:'section'
     *})
     *
     * //This element will be a

 by default.
     *
    */
    $node: function( node ) {

      var originalNode
      var attributes
      var attribute

      //TODO remove the old node
      if( typeof node === 'string' ) { //maybe move this to the getter
        node = document.createElement( node )
        //if there are attributes, copy these to new node
        if(originalNode = this._$node){
          attributes = originalNode.attributes
          for (var i = attributes.length - 1; i >= 0; i--) {
            attribute = attributes[i]
            node.setAttribute( attribute.nodeName, attribute.value )
          }
        }
      }

      node.$base = this
      this._$node = node
    }
  },
  $useVal: true,
  $on: {
    $addToParent:function( event, meta ) {
      if( ( this instanceof Element ) || this === elementPrototype ) {
        //TODO: maak functie voor generation
        this.$parent.$node.appendChild( this.$node )
      }
    }
  }
} )

Element = elementPrototype.$Constructor

elementPrototype.define( {
  $ChildConstructor: Element
} )

module.exports = Element
<commit_msg>Added more documentation for elements class<commit_after>/**
 * Element class is used to represent the object that you want to add into the DOM tree.
 * @namespace Element
 *
 * @example
 *var elem = new Element({
 *  $text:{
 *    $val:"simple div"
 *  }
 *})
 * It will be rendered in dom as a simple div element with "simple div text"
 */
"use strict";

var Observable = require( 'vjs/lib/observable' )
var derivedObservable = Observable.prototype.$generateConstructor()
var Element

var elementPrototype = new Observable( {
  $inject:require( '../events' ),
  $define: {
    $trackInstances:false,
    _$key: {

      set: function( val ) {
        var node = this._$node
        if( node ) {
          this.$setNodeKey(node, val)
        }
        this.__$key = val
      },
      get: function() {
        return this.__$key
      }
    },
    /**
     * Use remove to remove a child Element from his parent.
     * @function remove
     * @memberOf Element
     *
     * @example
     *
     * var elem = new Element({
     *  otherElement:{
     *    $css:"style"
     *  }
     *})
     * elem.otherElement.remove(); //elem.otherElement === null
     */
    remove: function( event ) {
      var node = this.$node
      var parentNode = node.parentNode
      var parent = this
      if( parentNode ) {
        parentNode.removeChild( node )
      }
      return Observable.prototype.remove.apply( this, arguments )
    },
    $generateConstructor: function() {
      return (function DerivedElement( val, event, parent, key ) {
        if( this._$node ) {
          var checkNode
          var key
          var node
          var childNodes
          var originElement

          if( parent ) {
            checkNode = parent._$node

            if( checkNode ){
              originElement = Object.getPrototypeOf( this )

              if( parent instanceof originElement._$parent._$Constructor ) {
                key = originElement._$key
                childNodes = checkNode.childNodes

                for( var i = 0, l = childNodes.length; i < l; i++ ) {
                  checkNode = childNodes[ i ]
                  if(checkNode.nodeType !== 3){
                    if( this.$getNodeKey(checkNode) === key) {
                      node = checkNode
                      break
                    }
                  }
                }
              }
            }
          }

          if(!node){
            node = this._$node.cloneNode( true )
          }

          node.$base = this
          this._$node = node
        }
        return derivedObservable.apply( this, arguments )
      })
    },

    /**
     * This returns the node element of the Element.
     * @memberOf Element
     * @type {Element}
     *
     * @example
     *
     *var elem = new Element({
     *  element:{
     *    $css:"style"
     *  }
     *})
     *
     * //This element will be a

 by default.
     *
     * console.log(element.$node) //

    */
    $node: {
      get: function() {
        var node = this._$node
        var context
        var parent
        var nextNode
        var key
        var path
        var length
        var childNodes

        if( !node ) {
          node = document.createElement( 'div' )
          node.$base = this

          if( key = this._$key ) {
            this.$setNodeKey(node, key)
          }

          this._$node = node

        } else if( context = this._$context ) {

          path = this.$path
          length = path.length
          node = context._$node
          childNodes = node.childNodes

          for( var i = length - this._$contextLevel - 1; i < length; i++ ) {
            for( var j = childNodes.length - 1; j >= 0; j-- ) {
              node = childNodes[ j ]

              if(node.nodeType !== 3){
                if( this.$getNodeKey(node) === path[ i ] ) {
                  childNodes = node.childNodes
                  break
                }
              }
            }
          }
        }
        return node
      }
    },
    /**
     * This internal function checks if there's a property called $css in the element, if not, it will create
     * a data-key attibute on the tag with the node $key. Otherwise it will create a class attribute with this value
     * @memberOf Element
     * @function $setNodeKey
     *
     * @example
     *
     *var elem = new Element({
     *
     *})
     *
     * app.set({
     *  userBox :new elem.$Connstructor
     * })
     *
     * //This element will be a

 by default.
     *
    */
    $setNodeKey:function( node, key ){
      if( this.$css ){
        node.setAttribute('data-key',key)
      }else{
        node.className = key
      }
    },
    $getNodeKey:function( node ){
      if( this.$css ){
        return node.getAttribute('data-key')
      }else{
        return node.className
      }
    }
  },

  $flags: {
    /**
     * This is a $node flag, and it allows you to specify the node type that you want to create.
     * The default element will be a

     * @memberOf Element
     * @function $node
     *
     * @example
     *
     *var elem = new Element({
     *  $node:'section'
     *})
     *
     * //This element will be a

 by default.
     *
    */
    $node: function( node ) {

      var originalNode
      var attributes
      var attribute

      //TODO remove the old node
      if( typeof node === 'string' ) { //maybe move this to the getter
        node = document.createElement( node )
        //if there are attributes, copy these to new node
        if(originalNode = this._$node){
          attributes = originalNode.attributes
          for (var i = attributes.length - 1; i >= 0; i--) {
            attribute = attributes[i]
            node.setAttribute( attribute.nodeName, attribute.value )
          }
        }
      }

      node.$base = this
      this._$node = node
    }
  },
  $useVal: true,
  $on: {
    $addToParent:function( event, meta ) {
      if( ( this instanceof Element ) || this === elementPrototype ) {
        //TODO: maak functie voor generation
        this.$parent.$node.appendChild( this.$node )
      }
    }
  }
} )

Element = elementPrototype.$Constructor

elementPrototype.define( {
  $ChildConstructor: Element
} )

module.exports = Element
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * 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.
 */
 /* global i18nProvider,i18nTranslatorFactory,grecaptcha,d3,textSummary */

'use strict';

$(document).ready(function() {

  var demo = {
    getTooltip : undefined // Loaded later
  };

  i18nProvider.getJson('json', 'tooltipdata',
    function(tooltipdata) {
      demo.getTooltip = i18nTranslatorFactory.createTranslator(tooltipdata);
    }
  );

  var MIN_WORDS = 100;

  var widgetId = 'vizcontainer', // Must match the ID in index.jade
    widgetWidth = 700, widgetHeight = 700, // Default width and height
    personImageUrl = 'images/app.png', // Can be blank
    language = 'en'; // language selection

  // Jquery variables
  var $content = $('.content'),
    $loading   = $('.loading'),
    $error     = $('.error'),
    $errorMsg  = $('.errorMsg'),
    $traits    = $('.traits'),
    $results   = $('.results'),
    $captcha   = $('.captcha');

  /**
   * Clear the "textArea"
   */
  $('.clear-btn').click(function(){
    $('.clear-btn').blur();
    $content.val('');
    updateWordsCount();
  });

  /**
   * Update words count on change
   */
  $content.change(updateWordsCount);

  /**
   * Update words count on copy/past
   */
  $content.bind('paste', function() {
    setTimeout(updateWordsCount, 100);
  });

  /**
   * 1. Create the request
   * 2. Call the API
   * 3. Call the methods to display the results
   */

  $('.test-btn').click(function(){

	  $.ajax({
	      headers:{
	        'csrf-token': $('meta[name="ct"]').attr('content')
	      },
	      type: 'POST',
	      data: {
	        recaptcha: recaptcha,
	        text: $content.val(),
	        language: language
	      },
	      url: '/api/profile',
	      dataType: 'json',
	      success: function(response) {
	        $loading.hide();

	        if (response.error) {
	          showError(response.error);
	        } else {
	          $results.show();
	          showTraits(response);
	          showTextSummary(response);
	          showVizualization(response);
	        }

	      }

  });

  $('.analysis-btn').click(function(){
    $('.analysis-btn').blur();

    // check if the captcha is active and the user complete it
    var recaptcha = grecaptcha.getResponse();

    // reset the captcha
    grecaptcha.reset();

    if ($captcha.css('display') === 'table' && recaptcha === '')
      return;

    $loading.show();
    $captcha.hide();
    $error.hide();
    $traits.hide();
    $results.hide();

    $.ajax({
      headers:{
        'csrf-token': $('meta[name="ct"]').attr('content')
      },
      type: 'POST',
      data: {
        recaptcha: recaptcha,
        text: $content.val(),
        language: language
      },
      url: '/api/profile',
      dataType: 'json',
      success: function(response) {
        $loading.hide();

        if (response.error) {
          showError(response.error);
        } else {
          $results.show();
          showTraits(response);
          showTextSummary(response);
          showVizualization(response);
        }

      },
      error: function(xhr) {
        $loading.hide();

        var error;
        try {
          error = JSON.parse(xhr.responseText || {});
        } catch(e) {}

        if (xhr && xhr.status === 429){
          $captcha.css('display','table');
          $('.errorMsg').css('color','black');
          error.error = 'Complete the captcha to proceed';
        } else {
          $('.errorMsg').css('color','red');
        }

        showError(error ? (error.error || error): '');
      }
    });
  });

  /**
   * Display an error or a default message
   * @param  {String} error The error
   */
  function showError(error) {
    var defaultErrorMsg = 'Error processing the request, please try again later.';
    $error.show();
    $errorMsg.text(error || defaultErrorMsg);
  }

  /**
   * Displays the traits received from the
   * Personality Insights API in a table,
   * just trait names and values.
   */
  function showTraits(data) {
    console.log('showTraits()');
    $traits.show();

    var traitList = flatten(data.tree),
      table = $traits;

    table.empty();

    // Header
    $('#header-template').clone().appendTo(table);

    // For each trait
    for (var i = 0; i < traitList.length; i++) {
      var elem = traitList[i];

      var Klass = 'row';
      Klass += (elem.title) ? ' model_title' : ' model_trait';
      Klass += (elem.value === '') ? ' model_name' : '';

      if (elem.value !== '') { // Trait child name
        $('#trait-template').clone()
          .attr('class', Klass)
          .find('.tname')
          .find('span').html(elem.id).end()
          .end()
          .find('.tvalue')
            .find('span').html(elem.value === '' ?  '' : elem.value)
            .end()
          .end()
          .appendTo(table);
      } else {
        // Model name
        $('#model-template').clone()
          .attr('class', Klass)
          .find('.col-lg-12')
          .find('span').html(elem.id).end()
          .end()
          .appendTo(table);
      }
    }
  }

  /**
   * Construct a text representation for big5 traits crossing, facets and
   * values.
   */
  function showTextSummary(data) {
    console.log('showTextSummary()');
    var paragraphs = textSummary.assemble(data.tree);
    var div = $('.summary-div');
    $('.outputMessageFootnote').text(data.word_count_message ? '**' + data.word_count_message + '.' : '');
    div.empty();
    paragraphs.forEach(function(sentences) {
      $('

').text(sentences.join(' ')).appendTo(div);
    });
  }

/**
 * Renders the sunburst visualization. The parameter is the tree as returned
 * from the Personality Insights JSON API.
 * It uses the arguments widgetId, widgetWidth, widgetHeight and personImageUrl
 * declared on top of this script.
 */
function showVizualization(theProfile) {
  console.log('showVizualization()');

  $('#' + widgetId).empty();
  var d3vis = d3.select('#' + widgetId)
      .append('svg:svg'),
    tooltip = {
      element : d3.select('body')
        .append('div')
        .classed('tooltip', true),
      target: undefined
    };
  var widget = {
    d3vis: d3vis,
    tooltip: tooltip,
    data: theProfile,
    loadingDiv: 'dummy',
    switchState: function() {
      console.log('[switchState]');
    },
    _layout: function() {
      console.log('[_layout]');
    },
    showTooltip: function(d, context, d3event) {
      if (d.id) {
        this.tooltip.target = d3event.currentTarget;
        console.debug('[showTooltip]');
        var
          tooltip = demo.getTooltip(d.id.replace('_parent', '')),
          tooltipText = d.name + ' (' + d.category + '): ' + tooltip.msg;
        console.debug(tooltipText);
        this.tooltip.element
          .text(tooltipText)
          .classed('in', true);
      }

      d3event.stopPropagation();
    },
    updateTooltipPosition: function(d3event) {
      this.tooltip.element
        .style('top', (d3event.pageY - 16) + 'px')
        .style('left', (d3event.pageX - 16) + 'px');
      d3event.stopPropagation();
    },
    hideTooltip: function () {
      console.debug('[hideTooltip]');
      this.tooltip.element
        .classed('in', false)
      ;
    },
    id: 'SystemUWidget',
    COLOR_PALLETTE: ['#1b6ba2', '#488436', '#d52829', '#F53B0C', '#972a6b', '#8c564b', '#dddddd'],
    expandAll: function() {
      this.vis.selectAll('g').each(function() {
        var g = d3.select(this);
        if (g.datum().parent && // Isn't the root g object.
          g.datum().parent.parent && // Isn't the feature trait.
          g.datum().parent.parent.parent) { // Isn't the feature dominant trait.
          g.attr('visibility', 'visible');
        }
      });
    },
    collapseAll: function() {
      this.vis.selectAll('g').each(function() {
        var g = d3.select(this);
        if (g.datum().parent !== null && // Isn't the root g object.
          g.datum().parent.parent !== null && // Isn't the feature trait.
          g.datum().parent.parent.parent !== null) { // Isn't the feature dominant trait.
          g.attr('visibility', 'hidden');
        }
      });
    },
    addPersonImage: function(url) {
      if (!this.vis || !url) {
        return;
      }
      var icon_defs = this.vis.append('defs');
      var width = this.dimW,
        height = this.dimH;

      // The flower had a radius of 640 / 1.9 = 336.84 in the original, now is 3.2.
      var radius = Math.min(width, height) / 16.58; // For 640 / 1.9 -> r = 65
      var scaled_w = radius * 2.46; // r = 65 -> w = 160

      var id = 'user_icon_' + this.id;
      icon_defs.append('pattern')
        .attr('id', id)
        .attr('height', 1)
        .attr('width', 1)
        .attr('patternUnits', 'objectBoundingBox')
        .append('image')
        .attr('width', scaled_w)
        .attr('height', scaled_w)
        .attr('x', radius - scaled_w / 2) // r = 65 -> x = -25
        .attr('y', radius - scaled_w / 2)
        .attr('xlink:href', url)
        .attr('opacity', 1.0)
        .on('dblclick.zoom', null);
      this.vis.append('circle')
        .attr('r', radius)
        .attr('stroke-width', 0)
        .attr('fill', 'url(#' + id + ')');
    }
  };

  d3vis.on("mousemove", function () {
    if (d3.event.target.tagName != 'g') {
      widget.hideTooltip();
    }
  });

  widget.dimH = widgetHeight;
  widget.dimW = widgetWidth;
  widget.d3vis.attr('width', widget.dimW).attr('height', widget.dimH);
  widget.d3vis.attr('viewBox', '0 0 ' + widget.dimW + ', ' + widget.dimH);
  renderChart.call(widget);
  widget.expandAll.call(widget);
  if (personImageUrl)
    widget.addPersonImage.call(widget, personImageUrl);
}

  /**
   * Returns a 'flattened' version of the traits tree, to display it as a list
   * @return array of {id:string, title:boolean, value:string} objects
   */
  function flatten( /*object*/ tree) {
    var arr = [],
      f = function(t, level) {
        if (!t) return;
        if (level > 0 && (!t.children || level !== 2)) {
          arr.push({
            'id': t.name,
            'title': t.children ? true : false,
            'value': (typeof (t.percentage) !== 'undefined') ? Math.floor(t.percentage * 100) + '%' : '',
            'sampling_error': (typeof (t.sampling_error) !== 'undefined') ? Math.floor(t.sampling_error * 100) + '%' : ''
          });
        }
        if (t.children && t.id !== 'sbh') {
          for (var i = 0; i < t.children.length; i++) {
            f(t.children[i], level + 1);
          }
        }
      };
    f(tree, 0);
    return arr;
  }

  function updateWordsCount() {
    var text = $content.val();
    var wordsCount = text.match(/\S+/g) ? text.match(/\S+/g).length : 0;
    $('.wordsCountFootnote').css('color',wordsCount < MIN_WORDS ? 'red' : 'gray');
    $('.wordsCount').text(wordsCount);
  }

  function onSampleTextChange() {
    var isEnglish = $('#english_radio').is(':checked');
    language = isEnglish ? 'en' : 'es';

    $.get('/text/' + language + '.txt').done(function(text) {
      $content.val(text);
      updateWordsCount();
    });
  }

  onSampleTextChange();
  $content.keyup(updateWordsCount);
  $('.sample-radio').change(onSampleTextChange);
});
<commit_msg>commented<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * 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.
 */
 /* global i18nProvider,i18nTranslatorFactory,grecaptcha,d3,textSummary */

'use strict';

$(document).ready(function() {

  var demo = {
    getTooltip : undefined // Loaded later
  };

  i18nProvider.getJson('json', 'tooltipdata',
    function(tooltipdata) {
      demo.getTooltip = i18nTranslatorFactory.createTranslator(tooltipdata);
    }
  );

  var MIN_WORDS = 100;

  var widgetId = 'vizcontainer', // Must match the ID in index.jade
    widgetWidth = 700, widgetHeight = 700, // Default width and height
    personImageUrl = 'images/app.png', // Can be blank
    language = 'en'; // language selection

  // Jquery variables
  var $content = $('.content'),
    $loading   = $('.loading'),
    $error     = $('.error'),
    $errorMsg  = $('.errorMsg'),
    $traits    = $('.traits'),
    $results   = $('.results'),
    $captcha   = $('.captcha');

  /**
   * Clear the "textArea"
   */
  $('.clear-btn').click(function(){
    $('.clear-btn').blur();
    $content.val('');
    updateWordsCount();
  });

  /**
   * Update words count on change
   */
  $content.change(updateWordsCount);

  /**
   * Update words count on copy/past
   */
  $content.bind('paste', function() {
    setTimeout(updateWordsCount, 100);
  });

  /**
   * 1. Create the request
   * 2. Call the API
   * 3. Call the methods to display the results
   */

  $('.test-btn').click(function(){

	  $.ajax({
	      headers:{
	        'csrf-token': $('meta[name="ct"]').attr('content')
	      },
	      type: 'POST',
	      data: {
	        recaptcha: recaptcha,
	        text: $content.val(),
	        language: language
	      },
	      url: '/api/profile',
	      dataType: 'json',
	      success: function(response) {
	      //  $loading.hide();

	        if (response.error) {
	          showError(response.error);
	        } else {
	          $results.show();
	          showTraits(response);
	          showTextSummary(response);
	          showVizualization(response);
	        }

	      }

  });

  $('.analysis-btn').click(function(){
    $('.analysis-btn').blur();

    // check if the captcha is active and the user complete it
    var recaptcha = grecaptcha.getResponse();

    // reset the captcha
    grecaptcha.reset();

    if ($captcha.css('display') === 'table' && recaptcha === '')
      return;

    $loading.show();
    $captcha.hide();
    $error.hide();
    $traits.hide();
    $results.hide();

    $.ajax({
      headers:{
        'csrf-token': $('meta[name="ct"]').attr('content')
      },
      type: 'POST',
      data: {
        recaptcha: recaptcha,
        text: $content.val(),
        language: language
      },
      url: '/api/profile',
      dataType: 'json',
      success: function(response) {
        $loading.hide();

        if (response.error) {
          showError(response.error);
        } else {
          $results.show();
          showTraits(response);
          showTextSummary(response);
          showVizualization(response);
        }

      },
      error: function(xhr) {
        $loading.hide();

        var error;
        try {
          error = JSON.parse(xhr.responseText || {});
        } catch(e) {}

        if (xhr && xhr.status === 429){
          $captcha.css('display','table');
          $('.errorMsg').css('color','black');
          error.error = 'Complete the captcha to proceed';
        } else {
          $('.errorMsg').css('color','red');
        }

        showError(error ? (error.error || error): '');
      }
    });
  });

  /**
   * Display an error or a default message
   * @param  {String} error The error
   */
  function showError(error) {
    var defaultErrorMsg = 'Error processing the request, please try again later.';
    $error.show();
    $errorMsg.text(error || defaultErrorMsg);
  }

  /**
   * Displays the traits received from the
   * Personality Insights API in a table,
   * just trait names and values.
   */
  function showTraits(data) {
    console.log('showTraits()');
    $traits.show();

    var traitList = flatten(data.tree),
      table = $traits;

    table.empty();

    // Header
    $('#header-template').clone().appendTo(table);

    // For each trait
    for (var i = 0; i < traitList.length; i++) {
      var elem = traitList[i];

      var Klass = 'row';
      Klass += (elem.title) ? ' model_title' : ' model_trait';
      Klass += (elem.value === '') ? ' model_name' : '';

      if (elem.value !== '') { // Trait child name
        $('#trait-template').clone()
          .attr('class', Klass)
          .find('.tname')
          .find('span').html(elem.id).end()
          .end()
          .find('.tvalue')
            .find('span').html(elem.value === '' ?  '' : elem.value)
            .end()
          .end()
          .appendTo(table);
      } else {
        // Model name
        $('#model-template').clone()
          .attr('class', Klass)
          .find('.col-lg-12')
          .find('span').html(elem.id).end()
          .end()
          .appendTo(table);
      }
    }
  }

  /**
   * Construct a text representation for big5 traits crossing, facets and
   * values.
   */
  function showTextSummary(data) {
    console.log('showTextSummary()');
    var paragraphs = textSummary.assemble(data.tree);
    var div = $('.summary-div');
    $('.outputMessageFootnote').text(data.word_count_message ? '**' + data.word_count_message + '.' : '');
    div.empty();
    paragraphs.forEach(function(sentences) {
      $('

').text(sentences.join(' ')).appendTo(div);
    });
  }

/**
 * Renders the sunburst visualization. The parameter is the tree as returned
 * from the Personality Insights JSON API.
 * It uses the arguments widgetId, widgetWidth, widgetHeight and personImageUrl
 * declared on top of this script.
 */
function showVizualization(theProfile) {
  console.log('showVizualization()');

  $('#' + widgetId).empty();
  var d3vis = d3.select('#' + widgetId)
      .append('svg:svg'),
    tooltip = {
      element : d3.select('body')
        .append('div')
        .classed('tooltip', true),
      target: undefined
    };
  var widget = {
    d3vis: d3vis,
    tooltip: tooltip,
    data: theProfile,
    loadingDiv: 'dummy',
    switchState: function() {
      console.log('[switchState]');
    },
    _layout: function() {
      console.log('[_layout]');
    },
    showTooltip: function(d, context, d3event) {
      if (d.id) {
        this.tooltip.target = d3event.currentTarget;
        console.debug('[showTooltip]');
        var
          tooltip = demo.getTooltip(d.id.replace('_parent', '')),
          tooltipText = d.name + ' (' + d.category + '): ' + tooltip.msg;
        console.debug(tooltipText);
        this.tooltip.element
          .text(tooltipText)
          .classed('in', true);
      }

      d3event.stopPropagation();
    },
    updateTooltipPosition: function(d3event) {
      this.tooltip.element
        .style('top', (d3event.pageY - 16) + 'px')
        .style('left', (d3event.pageX - 16) + 'px');
      d3event.stopPropagation();
    },
    hideTooltip: function () {
      console.debug('[hideTooltip]');
      this.tooltip.element
        .classed('in', false)
      ;
    },
    id: 'SystemUWidget',
    COLOR_PALLETTE: ['#1b6ba2', '#488436', '#d52829', '#F53B0C', '#972a6b', '#8c564b', '#dddddd'],
    expandAll: function() {
      this.vis.selectAll('g').each(function() {
        var g = d3.select(this);
        if (g.datum().parent && // Isn't the root g object.
          g.datum().parent.parent && // Isn't the feature trait.
          g.datum().parent.parent.parent) { // Isn't the feature dominant trait.
          g.attr('visibility', 'visible');
        }
      });
    },
    collapseAll: function() {
      this.vis.selectAll('g').each(function() {
        var g = d3.select(this);
        if (g.datum().parent !== null && // Isn't the root g object.
          g.datum().parent.parent !== null && // Isn't the feature trait.
          g.datum().parent.parent.parent !== null) { // Isn't the feature dominant trait.
          g.attr('visibility', 'hidden');
        }
      });
    },
    addPersonImage: function(url) {
      if (!this.vis || !url) {
        return;
      }
      var icon_defs = this.vis.append('defs');
      var width = this.dimW,
        height = this.dimH;

      // The flower had a radius of 640 / 1.9 = 336.84 in the original, now is 3.2.
      var radius = Math.min(width, height) / 16.58; // For 640 / 1.9 -> r = 65
      var scaled_w = radius * 2.46; // r = 65 -> w = 160

      var id = 'user_icon_' + this.id;
      icon_defs.append('pattern')
        .attr('id', id)
        .attr('height', 1)
        .attr('width', 1)
        .attr('patternUnits', 'objectBoundingBox')
        .append('image')
        .attr('width', scaled_w)
        .attr('height', scaled_w)
        .attr('x', radius - scaled_w / 2) // r = 65 -> x = -25
        .attr('y', radius - scaled_w / 2)
        .attr('xlink:href', url)
        .attr('opacity', 1.0)
        .on('dblclick.zoom', null);
      this.vis.append('circle')
        .attr('r', radius)
        .attr('stroke-width', 0)
        .attr('fill', 'url(#' + id + ')');
    }
  };

  d3vis.on("mousemove", function () {
    if (d3.event.target.tagName != 'g') {
      widget.hideTooltip();
    }
  });

  widget.dimH = widgetHeight;
  widget.dimW = widgetWidth;
  widget.d3vis.attr('width', widget.dimW).attr('height', widget.dimH);
  widget.d3vis.attr('viewBox', '0 0 ' + widget.dimW + ', ' + widget.dimH);
  renderChart.call(widget);
  widget.expandAll.call(widget);
  if (personImageUrl)
    widget.addPersonImage.call(widget, personImageUrl);
}

  /**
   * Returns a 'flattened' version of the traits tree, to display it as a list
   * @return array of {id:string, title:boolean, value:string} objects
   */
  function flatten( /*object*/ tree) {
    var arr = [],
      f = function(t, level) {
        if (!t) return;
        if (level > 0 && (!t.children || level !== 2)) {
          arr.push({
            'id': t.name,
            'title': t.children ? true : false,
            'value': (typeof (t.percentage) !== 'undefined') ? Math.floor(t.percentage * 100) + '%' : '',
            'sampling_error': (typeof (t.sampling_error) !== 'undefined') ? Math.floor(t.sampling_error * 100) + '%' : ''
          });
        }
        if (t.children && t.id !== 'sbh') {
          for (var i = 0; i < t.children.length; i++) {
            f(t.children[i], level + 1);
          }
        }
      };
    f(tree, 0);
    return arr;
  }

  function updateWordsCount() {
    var text = $content.val();
    var wordsCount = text.match(/\S+/g) ? text.match(/\S+/g).length : 0;
    $('.wordsCountFootnote').css('color',wordsCount < MIN_WORDS ? 'red' : 'gray');
    $('.wordsCount').text(wordsCount);
  }

  function onSampleTextChange() {
    var isEnglish = $('#english_radio').is(':checked');
    language = isEnglish ? 'en' : 'es';

    $.get('/text/' + language + '.txt').done(function(text) {
      $content.val(text);
      updateWordsCount();
    });
  }

  onSampleTextChange();
  $content.keyup(updateWordsCount);
  $('.sample-radio').change(onSampleTextChange);
});
<|endoftext|>


<commit_before>$(function () {
    var query = getQuery(["q", "t", "a", "d"]);

    var targets;
    switch (query.key) {
        case "t":
            targets = ["tags"];
            break;
        case "a":
            targets = ["author"];
            break;
        case "d":
            targets = ["date"];
            break;
        case "q":
        default:
            targets = ["title", "tags", "author", "url", "date", "content"];
            break;
    }
    showPosts(query.words, targets);

    if (query.key == "q") {
        $("#search").val(query.query).focus();
    }
});

function getQuery(keys)
{
    var query = "";
    var key = "";
    var words = [];

    keys.forEach(function (queryKey) {
        var regex = RegExp("[?&]" + queryKey + "=([^&]+)", 'i');
        var matched;
        if (matched = window.location.search.match(regex)) {
            query = decodeURIComponent(matched[1]).replace(/(　| )+/g, ' ');
            words = query.split('+');
            key = queryKey;
            return false;  // break;
        }
        return true;  // continue;
    });

    return { query: query, key: key, words: words };
}

function showPosts(words, targets)
{
    var getJson = function () {

        var dfd = $.Deferred();
        $.ajax({
            url: baseurl + "/assets/lib/search.json",
            dataType: "json",
            timeout: 3000,  // 3 sec
            success: function (posts) {
                var matchedPosts = [];
                posts.forEach(function (post) {

                    // concatenate target fields as a string.
                    var searchee = "";
                    for (var i = 0; i < targets.length; i++) {
                        var target = post[targets[i]];
                        var targetString = "";
                        if (target instanceof Array) {
                            for (var j = 0; j < target.length; j++) {
                                targetString += target[j];
                            }
                        } else if (typeof target == "object") {
                            for (key in target) {
                                targetString += target[key];
                            }
                        } else {
                            targetString = target;
                        }
                        searchee += targetString;
                    }

                    // matching.
                    var matched = false;
                    words.forEach(function (word) {
                        var regex = new RegExp(word, 'i');
                        if (searchee.match(regex) != null) {
                            matched = true;
                            return false;  // break;
                        }
                        return true;  // continue;
                    });

                    if (matched) {
                        matchedPosts.push(post);
                    }
                });

                dfd.resolve(matchedPosts);
            }
        });

        return dfd.promise();
    };

    getJson().then(function (matchedPosts) {
        matchedPosts.forEach(function (post) {
            $("#search-results").find("#" + post.id).show();
        });
    });
}
<commit_msg>fix logical error with searching<commit_after>$(function () {
    var query = getQuery(["q", "t", "a", "d"]);

    var targets;
    switch (query.key) {
        case "t":
            targets = ["tags"];
            break;
        case "a":
            targets = ["author"];
            break;
        case "d":
            targets = ["date"];
            break;
        case "q":
        default:
            targets = ["title", "tags", "author", "url", "date", "content"];
            break;
    }
    showPosts(query.words, targets);

    if (query.key == "q") {
        $("#search").val(query.query).focus();
    }
});

function getQuery(keys)
{
    var query = "";
    var key = "";
    var words = [];

    keys.forEach(function (queryKey) {
        var regex = RegExp("[?&]" + queryKey + "=([^&]+)", 'i');
        var matched;
        if (matched = window.location.search.match(regex)) {
            query = decodeURIComponent(matched[1]).replace(/(　| )+/g, ' ');
            words = query.split('+');
            key = queryKey;
            return false;  // break;
        }
        return true;  // continue;
    });

    return { query: query, key: key, words: words };
}

function showPosts(words, targets)
{
    var getJson = function () {

        var dfd = $.Deferred();
        $.ajax({
            url: baseurl + "/assets/lib/search.json",
            dataType: "json",
            timeout: 3000,  // 3 sec
            success: function (posts) {
                var matchedPosts = [];
                posts.forEach(function (post) {

                    // concatenate target fields as a string.
                    var searchee = "";
                    for (var i = 0; i < targets.length; i++) {
                        var target = post[targets[i]];
                        var targetString = "";
                        if (target instanceof Array) {
                            for (var j = 0; j < target.length; j++) {
                                targetString += target[j];
                            }
                        } else if (typeof target == "object") {
                            for (key in target) {
                                targetString += target[key];
                            }
                        } else {
                            targetString = target;
                        }
                        searchee += targetString;
                    }

                    // matching.
                    var matched = 0;
                    words.forEach(function (word) {
                        var regex = new RegExp(word, 'i');
                        if (searchee.match(regex) != null) {
                            matched = matched + 1;
                            return false;  // break;
                        }
                        return true;  // continue;
                    });

                    if (matched == words.length) {
                        matchedPosts.push(post);
                    }
                });

                dfd.resolve(matchedPosts);
            }
        });

        return dfd.promise();
    };

    getJson().then(function (matchedPosts) {
        matchedPosts.forEach(function (post) {
            $("#search-results").find("#" + post.id).show();
        });
    });
}
<|endoftext|>