<commit_before>/*jslint browser:true */

/*globals $, d3, tangelo */

var color = null;
var force = null;
var graph = null;
var svg = null;
var width = 0;
var height = 0;

var enron = {};
enron.date = null;
enron.range = null;
enron.center = null;
enron.degree = null;
enron.host = null;

function stringifyDate(d) {
    "use strict";

    return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}

function displayDate(d) {
    "use strict";

    return tangelo.date.monthNames()[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
}

function updateGraph() {
    "use strict";

    var center,
        data,
        end_date,
        degree,
        hops,
        start_date;

    d3.select("#update")
        .attr("disabled", true)
        .text("Updating...");

    // Construct a Javascript date object from the date slider.
    start_date = new Date(enron.date.slider("value"));

    // Create another date that is ahead of the start date by the number of days
    // indicated by the slider (i.e., advanced from that date by the number of
    // milliseconds in that many days).
    end_date = new Date(start_date.getTime() + enron.range.slider("value") * 86400 * 1000);

    center = enron.center.val();

    hops = enron.degree.spinner("value");

    data = {
        start_time: stringifyDate(start_date),
        end_time: stringifyDate(end_date),
        center: center,
        degree: hops
    };

    $.ajax({
        url: "service/emailers/" + enron.host + "/xdata/enron",
        data: data,
        dataType: "json",
        success: function (resp) {
            var enter,
                link,
                map,
                node;

            d3.select("#update")
                .attr("disabled", null)
                .text("Update");

            if (resp.error !== null) {
                console.log("error: " + resp.error);
                return;
            }

            // Save the last iteration of node data, so we can transfer the
            // positions to the new iteration.
            map = {};
            $.each(force.nodes(), function (i, v) {
                map[v.email] = v;
            });

            graph = resp.result;
            $.each(graph.nodes, function (i, v) {
                if (map.hasOwnProperty(v.email)) {
                    graph.nodes[i].x = map[v.email].x;
                    graph.nodes[i].y = map[v.email].y;
                }
            });

            console.log("Got " + graph.nodes.length + " nodes");
            console.log("Got " + graph.edges.length + " edges");

            force.nodes(graph.nodes)
                .links(graph.edges)
                .start();

            link = svg.select("g#links")
                .selectAll(".link")
                .data(graph.edges, function (d) {
                    return d.id;
                });

            link.enter().append("line")
                .classed("link", true);

            link.exit()
                .transition()
                .duration(1000)
                .attr("x1", width)
                .attr("x2", width)
                .attr("y1", height/2)
                .attr("y2", height/2)
                .style("opacity", 0.0)
                .remove();

            node = svg.select("g#nodes")
                .selectAll(".node")
                .data(graph.nodes, function (d) { return d.email; });

            enter = node.enter().append("circle")
                .classed("node", true)
                .attr("r", 0)
                .style("opacity", 0.0)
                .style("fill", function (d) {
                    return color(d.distance);
                });
            enter.transition()
                .duration(500)
                .attr("r", 5)
                .style("opacity", 1.0);

            enter.call(force.drag)
                .append("title")
                .text(function (d) {
                    return d.email || "(no email address)";
                });

            node.exit()
                .transition()
                .duration(1000)
                .style("opacity", 0.0)
                .attr("cx", width)
                .attr("cy", height/2)
                .attr("r", 0.0)
                .remove();

            force.on("tick", function () {
                link.attr("x1", function (d) { return d.source.x; })
                    .attr("y1", function (d) { return d.source.y; })
                    .attr("x2", function (d) { return d.target.x; })
                    .attr("y2", function (d) { return d.target.y; });

                node.attr("cx", function (d) { return d.x; })
                    .attr("cy", function (d) { return d.y; });
            });
        }
    });
}

function toggleAnimation() {
    anim = d3.select("#animate");
    if (anim.text() === "Animate") {
        anim.text("Stop animation")
            .classed("btn-success", false)
            .classed("btn-warning", true);
    } else {
        anim.text("Animate")
            .classed("btn-success", true)
            .classed("brn-warning", false);
    }
}

window.onload = function () {
    "use strict";

    tangelo.util.defaults("defaults.json", function (defaults) {
        enron.host = (defaults && defaults.get("host")) || "mongo";

        console.log("enron.host: " + enron.host);

        svg = d3.select("svg");

        width = $(window).width();
        height = $(window).height();
        force = d3.layout.force()
            .charge(-240)
            .linkDistance(50)
            .gravity(0.5)
            .size([width, height]);

        color = d3.scale.category20();

        // Activate the jquery controls.
        enron.date = $("#date");
        enron.range = $("#range");
        enron.center = $("#center");
        enron.degree = $("#degree");

        enron.date.slider({
            min: new Date("January 1, 1998").getTime(),
            max: new Date("December 31, 2002").getTime(),
            value: new Date("December 13, 2000").getTime(),
            step: 86400,
            slide: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            },
            change: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            }
        });
        enron.date.slider("value", enron.date.slider("value"));

        enron.range.slider({
            min: 1,
            max: 6 * 7,
            value: 3,
            slide: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            },
            change: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            }
        });
        enron.range.slider("value", enron.range.slider("value"));

        enron.center.val("phillip.allen@enron.com");

        enron.degree.spinner({
            min: 1,
            max: 10
        });
        enron.degree.spinner("value", 2);

        d3.select("#update")
            .on("click", updateGraph);

        d3.select("#animate")
            .on("click", toggleAnimation);
    });
};
<commit_msg>Adding animation button.<commit_after>/*jslint browser:true */

/*globals $, d3, tangelo */

var color = null;
var force = null;
var graph = null;
var svg = null;
var width = 0;
var height = 0;

var enron = {};
enron.date = null;
enron.range = null;
enron.center = null;
enron.degree = null;
enron.host = null;

function stringifyDate(d) {
    "use strict";

    return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}

function displayDate(d) {
    "use strict";

    return tangelo.date.monthNames()[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
}

function updateGraph() {
    "use strict";

    var center,
        data,
        end_date,
        degree,
        hops,
        change_button,
        start_date,
        update;

    update = d3.select("#update");
    change_button = !update.attr("disabled");

    if (change_button) {
        update.attr("disabled", true)
            .text("Updating...");
    }

    // Construct a Javascript date object from the date slider.
    start_date = new Date(enron.date.slider("value"));

    // Create another date that is ahead of the start date by the number of days
    // indicated by the slider (i.e., advanced from that date by the number of
    // milliseconds in that many days).
    end_date = new Date(start_date.getTime() + enron.range.slider("value") * 86400 * 1000);

    center = enron.center.val();

    hops = enron.degree.spinner("value");

    data = {
        start_time: stringifyDate(start_date),
        end_time: stringifyDate(end_date),
        center: center,
        degree: hops
    };

    $.ajax({
        url: "service/emailers/" + enron.host + "/xdata/enron",
        data: data,
        dataType: "json",
        success: function (resp) {
            var angle,
                enter,
                link,
                map,
                newidx,
                node,
                tau;

            if (change_button) {
                d3.select("#update")
                    .attr("disabled", null)
                    .text("Update");
            }

            if (resp.error !== null) {
                console.log("error: " + resp.error);
                return;
            }

            // Save the last iteration of node data, so we can transfer the
            // positions to the new iteration.
            map = {};
            $.each(force.nodes(), function (i, v) {
                map[v.email] = v;
            });

            graph = resp.result;
            newidx = [];
            $.each(graph.nodes, function (i, v) {
                if (map.hasOwnProperty(v.email)) {
                    graph.nodes[i].x = map[v.email].x;
                    graph.nodes[i].y = map[v.email].y;
                } else {
                    newidx.push(i);
                }
            });

            tau = 2 * Math.PI;
            angle = tau / newidx.length;
            $.each(newidx, function (i, v) {
                graph.nodes[i].x = (width/4) * Math.cos(i * angle) + (width/2);
                graph.nodes[i].y = (height/4) * Math.sin(i * angle) + (height/2);
                console.log("(x, y) = (" + graph.nodes[i].x + ", " + graph.nodes[i].y + ")");
            });

            console.log("Got " + graph.nodes.length + " nodes");
            console.log("Got " + graph.edges.length + " edges");

            force.nodes(graph.nodes)
                .links(graph.edges)
                .start();

            link = svg.select("g#links")
                .selectAll(".link")
                .data(graph.edges, function (d) {
                    return d.id;
                });

            link.enter().append("line")
                .classed("link", true)
                .style("opacity", 0.0)
                .transition()
                .duration(500)
                .style("opacity", 1.0);

            link.exit()
                .transition()
                .duration(1000)
                .attr("x1", width)
                .attr("x2", width)
                .attr("y1", height/2)
                .attr("y2", height/2)
                .style("opacity", 0.0)
                .remove();

            node = svg.select("g#nodes")
                .selectAll(".node")
                .data(graph.nodes, function (d) { return d.email; });

            enter = node.enter().append("circle")
                .classed("node", true)
                .attr("r", 0)
                .style("opacity", 0.0)
                .style("fill", function (d) {
                    return color(d.distance);
                });
            enter.transition()
                .duration(500)
                .attr("r", 5)
                .style("opacity", 1.0);

            enter.call(force.drag)
                .append("title")
                .text(function (d) {
                    return d.email || "(no email address)";
                });

            node.exit()
                .transition()
                .duration(1000)
                .style("opacity", 0.0)
                .attr("cx", width)
                .attr("cy", height/2)
                .attr("r", 0.0)
                .remove();

            force.on("tick", function () {
                link.attr("x1", function (d) { return d.source.x; })
                    .attr("y1", function (d) { return d.source.y; })
                    .attr("x2", function (d) { return d.target.x; })
                    .attr("y2", function (d) { return d.target.y; });

                node.attr("cx", function (d) { return d.x; })
                    .attr("cy", function (d) { return d.y; });
            });
        }
    });
}

function advanceTimer() {
    "use strict";

    var value;

    console.log("yay");

    value = enron.date.slider("value") + 86400e3;
    enron.date.slider("value", value);
    //enron.date.slider("option", "change")(null, {handle: enron.date.slider, value: value});
    //
    updateGraph();
}

var timeout = null;
function toggleAnimation() {
    anim = d3.select("#animate");
    update = d3.select("#update");

    if (anim.text() === "Animate") {
        anim.text("Stop animation")
            .classed("btn-success", false)
            .classed("btn-warning", true);
        update.attr("disabled", true);

        timeout = setInterval(advanceTimer, 1000);
    } else {
        anim.text("Animate")
            .classed("btn-success", true)
            .classed("brn-warning", false);
        update.attr("disabled", null);

        clearInterval(timeout);
    }
}

window.onload = function () {
    "use strict";

    tangelo.util.defaults("defaults.json", function (defaults) {
        enron.host = (defaults && defaults.get("host")) || "mongo";

        console.log("enron.host: " + enron.host);

        svg = d3.select("svg");

        width = $(window).width();
        height = $(window).height();
        force = d3.layout.force()
            .charge(-240)
            .linkDistance(50)
            .gravity(0.5)
            .size([width, height]);

        color = d3.scale.category20();

        // Activate the jquery controls.
        enron.date = $("#date");
        enron.range = $("#range");
        enron.center = $("#center");
        enron.degree = $("#degree");

        enron.date.slider({
            min: new Date("January 1, 1998").getTime(),
            max: new Date("December 31, 2002").getTime(),
            value: new Date("December 13, 2000").getTime(),
            step: 86400,
            slide: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            },
            change: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            }
        });
        enron.date.slider("value", enron.date.slider("value"));

        enron.range.slider({
            min: 1,
            max: 6 * 7,
            value: 3,
            slide: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            },
            change: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            }
        });
        enron.range.slider("value", enron.range.slider("value"));

        enron.center.val("phillip.allen@enron.com");

        enron.degree.spinner({
            min: 1,
            max: 10
        });
        enron.degree.spinner("value", 2);

        d3.select("#update")
            .on("click", updateGraph);

        d3.select("#animate")
            .on("click", toggleAnimation);
    });
};
<|endoftext|>


<commit_before>/*jslint browser:true */

/*globals $, d3, tangelo */

var color = null;
var force = null;
var graph = null;
var svg = null;
var width = 0;
var height = 0;

var enron = {};
enron.date = null;
enron.range = null;
enron.center = null;
enron.degree = null;
enron.host = null;

function stringifyDate(d) {
    "use strict";

    return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}

function displayDate(d) {
    "use strict";

    return tangelo.date.monthNames()[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
}

function updateGraph() {
    "use strict";

    var center,
        data,
        end_date,
        degree,
        hops,
        change_button,
        start_date,
        update;

    update = d3.select("#update");
    change_button = !update.attr("disabled");

    if (change_button) {
        update.attr("disabled", true)
            .text("Updating...");
    }

    // Construct a Javascript date object from the date slider.
    start_date = new Date(enron.date.slider("value"));

    // Create another date that is ahead of the start date by the number of days
    // indicated by the slider (i.e., advanced from that date by the number of
    // milliseconds in that many days).
    end_date = new Date(start_date.getTime() + enron.range.slider("value") * 86400 * 1000);

    center = enron.center.val();

    hops = enron.degree.spinner("value");

    data = {
        start_time: stringifyDate(start_date),
        end_time: stringifyDate(end_date),
        center: center,
        degree: hops
    };

    $.ajax({
        url: "service/emailers/" + enron.host + "/xdata/enron",
        data: data,
        dataType: "json",
        success: function (resp) {
            var angle,
                enter,
                link,
                map,
                newidx,
                node,
                tau;

            if (change_button) {
                d3.select("#update")
                    .attr("disabled", null)
                    .text("Update");
            }

            if (resp.error !== null) {
                console.log("error: " + resp.error);
                return;
            }

            // Save the last iteration of node data, so we can transfer the
            // positions to the new iteration.
            map = {};
            $.each(force.nodes(), function (i, v) {
                map[v.email] = v;
            });

            graph = resp.result;
            newidx = [];
            $.each(graph.nodes, function (i, v) {
                if (map.hasOwnProperty(v.email)) {
                    graph.nodes[i].x = map[v.email].x;
                    graph.nodes[i].y = map[v.email].y;
                } else {
                    newidx.push(i);
                }
            });

            tau = 2 * Math.PI;
            angle = tau / newidx.length;
            $.each(newidx, function (i, v) {
                graph.nodes[i].x = (width/4) * Math.cos(i * angle) + (width/2);
                graph.nodes[i].y = (height/4) * Math.sin(i * angle) + (height/2);
            });

            console.log("Got " + graph.nodes.length + " nodes");
            console.log("Got " + graph.edges.length + " edges");

            force.nodes(graph.nodes)
                .links(graph.edges)
                .start();

            link = svg.select("g#links")
                .selectAll(".link")
                .data(graph.edges, function (d) {
                    return d.id;
                });

            link.enter().append("line")
                .classed("link", true)
                .style("opacity", 0.0)
                .transition()
                .duration(500)
                .style("opacity", 1.0);

            link.exit()
                .transition()
                .duration(1000)
                .attr("x1", width)
                .attr("x2", width)
                .attr("y1", height/2)
                .attr("y2", height/2)
                .style("opacity", 0.0)
                .remove();

            node = svg.select("g#nodes")
                .selectAll(".node")
                .data(graph.nodes, function (d) { return d.email; });

            enter = node.enter().append("circle")
                .classed("node", true)
                .attr("r", 0)
                .style("opacity", 0.0)
                .style("fill", function (d) {
                    return color(d.distance);
                });
            enter.transition()
                .duration(500)
                .attr("r", 5)
                .style("opacity", 1.0);

            enter.call(force.drag)
                .append("title")
                .text(function (d) {
                    return d.email || "(no email address)";
                });

            node.exit()
                .transition()
                .duration(1000)
                .style("opacity", 0.0)
                .attr("cx", width)
                .attr("cy", height/2)
                .attr("r", 0.0)
                .remove();

            force.on("tick", function () {
                link.attr("x1", function (d) { return d.source.x; })
                    .attr("y1", function (d) { return d.source.y; })
                    .attr("x2", function (d) { return d.target.x; })
                    .attr("y2", function (d) { return d.target.y; });

                node.attr("cx", function (d) { return d.x; })
                    .attr("cy", function (d) { return d.y; });
            });
        }
    });
}

function advanceTimer() {
    "use strict";

    var value;

    value = enron.date.slider("value") + 86400e3;
    enron.date.slider("value", value);

    updateGraph();
}

var timeout = null;
function toggleAnimation() {
    anim = d3.select("#animate");
    update = d3.select("#update");

    if (anim.text() === "Animate") {
        anim.text("Stop animation")
            .classed("btn-success", false)
            .classed("btn-warning", true);
        update.attr("disabled", true);

        timeout = setInterval(advanceTimer, 1000);
    } else {
        anim.text("Animate")
            .classed("btn-success", true)
            .classed("brn-warning", false);
        update.attr("disabled", null);

        clearInterval(timeout);
    }
}

window.onload = function () {
    "use strict";

    tangelo.util.defaults("defaults.json", function (defaults) {
        enron.host = (defaults && defaults.get("host")) || "mongo";

        svg = d3.select("svg");

        width = $(window).width();
        height = $(window).height();
        force = d3.layout.force()
            .charge(-240)
            .linkDistance(50)
            .gravity(0.5)
            .size([width, height]);

        color = d3.scale.category20();

        // Activate the jquery controls.
        enron.date = $("#date");
        enron.range = $("#range");
        enron.center = $("#center");
        enron.degree = $("#degree");

        enron.date.slider({
            min: new Date("January 1, 1998").getTime(),
            max: new Date("December 31, 2002").getTime(),
            value: new Date("December 13, 2000").getTime(),
            step: 86400,
            slide: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            },
            change: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            }
        });
        enron.date.slider("value", enron.date.slider("value"));

        enron.range.slider({
            min: 1,
            max: 6 * 7,
            value: 3,
            slide: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            },
            change: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            }
        });
        enron.range.slider("value", enron.range.slider("value"));

        enron.center.val("phillip.allen@enron.com");

        enron.degree.spinner({
            min: 1,
            max: 10
        });
        enron.degree.spinner("value", 2);

        d3.select("#update")
            .on("click", updateGraph);

        d3.select("#animate")
            .on("click", toggleAnimation);
    });
};
<commit_msg>Bootstrap application by calling updateGraph() once manually.<commit_after>/*jslint browser:true */

/*globals $, d3, tangelo */

var color = null;
var force = null;
var graph = null;
var svg = null;
var width = 0;
var height = 0;

var enron = {};
enron.date = null;
enron.range = null;
enron.center = null;
enron.degree = null;
enron.host = null;

function stringifyDate(d) {
    "use strict";

    return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}

function displayDate(d) {
    "use strict";

    return tangelo.date.monthNames()[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
}

function updateGraph() {
    "use strict";

    var center,
        data,
        end_date,
        degree,
        hops,
        change_button,
        start_date,
        update;

    update = d3.select("#update");
    change_button = !update.attr("disabled");

    if (change_button) {
        update.attr("disabled", true)
            .text("Updating...");
    }

    // Construct a Javascript date object from the date slider.
    start_date = new Date(enron.date.slider("value"));

    // Create another date that is ahead of the start date by the number of days
    // indicated by the slider (i.e., advanced from that date by the number of
    // milliseconds in that many days).
    end_date = new Date(start_date.getTime() + enron.range.slider("value") * 86400 * 1000);

    center = enron.center.val();

    hops = enron.degree.spinner("value");

    data = {
        start_time: stringifyDate(start_date),
        end_time: stringifyDate(end_date),
        center: center,
        degree: hops
    };

    $.ajax({
        url: "service/emailers/" + enron.host + "/xdata/enron",
        data: data,
        dataType: "json",
        success: function (resp) {
            var angle,
                enter,
                link,
                map,
                newidx,
                node,
                tau;

            if (change_button) {
                d3.select("#update")
                    .attr("disabled", null)
                    .text("Update");
            }

            if (resp.error !== null) {
                console.log("error: " + resp.error);
                return;
            }

            // Save the last iteration of node data, so we can transfer the
            // positions to the new iteration.
            map = {};
            $.each(force.nodes(), function (i, v) {
                map[v.email] = v;
            });

            graph = resp.result;
            newidx = [];
            $.each(graph.nodes, function (i, v) {
                if (map.hasOwnProperty(v.email)) {
                    graph.nodes[i].x = map[v.email].x;
                    graph.nodes[i].y = map[v.email].y;
                } else {
                    newidx.push(i);
                }
            });

            tau = 2 * Math.PI;
            angle = tau / newidx.length;
            $.each(newidx, function (i, v) {
                graph.nodes[i].x = (width/4) * Math.cos(i * angle) + (width/2);
                graph.nodes[i].y = (height/4) * Math.sin(i * angle) + (height/2);
            });

            console.log("Got " + graph.nodes.length + " nodes");
            console.log("Got " + graph.edges.length + " edges");

            force.nodes(graph.nodes)
                .links(graph.edges)
                .start();

            link = svg.select("g#links")
                .selectAll(".link")
                .data(graph.edges, function (d) {
                    return d.id;
                });

            link.enter().append("line")
                .classed("link", true)
                .style("opacity", 0.0)
                .transition()
                .duration(500)
                .style("opacity", 1.0);

            link.exit()
                .transition()
                .duration(1000)
                .attr("x1", width)
                .attr("x2", width)
                .attr("y1", height/2)
                .attr("y2", height/2)
                .style("opacity", 0.0)
                .remove();

            node = svg.select("g#nodes")
                .selectAll(".node")
                .data(graph.nodes, function (d) { return d.email; });

            enter = node.enter().append("circle")
                .classed("node", true)
                .attr("r", 0)
                .style("opacity", 0.0)
                .style("fill", function (d) {
                    return color(d.distance);
                });
            enter.transition()
                .duration(500)
                .attr("r", 5)
                .style("opacity", 1.0);

            enter.call(force.drag)
                .append("title")
                .text(function (d) {
                    return d.email || "(no email address)";
                });

            node.exit()
                .transition()
                .duration(1000)
                .style("opacity", 0.0)
                .attr("cx", width)
                .attr("cy", height/2)
                .attr("r", 0.0)
                .remove();

            force.on("tick", function () {
                link.attr("x1", function (d) { return d.source.x; })
                    .attr("y1", function (d) { return d.source.y; })
                    .attr("x2", function (d) { return d.target.x; })
                    .attr("y2", function (d) { return d.target.y; });

                node.attr("cx", function (d) { return d.x; })
                    .attr("cy", function (d) { return d.y; });
            });
        }
    });
}

function advanceTimer() {
    "use strict";

    var value;

    value = enron.date.slider("value") + 86400e3;
    enron.date.slider("value", value);

    updateGraph();
}

var timeout = null;
function toggleAnimation() {
    anim = d3.select("#animate");
    update = d3.select("#update");

    if (anim.text() === "Animate") {
        anim.text("Stop animation")
            .classed("btn-success", false)
            .classed("btn-warning", true);
        update.attr("disabled", true);

        timeout = setInterval(advanceTimer, 1000);
    } else {
        anim.text("Animate")
            .classed("btn-success", true)
            .classed("brn-warning", false);
        update.attr("disabled", null);

        clearInterval(timeout);
    }
}

window.onload = function () {
    "use strict";

    tangelo.util.defaults("defaults.json", function (defaults) {
        enron.host = (defaults && defaults.get("host")) || "mongo";

        svg = d3.select("svg");

        width = $(window).width();
        height = $(window).height();
        force = d3.layout.force()
            .charge(-240)
            .linkDistance(50)
            .gravity(0.5)
            .size([width, height]);

        color = d3.scale.category20();

        // Activate the jquery controls.
        enron.date = $("#date");
        enron.range = $("#range");
        enron.center = $("#center");
        enron.degree = $("#degree");

        enron.date.slider({
            min: new Date("January 1, 1998").getTime(),
            max: new Date("December 31, 2002").getTime(),
            value: new Date("December 13, 2000").getTime(),
            step: 86400,
            slide: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            },
            change: function (evt, ui) {
                d3.select("#date-label")
                    .text(displayDate(new Date(ui.value)));
            }
        });
        enron.date.slider("value", enron.date.slider("value"));

        enron.range.slider({
            min: 1,
            max: 6 * 7,
            value: 3,
            slide: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            },
            change: function (evt, ui) {
                d3.select("#range-label")
                    .text(ui.value + " day" + (ui.value === 1 ? "" : "s"));
            }
        });
        enron.range.slider("value", enron.range.slider("value"));

        enron.center.val("phillip.allen@enron.com");

        enron.degree.spinner({
            min: 1,
            max: 10
        });
        enron.degree.spinner("value", 2);

        d3.select("#update")
            .on("click", updateGraph);

        d3.select("#animate")
            .on("click", toggleAnimation);

        updateGraph();
    });
};
<|endoftext|>


<commit_before>function DiffPage() {
	//hold the tab object
	this.tab = null;

	//hold signals for the page
	this._signals = new Array();

	//hold status message for the page
	this._prompt = null;

	//store inited state
	this._inited = false;

	//store file path
	this.file = '';

	//store newer file revision
	this.newrev = -1;
}

/* *****	Initialization code	***** */
DiffPage.prototype.init = function() {
	if(!this._inited) {
		logDebug("Diff: Initializing");

		/* Initialize a new tab for Diff - Do this only once */
		this.tab = new Tab( "File Difference" );
		this._signals.push(connect( this.tab, "onfocus", bind( this._onfocus, this ) ));
		this._signals.push(connect( this.tab, "onblur", bind( this._onblur, this ) ));
		this._signals.push(connect( this.tab, "onclickclose", bind( this._close, this ) ));
		tabbar.add_tab( this.tab );

		/* remember that we are initialised */
		this._inited = true;
	}

	/* now switch to it */
	tabbar.switch_to(this.tab);
}
/* *****	End Initialization Code 	***** */

/* *****	Tab events: onfocus, onblur and close	***** */
DiffPage.prototype._onfocus = function() {
	showElement('diff-page');
}

DiffPage.prototype._onblur = function() {
	/* Clear any prompts */
	if( this._prompt != null ) {
		this._prompt.close();
		this._prompt = null;
	}
	/* hide Diff page */
	hideElement('diff-page');
}

DiffPage.prototype._close = function() {
	/* Disconnect all signals */
	for(var i = 0; i < this._signals.length; i++) {
		disconnect(this._signals[i]);
	}
	this._signals = new Array();

	/* Close tab */
	this._onblur();
	this.tab.close();
	this._inited = false;
}
/* *****	End Tab events	***** */

/* *****	Team editing Code	***** */
DiffPage.prototype._recieveDiff = function(nodes) {
	replaceChildNodes('diff-page-diff');
	var difflines = nodes.diff.replace('\r','').split('\n');
	var modeclasses = {
		' ' : '',
		'+' : 'add',
		'-' : 'remove',
		'=' : '',
		'@' : 'at'
	};
	var mode = '=';
	var group = '';
	for( var i=0; i < difflines.length; i++) {
		line = difflines[i];
		if(line[0] == mode) {
			group += line+'\n';
		} else {
			appendChildNodes('diff-page-diff', DIV({'class': modeclasses[mode]}, group));
			mode = line[0];
			group = line+'\n';
		}
	}
	var newrev = this.newrev == -2 ? 'your modifications' : 'r'+this.newrev;
	$('diff-page-summary').innerHTML = 'Displaying differences on '
			+this.file+' between r'+nodes.oldrev+' and '+newrev+'.';
	this.init();
}

DiffPage.prototype._errDiff = function(rev, code, nodes) {
	status_button("Error retrieving diff", LEVEL_WARN, "Retry", bind(this.diff, this, this.file, rev, code));
	return;
}

DiffPage.prototype.diff = function(file, rev, code) {
	this.file = file;
	if( code == undefined ) {
		var d = loadJSONDoc("./diff", {
					team: team,
					file: file,
					rev: rev
				});
		this.newrev = rev;
	} else {
		var d = postJSONDoc("./diff", {
			queryString: {
					team: team,
					file: file,
					rev: rev
				},
			sendContent: { code: code }
		});
		this.newrev = -2;
	}

	d.addCallback( bind( this._recieveDiff, this) );
	d.addErrback( bind( this._errDiff, this, rev, code) );
}
/* *****	End Diff loading Code 	***** */
<commit_msg>Update the frontend to diff to match the new backend<commit_after>function DiffPage() {
	//hold the tab object
	this.tab = null;

	//hold signals for the page
	this._signals = new Array();

	//hold status message for the page
	this._prompt = null;

	//store inited state
	this._inited = false;

	//store file path
	this.file = '';

	//store newer file revision
	this.newrev = -1;
}

/* *****	Initialization code	***** */
DiffPage.prototype.init = function() {
	if(!this._inited) {
		logDebug("Diff: Initializing");

		/* Initialize a new tab for Diff - Do this only once */
		this.tab = new Tab( "File Difference" );
		this._signals.push(connect( this.tab, "onfocus", bind( this._onfocus, this ) ));
		this._signals.push(connect( this.tab, "onblur", bind( this._onblur, this ) ));
		this._signals.push(connect( this.tab, "onclickclose", bind( this._close, this ) ));
		tabbar.add_tab( this.tab );

		/* remember that we are initialised */
		this._inited = true;
	}

	/* now switch to it */
	tabbar.switch_to(this.tab);
}
/* *****	End Initialization Code 	***** */

/* *****	Tab events: onfocus, onblur and close	***** */
DiffPage.prototype._onfocus = function() {
	showElement('diff-page');
}

DiffPage.prototype._onblur = function() {
	/* Clear any prompts */
	if( this._prompt != null ) {
		this._prompt.close();
		this._prompt = null;
	}
	/* hide Diff page */
	hideElement('diff-page');
}

DiffPage.prototype._close = function() {
	/* Disconnect all signals */
	for(var i = 0; i < this._signals.length; i++) {
		disconnect(this._signals[i]);
	}
	this._signals = new Array();

	/* Close tab */
	this._onblur();
	this.tab.close();
	this._inited = false;
}
/* *****	End Tab events	***** */

/* *****	Team editing Code	***** */
DiffPage.prototype._recieveDiff = function(nodes) {
	replaceChildNodes('diff-page-diff');
	var difflines = nodes.diff.replace('\r','').split('\n');
	var modeclasses = {
		' ' : '',
		'+' : 'add',
		'-' : 'remove',
		'=' : '',
		'@' : 'at'
	};
	var mode = '=';
	var group = '';
	for( var i=0; i < difflines.length; i++) {
		line = difflines[i];
		if(line[0] == mode) {
			group += line+'\n';
		} else {
			appendChildNodes('diff-page-diff', DIV({'class': modeclasses[mode]}, group));
			mode = line[0];
			group = line+'\n';
		}
	}
	var newrev = this.newrev == -2 ? 'your modifications' : 'r'+this.newrev;
	$('diff-page-summary').innerHTML = 'Displaying differences on '
			+this.file+' between r'+nodes.oldrev+' and '+newrev+'.';
	this.init();
}

DiffPage.prototype._errDiff = function(rev, code, nodes) {
	status_button("Error retrieving diff", LEVEL_WARN, "Retry", bind(this.diff, this, this.file, rev, code));
	return;
}

DiffPage.prototype.diff = function(file, rev, code) {
	this.file = file;
	var recieve = bind( this._recieveDiff, this );
	var err = bind( this._errDiff, this, rev, code );

	var args = {
		   team: team,
		project: IDE_path_get_project(file),
		   path: IDE_path_get_file(file),
		   hash: rev
	};

	if( code == undefined ) {
		this.newrev = rev;
	} else {
		args.code = code;
		this.newrev = -2;
	}

	IDE_backend_request("file/diff", args, recieve, err);

}
/* *****	End Diff loading Code 	***** */
<|endoftext|>


<commit_before>// simple POST request that returns the backtest result

const _ = require('lodash');
const promisify = require('tiny-promisify');
const pipelineRunner = promisify(require('../../core/workers/pipeline/parent'));

// starts a backtest
// requires a post body like:
//
// {
//   gekkoConfig: {watch: {exchange: "poloniex", currency: "USDT", asset: "BTC"},…},…}
//   data: {
//     candleProps: ["close", "start"],
//     indicatorResults: true,
//     report: true,
//     roundtrips: true
//   }
// }
module.exports = function *() {
  var mode = 'backtest';

  var config = require('./baseConfig');

  var req = this.request.body;

  _.merge(config, req.gekkoConfig);

  var result = yield pipelineRunner(mode, config);

  if(!req.data.report)
    delete result.report;

  if(!req.data.roundtrips)
    delete result.roundtrips;

  if(!req.data.trades)
    delete result.trades;

  // todo: indicatorResults

  result.candles = _.map(
    result.candles,
    c => _.pick(c, req.data.candleProps)
  );

  this.body = result;
}<commit_msg>prevent merging hoisted config when running a backtest, fix #840<commit_after>// simple POST request that returns the backtest result

const _ = require('lodash');
const promisify = require('tiny-promisify');
const pipelineRunner = promisify(require('../../core/workers/pipeline/parent'));

// starts a backtest
// requires a post body like:
//
// {
//   gekkoConfig: {watch: {exchange: "poloniex", currency: "USDT", asset: "BTC"},…},…}
//   data: {
//     candleProps: ["close", "start"],
//     indicatorResults: true,
//     report: true,
//     roundtrips: true
//   }
// }
module.exports = function *() {
  var mode = 'backtest';

  var config = {};

  var base = require('./baseConfig');

  var req = this.request.body;

  _.merge(config, base, req.gekkoConfig);

  var result = yield pipelineRunner(mode, config);

  if(!req.data.report)
    delete result.report;

  if(!req.data.roundtrips)
    delete result.roundtrips;

  if(!req.data.trades)
    delete result.trades;

  // todo: indicatorResults

  result.candles = _.map(
    result.candles,
    c => _.pick(c, req.data.candleProps)
  );

  this.body = result;
}<|endoftext|>


<commit_before>/**
    Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at

        http://aws.amazon.com/apache2.0/

    or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

'use strict';

function AlexaSkill(appId) {
    this._appId = appId;
}

AlexaSkill.speechOutputType = {
    PLAIN_TEXT: 'PlainText',
    SSML: 'SSML'
}

AlexaSkill.prototype.requestHandlers = {
    LaunchRequest: function (event, context, response) {
        this.eventHandlers.onLaunch.call(this, event.request, event.session, response);
    },

    IntentRequest: function (event, context, response) {
        this.eventHandlers.onIntent.call(this, event.request, event.session, response);
    },

    SessionEndedRequest: function (event, context) {
        this.eventHandlers.onSessionEnded(event.request, event.session);
        context.succeed();
    }
};

/**
 * Override any of the eventHandlers as needed
 */
AlexaSkill.prototype.eventHandlers = {
    /**
     * Called when the session starts.
     * Subclasses could have overriden this function to open any necessary resources.
     */
    onSessionStarted: function (sessionStartedRequest, session) {
    },

    /**
     * Called when the user invokes the skill without specifying what they want.
     * The subclass must override this function and provide feedback to the user.
     */
    onLaunch: function (launchRequest, session, response) {
        throw "onLaunch should be overriden by subclass";
    },

    /**
     * Called when the user specifies an intent.
     */
    onIntent: function (intentRequest, session, response) {
        var intent = intentRequest.intent,
            intentName = intentRequest.intent.name,
            intentHandler = this.intentHandlers[intentName];
        if (intentHandler) {
            console.log('dispatch intent = ' + intentName);
            intentHandler.call(this, intent, session, response);
        } else {
            throw 'Unsupported intent = ' + intentName;
        }
    },

    /**
     * Called when the user ends the session.
     * Subclasses could have overriden this function to close any open resources.
     */
    onSessionEnded: function (sessionEndedRequest, session) {
    }
};

/**
 * Subclasses should override the intentHandlers with the functions to handle specific intents.
 */
AlexaSkill.prototype.intentHandlers = {};

AlexaSkill.prototype.execute = function (event, context) {
    try {
        console.log("session applicationId: " + event.session.application.applicationId);

        // Validate that this request originated from authorized source.
        if (this._appId && event.session.application.applicationId !== this._appId) {
            console.log("The applicationIds don't match : " + event.session.application.applicationId + " and "
                + this._appId);
            throw "Invalid applicationId";
        }

        if (!event.session.attributes) {
            event.session.attributes = {};
        }

        if (event.session.new) {
            this.eventHandlers.onSessionStarted(event.request, event.session);
        }

        // Route the request to the proper handler which may have been overriden.
        var requestHandler = this.requestHandlers[event.request.type];
        requestHandler.call(this, event, context, new Response(context, event.session));
    } catch (e) {
        console.log("Unexpected exception " + e);
        context.fail(e);
    }
};

var Response = function (context, session) {
    this._context = context;
    this._session = session;
};

function createSpeechObject(optionsParam) {
    if (optionsParam && optionsParam.type === 'SSML') {
        return {
            type: optionsParam.type,
            ssml: optionsParam.speech
        };
    } else {
        return {
            type: optionsParam.type || 'PlainText',
            text: optionsParam.speech || optionsParam
        }
    }
}

Response.prototype = (function () {
    var buildSpeechletResponse = function (options) {
        var alexaResponse = {
            outputSpeech: createSpeechObject(options.output),
            shouldEndSession: options.shouldEndSession
        };
        if (options.reprompt) {
            alexaResponse.reprompt = {
                outputSpeech: createSpeechObject(options.reprompt)
            };
        }
        if (options.cardTitle && options.cardContent) {
            alexaResponse.card = {
                type: "Simple",
                title: options.cardTitle,
                content: options.cardContent
            };
        }
        var returnResult = {
                version: '1.0',
                response: alexaResponse
        };
        if (options.session && options.session.attributes) {
            returnResult.sessionAttributes = options.session.attributes;
        }
        return returnResult;
    };

    return {
        tell: function (speechOutput) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                shouldEndSession: true
            }));
        },
        tellWithCard: function (speechOutput, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: true
            }));
        },
        ask: function (speechOutput, repromptSpeech) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                shouldEndSession: false
            }));
        },
        askWithCard: function (speechOutput, repromptSpeech, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: false
            }));
        }
    };
})();

module.exports = AlexaSkill;
<commit_msg>Delete AlexaSkill.js<commit_after><|endoftext|>


<commit_before>import { API_URL } from '../constants/apiUrls';
import { CREATED, UPDATED, DELETED } from '../constants/apiHistoryActions';
import { sprintf } from 'sprintf-js';

let apiClass = undefined;

class Api
{

    constructor(url, auth) {
        this.url = url;
        this.auth = auth;
        this.cache = [];
        this.ignoredStores = ['METADATASTORE', 'HISTORYSTORE'];

        fetch(`${this.url}/me`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(user => this.userId = user.userCredentials.username);
    }

    getNamespaces() {
        const ignoredStores = this.ignoredStores;

        return fetch(`${this.url}/dataStore`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => response.filter((value) => ignoredStores.indexOf(value) === -1));
    }

    deleteNamespace(namespace) {
        return fetch(`${this.url}/dataStore/${namespace}`, Object.assign({}, this.getHeaders(), {
            method: 'DELETE',
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json());
    }

    getKeys(namespace) {
        return fetch(`${this.url}/dataStore/${namespace}`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .catch(error => Promise.reject(error));
    }

    getValue(namespace, key) {
        const k = this.buildId(namespace, key);
        const cache = this.cache;

        if (cache[namespace] === undefined || cache[namespace][key] === undefined) {
            return this.getMetaData(namespace, key)
                .then(result => {
                    const val = JSON.parse(result.value);
                    if (cache[namespace] === undefined) {
                        cache[namespace] = [];
                    }
                    cache[namespace][key] = val;
                    return val;
                });
        }

        return new Promise((resolve) => {
            console.log('cache resolve');
            resolve(cache[namespace][key]);
        });
    }

    getMetaData(namespace, key) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}/metaData`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json());
    }

    createValue(namespace, key, value, log = true) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'POST',
            body: JSON.stringify(value),
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                if (this.cache[namespace] === undefined) {
                    this.cache[namespace] = [];
                }

                this.cache[namespace][key] = value;
                log && this.updateHistory(namespace, key, value, CREATED);
                return response;
            });
    }

    updateValue(namespace, key, value, log = true) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'PUT',
            body: JSON.stringify(value),
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                this.cache[namespace][key] = value;
                log && this.updateHistory(namespace, key, value, UPDATED);
                return response;
            });
    }

    deleteValue(namespace, key) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'DELETE',
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                delete this.cache[namespace][key];
                this.updateHistory(namespace, key, this.getValue(namespace, key), DELETED);
                return response;
            });
    }

    getHistory(namespace, key = null) {
        const id = key === null ? namespace : this.buildId(namespace, key);
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${id}`, this.getHeaders());
    }

    getHistoryOfKey(namespace, key) {
        const id = this.buildId(namespace, key);
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${id}`, this.getHeaders())
          .then(response => this.successOnly(response))
          .then(response => response.json())
          .then(response => response);
    }

    getHistoryOfNamespace(namespace) {
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${namespace}`, this.getHeaders())
          .then(response => this.successOnly(response))
          .then(response => response.json())
          .then(response => response);
    }

    updateHistory(namespace, key, newValue, action) {
        const id = this.buildId(namespace, key);
        const historyRecord = {
            action,
            date: new Date(),
            user: this.userId,
            value: newValue,
        };

        return this.getHistory(namespace, key)
            .then(response => {
                if (response.status === 404) {
                    this.createValue('HISTORYSTORE', id, [historyRecord], false);
                    return null;
                }
                return response.json();
            }).then(history => {
                if (history !== null) {
                    history.unshift(historyRecord);
                    this.updateValue('HISTORYSTORE', id, history, false);
                }
            }).then(foo => this.updateNamespaceHistory(namespace, key, historyRecord));
    }

    updateNamespaceHistory(namespace, key, historyRecord) {
        const namespaceHistoryRecord = {
            action: historyRecord.action,
            date: new Date(),
            user: historyRecord.user,
            value: sprintf('Key \'%s\' was %s.', key, historyRecord.action.toLowerCase()),
        };

        return this.getHistory(namespace)
            .then(response => {
                console.log(response);
                if (response.status === 404) {
                    const value = [{
                        action: CREATED,
                        date: namespaceHistoryRecord.date,
                        user: historyRecord.user,
                        value: 'Namespace was created.',
                    }];

                    return this.createValue('HISTORYSTORE', namespace, value, false)
                        .then(response => new Promise((resolve, reject) => resolve(value)));
                }
                return response.json();
            }).then(history => {
                history.unshift(namespaceHistoryRecord);
                this.updateValue('HISTORYSTORE', namespace, history, false);
            });
    }

    successOnly(response) {
        if (response.status >= 200 && response.status < 300) {
            return Promise.resolve(response);
        }
        return Promise.reject(response);
    }

    buildId(namespace, key) {
        return encodeURIComponent(`${namespace}:${key}`);
    }

    getHeaders() {
        return {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                Authorization: this.auth,
            },
        };
    }
}

export default (function getApi() {
    if (typeof apiClass === 'undefined') {
        apiClass = new Api(API_URL, `Basic ${btoa('admin:district')}`);
    }

    return apiClass;
}());
<commit_msg>api: add history record to namespace if it’s deleted or last key is deleted<commit_after>import { API_URL } from '../constants/apiUrls';
import { CREATED, UPDATED, DELETED } from '../constants/apiHistoryActions';
import { sprintf } from 'sprintf-js';

let apiClass = undefined;

class Api
{

    constructor(url, auth) {
        this.url = url;
        this.auth = auth;
        this.cache = [];
        this.ignoredStores = ['METADATASTORE', 'HISTORYSTORE'];

        fetch(`${this.url}/me`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(user => this.userId = user.userCredentials.username);
    }

    getNamespaces() {
        const ignoredStores = this.ignoredStores;

        return fetch(`${this.url}/dataStore`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => response.filter((value) => ignoredStores.indexOf(value) === -1));
    }

    deleteNamespace(namespace) {
        return fetch(`${this.url}/dataStore/${namespace}`, Object.assign({}, this.getHeaders(), {
            method: 'DELETE',
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                this.cache[namespace] = [];
                this.updateNamespaceHistory(namespace, null, {
                    action: DELETED,
                    user: this.userId,
                });
                return response;
            });
    }

    getKeys(namespace) {
        return fetch(`${this.url}/dataStore/${namespace}`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .catch(error => Promise.reject(error));
    }

    getValue(namespace, key) {
        const k = this.buildId(namespace, key);
        const cache = this.cache;

        if (cache[namespace] === undefined || cache[namespace][key] === undefined) {
            return this.getMetaData(namespace, key)
                .then(result => {
                    const val = JSON.parse(result.value);
                    if (cache[namespace] === undefined) {
                        cache[namespace] = [];
                    }
                    cache[namespace][key] = val;
                    return val;
                });
        }

        return new Promise((resolve) => {
            console.log('cache resolve');
            resolve(cache[namespace][key]);
        });
    }

    getMetaData(namespace, key) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}/metaData`, this.getHeaders())
            .then(response => this.successOnly(response))
            .then(response => response.json());
    }

    createValue(namespace, key, value, log = true) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'POST',
            body: JSON.stringify(value),
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                if (this.cache[namespace] === undefined) {
                    this.cache[namespace] = [];
                }

                this.cache[namespace][key] = value;
                log && this.updateHistory(namespace, key, value, CREATED);
                return response;
            });
    }

    updateValue(namespace, key, value, log = true) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'PUT',
            body: JSON.stringify(value),
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                this.cache[namespace][key] = value;
                log && this.updateHistory(namespace, key, value, UPDATED);
                return response;
            });
    }

    deleteValue(namespace, key) {
        return fetch(`${this.url}/dataStore/${namespace}/${key}`, Object.assign({}, this.getHeaders(), {
            method: 'DELETE',
        }))
            .then(response => this.successOnly(response))
            .then(response => response.json())
            .then(response => {
                delete this.cache[namespace][key];
                this.updateHistory(namespace, key, this.getValue(namespace, key), DELETED);
                return response;
            });
    }

    getHistory(namespace, key = null) {
        const id = key === null ? namespace : this.buildId(namespace, key);
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${id}`, this.getHeaders());
    }

    getHistoryOfKey(namespace, key) {
        const id = this.buildId(namespace, key);
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${id}`, this.getHeaders())
          .then(response => this.successOnly(response))
          .then(response => response.json())
          .then(response => response);
    }

    getHistoryOfNamespace(namespace) {
        return fetch(`${this.url}/dataStore/HISTORYSTORE/${namespace}`, this.getHeaders())
          .then(response => this.successOnly(response))
          .then(response => response.json())
          .then(response => response);
    }

    updateHistory(namespace, key, newValue, action) {
        const id = this.buildId(namespace, key);
        const historyRecord = {
            action,
            date: new Date(),
            user: this.userId,
            value: newValue,
        };

        return this.getHistory(namespace, key)
            .then(response => {
                if (response.status === 404) {
                    this.createValue('HISTORYSTORE', id, [historyRecord], false);
                    return null;
                }
                return response.json();
            }).then(history => {
                if (history !== null) {
                    history.unshift(historyRecord);
                    this.updateValue('HISTORYSTORE', id, history, false);
                }
            }).then(foo => this.updateNamespaceHistory(namespace, key, historyRecord));
    }

    updateNamespaceHistory(namespace, key, historyRecord) {
        const namespaceHistoryRecord = {
            action: historyRecord.action,
            date: new Date(),
            user: historyRecord.user,
            value: sprintf('Key \'%s\' was %s.', key, historyRecord.action.toLowerCase()),
        };

        return this.getHistory(namespace)
            .then(response => {
                console.log(response);
                if (response.status === 404) {
                    const value = [{
                        action: CREATED,
                        date: namespaceHistoryRecord.date,
                        user: historyRecord.user,
                        value: 'Namespace was created.',
                    }];

                    return this.createValue('HISTORYSTORE', namespace, value, false)
                        .then(response => new Promise((resolve, reject) => resolve(value)));
                }
                return response.json();
            }).then(history => {
                history.unshift(namespaceHistoryRecord);

                if (historyRecord.action === DELETED && this.cache[namespace].length === 0) {
                    history.unshift({
                        action: DELETED,
                        date: new Date(),
                        user: historyRecord.user,
                        value: 'Namespace was deleted.',
                    });
                    delete this.cache[namespace];
                }

                this.updateValue('HISTORYSTORE', namespace, history, false);
            });
    }

    successOnly(response) {
        if (response.status >= 200 && response.status < 300) {
            return Promise.resolve(response);
        }
        return Promise.reject(response);
    }

    buildId(namespace, key) {
        return encodeURIComponent(`${namespace}:${key}`);
    }

    getHeaders() {
        return {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                Authorization: this.auth,
            },
        };
    }
}

export default (function getApi() {
    if (typeof apiClass === 'undefined') {
        apiClass = new Api(API_URL, `Basic ${btoa('admin:district')}`);
    }

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


<commit_before>var CoreView = require('backbone/core-view');
var TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
var CreationModalView = require('builder/components/modals/creation/modal-creation-view');
var SyncOptionsModalView = require('builder/components/modals/sync-options/sync-options-modal-view');
var SyncModel = require('builder/data/synchronization-model');
var template = require('./dataset-content-sync.tpl');
var moment = require('moment');
var checkAndBuildOpts = require('builder/helpers/required-opts');

var REQUIRED_OPTS = [
  'syncModel',
  'tableModel',
  'querySchemaModel',
  'modals',
  'visModel'
];

module.exports = CoreView.extend({
  tagName: 'div',
  className: 'SyncInfo',

  events: {
    'click .js-options': '_onClickOptions',
    'click .js-syncNow': '_onClickSyncNow'
  },

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);
    this._startSync = this._startSync.bind(this);

    this._initBinds();

    // Check sync now button
    if (this._syncModel.isSyncing()) {
      this._showSyncNowModal();
    }
  },

  render: function () {
    this.clearSubViews();
    var runAt = this._syncModel.get('run_at');
    var ranAt = this._syncModel.get('ran_at');
    var modifiedAt = this._syncModel.get('modified_at');
    var subscription = this._visModel.get('subscription');

    var d = {
      canSyncNow: this._syncModel.canSyncNow(),
      fromExternalSource: this._syncModel.get('from_external_source'),
      ranAt: moment(ranAt || new Date()).fromNow(),
      runAt: moment(runAt).fromNow(),
      modifiedAt: (modifiedAt && moment(modifiedAt).fromNow()) || (ranAt && moment(ranAt).fromNow()),
      state: this._syncModel.get('state'),
      errorCode: this._syncModel.get('error_code'),
      errorMessage: this._syncModel.get('error_message'),
      isSubscription: subscription && !!subscription.entity_id
    };

    // Due to the time we need to polling, we have to display to the user
    // that the sync will be in a moment
    if (!runAt || (new Date(runAt) <= new Date())) {
      d.runAt = _t('dataset.sync.in-a-moment');
    }

    this.$el
      .html(template(d))
      .removeClass()
      .addClass(this.className + ' ' + 'is-' + d.state);

    // Tipsy
    var tooltip = new TipsyTooltipView({
      el: this.$('.js-syncNowDisabled'),
      title: function () {
        return _t('dataset.sync.disabled', {
          gap: SyncModel.SYNC_GAP / (1000 * 60)
        });
      }
    });
    this.addView(tooltip);

    return this;
  },

  _initBinds: function () {
    // Unbind in clean method
    this._syncModel.bind('change', this.render, this);
  },

  _bindChangeSyncEvent: function () {
    this._syncModel.bind('change:state', this._finishSync, this);
  },

  _unbindChangeSyncEvent: function () {
    this._syncModel.unbind(null, null, this);
  },

  _onClickSyncNow: function (e) {
    if (e) this.killEvent(e);

    if (this._syncModel.canSyncNow()) {
      this._showSyncNowModal();
    }
  },

  _onClickOptions: function (e) {
    var self = this;
    var tableName = this._tableModel.getUnqualifiedName();

    this._modals.create(function (modalModel) {
      return new SyncOptionsModalView({
        modalModel: modalModel,
        syncModel: self._syncModel,
        tableName: tableName
      });
    });
  },

  _startSync: function () {
    this.render();
    this._bindChangeSyncEvent();
    this._syncModel.pollCheck();
  },

  _finishSync: function () {
    if (!this._syncModel.isSyncing()) {
      this._unbindChangeSyncEvent();
      this._syncModel.destroyCheck();

      // Reload table
      this._querySchemaModel.set({
        status: 'unfetched',
        query: 'SELECT * FROM ' + this._tableModel.getUnquotedName()
      });

      this.render();
    }
  },

  _showSyncNowModal: function (e) {
    var self = this;
    var tableName = this._tableModel.getUnqualifiedName();

    this._modals.create(function (modalModel) {
      return new CreationModalView({
        modalModel: modalModel,
        loadingTitle: _t('dataset.sync.loading', { tableName: tableName }),
        errorTitle: _t('dataset.sync.error', { tableName: tableName }),
        runAction: function (opts) {
          self._syncModel.set({
            state: 'syncing',
            error_code: '',
            error_message: ''
          });

          self._syncModel.bind('change:state', function () {
            if (!self._syncModel.isSyncing()) {
              modalModel.destroy();
            }
          }, self);

          self._syncModel.syncNow(self._startSync);
        }
      });
    });
  },

  clean: function () {
    this._unbindChangeSyncEvent();
    CoreView.prototype.clean.apply(this);
  }

});
<commit_msg>Update modified_at<commit_after>var CoreView = require('backbone/core-view');
var TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
var CreationModalView = require('builder/components/modals/creation/modal-creation-view');
var SyncOptionsModalView = require('builder/components/modals/sync-options/sync-options-modal-view');
var SyncModel = require('builder/data/synchronization-model');
var template = require('./dataset-content-sync.tpl');
var moment = require('moment');
var checkAndBuildOpts = require('builder/helpers/required-opts');

var REQUIRED_OPTS = [
  'syncModel',
  'tableModel',
  'querySchemaModel',
  'modals',
  'visModel'
];

module.exports = CoreView.extend({
  tagName: 'div',
  className: 'SyncInfo',

  events: {
    'click .js-options': '_onClickOptions',
    'click .js-syncNow': '_onClickSyncNow'
  },

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);
    this._startSync = this._startSync.bind(this);

    this._initBinds();

    // Check sync now button
    if (this._syncModel.isSyncing()) {
      this._showSyncNowModal();
    }
  },

  render: function () {
    this.clearSubViews();
    var runAt = this._syncModel.get('run_at');
    var ranAt = this._syncModel.get('ran_at');
    var modifiedAt = this._syncModel.get('modified_at');
    var subscription = this._visModel.get('subscription');

    var d = {
      canSyncNow: this._syncModel.canSyncNow(),
      fromExternalSource: this._syncModel.get('from_external_source'),
      ranAt: moment(ranAt || new Date()).fromNow(),
      runAt: moment(runAt).fromNow(),
      modifiedAt: modifiedAt && moment(modifiedAt).fromNow(),
      state: this._syncModel.get('state'),
      errorCode: this._syncModel.get('error_code'),
      errorMessage: this._syncModel.get('error_message'),
      isSubscription: subscription && !!subscription.entity_id
    };

    // Due to the time we need to polling, we have to display to the user
    // that the sync will be in a moment
    if (!runAt || (new Date(runAt) <= new Date())) {
      d.runAt = _t('dataset.sync.in-a-moment');
    }

    this.$el
      .html(template(d))
      .removeClass()
      .addClass(this.className + ' ' + 'is-' + d.state);

    // Tipsy
    var tooltip = new TipsyTooltipView({
      el: this.$('.js-syncNowDisabled'),
      title: function () {
        return _t('dataset.sync.disabled', {
          gap: SyncModel.SYNC_GAP / (1000 * 60)
        });
      }
    });
    this.addView(tooltip);

    return this;
  },

  _initBinds: function () {
    // Unbind in clean method
    this._syncModel.bind('change', this.render, this);
  },

  _bindChangeSyncEvent: function () {
    this._syncModel.bind('change:state', this._finishSync, this);
  },

  _unbindChangeSyncEvent: function () {
    this._syncModel.unbind(null, null, this);
  },

  _onClickSyncNow: function (e) {
    if (e) this.killEvent(e);

    if (this._syncModel.canSyncNow()) {
      this._showSyncNowModal();
    }
  },

  _onClickOptions: function (e) {
    var self = this;
    var tableName = this._tableModel.getUnqualifiedName();

    this._modals.create(function (modalModel) {
      return new SyncOptionsModalView({
        modalModel: modalModel,
        syncModel: self._syncModel,
        tableName: tableName
      });
    });
  },

  _startSync: function () {
    this.render();
    this._bindChangeSyncEvent();
    this._syncModel.pollCheck();
  },

  _finishSync: function () {
    if (!this._syncModel.isSyncing()) {
      this._unbindChangeSyncEvent();
      this._syncModel.destroyCheck();

      // Reload table
      this._querySchemaModel.set({
        status: 'unfetched',
        query: 'SELECT * FROM ' + this._tableModel.getUnquotedName()
      });

      this.render();
    }
  },

  _showSyncNowModal: function (e) {
    var self = this;
    var tableName = this._tableModel.getUnqualifiedName();

    this._modals.create(function (modalModel) {
      return new CreationModalView({
        modalModel: modalModel,
        loadingTitle: _t('dataset.sync.loading', { tableName: tableName }),
        errorTitle: _t('dataset.sync.error', { tableName: tableName }),
        runAction: function (opts) {
          self._syncModel.set({
            state: 'syncing',
            error_code: '',
            error_message: ''
          });

          self._syncModel.bind('change:state', function () {
            if (!self._syncModel.isSyncing()) {
              modalModel.destroy();
            }
          }, self);

          self._syncModel.syncNow(self._startSync);
        }
      });
    });
  },

  clean: function () {
    this._unbindChangeSyncEvent();
    CoreView.prototype.clean.apply(this);
  }

});
<|endoftext|>


<commit_before>const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const {ENV} = require('./paths')

const cssLoader = {
  loader: 'css-loader',
  options: {
    modules: true,
    sourceMap: true,
    importLoaders: 1,
    minimize: ENV === 'production',
    localIdentName: '[hash:base64:5]',
    camelCase: 'dashesOnly'
  }
}

module.exports = {
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        cssLoader,
        'postcss-loader'
      ]
    }]
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        // This magically solves class name collision in CSS module
        context: __dirname
      }
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  }
}
<commit_msg>Use longer class name in development<commit_after>const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const {ENV} = require('./paths')

const cssLoader = {
  loader: 'css-loader',
  options: {
    modules: true,
    sourceMap: true,
    importLoaders: 1,
    minimize: ENV === 'production',
    localIdentName:
      ENV === 'production'
        ? '[hash:base64:5]'
        : '[name]__[local]--[hash:base64:5]',
    camelCase: 'dashesOnly'
  }
}

module.exports = {
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        cssLoader,
        'postcss-loader'
      ]
    }]
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        // This magically solves class name collision in CSS module
        context: __dirname
      }
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>/* eslint no-var: 0 */
var nib = require('nib');
var path = require('path');
var webpack = require('webpack');

module.exports = {
    cache: true,
    target: 'web',
    entry: {
        app: [
            path.resolve(__dirname, 'src/web/index.jsx')
        ],
        vendor: [
            'async',
            'classnames',
            'colornames',
            'gcode-interpreter',
            'gcode-parser',
            'gcode-toolpath',
            'i18next',
            'i18next-browser-languagedetector',
            'i18next-xhr-backend',
            'jsuri',
            'lodash',
            'moment',
            'mousetrap',
            'pubsub-js',
            'rc-slider',
            'rc-switch',
            'react',
            'react-addons-shallow-compare',
            'react-addons-update',
            'react-bootstrap',
            'react-dom',
            'react-dropzone',
            'react-infinite',
            'react-router',
            'react-select',
            'react-sortablejs',
            'react-virtualized',
            'sha1',
            'sortablejs',
            'stacktrace-js',
            'superagent',
            'three'
        ]
    },
    output: {
        path: path.join(__dirname, 'dist/cnc/web'),
        filename: '[name].js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js')
    ],
    module: {
        preLoaders: [
            // http://survivejs.com/webpack_react/linting_in_webpack/
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            },
            {
                test: /\.styl$/,
                loader: 'stylint'
            }
        ],
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel',
                exclude: /(node_modules|bower_components)/,
                query: {
                    env: {
                        development: {
                            presets: ['react-hmre']
                        }
                    },
                    presets: ['es2015', 'stage-0', 'react'],
                    plugins: [
                        'transform-decorators-legacy'
                    ]
                }
            },
            {
                test: /\.styl$/,
                loader: 'style!css!stylus'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url',
                query: {
                    limit: 8192
                }
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    mimetype: 'application/font-woff'
                }
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file'
            }
        ]
    },
    stylus: {
        // nib - CSS3 extensions for Stylus
        use: [nib()],
        // no need to have a '@import "nib"' in the stylesheet
        import: ['~nib/lib/nib/index.styl']
    },
    resolve: {
        alias: {},
        extensions: ['', '.js', '.jsx', '.styl']
    },
    node: {
        fs: 'empty'
    }
};
<commit_msg>Add new vendor bundle dependencies<commit_after>/* eslint no-var: 0 */
var nib = require('nib');
var path = require('path');
var webpack = require('webpack');

module.exports = {
    cache: true,
    target: 'web',
    entry: {
        app: [
            path.resolve(__dirname, 'src/web/index.jsx')
        ],
        vendor: [
            'async',
            'classnames',
            'colornames',
            'gcode-interpreter',
            'gcode-parser',
            'gcode-toolpath',
            'i18next',
            'i18next-browser-languagedetector',
            'i18next-xhr-backend',
            'jsuri',
            'lodash',
            'moment',
            'mousetrap',
            'pubsub-js',
            'rc-slider',
            'rc-switch',
            'react',
            'react-addons-shallow-compare',
            'react-addons-update',
            'react-bootstrap',
            'react-css-modules',
            'react-dom',
            'react-dropzone',
            'react-infinite',
            'react-redux',
            'react-router',
            'react-router-redux',
            'react-select',
            'react-sortablejs',
            'react-virtualized',
            'redux',
            'sha1',
            'sortablejs',
            'stacktrace-js',
            'superagent',
            'three'
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js')
    ],
    module: {
        preLoaders: [
            // http://survivejs.com/webpack_react/linting_in_webpack/
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            },
            {
                test: /\.styl$/,
                loader: 'stylint'
            }
        ],
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel',
                exclude: /(node_modules|bower_components)/,
                query: {
                    env: {
                        development: {
                            presets: ['react-hmre']
                        }
                    },
                    presets: ['es2015', 'stage-0', 'react'],
                    plugins: [
                        'transform-decorators-legacy'
                    ]
                }
            },
            {
                test: /\.styl$/,
                loader: 'style!css!stylus'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url',
                query: {
                    limit: 8192
                }
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    mimetype: 'application/font-woff'
                }
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file'
            }
        ]
    },
    stylus: {
        // nib - CSS3 extensions for Stylus
        use: [nib()],
        // no need to have a '@import "nib"' in the stylesheet
        import: ['~nib/lib/nib/index.styl']
    },
    resolve: {
        alias: {},
        extensions: ['', '.js', '.jsx', '.styl']
    },
    node: {
        fs: 'empty'
    }
};
<|endoftext|>


<commit_before>// Public Class Aria2 ( options )
var Aria2 = (function (_merge, _format, _isFunction) {
	var jsonrpc_ver = '2.0';

	// I'm lazy
	if (typeof GM_xmlhttpRequest == 'undefined') {
		console.error ('GM_xmlhttpRequest is required for `Aria2.jsonrpc` to work.');
		return null;
	}

	var AriaBase = function ( options ) {
		this.options = _merge ({
			auth: {
				type: AriaBase.AUTH.noAuth,
				user: '',
				pass: ''
			},
			host: '127.0.0.1',
			port: 6800
		}, options || {});

		this.id = parseInt (options, 10) || (0 + new Date());
	};

	// 静态常量
	AriaBase.AUTH = {
		noAuth: 0,
		user:   1,
		secret: 2
	};

	// public 函数
	AriaBase.prototype = {
		getAuthString: function () {
			var user = this.options.auth.user,
				pass = this.options.auth.pass;

			switch ( this.options.auth.type ) {
				case AriaBase.AUTH.noAuth:
					return '';

				case AriaBase.AUTH.user:
					break;

				case AriaBase.AUTH.secret:
					user = 'token';
					break;

				default:
					throw new Error('Undefined auth type: %s', this.options.auth.type);
					break;
			}

			return btoa (_format('%s:%s', user, pass));
		},

		send: function ( data, cbSuccess, cbError ) {
			var payload = {

				method: 'POST',
				url: _format('http://%s:%s/jsonrpc', this.options.host, this.options.port),
				headers: {
					'Content-Type': 'application/json; charset=UTF-8'
				},
				data: JSON.stringify ( _merge ({ jsonrpc: jsonrpc_ver, id: this.id }, data) ),
				onload: function (r) {
					if (cbSuccess)
						cbSuccess (JSON.parse (r.responseText));
				},
				onerror: cbError
			};

			if (this.options.auth.type !== AriaBase.AUTH.noAuth) {
				payload.headers.Authorization = 'Basic ' + this.getAuthString();
			}

			return GM_xmlhttpRequest (payload);
		}
	};

	// 添加各类函数
	[
		"addUri", "addTorrent", "addMetalink", "remove", "forceRemove",
		"pause", "pauseAll", "forcePause", "forcePauseAll", "unpause",
		"unpauseAll", "tellStatus", "getUris", "getFiles", "getPeers",
		"getServers", "tellActive", "tellWaiting", "tellStopped",
		"changePosition", "changeUri", "getOption", "changeOption",
		"getGlobalOption", "changeGlobalOption", "getGlobalStat",
		"purgeDownloadResult", "removeDownloadResult", "getVersion",
		"getSessionInfo", "shutdown", "forceShutdown", "saveSession"
	].forEach (function (sMethod) {
		// arg1, arg2, ... , [cbSuccess, [cbError]]
		AriaBase.prototype[sMethod] = function ( ) {
			var args = [].slice.call (arguments);

			var cbSuccess, cbError;
			if (args.length && _isFunction(args[args.length - 1])) {
				cbSuccess = args[args.length - 1];
				args.splice (-1, 1);

				if (args.length && _isFunction(args[args.length - 1])) {
					cbError = cbSuccess;
					cbSuccess =args[args.length - 1];
					args.splice (-1, 1);
				}
			}

			return this.send ({
				method: 'aria2.' + sMethod,
				params: args
			}, cbSuccess, cbError);
		};
	});

	return AriaBase;
})
// private 函数
((function (base) {
	var _isObject = function (obj) {
		return obj instanceof Object;
	};
	var _merge = function (base) {
		var args = arguments,
			argL = args.length;
		for ( var i = 1; i < argL; i++ ) {
			Object.keys (args[i]).forEach (function (key) {
				if (_isObject(args[i][key]) && _isObject(base[key])) {
					base[key] = _merge (base[key], args[i][key]);
				} else {
					base[key] = args[i][key];
				}
			});
		}
		return base;
	};
	return _merge;
})(), function (src) {
	var args = arguments,
		argL = args.length;

	var ret = src.slice ();
	for ( var i = 1; i < argL; i++ )
		ret = ret.replace ('%s', args[i]);
	return ret;
}, function (foo) {
	return typeof foo === 'function'
});<commit_msg>Callback to cbError when return is an error.<commit_after>// Public Class Aria2 ( options )
var Aria2 = (function (_merge, _format, _isFunction) {
	var jsonrpc_ver = '2.0';

	// I'm lazy
	if (typeof GM_xmlhttpRequest == 'undefined') {
		console.error ('GM_xmlhttpRequest is required for `Aria2.jsonrpc` to work.');
		return null;
	}

	var AriaBase = function ( options ) {
		this.options = _merge ({
			auth: {
				type: AriaBase.AUTH.noAuth,
				user: '',
				pass: ''
			},
			host: '127.0.0.1',
			port: 6800
		}, options || {});

		this.id = parseInt (options, 10) || (0 + new Date());
	};

	// 静态常量
	AriaBase.AUTH = {
		noAuth: 0,
		user:   1,
		secret: 2
	};

	// public 函数
	AriaBase.prototype = {
		getAuthString: function () {
			var user = this.options.auth.user,
				pass = this.options.auth.pass;

			switch ( this.options.auth.type ) {
				case AriaBase.AUTH.noAuth:
					return '';

				case AriaBase.AUTH.user:
					break;

				case AriaBase.AUTH.secret:
					user = 'token';
					break;

				default:
					throw new Error('Undefined auth type: %s', this.options.auth.type);
					break;
			}

			return btoa (_format('%s:%s', user, pass));
		},

		send: function ( data, cbSuccess, cbError ) {
			var payload = {

				method: 'POST',
				url: _format('http://%s:%s/jsonrpc', this.options.host, this.options.port),
				headers: {
					'Content-Type': 'application/json; charset=UTF-8'
				},
				data: JSON.stringify ( _merge ({ jsonrpc: jsonrpc_ver, id: this.id }, data) ),
				onload: function (r) {
					var repData = JSON.parse (r.responseText);
					if (repData.error) {
						cbError && cbError (repData);
					} else {
						cbSuccess && cbSuccess (repData);
					}
				},
				onerror: cbError
			};

			if (this.options.auth.type !== AriaBase.AUTH.noAuth) {
				payload.headers.Authorization = 'Basic ' + this.getAuthString();
			}

			return GM_xmlhttpRequest (payload);
		}
	};

	// 添加各类函数
	[
		"addUri", "addTorrent", "addMetalink", "remove", "forceRemove",
		"pause", "pauseAll", "forcePause", "forcePauseAll", "unpause",
		"unpauseAll", "tellStatus", "getUris", "getFiles", "getPeers",
		"getServers", "tellActive", "tellWaiting", "tellStopped",
		"changePosition", "changeUri", "getOption", "changeOption",
		"getGlobalOption", "changeGlobalOption", "getGlobalStat",
		"purgeDownloadResult", "removeDownloadResult", "getVersion",
		"getSessionInfo", "shutdown", "forceShutdown", "saveSession"
	].forEach (function (sMethod) {
		// arg1, arg2, ... , [cbSuccess, [cbError]]
		AriaBase.prototype[sMethod] = function ( ) {
			var args = [].slice.call (arguments);

			var cbSuccess, cbError;
			if (args.length && _isFunction(args[args.length - 1])) {
				cbSuccess = args[args.length - 1];
				args.splice (-1, 1);

				if (args.length && _isFunction(args[args.length - 1])) {
					cbError = cbSuccess;
					cbSuccess =args[args.length - 1];
					args.splice (-1, 1);
				}
			}

			return this.send ({
				method: 'aria2.' + sMethod,
				params: args
			}, cbSuccess, cbError);
		};
	});

	return AriaBase;
})
// private 函数
((function (base) {
	var _isObject = function (obj) {
		return obj instanceof Object;
	};
	var _merge = function (base) {
		var args = arguments,
			argL = args.length;
		for ( var i = 1; i < argL; i++ ) {
			Object.keys (args[i]).forEach (function (key) {
				if (_isObject(args[i][key]) && _isObject(base[key])) {
					base[key] = _merge (base[key], args[i][key]);
				} else {
					base[key] = args[i][key];
				}
			});
		}
		return base;
	};
	return _merge;
})(), function (src) {
	var args = arguments,
		argL = args.length;

	var ret = src.slice ();
	for ( var i = 1; i < argL; i++ )
		ret = ret.replace ('%s', args[i]);
	return ret;
}, function (foo) {
	return typeof foo === 'function'
});<|endoftext|>


<commit_before>var webpack = require('webpack');
var join = require('path').join

module.exports = {
  output: {
    publicPath: 'assets/',
    path: 'dist/assets/',
    filename: 'main.js'
  },

  debug: false,
  devtool: false,
  entry: './editor/main.js',

  stats: {
    colors: true,
    reasons: false
  },

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'icons': 'material-ui-mdi/icons',
      'assets': join(__dirname, 'assets'),
      'core': join(__dirname, 'core'),
      'editor': join(__dirname, 'editor'),
      'io': join(__dirname, 'io'),
      'renderer': join(__dirname, 'renderer')
    }
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'react-hot!babel-loader?stage=1'
    }, {
      test: /\.less/,
      loader: 'style-loader!css-loader!autoprefixer-loader!less-loader'
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader!autoprefixer-loader'
    }, {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192'
    }, {
      test: /\.(woff)(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=application/font-woff"
    }, {
      test: /\.(woff2)(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=application/font-woff2"
    }, {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=image/svg+xml"
    }]
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"'
    })
  ]

};
<commit_msg>replace assets/main.js with main.js in webpack.dist.config<commit_after>var webpack = require('webpack');
var join = require('path').join

module.exports = {
  output: {
    publicPath: 'assets/',
    path: 'dist/',
    filename: 'main.js'
  },

  debug: false,
  devtool: false,
  entry: './editor/main.js',

  stats: {
    colors: true,
    reasons: false
  },

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'icons': 'material-ui-mdi/icons',
      'assets': join(__dirname, 'assets'),
      'core': join(__dirname, 'core'),
      'editor': join(__dirname, 'editor'),
      'io': join(__dirname, 'io'),
      'renderer': join(__dirname, 'renderer')
    }
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'react-hot!babel-loader?stage=1'
    }, {
      test: /\.less/,
      loader: 'style-loader!css-loader!autoprefixer-loader!less-loader'
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader!autoprefixer-loader'
    }, {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192'
    }, {
      test: /\.(woff)(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=application/font-woff"
    }, {
      test: /\.(woff2)(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=application/font-woff2"
    }, {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      loader: "url?limit=10000&minetype=image/svg+xml"
    }]
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"'
    })
  ]

};
<|endoftext|>


<commit_before>/*
 * Webpack distribution configuration
 *
 * This file is set up for serving the distribution version. It will be compiled to dist/ by default
 */

'use strict';

var webpack = require('webpack'),
  path = require('path'),
  webpackDevConfig = require('./webpack.config.js');

module.exports = {

  output: {
    publicPath: '/assets/',
    path: 'dist/assets/',
    filename: 'main.js'
  },

  debug: false,
  devtool: false,
  entry: './src/components/main.jsx',

  stats: {
    colors: true,
    reasons: false
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin()
  ],

  resolve: webpackDevConfig.resolve,
  module: webpackDevConfig.module
};
<commit_msg>Specify options for UglifyJsPlugin & CompressionPlugin<commit_after>/*
 * Webpack distribution configuration
 *
 * This file is set up for serving the distribution version. It will be compiled to dist/ by default
 */

'use strict';

var webpack = require('webpack'),
  path = require('path'),
  CompressionPlugin = require('compression-webpack-plugin'),
  webpackDevConfig = require('./webpack.config.js');

module.exports = {

  output: {
    publicPath: '/assets/',
    path: 'dist/assets/',
    filename: 'main.js'
  },

  debug: false,
  devtool: false,
  entry: './src/components/main.jsx',

  stats: {
    colors: true,
    reasons: false
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        except: ['require', 'export', '$super']
      },
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
    new CompressionPlugin({
      asset: '{file}.gz',
      algorithm: 'gzip',
      regExp: /\.js$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })
  ],

  resolve: webpackDevConfig.resolve,
  module: webpackDevConfig.module
};
<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');
const config = require('./webpack.config');

config.output = {
    filename: '[name].bundle.js',
    publicPath: '',
    path: path.resolve(__dirname, './dist')
};

config.plugins = config.plugins.concat([
    new webpack.optimize.UglifyJsPlugin({
        mangle: false
    })
]);

module.exports = config;
<commit_msg>chore(fixing formatting): fixing formatting in the webpack configs.<commit_after>const webpack = require('webpack');
const path = require('path');
const config = require('./webpack.config');

config.output = {
  filename: '[name].bundle.js',
  publicPath: '',
  path: path.resolve(__dirname, './dist')
};

config.plugins = config.plugins.concat([
  new webpack.optimize.UglifyJsPlugin({
    mangle: false
  })
]);

module.exports = config;
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');

module.exports = {
  entry: {
    'main': './src/index.ts'
  },

  resolve: {
    extensions: ['.ts','.js'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      // path.resolve(__dirname, 'src'),
    ]
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    library: 'nvd3-chart',
    libraryTarget: 'umd',
    filename: '[name].js'
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          'awesome-typescript-loader'
        ]
      }
    ]
  },

  plugins: [
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      path.resolve(__dirname, 'src'),
      {
        // your Angular Async Route paths relative to this root directory
      }
    )
  ],

  /*
  * Include polyfills or mocks for various node stuff
  * Description: Node configuration
  *
  * See: https://webpack.github.io/docs/configuration.html#node
  */
  node: {
    global: true,
    crypto: 'empty',
    process: true,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};<commit_msg>chore: remove webpack config<commit_after><|endoftext|>