<commit_before>
function CommandParser(){
	this.state = "DEFAULT",
	this.quoteMark = '';
	this.escaped = false;

	this.tree = {
        nodes: []
    };

	this.branch = this.tree;

	this.node = {
        parentNode: this.branch,
        value: "",
        nodes: []
    };

}

CommandParser.prototype.states = ["DEFAULT", "LITERAL", "QUOTED"];

CommandParser.prototype.write = function(chunk){
	chunk = (chunk || "").toString("binary");
	this.parseLine(chunk);
	return true;
}

CommandParser.prototype.parseLine = function(line){

	var i=0, curchar;

    while(i < line.length){

        curchar = line[i].charAt(0);

        switch(curchar){
            case " ":
            case "\t":
                if(this.state == "QUOTED"){
                	this.node.value += curchar;
                }else if(this.state == "LITERAL" && this.escaped){
                	this.node.value += curchar;
                }else if(this.state == "LITERAL"){
                	this.branch.nodes.push(this.node);
                	this.state = "DEFAULT";
                	this.node = {
                        parentNode: this.branch,
                        value: "",
                        nodes: []
                    }
                }
                break;
            case '\\':
                if(this.escaped || this.state == "LITERAL"){
                	this.node.value += curchar;
                }else if(this.state == "QUOTED"){
                	this.escaped = true;
                }else if(this.state == "DEFAULT"){
                	this.state = "LITERAL";
                	this.node = {
                        parentNode: this.branch,
                        value: curchar,
                        nodes: []
                    }
                }
                break;
            case '"':
            case "'":
                if(this.escaped || (this.state == "QUOTED" && this.quoteMark != curchar)){
                	this.node.value += curchar;
                }else if(this.state == "DEFAULT"){
                	this.quoteMark = curchar;
                	this.state = "QUOTED";
                    node = {
                        parentNode: this.branch,
                        value: "",
                        nodes: []
                    }
                }else if(this.state == "QUOTED"){
                	this.branch.nodes.push(this.node);
                	this.state = "DEFAULT";
                	this.node = {
                        parentNode: this.branch,
                        value: "",
                        nodes: []
                    }
                }else if(this.state == "LITERAL"){
                	this.branch.nodes.push(this.node);
                	this.quoteMark = curchar;
                	this.state = "QUOTED";
                    node = {
                        parentNode: this.branch,
                        value: "",
                        nodes: []
                    }
                }
                break;
            case "[":
            case "(":
                if(this.escaped || this.state=="QUOTED"){
                	this.node.value += curchar;
                    break;
                }

                if(this.state == "LITERAL"){
                	this.branch.nodes.push(this.node);
                }

                this.state = "DEFAULT";
                this.branch = this.branch.nodes[this.branch.nodes.length-1] || this.tree;

                this.node = {
                    parentNode: this.branch,
                    value: "",
                    nodes: []
                }
                break;
            case "]":
            case ")":
                if(this.escaped || this.state=="QUOTED"){
                	this.node.value += curchar;
                    break;
                }

                if(this.state == "LITERAL"){
                	this.branch.nodes.push(this.node);
                }

                this.state = "DEFAULT";
                this.branch = this.branch.parentNode || this.branch;

                this.node = {
                    parentNode: this.branch,
                    value: "",
                    nodes: []
                }
                break;
            default:
                if(this.state == "LITERAL" || this.state == "QUOTED"){
                	this.node.value += curchar;
                }else{
                	this.state = "LITERAL";
                	this.node = {
                        parentNode: this.branch,
                        value: curchar,
                        nodes: []
                    }
                }
        }

        if(this.escaped && curchar != "\\"){
        	this.escaped = false;
        }

        i++;
    }

}

CommandParser.prototype.end = function(){
	if(this.node.value){
	    if(this.state == "LITERAL" || this.state=="QUOTED"){
	    	this.branch.nodes.push(this.node);
	    }
	}
	console.log(require("util").inspect(this.tree, false, 7));
}

var cp = new CommandParser();

cp.write("14 FETCH (FL\\AGS (\\Seen \\Dele");
cp.write("ted)) * 12 FETCH (RFC822 {342}");
cp.end();

//console.log(require("util").inspect(parseLine("14 FETCH (FL\\AGS (\\Seen \\Dele"), false, 7));

<commit_msg>update<commit_after>
function CommandParser(){
	this.init();
}

CommandParser.prototype.states = ["DEFAULT", "LITERAL", "QUOTED"];

CommandParser.prototype.init = function(){
	this.state = "DEFAULT",
	this.quoteMark = '';
	this.escaped = false;

	this.tree = {
        nodes: []
    };

	this.branch = this.tree;

	this.node = {
        parentNode: this.branch,
        value: "",
        nodes: []
    };
}

CommandParser.prototype.write = function(chunk){
	chunk = (chunk || "").toString("binary");
	this.parseLine(chunk);
	return true;
}

CommandParser.prototype.writeBlock = function(chunk){
	if(!this.node.block){
		this.node.value = "";
		this.node.block = true;
	}
	this.node.value += (chunk || "").toString("binary");
}

CommandParser.prototype.parseLine = function(line){

	var i=0, curchar;

    while(i < line.length){

        curchar = line[i].charAt(0);

        switch(curchar){
            case " ":
            case "\t":
                if(this.state == "QUOTED"){
                	this.node.value += curchar;
                }else if(this.state == "LITERAL" && this.escaped){
                	this.node.value += curchar;
                }else if(this.state == "LITERAL"){
                	this.addToBranch();
                	this.state = "DEFAULT";
                	this.createNode();
                }
                break;
            case '\\':
                if(this.escaped || this.state == "LITERAL"){
                	this.node.value += curchar;
                }else if(this.state == "QUOTED"){
                	this.escaped = true;
                }else if(this.state == "DEFAULT"){
                	this.state = "LITERAL";
                	this.createNode(curchar);
                }
                break;
            case '"':
            case "'":
                if(this.escaped || (this.state == "QUOTED" && this.quoteMark != curchar)){
                	this.node.value += curchar;
                }else if(this.state == "DEFAULT"){
                	this.quoteMark = curchar;
                	this.state = "QUOTED";
                	this.createNode();
                }else if(this.state == "QUOTED"){
                	this.addToBranch();
                	this.state = "DEFAULT";
                	this.createNode();
                }else if(this.state == "LITERAL"){
                	this.addToBranch();
                	this.quoteMark = curchar;
                	this.state = "QUOTED";
                	this.createNode();
                }
                break;
            case "[":
            case "(":
                if(this.escaped || this.state=="QUOTED"){
                	this.node.value += curchar;
                    break;
                }

                if(this.state == "LITERAL"){
                	this.addToBranch();
                }

                this.state = "DEFAULT";

                // () gets a separate node, [] uses last node as parent
                if(curchar == "("){
                	// create new empty node
                	this.createNode(false);
                	this.node.type = "GROUP";
                	this.addToBranch();

                    this.branch = this.node || this.tree;
                    if(!this.branch.nodes){
                    	this.branch.nodes = [];
                    }
                }else{
                	this.branch = this.branch.lastNode || this.tree;
                	this.branch.type = "PARAMS";
                	if(!this.branch.nodes){
                    	this.branch.nodes = [];
                    }
                }

                this.createNode();

                break;
            case "]":
            case ")":
                if(this.escaped || this.state=="QUOTED"){
                	this.node.value += curchar;
                    break;
                }

                if(this.state == "LITERAL"){
                	this.addToBranch();
                }

                this.state = "DEFAULT";

                this.branch = this.branch.parentNode || this.branch;
                if(!this.branch.nodes){
                	this.branch.nodes = [];
                }

                this.createNode();
                break;
            default:
                if(this.state == "LITERAL" || this.state == "QUOTED"){
                	this.node.value += curchar;
                }else{
                	this.state = "LITERAL";
                	this.createNode(curchar);
                }
        }

        if(this.escaped && curchar != "\\"){
        	this.escaped = false;
        }

        i++;
    }

}

CommandParser.prototype.addToBranch = function(){
	this.branch.nodes.push(this.node);
	this.branch.lastNode = this.node;
}

CommandParser.prototype.createNode = function(value){
	this.lastNode = this.node;

	this.node = {};

	if(value !== false){
		this.node.value = value || "";
	}

	this.node.parentNode = this.branch;
}

CommandParser.prototype.end = function(){
	if(this.node.value){
	    if(this.state == "LITERAL" || this.state=="QUOTED"){
	    	this.branch.nodes.push(this.node);
	    }
	}

	var tree = this.finalize();

	this.init();

	return tree;
}

CommandParser.prototype.finalize = function(){
	var tree = [];
	walker(this.tree.nodes, tree);
	return tree;

	function walker(branch, local){
		var node, i, len, curnode;

		for(i=0, len = branch.length; i<len; i++){
			node = branch[i];

			if(typeof node.value == "string" && !node.type){
				local.push(node.value);
			}else if(node.type == "PARAMS"){
				if(!node.nodes.length){
					local.push(node.value);
				}else{
					curnode = {
						value: node.value
					};
					local.push(curnode);
					curnode.params = [];
					walker(node.nodes, curnode.params);
				}

			}else if(node.type == "GROUP" && node.nodes.length){
				curnode = [];
				local.push(curnode);
				walker(node.nodes, curnode);
			}
		}
	}
}

var cp = new CommandParser();

//cp.write("A654 FETCH 2:4 (FLAGS BODY[HEADER.FIELDS (DATE FROM)])");
//cp.write("* 23 FETCH (FLAGS (\\Seen) UID 4827313)");
/*
cp.write("* 12 FETCH (BODY[HEADER] {342}");
cp.writeBlock("TERE TERE");
cp.write(" BODY[RFC] {123}");
cp.writeBlock("VANA KERE");
cp.write(")");

cp.end();
*/
//cp.write("* 12 FETCH (FLAGS (\\Seen) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" RFC822.SIZE 4286 ENVELOPE (\"Wed, 17 Jul 1996 02:23:25 -0700 (PDT)\" \"IMAP4rev1 WG mtg summary and minutes\" ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) ((NIL NIL \"imap\" \"cac.washington.edu\")) ((NIL NIL \"minutes\" \"CNRI.Reston.VA.US\") (\"John Klensin\" NIL \"KLENSIN\" \"MIT.EDU\")) NIL NIL \"<B27397-0100000@cac.washington.edu>\") BODY (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" 3028 92))");

cp.write("* OK [ALERT] System shutdown in 10 minutes");

console.log(JSON.stringify(cp.end()))

//console.log(require("util").inspect(cp.end(), false, 11));

//console.log(require("util").inspect(parseLine("14 FETCH (FL\\AGS (\\Seen \\Dele"), false, 7));

<|endoftext|>


<commit_before>modify in master
heihei
added in test
haha
<commit_msg>remove test.js<commit_after><|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-14 19:22:29<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>import differ from 'deep-diff';

// https://github.com/flitbit/diff#differences
const dictionary = {
  'E': {
    color: `#2196F3`,
    text: `CHANGED:`,
  },
  'N': {
    color: `#4CAF50`,
    text: `ADDED:`,
  },
  'D': {
    color: `#F44336`,
    text: `DELETED:`,
  },
  'A': {
    color: `#2196F3`,
    text: `ARRAY:`,
  },
};

function style(kind) {
  return `color: ${dictionary[kind].color}; font-weight: bold`;
}

function render(diff) {
  const { kind, path, lhs, rhs, index, item } = diff;

  switch (kind) {
    case `E`:
      return `${path.join(`.`)} ${lhs} → ${rhs}`;
    case `N`:
      return `${path.join(`.`)} ${rhs}`;
    case `D`:
      return `${path.join(`.`)}`;
    case `A`:
      return [`${path.join(`.`)}[${index}]`, item];
    default:
      return null;
  }
}

export default function diffLogger(prevState, newState, logger, isCollapsed) {
  const diff = differ(prevState, newState);

  try {
    if (isCollapsed) {
      logger.groupCollapsed(`diff`);
    } else {
      logger.group(`diff`);
    }
  } catch (e) {
    logger.log(`diff`);
  }

  if (diff) {
    diff.forEach((elem) => {
      const { kind } = elem;
      const output = render(elem);

      logger.log(`%c ${dictionary[kind].text}`, style(kind), output);
    });
  } else {
    logger.log(`—— no diff ——`);
  }

  try {
    logger.groupEnd();
  } catch (e) {
    logger.log(`—— diff end —— `);
  }
}
<commit_msg>fix: log diff output directly instead of converting to string (#182)<commit_after>import differ from 'deep-diff';

// https://github.com/flitbit/diff#differences
const dictionary = {
  'E': {
    color: `#2196F3`,
    text: `CHANGED:`,
  },
  'N': {
    color: `#4CAF50`,
    text: `ADDED:`,
  },
  'D': {
    color: `#F44336`,
    text: `DELETED:`,
  },
  'A': {
    color: `#2196F3`,
    text: `ARRAY:`,
  },
};

function style(kind) {
  return `color: ${dictionary[kind].color}; font-weight: bold`;
}

function render(diff) {
  const { kind, path, lhs, rhs, index, item } = diff;

  switch (kind) {
    case `E`:
      return [path.join(`.`), lhs, `→`, rhs];
    case `N`:
      return [path.join(`.`), rhs];
    case `D`:
      return [path.join(`.`)];
    case `A`:
      return [`${path.join(`.`)}[${index}]`, item];
    default:
      return [];
  }
}

export default function diffLogger(prevState, newState, logger, isCollapsed) {
  const diff = differ(prevState, newState);

  try {
    if (isCollapsed) {
      logger.groupCollapsed(`diff`);
    } else {
      logger.group(`diff`);
    }
  } catch (e) {
    logger.log(`diff`);
  }

  if (diff) {
    diff.forEach((elem) => {
      const { kind } = elem;
      const output = render(elem);

      logger.log(`%c ${dictionary[kind].text}`, style(kind), ...output);
    });
  } else {
    logger.log(`—— no diff ——`);
  }

  try {
    logger.groupEnd();
  } catch (e) {
    logger.log(`—— diff end —— `);
  }
}
<|endoftext|>


<commit_before>(function(window, factory) {
	var dom = factory(window, window.document);
	window.dom = dom;
	if(typeof module == 'object' && module.exports){
		module.exports = dom;
	}
}(typeof window != 'undefined' ? window : this , function(window, document) {
	'use strict';
	var slice = [].slice;
	var dom = function(elements){

		if(typeof elements == 'string'){
			return dom.q(elements);
		}
		if(!this){
			return new dom(elements);
		}

		if(!Array.isArray(elements)){
			if(!elements){
				elements = [];
			} else if(elements.nodeName || !('length' in elements)){
				elements = [elements];
			} else {
				elements = slice.call(elements);
			}
		}

		this.elements = elements;
	};
	var fn = dom.prototype;

	dom.fn = dom.prototype;

	dom.q = function(sel, context){
		return new dom( (context || document).querySelectorAll(sel) );
	};

	fn.find = function(sel){
		var array = [];
		this.elements.forEach(function(elem){
			var i, len;
			var elements = elem.querySelectorAll(sel);
			for(i = 0, len = elements.length; i < len; i++){
				if(array.indexOf(elements[i]) == -1){
					array.push(elements[i]);
				}
			}
		});

		return new dom( array );
	};

	fn.closest = function(sel){
		var array = [];
		this.elements.forEach(function(elem){
			var element = elem.closest(sel);
			if(array.indexOf(element) == -1){
				array.push(element);
			}
		});
		return new dom( array );
	};

	fn.get = function(number){
		return arguments.length ? this.elements[number] : this.elements;
	};

	[['on', 'addEventListener'], ['off', 'removeEventListener']].forEach(function(action){
		dom.fn[action[0]] = function(type, sel, fn, capture){
			var useFn;
			if(typeof sel == 'function'){
				capture = fn;
				fn = sel;
				sel = null;
			}

			if(sel){
				if(!fn[sel]){
					fn[sel] = function(e){
						e.delegatedTarget = e.target.closest(sel);
						if(!e.delegatedTarget){return;}
						return fn.apply(this, arguments);
					};
				}
				useFn = fn[sel];
			} else {
				useFn = fn;
			}

			this.elements.forEach(function(elem){
				elem[action[1]](type, useFn, capture || false);
			});

			return this;
		};
	});

	fn.css = function(style, pseudo){
		var elem;
		if(typeof style == 'string'){
			elem = this.elements[0];
			return elem && getComputedStyle(elem, pseudo).getPropertyValue(style);
		}
		this.elements.forEach(function(elem){
			var prop;
			var eStyle = elem.style;
			for(prop in style){
				eStyle[prop] = style[prop];
			}
		});
		return this;
	};

	fn.prop = function(props){
		var elem;
		if(typeof props == 'string'){
			elem = this.elements[0];
			return elem && elem[props];
		}
		this.elements.forEach(function(elem){
			var prop;
			for(prop in props){
				elem[prop] = props[prop];
			}
		});
		return this;
	};

	fn.attr = function(attrs){
		var elem;
		if(typeof attrs == 'string'){
			elem = this.elements[0];
			return elem && elem.getAttribute(attrs);
		}
		this.elements.forEach(function(elem){
			var attr;
			for(attr in attrs){
				elem.setAttribute(attr, attrs[attr]);
			}
		});
		return this;
	};

	['add', 'remove'].forEach(function(action){
		fn[action + 'Class'] =  function(cl){
			this.elements.forEach(function(elem){
				elem.classList[action](cl);
			});
			return this;
		};
	});

	fn.matches = function(sel){
		return this.elements.some(function(elem){
			return elem.matches(sel);
		});
	};

	fn.html = function(html){
		var elem;
		var isString = typeof html == 'string';
		if(!arguments.length){
			elem = this.elements[0];
			return elem && elem.innerHTML || '';
		}
		this.elements.forEach(function(elem){
			if(isString){
				elem.innerHTML = html;
			} else {
				elem.innerHTML = '';
				elem.appendChild(html);
			}
		});
		return this;
	};

	fn.before = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			var parentElement;
			if (isString){
				elem.insertAdjacentHTML('beforebegin', html);
			} else {
				parentElement = elem.parentNode;
				if(parentElement){
					parentElement.insertBefore(html, elem);
				}
			}
		});
		return this;
	};

	fn.prepend = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			if (isString){
				elem.insertAdjacentHTML('afterbegin', html);
			} else {
				elem.insertBefore(html, elem.firstChild);
			}
		});
		return this;
	};

	fn.append = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			if (isString){
				elem.insertAdjacentHTML('beforeend', html);
			} else {
				elem.insertBefore(html, null);
			}
		});
		return this;
	};

	fn.after = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			var parentElement;
			if (isString){
				elem.insertAdjacentHTML('afterend', html);
			} else {
				parentElement = elem.parentNode;
				if(parentElement){
					parentElement.insertBefore(html, elem.nextElementSibling);
				}
			}
		});
		return this;
	};

	fn.each = function(cb){
		this.elements.forEach(cb);
		return this;
	};

	DOM.Event = function(type, options){
		if(!options){
			options = {};
		}

		if(options.bubbles == null){
			options.bubbles = true;
		}

		return new CustomEvent(type, options);
	};

	fn.trigger = function(type, options, getEvent){
		var ret, firstEvent;

		if(typeof type == 'object'){
			firstEvent = type;
			type = firstEvent.type;
		}

		if(typeof options == 'boolean'){
			getEvent = options;
			options = null;
		}

		if(!options){
			options = {};
		}

		if(options.bubbles == null){
			options.bubbles = true;
		}

		this.elements.forEach(function(elem){
			var event = firstEvent || new CustomEvent(type, options);
			firstEvent = null;

			if(!ret && getEvent){
				ret = event;
			}
			elem.dispatchEvent(event);
		});

		return ret || this;
	};

	['forEach', 'reverse', 'sort', 'push'].forEach(function(name){
		fn[name] = function(){
			this.elements[name].apply(this.elements, arguments);
			return this;
		};
	});

	//new array or returns array
	['map', 'filter', 'pop', 'shift', 'slice', 'splice', 'unshift'].forEach(function(name){
		fn[name] = function(){
			return new dom(this.elements[name].apply(this.elements, arguments));
		};
	});

	['every', 'findIndex', 'includes', 'indexOf', 'lastIndexOf', 'some'].forEach(function(name){
		fn[name] = function(){
			return this.elements[name].apply(this.elements, arguments);
		};
	});

	return dom;
}));
<commit_msg>improve dom lib<commit_after>(function(window, factory) {
	var dom = factory(window, window.document);
	window.dom = dom;
	if(typeof module == 'object' && module.exports){
		module.exports = dom;
	}
}(typeof window != 'undefined' ? window : this , function(window, document) {
	'use strict';
	var slice = [].slice;
	var dom = function(elements){

		if(typeof elements == 'string'){
			return dom.q(elements);
		}
		if(!this){
			return new dom(elements);
		}

		if(!Array.isArray(elements)){
			if(!elements){
				elements = [];
			} else if(elements.nodeName || !('length' in elements)){
				elements = [elements];
			} else {
				elements = slice.call(elements);
			}
		}

		this.elements = elements;
	};
	var fn = dom.prototype;

	dom.fn = dom.prototype;

	dom.q = function(sel, context){
		return new dom( (context || document).querySelectorAll(sel) );
	};

	dom.Event = function(type, options){
		if(!options){
			options = {};
		}

		if(options.bubbles == null){
			options.bubbles = true;
		}

		return new CustomEvent(type, options);
	};

	fn.find = function(sel){
		var array = [];
		this.elements.forEach(function(elem){
			var i, len;
			var elements = elem.querySelectorAll(sel);
			for(i = 0, len = elements.length; i < len; i++){
				if(array.indexOf(elements[i]) == -1){
					array.push(elements[i]);
				}
			}
		});

		return new dom( array );
	};

	fn.closest = function(sel){
		var array = [];
		this.elements.forEach(function(elem){
			var element = elem.closest(sel);
			if(array.indexOf(element) == -1){
				array.push(element);
			}
		});
		return new dom( array );
	};

	fn.get = function(number){
		return arguments.length ? this.elements[number] : this.elements;
	};

	[['on', 'addEventListener'], ['off', 'removeEventListener']].forEach(function(action){
		dom.fn[action[0]] = function(type, sel, fn, capture){
			var useFn;
			if(typeof sel == 'function'){
				capture = fn;
				fn = sel;
				sel = null;
			}

			if(sel){
				if(!fn[sel]){
					fn[sel] = function(e){
						e.delegatedTarget = e.target.closest(sel);
						if(!e.delegatedTarget){return;}
						return fn.apply(this, arguments);
					};
				}
				useFn = fn[sel];
			} else {
				useFn = fn;
			}

			this.elements.forEach(function(elem){
				elem[action[1]](type, useFn, capture || false);
			});

			return this;
		};
	});

	fn.css = function(style, pseudo){
		var elem;
		if(typeof style == 'string'){
			elem = this.elements[0];
			return elem && getComputedStyle(elem, pseudo).getPropertyValue(style);
		}
		this.elements.forEach(function(elem){
			var prop;
			var eStyle = elem.style;
			for(prop in style){
				eStyle[prop] = style[prop];
			}
		});
		return this;
	};

	fn.prop = function(props){
		var elem;
		if(typeof props == 'string'){
			elem = this.elements[0];
			return elem && elem[props];
		}
		this.elements.forEach(function(elem){
			var prop;
			for(prop in props){
				elem[prop] = props[prop];
			}
		});
		return this;
	};

	fn.attr = function(attrs){
		var elem;
		if(typeof attrs == 'string'){
			elem = this.elements[0];
			return elem && elem.getAttribute(attrs);
		}
		this.elements.forEach(function(elem){
			var attr;
			for(attr in attrs){
				elem.setAttribute(attr, attrs[attr]);
			}
		});
		return this;
	};

	['add', 'remove'].forEach(function(action){
		fn[action + 'Class'] =  function(cl){
			this.elements.forEach(function(elem){
				elem.classList[action](cl);
			});
			return this;
		};
	});

	fn.matches = function(sel){
		return this.elements.some(function(elem){
			return elem.matches(sel);
		});
	};

	fn.html = function(html){
		var elem;
		var isString = typeof html == 'string';
		if(!arguments.length){
			elem = this.elements[0];
			return elem && elem.innerHTML || '';
		}
		this.elements.forEach(function(elem){
			if(isString){
				elem.innerHTML = html;
			} else {
				elem.innerHTML = '';
				elem.appendChild(html);
			}
		});
		return this;
	};

	fn.before = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			var parentElement;
			if (isString){
				elem.insertAdjacentHTML('beforebegin', html);
			} else {
				parentElement = elem.parentNode;
				if(parentElement){
					parentElement.insertBefore(html, elem);
				}
			}
		});
		return this;
	};

	fn.prepend = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			if (isString){
				elem.insertAdjacentHTML('afterbegin', html);
			} else {
				elem.insertBefore(html, elem.firstChild);
			}
		});
		return this;
	};

	fn.append = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			if (isString){
				elem.insertAdjacentHTML('beforeend', html);
			} else {
				elem.insertBefore(html, null);
			}
		});
		return this;
	};

	fn.after = function(html){
		var isString = typeof html == 'string';
		this.elements.forEach(function(elem){
			var parentElement;
			if (isString){
				elem.insertAdjacentHTML('afterend', html);
			} else {
				parentElement = elem.parentNode;
				if(parentElement){
					parentElement.insertBefore(html, elem.nextElementSibling);
				}
			}
		});
		return this;
	};

	fn.each = function(cb){
		this.elements.forEach(cb);
		return this;
	};

	fn.trigger = function(type, options, getEvent){
		var ret, firstEvent;

		if(typeof type == 'object'){
			firstEvent = type;
			type = firstEvent.type;
		}

		if(typeof options == 'boolean'){
			getEvent = options;
			options = null;
		}

		if(!options){
			options = {};
		}

		if(options.bubbles == null){
			options.bubbles = true;
		}

		this.elements.forEach(function(elem){
			var event = firstEvent || new CustomEvent(type, options);
			firstEvent = null;

			if(!ret && getEvent){
				ret = event;
			}
			elem.dispatchEvent(event);
		});

		return ret || this;
	};

	['forEach', 'reverse', 'sort', 'push'].forEach(function(name){
		fn[name] = function(){
			this.elements[name].apply(this.elements, arguments);
			return this;
		};
	});

	//new array or returns array
	['map', 'filter', 'pop', 'shift', 'slice', 'splice', 'unshift'].forEach(function(name){
		fn[name] = function(){
			return new dom(this.elements[name].apply(this.elements, arguments));
		};
	});

	['every', 'findIndex', 'includes', 'indexOf', 'lastIndexOf', 'some'].forEach(function(name){
		fn[name] = function(){
			return this.elements[name].apply(this.elements, arguments);
		};
	});

	return dom;
}));
<|endoftext|>


<commit_before>'use strict';
var MACROUTILS = require( 'osg/Utils' );
var Notify = require( 'osg/Notify' );
var GLObject = require( 'osg/GLObject' );
var StateAttribute = require( 'osg/StateAttribute' );
var CustomMap = require( 'osg/Map' );
var Timer = require( 'osg/Timer' );

/**
 * Program encapsulate an vertex and fragment shader
 * @class Program
 */
var Program = function ( vShader, fShader ) {
    GLObject.call( this );
    StateAttribute.call( this );
    this._program = null;

    // used to know if it's a default program
    // a default program does nothing but avoid to do some
    // useless logic
    // if we vertex or fragment shader are set it's not a default
    // program anymore
    this._nullProgram = true;

    this._vertex = undefined;
    this._fragment = undefined;

    this._uniformsCache = undefined;
    this._attributesCache = undefined;

    if ( vShader )
        this.setVertexShader( vShader );

    if ( fShader )
        this.setFragmentShader( fShader );

    this._dirty = true;
};

// static cache of glPrograms flagged for deletion, which will actually
// be deleted in the correct GL context.
Program._sDeletedGLProgramCache = new window.Map();

// static method to delete Program
Program.deleteGLProgram = function ( gl, program ) {

    if ( !Program._sDeletedGLProgramCache.has( gl ) )
        Program._sDeletedGLProgramCache.set( gl, [] );

    Program._sDeletedGLProgramCache.get( gl ).push( program );
};

// static method to flush all the cached glPrograms which need to be deleted in the GL context specified
Program.flushDeletedGLPrograms = function ( gl, availableTime ) {

    // if no time available don't try to flush objects.
    if ( availableTime <= 0.0 ) return availableTime;

    if ( !Program._sDeletedGLProgramCache.has( gl ) ) return availableTime;

    var elapsedTime = 0.0;
    var beginTime = Timer.instance().tick();
    var deleteList = Program._sDeletedGLProgramCache.get( gl );
    var numPrograms = deleteList.length;

    for ( var i = numPrograms - 1; i >= 0 && elapsedTime < availableTime; i-- ) {
        gl.deleteProgram( deleteList[ i ] );
        deleteList.splice( i, 1 );
        elapsedTime = Timer.instance().deltaS( beginTime, Timer.instance().tick() );
    }

    return availableTime - elapsedTime;
};

Program.flushAllDeletedGLPrograms = function ( gl ) {

    if ( !Program._sDeletedGLProgramCache.has( gl ) ) return;

    var deleteList = Program._sDeletedGLProgramCache.get( gl );
    var numPrograms = deleteList.length;

    for ( var i = numPrograms - 1; i >= 0; i-- ) {
        gl.deleteProgram( deleteList[ i ] );
        deleteList.splice( i, 1 );
    }
};

/** @lends Program.prototype */
Program.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( GLObject.prototype, MACROUTILS.objectInherit( StateAttribute.prototype, {

    attributeType: 'Program',

    cloneType: function () {
        return new Program();
    },

    setVertexShader: function ( vs ) {
        this._vertex = vs;
        this._nullProgram = false;
    },

    setFragmentShader: function ( fs ) {
        this._fragment = fs;
        this._nullProgram = false;
    },

    getVertexShader: function () {
        return this._vertex;
    },
    getFragmentShader: function () {
        return this._fragment;
    },

    getProgram: function () {
        return this._program;
    },

    releaseGLObjects: function () {
        // Call to releaseGLOBjects on shaders
        if ( this._vertex !== undefined ) this._vertex.releaseGLObjects();
        if ( this._fragment !== undefined ) this._fragment.releaseGLObjects();
        if ( this._program === null ) return;
        if ( this._gl !== undefined ) {
            Program.deleteGLProgram( this._gl, this._program );
        }
        this._program = undefined;
    },

    apply: function ( state ) {

        if ( this._nullProgram ) return;

        if ( !this._gl ) {
            this.setGraphicContext( state.getGraphicContext() );
        }
        var gl = this._gl;
        if ( !this._program || this._dirty ) {

            var compileClean;

            if ( !this._vertex.shader ) {
                compileClean = this._vertex.compile( gl );
            }

            if ( !this._fragment.shader ) {
                compileClean = this._fragment.compile( gl );
            }

            if ( compileClean ) {

                this._program = gl.createProgram();

                gl.attachShader( this._program, this._vertex.shader );
                gl.attachShader( this._program, this._fragment.shader );
                MACROUTILS.timeStamp( 'osgjs.metrics:linkShader' );
                gl.linkProgram( this._program );

                if ( !gl.getProgramParameter( this._program, gl.LINK_STATUS ) && !gl.isContextLost() ) {
                    var errLink = gl.getProgramInfoLog( this._program );

                    Notify.error( errLink );
                    Notify.log( 'can\'t link program\n' + 'vertex shader:\n' + this._vertex.text + '\n fragment shader:\n' + this._fragment.text, true, false );
                    // rawgl trick is for webgl inspector
                    var debugShader = ( gl.rawgl !== undefined ? gl.rawgl : gl );
                    if ( debugShader !== undefined && debugShader.getExtension !== undefined ) debugShader = debugShader.getExtension( 'WEBGL_debug_shaders' );
                    if ( debugShader && errLink === 'Failed to create D3D shaders.\n' ) {

                        Notify.error( debugShader.getTranslatedShaderSource( this._vertex.shader ), true, false );
                        Notify.error( debugShader.getTranslatedShaderSource( this._fragment.shader ), true, false );
                    }

                    compileClean = false;
                }
                // TODO: better usage of validate.
                // as it's intended at shader program usage
                // validating against current gl state
                // Not for compilation stage
                // gl.validateProgram( this._program );

            }

            if ( !compileClean ) {
                // Any error, Any
                // Pink must die.
                if ( !Program.prototype._failSafeCache ) {

                    var program = gl.createProgram();
                    this._vertex.failSafe( gl );
                    this._fragment.failSafe( gl );

                    gl.attachShader( program, this._vertex.shader );
                    gl.attachShader( program, this._fragment.shader );
                    gl.linkProgram( program );
                    gl.validateProgram( program );

                    // cache to compile and allocate only once
                    // not polluting the inspector
                    Program.prototype._failSafeCache = program;
                }
                Notify.warn( 'FailSafe shader Activated ' );
                this._program = this._failSafeCache;
            }

            this._uniformsCache = new CustomMap();
            this._attributesCache = new CustomMap();

            this.cacheUniformList( gl, this._vertex.text );
            this.cacheUniformList( gl, this._fragment.text );

            this.cacheAttributeList( gl, this._vertex.text );

            this._dirty = false;
        }

        state.applyProgram( this._program );
    },

    cacheUniformList: function ( gl, str ) {
        var r = str.match( /uniform\s+\w+\s+\w+((\s)?\[(.*?)\])?/g );
        var map = this._uniformsCache;
        if ( r !== null ) {
            for ( var i = 0, l = r.length; i < l; i++ ) {
                var uniform = r[ i ].match( /uniform\s+\w+\s+(\w+)/ )[ 1 ];
                var uniformName = r[ i ].match( /uniform\s+\w+\s+(\w+((\s)?\[(.*?)\])?)/ )[ 1 ];
                var location = gl.getUniformLocation( this._program, uniform );
                if ( location !== undefined && location !== null ) {
                    if ( map[ uniformName ] === undefined ) {
                        map[ uniformName ] = location;
                        this._uniformsCache.dirty();
                    }
                }
            }
        }
    },

    cacheAttributeList: function ( gl, str ) {
        var r = str.match( /attribute\s+\w+\s+\w+/g );
        var map = this._attributesCache;
        if ( r !== null ) {
            for ( var i = 0, l = r.length; i < l; i++ ) {
                var attr = r[ i ].match( /attribute\s+\w+\s+(\w+)/ )[ 1 ];
                var location = gl.getAttribLocation( this._program, attr );
                if ( location !== -1 && location !== undefined ) {
                    if ( map[ attr ] === undefined ) {
                        map[ attr ] = location;
                        this._attributesCache.dirty();
                    }
                }
            }
        }
    }
} ) ), 'osg', 'Program' );

module.exports = Program;
<commit_msg>Fixes uniform array regexp<commit_after>'use strict';
var MACROUTILS = require( 'osg/Utils' );
var Notify = require( 'osg/Notify' );
var GLObject = require( 'osg/GLObject' );
var StateAttribute = require( 'osg/StateAttribute' );
var CustomMap = require( 'osg/Map' );
var Timer = require( 'osg/Timer' );

/**
 * Program encapsulate an vertex and fragment shader
 * @class Program
 */
var Program = function ( vShader, fShader ) {
    GLObject.call( this );
    StateAttribute.call( this );
    this._program = null;

    // used to know if it's a default program
    // a default program does nothing but avoid to do some
    // useless logic
    // if we vertex or fragment shader are set it's not a default
    // program anymore
    this._nullProgram = true;

    this._vertex = undefined;
    this._fragment = undefined;

    this._uniformsCache = undefined;
    this._attributesCache = undefined;

    if ( vShader )
        this.setVertexShader( vShader );

    if ( fShader )
        this.setFragmentShader( fShader );

    this._dirty = true;
};

// static cache of glPrograms flagged for deletion, which will actually
// be deleted in the correct GL context.
Program._sDeletedGLProgramCache = new window.Map();

// static method to delete Program
Program.deleteGLProgram = function ( gl, program ) {

    if ( !Program._sDeletedGLProgramCache.has( gl ) )
        Program._sDeletedGLProgramCache.set( gl, [] );

    Program._sDeletedGLProgramCache.get( gl ).push( program );
};

// static method to flush all the cached glPrograms which need to be deleted in the GL context specified
Program.flushDeletedGLPrograms = function ( gl, availableTime ) {

    // if no time available don't try to flush objects.
    if ( availableTime <= 0.0 ) return availableTime;

    if ( !Program._sDeletedGLProgramCache.has( gl ) ) return availableTime;

    var elapsedTime = 0.0;
    var beginTime = Timer.instance().tick();
    var deleteList = Program._sDeletedGLProgramCache.get( gl );
    var numPrograms = deleteList.length;

    for ( var i = numPrograms - 1; i >= 0 && elapsedTime < availableTime; i-- ) {
        gl.deleteProgram( deleteList[ i ] );
        deleteList.splice( i, 1 );
        elapsedTime = Timer.instance().deltaS( beginTime, Timer.instance().tick() );
    }

    return availableTime - elapsedTime;
};

Program.flushAllDeletedGLPrograms = function ( gl ) {

    if ( !Program._sDeletedGLProgramCache.has( gl ) ) return;

    var deleteList = Program._sDeletedGLProgramCache.get( gl );
    var numPrograms = deleteList.length;

    for ( var i = numPrograms - 1; i >= 0; i-- ) {
        gl.deleteProgram( deleteList[ i ] );
        deleteList.splice( i, 1 );
    }
};

/** @lends Program.prototype */
Program.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( GLObject.prototype, MACROUTILS.objectInherit( StateAttribute.prototype, {

    attributeType: 'Program',

    cloneType: function () {
        return new Program();
    },

    setVertexShader: function ( vs ) {
        this._vertex = vs;
        this._nullProgram = false;
    },

    setFragmentShader: function ( fs ) {
        this._fragment = fs;
        this._nullProgram = false;
    },

    getVertexShader: function () {
        return this._vertex;
    },
    getFragmentShader: function () {
        return this._fragment;
    },

    getProgram: function () {
        return this._program;
    },

    releaseGLObjects: function () {
        // Call to releaseGLOBjects on shaders
        if ( this._vertex !== undefined ) this._vertex.releaseGLObjects();
        if ( this._fragment !== undefined ) this._fragment.releaseGLObjects();
        if ( this._program === null ) return;
        if ( this._gl !== undefined ) {
            Program.deleteGLProgram( this._gl, this._program );
        }
        this._program = undefined;
    },

    apply: function ( state ) {

        if ( this._nullProgram ) return;

        if ( !this._gl ) {
            this.setGraphicContext( state.getGraphicContext() );
        }
        var gl = this._gl;
        if ( !this._program || this._dirty ) {

            var compileClean;

            if ( !this._vertex.shader ) {
                compileClean = this._vertex.compile( gl );
            }

            if ( !this._fragment.shader ) {
                compileClean = this._fragment.compile( gl );
            }

            if ( compileClean ) {

                this._program = gl.createProgram();

                gl.attachShader( this._program, this._vertex.shader );
                gl.attachShader( this._program, this._fragment.shader );
                MACROUTILS.timeStamp( 'osgjs.metrics:linkShader' );
                gl.linkProgram( this._program );

                if ( !gl.getProgramParameter( this._program, gl.LINK_STATUS ) && !gl.isContextLost() ) {
                    var errLink = gl.getProgramInfoLog( this._program );

                    Notify.error( errLink );
                    Notify.log( 'can\'t link program\n' + 'vertex shader:\n' + this._vertex.text + '\n fragment shader:\n' + this._fragment.text, true, false );
                    // rawgl trick is for webgl inspector
                    var debugShader = ( gl.rawgl !== undefined ? gl.rawgl : gl );
                    if ( debugShader !== undefined && debugShader.getExtension !== undefined ) debugShader = debugShader.getExtension( 'WEBGL_debug_shaders' );
                    if ( debugShader && errLink === 'Failed to create D3D shaders.\n' ) {

                        Notify.error( debugShader.getTranslatedShaderSource( this._vertex.shader ), true, false );
                        Notify.error( debugShader.getTranslatedShaderSource( this._fragment.shader ), true, false );
                    }

                    compileClean = false;
                }
                // TODO: better usage of validate.
                // as it's intended at shader program usage
                // validating against current gl state
                // Not for compilation stage
                // gl.validateProgram( this._program );

            }

            if ( !compileClean ) {
                // Any error, Any
                // Pink must die.
                if ( !Program.prototype._failSafeCache ) {

                    var program = gl.createProgram();
                    this._vertex.failSafe( gl );
                    this._fragment.failSafe( gl );

                    gl.attachShader( program, this._vertex.shader );
                    gl.attachShader( program, this._fragment.shader );
                    gl.linkProgram( program );
                    gl.validateProgram( program );

                    // cache to compile and allocate only once
                    // not polluting the inspector
                    Program.prototype._failSafeCache = program;
                }
                Notify.warn( 'FailSafe shader Activated ' );
                this._program = this._failSafeCache;
            }

            this._uniformsCache = new CustomMap();
            this._attributesCache = new CustomMap();

            this.cacheUniformList( gl, this._vertex.text );
            this.cacheUniformList( gl, this._fragment.text );

            this.cacheAttributeList( gl, this._vertex.text );

            this._dirty = false;
        }

        state.applyProgram( this._program );
    },

    cacheUniformList: function ( gl, str ) {

        var r = str.match( /uniform\s+\w+\s+\w+((\s)?\[(.*?)\])?/g );
        var map = this._uniformsCache;
        if ( r !== null ) {
            for ( var i = 0, l = r.length; i < l; i++ ) {
                var uniform = r[ i ].match( /uniform\s+\w+\s+(\w+)/ )[ 1 ];
                var uniformName = r[ i ].match( /uniform\s+\w+\s+(\w+)(\s?\[.*?\])?/ )[ 1 ];
                var location = gl.getUniformLocation( this._program, uniform );
                if ( location !== undefined && location !== null ) {
                    if ( map[ uniformName ] === undefined ) {
                        map[ uniformName ] = location;
                        this._uniformsCache.dirty();
                    }
                }
            }
        }

    },

    cacheAttributeList: function ( gl, str ) {
        var r = str.match( /attribute\s+\w+\s+\w+/g );
        var map = this._attributesCache;
        if ( r !== null ) {
            for ( var i = 0, l = r.length; i < l; i++ ) {
                var attr = r[ i ].match( /attribute\s+\w+\s+(\w+)/ )[ 1 ];
                var location = gl.getAttribLocation( this._program, attr );
                if ( location !== -1 && location !== undefined ) {
                    if ( map[ attr ] === undefined ) {
                        map[ attr ] = location;
                        this._attributesCache.dirty();
                    }
                }
            }
        }
    }
} ) ), 'osg', 'Program' );

module.exports = Program;
<|endoftext|>


<commit_before>/**
 * @file docx.js
 * @author schoeu
 * */

var path = require('path');
var fs = require('fs');
var url = require('url');
var express = require('express');
var bodyParser = require('body-parser');
var marked = require('marked');
var highlight = require('highlight.js');
var glob = require('glob');
var serve_static = require('serve-static');
var exphbs  = require('express-handlebars');

var CONF = require('../docx-conf.json');
var warning = require('./warning.js');
var update = require('./update.js');

var app = express();
var ignorDor = CONF.ignoreDir || [];

var dirMap = {};
var htmlStr = '';
var headText = CONF.headText || '';
var headParts = headText.split('-') || [];
var locals = {
    headMain: headParts[0] || '',
    headSub: headParts[1] || '',
    title: CONF.title || headText,
    links: CONF.extUrls.links || [],
    surposEmail: CONF.surposEmail || '',
    label: CONF.extUrls.label
};

function Docx() {
    this.init();
}

var htmlCodes = [
    '
',
    '
',
    '
' + headText + '
',
    '                {{brandData}}',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '                        {{mdData}}',
    '
',
    '
',
    '
',
    '
',
    '
'
].join('');

Docx.prototype = {
    contributor: Docx,

    /**
     * 初始化DOCX,主要初始化了express
     * */
    init: function () {
        var me = this;
        // express 视图设置
        if (!CONF.debug) {
            app.enable('view cache');
        }
        app.set('views', path.join(__dirname, '..', 'views'));
        app.engine('.hbs', exphbs({extname: '.hbs'}));
        app.set('view engine', '.hbs');
        app.use(express.static(path.join(__dirname, '..', 'public')));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));

        // 路由处理
        me.routes();
        // 容错处理
        app.use(function(err, req, res, next) {
            // 如果开启了错误邮件报警则发错邮件
            if (err && CONF.waringFlag) {
                warning.sendMail(err.toString());
            }
        });

        app.listen(CONF.port || 8910);

        // 根据文档获取文档结构树
        me.getDocTree();
    },

    /**
     * 系统的路由定义
     * */
    routes: function () {
        var me = this;

        // 文档主路径
        app.get('/', function (req, res) {
            res.redirect(CONF.index);
        });

        // markdown文件路由
        app.get('/*.md', function (req, res) {
            var relativePath = url.parse(req.originalUrl);
            var pathName = relativePath.pathname || '';
            var mdPath = path.join(CONF.path, pathName);
            if (mdPath) {
                mdPath = decodeURIComponent(mdPath);
            }

            var file = fs.readFileSync(mdPath);

            // markdown转换成html
            var content = me.getMarked(file.toString());

            // 判断是pjax请求则返回html片段
            if (req.headers['x-pjax'] === 'true') {
                var rsPjaxDom = me.getPjaxContent(pathName, content);
                res.end(rsPjaxDom);
            }
            // 否则返回整个模板
            else {
                var parseObj = Object.assign({}, locals, {navData: htmlStr, mdData: content});
                res.render('main', parseObj);
            }
        });

        // API: 搜索功能
        app.post('/api/search', function (req, res) {
            var searchRs = [];
            var key = req.body.name;
            var filePath = path.join(CONF.path, '**/*.md');
            var files = glob.sync(filePath) || [];
            files.forEach(function (it) {
                if (it) {
                    it = decodeURIComponent(it);
                }
                // 判断文件是否存在
                // var file = fs.readFileSync(it);
                // var fileContent = file.toString();
                var fileTitle = me.getMdTitle(it) || '';
                var reg = new RegExp(key,'ig');
                if (reg.test(fileTitle)) {
                    searchRs.push({
                        path: it.replace(CONF.path, ''),
                        title: me.getMdTitle(it)
                    });
                }
            });
            res.json({
                error: 0,
                data: searchRs
            });
        });

        // API: 文档更新钩子
        app.get('/api/update', function (req, res, next) {
            var status = update(req, res, next);
            res.json({
                errorno: 0,
                files: files
            });
        });

        // 委托其他静态资源
        app.use('/', serve_static(CONF.path));
    },

    /**
     * 处理&组装面包屑数据
     * @param {String} pathName 文件路径
     * @return {String} 转换为中文的HTML字符串
     * */
    getPjaxContent: function (pathName, content) {
        var me = this;
        var brandStr = '';
        var pathArr = pathName.split('/');
        var brandData = me.processBreadcrumb(pathArr);
        brandData.forEach(function (it) {
            brandStr += '
' + it + '
';
        });
        var rsHTML = htmlCodes.replace('{{brandData}}', brandStr).replace('{{mdData}}', content);
        return rsHTML;
    },

    /**
     * 处理&组装面包屑数据
     * @param {Array} breadcrumb 面包屑原始数据
     * @return {Array} 转换为中文的数据
     * */
    processBreadcrumb: function(breadcrumb) {
        breadcrumb = breadcrumb || [];
        var dirMap = [];
        breadcrumb.forEach(function (it) {
            if (it) {
                if (it.indexOf('.md') > -1) {
                }
                else {
                    var nameMap = CONF.dirname[it] || {};
                    dirMap.push(nameMap.name || '');
                }
            }
        });
        return dirMap;
    },

    /**
     * markdown文件转html处理
     *
     * @param {String} content markdown字符串
     * @return {String} html字符串
     * */
    getMarked: function (content) {
        var renderer = new marked.Renderer();

        // markdown中渲染代码处理
        renderer.code = function (data, lang) {
            data = highlight.highlightAuto(data).value;
            if (lang) {
                // 超过3行有提示
                if (data.split(/\n/).length >= 3) {
                    var html = '
' + lang + '';
                    return html + data + '
';
                }
                return '
' + data + '
';
            }
            return '
' + data + '
';
        };

        return marked(content, {renderer});
    },

    /**
     * 获取文件目录树
     * */
    getDocTree: function () {
        this.walker(CONF.path, dirMap);
        this.makeNav(dirMap);
    },

    /**
     * 获取文件目录树
     *
     * @param {String} 文件起始路径
     * @param {Object} 文件目录树容器
     * */
    walker: function (dirs, dirCtt) {
        var me = this;
        var dirArr = fs.readdirSync(dirs);
        dirArr = dirArr || [];
        dirArr.forEach(function(it) {
            var childPath = path.join(dirs, it);
            var stat = fs.statSync(childPath);
            var relPath = childPath.replace(CONF.path, '');
            // 如果是文件夹就递归查找
            if (stat.isDirectory()) {
                // 如果是配置中忽略的目录,则跳过
                if (ignorDor.indexOf(it) === -1) {
                    var dirName = CONF.dirname[it] || {};
                    // 如果没有配置文件夹目录名称,则不显示
                    dirCtt[it] = {
                        type: 'dir',
                        path: relPath,
                        displayName: dirName.name || it ||''
                    };
                    dirCtt[it]['child'] = {};
                    me.walker(childPath, dirCtt[it]['child']);
                }
            }
            // 如果是文件
            else {
                //if (path.extname(it) === '.html') {
                if (/^\.md$/i.test(path.extname(it))) {
                    var basename = path.basename(it, '.md');
                    var title = me.getMdTitle(childPath);
                    dirCtt[basename] = {
                        type: 'md',
                        path: relPath,
                        title: title
                    };
                }
            }
        });
    },

    /**
     * 根据文件目录数据组装文件html
     *
     * @param {Array} dirs 文件目录数组
     * */
    makeNav: function (dirs) {
        if (!dirs) {
            return false;
        }
        for(var i in dirs) {
            var item = dirs[i] || {};
            if (item.type === 'md') {
                htmlStr += '
' + item.title + '
';
            }
            else if (item.type === 'dir') {
                htmlStr += '
' + item.displayName + '
';
                this.makeNav(item.child);
                htmlStr += '

';
            }
        }
    },

    /**
     * 获取markdown文件大标题
     *
     * @param {String} markdown文件的路径
     * @return {String} markdown文件大标题
     * */
    getMdTitle: function(dir) {
        if (dir) {
            dir = decodeURIComponent(dir);
            var content = fs.readFileSync(dir);
            var titleArr =  /^\s*\#+\s?(.+)/.exec(content.toString()) || [];
            return titleArr[1] || '';
        }
        return '';
    }
};

/**
 * 初始化docx
 * */
new Docx();<commit_msg>update render path for async<commit_after>/**
 * @file docx.js
 * @author schoeu
 * */

var path = require('path');
var fs = require('fs');
var url = require('url');
var express = require('express');
var bodyParser = require('body-parser');
var marked = require('marked');
var highlight = require('highlight.js');
var glob = require('glob');
var serve_static = require('serve-static');
var exphbs  = require('express-handlebars');

var CONF = require('../docx-conf.json');
var warning = require('./warning.js');
var update = require('./update.js');

var app = express();
var ignorDor = CONF.ignoreDir || [];

var dirMap = {};
var htmlStr = '';
var headText = CONF.headText || '';
var headParts = headText.split('-') || [];
var locals = {
    headMain: headParts[0] || '',
    headSub: headParts[1] || '',
    title: CONF.title || headText,
    links: CONF.extUrls.links || [],
    surposEmail: CONF.surposEmail || '',
    label: CONF.extUrls.label
};

function Docx() {
    this.init();
}

var htmlCodes = [
    '
',
    '
',
    '
' + headText + '
',
    '                {{brandData}}',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '                        {{mdData}}',
    '
',
    '
',
    '
',
    '
',
    '
'
].join('');

Docx.prototype = {
    contributor: Docx,

    /**
     * 初始化DOCX,主要初始化了express
     * */
    init: function () {
        var me = this;
        // express 视图设置
        if (!CONF.debug) {
            app.enable('view cache');
        }
        app.set('views', path.join(__dirname, '..', 'views'));
        app.engine('.hbs', exphbs({extname: '.hbs'}));
        app.set('view engine', '.hbs');
        app.use(express.static(path.join(__dirname, '..', 'public')));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));

        // 根据文档获取文档结构树
        me.getDocTree();

        // 路由处理
        me.routes();

        // 容错处理
        app.use(function(err, req, res, next) {
            // 如果开启了错误邮件报警则发错邮件
            if (err && CONF.waringFlag) {
                warning.sendMail(err.toString());
            }
        });

        // 端口监听
        app.listen(CONF.port || 8910);
    },

    /**
     * 系统的路由定义
     * */
    routes: function () {
        var me = this;

        // 文档主路径
        app.get('/', function (req, res) {
            res.redirect(CONF.index);
        });

        // markdown文件路由
        app.get('/*.md', function (req, res) {
            var relativePath = url.parse(req.originalUrl);
            var pathName = relativePath.pathname || '';
            var mdPath = path.join(CONF.path, pathName);
            if (mdPath) {
                mdPath = decodeURIComponent(mdPath);
            }

            // var file = fs.readFileSync(mdPath);
            fs.readFile(mdPath, 'utf8', function (err, file) {
                // markdown转换成html
                var content = me.getMarked(file.toString());

                // 判断是pjax请求则返回html片段
                if (req.headers['x-pjax'] === 'true') {
                    var rsPjaxDom = me.getPjaxContent(pathName, content);
                    res.end(rsPjaxDom);
                }

                // 否则返回整个模板
                else {
                    var parseObj = Object.assign({}, locals, {navData: htmlStr, mdData: content});
                    res.render('main', parseObj);
                }
            });
        });

        // API: 搜索功能
        app.post('/api/search', function (req, res) {
            var searchRs = [];
            var key = req.body.name;
            var filePath = path.join(CONF.path, '**/*.md');
            var files = glob.sync(filePath) || [];
            files.forEach(function (it) {
                if (it) {
                    it = decodeURIComponent(it);
                }
                // 判断文件是否存在
                // var file = fs.readFileSync(it);
                // var fileContent = file.toString();
                var fileTitle = me.getMdTitle(it) || '';
                var reg = new RegExp(key,'ig');
                if (reg.test(fileTitle)) {
                    searchRs.push({
                        path: it.replace(CONF.path, ''),
                        title: fileTitle
                    });
                }
            });
            res.json({
                error: 0,
                data: searchRs
            });
        });

        // API: 文档更新钩子
        app.get('/api/update', function (req, res, next) {
            var status = update(req, res, next);
            res.json({
                errorno: 0,
                files: files
            });
        });

        // 委托其他静态资源
        app.use('/', serve_static(CONF.path));
    },

    /**
     * 处理&组装面包屑数据
     * @param {String} pathName 文件路径
     * @return {String} 转换为中文的HTML字符串
     * */
    getPjaxContent: function (pathName, content) {
        var me = this;
        var brandStr = '';
        var pathArr = pathName.split('/');
        var brandData = me.processBreadcrumb(pathArr);
        brandData.forEach(function (it) {
            brandStr += '
' + it + '
';
        });
        var rsHTML = htmlCodes.replace('{{brandData}}', brandStr).replace('{{mdData}}', content);
        return rsHTML;
    },

    /**
     * 处理&组装面包屑数据
     * @param {Array} breadcrumb 面包屑原始数据
     * @return {Array} 转换为中文的数据
     * */
    processBreadcrumb: function(breadcrumb) {
        breadcrumb = breadcrumb || [];
        var dirMap = [];
        breadcrumb.forEach(function (it) {
            if (it) {
                if (it.indexOf('.md') > -1) {
                }
                else {
                    var nameMap = CONF.dirname[it] || {};
                    dirMap.push(nameMap.name || '');
                }
            }
        });
        return dirMap;
    },

    /**
     * markdown文件转html处理
     *
     * @param {String} content markdown字符串
     * @return {String} html字符串
     * */
    getMarked: function (content) {
        var renderer = new marked.Renderer();

        // markdown中渲染代码处理
        renderer.code = function (data, lang) {
            data = highlight.highlightAuto(data).value;
            if (lang) {
                // 超过3行有提示
                if (data.split(/\n/).length >= 3) {
                    var html = '
' + lang + '';
                    return html + data + '
';
                }
                return '
' + data + '
';
            }
            return '
' + data + '
';
        };

        return marked(content, {renderer});
    },

    /**
     * 获取文件目录树
     * */
    getDocTree: function () {
        this.walker(CONF.path, dirMap);
        this.makeNav(dirMap);
    },

    /**
     * 获取文件目录树
     *
     * @param {String} 文件起始路径
     * @param {Object} 文件目录树容器
     * */
    walker: function (dirs, dirCtt) {
        var me = this;
        var dirArr = fs.readdirSync(dirs);
        dirArr = dirArr || [];
        dirArr.forEach(function(it) {
            var childPath = path.join(dirs, it);
            var stat = fs.statSync(childPath);
            var relPath = childPath.replace(CONF.path, '');
            // 如果是文件夹就递归查找
            if (stat.isDirectory()) {
                // 如果是配置中忽略的目录,则跳过
                if (ignorDor.indexOf(it) === -1) {
                    var dirName = CONF.dirname[it] || {};
                    // 如果没有配置文件夹目录名称,则不显示
                    dirCtt[it] = {
                        type: 'dir',
                        path: relPath,
                        displayName: dirName.name || it ||''
                    };
                    dirCtt[it]['child'] = {};
                    me.walker(childPath, dirCtt[it]['child']);
                }
            }
            // 如果是文件
            else {
                //if (path.extname(it) === '.html') {
                if (/^\.md$/i.test(path.extname(it))) {
                    var basename = path.basename(it, '.md');
                    var title = me.getMdTitle(childPath);
                    dirCtt[basename] = {
                        type: 'md',
                        path: relPath,
                        title: title
                    };
                }
            }
        });
    },

    /**
     * 根据文件目录数据组装文件html
     *
     * @param {Array} dirs 文件目录数组
     * */
    makeNav: function (dirs) {
        if (!dirs) {
            return false;
        }
        for(var i in dirs) {
            var item = dirs[i] || {};
            if (item.type === 'md') {
                htmlStr += '
' + item.title + '
';
            }
            else if (item.type === 'dir') {
                htmlStr += '
' + item.displayName + '
';
                this.makeNav(item.child);
                htmlStr += '

';
            }
        }
    },

    /**
     * 获取markdown文件大标题
     *
     * @param {String} markdown文件的路径
     * @return {String} markdown文件大标题
     * */
    getMdTitle: function(dir) {
        if (dir) {
            dir = decodeURIComponent(dir);
            var content = fs.readFileSync(dir);
            var titleArr =  /^\s*\#+\s?(.+)/.exec(content.toString()) || [];
            return titleArr[1] || '';
        }
        return '';
    }
};

/**
 * 初始化docx
 * */
new Docx();<|endoftext|>


<commit_before>import {dispatch} from "d3-dispatch";
import {event, customEvent, select, mouse, touch} from "d3-selection";
import nodrag, {yesdrag} from "./nodrag";
import noevent, {nopropagation} from "./noevent";
import constant from "./constant";
import DragEvent from "./event";

// Ignore right-click, since that should open the context menu.
function defaultFilter() {
  return !event.button;
}

function defaultContainer() {
  return this.parentNode;
}

function defaultSubject(d) {
  return d == null ? {x: event.x, y: event.y} : d;
}

export default function() {
  var filter = defaultFilter,
      container = defaultContainer,
      subject = defaultSubject,
      gestures = {},
      listeners = dispatch("start", "drag", "end"),
      active = 0,
      mousemoving,
      touchending;

  function drag(selection) {
    selection
        .on("mousedown.drag", mousedowned)
        .on("touchstart.drag", touchstarted)
        .on("touchmove.drag", touchmoved)
        .on("touchend.drag touchcancel.drag", touchended)
        .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }

  function mousedowned() {
    if (touchending || !filter.apply(this, arguments)) return;
    var gesture = beforestart("mouse", container.apply(this, arguments), mouse, this, arguments);
    if (!gesture) return;
    select(event.view).on("mousemove.drag", mousemoved, true).on("mouseup.drag", mouseupped, true);
    nodrag(event.view);
    nopropagation();
    mousemoving = false;
    gesture("start");
  }

  function mousemoved() {
    noevent();
    mousemoving = true;
    gestures.mouse("drag");
  }

  function mouseupped() {
    select(event.view).on("mousemove.drag mouseup.drag", null);
    yesdrag(event.view, mousemoving);
    noevent();
    gestures.mouse("end");
  }

  function touchstarted() {
    if (!filter.apply(this, arguments)) return;
    var touches = event.changedTouches,
        c = container.apply(this, arguments),
        n = touches.length, i, gesture;

    nopropagation();
    for (i = 0; i < n; ++i) {
      if (gesture = beforestart(touches[i].identifier, c, touch, this, arguments)) {
        gesture("start");
      }
    }
  }

  function touchmoved() {
    var touches = event.changedTouches,
        n = touches.length, i, gesture;

    noevent();
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        gesture("drag");
      }
    }
  }

  function touchended() {
    var touches = event.changedTouches,
        n = touches.length, i, gesture;

    nopropagation();
    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        gesture("end");
      }
    }
  }

  function beforestart(id, container, point, that, args) {
    var p = point(container, id), s, dx, dy,
        sublisteners = listeners.copy();

    if (!customEvent(new DragEvent(drag, "beforestart", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {
      if ((event.subject = s = subject.apply(that, args)) == null) return false;
      dx = s.x - p[0] || 0;
      dy = s.y - p[1] || 0;
      return true;
    })) return;

    return function gesture(type) {
      var p0 = p, n;
      switch (type) {
        case "start": gestures[id] = gesture, n = active++; break;
        case "end": delete gestures[id], --active; // nobreak
        case "drag": p = point(container, id), n = active; break;
      }
      customEvent(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);
    };
  }

  drag.filter = function(_) {
    return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), drag) : filter;
  };

  drag.container = function(_) {
    return arguments.length ? (container = typeof _ === "function" ? _ : constant(_), drag) : container;
  };

  drag.subject = function(_) {
    return arguments.length ? (subject = typeof _ === "function" ? _ : constant(_), drag) : subject;
  };

  drag.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? drag : value;
  };

  return drag;
}
<commit_msg>Only consume handled touch events.<commit_after>import {dispatch} from "d3-dispatch";
import {event, customEvent, select, mouse, touch} from "d3-selection";
import nodrag, {yesdrag} from "./nodrag";
import noevent, {nopropagation} from "./noevent";
import constant from "./constant";
import DragEvent from "./event";

// Ignore right-click, since that should open the context menu.
function defaultFilter() {
  return !event.button;
}

function defaultContainer() {
  return this.parentNode;
}

function defaultSubject(d) {
  return d == null ? {x: event.x, y: event.y} : d;
}

export default function() {
  var filter = defaultFilter,
      container = defaultContainer,
      subject = defaultSubject,
      gestures = {},
      listeners = dispatch("start", "drag", "end"),
      active = 0,
      mousemoving,
      touchending;

  function drag(selection) {
    selection
        .on("mousedown.drag", mousedowned)
        .on("touchstart.drag", touchstarted)
        .on("touchmove.drag", touchmoved)
        .on("touchend.drag touchcancel.drag", touchended)
        .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }

  function mousedowned() {
    if (touchending || !filter.apply(this, arguments)) return;
    var gesture = beforestart("mouse", container.apply(this, arguments), mouse, this, arguments);
    if (!gesture) return;
    select(event.view).on("mousemove.drag", mousemoved, true).on("mouseup.drag", mouseupped, true);
    nodrag(event.view);
    nopropagation();
    mousemoving = false;
    gesture("start");
  }

  function mousemoved() {
    noevent();
    mousemoving = true;
    gestures.mouse("drag");
  }

  function mouseupped() {
    select(event.view).on("mousemove.drag mouseup.drag", null);
    yesdrag(event.view, mousemoving);
    noevent();
    gestures.mouse("end");
  }

  function touchstarted() {
    if (!filter.apply(this, arguments)) return;
    var touches = event.changedTouches,
        c = container.apply(this, arguments),
        n = touches.length, i, gesture;

    for (i = 0; i < n; ++i) {
      if (gesture = beforestart(touches[i].identifier, c, touch, this, arguments)) {
        nopropagation();
        gesture("start");
      }
    }
  }

  function touchmoved() {
    var touches = event.changedTouches,
        n = touches.length, i, gesture;

    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        noevent();
        gesture("drag");
      }
    }
  }

  function touchended() {
    var touches = event.changedTouches,
        n = touches.length, i, gesture;

    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        nopropagation();
        gesture("end");
      }
    }
  }

  function beforestart(id, container, point, that, args) {
    var p = point(container, id), s, dx, dy,
        sublisteners = listeners.copy();

    if (!customEvent(new DragEvent(drag, "beforestart", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {
      if ((event.subject = s = subject.apply(that, args)) == null) return false;
      dx = s.x - p[0] || 0;
      dy = s.y - p[1] || 0;
      return true;
    })) return;

    return function gesture(type) {
      var p0 = p, n;
      switch (type) {
        case "start": gestures[id] = gesture, n = active++; break;
        case "end": delete gestures[id], --active; // nobreak
        case "drag": p = point(container, id), n = active; break;
      }
      customEvent(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);
    };
  }

  drag.filter = function(_) {
    return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), drag) : filter;
  };

  drag.container = function(_) {
    return arguments.length ? (container = typeof _ === "function" ? _ : constant(_), drag) : container;
  };

  drag.subject = function(_) {
    return arguments.length ? (subject = typeof _ === "function" ? _ : constant(_), drag) : subject;
  };

  drag.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? drag : value;
  };

  return drag;
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Iterates of an iterable object and call the given method for each item
 * For example:
 *

 *      // (a) default use case iterate through an array or an object
 *      each([1, 2, ..., n], function doStuff(val) { ... });
 *
 *      // (b) map data
 *      each([1, 2, 3], function double(val) {
 *          return 2 * val;
 *      }); // -> [2, 4, 6]
 *      each({foo: 1, bar: 2}, function double(val) {
 *          return 2 * val;
 *      }); // -> {foo: 2, bar: 4}
 *
 *      // (c) filter data
 *      each([1, 2, 3, 4], function (val) {
 *          return (val % 2 === 0) ? val : undefined;
 *      }); // -> [2, 4]
 *      each({ foo: 1, bar: 2, baz: 3, }, function uneven(val) {
 *          return (val % 2 !== 0) ? val : undefined;
 *      }); // -> { foo: 1, baz: 3 }
 *

 *
 * @param {Object/Array} iterable The object to iterate through
 * @param {Function} fn The callback function to be called for each item
 * @param {Object} scope The execution scope for the callback function
 * @param {Array} more Optional; an addional set of arguments which will
 *      be passed to the callback function
 * @return {Object/Array} The aggregated results of each callback (see examples)
 */
 function each(iterable, fn, scope, more) {
    var args = [null, null];
    var result, resultSet;
    var i, l;

    if (more !== undefined) {
        args = args.concat(more);
    }

    if (Array.isArray(iterable)) {
        resultSet = [];

        for (i = 0, l = iterable.length; i < l; ++i) {
            args[0] = iterable[i];
            args[1] = i;
            result = fn.apply(scope, args);

            if (typeof result !== 'undefined') {
                resultSet.push(result);
            }
        }

    } else if (iterable && typeof iterable === 'object') {
        var keys = Object.keys(iterable);
        // use Object.keys + for-loop to allow optimizing each for
        // iterating over objects in hash-table-mode

        resultSet = {};

        for (i = 0, l = keys.length; i < l; ++i) {
            var key = keys[i];

            args[0] = iterable[key];
            args[1] = key;
            result = fn.apply(scope, args);

            if (typeof result !== 'undefined') {
                resultSet[key] = result;
            }
        }
    }

    return resultSet;
}

/**
 * Creates a function which is bound to a given callback and scope
 *
 * @param {Function} fn The callback (same as for each itself)
 * @param {Object} scope The execution context for the callback
 * @return Function The new iterator function which expects the
 *      iterable and an array of additional parameter which are
 *      passed to the callback
 */
each.prepare = function (fn, scope) {
    return function (iterable, more) {
        return each(iterable, fn, scope, more);
    };
};

module.exports = each;
<commit_msg>add closure to avoid side effects<commit_after>module.exports = function () {
    'use strict';

    /**
     * Iterates of an iterable object and call the given method for each item
     * For example:
     *

     *      // (a) default use case iterate through an array or an object
     *      each([1, 2, ..., n], function doStuff(val) { ... });
     *
     *      // (b) map data
     *      each([1, 2, 3], function double(val) {
     *          return 2 * val;
     *      }); // -> [2, 4, 6]
     *      each({foo: 1, bar: 2}, function double(val) {
     *          return 2 * val;
     *      }); // -> {foo: 2, bar: 4}
     *
     *      // (c) filter data
     *      each([1, 2, 3, 4], function (val) {
     *          return (val % 2 === 0) ? val : undefined;
     *      }); // -> [2, 4]
     *      each({ foo: 1, bar: 2, baz: 3, }, function uneven(val) {
     *          return (val % 2 !== 0) ? val : undefined;
     *      }); // -> { foo: 1, baz: 3 }
     *

     *
     * @param {Object/Array} iterable The object to iterate through
     * @param {Function} fn The callback function to be called for each item
     * @param {Object} scope The execution scope for the callback function
     * @param {Array} more Optional; an addional set of arguments which will
     *      be passed to the callback function
     * @return {Object/Array} The aggregated results of each callback (see examples)
     */
    function each(iterable, fn, scope, more) {
        var args = [null, null];
        var result, resultSet;
        var i, l;

        if (more !== undefined) {
            args = args.concat(more);
        }

        if (Array.isArray(iterable)) {
            resultSet = [];

            for (i = 0, l = iterable.length; i < l; ++i) {
                args[0] = iterable[i];
                args[1] = i;
                result = fn.apply(scope, args);

                if (typeof result !== 'undefined') {
                    resultSet.push(result);
                }
            }

        } else if (iterable && typeof iterable === 'object') {
            var keys = Object.keys(iterable);
            // use Object.keys + for-loop to allow optimizing each for
            // iterating over objects in hash-table-mode

            resultSet = {};

            for (i = 0, l = keys.length; i < l; ++i) {
                var key = keys[i];

                args[0] = iterable[key];
                args[1] = key;
                result = fn.apply(scope, args);

                if (typeof result !== 'undefined') {
                    resultSet[key] = result;
                }
            }
        }

        return resultSet;
    }

    /**
     * Creates a function which is bound to a given callback and scope
     *
     * @param {Function} fn The callback (same as for each itself)
     * @param {Object} scope The execution context for the callback
     * @return Function The new iterator function which expects the
     *      iterable and an array of additional parameter which are
     *      passed to the callback
     */
    each.prepare = function (fn, scope) {
        return function (iterable, more) {
            return each(iterable, fn, scope, more);
        };
    };

    return each;
}();
<|endoftext|>


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

/**
 * Created by neil on 01/08/2014.
 */
var frisby = require('frisby');
var querystring = require('querystring');

var key = 'free';
var baseURL = 'http://ocalhost:8080/api/0.1/render/render';
var urls = ["http://time.is/", "example.com", "https://google.com"];
//var url= ["www.ultrasounds.com","www.nasa.gov", "mashable.com", "http://news.bbc.co.uk"];
//var url= ["http://www.webthrower.com/portfolio/narnia.htm"];       // flash site
var sizes = ["sc", "tc", "full", "lc", "mc", "sc", "100x200"]
var freshness = [0, "recent", "cached", "day", 300];
//var freshness = [0, "recent", "cached", "day", 300];
var imageTypes = ["png", "jpeg"];
var delays = ["0", "2"];
var screens = ["desktop", "600x200", "iphone"];
var qualities = ["low", "medium", "high"];

frisby.globalSetup({
    timeout: (60 * 1000)

});

function buildImageURL(params) {
    return  baseURL + '?' + querystring.stringify(params);
}

frisby.create('Basic Image Test')
    .get(buildImageURL({url: "http://google.com", width: 200}))
    .expectStatus(200)
    .expectHeaderContains('Content-Type', 'png')
    .toss();

for (var i = 0; i < urls.length; i++) {
    frisby.create('URL: ' + urls[i])
        .get(buildImageURL({url: urls[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', 'png')
        .toss();

}

for (var i = 0; i < sizes.length; i++) {
    frisby.create('Size: ' + sizes[i])
        .get(buildImageURL({url: "http://google.com", size: sizes[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', 'png')
        .toss();

}

for (var i = 0; i < screens.length; i++) {
    frisby.create('Screen: ' + screens[i])
        .get(buildImageURL({url: "http://google.com", screen: screens[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', 'png')
        .toss();

}

for (var i = 0; i < qualities.length; i++) {
    frisby.create('Quality: ' + qualities[i])
        .get(buildImageURL({url: "http://google.com", quality: qualities[i]}))
        .expectStatus(200)
        .toss();

}

frisby.create('Low Quality')
    .get(buildImageURL({url: "http://google.com", quality: "low"}))
    .expectStatus(200)
    .expectHeaderContains('Content-Type', 'jpeg')
    .toss();

frisby.create('Medium Quality')
    .get(buildImageURL({url: "http://google.com", quality: "medium"}))
    .expectStatus(200)
    .expectHeaderContains('Content-Type', 'jpeg')
    .toss();

frisby.create('High Quality')
    .get(buildImageURL({url: "http://google.com", quality: "high"}))
    .expectStatus(200)
    .expectHeaderContains('Content-Type', 'png')
    .toss();

for (var i = 0; i < freshness.length; i++) {
    frisby.create('Freshness: ' + freshness[i])
        .get(buildImageURL({url: "http://google.com", freshness: freshness[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', 'png')
        .toss();

}

for (var i = 0; i < imageTypes.length; i++) {
    frisby.create('Type: ' + imageTypes[i])
        .get(buildImageURL({url: "http://google.com", type: imageTypes[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', imageTypes[i])
        .toss();

}

for (var i = 0; i < delays.length; i++) {
    frisby.create('Delay: ' + delays[i])
        .get(buildImageURL({url: "http://google.com", delay: delays[i]}))
        .expectStatus(200)
        .expectHeaderContains('Content-Type', 'png')
        .toss();

}

<commit_msg>Delete image_spec.js<commit_after><|endoftext|>


<commit_before>var exported = {
  noflo: require('../../src/lib/NoFlo.coffee')
};

if (window) {
  window.require = function (moduleName) {
    if (exported[moduleName]) {
      return exported[moduleName];
    }
    throw new Error('Module ' + moduleName + ' not available');
  };
}

<commit_msg>Include only the compiled NoFlo version<commit_after>var exported = {
  noflo: require('../../lib/NoFlo')
};

if (window) {
  window.require = function (moduleName) {
    if (exported[moduleName]) {
      return exported[moduleName];
    }
    throw new Error('Module ' + moduleName + ' not available');
  };
}

<|endoftext|>


<commit_before>'use strict'
var Promise = require('./promise')
var asArray = require('./util').asArray
var INTERNAL = require('./util').INTERNAL

// In these implementations, all values from the iterable are plucked before a
// single callback is invoked. Modifying the input array after the handler has
// returned will have no effect on the items that are processed, or the result
// array. The result array is always a safe, clean, base array.

// No items are processed synchronously.

// Each item is processed as soon as it becomes available (in order of promise
// resolution). The index passed to the callback functions are the item's
// position in the input array, NOT their index in the order of processing.
// Of course, in reduce and reduceRight, the execution is ordered.

// All indexes are processed, even deleted or non-existent values of an array.

Promise.prototype.filter = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		return mapArray(array, fn, ctx)._then(function (bools) {
			var result = []
			for (var i=0, len=bools.length; i<len; i++) {
				bools[i] && result.push(array[i])
			}
			return result
		})
	})
}
Promise.prototype.map = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		return mapArray(asArray(iterable), fn, ctx)
	})
}
Promise.prototype.forEach = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		return mapArray(array, fn, ctx)._then(function () {
			return array
		})
	})
}
Promise.prototype.reduce = function (fn, seed) {
	var useSeed = arguments.length > 1
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		if (useSeed) {
			array.unshift(seed)
		} else if (array.length === 0) {
			throw new Error('Cannot reduce an empty iterable with no initial value.')
		}
		var result
		var firstItem = true
		var len = array.length
		var i = useSeed ? 0 : 1
		var setResult = function (value) {result = value}
		return Promise.iterate(array, function (item) {
			if (firstItem) {
				firstItem = false
				result = item
				return
			}
			return Promise.resolve(fn(result, item, i++, len))._then(setResult)
		})._then(function () {return result})
	})
}

function mapArray(input, fn, ctx) {
	return new Promise(function (res, rej) {
		var pendings = input.length
		var result = new Array(pendings)
		if (pendings === 0) {
			return res(result)
		}
		var each = function (i) {
			return function (value) {
				return Promise.resolve(fn.call(ctx, value, i, len))._then(function (value) {
					result[i] = value
					if (--pendings === 0) {res(result)}
				})
			}
		}
		for (var i=0, len=pendings; i<len; i++) {
			Promise.resolve(input[i])._then(each(i))._then(null, rej)
		}
	})
}

function asArrayCopy(iterable) {
	var array = asArray(iterable)
	if (array === iterable) {
		var len = array.length
		var result = new Array(len)
		for (var i=0; i<len; i++) {result[i] = array[i]}
		return result
	}
	return array
}
<commit_msg>comments<commit_after>'use strict'
var Promise = require('./promise')
var asArray = require('./util').asArray
var INTERNAL = require('./util').INTERNAL

// In these implementations, all values from the iterable are plucked before a
// single callback is invoked. Modifying the input array after the handler has
// returned will have no effect on the items that are processed, or the result
// array. The result array is always a safe, clean, base array.

// No items are processed synchronously.

// Each item is processed as soon as it becomes available (in order of promise
// resolution). The index passed to the callback functions are the item's
// position in the input array, NOT their index in the order of processing.
// Of course, in .reduce(), the execution is ordered.

// All indexes are processed, even deleted or non-existent values of an array.

Promise.prototype.filter = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		return mapArray(array, fn, ctx)._then(function (bools) {
			var result = []
			for (var i=0, len=bools.length; i<len; i++) {
				bools[i] && result.push(array[i])
			}
			return result
		})
	})
}
Promise.prototype.map = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		return mapArray(asArray(iterable), fn, ctx)
	})
}
Promise.prototype.forEach = function (fn, ctx) {
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		return mapArray(array, fn, ctx)._then(function () {
			return array
		})
	})
}
Promise.prototype.reduce = function (fn, seed) {
	var useSeed = arguments.length > 1
	return this._then(function (iterable) {
		if (typeof fn !== 'function') {
			throw new TypeError('Expected first argument to be a function.')
		}
		var array = asArrayCopy(iterable)
		if (useSeed) {
			array.unshift(seed)
		} else if (array.length === 0) {
			throw new Error('Cannot reduce an empty iterable with no initial value.')
		}
		var result
		var firstItem = true
		var len = array.length
		var i = useSeed ? 0 : 1
		var setResult = function (value) {result = value}
		return Promise.iterate(array, function (item) {
			if (firstItem) {
				firstItem = false
				result = item
				return
			}
			return Promise.resolve(fn(result, item, i++, len))._then(setResult)
		})._then(function () {return result})
	})
}

function mapArray(input, fn, ctx) {
	return new Promise(function (res, rej) {
		var pendings = input.length
		var result = new Array(pendings)
		if (pendings === 0) {
			return res(result)
		}
		var each = function (i) {
			return function (value) {
				return Promise.resolve(fn.call(ctx, value, i, len))._then(function (value) {
					result[i] = value
					if (--pendings === 0) {res(result)}
				})
			}
		}
		for (var i=0, len=pendings; i<len; i++) {
			Promise.resolve(input[i])._then(each(i))._then(null, rej)
		}
	})
}

function asArrayCopy(iterable) {
	var array = asArray(iterable)
	if (array === iterable) {
		var len = array.length
		var result = new Array(len)
		for (var i=0; i<len; i++) {result[i] = array[i]}
		return result
	}
	return array
}
<|endoftext|>


<commit_before>import {actionBuilder} from '../../actions/entity-actions-builder';
import {loadUserSvc, saveUserSvc} from '../services/user-service';

const loadAction = actionBuilder({names: ['user'], type: 'load', service: loadUserSvc});
export const loadUserTypes = loadAction.types;
export const loadUserAction = loadAction.action;

const saveAction = actionBuilder({names: ['user'], type: 'save', service: saveUserSvc});
export const saveUserTypes = saveAction.types;
export const saveUserAction = saveAction.action;
<commit_msg>[example] Create an action with address and user loaded.<commit_after>import {actionBuilder} from '../../actions/entity-actions-builder';
import {loadUserSvc, saveUserSvc, loadMixedEntities} from '../services/user-service';

const loadAction = actionBuilder({names: ['user'], type: 'load', service: loadUserSvc});
export const loadUserTypes = loadAction.types;
export const loadUserAction = loadAction.action;

const _loadMixedAction = actionBuilder({names: ['user', 'address'], type: 'load', service: loadMixedEntities});
export const loadMixedTypes = _loadMixedAction.types;
export const loadMixedAction = _loadMixedAction.action;

const saveAction = actionBuilder({names: ['user'], type: 'save', service: saveUserSvc});
export const saveUserTypes = saveAction.types;
export const saveUserAction = saveAction.action;
<|endoftext|>


<commit_before>'use strict';

var app = angular.module("app",['ui.ace']);

app.controller("mainController", ["$scope",  function($scope) {

        $scope.headerTitle = "Direct manipulation interfaces as a transition to textual programming";

        $scope.infoEntry = [
            {"name" : "about"},
            {"name" : "help"}
        ];

        $scope.navigationEntry = [
            {"name" : "file"},
            {"name" : "tasks"}
        ];

        $scope.menuEntry = [
            {"name" : "rnorm", "id" : "rnorm"},
            {"name" : "mean", "id" : "mean"},
            {"name" : "standard deviation" , "id" : "sd"}

        ];

		$scope.aceOptions = {
			theme : 'solarized_dark',
			mode : 'r',
			useWrapMode : 'true'
		};

		$scope.example = "Example Works!";

        $scope.makecode = function(funct){
            switch(funct){
                case "rnorm":
                    $scope.code = "rnorm was selected";
                    break;
                case "qnorm":
                    $scope.code = "qnorm was selected";
                    break;
                case "pnorm":
                    $scope.code = "pnorm was selected";
                    break;
                default:
                    $scope.code = "function unknown";
            }
        }

        $scope.rnorm = function(){

            ocpu.seturl("https://public.opencpu.org/ocpu/library/stats/R");

            ocpu.call("rnorm", {n:100}, function(session){
                session.getObject(function(data){
                    //alert("First few values:" + data.slice(0,3));
                    $("#output").text(data.slice(0,3));
                });
            });
        }

        $scope.runcode = function(){

            //because identity is in base
            ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R");

            // access editor
            var editor = ace.edit("aceEditor");
            var code = editor.getSession().getValue();

            //arguments
            var mysnippet = new ocpu.Snippet(code);

            //alert("Snippet: " + mysnippet);

            //disable button
            $("runbutton").attr("disabled", "disabled");

            //perform the request
            var req = ocpu.call("identity", {
                "x" : mysnippet
            }, function(session){
                session.getConsole(function(outtxt){
                    $("#workspace").text(outtxt);
                });
            });

            //if R returns an error, alert the error message
            req.fail(function(){
                alert("Server error: " + req.responseText);
            });

        }

        $scope.readcsv = function(){

            //because read.csv is in utils
            ocpu.seturl("https://public.opencpu.org/ocpu/library/utils/R");
            var myfile = $("#csvfile")[0].files[0];

            if(!myfile){
                alert("No file selected.");
            return;
            }

            //disable the button during upload
            $("#readfile").attr("disabled", "disabled");

            //perform the request
            var req = ocpu.call("read.csv", {
                "file" : myfile,
                "header" : false,
                "sep" : " "
            }, function(session){
                session.getConsole(function(outtxt){
                $("#workspace").text(outtxt);
                });
            });
        }

}]);

/*
app.controller("controller2",["$scope", function($scope){

	$scope.functions = [
		{ 'name' : 'rnorm' , 'description' : 'description of rnorm'},
		{ 'name' : 'qnorm' , 'description' : 'description of qnorm'},
		{ 'name' : 'pnorm' , 'description' : 'description of pnorm'}
	];

	$scope.test = "Controller 2 works!"

    ;
}]);
*/<commit_msg>csvread<commit_after>'use strict';

var app = angular.module("app",['ui.ace']);

app.controller("mainController", ["$scope",  function($scope) {

        $scope.headerTitle = "Direct manipulation interfaces as a transition to textual programming";

        $scope.infoEntry = [
            {"name" : "about"},
            {"name" : "help"}
        ];

        $scope.navigationEntry = [
            {"name" : "file"},
            {"name" : "tasks"}
        ];

        $scope.menuEntry = [
            {"name" : "rnorm", "id" : "rnorm"},
            {"name" : "mean", "id" : "mean"},
            {"name" : "standard deviation" , "id" : "sd"}

        ];

		$scope.aceOptions = {
			theme : 'solarized_dark',
			mode : 'r',
			useWrapMode : 'true'
		};

		$scope.example = "Example Works!";

        $scope.makecode = function(funct){
            switch(funct){
                case "rnorm":
                    $scope.code = "rnorm was selected";
                    break;
                case "qnorm":
                    $scope.code = "qnorm was selected";
                    break;
                case "pnorm":
                    $scope.code = "pnorm was selected";
                    break;
                default:
                    $scope.code = "function unknown";
            }
        }

        $scope.rnorm = function(){

            ocpu.seturl("https://public.opencpu.org/ocpu/library/stats/R");

            ocpu.call("rnorm", {n:100}, function(session){
                session.getObject(function(data){
                    //alert("First few values:" + data.slice(0,3));
                    $("#output").text(data.slice(0,3));
                });
            });
        }

        $scope.runcode = function(){

            //because identity is in base
            ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R");

            // access editor
            var editor = ace.edit("aceEditor");
            var code = editor.getSession().getValue();

            //arguments
            var mysnippet = new ocpu.Snippet(code);

            //disable button
            $("runbutton").attr("disabled", "disabled");

            //perform the request
            var req = ocpu.call("identity", {
                "x" : mysnippet
            }, function(session){
                session.getConsole(function(outtxt){
                    alert(typeof outtxt);
                    //$("#workspace").text(outtxt);
                });
            });

            //if R returns an error, alert the error message
            req.fail(function(){
                alert("Server error: " + req.responseText);
            });

        }

        $scope.readcsv = function(){

            //because read.csv is in utils
            ocpu.seturl("https://public.opencpu.org/ocpu/library/utils/R");
            var myfile = $("#csvfile")[0].files[0];

            if(!myfile){
                alert("No file selected.");
            return;
            }

            //disable the button during upload
            $("#readfile").attr("disabled", "disabled");

            //perform the request
            var req = ocpu.call("read.csv", {
                "file" : myfile,
                "header" : false,
                "sep" : " "
            }, function(session){
                session.getConsole(function(outtxt){
                $("#workspace").text(outtxt);
                });
            });
        }

}]);

/*
app.controller("controller2",["$scope", function($scope){

	$scope.functions = [
		{ 'name' : 'rnorm' , 'description' : 'description of rnorm'},
		{ 'name' : 'qnorm' , 'description' : 'description of qnorm'},
		{ 'name' : 'pnorm' , 'description' : 'description of pnorm'}
	];

	$scope.test = "Controller 2 works!"

    ;
}]);
*/<|endoftext|>