<commit_before>/**
 * [XMLvalidation evaluates an MODS XML file and ensures it meets standards set here: https://wiki.lib.utk.edu/display/DLP/UTK+Data+Dictionary]
 * @param {[String]} input [MODS XML filename]
 * @return {[Array]}       [Success] or [Filename, Error 1, Error 2, Error 3, ...]
 *
 */

var fs = require('fs');
var parser = require('xml2json');
var status = [];
var filename = process.argv;
filename = String(filename[2]);

startProcessing(filename, fileRead);

function startProcessing(file, callback) {
  fs.readFile(file, 'utf8', callback);
}

function fileRead(err, data) {
  var message;
  if (err) {
    message = 'Cannot read file';
  }
  else {
    message = 'Successfully read file';
  }
  console.log('message :' + message);
  postResults(message, data);
}

function postResults(x, data) {
  switch(x) {
    case 'Cannot read file':
      console.log('CANNOT');
      break;
    case 'Successfully read file':
      console.log('READ');
      console.log('typeof data: ' + typeof data);
      // data is still XML at this point
      //console.log(data);
      //readMODS(data);
      return data;
      break;
  }
}

//var dataS = parser.toJson(data);
//console.log('typeof dataS: ' + dataS);
//console.log('dataS: ' + dataS);

<commit_msg>start brute forcing MODS check<commit_after>/**
 * [XMLvalidation evaluates an MODS XML file and ensures it meets standards set here: https://wiki.lib.utk.edu/display/DLP/UTK+Data+Dictionary]
 * @param {[String]} input [MODS XML filename]
 * @return {[Array]}       [Success] or [Filename, Error 1, Error 2, Error 3, ...]
 *
 */

var fs = require('fs');
var parser = require('xml2json');
var jp = require('jsonpath');
var status = [];
var filename = process.argv;
filename = String(filename[2]);

var modsIn = fs.readFileSync(filename, 'utf8');
//console.log(modsIn);
var modsObj = parser.toJson(modsIn, options = {object: true});

// abstract (optional and repeatable)
// MS/AR collection title test (req'd if available, non-repeating)
if (jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].titleInfo.title') > 1) {
  console.log('Too many collection titles');
  status.push('Too many collection titles');
}
// MS/AR collection identifier test (req'd if available, non-repeating)
if (jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].identifier') > 1) {
  console.log('Too many MS/AR identifiers');
  status.push('Too many MS/AR identifiers');
}
// originInfo/dateCreated test (required and repeatable)
// @TODO clean up this test; should be at least 1 dateCreated w/ no keyDate
if (!jp.query(modsObj, '$.mods.originInfo.dateCreated[0][?(@.keyDate)]')) {
  console.log('Missing originInfo/dateCreated');
  status.push('Missing originInfo/dateCreated');
} else {
  console.log('Has an originInfo/dateCreated');
}
// originInfo/dateCreated[@keyDate][@point='start'] (req'd, non-repeating)
if (!jp.query(modsObj, '$.mods.originInfo.dateCreated[?(@.keyDate && @.point=="start")]' || jp.query(modsObj, '$.mods.originInfo.dateCreated[?(@.keyDate && @.point=="start")]') > 1)) {
  console.log('Too many keyDate starting points');
} else {
  console.log('keyDate test passed');
}

startProcessing(filename, fileRead);

function startProcessing(file, callback) {
  fs.readFile(file, 'utf8', callback);
}

function fileRead(err, data) {
  var message;
  if (err) {
    message = 'Cannot read file';
  }
  else {
    message = 'Successfully read file';
  }
  console.log('message :' + message);
  postResults(message, data);
}

function postResults(x, data) {
  switch(x) {
    case 'Cannot read file':
      console.log('CANNOT');
      break;
    case 'Successfully read file':
      console.log('READ');
      console.log('typeof data: ' + typeof data);
      // data is still XML at this point
      //console.log(data);
      //readMODS(data);
      return data;
      break;
  }
}
<|endoftext|>


<commit_before>'use strict';

define([
    'plugins',
    'lib/utils'
], function(plugins, utils) {

    plugins['post-hash'] = function(config) {

        var href,
            hash = 'liveblog',
            hashMark = '?';

        if (utils.isClient) {
            href = window.location.href;
        } else {
            // locationHref is the host embedding the live blog
            //  (equivalent to window.location.href in the browser)
            // if none is provided just use a relative path for permanent links
            href = liveblog.locationHref || '/';
        }

        utils.dispatcher.on('initialize.post-view', function(view) {
            view.permalink = function(options) {
                var _hashMark = (options && options.hashMark) ? options.hashMark : hashMark,
                    permalink = false,
                    newHash = hash + '=' + parseFloat(view.model.get('Order'));

                if (href.indexOf(_hashMark) === -1) {
                    permalink = href + _hashMark + newHash;
                } else if (href.indexOf(hash + '=') !== -1) {
                    var regexHash = new RegExp(hash + '=[^&]*');
                    permalink = href.replace(regexHash, newHash);
                } else {
                    permalink = href + '&' + newHash;
                }
                return permalink;
            };
        });

        utils.dispatcher.on('initialize.posts-view', function(view) {
            // Find if the liveblog was accessed with a hash identifier
            //   then use it as a parameter on the collection for the first request.
            var hashIndex = href.indexOf(hash + '=');
            if (hashIndex !== -1) {
                // order.end: id of the last post loaded
                // To be passed as a param in the request for pagination
                // ex: in a blog with posts 1 2 3 4 5 6 7
                // http://localhost:8080/resources/LiveDesk/Blog/1/Post/
                //      Published?order.end=3&limit=2&offset=0
                // -> gives back posts 4 5
                // http://localhost:8080/resources/LiveDesk/Blog/1/Post/
                //      Published?order.end=3&limit=2&offset=2
                // -> gives back posts 6 7
                view.collection.syncParams.pagination['order.end'] = parseFloat(href.substr(hashIndex + hash.length + 1));

                view.flags.hasTopPage = true;

                view.flags.autoRender = false;
            }
        });
    };
});
<commit_msg>LB-1687 Changed url item to liveblog[item][id[<commit_after>'use strict';

define([
    'plugins',
    'lib/utils'
], function(plugins, utils) {

    plugins['post-hash'] = function(config) {

        var href,
            hash = 'liveblog[item][id]',
            hashMark = '?';

        if (utils.isClient) {
            href = window.location.href;
        } else {
            // locationHref is the host embedding the live blog
            //  (equivalent to window.location.href in the browser)
            // if none is provided just use a relative path for permanent links
            href = liveblog.locationHref || '/';
        }

        utils.dispatcher.on('initialize.post-view', function(view) {
            view.permalink = function(options) {
                var _hashMark = (options && options.hashMark) ? options.hashMark : hashMark,
                    permalink = false,
                    newHash = hash + '=' + parseFloat(view.model.get('Order'));

                if (href.indexOf(_hashMark) === -1) {
                    permalink = href + _hashMark + newHash;
                } else if (href.indexOf(hash + '=') !== -1) {
                    var regexHash = new RegExp(hash + '=[^&]*');
                    permalink = href.replace(regexHash, newHash);
                } else {
                    permalink = href + '&' + newHash;
                }
                return permalink;
            };
        });

        utils.dispatcher.on('initialize.posts-view', function(view) {
            // Find if the liveblog was accessed with a hash identifier
            //   then use it as a parameter on the collection for the first request.
            var hashIndex = href.indexOf(hash + '=');
            if (hashIndex !== -1) {
                // order.end: id of the last post loaded
                // To be passed as a param in the request for pagination
                // ex: in a blog with posts 1 2 3 4 5 6 7
                // http://localhost:8080/resources/LiveDesk/Blog/1/Post/
                //      Published?order.end=3&limit=2&offset=0
                // -> gives back posts 4 5
                // http://localhost:8080/resources/LiveDesk/Blog/1/Post/
                //      Published?order.end=3&limit=2&offset=2
                // -> gives back posts 6 7
                view.collection.syncParams.pagination['order.end'] = parseFloat(href.substr(hashIndex + hash.length + 1));

                view.flags.hasTopPage = true;

                view.flags.autoRender = false;
            }
        });
    };
});
<|endoftext|>


<commit_before>import { h, Component } 				from 'preact/preact';
import SVGIcon 							from 'com/svg-icon/icon';

export default class SidebarCalendar extends Component {
	constructor( props ) {
		super(props);
	}

	shouldComponentUpdate( nextProps, nextState ) {
		// At the moment, there are no external events that should trigger an update (I ignore my props)
		return false;
	}

	genCalendar( today, rows ) {
		let cols = 7;
		let thisWeekday = today.getDay();
		let thisDay = today.getDate();
		let thisMonth = today.getMonth();
		let thisYear = today.getFullYear();

		/* Months and Weeks start at 0. Years and Days start at 1. Using 0th day is like -1 */
		let monthEndsOn = new Date(thisYear, thisMonth+1, 0).getDate();
		let nextDay = thisDay - thisWeekday;
		let toggleMonth = false;

		if ( nextDay < 1 ) {
			let lastMonth = new Date(thisYear, thisMonth, 0);
			monthEndsOn = lastMonth.getDate();
			//console.log( lastMonth.getFullYear(), lastMonth.getMonth(), lastMonth.getDate(), lastMonth.getDay() );
			nextDay = lastMonth.getDate() - lastMonth.getDay();
			toggleMonth = true;
		}

		// TODO: Insert scheduled events here
		let data = Array(...Array(rows)).map(() => Array.from( Array(cols),function(){
			let ret = {
				'year': thisYear,
				'month': thisMonth,
				'day': nextDay
			};

			if ( nextDay === thisDay ) {
				ret['selected'] = true;
			}
			if ( toggleMonth ) {
				ret['toggle'] = true;
			}

			nextDay++;
			if ( nextDay > monthEndsOn ) {
				nextDay -= monthEndsOn;
				thisMonth++;
				if ( thisMonth > 12 ) {
					thisYear++;
					thisMonth = 1;
				}
				toggleMonth = !toggleMonth;
			}

			return ret;
		}));

		return data;
	}

	genRow( row ) {
		return row.map(col => {
			let props = {};
			props.class = [];

			if ( col.selected ) {
				props.class.push('selected');
			}
			if ( col.toggle === true ) {
				props.class.push('month');
			}
			props.onclick = (e) => {
				console.log('cal: ',col);
				window.location.hash = "#cal/"+col.year+"/"+col.month+"/"+col.day;
			};
			// In case Intl extensions are not available
			props.title = col.month+"-"+col.day+"-"+col.year;
			if ( window.Intl ) {
				// http://stackoverflow.com/a/18648314/5678759
				let objDate = new Date(col.year, col.month, col.day);
				props.title = objDate.toLocaleString("en-us", {month:"long", day:"numeric", year:"numeric"});
			}

			// Hack
			var ShowIcon = null;
			if ( col.year == 2017 && col.month == 3 && (col.day >= 21 && col.day <= 24) ) {
				if ( col.day === 21 ) {
					ShowIcon = <SVGIcon class="-icon">trophy</SVGIcon>;
				}
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 4 && col.day == 19 ) {
				ShowIcon = <SVGIcon class="-icon">checker</SVGIcon>;
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 2 && col.day == 24 ) {
				ShowIcon = <SVGIcon class="-icon">suggestion</SVGIcon>;
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 3 && col.day == 7 ) {
				ShowIcon = <SVGIcon class="-icon">mallet</SVGIcon>;
				props.class.push('scheduled');
			}

			return (

					{ShowIcon}

{col.day}

			);
		});
	}

	genWeek( row ) {
		return (

				{this.genRow(row)}

		);
	}

	render( {rows} ) {
		// TODO: Adjust noted days based on timezone
		// TODO: Adjust selected day/week when time itself rolls over

		let data = this.genCalendar(new Date(), rows ? rows : 3);

		return (

				{data.map(row => this.genWeek(row))}

		);
	}
}
<commit_msg>calender bug when months roll over<commit_after>import { h, Component } 				from 'preact/preact';
import SVGIcon 							from 'com/svg-icon/icon';

export default class SidebarCalendar extends Component {
	constructor( props ) {
		super(props);
	}

	shouldComponentUpdate( nextProps, nextState ) {
		// At the moment, there are no external events that should trigger an update (I ignore my props)
		return false;
	}

	genCalendar( today, rows ) {
		let cols = 7;
		let thisWeekday = today.getDay();
		let thisDay = today.getDate();
		let thisMonth = today.getMonth();
		let thisYear = today.getFullYear();

		/* Months and Weeks start at 0. Years and Days start at 1. Using 0th day is like -1 */
		let monthEndsOn = new Date(thisYear, thisMonth+1, 0).getDate();
		let nextDay = thisDay - thisWeekday;
		let toggleMonth = false;

		if ( nextDay < 1 ) {
			let lastMonth = new Date(thisYear, thisMonth, 0);
			monthEndsOn = lastMonth.getDate();
			//console.log( lastMonth.getFullYear(), lastMonth.getMonth(), lastMonth.getDate(), lastMonth.getDay() );
			nextDay = lastMonth.getDate() - lastMonth.getDay();
			toggleMonth = true;
		}

		// TODO: Insert scheduled events here
		let data = Array(...Array(rows)).map(() => Array.from( Array(cols),function(){
			let ret = {
				'year': thisYear,
				'month': thisMonth,
				'day': nextDay
			};

			if ( nextDay === thisDay ) {
				ret['selected'] = true;
			}
			if ( toggleMonth ) {
				ret['toggle'] = true;
			}

			nextDay++;
			if ( nextDay > monthEndsOn ) {
				nextDay -= monthEndsOn;
				thisMonth++;
				if ( thisMonth > 12 ) {
					thisYear++;
					thisMonth = 1;
				}
				toggleMonth = !toggleMonth;
			}

			return ret;
		}));

		return data;
	}

	genRow( row ) {
		return row.map(col => {
			let props = {};
			props.class = [];

			if ( col.selected ) {
				props.class.push('selected');
			}
			if ( col.toggle === true ) {
				props.class.push('month');
			}
			props.onclick = (e) => {
				console.log('cal: ',col);
				window.location.hash = "#cal/"+col.year+"/"+col.month+"/"+col.day;
			};
			// In case Intl extensions are not available
			props.title = col.month+"-"+col.day+"-"+col.year;
			if ( window.Intl ) {
				// http://stackoverflow.com/a/18648314/5678759
				let objDate = new Date(col.year, col.month, col.day);
				props.title = objDate.toLocaleString("en-us", {month:"long", day:"numeric", year:"numeric"});
			}

			// Hack
			var ShowIcon = null;
			if ( col.year == 2017 && col.month == 3 && (col.day >= 21 && col.day <= 24) ) {
				if ( col.day === 21 ) {
					ShowIcon = <SVGIcon class="-icon">trophy</SVGIcon>;
				}
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 5 /*4*/ && col.day == 19 ) {
				ShowIcon = <SVGIcon class="-icon">checker</SVGIcon>;
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 2 && col.day == 24 ) {
				ShowIcon = <SVGIcon class="-icon">suggestion</SVGIcon>;
				props.class.push('scheduled');
			}
			else if ( col.year == 2017 && col.month == 3 && col.day == 7 ) {
				ShowIcon = <SVGIcon class="-icon">mallet</SVGIcon>;
				props.class.push('scheduled');
			}

			return (

					{ShowIcon}

{col.day}

			);
		});
	}

	genWeek( row ) {
		return (

				{this.genRow(row)}

		);
	}

	render( {rows} ) {
		// TODO: Adjust noted days based on timezone
		// TODO: Adjust selected day/week when time itself rolls over

		let data = this.genCalendar(new Date(), rows ? rows : 3);

		return (

				{data.map(row => this.genWeek(row))}

		);
	}
}
<|endoftext|>


<commit_before>/*
 * DealPort
 * Copyright (c) 2014  DealPort B.V.
 *
 * This file is part of DealPort
 *
 * DealPort is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * DealPort is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with DealPort.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, the following supplemental terms apply, based on section 7 of
 * the GNU Affero General Public License (version 3):
 * a) Preservation of all legal notices and author attributions
 */

'use strict';
var P = require('bluebird');
var nodePool = require('generic-pool');
var mongo = require('mongoskin');
var livedbmongo = require('livedb-mongo');
var livedb = require('livedb');
var sharejs = require('share');

P.promisifyAll(mongo.Collection.prototype);
P.promisifyAll(mongo.Cursor.prototype);
P.promisifyAll(mongo.Grid.prototype);
P.promisifyAll(mongo.GridStore);
P.promisifyAll(mongo.GridStore.prototype);
P.promisifyAll(require('mongodb').Collection.prototype);
P.promisifyAll(require('mongodb').Cursor.prototype);
P.promisifyAll(require('mongodb').Grid.prototype);
P.promisifyAll(require('mongodb').GridStore);
P.promisifyAll(require('mongodb').GridStore.prototype);
P.promisifyAll(livedb.client.prototype);

var ModelIndex = require('./');

module.exports = function(config)
{
        var initDb = mongo.db(config.mongoUri, {
                'native_parser': true,
                // http://docs.mongodb.org/manual/reference/write-concern/
                w: 'majority',
                j: true,
                wtimeout: 30 * 1000 // ms
        });
        initDb.bind('session');
        initDb.bind('namedEntity');
        initDb.bind('vacancy');

        P.join(
                // expire session that have not been used for 7 days
                initDb.session.ensureIndexAsync({lastAccess: 1}, { background: true, expireAfterSeconds: 7 * 24 * 60 * 60 }),
                initDb.namedEntity.ensureIndexAsync({ company: 1 }, { unique: true, sparse: true }),
                initDb.namedEntity.ensureIndexAsync({ user: 1 }, { unique: true, sparse: true }),
                // must be sparse because of the way livedb deletes stuff:
                initDb.vacancy.ensureIndexAsync({ company: 1, name: 1 }, { unique: true, sparse: true })
        )
        .then(function()
        {
                initDb.close();
        });

        var pool = nodePool.Pool({
                name: 'mongo',
                create: function(callback)
                {
                        P.try(function()
                        {
                                var db = mongo.db(config.mongoUri, {
                                        'native_parser': true,
                                        // http://docs.mongodb.org/manual/reference/write-concern/
                                        w: 'majority',
                                        j: true,
                                        wtimeout: 30 * 1000 // ms

                                });
                                db.bind('company');
                                db.bind('companyImport');
                                db.bind('session');
                                // uploadedImage.chunks
                                // uploadedImage.files
                                db.bind('user');
                                db.bind('namedEntity');
                                db.bind('vacancy');

                                return db;
                        }).nodeify(callback);
                },
                destroy: function(db)
                {
                        db.close();
                },
                min: parseInt(config.dbPoolMin, 10),
                max: parseInt(config.dbPoolMax, 10),
                idleTimeoutMillis : 30000,
                log : false
        });

        var db = livedbmongo(mongo.db(config.mongoUri, {
                'native_parser': true,
                // http://docs.mongodb.org/manual/reference/write-concern/
                w: 'majority',
                j: true,
                wtimeout: 30 * 1000 // ms
        }));

        var live = livedb.client({
                db: db
        });

        var share = sharejs.server.createClient({
                backend: live
        });

        var models = new ModelIndex(pool, live, share);

        share.filter(function(collection, docId, docData, next)
        {
                //console.log('filter', collection, docId, docData);
                // used by fetch, bulkFetch, query, queryFetch
                models.sharejsFilter(collection, docId, docData, this)
                .catch(function(err)
                {
                        console.warn('sharejs filter error', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(next);
        });

        share.filterOps(function(collection, docId, opData, next)
        {
                // used by getOps
                models.sharejsFilterOps(collection, docId, opData, this)
                .catch(function(err)
                {
                        console.warn('sharejs filterOps error', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(next);
        });

        /* actions:
        connect // request.stream, request.req
        fetch
        bulk fetch // request.requests
        get ops // request.start, request.end
        subscribe // request.version
        bulk subscribe // request.requests
        submit // request.opData, request.channelPrefix
        after submit // request.opData, request.snapshot
        query

        request.agent
        request.action
        request.collection
        request.docName
        request.backend
        */

        share.use('submit', function(request, callback)
        {
                models.sharejsSubmit(
                        request.collection,
                        request.docName,
                        request.opData,
                        request.agent
                )
                .catch(function(err)
                {
                        console.warn('sharejs submit not allowed', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(callback);
        });

        share.use('after submit', function(request, callback)
        {
                models.sharejsAfterSubmit(
                        request.collection,
                        request.docName,
                        request.opData,
                        request.snapshot,
                        request.agent
                )
                .nodeify(callback);
        });

        share.use('query', function(request, callback)
        {
                console.warn('Attempted use of sharejs query');
                callback(Error('sharejs queries are disabled, use a Resource instead'));
        });

        share.use('subscribe', function(request, callback)
        {
                // (also triggered by bulk subscribe)
                models.sharejsSubscribe(
                        request.collection,
                        request.docName,
                        request.version,
                        request.agent

                ).catch(function(err)
                {
                        console.warn('sharejs subscribe not allowed', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(callback);
        });

        return models;
};
<commit_msg>Fix bulk subscribe in sharejs not working (documentation lies)<commit_after>/*
 * DealPort
 * Copyright (c) 2014  DealPort B.V.
 *
 * This file is part of DealPort
 *
 * DealPort is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * DealPort is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with DealPort.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, the following supplemental terms apply, based on section 7 of
 * the GNU Affero General Public License (version 3):
 * a) Preservation of all legal notices and author attributions
 */

'use strict';
var P = require('bluebird');
var nodePool = require('generic-pool');
var mongo = require('mongoskin');
var livedbmongo = require('livedb-mongo');
var livedb = require('livedb');
var sharejs = require('share');

P.promisifyAll(mongo.Collection.prototype);
P.promisifyAll(mongo.Cursor.prototype);
P.promisifyAll(mongo.Grid.prototype);
P.promisifyAll(mongo.GridStore);
P.promisifyAll(mongo.GridStore.prototype);
P.promisifyAll(require('mongodb').Collection.prototype);
P.promisifyAll(require('mongodb').Cursor.prototype);
P.promisifyAll(require('mongodb').Grid.prototype);
P.promisifyAll(require('mongodb').GridStore);
P.promisifyAll(require('mongodb').GridStore.prototype);
P.promisifyAll(livedb.client.prototype);

var ModelIndex = require('./');

module.exports = function(config)
{
        var initDb = mongo.db(config.mongoUri, {
                'native_parser': true,
                // http://docs.mongodb.org/manual/reference/write-concern/
                w: 'majority',
                j: true,
                wtimeout: 30 * 1000 // ms
        });
        initDb.bind('session');
        initDb.bind('namedEntity');
        initDb.bind('vacancy');

        P.join(
                // expire session that have not been used for 7 days
                initDb.session.ensureIndexAsync({lastAccess: 1}, { background: true, expireAfterSeconds: 7 * 24 * 60 * 60 }),
                initDb.namedEntity.ensureIndexAsync({ company: 1 }, { unique: true, sparse: true }),
                initDb.namedEntity.ensureIndexAsync({ user: 1 }, { unique: true, sparse: true }),
                // must be sparse because of the way livedb deletes stuff:
                initDb.vacancy.ensureIndexAsync({ company: 1, name: 1 }, { unique: true, sparse: true })
        )
        .then(function()
        {
                initDb.close();
        });

        var pool = nodePool.Pool({
                name: 'mongo',
                create: function(callback)
                {
                        P.try(function()
                        {
                                var db = mongo.db(config.mongoUri, {
                                        'native_parser': true,
                                        // http://docs.mongodb.org/manual/reference/write-concern/
                                        w: 'majority',
                                        j: true,
                                        wtimeout: 30 * 1000 // ms

                                });
                                db.bind('company');
                                db.bind('companyImport');
                                db.bind('session');
                                // uploadedImage.chunks
                                // uploadedImage.files
                                db.bind('user');
                                db.bind('namedEntity');
                                db.bind('vacancy');

                                return db;
                        }).nodeify(callback);
                },
                destroy: function(db)
                {
                        db.close();
                },
                min: parseInt(config.dbPoolMin, 10),
                max: parseInt(config.dbPoolMax, 10),
                idleTimeoutMillis : 30000,
                log : false
        });

        var db = livedbmongo(mongo.db(config.mongoUri, {
                'native_parser': true,
                // http://docs.mongodb.org/manual/reference/write-concern/
                w: 'majority',
                j: true,
                wtimeout: 30 * 1000 // ms
        }));

        var live = livedb.client({
                db: db
        });

        var share = sharejs.server.createClient({
                backend: live
        });

        var models = new ModelIndex(pool, live, share);

        share.filter(function(collection, docId, docData, next)
        {
                //console.log('filter', collection, docId, docData);
                // used by fetch, bulkFetch, query, queryFetch
                models.sharejsFilter(collection, docId, docData, this)
                .catch(function(err)
                {
                        console.warn('sharejs filter error', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(next);
        });

        share.filterOps(function(collection, docId, opData, next)
        {
                // used by getOps
                models.sharejsFilterOps(collection, docId, opData, this)
                .catch(function(err)
                {
                        console.warn('sharejs filterOps error', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(next);
        });

        /* actions:
        connect // request.stream, request.req
        fetch
        bulk fetch // request.requests
        get ops // request.start, request.end
        subscribe // request.version
        bulk subscribe // request.requests
        submit // request.opData, request.channelPrefix
        after submit // request.opData, request.snapshot
        query

        request.agent
        request.action
        request.collection
        request.docName
        request.backend
        */

        share.use('submit', function(request, callback)
        {
                models.sharejsSubmit(
                        request.collection,
                        request.docName,
                        request.opData,
                        request.agent
                )
                .catch(function(err)
                {
                        console.warn('sharejs submit not allowed', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(callback);
        });

        share.use('after submit', function(request, callback)
        {
                models.sharejsAfterSubmit(
                        request.collection,
                        request.docName,
                        request.opData,
                        request.snapshot,
                        request.agent
                )
                .nodeify(callback);
        });

        share.use('query', function(request, callback)
        {
                console.warn('Attempted use of sharejs query');
                callback(Error('sharejs queries are disabled, use a Resource instead'));
        });

        share.use('subscribe', function(request, callback)
        {
                models.sharejsSubscribe(
                        request.collection,
                        request.docName,
                        request.version,
                        request.agent

                ).catch(function(err)
                {
                        console.warn('sharejs subscribe not allowed', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(callback);
        });

        // if a subscribe middleware is added, a bulk subscribe middleware must also
        // be implemented or otherwise sharejs triggers a "Not implemented" error
        share.use('bulk subscribe', function(request, callback)
        {
                // {collection name: {doc name -> version} }
                var promises = [];
                var collections = request.requests;
                var collectionNames = Object.keys(collections);

                collectionNames.forEach(function(collectionName)
                {
                        var docs = collections[collectionName];
                        var docNames = Object.keys(docs);

                        docNames.forEach(function(docName)
                        {
                                var version = docs[docName];

                                promises.push(models.sharejsSubscribe(
                                        collectionName,
                                        docName,
                                        version,
                                        request.agent
                                ));
                        });
                });

                P.all(promises)
                .catch(function(err)
                {
                        console.warn('sharejs subscribe not allowed (bulk)', err, err.stack);
                        return P.reject(err);
                })
                .nodeify(callback);
        });

        return models;
};
<|endoftext|>


<commit_before>var TargetBase = require('./base').TargetBase,
    TargetNodes = require('./base').TargetNodes,
    TargetNodesDev = function (options) {
        this.init(options);
    };

TargetNodesDev.prototype = Object.create(TargetNodes.prototype);

TargetNodesDev.prototype.init = function (options) {
    var tasks = [
        require('../tasks/init'),
        require('../tasks/get-jsmodel'),
        require('../tasks/nodes'),
        require('../tasks/rm-model'),
        require('../tasks/docs'),
        require('../tasks/people'),
        require('../tasks/dynamic-people'),
        require('../tasks/dynamic-tags'),
        require('../tasks/libraries-files'),
        require('../tasks/libraries-db'),
        require('../tasks/urls-map'),
        require('../tasks/override-links'),
        require('../tasks/finalize')
    ];

    tasks.forEach(function (task) {
        this.addTask(task);
    }, this);

    TargetBase.prototype.init.call(this, options);
};

TargetNodesDev.prototype.getName = function () {
    return 'NODES DEV SYNCHRONIZATION';
};

exports.TargetNodesDev = TargetNodesDev;
<commit_msg>Fix invalid requirement path<commit_after>var TargetBase = require('./base').TargetBase,
    TargetNodes = require('./nodes').TargetNodes,
    TargetNodesDev = function (options) {
        this.init(options);
    };

TargetNodesDev.prototype = Object.create(TargetNodes.prototype);

TargetNodesDev.prototype.init = function (options) {
    var tasks = [
        require('../tasks/init'),
        require('../tasks/get-jsmodel'),
        require('../tasks/nodes'),
        require('../tasks/rm-model'),
        require('../tasks/docs'),
        require('../tasks/people'),
        require('../tasks/dynamic-people'),
        require('../tasks/dynamic-tags'),
        require('../tasks/libraries-files'),
        require('../tasks/libraries-db'),
        require('../tasks/urls-map'),
        require('../tasks/override-links'),
        require('../tasks/finalize')
    ];

    tasks.forEach(function (task) {
        this.addTask(task);
    }, this);

    TargetBase.prototype.init.call(this, options);
};

TargetNodesDev.prototype.getName = function () {
    return 'NODES DEV SYNCHRONIZATION';
};

exports.TargetNodesDev = TargetNodesDev;
<|endoftext|>


<commit_before>
// SmoothScroll v0.9.8
// Licensed under the terms of the MIT license.

// People involved
// - Balazs Galambosi: maintainer (CHANGELOG.txt)
// - Patrick Brunner (patrickb1991@gmail.com)
// - Michael Herf: Pulse Algorithm

// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime  = 400; // [px]
var stepsize  = 120; // [px]

// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
var pulseAlgorithm = true;
var pulseScale     = 8;
var pulseNormalize = 1;

// Keyboard Settings
var keyboardsupport = true;
var disableKeyboard = false;
var arrowscroll     = 50; // [px]

// Excluded pages
var exclude = "";

// Other Variables
var frame = false;
var direction = "down";
var initdone  = false;
var activeElement;
var root;

var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };

/***********************************************
 * SETTINGS
 ***********************************************/

chrome.extension.connect({ name: "smoothscroll" }).
onMessage.addListener(function (settings) {

    // NOTE: + converts to {Number}
    framerate = +settings.framerate;
    animtime  = +settings.animtime;
    stepsize  = +settings.scrollsz;
    exclude   = settings.exclude;
    pulseAlgorithm  = (settings.pulseAlgorithm == "true");
    pulseScale      = +settings.pulseScale;
    keyboardsupport = (settings.keyboardsupport == "true");
    arrowscroll     = +settings.arrscroll;

    computePulseScale();

    // it seems that sometimes settings come late
    // and we need to test again for excluded pages
    initTest();

    if (keyboardsupport && !disableKeyboard) {
        addEvent("keydown", keydown);
    }

    // If extension settings were deleted somehow
    if (!framerate) {
        alert("SmoothScroll: Please restart Chrome");
    }
});

/***********************************************
 * INITIALIZE
 ***********************************************/

/**
 * Tests if smooth scrolling is allowed. Shuts down everything if not.
 */
function initTest() {

    // disable keys for google reader (spacebar conflict)
    if (document.URL.indexOf("google.com/reader/view") > -1) {
        disableKeyboard = true;
    }

    // disable everything if the page is blacklisted
    if (exclude) {
        var domains = exclude.split(/[,\n] ?/);
        for (var i = domains.length; i--;) {
            if (document.URL.indexOf(domains[i]) > -1) {
                removeEvent("mousewheel", wheel);
                disableKeyboard = true;
                break;
            }
        }
    }

    // disable keyboard support if anything above requested it
    if (disableKeyboard) {
        removeEvent("keydown", keydown);
    }
}

/**
 * Sets up scrolls array, determines if frames are involved.
 */
function init() {

    if (!document.body) return;
    if (document.domain === "acid3.acidtests.org") return;

    var body = document.body;
    var html = document.documentElement;
    var windowHeight = window.innerHeight;
    var scrollHeight = body.scrollHeight;

    // check compat mode for root element
    root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
    activeElement = body;

    initTest();

    // Checks if this script is running in a frame
    if (top != self) {
        frame = true;
    }

    /**
     * This fixes a bug where the areas left and right to
     * the content does not trigger the onmousewheel event
     * on some pages. e.g.: html, body { height: 100% }
     */
    else if (scrollHeight > windowHeight &&
            (body.offsetHeight <= windowHeight ||
             html.offsetHeight <= windowHeight)) {

        var underlay = document.createElement("div");
        underlay.setAttribute( "style",
            "z-index: -1; position: absolute; top: 0; left: 0; " +
            "width: 100%; height: " + scrollHeight + "px;" );
        body.appendChild(underlay);

        var pending = false;

        // DOMChange (throttle)
        var refresh = function() {
            if (!pending) {
                underlay.style.display = "none";
                if (scrollHeight != body.scrollHeight) {
                    pending = true; // add a new pending action
                    setTimeout(function(){
                        underlay.style.display = "none";
                        scrollHeight = body.scrollHeight;
                        underlay.style.height  = scrollHeight + "px";
                        underlay.style.display = "";
                        pending = false;
                    }, 1000); // act rarely to stay fast
                }
                underlay.style.display = "";
            }
        }

        addEvent("DOMNodeInserted", refresh);
        addEvent("DOMNodeRemoved",  refresh);
    }
    initdone = true;
}

/************************************************
 * SCROLLING
 ************************************************/

var que = [];
var pending = false;

/**
 * Pushes scroll actions to the scrolling queue.
 */
function scrollArray(elem, dir, multiplyX, multiplyY, delay) {

    delay || (delay = 1000);
    directionCheck(dir);

    // push a scroll command
    que.push({
        x: multiplyX,
        y: multiplyY,
        lastX: (multiplyX < 0) ? 0.99 : -0.99,
        lastY: (multiplyY < 0) ? 0.99 : -0.99,
        start: +new Date
    });

    // don't act if there's a pending queue
    if (pending) {
        return;
    }

    var step = function() {

        var now = +new Date;
        var totalX = 0;
        var totalY = 0;

        for (var i = 0; i < que.length; i++) {

            var item = que[i];
            var elapsed  = now - item.start;
            var finished = (elapsed >= animtime);

            // scroll position: [0, 1]
            var position = (finished) ? 1 : elapsed / animtime;

            // easing [optional]
            if (pulseAlgorithm) {
                position = pulse(position);
            }

            // only need the difference
            var scrollX = (item.x * position - item.lastX) >> 0;
            var scrollY = (item.y * position - item.lastY) >> 0;

            // add this to the total scrolling
            totalX += scrollX;
            totalY += scrollY;

            // update last values
            item.lastX += scrollX;
            item.lastY += scrollY;

            // delete and step back if it's over
            if (finished) {
                que.splice(i, 1); i--;
            }
        }

        // scroll left
        if (multiplyX) {
            var lastLeft = elem.scrollLeft;
            elem.scrollLeft += totalX;

            // scroll left failed (edge)
            if (totalX && elem.scrollLeft === lastLeft) {
                multiplyX = 0;
            }
        }

        // scroll top
        if (multiplyY) {
            var lastTop = elem.scrollTop;
            elem.scrollTop += totalY;

            // scroll top failed (edge)
            if (totalY && elem.scrollTop === lastTop) {
                multiplyY = 0;
            }
        }

        // clean up if there's nothing left to do
        if (!multiplyX && !multiplyY) {
            que = [];
        }

        if (que.length) {
            setTimeout(step, delay / framerate + 1);
        } else {
            pending = false;
        }
    }

    // start a new queue of actions
    setTimeout(step, 0);
    pending = true;
}

/***********************************************
 * EVENTS
 ***********************************************/

/**
 * Mouse wheel handler.
 * @param {Object} event
 */
function wheel(event) {

    if (!initdone) {
        init();
    }

    var target = event.target;
    var elem   = overflowingAncestor(target);

    // use default if there's no overflowing
    // element or default action is prevented
    if (!elem || event.defaultPrevented ||
        isNodeName(activeElement, "embed") ||
       (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) {
        return true;
    }

    var deltaX = event.wheelDeltaX || 0;
    var deltaY = event.wheelDeltaY || 0;

    // use wheelDelta if deltaX/Y is not available
    if (!deltaX && !deltaY) {
        deltaY = event.wheelDelta || 0;
    }

    // scale by step size
    // delta is 120 most of the time
    // synaptics seems to send 1 sometimes
    if (Math.abs(deltaX) > 1.2) {
        deltaX *= stepsize / 120;
    }
    if (Math.abs(deltaY) > 1.2) {
        deltaY *= stepsize / 120;
    }

    var dir = (deltaY > 0) ? "up" : "down";
    scrollArray(elem, dir, -deltaX, -deltaY);
    event.preventDefault();
}

/**
 * Keydown event handler.
 * @param {Object} event
 */
function keydown(event) {

    var target   = event.target;
    var modifier = event.ctrlKey || event.altKey || event.metaKey;

    // do nothing if user is editing text
    // or using a modifier key (except shift)
    if ( /input|textarea|embed/i.test(target.nodeName) ||
         target.isContentEditable ||
         event.defaultPrevented   ||
         modifier ) {
      return true;
    }
    // spacebar should trigger button press
    if (isNodeName(target, "button") &&
        event.keyCode === key.spacebar) {
      return true;
    }

    var dir, shift, scaleX = 0, scaleY = 0;
    var elem = overflowingAncestor(activeElement);
    var clientHeight = elem.clientHeight;

    if (elem == document.body) {
        clientHeight = window.innerHeight;
    }

    switch (event.keyCode) {
        case key.up:
            scaleY = -arrowscroll;
            dir = "up";
            break;
        case key.down:
            scaleY = arrowscroll;
            dir = "down";
            break;
        case key.spacebar: // (+ shift)
            shift = event.shiftKey ? 1 : -1;
            scaleY = -shift * clientHeight * 0.9;
            dir = (shift > 0) ? "up" : "down";
            break;
        case key.pageup:
            scaleY = -clientHeight * 0.9;
            dir = "up";
            break;
        case key.pagedown:
            scaleY = clientHeight * 0.9;
            dir = "down";
            break;
        case key.home:
            scaleY = -elem.scrollTop;
            dir = "up";
            break;
        case key.end:
            var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
            scaleY = (damt > 0) ? damt+10 : 0;
            dir = "down";
            break;
        case key.left:
            scaleX = -arrowscroll;
            break;
        case key.right:
            scaleX = arrowscroll;
            break;
        default:
            return true; // a key we don"t care about
    }

    scrollArray(elem, dir, scaleX, scaleY);
    event.preventDefault();
}

/**
 * Mousedown event only for updating activeElement
 */
function mousedown(event) {
    activeElement = event.target;
}

/***********************************************
 * HELPERS
 ***********************************************/

function addEvent(type, fn, bubble) {
    window.addEventListener(type, fn, (bubble||false));
}

function removeEvent(type, fn, bubble) {
    window.removeEventListener(type, fn, (bubble||false));
}

function isNodeName(el, tag) {
    return el.nodeName.toLowerCase() === tag.toLowerCase();
}

function directionCheck(dir) {
    if (direction !== dir) {
        que = [];
        direction = dir;
    }
}

function overflowingAncestor(el) {
    var rootScrollHeight = root.scrollHeight;
    do {
        if (rootScrollHeight === el.scrollHeight) {
            if (!frame || root.clientHeight + 10 < rootScrollHeight) {
                return document.body; // scrolling root in WebKit
            }
        }
        else if (el.clientHeight + 10 < el.scrollHeight) {
            overflow = getComputedStyle(el, "").getPropertyValue("overflow");
            if (overflow === "scroll" || overflow === "auto") {
                return el;
            }
        }
    } while (el = el.parentNode);
}

/***********************************************
 * PULSE
 ***********************************************/

/**
 * Viscous fluid with a pulse for part and decay for the rest.
 * - Applies a fixed force over an interval (a damped acceleration), and
 * - Lets the exponential bleed away the velocity over a longer interval
 * - Michael Herf, http://stereopsis.com/stopping/
 */
function pulse_(x) {
    var val, start, expx;
    // test
    x = x * pulseScale;
    if (x < 1) { // acceleartion
        val = x - (1 - Math.exp(-x));
    } else {     // tail
        // the previous animation ended here:
        start = Math.exp(-1);
        // simple viscous drag
        x -= 1;
        expx = 1 - Math.exp(-x);
        val = start + (expx * (1 - start));
    }
    return val * pulseNormalize;
}

function computePulseScale() {
    pulseNormalize = 1 / pulse_(1);
}

/**
 * Viscous fluid with a pulse for part and decay for the rest
 */
function pulse(x) {
    if (x >= 1) return 1;
    if (x <= 0) return 0;

    if (pulseNormalize == 1) {
        computePulseScale();
    }
    return pulse_(x);
}

addEvent("mousedown", mousedown);
addEvent("mousewheel", wheel);
addEvent("load", init);
<commit_msg>removed underlay completely, try to use html { height:auto } instead<commit_after>
// SmoothScroll v0.9.8
// Licensed under the terms of the MIT license.

// People involved
// - Balazs Galambosi: maintainer (CHANGELOG.txt)
// - Patrick Brunner (patrickb1991@gmail.com)
// - Michael Herf: Pulse Algorithm

// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime  = 400; // [px]
var stepsize  = 120; // [px]

// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
var pulseAlgorithm = true;
var pulseScale     = 8;
var pulseNormalize = 1;

// Keyboard Settings
var keyboardsupport = true;
var disableKeyboard = false;
var arrowscroll     = 50; // [px]

// Excluded pages
var exclude = "";

// Other Variables
var frame = false;
var direction = "down";
var initdone  = false;
var activeElement;
var root;

var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };

/***********************************************
 * SETTINGS
 ***********************************************/

chrome.extension.connect({ name: "smoothscroll" }).
onMessage.addListener(function (settings) {

    // NOTE: + converts to {Number}
    framerate = +settings.framerate;
    animtime  = +settings.animtime;
    stepsize  = +settings.scrollsz;
    exclude   = settings.exclude;
    pulseAlgorithm  = (settings.pulseAlgorithm == "true");
    pulseScale      = +settings.pulseScale;
    keyboardsupport = (settings.keyboardsupport == "true");
    arrowscroll     = +settings.arrscroll;

    computePulseScale();

    // it seems that sometimes settings come late
    // and we need to test again for excluded pages
    initTest();

    if (keyboardsupport && !disableKeyboard) {
        addEvent("keydown", keydown);
    }

    // If extension settings were deleted somehow
    if (!framerate) {
        alert("SmoothScroll: Please restart Chrome");
    }
});

/***********************************************
 * INITIALIZE
 ***********************************************/

/**
 * Tests if smooth scrolling is allowed. Shuts down everything if not.
 */
function initTest() {

    // disable keys for google reader (spacebar conflict)
    if (document.URL.indexOf("google.com/reader/view") > -1) {
        disableKeyboard = true;
    }

    // disable everything if the page is blacklisted
    if (exclude) {
        var domains = exclude.split(/[,\n] ?/);
        for (var i = domains.length; i--;) {
            if (document.URL.indexOf(domains[i]) > -1) {
                removeEvent("mousewheel", wheel);
                disableKeyboard = true;
                break;
            }
        }
    }

    // disable keyboard support if anything above requested it
    if (disableKeyboard) {
        removeEvent("keydown", keydown);
    }
}

/**
 * Sets up scrolls array, determines if frames are involved.
 */
function init() {

    if (!document.body) return;

    var body = document.body;
    var html = document.documentElement;
    var windowHeight = window.innerHeight;
    var scrollHeight = body.scrollHeight;

    // check compat mode for root element
    root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
    activeElement = body;

    initTest();
    initdone = true;

    // Checks if this script is running in a frame
    if (top != self) {
        frame = true;
    }

    /**
     * This fixes a bug where the areas left and right to
     * the content does not trigger the onmousewheel event
     * on some pages. e.g.: html, body { height: 100% }
     */
    else if (scrollHeight > windowHeight &&
            (body.offsetHeight <= windowHeight ||
             html.offsetHeight <= windowHeight)) {
        html.style.height = "auto";
    }
}

/************************************************
 * SCROLLING
 ************************************************/

var que = [];
var pending = false;

/**
 * Pushes scroll actions to the scrolling queue.
 */
function scrollArray(elem, dir, multiplyX, multiplyY, delay) {

    delay || (delay = 1000);
    directionCheck(dir);

    // push a scroll command
    que.push({
        x: multiplyX,
        y: multiplyY,
        lastX: (multiplyX < 0) ? 0.99 : -0.99,
        lastY: (multiplyY < 0) ? 0.99 : -0.99,
        start: +new Date
    });

    // don't act if there's a pending queue
    if (pending) {
        return;
    }

    var step = function() {

        var now = +new Date;
        var totalX = 0;
        var totalY = 0;

        for (var i = 0; i < que.length; i++) {

            var item = que[i];
            var elapsed  = now - item.start;
            var finished = (elapsed >= animtime);

            // scroll position: [0, 1]
            var position = (finished) ? 1 : elapsed / animtime;

            // easing [optional]
            if (pulseAlgorithm) {
                position = pulse(position);
            }

            // only need the difference
            var scrollX = (item.x * position - item.lastX) >> 0;
            var scrollY = (item.y * position - item.lastY) >> 0;

            // add this to the total scrolling
            totalX += scrollX;
            totalY += scrollY;

            // update last values
            item.lastX += scrollX;
            item.lastY += scrollY;

            // delete and step back if it's over
            if (finished) {
                que.splice(i, 1); i--;
            }
        }

        // scroll left
        if (multiplyX) {
            var lastLeft = elem.scrollLeft;
            elem.scrollLeft += totalX;

            // scroll left failed (edge)
            if (totalX && elem.scrollLeft === lastLeft) {
                multiplyX = 0;
            }
        }

        // scroll top
        if (multiplyY) {
            var lastTop = elem.scrollTop;
            elem.scrollTop += totalY;

            // scroll top failed (edge)
            if (totalY && elem.scrollTop === lastTop) {
                multiplyY = 0;
            }
        }

        // clean up if there's nothing left to do
        if (!multiplyX && !multiplyY) {
            que = [];
        }

        if (que.length) {
            setTimeout(step, delay / framerate + 1);
        } else {
            pending = false;
        }
    }

    // start a new queue of actions
    setTimeout(step, 0);
    pending = true;
}

/***********************************************
 * EVENTS
 ***********************************************/

/**
 * Mouse wheel handler.
 * @param {Object} event
 */
function wheel(event) {

    if (!initdone) {
        init();
    }

    var target = event.target;
    var elem   = overflowingAncestor(target);

    // use default if there's no overflowing
    // element or default action is prevented
    if (!elem || event.defaultPrevented ||
        isNodeName(activeElement, "embed") ||
       (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) {
        return true;
    }

    var deltaX = event.wheelDeltaX || 0;
    var deltaY = event.wheelDeltaY || 0;

    // use wheelDelta if deltaX/Y is not available
    if (!deltaX && !deltaY) {
        deltaY = event.wheelDelta || 0;
    }

    // scale by step size
    // delta is 120 most of the time
    // synaptics seems to send 1 sometimes
    if (Math.abs(deltaX) > 1.2) {
        deltaX *= stepsize / 120;
    }
    if (Math.abs(deltaY) > 1.2) {
        deltaY *= stepsize / 120;
    }

    var dir = (deltaY > 0) ? "up" : "down";
    scrollArray(elem, dir, -deltaX, -deltaY);
    event.preventDefault();
}

/**
 * Keydown event handler.
 * @param {Object} event
 */
function keydown(event) {

    var target   = event.target;
    var modifier = event.ctrlKey || event.altKey || event.metaKey;

    // do nothing if user is editing text
    // or using a modifier key (except shift)
    if ( /input|textarea|embed/i.test(target.nodeName) ||
         target.isContentEditable ||
         event.defaultPrevented   ||
         modifier ) {
      return true;
    }
    // spacebar should trigger button press
    if (isNodeName(target, "button") &&
        event.keyCode === key.spacebar) {
      return true;
    }

    var dir, shift, scaleX = 0, scaleY = 0;
    var elem = overflowingAncestor(activeElement);
    var clientHeight = elem.clientHeight;

    if (elem == document.body) {
        clientHeight = window.innerHeight;
    }

    switch (event.keyCode) {
        case key.up:
            scaleY = -arrowscroll;
            dir = "up";
            break;
        case key.down:
            scaleY = arrowscroll;
            dir = "down";
            break;
        case key.spacebar: // (+ shift)
            shift = event.shiftKey ? 1 : -1;
            scaleY = -shift * clientHeight * 0.9;
            dir = (shift > 0) ? "up" : "down";
            break;
        case key.pageup:
            scaleY = -clientHeight * 0.9;
            dir = "up";
            break;
        case key.pagedown:
            scaleY = clientHeight * 0.9;
            dir = "down";
            break;
        case key.home:
            scaleY = -elem.scrollTop;
            dir = "up";
            break;
        case key.end:
            var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
            scaleY = (damt > 0) ? damt+10 : 0;
            dir = "down";
            break;
        case key.left:
            scaleX = -arrowscroll;
            break;
        case key.right:
            scaleX = arrowscroll;
            break;
        default:
            return true; // a key we don"t care about
    }

    scrollArray(elem, dir, scaleX, scaleY);
    event.preventDefault();
}

/**
 * Mousedown event only for updating activeElement
 */
function mousedown(event) {
    activeElement = event.target;
}

/***********************************************
 * HELPERS
 ***********************************************/

function addEvent(type, fn, bubble) {
    window.addEventListener(type, fn, (bubble||false));
}

function removeEvent(type, fn, bubble) {
    window.removeEventListener(type, fn, (bubble||false));
}

function isNodeName(el, tag) {
    return el.nodeName.toLowerCase() === tag.toLowerCase();
}

function directionCheck(dir) {
    if (direction !== dir) {
        que = [];
        direction = dir;
    }
}

function overflowingAncestor(el) {
    var rootScrollHeight = root.scrollHeight;
    do {
        if (rootScrollHeight === el.scrollHeight) {
            if (!frame || root.clientHeight + 10 < rootScrollHeight) {
                return document.body; // scrolling root in WebKit
            }
        }
        else if (el.clientHeight + 10 < el.scrollHeight) {
            overflow = getComputedStyle(el, "").getPropertyValue("overflow");
            if (overflow === "scroll" || overflow === "auto") {
                return el;
            }
        }
    } while (el = el.parentNode);
}

/***********************************************
 * PULSE
 ***********************************************/

/**
 * Viscous fluid with a pulse for part and decay for the rest.
 * - Applies a fixed force over an interval (a damped acceleration), and
 * - Lets the exponential bleed away the velocity over a longer interval
 * - Michael Herf, http://stereopsis.com/stopping/
 */
function pulse_(x) {
    var val, start, expx;
    // test
    x = x * pulseScale;
    if (x < 1) { // acceleartion
        val = x - (1 - Math.exp(-x));
    } else {     // tail
        // the previous animation ended here:
        start = Math.exp(-1);
        // simple viscous drag
        x -= 1;
        expx = 1 - Math.exp(-x);
        val = start + (expx * (1 - start));
    }
    return val * pulseNormalize;
}

function computePulseScale() {
    pulseNormalize = 1 / pulse_(1);
}

/**
 * Viscous fluid with a pulse for part and decay for the rest
 */
function pulse(x) {
    if (x >= 1) return 1;
    if (x <= 0) return 0;

    if (pulseNormalize == 1) {
        computePulseScale();
    }
    return pulse_(x);
}

addEvent("mousedown", mousedown);
addEvent("mousewheel", wheel);
addEvent("load", init);
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-checkbox', 'Integration | Component | sl checkbox', {
    integration: true
});

test( 'Defaults applied correctly', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'checkbox' ),
        'Has class "checkbox"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'form-group' ),
        'Has class "form-group"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'sl-checkbox' ),
        'Has class "sl-checkbox"'
    );
});

test( 'Disabled state applies class and disables input', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'disabled' ),
        false,
        'Initially does not have class "disabled"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'disabled' ),
        false,
        'Rendered input is initially enabled'
    );

    this.render( hbs`
        {{sl-checkbox disabled=true}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'disabled' ),
        true,
        'Has class "disabled"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'disabled' ),
        true,
        'Rendered input is disabled'
    );
});

test( 'Checked state applies property to input', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'checked' ),
        false,
        'Rendered input is not checked'
    );

    this.render( hbs`
        {{sl-checkbox checked=true}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'checked' ),
        true,
        'Rendered input is checked'
    );
});
<commit_msg>Closes softlayer/sl-ember-components#756<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-checkbox', 'Integration | Component | sl checkbox', {
    integration: true
});

test( 'Defaults applied correctly', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'checkbox' ),
        'Has class "checkbox"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'form-group' ),
        'Has class "form-group"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'sl-checkbox' ),
        'Has class "sl-checkbox"'
    );
});

test( 'Disabled state applies class and disables input', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'disabled' ),
        false,
        'Initially does not have class "disabled"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'disabled' ),
        false,
        'Rendered input is initially enabled'
    );

    this.render( hbs`
        {{sl-checkbox disabled=true}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'disabled' ),
        true,
        'Has class "disabled"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'disabled' ),
        true,
        'Rendered input is disabled'
    );
});

test( 'Checked state applies property to input', function( assert ) {
    this.render( hbs`
        {{sl-checkbox}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'checked' ),
        false,
        'Rendered input is not checked'
    );

    this.render( hbs`
        {{sl-checkbox checked=true}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'input' ).prop( 'checked' ),
        true,
        'Rendered input is checked'
    );
});

test( 'Tooltip properties are set correctly when title parameter is set', function( assert ) {
    const title = 'test title';

    this.set( 'title', title );

    this.render( hbs`
        {{sl-checkbox title=title}}
    ` );

    const data = this.$( '>:first-child' ).data();
    const tooltipData = data[ 'bs.tooltip' ];
    const options = tooltipData.getOptions();

    assert.strictEqual(
        tooltipData.enabled,
        true,
        'tooltip is enabled'
    );

    assert.strictEqual(
        tooltipData.getTitle(),
        title,
        'Title text is set correctly'
    );

    assert.strictEqual(
        options.trigger,
        'hover focus',
        'Default trigger is "hover focus"'
    );
});
<|endoftext|>


<commit_before>module.exports = {

    db_connection_string: "mysql://dev:" + encodeURIComponent('Bysun4321$#@!') + "@120.26.239.94:3306/hp_scheduler",
    db_pool_max: 2,
    db_pool_min: 0,
    db_pool_idle: 10000,

    rabbitmq_url: 'amqp://mquser:Bysun@120.26.242.51:5672',

    max_page_size: 200,
}
<commit_msg>config<commit_after>module.exports = {

    db_connection_string: "mysql://localhost:3306/hp_scheduler",
    db_pool_max: 2,
    db_pool_min: 0,
    db_pool_idle: 10000,

    rabbitmq_url: 'amqp://localhost:5672',

    max_page_size: 200,
}
<|endoftext|>


<commit_before>pref("extensions.tinyurlgen.createpreviewbydefault", false);
pref("extensions.tinyurlgen.exposedestination", true);
pref("extensions.tinyurlgen.showcontextoptionforpage", true);
pref("extensions.tinyurlgen.showcontextoptionforlinks", true);
pref("extensions.tinyurlgen.shortcutenabled", false);
pref("extensions.tinyurlgen.shortcutmodifier.accel", false);
pref("extensions.tinyurlgen.shortcutmodifier.alt", true);
pref("extensions.tinyurlgen.shortcutmodifier.shift", false);
pref("extensions.tinyurlgen.shortcutkey", "VK_G");
pref("extensions.tinyurlgen.firstrun", true);<commit_msg>Fix default shortcut key: VK_G becomes G<commit_after>pref("extensions.tinyurlgen.createpreviewbydefault", false);
pref("extensions.tinyurlgen.exposedestination", true);
pref("extensions.tinyurlgen.showcontextoptionforpage", true);
pref("extensions.tinyurlgen.showcontextoptionforlinks", true);
pref("extensions.tinyurlgen.shortcutenabled", false);
pref("extensions.tinyurlgen.shortcutmodifier.accel", false);
pref("extensions.tinyurlgen.shortcutmodifier.alt", true);
pref("extensions.tinyurlgen.shortcutmodifier.shift", false);
pref("extensions.tinyurlgen.shortcutkey", "G");
pref("extensions.tinyurlgen.firstrun", true);<|endoftext|>


<commit_before>import { SEARCH_HISTORY } from '../constants/actionTypes';

export default function searchHistory(
  state = {
    items: [],
  },
  action = {},
) {
  switch (action.type) {
    case SEARCH_HISTORY.ADD: {
      let newItems;
      const items = state.items;
      const newItem = action.payload.item;
      if (items && items.length) {
        if (items.indexOf(newItem) === -1) {
          newItems = [newItem, ...items.slice(0, 9)];
        } else {
          newItems = [...items];
        }
      } else {
        newItems = [newItem];
      }
      return {
        ...state,
        items: newItems,
      };
    }
    case SEARCH_HISTORY.REMOVE:
      return {
        ...state,
        items: state.items.filter(item => item !== action.payload.item),
      };
    case SEARCH_HISTORY.CLEAR:
      return {
        ...state,
        items: [],
      };
    default:
      return state;
  }
}
<commit_msg>increase search history to 30<commit_after>import { SEARCH_HISTORY } from '../constants/actionTypes';

export default function searchHistory(
  state = {
    items: [],
  },
  action = {},
) {
  switch (action.type) {
    case SEARCH_HISTORY.ADD: {
      let newItems;
      const items = state.items;
      const newItem = action.payload.item;
      if (items && items.length) {
        if (items.indexOf(newItem) === -1) {
          newItems = [newItem, ...items.slice(0, 29)];
        } else {
          newItems = [...items];
        }
      } else {
        newItems = [newItem];
      }
      return {
        ...state,
        items: newItems,
      };
    }
    case SEARCH_HISTORY.REMOVE:
      return {
        ...state,
        items: state.items.filter(item => item !== action.payload.item),
      };
    case SEARCH_HISTORY.CLEAR:
      return {
        ...state,
        items: [],
      };
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 * Tim Taubert <tim@timtaubert.de>
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

let {getElementById, createXulElement, getMostRecentWindow} = require("util/browser-windows");

let mainCommandSet = getElementById("mainCommandSet");
let mainKeyset = getElementById("mainKeyset");

// <command id="Browser:NextTabGroup" oncommand="TabView.switchToNextGroup();"/>
let cmd1 = createXulElement("command");
cmd1.setAttribute("id", "Browser:NextTabGroup");
cmd1.setAttribute("oncommand", "TabView.switchToNextGroup();");
mainCommandSet.appendChild(cmd1);

// <command id="Browser:PreviousTabGroup" oncommand="TabView.switchToPreviousGroup();"/>
let cmd2 = createXulElement("command");
cmd2.setAttribute("id", "Browser:PreviousTabGroup");
cmd2.setAttribute("oncommand", "TabView.switchToPreviousGroup();");
mainCommandSet.appendChild(cmd2);

// <key id="key_nextTabGroup" key="&switchTabGroup.commandkey;" command="Browser:NextTabGroup" modifiers="accel"/>
let key1 = createXulElement("key");
key1.setAttribute("id", "key_nextTabGroup");
key1.setAttribute("key", "`");
key1.setAttribute("command", "Browser:NextTabGroup");
key1.setAttribute("modifiers", "accel");
mainKeyset.appendChild(key1);

// <key id="key_previousTabGroup" key="&switchTabGroup.commandkey;" command="Browser:PreviousTabGroup" modifiers="accel,shift"/>
let key2 = createXulElement("key");
key2.setAttribute("id", "key_previousTabGroup");
key2.setAttribute("key", "`");
key2.setAttribute("command", "Browser:PreviousTabGroup");
key2.setAttribute("modifiers", "accel,shift");
mainKeyset.appendChild(key2);

let window = getMostRecentWindow();
let TabView = window.TabView;
let gBrowser = window.gBrowser;

TabView.switchToNextGroup = function () {
  switchGroupItem(false);
}

TabView.switchToPreviousGroup = function () {
  switchGroupItem(true);
}

let switchGroupItem = function (reverse) {
  let numHiddenTabs = gBrowser.tabs.length - gBrowser.visibleTabs.length;
  if (TabView.isVisible() || !numHiddenTabs)
    return;

  TabView._initFrame(function () {
    let groupItems = TabView._window.GroupItems;
    let tabItem = groupItems.getNextGroupItemTab(reverse);
    if (!tabItem)
      return;

    // Switch to the new tab, and close the old group if it's now empty.
    let oldGroupItem = groupItems.getActiveGroupItem();
    gBrowser.selectedTab = tabItem.tab;
    oldGroupItem.closeIfEmpty();
  });
}
<commit_msg>check before applying patch for bug 645371 (do nothing if already fixed)<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 * Tim Taubert <tim@timtaubert.de>
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

let {getElementById, createXulElement, getMostRecentWindow} = require("util/browser-windows");

if (!getElementById("key_nextTabGroup")) {
  let mainCommandSet = getElementById("mainCommandSet");
  let mainKeyset = getElementById("mainKeyset");

  // <command id="Browser:NextTabGroup" oncommand="TabView.switchToNextGroup();"/>
  let cmd1 = createXulElement("command");
  cmd1.setAttribute("id", "Browser:NextTabGroup");
  cmd1.setAttribute("oncommand", "TabView.switchToNextGroup();");
  mainCommandSet.appendChild(cmd1);

  // <command id="Browser:PreviousTabGroup" oncommand="TabView.switchToPreviousGroup();"/>
  let cmd2 = createXulElement("command");
  cmd2.setAttribute("id", "Browser:PreviousTabGroup");
  cmd2.setAttribute("oncommand", "TabView.switchToPreviousGroup();");
  mainCommandSet.appendChild(cmd2);

  // <key id="key_nextTabGroup" key="&switchTabGroup.commandkey;" command="Browser:NextTabGroup" modifiers="accel"/>
  let key1 = createXulElement("key");
  key1.setAttribute("id", "key_nextTabGroup");
  key1.setAttribute("key", "`");
  key1.setAttribute("command", "Browser:NextTabGroup");
  key1.setAttribute("modifiers", "accel");
  mainKeyset.appendChild(key1);

  // <key id="key_previousTabGroup" key="&switchTabGroup.commandkey;" command="Browser:PreviousTabGroup" modifiers="accel,shift"/>
  let key2 = createXulElement("key");
  key2.setAttribute("id", "key_previousTabGroup");
  key2.setAttribute("key", "`");
  key2.setAttribute("command", "Browser:PreviousTabGroup");
  key2.setAttribute("modifiers", "accel,shift");
  mainKeyset.appendChild(key2);

  let window = getMostRecentWindow();
  let TabView = window.TabView;
  let gBrowser = window.gBrowser;

  TabView.switchToNextGroup = function () {
    switchGroupItem(false);
  }

  TabView.switchToPreviousGroup = function () {
    switchGroupItem(true);
  }

  let switchGroupItem = function (reverse) {
    let numHiddenTabs = gBrowser.tabs.length - gBrowser.visibleTabs.length;
    if (TabView.isVisible() || !numHiddenTabs)
      return;

    TabView._initFrame(function () {
      let groupItems = TabView._window.GroupItems;
      let tabItem = groupItems.getNextGroupItemTab(reverse);
      if (!tabItem)
        return;

      // Switch to the new tab, and close the old group if it's now empty.
      let oldGroupItem = groupItems.getActiveGroupItem();
      gBrowser.selectedTab = tabItem.tab;
      oldGroupItem.closeIfEmpty();
    });
  }
}
<|endoftext|>


<commit_before>/*
 * Don't forget to precompile to precompiled-user.js using
 * http://facebook.github.io/react/jsx-compiler.html.
 */

$('title').text('Summit PLP | My Future');
$('style').remove();

function getCourses() {
	courses = [];
	$('').append($.ajax({ type: 'GET', url: 'https://app.mysummitps.org/my/grades', async: false }).responseText).find('div.course.boxed').toArray().forEach(function(elem) {
		elem = $(elem);
		var skill_id = 0;

		courses.push({
			id: courses.length,
			name: elem.find('div.span8>h4').text().slice(0, -1),
			power_pace: elem.find('div.span1.text-right.out-of:eq(0)').text().split('/').map(function(elem) { return parseInt(elem, 10); }),
			additional_pace: elem.find('div.span1.text-right.out-of:eq(1)').text().split('/').map(function(elem) { return parseInt(elem, 10); }),
			overdue_projects: parseInt(elem.find('div.span7>b').text().replace(' projects'), 10),
			cog_skills: elem.find('tbody').children().toArray().map(function(skill) {
				var skill = $(skill);

				return {
					id: skill_id++,
					name: skill.find('td:eq(0)').text(),
					weight: parseInt(skill.find('td:eq(1)').text(), 10),
					score: parseFloat(skill.find('td.scored').text(), 10) || 0
				};
			})
		});
	});

	localStorage.setItem('old_courses', JSON.stringify(courses));
}

courses = JSON.parse(localStorage.getItem('old_courses') || 'null');
if (courses === null) {
	getCourses();
}

var Skill = React.createClass({
	buildTD: function(number) {
		return {number}
	},
	render: function() {
		return (

				{this.props.skill.name}
				<input style={{ height: '100%', width: '54px', margin: '0px', padding: '0px', border: 'none' }} value={this.props.skill.weight} onChange={this.props.onCogWeightChange} />
				{[1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8].map(this.buildTD)}

		);
	}
});

var Course = React.createClass({
	getInitialState: function() {
		var state = {};
		state.course = this.props.course;
		state.cog_avg = this.cog_avg(state.course.cog_skills);
		state.cog_percentage = Math.round((15 * (state.cog_avg - 5) + 70));
		state.power_percentage = Math.round(state.course.power_pace[0] / (state.course.power_pace[1] || 1) * 100);
		state.additional_percentage = Math.round(state.course.additional_pace[0] / (state.course.additional_pace[1] || 1) * 100);
		state.total_percentage = Math.round(state.cog_percentage * 0.7 + state.power_percentage * 0.21 + state.additional_percentage * 0.09);
		state.total_grade = this.letter_grade(state.total_percentage);

		return state;
	},
	updateState: function(children) {
		var newstate = {};

		children.forEach((function(child) {
			switch (child) {
				case 'course': {
					newstate.course = this.state.course;
					break;
				}

				case 'cog_avg': {
					this.state.cog_avg = this.cog_avg(this.state.course.cog_skills);
					newstate.cog_avg = this.state.cog_avg;
					break;
				}

				case 'cog_percentage': {
					this.state.cog_percentage = Math.round(15 * (+this.state.cog_avg - 5) + 70);
					newstate.cog_percentage = this.state.cog_percentage;
					break;
				}

				case 'power_percentage': {
					var retval = Math.round((+this.state.course.power_pace[0] || 0) / (+this.state.course.power_pace[1] || 0) * 100);
					isNaN(retval) && (retval = 100);

					this.state.power_percentage = retval;
					newstate.retval = this.state.retval;
					break;
				}

				case 'additional_percentage': {
					var retval = Math.round((+this.state.course.additional_pace[0] || 0) / (+this.state.course.additional_pace[1] || 0) * 100);
					isNaN(retval) && (retval = 100);

					this.state.additional_percentage = retval;
					newstate.additional_percentage = this.state.additional_percentage;
					break;
				}

				case 'total_percentage': {
					this.state.total_percentage = Math.round(+this.state.cog_percentage * 0.7 + +this.state.power_percentage * 0.21 + +this.state.additional_percentage * 0.09);
					newstate.total_percentage = this.state.total_percentage;
					break;
				}

				case 'total_grade': {
					this.state.total_grade = this.letter_grade(+this.state.total_percentage);
					newstate.total_grade = this.state.total_grade;
					break;
				}
			}
		}).bind(this));

		this.setState(newstate);
	},
	cog_avg: function(skills) {
		var cog_total = 0,
			weight_total = 0;

		for (var i = 0; i < skills.length; i++) {
			cog_total += (+skills[i].score || 0) * (+skills[i].weight || 0);
			weight_total += (+skills[i].weight || 0);
		}

		if (weight_total === 0) {
			return 7;
		}

		return Math.round(cog_total / weight_total * 100) / 100;
	},
	letter_grade: function(percentage) {
		var plusminus = percentage % 10;
		var abcf = (percentage - (plusminus)) / 10;
		var grade = '';

		if (abcf > 9) {
			return 'A+';
		} else if (abcf > 8) {
			grade = 'A';
		} else if (abcf > 7) {
			grade = 'B';
		} else if (abcf > 6) {
			grade = 'C';
		} else {
			return 'Incomplete';
		}

		if (plusminus < 4) {
			grade += '-';
		} else if (plusminus > 6) {
			grade += '+';
		}

		return grade;
	},
	onCogGradeChange: function(skill, e) {
		this.state.course.cog_skills[skill.id].score = +e.target.innerHTML || 0;
		this.updateState(['course', 'cog_avg', 'cog_percentage', 'total_percentage', 'total_grade']);
	},
	onCogWeightChange: function(skill, e) {
		this.state.course.cog_skills[skill.id].weight = e.target.value;
		this.updateState(['course', 'cog_avg', 'cog_percentage', 'total_percentage', 'total_grade']);
	},
	onAssessmentChange: function(type, e) {
		this.state.course[type + '_pace'][0] = e.target.value;
		this.updateState(['course', type + '_percentage', 'total_percentage', 'total_grade']);
	},
	buildSkill: function(skill) {
		return <Skill skill={skill} onCogGradeChange={this.onCogGradeChange.bind(this, skill)} onCogWeightChange={this.onCogWeightChange.bind(this, skill)} />;
	},
	render: function() {
		return (

{this.state.course.name}:

{this.state.total_percentage}%

{this.state.total_grade}

You have {this.state.course.overdue_projects} {this.state.course.overdue_projects === 1 ? 'project' : 'projects'} overdue.

For your cognitive skills, you have an average of:

{this.state.cog_avg}

{this.state.cog_percentage}%

{this.state.cog_avg.toFixed(2)}

									Cognitive Skill
									Weight

									C-

									A+

								{this.state.course.cog_skills.map(this.buildSkill)}

For your power focus areas, you are on pace to complete:

							<input value={this.state.course.power_pace[0]} style={{ width: '20px', border: 'none', textAlign: 'right' }} onChange={this.onAssessmentChange.bind(this, 'power')} />
							/ {this.state.course.power_pace[1]}

{this.state.power_percentage}%

For your additional focus areas, you are on pace to complete:

							<input value={this.state.course.additional_pace[0]} style={{ width: '20px', border: 'none', textAlign: 'right' }} onChange={this.onAssessmentChange.bind(this, 'additional')} />
							/ {this.state.course.additional_pace[1]}

{this.state.additional_percentage}%

		);
	}
});

var App = React.createClass({
	getInitialState: function() {
		return {
			courses: courses
		};
	},
	resetGrades: function() {
		getCourses();
		window.location.reload();
	},
	buildCourse: function(course) {
		return <Course course={course} />;
	},
	render: function() {
		return (

					These grades may not represent your current grades.

					<button onClick={this.resetGrades}>Reset/Update Grades</button>

				{this.state.courses.map(this.buildCourse)}

		);
	}
});

React.render(
	<App />,
	$('body').html('').get(0)
);
<commit_msg>Fix -.<commit_after>/*
 * Don't forget to precompile to precompiled-user.js using
 * http://facebook.github.io/react/jsx-compiler.html.
 */

$('title').text('Summit PLP | My Future');
$('style').remove();

function getCourses() {
	courses = [];
	$('').append($.ajax({ type: 'GET', url: 'https://app.mysummitps.org/my/grades', async: false }).responseText).find('div.course.boxed').toArray().forEach(function(elem) {
		elem = $(elem);
		var skill_id = 0;

		courses.push({
			id: courses.length,
			name: elem.find('div.span8>h4').text().slice(0, -1),
			power_pace: elem.find('div.span1.text-right.out-of:eq(0)').text().split('/').map(function(elem) { return parseInt(elem, 10); }),
			additional_pace: elem.find('div.span1.text-right.out-of:eq(1)').text().split('/').map(function(elem) { return parseInt(elem, 10); }),
			overdue_projects: parseInt(elem.find('div.span7>b').text().replace(' projects'), 10),
			cog_skills: elem.find('tbody').children().toArray().map(function(skill) {
				var skill = $(skill);

				return {
					id: skill_id++,
					name: skill.find('td:eq(0)').text(),
					weight: parseInt(skill.find('td:eq(1)').text(), 10),
					score: parseFloat(skill.find('td.scored').text(), 10) || 0
				};
			})
		});
	});

	localStorage.setItem('old_courses', JSON.stringify(courses));
}

courses = JSON.parse(localStorage.getItem('old_courses') || 'null');
if (courses === null) {
	getCourses();
}

var Skill = React.createClass({
	buildTD: function(number) {
		return {number}
	},
	render: function() {
		return (

				{this.props.skill.name}
				<input style={{ height: '100%', width: '54px', margin: '0px', padding: '0px', border: 'none' }} value={this.props.skill.weight} onChange={this.props.onCogWeightChange} />
				{[1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8].map(this.buildTD)}

		);
	}
});

var Course = React.createClass({
	getInitialState: function() {
		var state = {};
		state.course = this.props.course;
		state.cog_avg = this.cog_avg(state.course.cog_skills);
		state.cog_percentage = Math.round((15 * (state.cog_avg - 5) + 70));
		state.power_percentage = Math.round(state.course.power_pace[0] / (state.course.power_pace[1] || 1) * 100);
		state.additional_percentage = Math.round(state.course.additional_pace[0] / (state.course.additional_pace[1] || 1) * 100);
		state.total_percentage = Math.round(state.cog_percentage * 0.7 + state.power_percentage * 0.21 + state.additional_percentage * 0.09);
		state.total_grade = this.letter_grade(state.total_percentage);

		return state;
	},
	updateState: function(children) {
		var newstate = {};

		children.forEach((function(child) {
			switch (child) {
				case 'course': {
					newstate.course = this.state.course;
					break;
				}

				case 'cog_avg': {
					this.state.cog_avg = this.cog_avg(this.state.course.cog_skills);
					newstate.cog_avg = this.state.cog_avg;
					break;
				}

				case 'cog_percentage': {
					this.state.cog_percentage = Math.round(15 * (+this.state.cog_avg - 5) + 70);
					newstate.cog_percentage = this.state.cog_percentage;
					break;
				}

				case 'power_percentage': {
					var retval = Math.round((+this.state.course.power_pace[0] || 0) / (+this.state.course.power_pace[1] || 0) * 100);
					isNaN(retval) && (retval = 100);

					this.state.power_percentage = retval;
					newstate.retval = this.state.retval;
					break;
				}

				case 'additional_percentage': {
					var retval = Math.round((+this.state.course.additional_pace[0] || 0) / (+this.state.course.additional_pace[1] || 0) * 100);
					isNaN(retval) && (retval = 100);

					this.state.additional_percentage = retval;
					newstate.additional_percentage = this.state.additional_percentage;
					break;
				}

				case 'total_percentage': {
					this.state.total_percentage = Math.round(+this.state.cog_percentage * 0.7 + +this.state.power_percentage * 0.21 + +this.state.additional_percentage * 0.09);
					newstate.total_percentage = this.state.total_percentage;
					break;
				}

				case 'total_grade': {
					this.state.total_grade = this.letter_grade(+this.state.total_percentage);
					newstate.total_grade = this.state.total_grade;
					break;
				}
			}
		}).bind(this));

		this.setState(newstate);
	},
	cog_avg: function(skills) {
		var cog_total = 0,
			weight_total = 0;

		for (var i = 0; i < skills.length; i++) {
			cog_total += (+skills[i].score || 0) * (+skills[i].weight || 0);
			weight_total += (+skills[i].weight || 0);
		}

		if (weight_total === 0) {
			return 7;
		}

		return Math.round(cog_total / weight_total * 100) / 100;
	},
	letter_grade: function(percentage) {
		var plusminus = percentage % 10;
		var abcf = (percentage - (plusminus)) / 10;
		var grade = '';

		if (abcf > 9) {
			return 'A+';
		} else if (abcf > 8) {
			grade = 'A';
		} else if (abcf > 7) {
			grade = 'B';
		} else if (abcf > 6) {
			grade = 'C';
		} else {
			return 'Incomplete';
		}

		if (plusminus < 3) {
			grade += '-';
		} else if (plusminus > 6) {
			grade += '+';
		}

		return grade;
	},
	onCogGradeChange: function(skill, e) {
		this.state.course.cog_skills[skill.id].score = +e.target.innerHTML || 0;
		this.updateState(['course', 'cog_avg', 'cog_percentage', 'total_percentage', 'total_grade']);
	},
	onCogWeightChange: function(skill, e) {
		this.state.course.cog_skills[skill.id].weight = e.target.value;
		this.updateState(['course', 'cog_avg', 'cog_percentage', 'total_percentage', 'total_grade']);
	},
	onAssessmentChange: function(type, e) {
		this.state.course[type + '_pace'][0] = e.target.value;
		this.updateState(['course', type + '_percentage', 'total_percentage', 'total_grade']);
	},
	buildSkill: function(skill) {
		return <Skill skill={skill} onCogGradeChange={this.onCogGradeChange.bind(this, skill)} onCogWeightChange={this.onCogWeightChange.bind(this, skill)} />;
	},
	render: function() {
		return (

{this.state.course.name}:

{this.state.total_percentage}%

{this.state.total_grade}

You have {this.state.course.overdue_projects} {this.state.course.overdue_projects === 1 ? 'project' : 'projects'} overdue.

For your cognitive skills, you have an average of:

{this.state.cog_avg}

{this.state.cog_percentage}%

{this.state.cog_avg.toFixed(2)}

									Cognitive Skill
									Weight

									C-

									A+

								{this.state.course.cog_skills.map(this.buildSkill)}

For your power focus areas, you are on pace to complete:

							<input value={this.state.course.power_pace[0]} style={{ width: '20px', border: 'none', textAlign: 'right' }} onChange={this.onAssessmentChange.bind(this, 'power')} />
							/ {this.state.course.power_pace[1]}

{this.state.power_percentage}%

For your additional focus areas, you are on pace to complete:

							<input value={this.state.course.additional_pace[0]} style={{ width: '20px', border: 'none', textAlign: 'right' }} onChange={this.onAssessmentChange.bind(this, 'additional')} />
							/ {this.state.course.additional_pace[1]}

{this.state.additional_percentage}%

		);
	}
});

var App = React.createClass({
	getInitialState: function() {
		return {
			courses: courses
		};
	},
	resetGrades: function() {
		getCourses();
		window.location.reload();
	},
	buildCourse: function(course) {
		return <Course course={course} />;
	},
	render: function() {
		return (

					These grades may not represent your current grades.

					<button onClick={this.resetGrades}>Reset/Update Grades</button>

				{this.state.courses.map(this.buildCourse)}

		);
	}
});

React.render(
	<App />,
	$('body').html('').get(0)
);
<|endoftext|>


<commit_before>var debug = require('debug')('carcass:proto:loaderSync');

var isCallable = require('es5-ext/lib/Object/is-callable');

// Loader
// ---
// The synchronous version.
module.exports = {
    source: source,
    parser: parser,
    reload: reload,
    get: get
};

/**
 * Get value. Use cache if available.
 *
 * @return {value}
 */
function get() {
    var value = isCallable(this.cacheGet) && this.cacheGet();
    if (null != value) return value;
    return this.reload();
}

/**
 * Reload from source. Parse source if a parser is available. Save to cache if
 * available.
 *
 * @return {value}
 */
function reload() {
    if (null == this._source) return null;
    var value = isCallable(this._parser) ? this._parser(this._source)
        : this._source;
    if (isCallable(this.cacheSet)) this.cacheSet(value);
    return value;
}

/**
 * Accessor.
 *
 * @return {parser | this}
 */
function parser(_parser) {
    if (0 == arguments.length) return this._parser;
    // TODO: valid-callable?
    this._parser = _parser;
    return this;
}

/**
 * Accessor.
 *
 * @return {source | this}
 */
function source(_source) {
    if (0 == arguments.length) return this._source;
    // TODO: valid-value?
    this._source = _source;
    return this;
}
<commit_msg>Found a bug..<commit_after>var debug = require('debug')('carcass:proto:loaderSync');

var isCallable = require('es5-ext/lib/Object/is-callable');

// Loader
// ---
// The synchronous version.
module.exports = {
    source: source,
    parser: parser,
    reload: reload,
    get: get
};

/**
 * Get value. Use cache if available.
 *
 * @return {value}
 */
function get() {
    // FIXME: doesn't work without cache.
    var value = isCallable(this.cacheGet) && this.cacheGet();
    if (null != value) return value;
    return this.reload();
}

/**
 * Reload from source. Parse source if a parser is available. Save to cache if
 * available.
 *
 * @return {value}
 */
function reload() {
    if (null == this._source) return null;
    var value = isCallable(this._parser) ? this._parser(this._source)
        : this._source;
    if (isCallable(this.cacheSet)) this.cacheSet(value);
    return value;
}

/**
 * Accessor.
 *
 * @return {parser | this}
 */
function parser(_parser) {
    if (0 == arguments.length) return this._parser;
    // TODO: valid-callable?
    this._parser = _parser;
    return this;
}

/**
 * Accessor.
 *
 * @return {source | this}
 */
function source(_source) {
    if (0 == arguments.length) return this._source;
    // TODO: valid-value?
    this._source = _source;
    return this;
}
<|endoftext|>


<commit_before>import React from 'react';
import * as Objects from './objects/_index';

import ObjectActions from '../../actions/object';
import ObjectStore from '../../stores/object';

export default class PreviewPane extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rowResult: null
    };
  }

  componentDidMount() {
    this.unsubscribe = ObjectStore.listen((data) => {
      this.onUpdate(data);
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onUpdate(data){
    this.setState({
      rowResult: data.parsedCode
    });
  }

  capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  render() {
    if(!this.state.rowResult || !this.state.rowResult.checks || this.state.rowResult.checks.constructor !== Array ||
      !this.state.rowResult.assignments || this.state.rowResult.assignments.constructor !== Array){
        return false;
    }

    const checks = this.state.rowResult.checks.map((check, i) => {
      const ObjectRef = Objects[this.capitalizeFirstLetter(check.object)];
      if(!ObjectRef) return false;

      const classNames = 'check' + (check.valid ? ' valid' : '');
      return
<ObjectRef/> = {check.value}
;
    });

    const assignments = this.state.rowResult.assignments.map((assignment, i) => {
      const ObjectRef = Objects[this.capitalizeFirstLetter(assignment.object)];
      if(!ObjectRef) return false;

      const classNames = 'assignment' + (assignment.valid ? ' valid' : '');
      return
<ObjectRef/> = {assignment.value}
;
    });

    let output = [];

    if(checks.length > 0) {
      output.push(

          { checks }

      );

      if(checks.length > 1) {
        output.push(

            EN

        );
      }

      if(assignments.length > 0) {
        output.push(

            // Hier staat een computer //

        );
      }
    }

    if(assignments.length > 0) {
      output.push(

          { assignments }

      );
    }

    return(

        { output }

    );
  }
}
<commit_msg>Simplify rowResult check.<commit_after>import React from 'react';
import * as Objects from './objects/_index';

import ObjectActions from '../../actions/object';
import ObjectStore from '../../stores/object';

export default class PreviewPane extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rowResult: null
    };
  }

  componentDidMount() {
    this.unsubscribe = ObjectStore.listen((data) => {
      this.onUpdate(data);
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onUpdate(data){
    this.setState({
      rowResult: data.parsedCode
    });
  }

  capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  render() {
    if(!this.state.rowResult || !(this.state.rowResult.checks || this.state.rowResult.assignments)){
        return false;
    }

    const checks = this.state.rowResult.checks.map((check, i) => {
      const ObjectRef = Objects[this.capitalizeFirstLetter(check.object)];
      if(!ObjectRef) return false;

      const classNames = 'check' + (check.valid ? ' valid' : '');
      return
<ObjectRef/> = {check.value}
;
    });

    const assignments = this.state.rowResult.assignments.map((assignment, i) => {
      const ObjectRef = Objects[this.capitalizeFirstLetter(assignment.object)];
      if(!ObjectRef) return false;

      const classNames = 'assignment' + (assignment.valid ? ' valid' : '');
      return
<ObjectRef/> = {assignment.value}
;
    });

    let output = [];

    if(checks.length > 0) {
      output.push(

          { checks }

      );

      if(checks.length > 1) {
        output.push(

            EN

        );
      }

      if(assignments.length > 0) {
        output.push(

            // Hier staat een computer //

        );
      }
    }

    if(assignments.length > 0) {
      output.push(

          { assignments }

      );
    }

    return(

        { output }

    );
  }
}
<|endoftext|>