<commit_before>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth,
    height= ele.clientHeight;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([75])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", 100%)
    .attr("height", 100%)
    .append("g")
	.call(d3.behavior.zoom().scaleExtent([0.5,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

svg.append("rect")
    .attr("width", 100%)
    .attr("height", 100%)
    //.attr("fill","none")
    	.attr("fill", "grey")
    	.attr("opacity", 0.1)
    .attr("pointer-events","all");

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svg.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svg.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}

function mouseout() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = false);
    //d3.select(this).attr("d", d3.svg.symbol()
	//		.type(function(d) { return d.shape || "circle"; })
	//		.size(function(d) { return scaleSize(d.size * 2 || 2); })
	//);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = true);
    //d3.select(this).attr("d", d3.svg.symbol()
		//.type(function(d) { return d.shape || "circle"; })
		//.size(function(d) { return scaleSize(d.size || 1); })
	//);
}

<commit_msg>fixed a semicolon<commit_after>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth,
    height= ele.clientHeight;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([75])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .append("g")
	.call(d3.behavior.zoom().scaleExtent([0.5,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

svg.append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    //.attr("fill","none")
    	.attr("fill", "grey")
    	.attr("opacity", 0.1)
    .attr("pointer-events","all");

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svg.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svg.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}

function mouseout() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = false);
    //d3.select(this).attr("d", d3.svg.symbol()
	//		.type(function(d) { return d.shape || "circle"; })
	//		.size(function(d) { return scaleSize(d.size * 2 || 2); })
	//);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = true);
    //d3.select(this).attr("d", d3.svg.symbol()
		//.type(function(d) { return d.shape || "circle"; })
		//.size(function(d) { return scaleSize(d.size || 1); })
	//);
}

<|endoftext|>


<commit_before>import ManufacturingLayer from "./manufacturingLayer";
import DepthFeatureMap from "./depthFeatureMap";
import Device from "../core/device";

/**
 * Lasser Cutting Generator object
 */
export default class LaserCuttingGenerator {
    /**
     * Default Constructor for the laser cutting generator object
     * @param {Device} device Device object
     * @param {*} viewManagerDelegate
     */
    constructor(device, viewManagerDelegate) {
        this.__device = device;
        this.__viewManagerDelegate = viewManagerDelegate;

        this.__svgData = new Map();
    }
    /**
     * Gets the SVG data
     * @returns Returns the SVG data
     * @memberof LaserCuttingGenerator
     */
    getSVGOutputs() {
        return this.__svgData;
    }

    /**
     * Generate the port layers
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generatePortLayers() {
        /*
        Step 1 - Get all the layers
        Step 2 - Get all the ports in each of the layers
        Step 3 - Create a manufacturing layer
                -  Populate with the ports
         */
        // let components = this.__device.getComponents();
        let layers = this.__device.getLayers();

        let mfglayers = [];

        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];
            let ports = [];

            let features = layer.features;

            if (layer.name == "control") {
                isControl = true;
            }

            for (let key in features) {
                let feature = features[key];
                //TODO: Include fabtype check also
                if (feature.getType() == "Port") {
                    ports.push(key);
                }
            }

            if (ports.length == 0) {
                continue;
            }

            let manufacturinglayer = new ManufacturingLayer("ports_" + layer.name + "_" + i);
            // console.log("manufacturing layer :", manufacturinglayer);

            for (let fi in ports) {
                let featurekey = ports[fi];
                // console.log("Key:", featurekey);
                // console.log("rendered:feature", this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                if (!issuccess) {
                    console.error("Could not find the feature for the corresponding id: " + featurekey);
                }
            }

            if (isControl) {
                manufacturinglayer.flipX();
                isControl = false;
            }

            mfglayers.push(manufacturinglayer);
        }

        console.log("mfglayers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });

        console.log("SVG Outputs:", this.__svgData);
    }

    /**
     * Generates separate mfglayers and svgs for each of the depth layers
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateDepthLayers() {
        /*
        Step 1 - Go through each of the layers
        Step 2 - At each layer:
                   Step 2.1 - Sort each of the features based on their depths
                   Step 2.2 - Generate manufacturing layers for each of the depths

         */
        let layers = this.__device.getLayers();

        let mfglayers = [];
        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];

            let features = layer.features;

            if (layer.name == "control") {
                isControl = true;
            }

            //Create the depthmap for this
            let featuredepthmap = new DepthFeatureMap(layer.name);

            for (let key in features) {
                let feature = features[key];
                //TODO: Modify the port check
                if (feature.fabType == "XY" && feature.getType() != "Port") {
                    let depth = feature.getValue("height");
                    console.log("Depth of feature: ", key, depth);
                    featuredepthmap.addFeature(depth, key);
                }
            }

            //Generate Manufacturing Layers for each depth
            let manufacturinglayer;
            for (let depth of featuredepthmap.getDepths()) {
                manufacturinglayer = new ManufacturingLayer(layer.name + "_" + i + "_" + depth);
                let depthfeatures = featuredepthmap.getFeaturesAtDepth(depth);
                for (let j in depthfeatures) {
                    let featurekey = depthfeatures[j];

                    let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                    if (!issuccess) {
                        console.error("Could not find the feature for the corresponding id: " + featurekey);
                    }
                }

                if (isControl) {
                    manufacturinglayer.flipX();
                }

                mfglayers.push(manufacturinglayer);
            }

            isControl = false;
        }

        console.log("XY Manufacturing Layers:", mfglayers);
        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }

    /**
     * Generates all the edge cuts
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateEdgeLayers() {
        /*
        Step 1 - Go through each of the layers
        Step 2 - Get all the EDGE features in the drawing
        Step 3 - Generate separate SVGs
         */
        let layers = this.__device.getLayers();

        let mfglayers = [];

        let manufacturinglayer;

        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];
            manufacturinglayer = new ManufacturingLayer(layer.name + "_" + i + "_EDGE");

            if (layer.name == "control") {
                isControl = true;
            }

            let features = layer.features;

            for (let key in features) {
                let feature = features[key];
                //TODO: Modify the port check
                if (feature.fabType == "EDGE") {
                    console.log("EDGE Feature: ", key);
                    let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(key));
                    if (!issuccess) {
                        console.error("Could not find the feature for the corresponding id: " + key);
                    }
                }
            }

            if (isControl) {
                manufacturinglayer.flipX();
                isControl = false;
            }

            mfglayers.push(manufacturinglayer);
        }

        console.log("EDGE Manufacturing Layers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }

    /**
     * Sets the device the CNCGenerator needs to work of
     * @param {Device} currentDevice
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    setDevice(currentDevice) {
        this.__device = currentDevice;
        console.log("Currentdevice:", currentDevice);
    }

    /**
     * Flush all the data
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    flushData() {
        this.__svgData.clear();
    }

    /**
     * Generates all the glue burn off layers necessary for the valves
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateInverseControlLayers() {
        console.log("Generating inverse layers");
        let layers = this.__device.getLayers();

        let mfglayers = [];

        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];
            let negatives = [];

            let features = layer.features;

            if (layer.name == "control") {
                isControl = true;
            }

            //Add logic to generate the here to check if its control...
            if (isControl) {
                let manufacturinglayer = new ManufacturingLayer("control_negative_" + layer.name + "_" + i);

                //Do the actual feature generation part here
                for (let key in features) {
                    let feature = features[key];
                    //TODO: Include fabtype check also
                    let type = feature.getType();

                    /*
                    Check if type has an inverse layer
                     */

                    //Skip the EDGE features
                    if (type === "EDGE") {
                        continue;
                    }

                    if (Registry.featureSet.hasInverseRenderLayer(type)) {
                        /*
                        If the type has an inverse layer, then generate the inverse feature render
                         and throw it into the manufacturing layer.
                         */
                        manufacturinglayer.generateFeatureRender(feature, "INVERSE");
                    }
                }

                mfglayers.push(manufacturinglayer);
                isControl = false;
            }
        }

        console.log("Inverse Control Manufacturing Layers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }
}
<commit_msg>Undid deletes<commit_after>import ManufacturingLayer from "./manufacturingLayer";
import DepthFeatureMap from "./depthFeatureMap";
import Device from "../core/device";

/**
 * Lasser Cutting Generator object
 */
export default class LaserCuttingGenerator {
    /**
     * Default Constructor for the laser cutting generator object
     * @param {Device} device Device object
     * @param {*} viewManagerDelegate
     */
    constructor(device, viewManagerDelegate) {
        this.__device = device;
        this.__viewManagerDelegate = viewManagerDelegate;

        this.__svgData = new Map();
    }
    /**
     * Gets the SVG data
     * @returns Returns the SVG data
     * @memberof LaserCuttingGenerator
     */
    getSVGOutputs() {
        return this.__svgData;
    }

    /**
     * Generate the port layers
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generatePortLayers() {
        /*
        Step 1 - Get all the layers
        Step 2 - Get all the ports in each of the layers
        Step 3 - Create a manufacturing layer
                -  Populate with the ports
         */
        // let components = this.__device.getComponents();
        let layers = this.__device.getLayers();

        let mfglayers = [];

        for (let i in layers) {
            let layer = layers[i];
            let ports = [];

            let features = layer.features;

            for (let key in features) {
                let feature = features[key];
                //TODO: Include fabtype check also
                if (feature.getType() == "Port") {
                    ports.push(key);
                }
            }

            if (ports.length == 0) {
                continue;
            }

            let manufacturinglayer = new ManufacturingLayer("ports_" + layer.name + "_" + i);
            // console.log("manufacturing layer :", manufacturinglayer);

            for (let fi in ports) {
                let featurekey = ports[fi];
                // console.log("Key:", featurekey);
                // console.log("rendered:feature", this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                if (!issuccess) {
                    console.error("Could not find the feature for the corresponding id: " + featurekey);
                }
            }

            //We flip all the ports for this system
            //TODO: Future manufacturing user interface will require us to have options for each of the UI elements
            manufacturinglayer.flipX();

            mfglayers.push(manufacturinglayer);
        }

        console.log("mfglayers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });

        console.log("SVG Outputs:", this.__svgData);
    }

    /**
     * Generates separate mfglayers and svgs for each of the depth layers
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateDepthLayers() {
        /*
        Step 1 - Go through each of the layers
        Step 2 - At each layer:
                   Step 2.1 - Sort each of the features based on their depths
                   Step 2.2 - Generate manufacturing layers for each of the depths

         */
        let layers = this.__device.getLayers();

        let mfglayers = [];
        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];

            let features = layer.features;

            if (layer.name == "control") {
                isControl = true;
            }

            //Create the depthmap for this
            let featuredepthmap = new DepthFeatureMap(layer.name);

            for (let key in features) {
                let feature = features[key];
                //TODO: Modify the port check
                if (feature.fabType == "XY" && feature.getType() != "Port") {
                    let depth = feature.getValue("height");
                    console.log("Depth of feature: ", key, depth);
                    featuredepthmap.addFeature(depth, key);
                }
            }

            //Generate Manufacturing Layers for each depth
            let manufacturinglayer;
            for (let depth of featuredepthmap.getDepths()) {
                manufacturinglayer = new ManufacturingLayer(layer.name + "_" + i + "_" + depth);
                let depthfeatures = featuredepthmap.getFeaturesAtDepth(depth);
                for (let j in depthfeatures) {
                    let featurekey = depthfeatures[j];

                    let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(featurekey));
                    if (!issuccess) {
                        console.error("Could not find the feature for the corresponding id: " + featurekey);
                    }
                }

                if (isControl) {
                    manufacturinglayer.flipX();
                }

                mfglayers.push(manufacturinglayer);
            }

            isControl = false;
        }

        console.log("XY Manufacturing Layers:", mfglayers);
        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }

    /**
     * Generates all the edge cuts
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateEdgeLayers() {
        /*
        Step 1 - Go through each of the layers
        Step 2 - Get all the EDGE features in the drawing
        Step 3 - Generate separate SVGs
         */
        let layers = this.__device.getLayers();

        let mfglayers = [];

        let manufacturinglayer;

        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];
            manufacturinglayer = new ManufacturingLayer(layer.name + "_" + i + "_EDGE");

            if (layer.name == "control") {
                isControl = true;
            }

            let features = layer.features;

            for (let key in features) {
                let feature = features[key];
                //TODO: Modify the port check
                if (feature.fabType == "EDGE") {
                    console.log("EDGE Feature: ", key);
                    let issuccess = manufacturinglayer.addFeature(this.__viewManagerDelegate.view.getRenderedFeature(key));
                    if (!issuccess) {
                        console.error("Could not find the feature for the corresponding id: " + key);
                    }
                }
            }

            if (isControl) {
                manufacturinglayer.flipX();
                isControl = false;
            }

            mfglayers.push(manufacturinglayer);
        }

        console.log("EDGE Manufacturing Layers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }

    /**
     * Sets the device the CNCGenerator needs to work of
     * @param {Device} currentDevice
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    setDevice(currentDevice) {
        this.__device = currentDevice;
        console.log("Currentdevice:", currentDevice);
    }

    /**
     * Flush all the data
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    flushData() {
        this.__svgData.clear();
    }

    /**
     * Generates all the glue burn off layers necessary for the valves
     * @memberof LaserCuttingGenerator
     * @returns {void}
     */
    generateInverseControlLayers() {
        console.log("Generating inverse layers");
        let layers = this.__device.getLayers();

        let mfglayers = [];

        let isControl = false;

        for (let i in layers) {
            let layer = layers[i];
            let negatives = [];

            let features = layer.features;

            if (layer.name == "control") {
                isControl = true;
            }

            //Add logic to generate the here to check if its control...
            if (isControl) {
                let manufacturinglayer = new ManufacturingLayer("control_negative_" + layer.name + "_" + i);

                //Do the actual feature generation part here
                for (let key in features) {
                    let feature = features[key];
                    //TODO: Include fabtype check also
                    let type = feature.getType();

                    /*
                    Check if type has an inverse layer
                     */

                    //Skip the EDGE features
                    if (type === "EDGE") {
                        continue;
                    }

                    if (Registry.featureSet.hasInverseRenderLayer(type)) {
                        /*
                        If the type has an inverse layer, then generate the inverse feature render
                         and throw it into the manufacturing layer.
                         */
                        manufacturinglayer.generateFeatureRender(feature, "INVERSE");
                    }
                }

                mfglayers.push(manufacturinglayer);
                isControl = false;
            }
        }

        console.log("Inverse Control Manufacturing Layers:", mfglayers);

        let ref = this;
        mfglayers.forEach(function(mfglayer, index) {
            ref.__svgData.set(mfglayer.name, mfglayer.exportToSVG());
            mfglayer.flushData();
        });
    }
}
<|endoftext|>


<commit_before>
function doCancelDeclare() {
    var comment_srl = new Array();
    jQuery('#fo_list input[name=cart]:checked').each(function() {
        comment_srl[comment_srl.length] = jQuery(this).val();
    });

    if(comment_srl.length<1) return;

    var params = new Array();
    params['comment_srl'] = comment_srl.join(',');

    exec_xml('comment','procCommentAdminCancelDeclare', params, function() { location.reload(); });
}

function insertSelectedModule(id, module_srl, mid, browser_title) {
    location.href = current_url.setQuery('module_srl',module_srl);
}

function completeAddCart(ret_obj, response_tags)
{
}

function getCommentList()
{
	var commentListTable = jQuery('#commentListTable');
	var cartList = [];
	commentListTable.find(':checkbox[name=cart]').each(function(){
		if(this.checked) cartList.push(this.value);
	});

    var params = new Array();
    var response_tags = ['error','message', 'comment_list'];
	params["comment_srls"] = cartList.join(",");

    exec_xml('comment','procCommentGetList',params, completeGetCommentList, response_tags);
}

function completeGetCommentList(ret_obj, response_tags)
{
	var htmlListBuffer = '';
	var statusNameList = {"N":"Public", "Y":"Secret"};
	var publishedStatusList = {0:'Unpublished', 1:'Published'};
	if(ret_obj['comment_list'] == null)
	{
		htmlListBuffer = '
' +
							''+ret_obj['message']+'	' +
						'
';
	}
	else
	{
		var comment_list = ret_obj['comment_list']['item'];
		if(!jQuery.isArray(comment_list)) comment_list = [comment_list];
		for(var x in comment_list)
		{
			var objComment = comment_list[x];
			htmlListBuffer += '
' +
								''+ objComment.content +'	' +
								''+ objComment.nick_name +'	' +
								''+ statusNameList[objComment.is_secret] +'	' +
								''+ publishedStatusList[objComment.status] + '<input type="hidden" name="cart[]" value="'+objComment.comment_srl+'" />' + '	' +
							'
';
		}
		jQuery('#selectedCommentCount').html(comment_list.length);
	}
	jQuery('#commentManageListTable>tbody').html(htmlListBuffer);
}

function doChangePublishedStatus(new_status)
{
	container_div = jQuery("#listManager");
	var act = container_div.find("input[name=act]");
	var will_publish = container_div.find("input[name=will_publish]");
	var action = "procCommentAdminChangePublishedStatusChecked";
	will_publish.val(new_status);
	act.val(action);
}

function checkSearch(form)
{
	if(form.search_target.value == '')
	{
		alert(xe.lang.msg_empty_search_target);
		return false;
	}
	/*
	if(form.search_keyword.value == '')
	{
		alert(xe.lang.msg_empty_search_keyword);
		return false;
	}
	*/
}
<commit_msg>Update comment_admin.js<commit_after>
function doCancelDeclare() {
    var comment_srl = new Array();
    jQuery('#fo_list input[name="cart[]"]:checked').each(function() {
        comment_srl[comment_srl.length] = jQuery(this).val();
    });

    if(comment_srl.length<1) return;

    var params = new Array();
    params['comment_srl'] = comment_srl.join(',');

    exec_xml('comment','procCommentAdminCancelDeclare', params, function() { location.reload(); });
}

function insertSelectedModule(id, module_srl, mid, browser_title) {
    location.href = current_url.setQuery('module_srl',module_srl);
}

function completeAddCart(ret_obj, response_tags)
{
}

function getCommentList()
{
	var commentListTable = jQuery('#commentListTable');
	var cartList = [];
	commentListTable.find(':checkbox[name=cart]').each(function(){
		if(this.checked) cartList.push(this.value);
	});

    var params = new Array();
    var response_tags = ['error','message', 'comment_list'];
	params["comment_srls"] = cartList.join(",");

    exec_xml('comment','procCommentGetList',params, completeGetCommentList, response_tags);
}

function completeGetCommentList(ret_obj, response_tags)
{
	var htmlListBuffer = '';
	var statusNameList = {"N":"Public", "Y":"Secret"};
	var publishedStatusList = {0:'Unpublished', 1:'Published'};
	if(ret_obj['comment_list'] == null)
	{
		htmlListBuffer = '
' +
							''+ret_obj['message']+'	' +
						'
';
	}
	else
	{
		var comment_list = ret_obj['comment_list']['item'];
		if(!jQuery.isArray(comment_list)) comment_list = [comment_list];
		for(var x in comment_list)
		{
			var objComment = comment_list[x];
			htmlListBuffer += '
' +
								''+ objComment.content +'	' +
								''+ objComment.nick_name +'	' +
								''+ statusNameList[objComment.is_secret] +'	' +
								''+ publishedStatusList[objComment.status] + '<input type="hidden" name="cart[]" value="'+objComment.comment_srl+'" />' + '	' +
							'
';
		}
		jQuery('#selectedCommentCount').html(comment_list.length);
	}
	jQuery('#commentManageListTable>tbody').html(htmlListBuffer);
}

function doChangePublishedStatus(new_status)
{
	container_div = jQuery("#listManager");
	var act = container_div.find("input[name=act]");
	var will_publish = container_div.find("input[name=will_publish]");
	var action = "procCommentAdminChangePublishedStatusChecked";
	will_publish.val(new_status);
	act.val(action);
}

function checkSearch(form)
{
	if(form.search_target.value == '')
	{
		alert(xe.lang.msg_empty_search_target);
		return false;
	}
	/*
	if(form.search_keyword.value == '')
	{
		alert(xe.lang.msg_empty_search_keyword);
		return false;
	}
	*/
}
<|endoftext|>


<commit_before>// flow-typed signature: 336a37cc59a5628d581d11f98d1d94ab
// flow-typed version: ef52b40a4e/jest_v20.x.x/flow_>=v0.33.x

type JestMockFn = {
  (...args: Array<any>): any,
  /**
   * An object for introspecting mock calls
   */
  mock: {
    /**
     * An array that represents all calls that have been made into this mock
     * function. Each call is represented by an array of arguments that were
     * passed during the call.
     */
    calls: Array<Array<any>>,
    /**
     * An array that contains all the object instances that have been
     * instantiated from this mock function.
     */
    instances: mixed
  },
  /**
   * Resets all information stored in the mockFn.mock.calls and
   * mockFn.mock.instances arrays. Often this is useful when you want to clean
   * up a mock's usage data between two assertions.
   */
  mockClear(): Function,
  /**
   * Resets all information stored in the mock. This is useful when you want to
   * completely restore a mock back to its initial state.
   */
  mockReset(): Function,
  /**
   * Removes the mock and restores the initial implementation. This is useful
   * when you want to mock functions in certain test cases and restore the
   * original implementation in others. Beware that mockFn.mockRestore only
   * works when mock was created with jest.spyOn. Thus you have to take care of
   * restoration yourself when manually assigning jest.fn().
   */
  mockRestore(): Function,
  /**
   * Accepts a function that should be used as the implementation of the mock.
   * The mock itself will still record all calls that go into and instances
   * that come from itself -- the only difference is that the implementation
   * will also be executed when the mock is called.
   */
  mockImplementation(fn: Function): JestMockFn,
  /**
   * Accepts a function that will be used as an implementation of the mock for
   * one call to the mocked function. Can be chained so that multiple function
   * calls produce different results.
   */
  mockImplementationOnce(fn: Function): JestMockFn,
  /**
   * Just a simple sugar function for returning `this`
   */
  mockReturnThis(): void,
  /**
   * Deprecated: use jest.fn(() => value) instead
   */
  mockReturnValue(value: any): JestMockFn,
  /**
   * Sugar for only returning a value once inside your mock
   */
  mockReturnValueOnce(value: any): JestMockFn
};

type JestAsymmetricEqualityType = {
  /**
   * A custom Jasmine equality tester
   */
  asymmetricMatch(value: mixed): boolean
};

type JestCallsType = {
  allArgs(): mixed,
  all(): mixed,
  any(): boolean,
  count(): number,
  first(): mixed,
  mostRecent(): mixed,
  reset(): void
};

type JestClockType = {
  install(): void,
  mockDate(date: Date): void,
  tick(milliseconds?: number): void,
  uninstall(): void
};

type JestMatcherResult = {
  message?: string | (() => string),
  pass: boolean
};

type JestMatcher = (actual: any, expected: any) => JestMatcherResult;

type JestPromiseType = {
  /**
   * Use rejects to unwrap the reason of a rejected promise so any other
   * matcher can be chained. If the promise is fulfilled the assertion fails.
   */
  rejects: JestExpectType,
  /**
   * Use resolves to unwrap the value of a fulfilled promise so any other
   * matcher can be chained. If the promise is rejected the assertion fails.
   */
  resolves: JestExpectType
};

type JestExpectType = {
  not: JestExpectType,
  /**
   * If you have a mock function, you can use .lastCalledWith to test what
   * arguments it was last called with.
   */
  lastCalledWith(...args: Array<any>): void,
  /**
   * toBe just checks that a value is what you expect. It uses === to check
   * strict equality.
   */
  toBe(value: any): void,
  /**
   * Use .toHaveBeenCalled to ensure that a mock function got called.
   */
  toBeCalled(): void,
  /**
   * Use .toBeCalledWith to ensure that a mock function was called with
   * specific arguments.
   */
  toBeCalledWith(...args: Array<any>): void,
  /**
   * Using exact equality with floating point numbers is a bad idea. Rounding
   * means that intuitive things fail.
   */
  toBeCloseTo(num: number, delta: any): void,
  /**
   * Use .toBeDefined to check that a variable is not undefined.
   */
  toBeDefined(): void,
  /**
   * Use .toBeFalsy when you don't care what a value is, you just want to
   * ensure a value is false in a boolean context.
   */
  toBeFalsy(): void,
  /**
   * To compare floating point numbers, you can use toBeGreaterThan.
   */
  toBeGreaterThan(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeGreaterThanOrEqual.
   */
  toBeGreaterThanOrEqual(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeLessThan.
   */
  toBeLessThan(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeLessThanOrEqual.
   */
  toBeLessThanOrEqual(number: number): void,
  /**
   * Use .toBeInstanceOf(Class) to check that an object is an instance of a
   * class.
   */
  toBeInstanceOf(cls: Class<*>): void,
  /**
   * .toBeNull() is the same as .toBe(null) but the error messages are a bit
   * nicer.
   */
  toBeNull(): void,
  /**
   * Use .toBeTruthy when you don't care what a value is, you just want to
   * ensure a value is true in a boolean context.
   */
  toBeTruthy(): void,
  /**
   * Use .toBeUndefined to check that a variable is undefined.
   */
  toBeUndefined(): void,
  /**
   * Use .toContain when you want to check that an item is in a list. For
   * testing the items in the list, this uses ===, a strict equality check.
   */
  toContain(item: any): void,
  /**
   * Use .toContainEqual when you want to check that an item is in a list. For
   * testing the items in the list, this matcher recursively checks the
   * equality of all fields, rather than checking for object identity.
   */
  toContainEqual(item: any): void,
  /**
   * Use .toEqual when you want to check that two objects have the same value.
   * This matcher recursively checks the equality of all fields, rather than
   * checking for object identity.
   */
  toEqual(value: any): void,
  /**
   * Use .toHaveBeenCalled to ensure that a mock function got called.
   */
  toHaveBeenCalled(): void,
  /**
   * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
   * number of times.
   */
  toHaveBeenCalledTimes(number: number): void,
  /**
   * Use .toHaveBeenCalledWith to ensure that a mock function was called with
   * specific arguments.
   */
  toHaveBeenCalledWith(...args: Array<any>): void,
  /**
   * Check that an object has a .length property and it is set to a certain
   * numeric value.
   */
  toHaveLength(number: number): void,
  /**
   *
   */
  toHaveProperty(propPath: string, value?: any): void,
  /**
   * Use .toMatch to check that a string matches a regular expression.
   */
  toMatch(regexp: RegExp): void,
  /**
   * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
   */
  toMatchObject(object: Object): void,
  /**
   * This ensures that a React component matches the most recent snapshot.
   */
  toMatchSnapshot(name?: string): void,
  /**
   * Use .toThrow to test that a function throws when it is called.
   * If you want to test that a specific error gets thrown, you can provide an
   * argument to toThrow. The argument can be a string for the error message,
   * a class for the error, or a regex that should match the error.
   *
   * Alias: .toThrowError
   */
  toThrow(message?: string | Error | RegExp): void,
  toThrowError(message?: string | Error | RegExp): void,
  /**
   * Use .toThrowErrorMatchingSnapshot to test that a function throws a error
   * matching the most recent snapshot when it is called.
   */
  toThrowErrorMatchingSnapshot(): void
};

type JestObjectType = {
  /**
   *  Disables automatic mocking in the module loader.
   *
   *  After this method is called, all `require()`s will return the real
   *  versions of each module (rather than a mocked version).
   */
  disableAutomock(): JestObjectType,
  /**
   * An un-hoisted version of disableAutomock
   */
  autoMockOff(): JestObjectType,
  /**
   * Enables automatic mocking in the module loader.
   */
  enableAutomock(): JestObjectType,
  /**
   * An un-hoisted version of enableAutomock
   */
  autoMockOn(): JestObjectType,
  /**
   * Clears the mock.calls and mock.instances properties of all mocks.
   * Equivalent to calling .mockClear() on every mocked function.
   */
  clearAllMocks(): JestObjectType,
  /**
   * Resets the state of all mocks. Equivalent to calling .mockReset() on every
   * mocked function.
   */
  resetAllMocks(): JestObjectType,
  /**
   * Removes any pending timers from the timer system.
   */
  clearAllTimers(): void,
  /**
   * The same as `mock` but not moved to the top of the expectation by
   * babel-jest.
   */
  doMock(moduleName: string, moduleFactory?: any): JestObjectType,
  /**
   * The same as `unmock` but not moved to the top of the expectation by
   * babel-jest.
   */
  dontMock(moduleName: string): JestObjectType,
  /**
   * Returns a new, unused mock function. Optionally takes a mock
   * implementation.
   */
  fn(implementation?: Function): JestMockFn,
  /**
   * Determines if the given function is a mocked function.
   */
  isMockFunction(fn: Function): boolean,
  /**
   * Given the name of a module, use the automatic mocking system to generate a
   * mocked version of the module for you.
   */
  genMockFromModule(moduleName: string): any,
  /**
   * Mocks a module with an auto-mocked version when it is being required.
   *
   * The second argument can be used to specify an explicit module factory that
   * is being run instead of using Jest's automocking feature.
   *
   * The third argument can be used to create virtual mocks -- mocks of modules
   * that don't exist anywhere in the system.
   */
  mock(
    moduleName: string,
    moduleFactory?: any,
    options?: Object
  ): JestObjectType,
  /**
   * Resets the module registry - the cache of all required modules. This is
   * useful to isolate modules where local state might conflict between tests.
   */
  resetModules(): JestObjectType,
  /**
   * Exhausts the micro-task queue (usually interfaced in node via
   * process.nextTick).
   */
  runAllTicks(): void,
  /**
   * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
   * setInterval(), and setImmediate()).
   */
  runAllTimers(): void,
  /**
   * Exhausts all tasks queued by setImmediate().
   */
  runAllImmediates(): void,
  /**
   * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
   * or setInterval() and setImmediate()).
   */
  runTimersToTime(msToRun: number): void,
  /**
   * Executes only the macro-tasks that are currently pending (i.e., only the
   * tasks that have been queued by setTimeout() or setInterval() up to this
   * point)
   */
  runOnlyPendingTimers(): void,
  /**
   * Explicitly supplies the mock object that the module system should return
   * for the specified module. Note: It is recommended to use jest.mock()
   * instead.
   */
  setMock(moduleName: string, moduleExports: any): JestObjectType,
  /**
   * Indicates that the module system should never return a mocked version of
   * the specified module from require() (e.g. that it should always return the
   * real module).
   */
  unmock(moduleName: string): JestObjectType,
  /**
   * Instructs Jest to use fake versions of the standard timer functions
   * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
   * setImmediate and clearImmediate).
   */
  useFakeTimers(): JestObjectType,
  /**
   * Instructs Jest to use the real versions of the standard timer functions.
   */
  useRealTimers(): JestObjectType,
  /**
   * Creates a mock function similar to jest.fn but also tracks calls to
   * object[methodName].
   */
  spyOn(object: Object, methodName: string): JestMockFn
};

type JestSpyType = {
  calls: JestCallsType
};

/** Runs this function after every test inside this context */
declare function afterEach(fn: Function): void;
/** Runs this function before every test inside this context */
declare function beforeEach(fn: Function): void;
/** Runs this function after all tests have finished inside this context */
declare function afterAll(fn: Function): void;
/** Runs this function before any tests have started inside this context */
declare function beforeAll(fn: Function): void;
/** A context for grouping tests together */
declare function describe(name: string, fn: Function): void;

/** An individual test unit */
declare var it: {
  /**
   * An individual test unit
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  (name: string, fn?: Function): ?Promise<void>,
  /**
   * Only run this test
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  only(name: string, fn?: Function): ?Promise<void>,
  /**
   * Skip running this test
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  skip(name: string, fn?: Function): ?Promise<void>,
  /**
   * Run the test concurrently
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  concurrent(name: string, fn?: Function): ?Promise<void>
};
declare function fit(name: string, fn: Function): ?Promise<void>;
/** An individual test unit */
declare var test: typeof it;
/** A disabled group of tests */
declare var xdescribe: typeof describe;
/** A focused group of tests */
declare var fdescribe: typeof describe;
/** A disabled individual test */
declare var xit: typeof it;
/** A disabled individual test */
declare var xtest: typeof it;

/** The expect function is used every time you want to test a value */
declare var expect: {
  /** The object that you want to make assertions against */
  (value: any): JestExpectType & JestPromiseType,
  /** Add additional Jasmine matchers to Jest's roster */
  extend(matchers: { [name: string]: JestMatcher }): void,
  /** Add a module that formats application-specific data structures. */
  addSnapshotSerializer(serializer: (input: Object) => string): void,
  assertions(expectedAssertions: number): void,
  hasAssertions(): void,
  any(value: mixed): JestAsymmetricEqualityType,
  anything(): void,
  arrayContaining(value: Array<mixed>): void,
  objectContaining(value: Object): void,
  /** Matches any received string that contains the exact expected string. */
  stringContaining(value: string): void,
  stringMatching(value: string | RegExp): void
};

// TODO handle return type
// http://jasmine.github.io/2.4/introduction.html#section-Spies
declare function spyOn(value: mixed, method: string): Object;

/** Holds all functions related to manipulating test runner */
declare var jest: JestObjectType;

/**
 * The global Jamine object, this is generally not exposed as the public API,
 * using features inside here could break in later versions of Jest.
 */
declare var jasmine: {
  DEFAULT_TIMEOUT_INTERVAL: number,
  any(value: mixed): JestAsymmetricEqualityType,
  anything(): void,
  arrayContaining(value: Array<mixed>): void,
  clock(): JestClockType,
  createSpy(name: string): JestSpyType,
  createSpyObj(
    baseName: string,
    methodNames: Array<string>
  ): { [methodName: string]: JestSpyType },
  objectContaining(value: Object): void,
  stringMatching(value: string): void
};
<commit_msg>Add jest-enzyme type definitions<commit_after>// flow-typed signature: 336a37cc59a5628d581d11f98d1d94ab
// flow-typed version: ef52b40a4e/jest_v20.x.x/flow_>=v0.33.x

type JestMockFn = {
  (...args: Array<any>): any,
  /**
   * An object for introspecting mock calls
   */
  mock: {
    /**
     * An array that represents all calls that have been made into this mock
     * function. Each call is represented by an array of arguments that were
     * passed during the call.
     */
    calls: Array<Array<any>>,
    /**
     * An array that contains all the object instances that have been
     * instantiated from this mock function.
     */
    instances: mixed
  },
  /**
   * Resets all information stored in the mockFn.mock.calls and
   * mockFn.mock.instances arrays. Often this is useful when you want to clean
   * up a mock's usage data between two assertions.
   */
  mockClear(): Function,
  /**
   * Resets all information stored in the mock. This is useful when you want to
   * completely restore a mock back to its initial state.
   */
  mockReset(): Function,
  /**
   * Removes the mock and restores the initial implementation. This is useful
   * when you want to mock functions in certain test cases and restore the
   * original implementation in others. Beware that mockFn.mockRestore only
   * works when mock was created with jest.spyOn. Thus you have to take care of
   * restoration yourself when manually assigning jest.fn().
   */
  mockRestore(): Function,
  /**
   * Accepts a function that should be used as the implementation of the mock.
   * The mock itself will still record all calls that go into and instances
   * that come from itself -- the only difference is that the implementation
   * will also be executed when the mock is called.
   */
  mockImplementation(fn: Function): JestMockFn,
  /**
   * Accepts a function that will be used as an implementation of the mock for
   * one call to the mocked function. Can be chained so that multiple function
   * calls produce different results.
   */
  mockImplementationOnce(fn: Function): JestMockFn,
  /**
   * Just a simple sugar function for returning `this`
   */
  mockReturnThis(): void,
  /**
   * Deprecated: use jest.fn(() => value) instead
   */
  mockReturnValue(value: any): JestMockFn,
  /**
   * Sugar for only returning a value once inside your mock
   */
  mockReturnValueOnce(value: any): JestMockFn
};

type JestAsymmetricEqualityType = {
  /**
   * A custom Jasmine equality tester
   */
  asymmetricMatch(value: mixed): boolean
};

type JestCallsType = {
  allArgs(): mixed,
  all(): mixed,
  any(): boolean,
  count(): number,
  first(): mixed,
  mostRecent(): mixed,
  reset(): void
};

type JestClockType = {
  install(): void,
  mockDate(date: Date): void,
  tick(milliseconds?: number): void,
  uninstall(): void
};

type JestMatcherResult = {
  message?: string | (() => string),
  pass: boolean
};

type JestMatcher = (actual: any, expected: any) => JestMatcherResult;

type JestPromiseType = {
  /**
   * Use rejects to unwrap the reason of a rejected promise so any other
   * matcher can be chained. If the promise is fulfilled the assertion fails.
   */
  rejects: JestExpectType,
  /**
   * Use resolves to unwrap the value of a fulfilled promise so any other
   * matcher can be chained. If the promise is rejected the assertion fails.
   */
  resolves: JestExpectType
};

type JestExpectType = {
  not: JestExpectType,
  /**
   * If you have a mock function, you can use .lastCalledWith to test what
   * arguments it was last called with.
   */
  lastCalledWith(...args: Array<any>): void,
  /**
   * toBe just checks that a value is what you expect. It uses === to check
   * strict equality.
   */
  toBe(value: any): void,
  /**
   * Use .toHaveBeenCalled to ensure that a mock function got called.
   */
  toBeCalled(): void,
  /**
   * Use .toBeCalledWith to ensure that a mock function was called with
   * specific arguments.
   */
  toBeCalledWith(...args: Array<any>): void,
  /**
   * Using exact equality with floating point numbers is a bad idea. Rounding
   * means that intuitive things fail.
   */
  toBeCloseTo(num: number, delta: any): void,
  /**
   * Use .toBeDefined to check that a variable is not undefined.
   */
  toBeDefined(): void,
  /**
   * Use .toBeFalsy when you don't care what a value is, you just want to
   * ensure a value is false in a boolean context.
   */
  toBeFalsy(): void,
  /**
   * To compare floating point numbers, you can use toBeGreaterThan.
   */
  toBeGreaterThan(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeGreaterThanOrEqual.
   */
  toBeGreaterThanOrEqual(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeLessThan.
   */
  toBeLessThan(number: number): void,
  /**
   * To compare floating point numbers, you can use toBeLessThanOrEqual.
   */
  toBeLessThanOrEqual(number: number): void,
  /**
   * Use .toBeInstanceOf(Class) to check that an object is an instance of a
   * class.
   */
  toBeInstanceOf(cls: Class<*>): void,
  /**
   * .toBeNull() is the same as .toBe(null) but the error messages are a bit
   * nicer.
   */
  toBeNull(): void,
  /**
   * Use .toBeTruthy when you don't care what a value is, you just want to
   * ensure a value is true in a boolean context.
   */
  toBeTruthy(): void,
  /**
   * Use .toBeUndefined to check that a variable is undefined.
   */
  toBeUndefined(): void,
  /**
   * Use .toContain when you want to check that an item is in a list. For
   * testing the items in the list, this uses ===, a strict equality check.
   */
  toContain(item: any): void,
  /**
   * Use .toContainEqual when you want to check that an item is in a list. For
   * testing the items in the list, this matcher recursively checks the
   * equality of all fields, rather than checking for object identity.
   */
  toContainEqual(item: any): void,
  /**
   * Use .toEqual when you want to check that two objects have the same value.
   * This matcher recursively checks the equality of all fields, rather than
   * checking for object identity.
   */
  toEqual(value: any): void,
  /**
   * Use .toHaveBeenCalled to ensure that a mock function got called.
   */
  toHaveBeenCalled(): void,
  /**
   * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
   * number of times.
   */
  toHaveBeenCalledTimes(number: number): void,
  /**
   * Use .toHaveBeenCalledWith to ensure that a mock function was called with
   * specific arguments.
   */
  toHaveBeenCalledWith(...args: Array<any>): void,
  /**
   * Check that an object has a .length property and it is set to a certain
   * numeric value.
   */
  toHaveLength(number: number): void,
  /**
   *
   */
  toHaveProperty(propPath: string, value?: any): void,
  /**
   * Use .toMatch to check that a string matches a regular expression.
   */
  toMatch(regexp: RegExp): void,
  /**
   * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
   */
  toMatchObject(object: Object): void,
  /**
   * This ensures that a React component matches the most recent snapshot.
   */
  toMatchSnapshot(name?: string): void,
  /**
   * Use .toThrow to test that a function throws when it is called.
   * If you want to test that a specific error gets thrown, you can provide an
   * argument to toThrow. The argument can be a string for the error message,
   * a class for the error, or a regex that should match the error.
   *
   * Alias: .toThrowError
   */
  toThrow(message?: string | Error | RegExp): void,
  toThrowError(message?: string | Error | RegExp): void,
  /**
   * Use .toThrowErrorMatchingSnapshot to test that a function throws a error
   * matching the most recent snapshot when it is called.
   */
  toThrowErrorMatchingSnapshot(): void
};

/**
 *  Plugin: jest-enzyme
 */
type EnzymeMatchersType = {
  toBeChecked(): void,
  toBeDisabled(): void,
  toBeEmpty(): void,
  toBePresent(): void,
  toContainReact(component: React$Component<*, *, *>): void,
  toHaveClassName(className: string): void,
  toHaveHTML(html: string): void,
  toHaveProp(propKey: string, propValue?: any): void,
  toHaveRef(refName: string): void,
  toHaveState(stateKey: string, stateValue?: any): void,
  toHaveStyle(styleKey: string, styleValue?: any): void,
  toHaveTagName(tagName: string): void,
  toHaveText(text: string): void,
  toIncludeText(text: string): void,
  toHaveValue(value: any): void,
  toMatchSelector(selector: string): void,
};

type JestObjectType = {
  /**
   *  Disables automatic mocking in the module loader.
   *
   *  After this method is called, all `require()`s will return the real
   *  versions of each module (rather than a mocked version).
   */
  disableAutomock(): JestObjectType,
  /**
   * An un-hoisted version of disableAutomock
   */
  autoMockOff(): JestObjectType,
  /**
   * Enables automatic mocking in the module loader.
   */
  enableAutomock(): JestObjectType,
  /**
   * An un-hoisted version of enableAutomock
   */
  autoMockOn(): JestObjectType,
  /**
   * Clears the mock.calls and mock.instances properties of all mocks.
   * Equivalent to calling .mockClear() on every mocked function.
   */
  clearAllMocks(): JestObjectType,
  /**
   * Resets the state of all mocks. Equivalent to calling .mockReset() on every
   * mocked function.
   */
  resetAllMocks(): JestObjectType,
  /**
   * Removes any pending timers from the timer system.
   */
  clearAllTimers(): void,
  /**
   * The same as `mock` but not moved to the top of the expectation by
   * babel-jest.
   */
  doMock(moduleName: string, moduleFactory?: any): JestObjectType,
  /**
   * The same as `unmock` but not moved to the top of the expectation by
   * babel-jest.
   */
  dontMock(moduleName: string): JestObjectType,
  /**
   * Returns a new, unused mock function. Optionally takes a mock
   * implementation.
   */
  fn(implementation?: Function): JestMockFn,
  /**
   * Determines if the given function is a mocked function.
   */
  isMockFunction(fn: Function): boolean,
  /**
   * Given the name of a module, use the automatic mocking system to generate a
   * mocked version of the module for you.
   */
  genMockFromModule(moduleName: string): any,
  /**
   * Mocks a module with an auto-mocked version when it is being required.
   *
   * The second argument can be used to specify an explicit module factory that
   * is being run instead of using Jest's automocking feature.
   *
   * The third argument can be used to create virtual mocks -- mocks of modules
   * that don't exist anywhere in the system.
   */
  mock(
    moduleName: string,
    moduleFactory?: any,
    options?: Object
  ): JestObjectType,
  /**
   * Resets the module registry - the cache of all required modules. This is
   * useful to isolate modules where local state might conflict between tests.
   */
  resetModules(): JestObjectType,
  /**
   * Exhausts the micro-task queue (usually interfaced in node via
   * process.nextTick).
   */
  runAllTicks(): void,
  /**
   * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
   * setInterval(), and setImmediate()).
   */
  runAllTimers(): void,
  /**
   * Exhausts all tasks queued by setImmediate().
   */
  runAllImmediates(): void,
  /**
   * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
   * or setInterval() and setImmediate()).
   */
  runTimersToTime(msToRun: number): void,
  /**
   * Executes only the macro-tasks that are currently pending (i.e., only the
   * tasks that have been queued by setTimeout() or setInterval() up to this
   * point)
   */
  runOnlyPendingTimers(): void,
  /**
   * Explicitly supplies the mock object that the module system should return
   * for the specified module. Note: It is recommended to use jest.mock()
   * instead.
   */
  setMock(moduleName: string, moduleExports: any): JestObjectType,
  /**
   * Indicates that the module system should never return a mocked version of
   * the specified module from require() (e.g. that it should always return the
   * real module).
   */
  unmock(moduleName: string): JestObjectType,
  /**
   * Instructs Jest to use fake versions of the standard timer functions
   * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
   * setImmediate and clearImmediate).
   */
  useFakeTimers(): JestObjectType,
  /**
   * Instructs Jest to use the real versions of the standard timer functions.
   */
  useRealTimers(): JestObjectType,
  /**
   * Creates a mock function similar to jest.fn but also tracks calls to
   * object[methodName].
   */
  spyOn(object: Object, methodName: string): JestMockFn
};

type JestSpyType = {
  calls: JestCallsType
};

/** Runs this function after every test inside this context */
declare function afterEach(fn: Function): void;
/** Runs this function before every test inside this context */
declare function beforeEach(fn: Function): void;
/** Runs this function after all tests have finished inside this context */
declare function afterAll(fn: Function): void;
/** Runs this function before any tests have started inside this context */
declare function beforeAll(fn: Function): void;
/** A context for grouping tests together */
declare function describe(name: string, fn: Function): void;

/** An individual test unit */
declare var it: {
  /**
   * An individual test unit
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  (name: string, fn?: Function): ?Promise<void>,
  /**
   * Only run this test
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  only(name: string, fn?: Function): ?Promise<void>,
  /**
   * Skip running this test
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  skip(name: string, fn?: Function): ?Promise<void>,
  /**
   * Run the test concurrently
   *
   * @param {string} Name of Test
   * @param {Function} Test
   */
  concurrent(name: string, fn?: Function): ?Promise<void>
};
declare function fit(name: string, fn: Function): ?Promise<void>;
/** An individual test unit */
declare var test: typeof it;
/** A disabled group of tests */
declare var xdescribe: typeof describe;
/** A focused group of tests */
declare var fdescribe: typeof describe;
/** A disabled individual test */
declare var xit: typeof it;
/** A disabled individual test */
declare var xtest: typeof it;

/** The expect function is used every time you want to test a value */
declare var expect: {
  /** The object that you want to make assertions against */
  (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType,
  /** Add additional Jasmine matchers to Jest's roster */
  extend(matchers: { [name: string]: JestMatcher }): void,
  /** Add a module that formats application-specific data structures. */
  addSnapshotSerializer(serializer: (input: Object) => string): void,
  assertions(expectedAssertions: number): void,
  hasAssertions(): void,
  any(value: mixed): JestAsymmetricEqualityType,
  anything(): void,
  arrayContaining(value: Array<mixed>): void,
  objectContaining(value: Object): void,
  /** Matches any received string that contains the exact expected string. */
  stringContaining(value: string): void,
  stringMatching(value: string | RegExp): void
};

// TODO handle return type
// http://jasmine.github.io/2.4/introduction.html#section-Spies
declare function spyOn(value: mixed, method: string): Object;

/** Holds all functions related to manipulating test runner */
declare var jest: JestObjectType;

/**
 * The global Jamine object, this is generally not exposed as the public API,
 * using features inside here could break in later versions of Jest.
 */
declare var jasmine: {
  DEFAULT_TIMEOUT_INTERVAL: number,
  any(value: mixed): JestAsymmetricEqualityType,
  anything(): void,
  arrayContaining(value: Array<mixed>): void,
  clock(): JestClockType,
  createSpy(name: string): JestSpyType,
  createSpyObj(
    baseName: string,
    methodNames: Array<string>
  ): { [methodName: string]: JestSpyType },
  objectContaining(value: Object): void,
  stringMatching(value: string): void
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    fs = require("fs"),
    file = require('gulp-file'),
    runSequence = require('run-sequence'),
    replace = require('gulp-replace'),
    babel = require('gulp-babel'),
    bc=require('babel-core');

var componentFileArr=[];

gulp.task('readFile',function(callback) {
    walk("src/component", function (path) {
        var ext = getFileExt(path);
      //  if (ext === ".html" || ext === ".css") {
            componentFileArr.push(path);
       // }
    }, function () {
        var map=arrToObj(componentFileArr);
        console.log(map)
        for(var key in map){
            var paths=map[key];
            var i= 0,len=paths.length;
            var contentArr=[];
            for(;i<len;i++){
                var path=paths[i];
                if(getFileExt(path)===".js")continue;
                contentArr.push(fileContentToStr(fs.readFileSync(path, "utf8"),getFileExt(path)===".html",path));

            }

            contentArr.push(  bc.transform(fs.readFileSync("src/component/"+key+"/index.js", "utf8"), { presets: ['es2015'] }) .code);
            file(key+".js", contentArr.join("") , { src: true })
                .pipe(gulp.dest('dev/component'))

        }
        callback();
    })
})

gulp.task('copyHTML', function () {
    return gulp.src('src/*.html')
        .pipe(replace(/<script src="component\/(.*?)\/index.js"><\/script>/gm ,function(a,b,c){
           return '<script src="component\/'+b+'.js"><\/script>';
        }))
     .pipe(gulp.dest('dev'));
});

gulp.task('copyJS', function () {
    return gulp.src('src/js/*js').pipe(babel({
        presets: ['es2015']
    })).pipe(gulp.dest('dev/js'));
});

gulp.task('fixUtil', function () {
    return gulp.src('fix/util.js').pipe(gulp.dest('dev/js'));
});

//http://www.tuicool.com/articles/rQvUbu2
gulp.task('default',  function (taskDone) {
    runSequence(
        'readFile',
        'copyHTML',
        'copyJS',
        'fixUtil',
        taskDone
    );
});

function arrToObj(arr){
    var obj={};
    for(var i= 0,len=arr.length;i<len;i++){
        var item=arr[i];
        var key=item.split("/")[2];
        if(!obj[key]){
            obj[key]=[];
        }

        obj[key].push(item);

    }
    return obj;
}

function getFileExt(filename) {
    var index1 = filename.lastIndexOf(".")
    var index2 = filename.length;
    return filename.substring(index1, index2).toLowerCase();
}

function  fileContentToStr(r ,isTpl ,path) {
    var strVar =isTpl? "tpl":"css";
    var g = "";
    var arr = r.replace(/\r/g,"").split("\n");
    g += "App.componentRes['"+path.substring(4,path.length)+"'] =\n";
    var i = 0;
    for (; i < arr.length; i++) {
        var l = '';
        if (i === 0) {
            l += "'"
        }
        ;

        if (i === arr.length - 1) {
            l += arr[i] + "';\n\n";
        } else {
            l += arr[i] + "\\\n";
        }
        g += l;
    }
    return g;
}

function walk (path, handleFile, callback) {
    var len = 1,       // 文件|目录数，起始一个
        floor = 0;     // 第x个目录？

    function done () {
        // 完成任务, 运行回调函数
        if (--len === 0) {
            callback();
        }
    }

    function composeErr (err) {
        // 错误处理
        console.log('stat error');
        done();  // 以错误内容完成
    }

    function composeDir (path) {
        // 目录处理
        floor++;
        fs.readdir(path, function (err, files) {
            if (err) {
                console.log('read dir error');
                done();  // 目录完成
                return;
            }
            len += files.length;  // 子文件|子目录计数
            files.forEach(function (filename) {
                compose(path + '/' + filename);  // 子内容新的操作
            });
            done();  // 目录完成
        });
    }

    function composeFile (path) {
        // 文件处理
        handleFile(path, floor);
        done();  // 文件完成
    }

    function compose (path) {
        //同步
        fs.stat(path, function (err, stats) {
            if (err) {
                composeErr(err);
                return;
            }

            if (stats.isDirectory()) {
                composeDir(path);
                return;
            }

            composeFile(path);
        });
    }

    compose(path);
}

//todo es6转换<commit_msg>remove todo tag<commit_after>var gulp = require('gulp'),
    fs = require("fs"),
    file = require('gulp-file'),
    runSequence = require('run-sequence'),
    replace = require('gulp-replace'),
    babel = require('gulp-babel'),
    bc=require('babel-core');

var componentFileArr=[];

gulp.task('readFile',function(callback) {
    walk("src/component", function (path) {
        var ext = getFileExt(path);
      //  if (ext === ".html" || ext === ".css") {
            componentFileArr.push(path);
       // }
    }, function () {
        var map=arrToObj(componentFileArr);
        console.log(map)
        for(var key in map){
            var paths=map[key];
            var i= 0,len=paths.length;
            var contentArr=[];
            for(;i<len;i++){
                var path=paths[i];
                if(getFileExt(path)===".js")continue;
                contentArr.push(fileContentToStr(fs.readFileSync(path, "utf8"),getFileExt(path)===".html",path));

            }

            contentArr.push(  bc.transform(fs.readFileSync("src/component/"+key+"/index.js", "utf8"), { presets: ['es2015'] }) .code);
            file(key+".js", contentArr.join("") , { src: true })
                .pipe(gulp.dest('dev/component'))

        }
        callback();
    })
})

gulp.task('copyHTML', function () {
    return gulp.src('src/*.html')
        .pipe(replace(/<script src="component\/(.*?)\/index.js"><\/script>/gm ,function(a,b,c){
           return '<script src="component\/'+b+'.js"><\/script>';
        }))
     .pipe(gulp.dest('dev'));
});

gulp.task('copyJS', function () {
    return gulp.src('src/js/*js').pipe(babel({
        presets: ['es2015']
    })).pipe(gulp.dest('dev/js'));
});

gulp.task('fixUtil', function () {
    return gulp.src('fix/util.js').pipe(gulp.dest('dev/js'));
});

//http://www.tuicool.com/articles/rQvUbu2
gulp.task('default',  function (taskDone) {
    runSequence(
        'readFile',
        'copyHTML',
        'copyJS',
        'fixUtil',
        taskDone
    );
});

function arrToObj(arr){
    var obj={};
    for(var i= 0,len=arr.length;i<len;i++){
        var item=arr[i];
        var key=item.split("/")[2];
        if(!obj[key]){
            obj[key]=[];
        }

        obj[key].push(item);

    }
    return obj;
}

function getFileExt(filename) {
    var index1 = filename.lastIndexOf(".")
    var index2 = filename.length;
    return filename.substring(index1, index2).toLowerCase();
}

function  fileContentToStr(r ,isTpl ,path) {
    var strVar =isTpl? "tpl":"css";
    var g = "";
    var arr = r.replace(/\r/g,"").split("\n");
    g += "App.componentRes['"+path.substring(4,path.length)+"'] =\n";
    var i = 0;
    for (; i < arr.length; i++) {
        var l = '';
        if (i === 0) {
            l += "'"
        }
        ;

        if (i === arr.length - 1) {
            l += arr[i] + "';\n\n";
        } else {
            l += arr[i] + "\\\n";
        }
        g += l;
    }
    return g;
}

function walk (path, handleFile, callback) {
    var len = 1,       // 文件|目录数，起始一个
        floor = 0;     // 第x个目录？

    function done () {
        // 完成任务, 运行回调函数
        if (--len === 0) {
            callback();
        }
    }

    function composeErr (err) {
        // 错误处理
        console.log('stat error');
        done();  // 以错误内容完成
    }

    function composeDir (path) {
        // 目录处理
        floor++;
        fs.readdir(path, function (err, files) {
            if (err) {
                console.log('read dir error');
                done();  // 目录完成
                return;
            }
            len += files.length;  // 子文件|子目录计数
            files.forEach(function (filename) {
                compose(path + '/' + filename);  // 子内容新的操作
            });
            done();  // 目录完成
        });
    }

    function composeFile (path) {
        // 文件处理
        handleFile(path, floor);
        done();  // 文件完成
    }

    function compose (path) {
        //同步
        fs.stat(path, function (err, stats) {
            if (err) {
                composeErr(err);
                return;
            }

            if (stats.isDirectory()) {
                composeDir(path);
                return;
            }

            composeFile(path);
        });
    }

    compose(path);
}<|endoftext|>


<commit_before>//This currently throws a stack underflow, and thus commented out. Contract is correctly deployed, but createHumanStandardToken throws underflow.
//Replicated under testrpc and debugging to fix this.

contract("HumanStandardTokenFactory", function(accounts) {

    it("Verify A Human Standard Token Once Deployed", function(done) {
        var factory = null;
        var newTokenAddr = null;
        HumanStandardTokenFactory.new().then(function(ctr) {
        factory = ctr;

        return factory.createHumanStandardToken.call(100000, "Simon Bucks", 2, "SBX", {from: accounts[0]});
        }).then(function(tokenContractAddr) {
            newTokenAddr = tokenContractAddr;
            return factory.createHumanStandardToken(100000, "Simon Bucks", 2, "SBX", {from: accounts[0]});
        }).then(function(result) {
            return factory.verifyHumanStandardToken.call(newTokenAddr, {from: accounts[0]});
        }).then(function (result) {
            assert.strictEqual(result, true);
            return factory.isHumanToken.call(newTokenAddr, {from: accounts[0]}); //use other check as well.
        }).then(function (result) {
            assert.strictEqual(result, true);
            done();
        }).catch(done);
    });
});
<commit_msg>Clarified factory test<commit_after>//This currently throws a stack underflow, and thus commented out. Contract is correctly deployed, but createHumanStandardToken throws underflow.
//Replicated under testrpc and debugging to fix this.

contract("HumanStandardTokenFactory", function(accounts) {

    it("Verify a Human Standard Token once deployed using both verification functions.", function(done) {
        var factory = null;
        var newTokenAddr = null;
        HumanStandardTokenFactory.new().then(function(ctr) {
        factory = ctr;

        return factory.createHumanStandardToken.call(100000, "Simon Bucks", 2, "SBX", {from: accounts[0]});
        }).then(function(tokenContractAddr) {
            newTokenAddr = tokenContractAddr;
            return factory.createHumanStandardToken(100000, "Simon Bucks", 2, "SBX", {from: accounts[0]});
        }).then(function(result) {
            return factory.verifyHumanStandardToken.call(newTokenAddr, {from: accounts[0]});
        }).then(function (result) {
            assert.strictEqual(result, true);
            return factory.isHumanToken.call(newTokenAddr, {from: accounts[0]});
        }).then(function (result) {
            assert.strictEqual(result, true);
            done();
        }).catch(done);
    });
});
<|endoftext|>


<commit_before>// # Excerpt Helper
// Usage: `{{excerpt}}`, `{{excerpt words="50"}}`, `{{excerpt characters="256"}}`
//
// Attempts to remove all HTML from the string, and then shortens the result according to the provided option.
//
// Defaults to words="50"

var hbs             = require('express-hbs'),
    _               = require('lodash'),
    downsize        = require('downsize'),
    excerpt;

excerpt = function (options) {
    var truncateOptions = (options || {}).hash || {},
        excerpt;

    truncateOptions = _.pick(truncateOptions, ['words', 'characters']);
    _.keys(truncateOptions).map(function (key) {
        truncateOptions[key] = parseInt(truncateOptions[key], 10);
    });

    /*jslint regexp:true */
    excerpt = String(this.html);
    // Strip inline and bottom footnotes
    excerpt = excerpt.replace(/.*?<\/a>/gi, '');
    excerpt = excerpt.replace(/

.*?<\/ol><\/div>/, '');
    // Strip other html
    excerpt = excerpt.replace(/<\/?[^>]+>/gi, '');
    excerpt = excerpt.replace(/(\r\n|\n|\r)+/gm, ' ');
    /*jslint regexp:false */

    if (!truncateOptions.words && !truncateOptions.characters) {
        truncateOptions.words = 50;
    }

    return new hbs.handlebars.SafeString(
        downsize(excerpt, truncateOptions)
    );
};

module.exports = excerpt;
<commit_msg>Update excerpt helper to properly filter HTML footnotes<commit_after>// # Excerpt Helper
// Usage: `{{excerpt}}`, `{{excerpt words="50"}}`, `{{excerpt characters="256"}}`
//
// Attempts to remove all HTML from the string, and then shortens the result according to the provided option.
//
// Defaults to words="50"

var hbs             = require('express-hbs'),
    _               = require('lodash'),
    downsize        = require('downsize'),
    excerpt;

excerpt = function (options) {
    var truncateOptions = (options || {}).hash || {},
        excerpt;

    truncateOptions = _.pick(truncateOptions, ['words', 'characters']);
    _.keys(truncateOptions).map(function (key) {
        truncateOptions[key] = parseInt(truncateOptions[key], 10);
    });

    /*jslint regexp:true */
    excerpt = String(this.html);
    // Strip inline and bottom footnotes
    excerpt = excerpt.replace(/.*?<\/a>/gi, '');
    excerpt = excerpt.replace(/

.*?<\/ol><\/div>/, '');
    // Strip other html
    excerpt = excerpt.replace(/<\/?[^>]+>/gi, '');
    excerpt = excerpt.replace(/(\r\n|\n|\r)+/gm, ' ');
    /*jslint regexp:false */

    if (!truncateOptions.words && !truncateOptions.characters) {
        truncateOptions.words = 50;
    }

    return new hbs.handlebars.SafeString(
        downsize(excerpt, truncateOptions)
    );
};

module.exports = excerpt;
<|endoftext|>


<commit_before>var camera, scene, renderer, mesh;

function init () {
  var tunnel = new THREE.BoxGeometry( 600, 1200, 3000 );

  var material = new THREE.MeshBasicMaterial({
    color: 0xaffff,
    opacity: 0.5,
    wireframe: true,
    transparent: true
  })

  var tunnelMesh = new THREE.Mesh( tunnel, material );
  tunnelMesh.position.y = 300;
  tunnelMesh.position.z = -1200;

  //

  renderer = new THREE.WebGLRenderer({
    alpha: true
  });
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  //

  camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
    window.innerHeight, 1, 4000 );

  camera.position.y = 400;
  camera.position.z = 100;

  //

  scene = new THREE.Scene();
  scene.add( tunnelMesh );

  window.addEventListener( 'resize', onWindowResize, false );
  document.addEventListener( 'keyup', onKeyUp, false);

  startObstacles();
  addVideoFeed();
}

function startObstacles () {
  setInterval(function(){
    var geometry = new THREE.BoxGeometry( 100, 100, 100 );

    var material = new THREE.MeshBasicMaterial({
      color: 0xaff00,
      wireframe: true,
      wireframeLinewidth: 2
    });

    mesh = new THREE.Mesh( geometry, material );
    mesh.position.y = 400;
    mesh.position.z = -1500;

    var position = {
        x: mesh.position.x,
        y: mesh.position.y,
        z: mesh.position.z
      },
      target = {
        x: 0,
        y: 0,
        z: 3000
      };

    scene.add( mesh );

    doTween(position, target, mesh, TWEEN.Easing.Circular.Out, 100000);

  }, Math.random() * 100 + 3000);
}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

  requestAnimationFrame( animate );

  TWEEN.update();

  renderer.render( scene, camera );

}

var cameraMaxY = 400,
  cameraMinY = 200,
  cameraMaxX = 300,
  cameraMinX = -100;

function onKeyUp (event) {
  var increment = 100,
    position = {
      x: camera.position.x,
      y: camera.position.y,
      z: camera.position.z
    },
    target = {
      x: 0,
      y: 0,
      z: 0
    },
    tween;

  event.preventDefault();

  switch(event.keyCode) {
    case 38: //Up
      if (camera.position.y < cameraMaxY) {
        target.y = cameraMaxY;
        target.z = camera.position.z;

        doTween(position, target, camera, TWEEN.Easing.Circular.Out, 100);
      }
      break;

    case 40: //Down
      if (camera.position.y > cameraMinY) {
        target.y = cameraMinY;
        target.z = camera.position.z;

        doTween(position, target, camera, TWEEN.Easing.Circular.Out, 100);
      }
      break;

    // case 39: //Right
    //   break;

    // case 37:// left
    //   break;
  }

}

function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

function videoSuccess (stream) {
  video.src = stream;
  video.play();
}

function videoError (err) {
  console.log(err);
}

function sourceSelected (videoSource) {
  var constraints = {
    // audio: {
    //   optional: [{sourceId: audioSource}]
    // },
    video: {
      optional: [{sourceId: videoSource}]
    }
  };

  navigator.getUserMedia(constraints, videoSuccess, videoError);
}

function addVideoFeed () {
  var videoSource = null,
    video = document.getElementById("video"),
    errBack = function(error) {
      console.log("Video capture error: ", error.code);
    };

    var getUserMedia = navigator.getUserMedia ? function(a, b, c) {
          navigator.getUserMedia(a, b, c);
        } : (navigator.webkitGetUserMedia ? function(a, b, c) {
              navigator.webkitGetUserMedia(a, b, c);
            } : null);

  MediaStreamTrack.getSources(function(sourceInfos) {
    var sourceInfo,
      video;

    for (var i = 0; i != sourceInfos.length; ++i) {
      sourceInfo = sourceInfos[i];

      if (sourceInfo.kind === 'video') {
        console.log(sourceInfo);
        videoSource = sourceInfo.id;

      } else {
        console.log('Some other kind of source: ', sourceInfo);
      }
    }

    video = {
      optional: [{sourceId: videoSource}]
    };

    getUserMedia.call(this, {video: video}, function(stream) {
      console.log("getUserMedia");
      // window.stream = stream; // make stream available to console
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }, errBack);

  });

}

init();
animate();
<commit_msg>almost there<commit_after>var camera, scene, renderer, mesh;

function init () {
  var tunnel = new THREE.BoxGeometry( 600, 1200, 3000 );

  var material = new THREE.MeshBasicMaterial({
    color: 0xaffff,
    opacity: 0.5,
    wireframe: true,
    transparent: true
  })

  var tunnelMesh = new THREE.Mesh( tunnel, material );
  tunnelMesh.position.y = 300;
  tunnelMesh.position.z = -1200;

  //

  renderer = new THREE.WebGLRenderer({
    alpha: true
  });
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  //

  camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
    window.innerHeight, 1, 4000 );

  camera.position.y = 400;
  camera.position.z = 100;

  //

  scene = new THREE.Scene();
  scene.add( tunnelMesh );

  window.addEventListener( 'resize', onWindowResize, false );
  document.addEventListener( 'keyup', onKeyUp, false);

  startObstacles();
  addVideoFeed();
}

function startObstacles () {
  setInterval(function(){
    var geometry = new THREE.BoxGeometry( 100, 100, 100 );

    var material = new THREE.MeshBasicMaterial({
      color: 0xaff00,
      wireframe: true,
      wireframeLinewidth: 2
    });

    mesh = new THREE.Mesh( geometry, material );
    mesh.position.y = 400;
    mesh.position.z = -1500;

    var position = {
        x: mesh.position.x,
        y: mesh.position.y,
        z: mesh.position.z
      },
      target = {
        x: 0,
        y: 0,
        z: 3000
      };

    scene.add( mesh );

    doTween(position, target, mesh, TWEEN.Easing.Circular.Out, 100000);

  }, Math.random() * 100 + 3000);
}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

  requestAnimationFrame( animate );

  TWEEN.update();

  renderer.render( scene, camera );

}

var cameraMaxY = 400,
  cameraMinY = 200,
  cameraMaxX = 300,
  cameraMinX = -100;

function onKeyUp (event) {
  var increment = 100,
    position = {
      x: camera.position.x,
      y: camera.position.y,
      z: camera.position.z
    },
    target = {
      x: 0,
      y: 0,
      z: 0
    },
    tween;

  event.preventDefault();

  switch(event.keyCode) {
    case 38: //Up
      if (camera.position.y < cameraMaxY) {
        target.y = cameraMaxY;
        target.z = camera.position.z;

        doTween(position, target, camera, TWEEN.Easing.Circular.Out, 100);
      }
      break;

    case 40: //Down
      if (camera.position.y > cameraMinY) {
        target.y = cameraMinY;
        target.z = camera.position.z;

        doTween(position, target, camera, TWEEN.Easing.Circular.Out, 100);
      }
      break;

    // case 39: //Right
    //   break;

    // case 37:// left
    //   break;
  }

}

function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

function videoSuccess (stream) {
  video.src = stream;
  video.play();
}

function videoError (err) {
  console.log(err);
}

function sourceSelected (videoSource) {
  var constraints = {
    // audio: {
    //   optional: [{sourceId: audioSource}]
    // },
    video: {
      optional: [{sourceId: videoSource}]
    }
  };

  navigator.getUserMedia(constraints, videoSuccess, videoError);
}

function addVideoFeed () {
  var videoSource = null,
    video = document.getElementById("video"),
    errBack = function(error) {
      console.log("Video capture error: ", error.code);
    };

    var getUserMedia = navigator.getUserMedia ? function(a, b, c) {
          navigator.getUserMedia(a, b, c);
        } : (navigator.webkitGetUserMedia ? function(a, b, c) {
              navigator.webkitGetUserMedia(a, b, c);
            } : null);

  MediaStreamTrack.getSources(function(sourceInfos) {
    var sourceInfo,
      video;

    for (var i = 0; i != sourceInfos.length; ++i) {
      sourceInfo = sourceInfos[i];

      if (sourceInfo.kind === 'video') {
        console.log(sourceInfo);
        videoSource = sourceInfo.id;

      } else {
        console.log('Some other kind of source: ', sourceInfo);
      }
    }

    getUserMedia.call(this, {
      video: {
        optional: [{sourceId: videoSource}]
      }
    }, function(stream) {
      console.log("getUserMedia");
      console.log(video);
      // window.stream = stream; // make stream available to console
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }, errBack);

  });

}

init();
animate();
<|endoftext|>