<commit_before>dojo.provide("dojox.xml.parser");

//DOM type to int value for reference.
//Ints make for more compact code than full constant names.
//ELEMENT_NODE                  = 1;
//ATTRIBUTE_NODE                = 2;
//TEXT_NODE                     = 3;
//CDATA_SECTION_NODE            = 4;
//ENTITY_REFERENCE_NODE         = 5;
//ENTITY_NODE                   = 6;
//PROCESSING_INSTRUCTION_NODE   = 7;
//COMMENT_NODE                  = 8;
//DOCUMENT_NODE                 = 9;
//DOCUMENT_TYPE_NODE            = 10;
//DOCUMENT_FRAGMENT_NODE        = 11;
//NOTATION_NODE                 = 12;

dojox.xml.parser.parse = function(/*string?*/ str, /*string?*/ mimetype){
	//	summary:
	//		cross-browser implementation of creating an XML document object from null, empty string, and XML text..
	//
	//	str:
	//		Optional text to create the document from.  If not provided, an empty XML document will be created.
	//		If str is empty string "", then a new empty document will be created.
	//	mimetype:
	//		Optional mimetype of the text.  Typically, this is text/xml.  Will be defaulted to text/xml if not provided.
	var _document = dojo.doc;
	var doc;

	if(!mimetype){ mimetype = "text/xml"; }
	if(str && dojo.trim(str) !== "" && (typeof dojo.global["DOMParser"]) !== "undefined"){
		//Handle parsing the text on Mozilla based browsers etc..
		var parser = new DOMParser();
		doc = parser.parseFromString(str, mimetype);
		var de = doc.documentElement;
		var errorNS = "http://www.mozilla.org/newlayout/xml/parsererror.xml";
		if(de.nodeName == "parsererror" && de.namespaceURI == errorNS){
			var sourceText = de.getElementsByTagNameNS(errorNS, 'sourcetext')[0];
			if(!sourceText){
				sourceText = sourceText.firstChild.data;
			}
        	throw new Error("Error parsing text " + nativeDoc.documentElement.firstChild.data + " \n" + sourceText);
		}
		return doc;

	}else if((typeof dojo.global["ActiveXObject"]) !== "undefined"){
		//Handle IE.
		var ms = function(n){ return "MSXML" + n + ".DOMDocument"; };
		var dp = ["Microsoft.XMLDOM", ms(6), ms(4), ms(3), ms(2)];
		dojo.some(dp, function(p){
			try{
				doc = new ActiveXObject(p);
			}catch(e){ return false; }
			return true;
		});
		if(str){
			if(doc){
				doc.async = false;
				doc.loadXML(str);
				var pe = doc.parseError;
				if(pe.errorCode !== 0){
					throw new Error("Line: " + pe.line + "\n" +
						"Col: " + pe.linepos + "\n" +
						"Reason: " + pe.reason + "\n" +
						"Error Code: " + pe.errorCode + "\n" +
						"Source: " + pe.srcText);
				}
				return doc;	//	DOMDocument
			}
		}else{
			if(doc){
				return doc; //DOMDocument
			}
		}
	}else if((_document.implementation)&&
		(_document.implementation.createDocument)){
		if(str && dojo.trim(str) !== ""){
			if(_document.createElement){
				//Everyone else that we couldn't get to work.  Fallback case.
				// FIXME: this may change all tags to uppercase!
				var tmp = _document.createElement("xml");
				tmp.innerHTML = str;
				var xmlDoc = _document.implementation.createDocument("foo", "", null);
				for(var i = 0; i < tmp.childNodes.length; i++) {
					xmlDoc.importNode(tmp.childNodes.item(i), true);
				}
				return xmlDoc;	//	DOMDocument
			}
		}else{
			return _document.implementation.createDocument("", "", null); // DOMDocument
		}
	}
	return null;	//	DOMDocument
}

dojox.xml.parser.textContent = function(/*Node*/node, /*string?*/text){
	//	summary:
	//		Implementation of the DOM Level 3 attribute; scan node for text
	//	description:
	//		Implementation of the DOM Level 3 attribute; scan node for text
	//		This function can also update the text of a node by replacing all child
	//		content of the node.
	//	node:
	//		The node to get the text off of or set the text on.
	//	text:
	//		Optional argument of the text to apply to the node.
	if(arguments.length>1){
		var _document = node.ownerDocument || dojo.doc;  //Preference is to get the node owning doc first or it may fail
		dojox.xml.parser.replaceChildren(node, _document.createTextNode(text));
		return text;	//	string
	} else {
		if(node.textContent !== undefined){ //FF 1.5
			return node.textContent;	//	string
		}
		var _result = "";
		if(node == null){
			return _result; //empty string.
		}
		for(var i = 0; i < node.childNodes.length; i++){
			switch(node.childNodes[i].nodeType){
				case 1: // ELEMENT_NODE
				case 5: // ENTITY_REFERENCE_NODE
					_result += dojox.xml.parser.textContent(node.childNodes[i]);
					break;
				case 3: // TEXT_NODE
				case 2: // ATTRIBUTE_NODE
				case 4: // CDATA_SECTION_NODE
					_result += node.childNodes[i].nodeValue;
					break;
				default:
					break;
			}
		}
		return _result;	//	string
	}
}

dojox.xml.parser.replaceChildren = function(/*Element*/node, /*Node || array*/ newChildren){
	//	summary:
	//		Removes all children of node and appends newChild. All the existing
	//		children will be destroyed.
	//	description:
	//		Removes all children of node and appends newChild. All the existing
	//		children will be destroyed.
	// 	node:
	//		The node to modify the children on
	//	newChildren:
	//		The children to add to the node.  It can either be a single Node or an
	//		array of Nodes.
	var nodes = [];
	var i;

	if(dojo.isIE){
		for(i=0;i<node.childNodes.length;i++){
			nodes.push(node.childNodes[i]);
		}
	}

	dojox.xml.parser.removeChildren(node);
	for(i=0;i<nodes.length;i++){
		dojo._destroyElement(nodes[i]);
	}

	if(!dojo.isArray(newChildren)){
		node.appendChild(newChildren);
	}else{
		for(i=0;i<newChildren.length;i++){
			node.appendChild(newChildren[i]);
		}
	}
}

dojox.xml.parser.removeChildren = function(/*Element*/node){
	//	summary:
	//		removes all children from node and returns the count of children removed.
	//		The children nodes are not destroyed. Be sure to call dojo._destroyElement on them
	//		after they are not used anymore.
	//	node:
	//		The node to remove all the children from.
	var count = node.childNodes.length;
	while(node.hasChildNodes()){
		node.removeChild(node.firstChild);
	}
	return count; // int
}

dojox.xml.parser.innerXML = function(/*Node*/node){
	//	summary:
	//		Implementation of MS's innerXML function.
	//	node:
	//		The node from which to generate the XML text representation.
	if(node.innerXML){
		return node.innerXML;	//	string
	}else if (node.xml){
		return node.xml;		//	string
	}else if(typeof XMLSerializer != "undefined"){
		return (new XMLSerializer()).serializeToString(node);	//	string
	}
	return null;
}

<commit_msg>Style changes. Refs #8140<commit_after>dojo.provide("dojox.xml.parser");

//DOM type to int value for reference.
//Ints make for more compact code than full constant names.
//ELEMENT_NODE                  = 1;
//ATTRIBUTE_NODE                = 2;
//TEXT_NODE                     = 3;
//CDATA_SECTION_NODE            = 4;
//ENTITY_REFERENCE_NODE         = 5;
//ENTITY_NODE                   = 6;
//PROCESSING_INSTRUCTION_NODE   = 7;
//COMMENT_NODE                  = 8;
//DOCUMENT_NODE                 = 9;
//DOCUMENT_TYPE_NODE            = 10;
//DOCUMENT_FRAGMENT_NODE        = 11;
//NOTATION_NODE                 = 12;

dojox.xml.parser.parse = function(/*string?*/ str, /*string?*/ mimetype){
	//	summary:
	//		cross-browser implementation of creating an XML document object from null, empty string, and XML text..
	//
	//	str:
	//		Optional text to create the document from.  If not provided, an empty XML document will be created.
	//		If str is empty string "", then a new empty document will be created.
	//	mimetype:
	//		Optional mimetype of the text.  Typically, this is text/xml.  Will be defaulted to text/xml if not provided.
	var _document = dojo.doc;
	var doc;

	if(!mimetype){ mimetype = "text/xml"; }
	if(str && dojo.trim(str) !== "" && "DOMParser" in dojo.global){
		//Handle parsing the text on Mozilla based browsers etc..
		var parser = new DOMParser();
		doc = parser.parseFromString(str, mimetype);
		var de = doc.documentElement;
		var errorNS = "http://www.mozilla.org/newlayout/xml/parsererror.xml";
		if(de.nodeName == "parsererror" && de.namespaceURI == errorNS){
			var sourceText = de.getElementsByTagNameNS(errorNS, 'sourcetext')[0];
			if(!sourceText){
				sourceText = sourceText.firstChild.data;
			}
        	throw new Error("Error parsing text " + nativeDoc.documentElement.firstChild.data + " \n" + sourceText);
		}
		return doc;

	}else if("ActiveXObject" in dojo.global){
		//Handle IE.
		var ms = function(n){ return "MSXML" + n + ".DOMDocument"; };
		var dp = ["Microsoft.XMLDOM", ms(6), ms(4), ms(3), ms(2)];
		dojo.some(dp, function(p){
			try{
				doc = new ActiveXObject(p);
			}catch(e){ return false; }
			return true;
		});
		if(str){
			if(doc){
				doc.async = false;
				doc.loadXML(str);
				var pe = doc.parseError;
				if(pe.errorCode !== 0){
					throw new Error("Line: " + pe.line + "\n" +
						"Col: " + pe.linepos + "\n" +
						"Reason: " + pe.reason + "\n" +
						"Error Code: " + pe.errorCode + "\n" +
						"Source: " + pe.srcText);
				}
				return doc;	//	DOMDocument
			}
		}else{
			if(doc){
				return doc; //DOMDocument
			}
		}
	}else if(_document.implementation && _document.implementation.createDocument){
		if(str && dojo.trim(str) !== ""){
			if(_document.createElement){
				//Everyone else that we couldn't get to work.  Fallback case.
				// FIXME: this may change all tags to uppercase!
				var tmp = _document.createElement("xml");
				tmp.innerHTML = str;
				var xmlDoc = _document.implementation.createDocument("foo", "", null);
				for(var i = 0; i < tmp.childNodes.length; i++) {
					xmlDoc.importNode(tmp.childNodes.item(i), true);
				}
				return xmlDoc;	//	DOMDocument
			}
		}else{
			return _document.implementation.createDocument("", "", null); // DOMDocument
		}
	}
	return null;	//	DOMDocument
}

dojox.xml.parser.textContent = function(/*Node*/node, /*String?*/text){
	//	summary:
	//		Implementation of the DOM Level 3 attribute; scan node for text
	//	description:
	//		Implementation of the DOM Level 3 attribute; scan node for text
	//		This function can also update the text of a node by replacing all child
	//		content of the node.
	//	node:
	//		The node to get the text off of or set the text on.
	//	text:
	//		Optional argument of the text to apply to the node.
	if(arguments.length>1){
		var _document = node.ownerDocument || dojo.doc;  //Preference is to get the node owning doc first or it may fail
		dojox.xml.parser.replaceChildren(node, _document.createTextNode(text));
		return text;	//	string
	}else{
		if(node.textContent !== undefined){ //FF 1.5 -- remove?
			return node.textContent;	//	string
		}
		var _result = "";
		if(node){
			dojo.forEach(node.childNodes, function(child){
				switch(child.nodeType){
					case 1: // ELEMENT_NODE
					case 5: // ENTITY_REFERENCE_NODE
						_result += dojox.xml.parser.textContent(child);
						break;
					case 3: // TEXT_NODE
					case 2: // ATTRIBUTE_NODE
					case 4: // CDATA_SECTION_NODE
						_result += child.nodeValue;
				}
			});
		}
		return _result;	//	String
	}
}

dojox.xml.parser.replaceChildren = function(/*Element*/node, /*Node || array*/ newChildren){
	//	summary:
	//		Removes all children of node and appends newChild. All the existing
	//		children will be destroyed.
	//	description:
	//		Removes all children of node and appends newChild. All the existing
	//		children will be destroyed.
	// 	node:
	//		The node to modify the children on
	//	newChildren:
	//		The children to add to the node.  It can either be a single Node or an
	//		array of Nodes.
	var nodes = [];

	if(dojo.isIE){
		dojo.forEach(node.childNodes, function(child){
			nodes.push(child);
		});
	}

	dojox.xml.parser.removeChildren(node);
	dojo.forEach(nodes.length, function(child){
		dojo._destroyElement(child);
	});

	if(!dojo.isArray(newChildren)){
		node.appendChild(newChildren);
	}else{
		dojo.forEach(newChildren.length, function(child){
			node.appendChild(child);
		});
	}
}

dojox.xml.parser.removeChildren = function(/*Element*/node){
	//	summary:
	//		removes all children from node and returns the count of children removed.
	//		The children nodes are not destroyed. Be sure to call dojo._destroyElement on them
	//		after they are not used anymore.
	//	node:
	//		The node to remove all the children from.
	var count = node.childNodes.length;
	while(node.hasChildNodes()){
		node.removeChild(node.firstChild);
	}
	return count; // int
}

dojox.xml.parser.innerXML = function(/*Node*/node){
	//	summary:
	//		Implementation of MS's innerXML function.
	//	node:
	//		The node from which to generate the XML text representation.
	if(node.innerXML){
		return node.innerXML;	//	String
	}else if(node.xml){
		return node.xml;		//	String
	}else if(typeof XMLSerializer != "undefined"){
		return (new XMLSerializer()).serializeToString(node);	//	String
	}
	return null;
}
<|endoftext|>


<commit_before>
function Clumsy(canvas){
    var self = this;

    self.canvas = canvas;
    self.ctx = self.canvas.getContext('2d');

    self.padding_left = 0;
    self.padding_right = 0;
    self.padding_bottom = 0;
    self.padding_top = 0;

    self.step = 30;
    self.radius = 10;

    function isNumber(n){
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function isSet(object){
        return (typeof object !== 'undefined');
    }

    self.padding = function(p0, p1, p2, p3){
        if(p1 === undefined){
            self.padding_left = p0;
            self.padding_right = p0;
            self.padding_bottom = p0;
            self.padding_top = p0;
            return
        }

        if(p2 === undefined){
            self.padding_left = p0;
            self.padding_right = p0;
            self.padding_bottom = p1;
            self.padding_top = p1;
            return;
        }

        self.padding_left = p0;
        self.padding_right = p1;
        self.padding_bottom = p2;
        self.padding_top = p3;
    };

    self.range_left = 0;
    self.range_right = self.canvas.width;
    self.range_bottom = 0;
    self.range_top = self.canvas.height;

    self.range_horizontal = function(){
        return self.range_right - self.range_left;
    };

    self.range_vertical = function(){
        return self.range_top - self.range_bottom;
    };

    self.range = function(r0, r1, r2, r3){
        if(r3 === undefined){
            self.range_left = r0;
            self.range_right = r1;
            self.range_bottom = r0;
            self.range_top = r1;
            return;
        }

        self.range_left = r0;
        self.range_right = r1;
        self.range_bottom = r2;
        self.range_top = r3;
    };

    self.scale_horizontal = function(){
        return (self.canvas.width - self.padding_left - self.padding_right) / self.range_horizontal();
    };

    self.scale_vertical = function(){
        return (self.canvas.height - self.padding_bottom - self.padding_top) / self.range_vertical();
    }

    self.draw = function(line){
        var step = self.step;
        var radius = self.radius;

        var rescaledLine = self.rescale(line);
        console.log(rescaledLine);
        var replottedLine = self.replot(rescaledLine, step, radius);
        console.log(replottedLine);
        //return;

        var ctx = self.ctx;

        ctx.beginPath();
        ctx.moveTo(replottedLine[0].x, replottedLine[0].y);

        for(var i = 1; i < replottedLine.length - 2; i ++){
            var point = replottedLine[i];
            var nextPoint = replottedLine[i+1];

            var xc = (point.x + nextPoint.x) / 2;
            var yc = (point.y + nextPoint.y) / 2;
            ctx.quadraticCurveTo(point.x, point.y, xc, yc);
        }

        // curve through the last two points
        console.log(replottedLine);
        ctx.quadraticCurveTo(replottedLine[i].x, replottedLine[i].y, replottedLine[i+1].x,replottedLine[i+1].y);
        ctx.stroke();

        var last = {x: replottedLine[i+1].x, y:replottedLine[i+1].y};

        console.log(replottedLine.length);
        for(var i = 0; i < replottedLine.length; i++){
            var point = replottedLine[i];

            if(point.mark === undefined) continue;
            var tick_size = point.tick_size || 10;
            ctx.beginPath();
            ctx.moveTo(
                point.x - 0.5 * tick_size * point.normal.x,
                point.y - 0.5 * tick_size * point.normal.y);
            ctx.lineTo(
                point.x + 0.5 * tick_size * point.normal.x,
                point.y + 0.5 * tick_size * point.normal.y);
            ctx.stroke();

            self.drawText(point.mark,
                point.x + tick_size * point.normal.x,
                point.y + tick_size * point.normal.y,
                point.normal);
        }

        return last;
    }

    self.rescale = function(line){
        var result = [];
        var scale_horizontal = self.scale_horizontal();
        var scale_vertical = self.scale_vertical();

        for(var i = 0; i < line.length; i++){
            var point = line[i];

            result.push({
                x: (point.x - self.range_left) * scale_horizontal  + self.padding_left,
                y: self.canvas.height - ((point.y - self.range_bottom) * scale_vertical  + self.padding_bottom),
                mark: point.mark,
                normal: point.normal
            });
        };
        return result;
    };

    self.replot = function(line, step, radius){
        var accuracy = 0.25;

        if(line.length < 2) return [];
        var replottedLine = [];

        var beginning = line[0];
        replottedLine.push(beginning);

        for(var i = 1; i < line.length; i++){
            var point = line[i];
            var dx = point.x - beginning.x;
            var dy = point.y - beginning.y;
            var d = Math.sqrt(dx*dx+dy*dy);

            if(point.mark !== undefined){
                replottedLine.push(point);
                beginning = point;
                continue;
            }

            if(d < step * (1 - accuracy) && (i + 1 < line.length)){
                // too short
                continue;
            }

            if(d > step * (1 + accuracy)){
                // too long
                var n = Math.ceil(d / step);
                for(var j = 1; j < n; j++){
                    replottedLine.push({
                        x: beginning.x + dx * j / n,
                        y: beginning.y + dy * j / n
                    });
                }
            }

            replottedLine.push(point);
            beginning = point;
        };

        for(var i = 1; i < replottedLine.length; i++){
            var point = replottedLine[i];
            replottedLine[i].x = point.x + radius * (Math.random() - 0.5);
            replottedLine[i].y = point.y + radius * (Math.random() - 0.5);
        };

        return replottedLine;
    };

    self.rightArrow = function(x, y, dx, dy){
        var ctx = self.ctx;
        ctx.beginPath();
        ctx.moveTo(x-dx, y+dy);
        ctx.lineTo(x, y);
        ctx.lineTo(x-dx, y-dy);
        ctx.stroke();
    };

    self.topArrow = function(x, y, dx, dy){
        var ctx = self.ctx;
        ctx.beginPath();
        ctx.moveTo(x-dx, y-dy);
        ctx.lineTo(x, y);
        ctx.lineTo(x+dx, y-dy);
        ctx.stroke();
    };

    self.fillTextAtCenter = function(text, x, y){
        var size = self.ctx.measureText(text);
        self.ctx.fillText(text, x - size.width/2, y);
    };

    self.drawAxis = function(axis, t0, t1, options){
        var dir = axis;
        if(axis === 'x') dir = {x: 1, y: 0};
        if(axis === 'y') dir = {x: 0, y: 1};
        if(axis === '-x') dir = {x: -1, y: 0};
        if(axis === '-y') dir = {x: -0, y: 1};
        dir = {
            x: dir.x / Math.sqrt(dir.x*dir.x+dir.y*dir.y),
            y: dir.y / Math.sqrt(dir.x*dir.x+dir.y*dir.y),
        }

        var opts = options || {};
        var line = [];
        var zero = opts.zero || {x: 0, y: 0};
        var limits = opts.limits || [t0, t1];

        var mark = opts.mark || function(t){
            return parseInt(t) + '.' + parseInt(Math.abs(t*10) % 10)
        };

        if(isSet(opts.step)){
            for(var t=limits[0]; t <= limits[1]; t += opts.step){
                line.push({
                    x: zero.x + dir.x*t,
                    y: zero.y + dir.y*t,
                    normal: {x: -dir.y, y: dir.x},
                    mark: mark(t),
                    style: opts.style,
                    tick_size: opts.tick_size || 5
                });
            };
        }

        if(t0 != limits[0]) line.unshift({
            x: zero.x + dir.x*t0,
            y: zero.y + dir.y*t0
        });

        if(t1 != limits[0]) line.push({
            x: zero.x + dir.x*t1,
            y: zero.y + dir.y*t1
        });

        self.draw(line);

    };

    self.drawText = function(text, x, y, align){
        var ctx = self.ctx;
        var m = ctx.measureText(text);

        if(align === 'center'){
            ctx.fillText(text, x - m.width / 2, y);
            return;
        }
        if(isSet(align) && isNumber(align.x) && isNumber(align.y)){
            //console.log(align.y * m.actualBoundingBoxAscent);
            ctx.fillText(text,
                x + (-1 + align.x) * m.width / 2,
                y + (1 + align.y) * m.actualBoundingBoxAscent / 2);
            return;
        }

        ctx.fillText(text, x, y);
    };
};

module.exports = Clumsy;
<commit_msg>check module<commit_after>
function Clumsy(canvas){
    var self = this;

    self.canvas = canvas;
    self.ctx = self.canvas.getContext('2d');

    self.padding_left = 0;
    self.padding_right = 0;
    self.padding_bottom = 0;
    self.padding_top = 0;

    self.step = 30;
    self.radius = 10;

    function isNumber(n){
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function isSet(object){
        return (typeof object !== 'undefined');
    }

    self.padding = function(p0, p1, p2, p3){
        if(p1 === undefined){
            self.padding_left = p0;
            self.padding_right = p0;
            self.padding_bottom = p0;
            self.padding_top = p0;
            return
        }

        if(p2 === undefined){
            self.padding_left = p0;
            self.padding_right = p0;
            self.padding_bottom = p1;
            self.padding_top = p1;
            return;
        }

        self.padding_left = p0;
        self.padding_right = p1;
        self.padding_bottom = p2;
        self.padding_top = p3;
    };

    self.range_left = 0;
    self.range_right = self.canvas.width;
    self.range_bottom = 0;
    self.range_top = self.canvas.height;

    self.range_horizontal = function(){
        return self.range_right - self.range_left;
    };

    self.range_vertical = function(){
        return self.range_top - self.range_bottom;
    };

    self.range = function(r0, r1, r2, r3){
        if(r3 === undefined){
            self.range_left = r0;
            self.range_right = r1;
            self.range_bottom = r0;
            self.range_top = r1;
            return;
        }

        self.range_left = r0;
        self.range_right = r1;
        self.range_bottom = r2;
        self.range_top = r3;
    };

    self.scale_horizontal = function(){
        return (self.canvas.width - self.padding_left - self.padding_right) / self.range_horizontal();
    };

    self.scale_vertical = function(){
        return (self.canvas.height - self.padding_bottom - self.padding_top) / self.range_vertical();
    }

    self.draw = function(line){
        var step = self.step;
        var radius = self.radius;

        var rescaledLine = self.rescale(line);
        console.log(rescaledLine);
        var replottedLine = self.replot(rescaledLine, step, radius);
        console.log(replottedLine);
        //return;

        var ctx = self.ctx;

        ctx.beginPath();
        ctx.moveTo(replottedLine[0].x, replottedLine[0].y);

        for(var i = 1; i < replottedLine.length - 2; i ++){
            var point = replottedLine[i];
            var nextPoint = replottedLine[i+1];

            var xc = (point.x + nextPoint.x) / 2;
            var yc = (point.y + nextPoint.y) / 2;
            ctx.quadraticCurveTo(point.x, point.y, xc, yc);
        }

        // curve through the last two points
        console.log(replottedLine);
        ctx.quadraticCurveTo(replottedLine[i].x, replottedLine[i].y, replottedLine[i+1].x,replottedLine[i+1].y);
        ctx.stroke();

        var last = {x: replottedLine[i+1].x, y:replottedLine[i+1].y};

        console.log(replottedLine.length);
        for(var i = 0; i < replottedLine.length; i++){
            var point = replottedLine[i];

            if(point.mark === undefined) continue;
            var tick_size = point.tick_size || 10;
            ctx.beginPath();
            ctx.moveTo(
                point.x - 0.5 * tick_size * point.normal.x,
                point.y - 0.5 * tick_size * point.normal.y);
            ctx.lineTo(
                point.x + 0.5 * tick_size * point.normal.x,
                point.y + 0.5 * tick_size * point.normal.y);
            ctx.stroke();

            self.drawText(point.mark,
                point.x + tick_size * point.normal.x,
                point.y + tick_size * point.normal.y,
                point.normal);
        }

        return last;
    }

    self.rescale = function(line){
        var result = [];
        var scale_horizontal = self.scale_horizontal();
        var scale_vertical = self.scale_vertical();

        for(var i = 0; i < line.length; i++){
            var point = line[i];

            result.push({
                x: (point.x - self.range_left) * scale_horizontal  + self.padding_left,
                y: self.canvas.height - ((point.y - self.range_bottom) * scale_vertical  + self.padding_bottom),
                mark: point.mark,
                normal: point.normal
            });
        };
        return result;
    };

    self.replot = function(line, step, radius){
        var accuracy = 0.25;

        if(line.length < 2) return [];
        var replottedLine = [];

        var beginning = line[0];
        replottedLine.push(beginning);

        for(var i = 1; i < line.length; i++){
            var point = line[i];
            var dx = point.x - beginning.x;
            var dy = point.y - beginning.y;
            var d = Math.sqrt(dx*dx+dy*dy);

            if(point.mark !== undefined){
                replottedLine.push(point);
                beginning = point;
                continue;
            }

            if(d < step * (1 - accuracy) && (i + 1 < line.length)){
                // too short
                continue;
            }

            if(d > step * (1 + accuracy)){
                // too long
                var n = Math.ceil(d / step);
                for(var j = 1; j < n; j++){
                    replottedLine.push({
                        x: beginning.x + dx * j / n,
                        y: beginning.y + dy * j / n
                    });
                }
            }

            replottedLine.push(point);
            beginning = point;
        };

        for(var i = 1; i < replottedLine.length; i++){
            var point = replottedLine[i];
            replottedLine[i].x = point.x + radius * (Math.random() - 0.5);
            replottedLine[i].y = point.y + radius * (Math.random() - 0.5);
        };

        return replottedLine;
    };

    self.rightArrow = function(x, y, dx, dy){
        var ctx = self.ctx;
        ctx.beginPath();
        ctx.moveTo(x-dx, y+dy);
        ctx.lineTo(x, y);
        ctx.lineTo(x-dx, y-dy);
        ctx.stroke();
    };

    self.topArrow = function(x, y, dx, dy){
        var ctx = self.ctx;
        ctx.beginPath();
        ctx.moveTo(x-dx, y-dy);
        ctx.lineTo(x, y);
        ctx.lineTo(x+dx, y-dy);
        ctx.stroke();
    };

    self.fillTextAtCenter = function(text, x, y){
        var size = self.ctx.measureText(text);
        self.ctx.fillText(text, x - size.width/2, y);
    };

    self.drawAxis = function(axis, t0, t1, options){
        var dir = axis;
        if(axis === 'x') dir = {x: 1, y: 0};
        if(axis === 'y') dir = {x: 0, y: 1};
        if(axis === '-x') dir = {x: -1, y: 0};
        if(axis === '-y') dir = {x: -0, y: 1};
        dir = {
            x: dir.x / Math.sqrt(dir.x*dir.x+dir.y*dir.y),
            y: dir.y / Math.sqrt(dir.x*dir.x+dir.y*dir.y),
        }

        var opts = options || {};
        var line = [];
        var zero = opts.zero || {x: 0, y: 0};
        var limits = opts.limits || [t0, t1];

        var mark = opts.mark || function(t){
            return parseInt(t) + '.' + parseInt(Math.abs(t*10) % 10)
        };

        if(isSet(opts.step)){
            for(var t=limits[0]; t <= limits[1]; t += opts.step){
                line.push({
                    x: zero.x + dir.x*t,
                    y: zero.y + dir.y*t,
                    normal: {x: -dir.y, y: dir.x},
                    mark: mark(t),
                    style: opts.style,
                    tick_size: opts.tick_size || 5
                });
            };
        }

        if(t0 != limits[0]) line.unshift({
            x: zero.x + dir.x*t0,
            y: zero.y + dir.y*t0
        });

        if(t1 != limits[0]) line.push({
            x: zero.x + dir.x*t1,
            y: zero.y + dir.y*t1
        });

        self.draw(line);

    };

    self.drawText = function(text, x, y, align){
        var ctx = self.ctx;
        var m = ctx.measureText(text);

        if(align === 'center'){
            ctx.fillText(text, x - m.width / 2, y);
            return;
        }
        if(isSet(align) && isNumber(align.x) && isNumber(align.y)){
            //console.log(align.y * m.actualBoundingBoxAscent);
            ctx.fillText(text,
                x + (-1 + align.x) * m.width / 2,
                y + (1 + align.y) * m.actualBoundingBoxAscent / 2);
            return;
        }

        ctx.fillText(text, x, y);
    };
};

module && (module.exports = Clumsy);
<|endoftext|>


<commit_before>/*
* mvcController
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var events = require('events'),
	utils = require('./utilities'),
    mvcHelper = require('./mvcHelper'),
    mvcAction = require('./mvcAction'),
    mvcInjector = require('./mvcInjector'),
    mvcViewData = require('./mvcViewData'),
    mvcTempData = require('./mvcTempData'),
    mvcTempDataStore = require('./mvcTempDataStore'),
    mvcHelperUrl = require('./mvcHelperUrl'),
    mvcResultApi = require('./mvcActionResultApi'),
    mvcFilters = require('./filters/manager');

var mvcController = function(set) {
    utils.extend(this, set);
};

mvcController.define = function(name, impl) {
    var len = arguments.length;
    if (len === 0) {
        return new mvcController();
    } else if (len === 1) {
        return new mvcController({
            _impl: arguments[0]
        });
    } else if (len === 2) {
        return new mvcController({
            _filt: arguments[0],
            _impl: arguments[1]
        });
    } else {
        return new mvcController({
            _name: arguments[0],
            _filt: arguments[1],
            _impl: arguments[2]
        });
    }
};

mvcController.prototype = {

    _name: null, _path: null, _filt: null, _impl: null,

    actions: null,  events: null, url: null,

    viewData: null, tempData: null,

    resultApi: null, resultApiSync: null,

    httpContext: null, controllerContext: null,

    constructor: mvcController, className: 'mvcController',

    name: function(p) { return (p === undefined) ? (this._name) : (this._name = p, this); },
    path: function(p) { return (p === undefined) ? (this._path) : (this._path = p, this); },
    filt: function(p) { return (p === undefined) ? (this._filt) : (this._filt = p, this); },
    impl: function(p) { return (p === undefined) ? (this._impl) : (this._impl = p, this); },

    clone: function() {
        return new mvcController({
            _name: this._name,
            _path: this._path,
            _impl: this._impl
        });
    },

    destroy: function() {
        if (!this.actions) { return; } // already destroyed
        // break object leaks
        utils.each(this.actions, function() {
            this.controllerContext = null;
            this.controller = null;
        });
        this.events.removeAllListeners();
        this.url.httpContext = null;
        this.viewData.httpContext = null;
        this.resultApi.httpContext = null;
        this.resultApiSync.httpContext = null;
        this.controllerContext.controller = null;
        // clear reference types
        this._impl = null;
        this.actions = null;
        this.events = null;
        this.url = null;
        this.viewData = null;
        this.tempData = null;
        this.resultApi = null;
        this.resultApiSync = null;
        this.httpContext = null;
        this.controllerContext = null;
    },

    initialize: function(httpContext) {
        var self = this;
        this.actions = [];
        this.events = new events.EventEmitter();
        this.httpContext = httpContext;
        this.controllerContext = httpContext.toControllerContext(this);
        //
        this.url = new mvcHelperUrl({ httpContext: this.httpContext });
        this.viewData = new mvcViewData({ httpContext: this.httpContext });
        //
        this.tempData = new mvcTempData({ provider: mvcTempDataStore.sessionProvider });
        this.events.on('actionExecuting', function() { self.tempData.load(self.httpContext); });
        this.events.on('resultExecuting', function() { self.tempData.save(self.httpContext); });
        //
        this.resultApi = new mvcResultApi({ httpContext: this.httpContext, sync: false });
        this.resultApiSync = new mvcResultApi({ httpContext: this.httpContext, sync: true });
        utils.each(this.resultApiSync, function(name, func) {
            if (utils.isFunction(func) && !self[name]) {
                self[name] = function() {
                    var args = utils.arg2arr(arguments);
                    return self.resultApiSync[name].apply(self.resultApiSync, args);
                };
            }
        });
        //
        return this;
    },

    injectImpl: function(ctx) {
        var annotated = mvcInjector.annotate(this.impl());
        var params = annotated.params = [];
        if (!annotated.args || annotated.args.length === 0) { return annotated; }
        //
        var self = this, actionWrap;
        utils.each(annotated.args, function(i, name) {
            var loweName = name.toLowerCase();
            if (loweName.charAt(0) === '$') {
                loweName = loweName.substr(1);
            }
            switch(loweName) {
                case 'ctx':      params.push(ctx); break;
                case 'req':      params.push(ctx.request); break;
                case 'res':      params.push(ctx.response); break;
                case 'context':  params.push(ctx); break;
                case 'request':  params.push(ctx.request); break;
                case 'response': params.push(ctx.response); break;
                case 'session':  params.push(ctx.rulee.request.session); break;
                case 'query':    params.push(ctx.rulee.request.query); break;
                case 'form':     params.push(ctx.rulee.request.form); break;
                //
                case 'events':   params.push(self.events); break;
                case 'tempdata': params.push(self.tempData); break;
                case 'viewdata': params.push(self.viewData); break;
                case 'end':      params.push(self.resultApi); break;
                case 'url':      params.push(self.url); break;
                //
                case 'action': params.push(actionWrap || (actionWrap = function() {
                    var args = utils.arg2arr(arguments);
                    self.action.apply(self, args);
                    return actionWrap;
                })); break;
                //
                default: params.push(null); break;
            }
        });
        //
        return annotated;
    },

    executeImpl: function() {
        var annotated = this.injectImpl(this.httpContext);
        if (!utils.isFunction(annotated.func)) { return; }
        annotated.func.apply(this, annotated.params);
    },

    resolveFilters: function(type, filt) {
        if (!filt) { filt = this.filt(); }
        return mvcFilters.resolveSetts(type, filt);
    },

    on: function() {
        var args = utils.arg2arr(arguments);
        this.events.on.apply(this.events, args);
        return this;
    },

    action: function() {
        var len = arguments.length, act;
        if (len === 0) {
            act = new mvcAction();
        } else if (len === 1) {
            act = new mvcAction({
                _name: arguments[0]
            });
        } else if (len === 2) {
            act = new mvcAction({
                _name: arguments[0],
                _impl: arguments[1]
            });
        } else {
            act = new mvcAction({
                _name: arguments[0],
                _filt: arguments[1],
                _impl: arguments[2]
            });
        }
        act.controller = this;
        act.controllerContext = this.controllerContext;
        this.actions.push(act);
        return act; //  for chain
    },

    findAction: function(name, method, secure) {
        var action, self = this;
        utils.each([method, null], function(i, it) {
            if (action) { return false; }
            utils.each(self.actions, function() {
                if (mvcHelper.lowerEqual(this.name(), name) && this.isMatch(it, secure)) {
                    action = this;
                    return false;
                }
            });
        });
        return action;
    }
};

module.exports = mvcController;
<commit_msg>update<commit_after>/*
* mvcController
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var events = require('events'),
	utils = require('./utilities'),
    mvcHelper = require('./mvcHelper'),
    mvcAction = require('./mvcAction'),
    mvcInjector = require('./mvcInjector'),
    mvcHelperUrl = require('./mvcHelperUrl'),
    mvcViewData = require('./mvcViewData'),
    mvcTempData = require('./mvcTempData'),
    mvcTempDataStore = require('./mvcTempDataStore'),
    mvcActionResultApi = require('./mvcActionResultApi'),
    mvcFilters = require('./filters/manager');

var mvcController = function(set) {
    utils.extend(this, set);
};

mvcController.define = function(name, impl) {
    var len = arguments.length;
    if (len === 0) {
        return new mvcController();
    } else if (len === 1) {
        return new mvcController({
            _impl: arguments[0]
        });
    } else if (len === 2) {
        return new mvcController({
            _filt: arguments[0],
            _impl: arguments[1]
        });
    } else {
        return new mvcController({
            _name: arguments[0],
            _filt: arguments[1],
            _impl: arguments[2]
        });
    }
};

mvcController.prototype = {

    _name: null, _path: null, _filt: null, _impl: null,

    actions: null,  events: null, url: null,

    viewData: null, tempData: null,

    resultApi: null, resultApiSync: null,

    httpContext: null, controllerContext: null,

    constructor: mvcController, className: 'mvcController',

    name: function(p) { return (p === undefined) ? (this._name) : (this._name = p, this); },
    path: function(p) { return (p === undefined) ? (this._path) : (this._path = p, this); },
    filt: function(p) { return (p === undefined) ? (this._filt) : (this._filt = p, this); },
    impl: function(p) { return (p === undefined) ? (this._impl) : (this._impl = p, this); },

    clone: function() {
        return new mvcController({
            _name: this._name,
            _path: this._path,
            _impl: this._impl
        });
    },

    destroy: function() {
        if (!this.actions) { return; } // already destroyed
        // break object leaks
        utils.each(this.actions, function() {
            this.controllerContext = null;
            this.controller = null;
        });
        this.events.removeAllListeners();
        this.url.httpContext = null;
        this.viewData.httpContext = null;
        this.resultApi.httpContext = null;
        this.resultApiSync.httpContext = null;
        this.controllerContext.controller = null;
        // clear reference types
        this._impl = null;
        this.actions = null;
        this.events = null;
        this.url = null;
        this.viewData = null;
        this.tempData = null;
        this.resultApi = null;
        this.resultApiSync = null;
        this.httpContext = null;
        this.controllerContext = null;
    },

    initialize: function(httpContext) {
        var self = this;
        this.actions = [];
        this.events = new events.EventEmitter();
        this.httpContext = httpContext;
        this.controllerContext = httpContext.toControllerContext(this);
        //
        this.url = new mvcHelperUrl({ httpContext: this.httpContext });
        this.viewData = new mvcViewData({ httpContext: this.httpContext });
        //
        this.tempData = new mvcTempData({ provider: mvcTempDataStore.sessionProvider });
        this.events.on('actionExecuting', function() { self.tempData.load(self.httpContext); });
        this.events.on('resultExecuting', function() { self.tempData.save(self.httpContext); });
        //
        this.resultApi = new mvcActionResultApi({ httpContext: this.httpContext, sync: false });
        this.resultApiSync = new mvcActionResultApi({ httpContext: this.httpContext, sync: true });
        utils.each(this.resultApiSync, function(name, func) {
            if (utils.isFunction(func) && !self[name]) {
                self[name] = function() {
                    var args = utils.arg2arr(arguments);
                    return self.resultApiSync[name].apply(self.resultApiSync, args);
                };
            }
        });
        //
        return this;
    },

    injectImpl: function(ctx) {
        var annotated = mvcInjector.annotate(this.impl());
        var params = annotated.params = [];
        if (!annotated.args || annotated.args.length === 0) { return annotated; }
        //
        var self = this, actionWrap;
        utils.each(annotated.args, function(i, name) {
            var loweName = name.toLowerCase();
            if (loweName.charAt(0) === '$') {
                loweName = loweName.substr(1);
            }
            switch(loweName) {
                case 'ctx':      params.push(ctx); break;
                case 'req':      params.push(ctx.request); break;
                case 'res':      params.push(ctx.response); break;
                case 'context':  params.push(ctx); break;
                case 'request':  params.push(ctx.request); break;
                case 'response': params.push(ctx.response); break;
                case 'session':  params.push(ctx.rulee.request.session); break;
                case 'query':    params.push(ctx.rulee.request.query); break;
                case 'form':     params.push(ctx.rulee.request.form); break;
                //
                case 'events':   params.push(self.events); break;
                case 'tempdata': params.push(self.tempData); break;
                case 'viewdata': params.push(self.viewData); break;
                case 'end':      params.push(self.resultApi); break;
                case 'url':      params.push(self.url); break;
                //
                case 'action': params.push(actionWrap || (actionWrap = function() {
                    var args = utils.arg2arr(arguments);
                    self.action.apply(self, args);
                    return actionWrap;
                })); break;
                //
                default: params.push(null); break;
            }
        });
        //
        return annotated;
    },

    executeImpl: function() {
        var annotated = this.injectImpl(this.httpContext);
        if (!utils.isFunction(annotated.func)) { return; }
        annotated.func.apply(this, annotated.params);
    },

    resolveFilters: function(type, filt) {
        if (!filt) { filt = this.filt(); }
        return mvcFilters.resolveSetts(type, filt);
    },

    on: function() {
        var args = utils.arg2arr(arguments);
        this.events.on.apply(this.events, args);
        return this;
    },

    action: function() {
        var len = arguments.length, act;
        if (len === 0) {
            act = new mvcAction();
        } else if (len === 1) {
            act = new mvcAction({
                _name: arguments[0]
            });
        } else if (len === 2) {
            act = new mvcAction({
                _name: arguments[0],
                _impl: arguments[1]
            });
        } else {
            act = new mvcAction({
                _name: arguments[0],
                _filt: arguments[1],
                _impl: arguments[2]
            });
        }
        act.controller = this;
        act.controllerContext = this.controllerContext;
        this.actions.push(act);
        return act; //  for chain
    },

    findAction: function(name, method, secure) {
        var action, self = this;
        utils.each([method, null], function(i, it) {
            if (action) { return false; }
            utils.each(self.actions, function() {
                if (mvcHelper.lowerEqual(this.name(), name) && this.isMatch(it, secure)) {
                    action = this;
                    return false;
                }
            });
        });
        return action;
    }
};

module.exports = mvcController;
<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import { Redirect, withRouter } from 'react-router-dom'

import FacebookLoginButton from './view'

class FacebookLoginButtonContainer extends React.Component {
	constructor(props) {
		super(props)
	}

	render() {
		const { dispatch, facebookAppId, history, isLoggedIn } = this.props

		if (isLoggedIn) {
			return <Redirect to="/verification/pregnancy-resource-center" />
		}

		return (
			<FacebookLoginButton
				dispatch={dispatch}
				facebookAppId={facebookAppId}
				isLoggedIn={isLoggedIn}
			/>
		)
	}
}

function mapStateToProps(state) {
	const { initialData } = state
	return {
		facebookAppId: initialData.facebookAppId,
		isLoggedIn: initialData.isLoggedIn,
	}
}

export default connect(mapStateToProps)(
	withRouter(FacebookLoginButtonContainer),
)
<commit_msg>Remove unused code<commit_after>import React from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'

import FacebookLoginButton from './view'

class FacebookLoginButtonContainer extends React.Component {
	constructor(props) {
		super(props)
	}

	render() {
		const { dispatch, facebookAppId, isLoggedIn } = this.props

		if (isLoggedIn) {
			return <Redirect to="/verification/pregnancy-resource-center" />
		}

		return (
			<FacebookLoginButton
				dispatch={dispatch}
				facebookAppId={facebookAppId}
				isLoggedIn={isLoggedIn}
			/>
		)
	}
}

function mapStateToProps(state) {
	const { initialData } = state
	return {
		facebookAppId: initialData.facebookAppId,
		isLoggedIn: initialData.isLoggedIn,
	}
}

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


<commit_before>import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtAvatar, AtIcon } from 'taro-ui'
import { NAVIGATE_TYPE } from '../../constants/navigateType'
import { GLOBAL_CONFIG } from '../../constants/globalConfig'
import { baseUrl } from '../../service/config'
import userAction from '../../actions/user'
import { hasLogin } from '../../utils/common'

import './index.less'
import api from "../../service/api";

class Index extends Component {

  config = {
    navigationBarTitleText: '',
    navigationBarBackgroundColor: '#2d8cf0',
    navigationBarTextStyle: 'white',
    enablePullDownRefresh: true
  }

  constructor(props) {
    super(props)
    this.state = {
      isLogin: false,
      hasStar: true
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentDidMount() {
    Taro.showLoading({title: GLOBAL_CONFIG.LOADING_TEXT})
    this.getUserInfo()
  }

  componentWillUnmount() {
  }

  componentDidShow() {
    this.setState({
      isLogin: hasLogin()
    })
  }

  componentDidHide() {
  }

  onPullDownRefresh() {
    this.getUserInfo()
  }

  getUserInfo() {
    if (hasLogin()) {
      userAction.getUserInfo().then(()=>{
        Taro.hideLoading()
        Taro.stopPullDownRefresh()
        this.checkStarring()
      })
    } else {
      Taro.hideLoading()
      Taro.stopPullDownRefresh()
    }
  }

  checkStarring() {
    if (hasLogin()) {
      let that = this
      let url = '/user/starred/huangjianke/Gitter'
      api.get(url).then((res)=>{
        that.setState({
          hasStar: res.statusCode === 204
        })
      })
    }
  }

  handleNavigate(type) {
    switch (type) {
      case NAVIGATE_TYPE.REPOS: {
        let url = encodeURI(baseUrl + '/user/repos')
        Taro.navigateTo({
          url: '/pages/repo/repoList?url=' + url
        })
      }
      break
      case NAVIGATE_TYPE.FOLLOWERS: {
        Taro.navigateTo({
          url: '/pages/account/follow?type=followers'
        })
      }
      break
      case NAVIGATE_TYPE.FOLLOWING: {
        Taro.navigateTo({
          url: '/pages/account/follow?type=following'
        })
      }
      break
      case NAVIGATE_TYPE.STARRED_REPOS: {
        Taro.navigateTo({
          url: '/pages/repo/starredRepo'
        })
      }
      break
      case NAVIGATE_TYPE.ISSUES: {
        Taro.navigateTo({
          url: '/pages/repo/issues?url=/user/issues'
        })
      }
        break
      case NAVIGATE_TYPE.ABOUT: {
        Taro.navigateTo({
          url: '/pages/account/about'
        })
      }
        break
      case NAVIGATE_TYPE.STAR: {
        this.handleStar()
      }
        break
      default: {
      }
    }
  }

  login() {
    Taro.navigateTo({
      url: '/pages/login/login'
    })
  }

  handleStar() {
    Taro.showLoading({title: GLOBAL_CONFIG.LOADING_TEXT})
    let url = '/user/starred/huangjianke/Gitter'
    api.put(url).then((res)=>{
      Taro.hideLoading()
      if (res.statusCode === 204) {
        Taro.showToast({
          title: 'Thank you!',
          icon: 'success'
        })
        setTimeout(()=>{
          this.getUserInfo()
        }, 1000)
      }
    })
  }

  render() {
    const { isLogin, hasStar } = this.state
    const { userInfo } = this.props
    return (
      <View>
        {
          isLogin ? (
            <View className='content'>
              <Image className='account_bg' src={require('../../assets/images/account_bg.png')}/>
              <View className='user_info'>
                <AtAvatar className='avatar' circle image={userInfo.avatar_url}/>
                {
                  userInfo.name.length > 0 &&
                  <Text className='username'>{userInfo.name}</Text>
                }
                <View className='login_name'>@{userInfo.login}</View>
              </View>
              <View className='info_view'>
                {userInfo.bio.length > 0 && <View className='bio'>{userInfo.bio}</View>}
                <View className='item_view'>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.REPOS)}>
                    <View className='title'>{userInfo.public_repos}+{userInfo.owned_private_repos}</View>
                    <View className='desc'>Repos</View>
                  </View>
                  <View className='line'/>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.FOLLOWERS)}>
                    <View className='title'>{userInfo.followers}</View>
                    <View className='desc'>Followers</View>
                  </View>
                  <View className='line'/>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.FOLLOWING)}>
                    <View className='title'>{userInfo.following}</View>
                    <View className='desc'>Following</View>
                  </View>
                </View>
              </View>
              {
                !hasStar && (
                  <View className='list_view'>
                    <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.STAR)}>
                      <View className='list_title'>Star Gitter ❤</View>
                      <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                    </View>
                  </View>
                )
              }
              <View className='list_view'>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.STARRED_REPOS)}>
                  <View className='list_title'>Starred Repos</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.ISSUES)}>
                  <View className='list_title'>Issues</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
              </View>
              <View className='list_view'>
                <View className='list'>
                  <View className='list_title'>Email</View>
                  <View className='list_content'>{userInfo.email.length > 0 ? userInfo.email : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Blog</View>
                  <View className='list_content'>{userInfo.blog.length > 0 ? userInfo.blog : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Company</View>
                  <View className='list_content'>{userInfo.company.length > 0 ? userInfo.company : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Location</View>
                  <View className='list_content'>{userInfo.location.length > 0 ? userInfo.location : '--'}</View>
                </View>
              </View>
              <View className='list_view'>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.ABOUT)}>
                  <View className='list_title'>About</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
              </View>
              <View className='bottom_view' />
            </View>
          ) : (
            <View className='content'>
              <Image mode='aspectFit'
                     className='logo'
                     src={require('../../assets/images/octocat.png')} />
              <View className='login_button'
                    onClick={this.login.bind(this)}>
                Login
              </View>
            </View>
          )
        }
      </View>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    userInfo: state.user.userInfo
  }
}
export default connect(mapStateToProps)(Index)
<commit_msg>我的页面仓库数量样式调整<commit_after>import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtAvatar, AtIcon } from 'taro-ui'
import { NAVIGATE_TYPE } from '../../constants/navigateType'
import { GLOBAL_CONFIG } from '../../constants/globalConfig'
import { baseUrl } from '../../service/config'
import userAction from '../../actions/user'
import { hasLogin } from '../../utils/common'

import './index.less'
import api from "../../service/api";

class Index extends Component {

  config = {
    navigationBarTitleText: '',
    navigationBarBackgroundColor: '#2d8cf0',
    navigationBarTextStyle: 'white',
    enablePullDownRefresh: true
  }

  constructor(props) {
    super(props)
    this.state = {
      isLogin: false,
      hasStar: true
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentDidMount() {
    Taro.showLoading({title: GLOBAL_CONFIG.LOADING_TEXT})
    this.getUserInfo()
  }

  componentWillUnmount() {
  }

  componentDidShow() {
    this.setState({
      isLogin: hasLogin()
    })
  }

  componentDidHide() {
  }

  onPullDownRefresh() {
    this.getUserInfo()
  }

  getUserInfo() {
    if (hasLogin()) {
      userAction.getUserInfo().then(()=>{
        Taro.hideLoading()
        Taro.stopPullDownRefresh()
        this.checkStarring()
      })
    } else {
      Taro.hideLoading()
      Taro.stopPullDownRefresh()
    }
  }

  checkStarring() {
    if (hasLogin()) {
      let that = this
      let url = '/user/starred/huangjianke/Gitter'
      api.get(url).then((res)=>{
        that.setState({
          hasStar: res.statusCode === 204
        })
      })
    }
  }

  handleNavigate(type) {
    switch (type) {
      case NAVIGATE_TYPE.REPOS: {
        let url = encodeURI(baseUrl + '/user/repos')
        Taro.navigateTo({
          url: '/pages/repo/repoList?url=' + url
        })
      }
      break
      case NAVIGATE_TYPE.FOLLOWERS: {
        Taro.navigateTo({
          url: '/pages/account/follow?type=followers'
        })
      }
      break
      case NAVIGATE_TYPE.FOLLOWING: {
        Taro.navigateTo({
          url: '/pages/account/follow?type=following'
        })
      }
      break
      case NAVIGATE_TYPE.STARRED_REPOS: {
        Taro.navigateTo({
          url: '/pages/repo/starredRepo'
        })
      }
      break
      case NAVIGATE_TYPE.ISSUES: {
        Taro.navigateTo({
          url: '/pages/repo/issues?url=/user/issues'
        })
      }
        break
      case NAVIGATE_TYPE.ABOUT: {
        Taro.navigateTo({
          url: '/pages/account/about'
        })
      }
        break
      case NAVIGATE_TYPE.STAR: {
        this.handleStar()
      }
        break
      default: {
      }
    }
  }

  login() {
    Taro.navigateTo({
      url: '/pages/login/login'
    })
  }

  handleStar() {
    Taro.showLoading({title: GLOBAL_CONFIG.LOADING_TEXT})
    let url = '/user/starred/huangjianke/Gitter'
    api.put(url).then((res)=>{
      Taro.hideLoading()
      if (res.statusCode === 204) {
        Taro.showToast({
          title: 'Thank you!',
          icon: 'success'
        })
        setTimeout(()=>{
          this.getUserInfo()
        }, 1000)
      }
    })
  }

  render() {
    const { isLogin, hasStar } = this.state
    const { userInfo } = this.props
    return (
      <View>
        {
          isLogin ? (
            <View className='content'>
              <Image className='account_bg' src={require('../../assets/images/account_bg.png')}/>
              <View className='user_info'>
                <AtAvatar className='avatar' circle image={userInfo.avatar_url}/>
                {
                  userInfo.name.length > 0 &&
                  <Text className='username'>{userInfo.name}</Text>
                }
                <View className='login_name'>@{userInfo.login}</View>
              </View>
              <View className='info_view'>
                {userInfo.bio.length > 0 && <View className='bio'>{userInfo.bio}</View>}
                <View className='item_view'>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.REPOS)}>
                    <View className='title'>{userInfo ? (userInfo.public_repos + userInfo.owned_private_repos) : null}</View>
                    <View className='desc'>Repos</View>
                  </View>
                  <View className='line'/>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.FOLLOWERS)}>
                    <View className='title'>{userInfo.followers}</View>
                    <View className='desc'>Followers</View>
                  </View>
                  <View className='line'/>
                  <View className='item' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.FOLLOWING)}>
                    <View className='title'>{userInfo.following}</View>
                    <View className='desc'>Following</View>
                  </View>
                </View>
              </View>
              {
                !hasStar && (
                  <View className='list_view'>
                    <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.STAR)}>
                      <View className='list_title'>Star Gitter ❤</View>
                      <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                    </View>
                  </View>
                )
              }
              <View className='list_view'>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.STARRED_REPOS)}>
                  <View className='list_title'>Starred Repos</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.ISSUES)}>
                  <View className='list_title'>Issues</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
              </View>
              <View className='list_view'>
                <View className='list'>
                  <View className='list_title'>Email</View>
                  <View className='list_content'>{userInfo.email.length > 0 ? userInfo.email : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Blog</View>
                  <View className='list_content'>{userInfo.blog.length > 0 ? userInfo.blog : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Company</View>
                  <View className='list_content'>{userInfo.company.length > 0 ? userInfo.company : '--'}</View>
                </View>
                <View className='list'>
                  <View className='list_title'>Location</View>
                  <View className='list_content'>{userInfo.location.length > 0 ? userInfo.location : '--'}</View>
                </View>
              </View>
              <View className='list_view'>
                <View className='list' onClick={this.handleNavigate.bind(this, NAVIGATE_TYPE.ABOUT)}>
                  <View className='list_title'>About</View>
                  <AtIcon prefixClass='ion' value='ios-arrow-forward' size='18' color='#7f7f7f' />
                </View>
              </View>
              <View className='bottom_view' />
            </View>
          ) : (
            <View className='content'>
              <Image mode='aspectFit'
                     className='logo'
                     src={require('../../assets/images/octocat.png')} />
              <View className='login_button'
                    onClick={this.login.bind(this)}>
                Login
              </View>
            </View>
          )
        }
      </View>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    userInfo: state.user.userInfo
  }
}
export default connect(mapStateToProps)(Index)
<|endoftext|>


<commit_before>import React from "react";
import Nav from '../Components/Nav';
import indexStyles from "../styles/index.module.css";

export default () =>

Buy Now!

Legitimate Currency!

<commit_msg>Adds how it works<commit_after>import React from "react";
import Nav from '../Components/Nav';
import indexStyles from "../styles/index.module.css";

export default () =>

Buy Now!

Legitimate Currency!

How it works

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    var util = namespace.util;

    var AssetParser = namespace.AssetParser = function (meshType, assetManager) {
        var type, parsers, textureTypes,
            parseMesh, parseMaterial, parseTexture;

        type = meshType || 'ogre';

        parsers = {
            'ogre': new namespace.OgreXMLParser(assetManager),
            'collada': THREE.ColladaLoader
        };

        parseMesh = (function () {
            var parseFunc, parser;

            function parseMesh( data, name, requestUrl ) {
                if ( !data ) {
                    console.warn( "AssetParser: No mesh data given. Ignoring mesh:", name );
                    return false;
                }

                requestUrl = requestUrl || '';

                return parseFunc( data, name, requestUrl );
            }

            if ( type === 'ogre' ) {
                parseFunc = function ( data, name, requestUrl ) {
                    var request, result, usesMaterials, dispatchMaterial,  geometryGroup,
                        i;

                    usesMaterials = function ( el ) {
                        return el.materialRef;
                    };

                    dispatchMaterial = function ( mat ){
                        this.dispatch( mat );
                    };

                    parser = parsers[type];

                    try {
                        result = {
                            geometryGroup: parser.parseMeshXML( data ),
                            materialReady: new namespace.Signal(),
                            hasMaterials: false
                        };
                    } catch (e) {
                        console.error( "AssetParser: Error while parsing Ogre XML mesh", requestUrl, e.stack );
                        return false;
                    }

                    geometryGroup = result.geometryGroup;
                    if ( geometryGroup ) {
                        //Requesting material files if some submeshes use materials
                        if(geometryGroup.some(usesMaterials)){
                            result.hasMaterials = true;

                            for ( i = geometryGroup.length; i--; ) {

                                if ( geometryGroup[i].materialFileRef ) {
                                    request = assetManager.requestAsset( geometryGroup[i].materialFileRef, 'material' );
                                } else {
                                    request = assetManager.requestAsset( name, 'material' );
                                }

                                if ( request ) {
                                    (function ( signal, request ) {
                                        request.add( dispatchMaterial, signal );
                                    }( result.materialReady, request ));
                                }
                            }
                        }
                    }

                    return result;
                };

            } else if ( type === 'collada' ) {
                parseFunc = function ( data, name, requestUrl ) {
                    var group = [];

                    parser = new parsers[type]().parse;
                    parseResult = parser( data, undefined, requestUrl ).scene;

                    parseResult.traverse( function ( child ) {
                        if ( child instanceof THREE.Mesh ) {
                            group.push( [child.geometry.clone(), child.material.clone()] );
                        }
                    } );

                    return group;
                };
            }

            return parseMesh;

        }());

        parseMaterial = function ( data, name, requestUrl ) {
            var parser;

            if ( !data ) {
                console.warn( "AssetParser: No material data given. Ignoring material:", name );
                return false;
            }

            requestUrl = requestUrl || '';

            parser = parsers['ogre'].parseMaterial;

            try {
                return parser( data );
            } catch (e) {
                console.error( "AssetParser: Error while parsing material", requestUrl, e.stack );
                return false;
            }

        };

        parseTexture = function(data, name, requestUrl ){
        var type = name.split('.' ).pop(), image, texture;

                if(type === 'dds'){
                    image = THREE.ImageUtils.parseDDS( data.response, true );

                    if(image.format === null){
                        return false;
                    }

                    texture = new THREE.CompressedTexture();
                    texture.name = name;
                    texture.minFilter = texture.magFilter = THREE.LinearFilter;
                    texture.wrapS = THREE.RepeatWrapping;
                    texture.wrapT = THREE.RepeatWrapping;
                    texture.repeat.x = 1.0;
                    texture.repeat.y = 1.0;
                    texture.flipY = false;
                    texture.format = image.format;
                    texture.mipmaps = image.mipmaps;
                    texture.image.width = image.width;
                    texture.image.height = image.height;
                    texture.generateMipmaps = false;
                    texture.mapping = new THREE.UVMapping();

                    texture.needsUpdate = true;

                } else {
                    texture = new THREE.Texture();
                    texture.name = name;
                    texture.image = data;
                    texture.sourceFile = requestUrl;
                    texture.mapping = new THREE.UVMapping();
                    texture.needsUpdate = true;
                }

            return texture;
        };

        return {
            parseMesh: parseMesh,
            parseMaterial: parseMaterial,
            parseTexture: parseTexture
        };

    };

}( window['webtundra'] = window['webtundra'] || {} ));<commit_msg>Fixes to asset parser.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    var util = namespace.util;

    var AssetParser = namespace.AssetParser = function (meshType, assetManager) {
        var type, parsers, textureTypes,
            parseMesh, parseMaterial, parseTexture;

        type = meshType || 'ogre';

        parsers = {
            'ogre': new namespace.OgreXMLParser(assetManager),
            'collada': THREE.ColladaLoader
        };

        parseMesh = (function () {
            var parseFunc, parser;

            function parseMesh( data, name, requestUrl ) {
                if ( !data ) {
                    console.warn( "AssetParser: No mesh data given. Ignoring mesh:", name );
                    return false;
                }

                requestUrl = requestUrl || '';

                return parseFunc( data, name, requestUrl );
            }

            if ( type === 'ogre' ) {
                parseFunc = function ( data, name, requestUrl ) {
                    var request, result, usesMaterials, dispatchMaterial,  geometryGroup,
                        i;

                    usesMaterials = function ( el ) {
                        return el.materialRef;
                    };

                    dispatchMaterial = function ( mat ){
                        this.dispatch( mat );
                    };

                    parser = parsers[type];

                    try {
                        result = {
                            geometryGroup: parser.parseMeshXML( data ),
                            materialReady: new namespace.Signal(),
                            hasMaterials: false
                        };
                    } catch (e) {
                        console.error( "AssetParser: Error while parsing Ogre XML mesh", requestUrl, e.stack );
                        return false;
                    }

                    geometryGroup = result.geometryGroup;
                    if ( geometryGroup ) {
                        //Requesting material files if some submeshes use materials
                        if(geometryGroup.some(usesMaterials)){
                            result.hasMaterials = true;

                            for ( i = geometryGroup.length; i--; ) {

                                // If we got a material file reference from the OgreXMLParser, the material will be requested
                                // using that reference
                                if ( geometryGroup[i].materialFileRef ) {
                                    request = assetManager.requestAsset( geometryGroup[i].materialFileRef, 'material' );

                                // Else, if the OgreXMLParser could not decipher what is the material reference defined in the Mesh-file,
                                // the material will be requested using the mesh file reference.
                                } else {
                                    request = assetManager.requestAsset( assetManager.getBaseFileName(name), 'material' );
                                }

                                if ( request ) {
                                    (function ( signal, request ) {
                                        request.add( dispatchMaterial, signal );
                                    }( result.materialReady, request ));
                                }
                            }
                        }
                    }

                    return result;
                };

            } else if ( type === 'collada' ) {
                parseFunc = function ( data, name, requestUrl ) {
                    var group = [];

                    parser = new parsers[type]().parse;
                    parseResult = parser( data, undefined, requestUrl ).scene;

                    parseResult.traverse( function ( child ) {
                        if ( child instanceof THREE.Mesh ) {
                            group.push( [child.geometry.clone(), child.material.clone()] );
                        }
                    } );

                    return group;
                };
            }

            return parseMesh;

        }());

        parseMaterial = function ( data, name, requestUrl ) {
            var parser;

            if ( !data ) {
                console.warn( "AssetParser: No material data given. Ignoring material:", name );
                return false;
            }

            requestUrl = requestUrl || '';

            parser = parsers['ogre'].parseMaterial;

            try {
                return parser( data );
            } catch (e) {
                console.error( "AssetParser: Error while parsing material", requestUrl, e.stack );
                return false;
            }

        };

        parseTexture = function(data, name, requestUrl ){
        var type = name.split('.' ).pop(), image, texture;

                if(type === 'dds'){
                    image = THREE.ImageUtils.parseDDS( data.response, true );

                    if(image.format === null){
                        return false;
                    }

                    texture = new THREE.CompressedTexture();
                    texture.name = name;
                    texture.minFilter = texture.magFilter = THREE.LinearFilter;
                    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
                    texture.repeat.x = 1.0;
                    texture.repeat.y = 1.0;
                    texture.flipY = false;
                    texture.format = image.format;
                    texture.mipmaps = image.mipmaps;
                    texture.image.width = image.width;
                    texture.image.height = image.height;
                    texture.generateMipmaps = false;
                    texture.mapping = new THREE.UVMapping();

                    texture.needsUpdate = true;

                } else {
                    texture = new THREE.Texture();
                    texture.name = name;
                    texture.image = data;
                    texture.sourceFile = requestUrl;
                    texture.minFilter = texture.magFilter = THREE.LinearFilter;
                    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
                    texture.repeat.set(1,1);
                    texture.flipY = false;
                    texture.mapping = new THREE.UVMapping();
                    texture.needsUpdate = true;
                }

            return texture;
        };

        return {
            parseMesh: parseMesh,
            parseMaterial: parseMaterial,
            parseTexture: parseTexture
        };

    };

}( window['webtundra'] = window['webtundra'] || {} ));<|endoftext|>


<commit_before>define([
    '../jquery/autosubmit'
], function(require) {
    var autosubmit = {
        initContent: function(root) {
            $("[data-autosubmit]", root)
                .find("input[type-search]").andSelf()
                .patternAutosubmit();
        }
    };

    return autosubmit;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Fix error in define call<commit_after>define([
    '../jquery/autosubmit'
], function() {
    var autosubmit = {
        initContent: function(root) {
            $("[data-autosubmit]", root)
                .find("input[type-search]").andSelf()
                .patternAutosubmit();
        }
    };

    return autosubmit;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>define(["pex/core/Vec2", "pex/core/Context", "pex/core/Program", "pex/core/Vbo"], function(Vec2, Context, Program, Vbo) {
  var vert = ""
    + "attribute vec2 position;"
    + "attribute vec2 texCoord;"
    + "uniform vec2 windowSize;"
    + "uniform vec2 pixelPosition;"
    + "uniform vec2 pixelSize;"
    + "varying vec2 vTexCoord;"
    + "void main() {"
    +  "float x = -1.0 + 2.0 * (pixelPosition.x + pixelSize.x * position.x)/windowSize.x;"
    +  "float y = -1.0 + 2.0 * (pixelPosition.y + pixelSize.y * position.y)/windowSize.y;"
    +  "gl_Position = vec4(x, y, 0.0, 1.0);"
    +  "vTexCoord = texCoord;"
    + "}";

  var frag = ""
    + "varying vec2 vTexCoord;"
    + "uniform sampler2D tex0;"
    + "void main() {"
    +   "gl_FragColor = texture2D(tex0, vTexCoord);"
    + "}";

  function ScreenImage(screenWidth, screenHeight, x, y, w, h, tex, blending) {
    var gl = Context.currentContext.gl;
    this.program = new Program(vert, frag);
    this.vbo = new Vbo(gl.TRIANGLES);
    this.tex = tex;
    this.windowSize = new Vec2(screenWidth, screenHeight);
    this.position = new Vec2(x, y);
    this.size = new Vec2(w, h);
    this.blending = (blending !== undefined) ? blending : true;

    var vertices = [
       0, 0,
       0, 1,
       1, 1,
       1, 0
    ];

    var texCoords = [
       0,  0,
       0,  1,
       1,  1,
       1,  0
    ];

    var indices = [
      0, 2, 1,
      0, 3, 2
    ];

    this.vbo.addAttrib("position", vertices, 2);
    this.vbo.addAttrib("texCoord", texCoords, 2);
    this.vbo.setIndices(indices);
  }

  ScreenImage.prototype.setPosition = function(position) {
    this.position.x = position.x;
    this.position.y = position.y;
  }

  ScreenImage.prototype.setBounds = function(bounds) {
    this.position.x = bounds.x;
    this.position.y = bounds.y;
    this.size.x = bounds.width;
    this.size.y = bounds.height;
  }

  ScreenImage.prototype.setTexture = function(texture) {
    this.tex = texture;
  }

  ScreenImage.prototype.draw = function(program, dontBlend) {
    var gl = Context.currentContext.gl;
    if (this.blending) {
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    }
    if (this.tex) this.tex.bind();
    program = program ? program : this.program;
    program.use();
    program.uniforms.windowSize(this.windowSize);
    program.uniforms.pixelPosition(this.position);
    program.uniforms.pixelSize(this.size);
    gl.disable(gl.DEPTH_TEST);
    this.vbo.draw(program);
    if (this.blending) {
      gl.disable(gl.BLEND);
    }
    gl.enable(gl.DEPTH_TEST);
  }

  return ScreenImage;
});<commit_msg>Updated ScreenImage coords to be more understandable<commit_after>define(["pex/core/Vec2", "pex/core/Context", "pex/core/Program", "pex/core/Vbo"], function(Vec2, Context, Program, Vbo) {
  var vert = ""
    + "attribute vec2 position;"
    + "attribute vec2 texCoord;"
    + "uniform vec2 windowSize;"
    + "uniform vec2 pixelPosition;"
    + "uniform vec2 pixelSize;"
    + "varying vec2 vTexCoord;"
    + "void main() {"
    +  "float x = -1.0 + 2.0 * (pixelPosition.x + pixelSize.x * position.x)/windowSize.x;"
    +  "float y = -1.0 + 2.0 * (pixelPosition.y + pixelSize.y * position.y)/windowSize.y;"
    +  "gl_Position = vec4(x, y, 0.0, 1.0);"
    +  "vTexCoord = texCoord;"
    + "}";

  var frag = ""
    + "varying vec2 vTexCoord;"
    + "uniform sampler2D tex0;"
    + "void main() {"
    +   "gl_FragColor = texture2D(tex0, vTexCoord);"
    + "}";

  function ScreenImage(screenWidth, screenHeight, x, y, w, h, tex, blending) {
    var gl = Context.currentContext.gl;
    this.program = new Program(vert, frag);
    this.vbo = new Vbo(gl.TRIANGLES);
    this.tex = tex;
    this.windowSize = new Vec2(screenWidth, screenHeight);
    this.position = new Vec2(x, y);
    this.size = new Vec2(w, h);
    this.blending = (blending !== undefined) ? blending : true;

    // 0----1
    // | \  |
    // |  \ |
    // 3----2
    var vertices = [
       0,  1,
       1,  1,
       1,  0,
       0,  0
    ];

    var texCoords = [
       0, 1,
       1, 1,
       1, 0,
       0, 0
    ];

    var indices = [
      0, 2, 1,
      0, 3, 2
    ];

    this.vbo.addAttrib("position", vertices, 2);
    this.vbo.addAttrib("texCoord", texCoords, 2);
    this.vbo.setIndices(indices);
  }

  ScreenImage.prototype.setPosition = function(position) {
    this.position.x = position.x;
    this.position.y = position.y;
  }

  ScreenImage.prototype.setBounds = function(bounds) {
    this.position.x = bounds.x;
    this.position.y = bounds.y;
    this.size.x = bounds.width;
    this.size.y = bounds.height;
  }

  ScreenImage.prototype.setTexture = function(texture) {
    this.tex = texture;
  }

  ScreenImage.prototype.draw = function(program, dontBlend) {
    var gl = Context.currentContext.gl;
    if (this.blending) {
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    }
    if (this.tex) this.tex.bind();
    program = program ? program : this.program;
    program.use();
    program.uniforms.windowSize(this.windowSize);
    program.uniforms.pixelPosition(this.position);
    program.uniforms.pixelSize(this.size);
    gl.disable(gl.DEPTH_TEST);
    this.vbo.draw(program);
    if (this.blending) {
      gl.disable(gl.BLEND);
    }
    gl.enable(gl.DEPTH_TEST);
  }

  return ScreenImage;
});<|endoftext|>


<commit_before>/**
 * React Mixins
 * =============
 *
 * Compilation of react mixins designed to deal with cursors integration.
 */
var types = require('./typology.js');

module.exports = {
  atom: function(atom) {
    return {
      componentWillMount: function() {

        // Binding atom to instance
        this.atom = atom;

        // Is there any cursors to create?
        if (this.cursor && this.cursors)
          throw Error('precursors.Atom.mixin: you cannot have both ' +
                      '`component.cursor` and `component.cursors`. Please ' +
                      'make up your mind.');

        if (this.cursor) {
          if (!types.check(this.cursor, 'string|array|cursor'))
            throw Error('precursors.Atom.mixin.cursor: invalid data (string or array).');

          this.cursor = atom.select(this.cursor);
        }
        else if (this.cursors) {
          if (!types.check(this.cursors, 'object|array'))
            throw Error('precursors.Atom.mixin.cursor: invalid data (object or array).');

          if (types.check(this.cursors, 'array')) {
            this.cursors = this.cursors.map(function(path) {
              return types.check(path, 'cursor') ? path : atom.select(path);
            });
          }
          else {
            for (var k in this.cursors) {
              if (!types.check(path, 'cursor'))
                this.cursors[k] = atom.select(this.cursors[k]);
            }
          }
        }
      }
    };
  },
  cursor: function(cursor) {
    return {
      componentWillMount: function() {

        // Binding cursor to instance
        this.cursor = cursor;

        // Making update handler
        this.__updateHandler = this.forceUpdate.bind(this);
      },
      componentDidMount: function() {

        // Listening to updates
        this.cursor.on('update', this.__updateHandler);
      },
      componentWillUnmount: function() {

        // Unbinding handler
        this.cursor.off('update', this.__updateHandler);
      }
    };
  }
};
<commit_msg>Improving atom mixins<commit_after>/**
 * React Mixins
 * =============
 *
 * Compilation of react mixins designed to deal with cursors integration.
 */
var types = require('./typology.js');

module.exports = {
  atom: function(atom) {
    return {
      componentWillMount: function() {

        // Binding atom to instance
        this.atom = atom;
        this.__type = null;

        // Is there any cursors to create?
        if (this.cursor && this.cursors)
          throw Error('precursors.Atom.mixin: you cannot have both ' +
                      '`component.cursor` and `component.cursors`. Please ' +
                      'make up your mind.');

        if (this.cursor) {
          if (!types.check(this.cursor, 'string|array|cursor'))
            throw Error('precursors.Atom.mixin.cursor: invalid data (string or array).');

          this.cursor = atom.select(this.cursor);
          this.__type = 'single';
        }
        else if (this.cursors) {
          if (!types.check(this.cursors, 'object|array'))
            throw Error('precursors.Atom.mixin.cursor: invalid data (object or array).');

          if (types.check(this.cursors, 'array')) {
            this.cursors = this.cursors.map(function(path) {
              return types.check(path, 'cursor') ? path : atom.select(path);
            });
            this.__type = 'array';
          }
          else {
            for (var k in this.cursors) {
              if (!types.check(path, 'cursor'))
                this.cursors[k] = atom.select(this.cursors[k]);
            }
            this.__type = 'object';
          }
        }

        // Making update handler
        this.__updateHandler = this.forceUpdate.bind(this);
      },
      componentDidMount: function() {
        if (this.__type === 'single') {
          this.cursor.on('update', this.__updateHandler);
        }
        else if (this.__type === 'array') {
          this.cursors.forEach(function(cursor) {
            cursor.on('update', this.__updateHandler);
          }, this);
        }
        else if (this.__type === 'object') {
          for (var k in this.cursors)
            cursors[k].on('update', this.__updateHandler);
        }
      },
      componentWillUnmount: function() {
        if (this.__type === 'single') {
          this.cursor.off('update', this.__updateHandler);
        }
        else if (this.__type === 'array') {
          this.cursors.forEach(function(cursor) {
            cursor.off('update', this.__updateHandler);
          }, this);
        }
        else if (this.__type === 'object') {
          for (var k in this.cursors)
            cursors[k].off('update', this.__updateHandler);
        }
      }
    };
  },
  cursor: function(cursor) {
    return {
      componentWillMount: function() {

        // Binding cursor to instance
        this.cursor = cursor;

        // Making update handler
        this.__updateHandler = this.forceUpdate.bind(this);
      },
      componentDidMount: function() {

        // Listening to updates
        this.cursor.on('update', this.__updateHandler);
      },
      componentWillUnmount: function() {

        // Unbinding handler
        this.cursor.off('update', this.__updateHandler);
      }
    };
  }
};
<|endoftext|>


<commit_before>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * This helper function will automatically detect which renderer you should be using.
 * WebGL is the preferred renderer as it is a lot fastest. If webGL is not supported by
 * the browser then this function will return a canvas renderer
 *
 * @method autoDetectRenderer
 * @static
 * @param width {Number} the width of the renderers view
 * @param height {Number} the height of the renderers view
 * @param view {Canvas} the canvas to use as a view, optional
 * @param transparent=false {Boolean} the transparency of the render view, default false
 * @param antialias=false {Boolean} sets antialias (only applicable in webGL chrome at the moment)
 *
 * antialias
 */
PIXI.autoDetectRenderer = function(width, height, view, transparent, antialias)
{
	if(!width)width = 800;
	if(!height)height = 600;

	// BORROWED from Mr Doob (mrdoob.com)
	var webgl = ( function () { try { return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); } catch( e ) { return false; } } )();

	// TEMP FIX
	if(webgl)
	{
		var ie =  (navigator.userAgent.toLowerCase().indexOf('msie') != -1);
		 webgl = !ie;
	}
	//console.log(webgl);
	if( webgl )
	{
		return new PIXI.WebGLRenderer(width, height, view, transparent, antialias);
	}

	return	new PIXI.CanvasRenderer(width, height, view, transparent);
};

<commit_msg>Fixed the detector to correctly detect IE 11.<commit_after>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * This helper function will automatically detect which renderer you should be using.
 * WebGL is the preferred renderer as it is a lot fastest. If webGL is not supported by
 * the browser then this function will return a canvas renderer
 *
 * @method autoDetectRenderer
 * @static
 * @param width {Number} the width of the renderers view
 * @param height {Number} the height of the renderers view
 * @param view {Canvas} the canvas to use as a view, optional
 * @param transparent=false {Boolean} the transparency of the render view, default false
 * @param antialias=false {Boolean} sets antialias (only applicable in webGL chrome at the moment)
 *
 * antialias
 */
PIXI.autoDetectRenderer = function(width, height, view, transparent, antialias)
{
	if(!width)width = 800;
	if(!height)height = 600;

	// BORROWED from Mr Doob (mrdoob.com)
	var webgl = ( function () { try { return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); } catch( e ) { return false; } } )();

	// TEMP FIX
	if(webgl)
	{
		var agent = navigator.userAgent.toLowerCase();
		var ie =  (agent.indexOf('msie') != -1 || agent.indexOf('trident') != -1);
		webgl = !ie;
	}
	//console.log(webgl);
	if( webgl )
	{
		return new PIXI.WebGLRenderer(width, height, view, transparent, antialias);
	}

	return	new PIXI.CanvasRenderer(width, height, view, transparent);
};

<|endoftext|>


<commit_before>import { Node, Value, Step } from './vnode';

function assertPath(node) {
	if (node.index < 0) return node;
	var lastIndex = node.path.length - 1;
	if (node.index > lastIndex) {
		console.log("Node not in path");
		var last = node.path[lastIndex];
		let next = nextNode(node);
		while (next) {
			next = nextNode(next);
			if (next.vnode === node.vnode) {
				return next;
			}
		}
	}
	return node;
}

function assertNotInPath(child) {
	var check = assertPath(child);
	if(check) {
		console.log("child exists");
		// TODO clone child
	}
	return child;
}

export function appendChild(node, child) {
	// check if path to node is set
	node = assertPath(node);
	let last = lastNode(node);
	if(node.type == 9 && node.vnode.size > 0) {
		throw new Error("Document can only contain one child.");
	}
	let index = node.index;
	// create shallow copy of path down to lastchild of node
	let path = last.path.slice(0, last.index + 1);
	//node = cloneNode(node);
	node.path = path;
	if (typeof child.vnode === "function") {
		child = child.vnode(node);
	} else {
		child = assertNotInPath(child);
	}
	// overwrite parent in prevNode
	node.vnode = restoreNode(child.parent,node.vnode);
	if(node.index < 0) return node;
	node.parent = restoreNode(node.parent.push(node.vnode),node.parent);
	node.path[node.index] = node;
	child = node;
	while (node.vnode._depth > 0) {
		// overwrite parent in prevNode
		node = parent(node);
		node.vnode = child.parent;
		node.path = path;
		node.path[node.index] = node;
		node.parent = restoreNode(node.parent.push(node.vnode),node.parent);
		if(node.parent._type == 9) break;
		child = node;
	}
	return node.path[index];
}

function insertBefore(node,elem){
	node = assertPath(node);
	// find indexInParent
	let index = node.indexInParent;
	// discard path from node down
	let path = node.path.slice(0, node.index + 1);
	node.path = path;
	// create elem from parent
	// pass insertBefore index
	if(typeof elem.vnode == "function") elem = elem.vnode(node.parent,index);
}
<commit_msg>renamed stuff<commit_after>import { Node, Value, Step, restoreNode } from './vnode';

import { lastNode, parent } from './access';

function assertPath(node) {
	if (node.index < 0) return node;
	var lastIndex = node.path.length - 1;
	if (node.index > lastIndex) {
		console.log("Node not in path");
		var last = node.path[lastIndex];
		let next = nextNode(node);
		while (next) {
			next = nextNode(next);
			if (next.inode === node.inode) {
				return next;
			}
		}
	}
	return node;
}

function assertNotInPath(child) {
	var check = assertPath(child);
	if(check) {
		console.log("child exists");
		// TODO clone child
	}
	return child;
}

export function appendChild(node, child) {
	// check if path to node is set
	node = assertPath(node);
	let last = lastNode(node);
	if(node.type == 9 && node.inode.size > 0) {
		throw new Error("Document can only contain one child.");
	}
	let index = node.index;
	// create shallow copy of path down to lastchild of node
	let path = last.path.slice(0, last.index + 1);
	node = node.clone();
	node.path = path;
	if (typeof child.inode === "function") {
		child = child.inode(node);
	} else {
		child = assertNotInPath(child);
	}
	// overwrite parent in prevNode
	node.inode = restoreNode(child.parent,node.inode);
	if(node.index < 0) return node;
	node.parent = restoreNode(node.parent.set(node.name,node.inode),node.parent);
	node.path[node.index] = node;
	child = node;
	while (node.inode._depth > 1) {
		// overwrite parent in prevNode
		node = parent(node).clone();
		node.inode = child.parent;
		node.path = path;
		node.path[node.index] = node;
		node.parent = restoreNode(node.parent.set(node.name,node.inode),node.parent);
		if(node.parent._type == 9) break;
		child = node;
	}
	return node.path[index];
}

function insertBefore(node,elem){
	node = assertPath(node);
	// find indexInParent
	let index = node.indexInParent;
	// discard path from node down
	let path = node.path.slice(0, node.index + 1);
	node.path = path;
	// create elem from parent
	// pass insertBefore index
	if(typeof elem.inode == "function") elem = elem.inode(node.parent,index);
}

export function removeChild(node,child){
	node = assertPath(node);
	child = assertPath(child);
	let index = node.index;
	// shallow copy up to, but not including, child
	let path = child.path.slice(0, child.index);
	let inode = node.inode.removeValue(child.name,child.inode);
	node = node.clone();
	node.path = path;
	// overwrite parent in prevNode
	node.inode = restoreNode(inode,node.inode);
	if(node.index < 0) return node;
	node.parent = restoreNode(node.parent.set(node.name,node.inode),node.parent);
	node.path[node.index] = node;
	child = node;
	while (node.inode._depth > 1) {
		// overwrite parent in prevNode
		node = parent(node).clone();
		node.inode = child.parent;
		node.path = path;
		node.path[node.index] = node;
		node.parent = restoreNode(node.parent.set(node.name,node.inode),node.parent);
		if(node.parent._type == 9) break;
		child = node;
	}
	return node.path[index];
}
<|endoftext|>