<commit_before>// ==UserScript==
// @id             iitc-commfilter
// @name           IITC plugin: COMM Filter
// @category       Info
// @version        0.1.0.20160912.110500
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      https://github.com/Finntaur/monkey/raw/master/iitc-commfilter.meta.js
// @downloadURL    https://github.com/Finntaur/monkey/raw/master/iitc-commfilter.user.js
// @description    [commfilter-2016-09-12-110500] Filter COMM chat messages to hide unwanted content.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.commFilter = function() {};
window.plugin.commFilter.enabled = true;
window.plugin.commFilter.filters = [ /xmps\.biz/i, /ingress\-store\.com/i ];
window.plugin.commFilter.addHooks = function() {
    addHook('publicChatDataAvailable' , window.plugin.commFilter.processChatData);
    addHook('factionChatDataAvailable' , window.plugin.commFilter.processChatData);
};

window.plugin.commFilter.toggleFiltering = function() {
    window.plugin.commFilter.enabled = !window.plugin.commFilter.enabled;
    console.log("COMM Filtering " + ( window.plugin.commFilter.enabled ? "ENABLED" : "DISABLED" ));
    window.plugin.commFilter.setTogglerStyle();
};

window.plugin.commFilter.setTogglerStyle = function() {
    if ( window.plugin.commFilter.enabled ) {
        $("#commFilter").css("color", "#ffce00");
        $("#commFilter").css("font-weight", "bold");
    } else {
        $("#commFilter").css("color", "red");
        $("#commFilter").css("font-weight", "normal");
    }
};

window.plugin.commFilter.processChatData = function(data) {
//    console.log("Received chat data:");
//    console.log(data.processed);
    var i, j, re;
    var stack = [];
    var flag = false;
    for ( i in data.processed ) {
        for ( j in data.processed[i] ) {
            for ( re in window.plugin.commFilter.filters ) {
                if ( window.plugin.commFilter.filters[re].exec("" + data.processed[i][j]) ) {
                    flag = true;
                    stack.push(i);
                    break;
                }
            }
            if ( flag ) {
                flag = false;
                break;
            }
        }
    }
    if ( window.plugin.commFilter.enabled ) {
        console.log("COMM Filter: filtered " + stack.length + " messages.");
        for ( i in stack ) {
            delete data.processed[stack[i]];
        }
    } else {
        console.log("COMM Filter: matched " + stack.length + " messages.");
    }
};

var setup = function() {
    window.plugin.commFilter.addHooks();
    $("#toolbox").append(' COMM/F');
    window.plugin.commFilter.setTogglerStyle();
};

// PLUGIN END //////////////////////////////////////////////////////////

setup.info = plugin_info; //add the script info data to the function as a property
if(!window.bootPlugins) window.bootPlugins = [];
window.bootPlugins.push(setup);
// if IITC has already booted, immediately run the 'setup' function
if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);
<commit_msg>Update iitc-commfilter.user.js<commit_after>// ==UserScript==
// @id             iitc-commfilter
// @name           IITC plugin: COMM Filter
// @category       Info
// @version        0.1.0.20160912.111500
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      https://github.com/Finntaur/monkey/raw/master/iitc-commfilter.meta.js
// @downloadURL    https://github.com/Finntaur/monkey/raw/master/iitc-commfilter.user.js
// @description    [commfilter-2016-09-12-111500] Filter COMM chat messages to hide unwanted content.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.commFilter = function() {};
window.plugin.commFilter.enabled = true;
window.plugin.commFilter.filters = [
    /xmps\.biz/i,
    /ingress\-store\.com/i,
    /ingressstore\.ru/i
];
window.plugin.commFilter.addHooks = function() {
    addHook('publicChatDataAvailable' , window.plugin.commFilter.processChatData);
    addHook('factionChatDataAvailable' , window.plugin.commFilter.processChatData);
};

window.plugin.commFilter.toggleFiltering = function() {
    window.plugin.commFilter.enabled = !window.plugin.commFilter.enabled;
    console.log("COMM Filtering " + ( window.plugin.commFilter.enabled ? "ENABLED" : "DISABLED" ));
    window.plugin.commFilter.setTogglerStyle();
};

window.plugin.commFilter.setTogglerStyle = function() {
    if ( window.plugin.commFilter.enabled ) {
        $("#commFilter").css("color", "#ffce00");
        $("#commFilter").css("font-weight", "bold");
    } else {
        $("#commFilter").css("color", "red");
        $("#commFilter").css("font-weight", "normal");
    }
};

window.plugin.commFilter.processChatData = function(data) {
//    console.log("Received chat data:");
//    console.log(data.processed);
    var i, j, re;
    var stack = [];
    var flag = false;
    for ( i in data.processed ) {
        for ( j in data.processed[i] ) {
            for ( re in window.plugin.commFilter.filters ) {
                if ( window.plugin.commFilter.filters[re].exec("" + data.processed[i][j]) ) {
                    flag = true;
                    stack.push(i);
                    break;
                }
            }
            if ( flag ) {
                flag = false;
                break;
            }
        }
    }
    if ( window.plugin.commFilter.enabled ) {
        console.log("COMM Filter: filtered " + stack.length + " messages.");
        for ( i in stack ) {
            delete data.processed[stack[i]];
        }
    } else {
        console.log("COMM Filter: matched " + stack.length + " messages.");
    }
};

var setup = function() {
    window.plugin.commFilter.addHooks();
    $("#toolbox").append(' COMM/F');
    window.plugin.commFilter.setTogglerStyle();
};

// PLUGIN END //////////////////////////////////////////////////////////

setup.info = plugin_info; //add the script info data to the function as a property
if(!window.bootPlugins) window.bootPlugins = [];
window.bootPlugins.push(setup);
// if IITC has already booted, immediately run the 'setup' function
if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);
<|endoftext|>


<commit_before>function c(a,b,d){
	if(typeof a !== "number" && typeof b === "function"){
		return mapWorker(a,b,d);
	}else if(typeof a === "object" && !Array.isArray(a)){
		if(typeof b === "number"){
			return queue(a,b,d);
		}else{
			return object(a);
		}
	}else if(typeof a !== "number"){
		return b ? single(a,b):multiUse(a);
	}else if(typeof a === "number"){
		return !b ? incrementalMapReduce(a):nonIncrementalMapReduce(a);
	}
}
c.reducer = rWorker;
c.worker = makeWorker;
c.makeUrl = function (fileName) {
	var link = document.createElement("link");
	link.href = fileName;
	return link.href;
};
c.ajax = function(url,after,notjson){
	var txt=!notjson?'JSON.parse(request.responseText)':"request.responseText";
	var resp = after?"("+after.toString()+")("+txt+",_cb)":txt;
	var func = 'function (url, _cb) {\n\
		var request = new XMLHttpRequest();\n\
		request.open("GET", url);\n\
			request.onreadystatechange = function() {\n\
				var _resp;\n\
				if (request.readyState === 4 && request.status === 200) {\n'+
					'_resp = '+resp+';\n\
					if(typeof _resp!=="undefined"){_cb(_resp);}\n\
					}\n\
			};\n\
			request.onerror=function(e){throw(e);}\n\
		request.send();\n\
	}';
	return c(func,c.makeUrl(url));
};
function initBrowser(c){
	var origCW = global.cw;
	c.noConflict=function(newName){
		global.cw = origCW;
		if(newName){
			global[newName]=c;
		}
	};
	global.communist = c;
	global.cw = c;

}
if(!('exports' in module)){
	initBrowser(c);
} else {
	module.exports=c;
}
<commit_msg>Update wrapup.js<commit_after>function c(a,b,d){
	if(typeof a !== "number" && typeof b === "function"){
		return mapWorker(a,b,d);
	}else if(typeof a === "object" && !Array.isArray(a)){
		if(typeof b === "number"){
			return queue(a,b,d);
		}else{
			return object(a);
		}
	}else if(typeof a !== "number"){
		return b ? single(a,b):multiUse(a);
	}else if(typeof a === "number"){
		return !b ? incrementalMapReduce(a):nonIncrementalMapReduce(a);
	}
}
c.reducer = rWorker;
c.worker = makeWorker;
c.makeUrl = function (fileName) {
	var link = document.createElement("link");
	link.href = fileName;
	return link.href;
};
c.ajax = function(url,after,notjson){
	var txt=!notjson?'JSON.parse(request.responseText)':"request.responseText";
	var resp = after?"("+after.toString()+")("+txt+",_cb)":txt;
	var func = 'function (url, _cb) {\n\
		var request = new XMLHttpRequest();\n\
		request.open("GET", url);\n\
			request.onreadystatechange = function() {\n\
				var _resp;\n\
				if (request.readyState === 4 && request.status === 200) {\n'+
					'_resp = '+resp+';\n\
					if(typeof _resp!=="undefined"){_cb(_resp);}\n\
					}\n\
			};\n\
			request.onerror=function(e){throw(e);}\n\
		request.send();\n\
	}';
	return c(func,c.makeUrl(url));
};
function initBrowser(c){
	var origCW = global.cw;
	c.noConflict=function(newName){
		global.cw = origCW;
		if(newName){
			global[newName]=c;
		}
	};
	global.communist = c;
	global.cw = c;

}
if(typeof module === "undefined" || !('exports' in module)){
	initBrowser(c);
} else {
	module.exports=c;
}
<|endoftext|>


<commit_before>// require.config({
//   baseUrl: 'asset/js',
//   paths: {
//     jquery: 'http://libs.baidu.com/jquery/2.0.0/jquery.min.js'
//   }
// });
alert('requiring...')<commit_msg>test 34<commit_after>// require.config({
//   baseUrl: 'asset/js',
//   paths: {
//     jquery: 'http://libs.baidu.com/jquery/2.0.0/jquery.min.js'
//   }
// });
alert('requiring...222')<|endoftext|>


<commit_before>const Promise = require('bluebird')
const fs = require('fs')
const _ = require('lodash')

exports = module.exports = {
  write
}

function write(filename, data) {

  return Promise
  .resolve({filename, data})
  .then(_ensureFileExists)
  .then(_readExisting)
  .then(_consolidateFile)
  .then(_writeData)
}

function _ensureFileExists(params) {
  fs.closeSync(fs.openSync(params.filename, 'a'))
  return params
}

function _readExisting(params) {
  const p = Promise.defer()
  fs.readFile(params.filename, 'utf8', (err, data) => {
    if (err) {
      p.reject(err)
    } else {
      if (!data) {
        params.existing = {}
      } else {
        params.existing = JSON.parse(data)
      }
      p.resolve(params)
    }
  })
  return p.promise
}

function _consolidateFile(params) {
  const existing = params.existing
  const parsed = params.data
  const result = _.unionBy(parsed, existing, 'cannonical')
  params.result = result
  return params
}

function _writeData(params) {
  const p = Promise.defer()
  const dataStr = JSON.stringify(params.result)
  fs.writeFile(params.filename, dataStr, (err) => {
    if (!err) {
      p.resolve(params.filename)
    } else {
      p.reject(err)
    }
  })
  return p.promise
}
<commit_msg>results are ordered by timestamp<commit_after>const Promise = require('bluebird')
const fs = require('fs')
const _ = require('lodash')

exports = module.exports = {
  write
}

function write(filename, data) {

  return Promise
  .resolve({filename, data})
  .then(_ensureFileExists)
  .then(_readExisting)
  .then(_consolidateFile)
  .then(_writeData)
}

function _ensureFileExists(params) {
  fs.closeSync(fs.openSync(params.filename, 'a'))
  return params
}

function _readExisting(params) {
  const p = Promise.defer()
  fs.readFile(params.filename, 'utf8', (err, data) => {
    if (err) {
      p.reject(err)
    } else {
      if (!data) {
        params.existing = {}
      } else {
        params.existing = JSON.parse(data)
      }
      p.resolve(params)
    }
  })
  return p.promise
}

function _consolidateFile(params) {
  const existing = params.existing
  const parsed = params.data
  let result = _.unionBy(parsed, existing, 'cannonical')
  result = _.orderBy(result, 'timestamp', 'desc')
  params.result = result
  return params
}

function _writeData(params) {
  const p = Promise.defer()
  const dataStr = JSON.stringify(params.result)
  fs.writeFile(params.filename, dataStr, (err) => {
    if (!err) {
      p.resolve(params.filename)
    } else {
      p.reject(err)
    }
  })
  return p.promise
}
<|endoftext|>


<commit_before>/**
 * Faster DOM manipulation
 * The most basic operations, but much faster than jquery. (mostly)
 * @author Vadim Kr.
 * @copyright (c) 2013 bndr
 * @license http://creativecommons.org/licenses/by-sa/3.0/legalcode
 */

function FasterDom(element) {
    this.type = element[0];
    this.name = element.substr(1, element.length);
    this.element = (this.type === "#") ? document.getElementById(this.name) : Array.prototype.slice.call(document.getElementsByClassName(this.name));
}
FasterDom.prototype = {
    constructor: FasterDom,
    attr: function (name, value) {
        if (typeof value == "undefined") {
            return this.element.getAttribute(name);
        }
        if (!this.checkIf(this.element, "Array")) {
            this.set(this.element, name, value);
        } else {
            var i = this.element.length;
            while (i--) {
                this.set(this.element[i], name, value);
            }
        }
        return this;
    }, set: function (element, name, value) {
        if (this.checkIf(name, "String")) {
            element.setAttribute(name, value);
        } else if (this.checkIf(name, "Object")) {
            for (var property in name) {
                element.setAttribute(property, name[property]);
            }
        }
    },
    html: function (html) {
        if (typeof html == "undefined") {
            return this.element.innerHTML;
        }
        if (!this.checkIf(this.element, "Array")) {
            this.element.innerHTML = html;
        } else {
            var len = this.element.length;
            for (var i = 0; i < len; i++) {
                var el = this.element[i];
                var el2 = this.element[len - 1];
                el.innerHTML = html;
                el2.innerHTML = html;
                len--;
            }
        }
        return this;
    },
    css: function (obj) {
        if (!this.checkIf(this.element, "Array")) {
            if (typeof obj == "undefined") {
                return this.element.style;
            }
            for (var key in obj) {
                this.element.style[key] = obj[key];
            }
        } else {
            var len = this.element.length;
            while (len--) {
                for (var key in obj) {
                    this.element[len].style[key] = obj[key];
                }
            }
        }
        return this;
    },
    hide: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.style.display = 'none';
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].style.display = 'none';
            }
        }
        return this;
    },
    show: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.style.display = 'block';
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].style.display = 'block';
            }
        }
        return this;
    }, append: function (doc) {
        if (!this.checkIf(this.element, "Array")) {
            if (this.checkIf(doc, "String"))
                this.element.insertAdjacentHTML('beforeend', doc);
            else
                this.element.appendChild(doc.cloneNode(true));
        } else {
            var len = this.element.length;
            var type = this.checkIf(doc, "String");
            while (len--) {
                if (type) {
                    this.element[len].insertAdjacentHTML('beforeend', doc);
                } else {
                    this.element[len].appendChild(doc.cloneNode(true));
                }
            }
        }

    }, prepend: function (doc) {
        if (!this.checkIf(this.element, "Array")) {
            if (this.checkIf(doc, "String"))
                this.element.insertAdjacentHTML('afterbegin', doc);
            else
                this.element.insertBefore(doc.cloneNode(true), this.element.firstChild);
        } else {
            var len = this.element.length;
            var type = this.checkIf(doc, "String");
            while (len--) {
                if (type) {
                    this.element[len].insertAdjacentHTML('afterbegin', doc);
                } else {
                    this.element[len].insertBefore(doc.cloneNode(true), this.element[len].firstChild);
                }
            }
        }
    }, remove: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.parentNode && this.element.parentNode.removeChild(this.element);
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].parentNode && this.element[len].parentNode.removeChild(this.element[len]);
            }
        }
    },
    get: function () {
        return this.element;
    },
    checkIf: function (obj, type) {
        return Object.prototype.toString.call(obj) == '[object ' + type + ']';
    }
}<commit_msg>comment update<commit_after>/**
 * Faster DOM manipulation
 * The most basic operations, but much faster than jquery. (mostly)
 * @author Vadim Kr.
 */

function FasterDom(element) {
    this.type = element[0];
    this.name = element.substr(1, element.length);
    this.element = (this.type === "#") ? document.getElementById(this.name) : Array.prototype.slice.call(document.getElementsByClassName(this.name));
}
FasterDom.prototype = {
    constructor: FasterDom,
    attr: function (name, value) {
        if (typeof value == "undefined") {
            return this.element.getAttribute(name);
        }
        if (!this.checkIf(this.element, "Array")) {
            this.set(this.element, name, value);
        } else {
            var i = this.element.length;
            while (i--) {
                this.set(this.element[i], name, value);
            }
        }
        return this;
    }, set: function (element, name, value) {
        if (this.checkIf(name, "String")) {
            element.setAttribute(name, value);
        } else if (this.checkIf(name, "Object")) {
            for (var property in name) {
                element.setAttribute(property, name[property]);
            }
        }
    },
    html: function (html) {
        if (typeof html == "undefined") {
            return this.element.innerHTML;
        }
        if (!this.checkIf(this.element, "Array")) {
            this.element.innerHTML = html;
        } else {
            var len = this.element.length;
            for (var i = 0; i < len; i++) {
                var el = this.element[i];
                var el2 = this.element[len - 1];
                el.innerHTML = html;
                el2.innerHTML = html;
                len--;
            }
        }
        return this;
    },
    css: function (obj) {
        if (!this.checkIf(this.element, "Array")) {
            if (typeof obj == "undefined") {
                return this.element.style;
            }
            for (var key in obj) {
                this.element.style[key] = obj[key];
            }
        } else {
            var len = this.element.length;
            while (len--) {
                for (var key in obj) {
                    this.element[len].style[key] = obj[key];
                }
            }
        }
        return this;
    },
    hide: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.style.display = 'none';
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].style.display = 'none';
            }
        }
        return this;
    },
    show: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.style.display = 'block';
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].style.display = 'block';
            }
        }
        return this;
    }, append: function (doc) {
        if (!this.checkIf(this.element, "Array")) {
            if (this.checkIf(doc, "String"))
                this.element.insertAdjacentHTML('beforeend', doc);
            else
                this.element.appendChild(doc.cloneNode(true));
        } else {
            var len = this.element.length;
            var type = this.checkIf(doc, "String");
            while (len--) {
                if (type) {
                    this.element[len].insertAdjacentHTML('beforeend', doc);
                } else {
                    this.element[len].appendChild(doc.cloneNode(true));
                }
            }
        }

    }, prepend: function (doc) {
        if (!this.checkIf(this.element, "Array")) {
            if (this.checkIf(doc, "String"))
                this.element.insertAdjacentHTML('afterbegin', doc);
            else
                this.element.insertBefore(doc.cloneNode(true), this.element.firstChild);
        } else {
            var len = this.element.length;
            var type = this.checkIf(doc, "String");
            while (len--) {
                if (type) {
                    this.element[len].insertAdjacentHTML('afterbegin', doc);
                } else {
                    this.element[len].insertBefore(doc.cloneNode(true), this.element[len].firstChild);
                }
            }
        }
    }, remove: function () {
        if (!this.checkIf(this.element, "Array")) {
            this.element.parentNode && this.element.parentNode.removeChild(this.element);
        } else {
            var len = this.element.length;
            while (len--) {
                this.element[len].parentNode && this.element[len].parentNode.removeChild(this.element[len]);
            }
        }
    },
    get: function () {
        return this.element;
    },
    checkIf: function (obj, type) {
        return Object.prototype.toString.call(obj) == '[object ' + type + ']';
    }
}<|endoftext|>


<commit_before>(function(){

var mi2 = mi2JS;

mi2._xClickCancel = function(el, end){

	// if disabled at any level
	if(el.hasAttribute(mi2JS.disabledAttribute)) return true;

	// if listen is on the root node of component
	if(el === end) return false;

	// do not mess with other components
	comp = el.getAttribute('as');
	return (comp && el != this.el && !(comp == 'Base' || comp =='Base' ));
};

mi2._xClickEventData = function(el,evt, end){
	var evtNames = [], actions = [], comp, cancelClick = false;
	while(true){
		if(mi2._xClickCancel(el, end)) cancelClick = true;

		if(el.hasAttribute('event')) evtNames.push(el.getAttribute('event'));
		if(el.hasAttribute('action')) actions.push(el.getAttribute('action'));

		if(el == end) break;
		el = el.parentNode;
	}

	return {
			action:actions[0],
			actions:actions,
			events:evtNames,
			name: evtNames[0],
			domEvent: evt,
			cancelClick: cancelClick,
			target: el,
			required: true,
			fireTo: 'parent'
		};
};

mi2.xclick = function(comp, attrValue){
	// udpaters not needed
	mi2._xClickListen(comp.el,attrValue,null,comp);
}

mi2._xClickListen = function(n, attrValue, updaters, parentComp){
	if(!parentComp) return;
	parentComp.listen(n,'click',function(evt){
		try{
			var evtData = mi2._xClickEventData(evt.target, evt,n);
			var context;
			if(typeof attrValue == 'function'){
				context = attrValue(evt, evtData.action);
			}else if(typeof attrValue == 'string'){
				evtData.name = attrValue;
			}

			evtData.context = context;

			// WORKAROUND to be compatible with base/Button
			// changing fireEvent recognitionf of skipping the initiator component
			// would break base/Button behavior, so this trick is used to make it work along
			evtData.__src = parentComp;

			if(evtData.name && !evtData.cancelClick){
				parentComp.fireEvent(evtData);
			}

		}catch(e){
			mi2.logError('problem activating click',evt, {target:evt.target,parent:parentComp});
			throw e;
		}
	});
}

mi2.registerDirective('x-click', function(el, comp, value, updaters, parentComp, options){
	if(comp) throw new Error('x-click not supported on component nodes');
	mi2._xClickListen(el, value, updaters, parentComp);
});

})();<commit_msg>Update x-click.js<commit_after>(function(){

var mi2 = mi2JS;

mi2._xClickCancel = function(el, end){

	// if disabled at any level
	if(el.hasAttribute(mi2JS.disabledAttribute)) return true;

	// if listen is on the root node of component
	if(el === end) return false;

	// do not mess with other components
	comp = el.getAttribute('as');
	return (comp && el != this.el && !(comp == 'Base' || comp =='Base' ));
};

mi2._xClickEventData = function(el,evt, end){
	var evtNames = [], actions = [], comp, cancelClick = false;
	while(true){
		if(mi2._xClickCancel(el, end)) cancelClick = true;

		if(el.hasAttribute('event')) evtNames.push(el.getAttribute('event'));
		if(el.hasAttribute('action')) actions.push(el.getAttribute('action'));

		if(el == end) break;
		el = el.parentNode;
	}

	return {
			action:actions[0],
			actions:actions,
			events:evtNames,
			name: evtNames[0],
			domEvent: evt,
			cancelClick: cancelClick,
			target: el,
			required: true,
			fireTo: 'parent'
		};
};

mi2.xclick = function(comp, attrValue){
	// udpaters not needed
	mi2._xClickListen(comp.el,attrValue,null,comp);
}

mi2._xClickListen = function(n, attrValue, updaters, parentComp){
	if(!parentComp) return;
	parentComp.listen(n,'click',function(evt){
		try{
			var evtData = mi2._xClickEventData(evt.target, evt, n);
			var context;
			if(typeof attrValue == 'function'){
				context = attrValue(evt, evtData.action);
			}else if(typeof attrValue == 'string'){
				evtData.name = attrValue;
			}

			evtData.context = context;

			// WORKAROUND to be compatible with base/Button
			// changing fireEvent recognitionf of skipping the initiator component
			// would break base/Button behavior, so this trick is used to make it work along
			evtData.__src = parentComp;

			if(evtData.name && !evtData.cancelClick){
				parentComp.fireEvent(evtData);
			}

		}catch(e){
			mi2.logError('problem activating click',evt, {target:evt.target,parent:parentComp});
			throw e;
		}
	});
}

mi2.registerDirective('x-click', function(el, comp, value, updaters, parentComp, options){
	if(comp) throw new Error('x-click not supported on component nodes');
	mi2._xClickListen(el, value, updaters, parentComp);
});

})();<|endoftext|>


<commit_before><commit_msg>update dendro js<commit_after><|endoftext|>


<commit_before>angular.module('sikre.directives', [])
  .directive("serviceList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'services',
      controller: function ($http, $scope) {

        $scope.getService = function (serviceId) {
          $http.get(mainAPIUrl + 'services/' + serviceId)
            .success(function (data, status) {
              $scope.services = data;
              $scope.lockedService = false;
              $timeout(function () {
                $scope.lockedService = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, serviceTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the service data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedService) {
            return '';
          } else {
            return 'includes/services.html';
          }
        };
      },
    };
  })

  .directive("itemList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'items',
      controller: function ($http, $scope) {

        $scope.getItem = function (groupId) {
          $http.get(mainAPIUrl + 'items?group=' + groupId)
            .success(function (data, status) {
              $scope.items = data;
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedItem) {
            return '';
          } else {
            return 'includes/items.html';
          }
        };
      },
    };
  })

  .directive("addItem", function(){
      return {
          restrict: 'A',
          templateUrl: 'includes/add-item.html',
          controllerAs: 'additem',
          controller: function($http, $scope) {
              $http.post(mainAPIUrl + 'items/')
              .success(function(data, status, headers, config) {
                  $.notify("Data saved successfully", "success");
              })
              .error(function(data, status, headers, config) {
                  $.notify("Can't access the API. We will disable the add functionality", "error");
                  // TODO: Decide if disabling the button or remove it completely
                  $(".additem").addClass("disabled");
                  $(".additem").prop("disabled", true);
                  // This removes the button
                  //$(".additem").remove();
              });
          }
      };
  });
<commit_msg>Directive patching<commit_after>angular.module('sikre.directives', [])
  .directive("serviceList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'services',
      controller: function ($http, $scope) {

        $scope.getService = function (serviceId) {
          $http.get(mainAPIUrl + 'services/' + serviceId)
            .success(function (data, status) {
              $scope.services = data;
              $scope.lockedService = false;
              $timeout(function () {
                $scope.lockedService = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, serviceTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the service data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedService) {
            return '';
          } else {
            return 'includes/services.html';
          }
        };
      },
    };
  })

  .directive("itemList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'items',
      controller: function ($http, $scope) {

        $scope.getItem = function (groupId) {
          $http.get(mainAPIUrl + 'items?group=' + groupId)
            .success(function (data, status) {
              $scope.items = data;
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedItem) {
            return '';
          } else {
            return 'includes/items.html';
          }
        };
      },
    };
  })

  .directive("addItem", function () {
    return {
      restrict: 'A',
      templateUrl: 'includes/add-item.html',
      controllerAs: 'additem',
      controller: function ($http, $scope) {
        $http.post(mainAPIUrl + 'items/')
          .success(function (data, status) {
            $.notify("Data saved successfully", "success");
          })
          .error(function (data, status) {
            $.notify("Can't access the API. We will disable the add functionality", "error");
            // TODO: Decide if disabling the button or remove it completely
            $(".additem").addClass("disabled");
            $(".additem").prop("disabled", true);
            // This removes the button
            //$(".additem").remove();
          });
      }
    };
  })

  .directive("addService", function () {
    return {
      restrict: 'A',
      templateUrl: 'includes/add-service.html',
      controllerAs: 'addservice',
      controller: function ($http) {
        $http.post(mainAPIUrl + 'services/')
          .success(function (data, status) {
            $.notify("Data saved successfully", "success");
          })
          .error(function (data, status) {
            $.notify("Can't access the API. We will disable the add functionality", "error");
              // TODO: Decide if disabling the button or remove it completely
            $(".additem").addClass("disabled");
            $(".additem").prop("disabled", true);
              // This removes the button
              //$(".additem").remove();
          });
      }
    };
  });
<|endoftext|>


<commit_before>// knockout-arrayTransforms 0.3.0 (https://github.com/mwiencek/knockout-arrayTransforms)
// Released under the MIT (X11) License; see the LICENSE file in the official code repository.

(function (factory) {
    if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
        factory(module.exports = require("knockout"));
    } else if (typeof define === "function" && define.amd) {
        define(["knockout"], factory);
    } else {
        factory(window.ko);
    }
})(function (ko) {

    var transformClasses = emptyObject();

    function applyChanges(changes) {
        var mappedItems = this.mappedItems,
            moves = emptyObject(),
            offset = 0;

        for (var i = 0, change; change = changes[i]; i++) {
            var status = change.status;

            if (status === "retained") {
                continue;
            }

            var index = change.index,
                moved = change.moved,
                value = change.value,
                item = change.mappedItem,
                tmpItem;

            if (moved !== undefined) {
                // For added statuses, index is a position in the new
                // array and moved is a position in the old array. For
                // deleted statuses, it's the opposite.
                if (status === "added") {
                    var to = index, from = moved + offset;

                } else if (status === "deleted") {
                    var to = moved, from = index + offset;
                }

                if (moves[to] === undefined) {
                    moves[to] = true;
                    item = mappedItems[from];
                    mappedItems.splice(from, 1)
                    mappedItems.splice(to, 0, item);

                    if (to > from) {
                        for (var j = from; j < to; j++) {
                            tmpItem = mappedItems[j];
                            tmpItem.index(tmpItem.index.peek() - 1);
                        }
                    } else {
                        for (var j = to + 1; j <= from; j++) {
                            tmpItem = mappedItems[j];
                            tmpItem.index(tmpItem.index.peek() + 1);
                        }
                    }

                    this.valueMoved(value, to, from, item.mappedValue, item);
                }
            }

            if (status === "added") {
                if (moved === undefined) {
                    item = emptyObject();
                    item.index = ko.observable(index);
                    item.value = value;
                    mapValue(this, item);
                    mappedItems.splice(index, 0, item);

                    for (var j = index + 1, len = mappedItems.length; j < len; j++) {
                        tmpItem = mappedItems[j];
                        tmpItem.index(tmpItem.index.peek() + 1);
                    }

                    this.valueAdded(value, index, item.mappedValue, item);
                }
                offset++;

            } else if (status === "deleted") {
                if (moved === undefined) {
                    item = mappedItems.splice(index + offset, 1)[0];
                    if (item.computed) {
                        item.computed.dispose();
                    }

                    for (var j = index + offset + 1, len = mappedItems.length; j < len; j++) {
                        tmpItem = mappedItems[j];
                        tmpItem.index(tmpItem.index.peek() - 1);
                    }

                    this.valueDeleted(value, index + offset, item.mappedValue, item);
                }
                offset--;
            }
        }
    };

    function updateIndex(items, prop, start, end, offset) {
        while (start <= end) {
            items[start++][prop] += offset;
        }
    }

    function addedIndex(array, prop, index) {
        updateIndex(array, prop, index + 1, array.length - 1, 1);
    }

    function deletedIndex(array, prop, index) {
        updateIndex(array, prop, index, array.length - 1, -1);
    }

    function movedIndex(array, prop, to, from) {
        if (to > from) {
            updateIndex(array, prop, from, to - 1, -1);
        } else {
            updateIndex(array, prop, to + 1, from, 1);
        }
    }

    function emptyObject() {
        return Object.create ? Object.create(null) : {};
    }

    function noop() {}

    function exactlyEqual(a, b) { return a === b }

    function mapValue(state, item) {
        var callback = state.callback;

        if (callback === undefined) {
            item.mappedValue = item.value;
            return;
        }

        var owner = state, method = "callback";

        if (typeof callback !== "function") {
            owner = item.value;
            method = callback;
            callback = owner[method];

            if (typeof callback !== "function") {
                item.mappedValue = callback;
                return;

            } else if (ko.isObservable(callback)) {
                watchItem(state, item, callback);
                return;
            }
        }

        var computedValue = ko.computed(function () {
            return owner[method](item.value, item.index);
        });

        if (computedValue.isActive()) {
            computedValue.equalityComparer = exactlyEqual;
            watchItem(state, item, computedValue);
            return computedValue;
        } else {
            item.mappedValue = computedValue.peek();
        }
    }

    function watchItem(self, item, observable) {
        item.mappedValue = observable.peek();

        observable.subscribe(function (newValue) {
            var oldValue = item.mappedValue;
            item.mappedValue = newValue;
            self.valueMutated(item.value, newValue, oldValue, item);
        });
    }

    function makeTransform(proto) {
        function TransformState(original, callback, options) {
            this.original = original;
            this.mappedItems = [];
            this.callback = callback;

            var transform = this.transform = this.init(options);
            if (ko.isObservable(transform) && transform.cacheDiffForKnownOperation) {
                // Too difficult to support
                transform.valueWillMutate = noop;
                this.transformedArray = transform.peek();
            }
        }

        TransformState.prototype.applyChanges = applyChanges;
        ko.utils.extend(TransformState.prototype, proto);
        transformClasses[proto.name] = TransformState;

        ko.observableArray.fn[proto.name] = function (callback, options) {
            var state = new TransformState(this, callback, options),
                originalArray = this.peek(),
                initialChanges = [];

            this.subscribe(function (changes) {
                state.applyChanges(changes);
            }, null, "arrayChange");

            for (var i = 0, len = originalArray.length; i < len; i++) {
                initialChanges.push({ status: "added", value: originalArray[i], index: i });
            }

            state.applyChanges(initialChanges);
            return state.transform;
        };
    };

    makeTransform({
        name: "sortBy",
        init: function () {
            this.keyCounts = emptyObject();
            this.sortedItems = [];
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, sortKey, item) {
            var mappedIndex = this.sortedIndexOf(sortKey, value, item),
                sortedItems = this.sortedItems,
                keyCounts = this.keyCounts;

            item.mappedIndex = mappedIndex;
            sortedItems.splice(mappedIndex, 0, item);
            addedIndex(sortedItems, "mappedIndex", mappedIndex);
            keyCounts[sortKey] = (keyCounts[sortKey] || 0) + 1;
            this.transform.splice(mappedIndex, 0, value);
        },
        valueDeleted: function (value, index, sortKey, item) {
            var mappedIndex = item.mappedIndex,
                sortedItems = this.sortedItems;

            sortedItems.splice(mappedIndex, 1);
            deletedIndex(sortedItems, "mappedIndex", mappedIndex);
            this.keyCounts[sortKey]--;
            this.transform.splice(mappedIndex, 1);
        },
        valueMoved: function (value, to, from, sortKey, item) {
            var oldIndex = item.mappedIndex,
                newIndex = this.sortedIndexOf(sortKey, value, item);

            if (oldIndex !== newIndex) {
                this.moveValue(value, sortKey, oldIndex, newIndex, item);
            }
        },
        valueMutated: function (value, newKey, oldKey, item) {
            // Revert to the old key temporarily, since it's already sorted,
            // otherwise the binary search won't work
            item.mappedValue = oldKey;

            var oldIndex = item.mappedIndex,
                newIndex = this.sortedIndexOf(newKey, value, item);

            item.mappedValue = newKey;

            if (oldIndex !== newIndex) {
                this.moveValue(value, newKey, oldIndex, newIndex, item, true);

                var keyCounts = this.keyCounts;
                keyCounts[oldKey]--;
                keyCounts[newKey] = (keyCounts[newKey] || 0) + 1;
            }
        },
        moveValue: function (value, sortKey, oldIndex, newIndex, item, isMutation) {
            var sortedItems = this.sortedItems,
                transformedArray = this.transformedArray;

            sortedItems.splice(oldIndex, 1);
            transformedArray.splice(oldIndex, 1);

            // If we're here because of a move in the original array, rather
            // than a mutated value, then the mappedItems array has already
            // been reordered, thus newIndex is correctly adjusted.
            if (isMutation && oldIndex < newIndex) {
                newIndex--;
            }

            item.mappedIndex = newIndex;
            sortedItems.splice(newIndex, 0, item);

            movedIndex(sortedItems, "mappedIndex", newIndex, oldIndex);
            transformedArray.splice(newIndex, 0, value);

            this.transform.notifySubscribers(transformedArray);
        },
        sortedIndexOf: function (key, value, item) {
            var sortedItems = this.sortedItems,
                length = sortedItems.length;

            if (!length) {
                return 0;
            }

            var start = 0, end = length - 1, index;

            while (start <= end) {
                index = (start + end) >> 1;

                if (sortedItems[index].mappedValue < key) {
                    start = index + 1;
                } else if ((end = index) === start) {
                    break;
                }
            }

            // Keep things stably sorted. Only incurs a cost if there are
            // multiple of this key.
            var count = this.keyCounts[key], offset = 0;

            if (count) {
                var mappedItems = this.mappedItems, mappedItem;

                for (var i = 0; i < length; i++) {
                    mappedItem = mappedItems[i];

                    if (mappedItem === item) {
                        break;
                    }
                    if (mappedItem.mappedValue === key) {
                        offset++;
                    }
                    if (offset === count) {
                        break;
                    }
                }
            }

            return start + offset;
        }
    });

    function updateFilterMapping() {
        var mappedItems = this.mappedItems,
            mappedIndexProp = this.mappedIndexProp,
            transformedArray = this.transformedArray,
            currentItem,
            currentIndex = 0;

        for (var i = 0, len = mappedItems.length; i < len; i++) {
            currentItem = mappedItems[i];

            if (this.getVisibility(currentItem.mappedValue)) {
                currentItem[mappedIndexProp] = currentIndex;
                transformedArray[currentIndex++] = currentItem.value;
            }
        }
        transformedArray.length = currentIndex;
        this.transform.notifySubscribers(transformedArray);
    }

    makeTransform({
        name: "filter",
        mappedIndexProp: "mappedIndex",
        init: function () {
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, visible) {
            if (visible) {
                this.updateMapping();
            }
        },
        valueDeleted: function (value, index, visible, item) {
            if (visible) {
                this.makeInvisible(value, index, item[this.mappedIndexProp]);
            }
        },
        valueMoved: function (value, to, from, visible) {
            if (visible) {
                this.updateMapping();
            }
        },
        valueMutated: function (value, shouldBeVisible, currentlyVisible, item) {
            if (shouldBeVisible && !currentlyVisible) {
                this.updateMapping();

            } else if (!shouldBeVisible && currentlyVisible) {
                this.makeInvisible(value, item.index.peek(), item[this.mappedIndexProp]);
            }
        },
        makeInvisible: function (value, index, mappedIndex) {
            this.transform.splice(mappedIndex, 1);
            deletedIndex(this.mappedItems, this.mappedIndexProp, index);
        },
        updateMapping: updateFilterMapping,
        getVisibility: Boolean
    });

    function getGroupVisibility(groupKey) {
        return String(groupKey) === this.groupKey;
    }

    makeTransform({
        name: "groupBy",
        init: function () {
            this.groups = emptyObject();
            return ko.observableArray([]);
        },
        applyChanges: function (changes) {
            var groups = this.groups;

            applyChanges.call(this, changes);

            for (var key in groups) {
                if (!groups[key].transformedArray.length) {
                    this.deleteGroup(key);
                }
            }
        },
        valueAdded: function (value, index, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            if (!groups[groupKey]) {
                var group = new transformClasses.filter(this.original);
                groups[groupKey] = group;

                group.groupKey = groupKey;
                group.mappedItems = this.mappedItems;
                group.mappedIndexProp = "mappedIndex." + groupKey;
                group.getVisibility = getGroupVisibility;

                var object = emptyObject();
                object.key = groupKey;
                object.values = group.transform;

                this.transform.push(object);
            }

            for (var key in groups) {
                groups[key].valueAdded(value, index, key === groupKey, item);
            }
        },
        valueDeleted: function (value, index, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            for (var key in groups) {
                groups[key].valueDeleted(value, index, key === groupKey, item);
            }
        },
        valueMoved: function (value, to, from, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            for (var key in groups) {
                groups[key].valueMoved(value, to, from, key === groupKey, item);
            }
        },
        valueMutated: function (value, newGroupKey, oldGroupKey, item) {
            var groups = this.groups,
                oldGroup = groups[oldGroupKey];

            oldGroup.makeInvisible(value, item.index.peek(), item[oldGroup.mappedIndexProp]);
            groups[newGroupKey].updateMapping();

            if (!oldGroup.transformedArray.length) {
                this.deleteGroup(String(oldGroupKey));
            }
        },
        deleteGroup: function (groupKey) {
            var transformedArray = this.transformedArray;

            delete this.groups[groupKey];

            for (var i = 0, len = transformedArray.length; i < len; i++) {
                if (transformedArray[i].key === groupKey) {
                    return this.transform.splice(i, 1);
                }
            }
        }
    });

    makeTransform({
        name: "map",
        init: function () {
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, mappedValue) {
            this.transform.splice(index, 0, mappedValue);
        },
        valueDeleted: function (value, index) {
            this.transform.splice(index, 1);
        },
        valueMoved: function (value, to, from, mappedValue) {
            var transformedArray = this.transformedArray;
            transformedArray.splice(from, 1);
            transformedArray.splice(to, 0, mappedValue);
            this.transform.notifySubscribers(transformedArray);
        },
        valueMutated: function (value, newMappedValue, oldMappedValue, item) {
            var transformedArray = this.transformedArray, index = item.index.peek();
            transformedArray.splice(index, 1);
            transformedArray.splice(index, 0, newMappedValue);
            this.transform.notifySubscribers(transformedArray);
        }
    });

    var allOrAny = {
        init: function () {
            this.truthinessCount = 0;
            return ko.observable(this.getTruthiness());
        },
        valueAdded: function (value, index, truthiness) {
            this.valueMutated(null, truthiness, false);
        },
        valueDeleted: function (value, index, truthiness) {
            this.valueMutated(null, false, truthiness);
        },
        valueMoved: noop,
        valueMutated: function (value, newTruthiness, oldTruthiness) {
            if (newTruthiness && !oldTruthiness) {
                this.truthinessCount++;
            } else if (oldTruthiness && !newTruthiness) {
                this.truthinessCount--;
            }
            this.transform(this.getTruthiness());
        }
    };

    makeTransform(ko.utils.extend({
        name: "any",
        getTruthiness: function () {
            return this.truthinessCount > 0;
        }
    }, allOrAny));

    makeTransform(ko.utils.extend({
        name: "all",
        getTruthiness: function () {
            return this.truthinessCount === this.mappedItems.length;
        }
    }, allOrAny));

    ko.observableArray.fn.some = ko.observableArray.fn.any;
    ko.observableArray.fn.every = ko.observableArray.fn.all;

    ko.arrayTransforms = {
        makeTransform: makeTransform
    };
});
<commit_msg>Inline all the updateIndex calls<commit_after>// knockout-arrayTransforms 0.3.0 (https://github.com/mwiencek/knockout-arrayTransforms)
// Released under the MIT (X11) License; see the LICENSE file in the official code repository.

(function (factory) {
    if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
        factory(module.exports = require("knockout"));
    } else if (typeof define === "function" && define.amd) {
        define(["knockout"], factory);
    } else {
        factory(window.ko);
    }
})(function (ko) {

    var transformClasses = emptyObject();

    function applyChanges(changes) {
        var mappedItems = this.mappedItems,
            moves = emptyObject(),
            offset = 0;

        for (var i = 0, change; change = changes[i]; i++) {
            var status = change.status;

            if (status === "retained") {
                continue;
            }

            var index = change.index,
                moved = change.moved,
                value = change.value,
                item = change.mappedItem,
                tmpItem;

            if (moved !== undefined) {
                // For added statuses, index is a position in the new
                // array and moved is a position in the old array. For
                // deleted statuses, it's the opposite.
                if (status === "added") {
                    var to = index, from = moved + offset;

                } else if (status === "deleted") {
                    var to = moved, from = index + offset;
                }

                if (moves[to] === undefined) {
                    moves[to] = true;
                    item = mappedItems[from];
                    mappedItems.splice(from, 1)
                    mappedItems.splice(to, 0, item);

                    if (to > from) {
                        for (var j = from; j < to; j++) {
                            tmpItem = mappedItems[j];
                            tmpItem.index(tmpItem.index.peek() - 1);
                        }
                    } else {
                        for (var j = to + 1; j <= from; j++) {
                            tmpItem = mappedItems[j];
                            tmpItem.index(tmpItem.index.peek() + 1);
                        }
                    }

                    this.valueMoved(value, to, from, item.mappedValue, item);
                }
            }

            if (status === "added") {
                if (moved === undefined) {
                    item = emptyObject();
                    item.index = ko.observable(index);
                    item.value = value;
                    mapValue(this, item);
                    mappedItems.splice(index, 0, item);

                    for (var j = index + 1, len = mappedItems.length; j < len; j++) {
                        tmpItem = mappedItems[j];
                        tmpItem.index(tmpItem.index.peek() + 1);
                    }

                    this.valueAdded(value, index, item.mappedValue, item);
                }
                offset++;

            } else if (status === "deleted") {
                if (moved === undefined) {
                    item = mappedItems.splice(index + offset, 1)[0];
                    if (item.computed) {
                        item.computed.dispose();
                    }

                    for (var j = index + offset + 1, len = mappedItems.length; j < len; j++) {
                        tmpItem = mappedItems[j];
                        tmpItem.index(tmpItem.index.peek() - 1);
                    }

                    this.valueDeleted(value, index + offset, item.mappedValue, item);
                }
                offset--;
            }
        }
    };

    function emptyObject() {
        return Object.create ? Object.create(null) : {};
    }

    function noop() {}

    function exactlyEqual(a, b) { return a === b }

    function mapValue(state, item) {
        var callback = state.callback;

        if (callback === undefined) {
            item.mappedValue = item.value;
            return;
        }

        var owner = state, method = "callback";

        if (typeof callback !== "function") {
            owner = item.value;
            method = callback;
            callback = owner[method];

            if (typeof callback !== "function") {
                item.mappedValue = callback;
                return;

            } else if (ko.isObservable(callback)) {
                watchItem(state, item, callback);
                return;
            }
        }

        var computedValue = ko.computed(function () {
            return owner[method](item.value, item.index);
        });

        if (computedValue.isActive()) {
            computedValue.equalityComparer = exactlyEqual;
            watchItem(state, item, computedValue);
            return computedValue;
        } else {
            item.mappedValue = computedValue.peek();
        }
    }

    function watchItem(self, item, observable) {
        item.mappedValue = observable.peek();

        observable.subscribe(function (newValue) {
            var oldValue = item.mappedValue;
            item.mappedValue = newValue;
            self.valueMutated(item.value, newValue, oldValue, item);
        });
    }

    function makeTransform(proto) {
        function TransformState(original, callback, options) {
            this.original = original;
            this.mappedItems = [];
            this.callback = callback;

            var transform = this.transform = this.init(options);
            if (ko.isObservable(transform) && transform.cacheDiffForKnownOperation) {
                // Too difficult to support
                transform.valueWillMutate = noop;
                this.transformedArray = transform.peek();
            }
        }

        TransformState.prototype.applyChanges = applyChanges;
        ko.utils.extend(TransformState.prototype, proto);
        transformClasses[proto.name] = TransformState;

        ko.observableArray.fn[proto.name] = function (callback, options) {
            var state = new TransformState(this, callback, options),
                originalArray = this.peek(),
                initialChanges = [];

            this.subscribe(function (changes) {
                state.applyChanges(changes);
            }, null, "arrayChange");

            for (var i = 0, len = originalArray.length; i < len; i++) {
                initialChanges.push({ status: "added", value: originalArray[i], index: i });
            }

            state.applyChanges(initialChanges);
            return state.transform;
        };
    };

    makeTransform({
        name: "sortBy",
        init: function () {
            this.keyCounts = emptyObject();
            this.sortedItems = [];
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, sortKey, item) {
            var mappedIndex = this.sortedIndexOf(sortKey, value, item),
                sortedItems = this.sortedItems,
                keyCounts = this.keyCounts;

            item.mappedIndex = mappedIndex;
            sortedItems.splice(mappedIndex, 0, item);
            keyCounts[sortKey] = (keyCounts[sortKey] || 0) + 1;

            for (var i = mappedIndex + 1, len = sortedItems.length; i < len; i++) {
                sortedItems[i].mappedIndex++;
            }

            this.transform.splice(mappedIndex, 0, value);
        },
        valueDeleted: function (value, index, sortKey, item) {
            var mappedIndex = item.mappedIndex,
                sortedItems = this.sortedItems;

            sortedItems.splice(mappedIndex, 1);
            this.keyCounts[sortKey]--;

            for (var i = mappedIndex, len = sortedItems.length; i < len; i++) {
                sortedItems[i].mappedIndex--;
            }

            this.transform.splice(mappedIndex, 1);
        },
        valueMoved: function (value, to, from, sortKey, item) {
            var oldIndex = item.mappedIndex,
                newIndex = this.sortedIndexOf(sortKey, value, item);

            if (oldIndex !== newIndex) {
                this.moveValue(value, sortKey, oldIndex, newIndex, item);
            }
        },
        valueMutated: function (value, newKey, oldKey, item) {
            // Revert to the old key temporarily, since it's already sorted,
            // otherwise the binary search won't work
            item.mappedValue = oldKey;

            var oldIndex = item.mappedIndex,
                newIndex = this.sortedIndexOf(newKey, value, item);

            item.mappedValue = newKey;

            if (oldIndex !== newIndex) {
                this.moveValue(value, newKey, oldIndex, newIndex, item, true);

                var keyCounts = this.keyCounts;
                keyCounts[oldKey]--;
                keyCounts[newKey] = (keyCounts[newKey] || 0) + 1;
            }
        },
        moveValue: function (value, sortKey, oldIndex, newIndex, item, isMutation) {
            var sortedItems = this.sortedItems,
                transformedArray = this.transformedArray;

            sortedItems.splice(oldIndex, 1);
            transformedArray.splice(oldIndex, 1);

            // If we're here because of a move in the original array, rather
            // than a mutated value, then the mappedItems array has already
            // been reordered, thus newIndex is correctly adjusted.
            if (isMutation && oldIndex < newIndex) {
                newIndex--;
            }

            item.mappedIndex = newIndex;
            sortedItems.splice(newIndex, 0, item);

            if (newIndex > oldIndex) {
                for (var i = oldIndex; i < newIndex; i++) {
                    sortedItems[i].mappedIndex--;
                }
            } else {
                for (var i = newIndex + 1; i <= oldIndex; i++) {
                    sortedItems[i].mappedIndex++;
                }
            }

            transformedArray.splice(newIndex, 0, value);
            this.transform.notifySubscribers(transformedArray);
        },
        sortedIndexOf: function (key, value, item) {
            var sortedItems = this.sortedItems,
                length = sortedItems.length;

            if (!length) {
                return 0;
            }

            var start = 0, end = length - 1, index;

            while (start <= end) {
                index = (start + end) >> 1;

                if (sortedItems[index].mappedValue < key) {
                    start = index + 1;
                } else if ((end = index) === start) {
                    break;
                }
            }

            // Keep things stably sorted. Only incurs a cost if there are
            // multiple of this key.
            var count = this.keyCounts[key], offset = 0;

            if (count) {
                var mappedItems = this.mappedItems, mappedItem;

                for (var i = 0; i < length; i++) {
                    mappedItem = mappedItems[i];

                    if (mappedItem === item) {
                        break;
                    }
                    if (mappedItem.mappedValue === key) {
                        offset++;
                    }
                    if (offset === count) {
                        break;
                    }
                }
            }

            return start + offset;
        }
    });

    function updateFilterMapping() {
        var mappedItems = this.mappedItems,
            mappedIndexProp = this.mappedIndexProp,
            transformedArray = this.transformedArray,
            currentItem,
            currentIndex = 0;

        for (var i = 0, len = mappedItems.length; i < len; i++) {
            currentItem = mappedItems[i];

            if (this.getVisibility(currentItem.mappedValue)) {
                currentItem[mappedIndexProp] = currentIndex;
                transformedArray[currentIndex++] = currentItem.value;
            }
        }
        transformedArray.length = currentIndex;
        this.transform.notifySubscribers(transformedArray);
    }

    makeTransform({
        name: "filter",
        mappedIndexProp: "mappedIndex",
        init: function () {
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, visible) {
            if (visible) {
                this.updateMapping();
            }
        },
        valueDeleted: function (value, index, visible, item) {
            if (visible) {
                this.makeInvisible(value, index, item[this.mappedIndexProp]);
            }
        },
        valueMoved: function (value, to, from, visible) {
            if (visible) {
                this.updateMapping();
            }
        },
        valueMutated: function (value, shouldBeVisible, currentlyVisible, item) {
            if (shouldBeVisible && !currentlyVisible) {
                this.updateMapping();

            } else if (!shouldBeVisible && currentlyVisible) {
                this.makeInvisible(value, item.index.peek(), item[this.mappedIndexProp]);
            }
        },
        makeInvisible: function (value, index, mappedIndex) {
            var mappedItems = this.mappedItems,
                mappedIndexProp = this.mappedIndexProp;

            for (var i = index, len = mappedItems.length; i < len; i++) {
                mappedItems[i][mappedIndexProp]--;
            }

            this.transform.splice(mappedIndex, 1);
        },
        updateMapping: updateFilterMapping,
        getVisibility: Boolean
    });

    function getGroupVisibility(groupKey) {
        return String(groupKey) === this.groupKey;
    }

    makeTransform({
        name: "groupBy",
        init: function () {
            this.groups = emptyObject();
            return ko.observableArray([]);
        },
        applyChanges: function (changes) {
            var groups = this.groups;

            applyChanges.call(this, changes);

            for (var key in groups) {
                if (!groups[key].transformedArray.length) {
                    this.deleteGroup(key);
                }
            }
        },
        valueAdded: function (value, index, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            if (!groups[groupKey]) {
                var group = new transformClasses.filter(this.original);
                groups[groupKey] = group;

                group.groupKey = groupKey;
                group.mappedItems = this.mappedItems;
                group.mappedIndexProp = "mappedIndex." + groupKey;
                group.getVisibility = getGroupVisibility;

                var object = emptyObject();
                object.key = groupKey;
                object.values = group.transform;

                this.transform.push(object);
            }

            for (var key in groups) {
                groups[key].valueAdded(value, index, key === groupKey, item);
            }
        },
        valueDeleted: function (value, index, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            for (var key in groups) {
                groups[key].valueDeleted(value, index, key === groupKey, item);
            }
        },
        valueMoved: function (value, to, from, groupKey, item) {
            groupKey = String(groupKey);

            var groups = this.groups;

            for (var key in groups) {
                groups[key].valueMoved(value, to, from, key === groupKey, item);
            }
        },
        valueMutated: function (value, newGroupKey, oldGroupKey, item) {
            var groups = this.groups,
                oldGroup = groups[oldGroupKey];

            oldGroup.makeInvisible(value, item.index.peek(), item[oldGroup.mappedIndexProp]);
            groups[newGroupKey].updateMapping();

            if (!oldGroup.transformedArray.length) {
                this.deleteGroup(String(oldGroupKey));
            }
        },
        deleteGroup: function (groupKey) {
            var transformedArray = this.transformedArray;

            delete this.groups[groupKey];

            for (var i = 0, len = transformedArray.length; i < len; i++) {
                if (transformedArray[i].key === groupKey) {
                    return this.transform.splice(i, 1);
                }
            }
        }
    });

    makeTransform({
        name: "map",
        init: function () {
            return ko.observableArray([]);
        },
        valueAdded: function (value, index, mappedValue) {
            this.transform.splice(index, 0, mappedValue);
        },
        valueDeleted: function (value, index) {
            this.transform.splice(index, 1);
        },
        valueMoved: function (value, to, from, mappedValue) {
            var transformedArray = this.transformedArray;
            transformedArray.splice(from, 1);
            transformedArray.splice(to, 0, mappedValue);
            this.transform.notifySubscribers(transformedArray);
        },
        valueMutated: function (value, newMappedValue, oldMappedValue, item) {
            var transformedArray = this.transformedArray, index = item.index.peek();
            transformedArray.splice(index, 1);
            transformedArray.splice(index, 0, newMappedValue);
            this.transform.notifySubscribers(transformedArray);
        }
    });

    var allOrAny = {
        init: function () {
            this.truthinessCount = 0;
            return ko.observable(this.getTruthiness());
        },
        valueAdded: function (value, index, truthiness) {
            this.valueMutated(null, truthiness, false);
        },
        valueDeleted: function (value, index, truthiness) {
            this.valueMutated(null, false, truthiness);
        },
        valueMoved: noop,
        valueMutated: function (value, newTruthiness, oldTruthiness) {
            if (newTruthiness && !oldTruthiness) {
                this.truthinessCount++;
            } else if (oldTruthiness && !newTruthiness) {
                this.truthinessCount--;
            }
            this.transform(this.getTruthiness());
        }
    };

    makeTransform(ko.utils.extend({
        name: "any",
        getTruthiness: function () {
            return this.truthinessCount > 0;
        }
    }, allOrAny));

    makeTransform(ko.utils.extend({
        name: "all",
        getTruthiness: function () {
            return this.truthinessCount === this.mappedItems.length;
        }
    }, allOrAny));

    ko.observableArray.fn.some = ko.observableArray.fn.any;
    ko.observableArray.fn.every = ko.observableArray.fn.all;

    ko.arrayTransforms = {
        makeTransform: makeTransform
    };
});
<|endoftext|>


<commit_before>import { Mongo } from 'meteor/mongo';

export const Patients = new Mongo.Collection('patient_demographic');

if (Meteor.isServer) {
  Meteor.publish('patients_demo', function patientsPublication() {
    return Patients.find();
  });
}<commit_msg>added deny rules to explicitly block any writes to the database<commit_after>import { Mongo } from 'meteor/mongo';

// patient_demographic is a collections with basic patient info
export const Patients = new Mongo.Collection('patient_demographic');

// Explicitly deny any writes in the patient_demographic collection.
// This application is a "read only" app to display info, not to modify data
Patients.deny({
	insert : function(userid, doc){
		return true;
	}

	,update : function(userId, doc, fields, modifier){
		return true;
	}

	,remove : function(userId, doc){
		return true;
	}
})

if (Meteor.isServer) {

// Publication
  Meteor.publish('patients_demo', function patientsPublication() {
    return Patients.find();
  });
}<|endoftext|>


<commit_before>'use strict';

var defaultEnvConfig = require('./default');

module.exports = {
  db: {
    uri: process.env.MONGOLAB_URI,
    options: {
      user: '',
      pass: ''
    },

    // Enable mongoose debug mode
    debug: process.env.MONGODB_DEBUG || false
  },
  log: {
    // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
    format: 'dev',
    // Stream defaults to process.stdout
    // Uncomment to enable logging to a log on the file system
    options: {
      //stream: 'access.log'
    }
  },
  app: {
    title: defaultEnvConfig.app.title //+ ' - Development Environment'
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/facebook/callback' //callbackURL: '/api/auth/facebook/callback'
  },
  twitter: {
    clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
    clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
    callbackURL: '/api/auth/twitter/callback'
  },
  google: {
    clientID: process.env.GOOGLE_ID || 'APP_ID',
    clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/google/callback'
  },
  linkedin: {
    clientID: process.env.LINKEDIN_ID || 'APP_ID',
    clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/linkedin/callback'
  },
  github: {
    clientID: process.env.GITHUB_ID || 'APP_ID',
    clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/github/callback'
  },
  paypal: {
    clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
    clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
    callbackURL: '/api/auth/paypal/callback',
    sandbox: true
  },
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  },
  livereload: true,
  seedDB: process.env.MONGO_SEED || false
};
<commit_msg>Let's see if I can't get it working after a full night's sleep<commit_after>'use strict';

var defaultEnvConfig = require('./default');

module.exports = {
  db: {
    uri: process.env.MONGOLAB_URI,
    options: {
      user: 'team7c',
      pass: '"[2-a)_61D*L 8O'
    },

    // Enable mongoose debug mode
    debug: process.env.MONGODB_DEBUG || false
  },
  log: {
    // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
    format: 'dev',
    // Stream defaults to process.stdout
    // Uncomment to enable logging to a log on the file system
    options: {
      //stream: 'access.log'
    }
  },
  app: {
    title: defaultEnvConfig.app.title //+ ' - Development Environment'
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/facebook/callback' //callbackURL: '/api/auth/facebook/callback'
  },
  twitter: {
    clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
    clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
    callbackURL: '/api/auth/twitter/callback'
  },
  google: {
    clientID: process.env.GOOGLE_ID || 'APP_ID',
    clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/google/callback'
  },
  linkedin: {
    clientID: process.env.LINKEDIN_ID || 'APP_ID',
    clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/linkedin/callback'
  },
  github: {
    clientID: process.env.GITHUB_ID || 'APP_ID',
    clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/github/callback'
  },
  paypal: {
    clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
    clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
    callbackURL: '/api/auth/paypal/callback',
    sandbox: true
  },
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  },
  livereload: true,
  seedDB: process.env.MONGO_SEED || false
};
<|endoftext|>


<commit_before>(function ($) {
    /*리스트 불러오기 + 초기화*/
    var project_list_load = function () {
        var str = "";
        $.ajax({
            url: "/project",
            method: "get",
            success: function (data) {
                var str = '';
                $.each(data, function (index, val) {
                    str += '
'+
             	   		   '

'+
             	   		   '
'+ val.title +'
'+
             	   		   '
'+ val.sdate +' ~ '+ val.edate +'
'+
                    	   '

';
                });
                $(".isotope-container").html(str);
            }, fail: function () {
                alert("실패")
            }

        })
    };

    /*초기 세팅*/
    project_list_load();

    /* 프로젝트 등록 */
    $(".write-btn").click(function() {
    	var check = true;
        var category = $('#w_category').attr("value");
        var sdate = $('#sdatepicker').val();
        var edate = $('#edatepicker').val();
        var title = $('#w_title').val();
        var content = CKEDITOR.instances.write_content.setData('');
        var img = imageParse(content);
        var url = $('#w_url').val();
        if (sdate == null || sdate == '' || edate == null || edate == '') {
        	$('#dateInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
        	check = false;
        }
        if (title == null || title == '') {
            $('#titleInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
            check = false;
        }
        if ( content ==null || content == "" || content.length < 1) {
            $('#contentInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
            check = false;
        }
        var object = {};
        object.category = category;
        object.sdate = sdate;
        object.edate = edate;
        object.title = title;
        object.content = content;
        object.img = img;
        object.url = url;

        if (check == true) {
            $.ajax({
            	url: "/project",
                method: "post",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(object),
                success: function (data) {
                    if (data.result == "SUCS") {
                    	$('#sdatepicker').val('');
                    	$('#edatepicker').val('');
                    	$('#w_title').val('');
                    	CKEDITOR.instances.write_content.getData();
                    	$(".write-btn").click();
                    } else {
                        alert("실패")

                    }
                }, fail: function () {
                    alert("실패")

                }
            })
        } else {
            show_message("빈칸이 있어요 전부 입력해주세요");
        }
    });

    /*메인에 뜰 이미지 파싱*/
    imageParse = function(content) {
    	var contentArray = [];
    	if(content!=null && content!="") {
    	    if(content.indexOf("<img")) {
                contentArray = content.split('alt="" src="');
                if (contentArray[1] != null && contentArray[1] != "") {
                    var src = contentArray[1].split('"');
                    return src[0];
                } else {

                }
            }
        }
        return "";
    };

    $('.clear-completed').click(function () {
        if ($('.filters li a.selected').attr('href').split('/')[1] == 'active') {
            /*만약 선택되있던 filter 가 active라면, 디폴트로 돌린다*/
            $('.filters li a[href="#/"]').click();
        }
        /*위의 이벤트가 일어나기 전까지 딜레이*/
        setTimeout("$('li.completed').find('.destroy').click()", 500);

    });

    $(document).ready(function(e) {
        $('.with-hover-text, .regular-link').click(function(e){
            e.stopPropagation();
        });

        /***************
         * = Hover text *
         * Hover text for the last slide
         ***************/
        $('.with-hover-text').hover(
            function(e) {
                $(this).css('overflow', 'visible');
                $(this).find('.hover-text')
                    .show()
                    .css('opacity', 0)
                    .delay(200)
                    .animate(
                        {
                            paddingTop: '25px',
                            opacity: 1
                        },
                        'fast',
                        'linear'
                    );
            },
            function(e) {
                var obj = $(this);
                $(this).find('.hover-text')
                    .animate(
                        {
                            paddingTop: '0',
                            opacity: 0
                        },
                        'fast',
                        'linear',
                        function() {
                            $(this).hide();
                            $( obj ).css('overflow', 'hidden');
                        }
                    );
            }
        );

        var img_loaded = 0;
        var j_images = [];

        /*************************
         * = Controls active menu *
         * Hover text for the last slide
         *************************/
        $(function() {
            var pause = 10;
            $(document).scroll(function(e) {
                delay(function() {

                        var tops = [];

                        $('.story').each(function(index, element) {
                            tops.push( $(element).offset().top - 200 );
                        });

                        var scroll_top = $(this).scrollTop();

                        var lis = $('.nav > li');

                        for ( var i=tops.length-1; i>=0; i-- ) {
                            if ( scroll_top >= tops[i] ) {
                                menu_focus( lis[i], i+1 );
                                break;
                            }
                        }
                    },
                    pause);
            });
            $(document).scroll();
        });
    });

    var delay = (function(){
        var timer = 0;
        return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    })();

    menu_focus = function( element, i ) {
        if ( $(element).hasClass('active') ) {
            if ( i == 4 ) {
                if ( $('.navbar').hasClass('inv') == false )
                    return;
            } else {
                return;
            }
        }

        $('.menu-nav li').removeClass('active');
        $(element).addClass('active');

        var icon = $(element).find('.icon');

        var left_pos = icon.offset().left - $('.menu-nav').offset().left;
        var el_width = icon.width() + $(element).find('.text').width() + 10;

        $('.active-menu').stop(false, false).animate(
            {
                left: left_pos,
                width: el_width
            },
            1500,
            'easeInOutQuart'
        );
    };

    /*************
     * = Parallax *
     *************/
    jQuery(document).ready(function ($) {
        //Cache some variables
        var links = $('.nav').find('li');
        slide = $('.slide');
        button = $('.button');
        mywindow = $(window);
        htmlbody = $('html,body');

        //Create a function that will be passed a slide number and then will scroll to that slide using jquerys animate. The Jquery
        //easing plugin is also used, so we passed in the easing method of 'easeInOutQuint' which is available throught the plugin.
        function goToByScroll(dataslide) {
            var offset_top = ( dataslide == 1 ) ? '0px' : $('.slide[data-slide="' + dataslide + '"]').offset().top;

            htmlbody.stop(false, false).animate({
                scrollTop: offset_top
            }, 1500, 'easeInOutQuart');
        }

        //When the user clicks on the navigation links, get the data-slide attribute value of the link and pass that variable to the goToByScroll function
        links.click(function (e) {
            e.preventDefault();
            dataslide = $(this).attr('data-slide');
            goToByScroll(dataslide);
            $(".nav-collapse").collapse('hide');
        });

        //When the user clicks on the navigation links, get the data-slide attribute value of the link and pass that variable to the goToByScroll function
        $('.navigation-slide').click(function (e) {
            e.preventDefault();
            dataslide = $(this).attr('data-slide');
            goToByScroll(dataslide);
            $(".nav-collapse").collapse('hide');
        });
    });

    /***************
     * = Menu hover *
     ***************/
    jQuery(document).ready(function ($) {
        //Cache some variables
        var menu_item = $('.nav').find('li');

        menu_item.hover(
            function(e) {
                var icon = $(this).find('.icon');

                var left_pos = icon.offset().left - $('.nav').offset().left;
                var el_width = icon.width() + $(this).find('.text').width() + 10;

                var hover_bar = $('

')
                    .css('left', left_pos)
                    .css('width', el_width)
                    .attr('id', 'special-active-menu-' + $(this).data('slide') );

                $('.active-menu').after( hover_bar );
            },
            function(e) {
                $('.special-active-menu').remove();
            }
        );
    });

})
(jQuery);
<commit_msg>datepicker<commit_after>(function ($) {
    /*리스트 불러오기 + 초기화*/
    var project_list_load = function () {
        var str = "";
        $.ajax({
            url: "/project",
            method: "get",
            success: function (data) {
                var str = '';
                $.each(data, function (index, val) {
                    str += '
'+
             	   		   '

'+
             	   		   '
'+ val.title +'
'+
             	   		   '
'+ val.sdate +' ~ '+ val.edate +'
'+
                    	   '

';
                });
                $(".isotope-container").html(str);
            }, fail: function () {
                alert("실패")
            }

        })
    };

    /*초기 세팅*/
    project_list_load();

    /* 프로젝트 등록 */
    $(".write-btn").click(function() {
    	var check = true;
        var category = $('#w_category').attr("value");
        var sdate = $('#sdatepicker').val();
        var edate = $('#edatepicker').val();
        var title = $('#w_title').val();
        var content = CKEDITOR.instances.write_content.setData('');
        var img = imageParse(content);
        var url = $('#w_url').val();
        if (sdate == null || sdate == '' || edate == null || edate == '') {
        	$('#dateInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
        	check = false;
        }
        if (title == null || title == '') {
            $('#titleInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
            check = false;
        }
        if ( content ==null || content == "" || content.length < 1) {
            $('#contentInput').css({'background-color': '##f2dede', 'border-color': '#ebccd1'});
            check = false;
        }
        var object = {};
        object.category = category;
        object.sdate = sdate;
        object.edate = edate;
        object.title = title;
        object.content = content;
        object.img = img;
        object.url = url;

        if (check == true) {
            $.ajax({
            	url: "/project",
                method: "post",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(object),
                success: function (data) {
                    if (data.result == "SUCS") {
                    	$('#sdatepicker').val('');
                    	$('#edatepicker').val('');
                    	$('#w_title').val('');
                    	CKEDITOR.instances.write_content.getData();
                    	$(".write-btn").click();
                    } else {
                        alert("실패")

                    }
                }, fail: function () {
                    alert("실패")

                }
            })
        } else {
            show_message("빈칸이 있어요 전부 입력해주세요");
        }
    });

    /*메인에 뜰 이미지 파싱*/
    imageParse = function(content) {
    	var contentArray = [];
    	if(content!=null && content!="") {
    	    if(content.indexOf("<img")) {
                contentArray = content.split('alt="" src="');
                if (contentArray[1] != null && contentArray[1] != "") {
                    var src = contentArray[1].split('"');
                    return src[0];
                } else {

                }
            }
        }
        return "";
    };

    /*카테고리 선택부분*/
    $('.categorySel').change(function () {
        $('#w_category').attr('value', $('.categorySel option:selected').text());
    });

    var dates = $("#sdatepicker, #edatepicker ").datepicker({
        dateFormat: "yy-mm-dd",
        yearSuffix: '년',
        showOtherMonths: true,
        yearRange: "2017:2022",
        monthNames: ["1월", "2월", "3월", "4월", "5월", "6월",
            "7월", "8월", "9월", "10월", "11월", "12월"],
        onSelect: function (selectedDate) {
            var option = this.id == "sdatepicker" ? "minDate" : "maxDate",
                instance = $(this).data("datepicker"),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings);
            dates.not(this).datepicker("option", option, date);
        }
    });

    $('.clear-completed').click(function () {
        if ($('.filters li a.selected').attr('href').split('/')[1] == 'active') {
            /*만약 선택되있던 filter 가 active라면, 디폴트로 돌린다*/
            $('.filters li a[href="#/"]').click();
        }
        /*위의 이벤트가 일어나기 전까지 딜레이*/
        setTimeout("$('li.completed').find('.destroy').click()", 500);

    });

    $(document).ready(function(e) {
        $('.with-hover-text, .regular-link').click(function(e){
            e.stopPropagation();
        });

        /***************
         * = Hover text *
         * Hover text for the last slide
         ***************/
        $('.with-hover-text').hover(
            function(e) {
                $(this).css('overflow', 'visible');
                $(this).find('.hover-text')
                    .show()
                    .css('opacity', 0)
                    .delay(200)
                    .animate(
                        {
                            paddingTop: '25px',
                            opacity: 1
                        },
                        'fast',
                        'linear'
                    );
            },
            function(e) {
                var obj = $(this);
                $(this).find('.hover-text')
                    .animate(
                        {
                            paddingTop: '0',
                            opacity: 0
                        },
                        'fast',
                        'linear',
                        function() {
                            $(this).hide();
                            $( obj ).css('overflow', 'hidden');
                        }
                    );
            }
        );

        var img_loaded = 0;
        var j_images = [];

        /*************************
         * = Controls active menu *
         * Hover text for the last slide
         *************************/
        $(function() {
            var pause = 10;
            $(document).scroll(function(e) {
                delay(function() {

                        var tops = [];

                        $('.story').each(function(index, element) {
                            tops.push( $(element).offset().top - 200 );
                        });

                        var scroll_top = $(this).scrollTop();

                        var lis = $('.nav > li');

                        for ( var i=tops.length-1; i>=0; i-- ) {
                            if ( scroll_top >= tops[i] ) {
                                menu_focus( lis[i], i+1 );
                                break;
                            }
                        }
                    },
                    pause);
            });
            $(document).scroll();
        });
    });

    var delay = (function(){
        var timer = 0;
        return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    })();

    menu_focus = function( element, i ) {
        if ( $(element).hasClass('active') ) {
            if ( i == 4 ) {
                if ( $('.navbar').hasClass('inv') == false )
                    return;
            } else {
                return;
            }
        }

        $('.menu-nav li').removeClass('active');
        $(element).addClass('active');

        var icon = $(element).find('.icon');

        var left_pos = icon.offset().left - $('.menu-nav').offset().left;
        var el_width = icon.width() + $(element).find('.text').width() + 10;

        $('.active-menu').stop(false, false).animate(
            {
                left: left_pos,
                width: el_width
            },
            1500,
            'easeInOutQuart'
        );
    };

    /*************
     * = Parallax *
     *************/
    jQuery(document).ready(function ($) {
        //Cache some variables
        var links = $('.nav').find('li');
        slide = $('.slide');
        button = $('.button');
        mywindow = $(window);
        htmlbody = $('html,body');

        //Create a function that will be passed a slide number and then will scroll to that slide using jquerys animate. The Jquery
        //easing plugin is also used, so we passed in the easing method of 'easeInOutQuint' which is available throught the plugin.
        function goToByScroll(dataslide) {
            var offset_top = ( dataslide == 1 ) ? '0px' : $('.slide[data-slide="' + dataslide + '"]').offset().top;

            htmlbody.stop(false, false).animate({
                scrollTop: offset_top
            }, 1500, 'easeInOutQuart');
        }

        //When the user clicks on the navigation links, get the data-slide attribute value of the link and pass that variable to the goToByScroll function
        links.click(function (e) {
            e.preventDefault();
            dataslide = $(this).attr('data-slide');
            goToByScroll(dataslide);
            $(".nav-collapse").collapse('hide');
        });

        //When the user clicks on the navigation links, get the data-slide attribute value of the link and pass that variable to the goToByScroll function
        $('.navigation-slide').click(function (e) {
            e.preventDefault();
            dataslide = $(this).attr('data-slide');
            goToByScroll(dataslide);
            $(".nav-collapse").collapse('hide');
        });
    });

    /***************
     * = Menu hover *
     ***************/
    jQuery(document).ready(function ($) {
        //Cache some variables
        var menu_item = $('.nav').find('li');

        menu_item.hover(
            function(e) {
                var icon = $(this).find('.icon');

                var left_pos = icon.offset().left - $('.nav').offset().left;
                var el_width = icon.width() + $(this).find('.text').width() + 10;

                var hover_bar = $('

')
                    .css('left', left_pos)
                    .css('width', el_width)
                    .attr('id', 'special-active-menu-' + $(this).data('slide') );

                $('.active-menu').after( hover_bar );
            },
            function(e) {
                $('.special-active-menu').remove();
            }
        );
    });

})
(jQuery);
<|endoftext|>