<commit_before>/**
 * Created by Alain Dechorgnat on 12/13/13.
 */

var StatusApp = angular.module('StatusApp', ['D3Directives','ngCookies','ngAnimate','InkscopeCommons'])
    .filter('bytes', funcBytesFilter)
    .filter('duration', funcDurationFilter);

StatusApp.controller("statusCtrl", function ($rootScope, $scope, $http , $cookieStore) {
    $scope.journal = [];
    $scope.osdControl =0;

    $scope.refreshPG = true;
    $scope.refreshPGcontrolClass = "icon-pause";

    $scope.viewControlPanel = false;
    $scope.viewMonitorModule = testAndSetCookie('viewMonitorModule',true);
    $scope.viewCapacityModule = testAndSetCookie('viewCapacityModule',true);
    $scope.viewPoolModule = testAndSetCookie('viewPoolModule',true);
    $scope.viewOsdModule = testAndSetCookie('viewOsdModule',true);
    $scope.viewPgStatusModule = testAndSetCookie('viewPgStatusModule',true);
    $scope.viewMdsModule = testAndSetCookie('viewMdsModule',true);

    function testAndSetCookie(param,defaultValue) {
        var value = $cookieStore.get(param);
        if (typeof value ==="undefined") {
            $cookieStore.put(param,defaultValue);
            value = defaultValue;
        }
        return value;
    }

    // instantiate our graph!
    var graph = new Rickshaw.Graph( {
        element: document.getElementById("iopschart"),
        width: 300,
        height: 30,
        renderer: 'line',
        series: new Rickshaw.Series.FixedDuration([{ name: 'read' },{ name: 'write' },{ name: 'recovery' }], undefined, {
            timeInterval: 3000,
            maxDataPoints: 100,
            timeBase: new Date().getTime() / 1000
        })
    } );
    var hoverDetail = new Rickshaw.Graph.HoverDetail( {
        graph: graph,
        xFormatter: function(x) { return  ""; },
        yFormatter: function(y) { return  funcBytes(y)+ "/s" ;}
    } );
    var yAxis = new Rickshaw.Graph.Axis.Y({
        graph: graph,
        height: 30,
        orientation: 'left',
        tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
        element: document.getElementById('y_axis')
    });
    yAxis.render();
    graph.render();

    //refresh data every x seconds
    refreshData();
    refreshPGData();
    setInterval(function () {
        refreshData()
    }, 5 * 1000);
    setInterval(function () {
        refreshPGData()
    }, 10 * 1000);

    function refreshPGData() {
        $scope.date = new Date();
        $http({method: "get", url: cephRestApiURL + "df.json",timeout:8000})
            .success(function (data, status) {
                $scope.nbPools = data.output.pools.length;;
            });
        $http({method: "get", url: cephRestApiURL + "pg/dump_stuck.json",timeout:8000})
            .success(function (data, status) {
                // fetching stuck pg list
                var pg_stats = data.output;
                var pools = [];
                for (var i = 0; i < pg_stats.length; i++) {
                    var pg = pg_stats[i];
                    //console.log(pg.pgid + " : " + pg.state)
                    var numPool = pg.pgid.split(".")[0];
                    pools[numPool] = false;
                }
                var cnt = 0;
                for (var i = 0; i < pools.length; i++) {
                    if (typeof pools[i] !== "undefined") {
                        ++cnt;
                    }
                }
                $scope.uncleanPools = cnt;
                if (typeof $scope.nbPools !== "undefined") $scope.cleanPools = $scope.nbPools -cnt;
            });
    };

    function refreshData() {
        //console.log("refreshing data...");
        $scope.date = new Date();
        $http({method: "get", url: cephRestApiURL + "status.json",timeout:4000})
            .success(function (data) {
                $scope.pgmap = data.output.pgmap;
                if ( typeof  data.output.pgmap.degraded_objects === "undefined" ) $scope.pgmap.degraded_objects=0;

                $scope.mdsmap = data.output.mdsmap;
                $scope.mdsmap.up_standby = data.output.mdsmap["up:standby"];
                $scope.percentUsed = $scope.pgmap.bytes_used / $scope.pgmap.bytes_total;

                if ($scope.refreshPG) $scope.pgsByState = $scope.pgmap.pgs_by_state;

                $scope.read = (data.output.pgmap.read_bytes_sec ? data.output.pgmap.read_bytes_sec : 0);
                $scope.write = (data.output.pgmap.write_bytes_sec ? data.output.pgmap.write_bytes_sec : 0);
                $scope.recovery = (data.output.pgmap.recovering_bytes_per_sec ? data.output.pgmap.recovering_bytes_per_sec : 0);

                var iopsdata = { read: $scope.read , write : $scope.write , recovery : $scope.recovery };
                graph.series.addData(iopsdata);
                yAxis.render();
                graph.render();

                $scope.health = {};
                $scope.health.severity = data.output.health.overall_status;
                // there may be several messages under data.output.health.summary
                $scope.health.summary="";
                var i = 0;
                while(typeof data.output.health.summary[i] !== "undefined"){
                    if ($scope.health.summary!="") $scope.health.summary+=" | ";
                    $scope.health.summary += data.output.health.summary[i].summary;
                    i++;
                }
                if ($scope.health.summary==""){
                    if (data.output.health.detail[0])
                        $scope.health.summary = data.output.health.detail[0];
                    else
                        //remove HEALTH_ in severity
                        $scope.health.summary = $scope.health.severity.substring(7);
                }
                $rootScope.healthSeverity = $scope.health.severity;
                historise();

                $scope.mons = data.output.monmap.mons;

                for (var i = 0; i < $scope.mons.length; i++) {
                    var mon = $scope.mons[i];
                    mon.health = "HEALTH_UNKNOWN"; // default for styling purpose
                    mon.quorum = "out";          // default for styling purpose
                    for (var j = 0; j < data.output.quorum_names.length; j++) {
                        if (mon.name == data.output.quorum_names[j]) {
                            mon.quorum = "in";
                            break
                        }
                    }
                    if (data.output.health.timechecks.mons) //not always defined
                        for (var j = 0; j < data.output.health.timechecks.mons.length; j++) {
                            mon2 = data.output.health.timechecks.mons[j];
                            if (mon.name == mon2.name) {
                                for (key in mon2) mon[key] = mon2[key];
                                break
                            }
                        }
                    for (var j = 0; j < data.output.health.health.health_services[0].mons.length; j++) {
                        mon2 = data.output.health.health.health_services[0].mons[j];
                        if (mon.name == mon2.name) {
                            for (key in mon2) {
                                if (( key == "health") && (mon[key]+"" != "undefined"))
                                    mon[key] =healthCompare(mon[key],mon2[key]);
                                else
                                    mon[key] = mon2[key];
                            }
                            break
                        }
                    }
                }

                function healthCompare(h1,h2){
                    if ((h1 == "HEALTH_ERROR")||(h2 == "HEALTH_ERROR")) return "HEALTH_ERROR";
                    if ((h1 == "HEALTH_WARN")||(h2 == "HEALTH_WARN")) return "HEALTH_WARN";
                    if ((h1 == "HEALTH_OK")||(h2 == "HEALTH_OK")) return "HEALTH_OK";
                    return "HEALTH_UNKNOWN";
                }

                var osdmap = data.output.osdmap.osdmap;
                $scope.osdsUp = osdmap.num_up_osds;
                $scope.osdsIn = parseInt(osdmap.num_in_osds);
                $scope.osdsOut = osdmap.num_osds - osdmap.num_in_osds;
                $scope.osdsDown = $scope.osdsIn - $scope.osdsUp + $scope.osdsOut;
                $scope.osdsNearFull = osdmap.nearfull ?1:0;
                $scope.osdsFull = osdmap.full ?1:0;
            })
            .error(function (data) {
                $scope.health = {};
                $scope.health.severity = "HEALTH_WARN";
                $scope.health.summary = "Status not available";
            });
    }

    $scope.refreshPGcontrol = function(){
        $scope.refreshPG = !$scope.refreshPG;
        if ($scope.refreshPG)
            $scope.refreshPGcontrolClass = "icon-pause";
        else
            $scope.refreshPGcontrolClass = "icon-play";
    }

    $scope.badgeClass = function (type, count) {
        if ((count == 0) || (count + "" == "undefined"))
            return "health_status_HEALTH_UNKNOWN mybadge";
        else
            return "health_status_HEALTH_" + type + " mybadge";
    }

    $scope.showModule = function(module,view){
        $cookieStore.put(module,view);
        $scope[module]=view;
    }

    $scope.getPgmapMessage=function(){
        if (typeof  $scope.pgmap ==="undefined") return "";
        if ((typeof  $scope.pgmap.degraded_objects ==="undefined" )||($scope.pgmap.degraded_objects==0)) return "";
        return $scope.pgmap.degraded_objects +" objects degraded on "+$scope.pgmap.degraded_total +" ("+ $scope.pgmap.degraded_ratio +"%)";
    }

    function historise() {
        if ($scope.last_health_summary + "" == "undefined") {
            $scope.last_health_summary = $scope.health.summary;
            $scope.journal.unshift({"date": new Date(), "summary": $scope.health.summary});
            return;
        }
        if ($scope.last_health_summary != $scope.health.summary) {
            $scope.journal.unshift({"date": new Date(), "summary": $scope.health.summary});
            $scope.last_health_summary = $scope.health.summary;
        }
    }

});

StatusApp.controller('ModalDemoCtrl', function ($scope, $modal, $log) {
    $scope.open = function (size) {

        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

StatusApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $http) {
    $scope.refresh = function () {
        $scope.details = ["fetching details ..."];
        $http({method: "get", url: cephRestApiURL + "health.json?detail",timeout:8000})
            .success(function (data, status) {
                $scope.details = data.output.detail;
                for (var i=0;i<$scope.details.length;i++){
                    var txt = $scope.details[i];
                    /([0-9]+\.[0-9a-f]+)/.exec(txt);
                    var pgid = RegExp.$1;
                    if (pgid != null)
                        //$scope.details[i] = txt.replace(pgid,""+pgid+"");
                        $scope.details[i] = txt.replace("pg "+pgid,"pg "+pgid+"");
                    // ceph-rest-api/tell/<pgid>/query.json
                }
            })
            .error(function (data, status) {
                $scope.details = ["details not available"];
            }
        );
    };
    $scope.refresh();

    $scope.close = function () {
        $modalInstance.dismiss('cancel');
    };
});

<commit_msg>Fix blank home screen with Jewel (#3)<commit_after>/**
 * Created by Alain Dechorgnat on 12/13/13.
 */

var StatusApp = angular.module('StatusApp', ['D3Directives','ngCookies','ngAnimate','InkscopeCommons'])
    .filter('bytes', funcBytesFilter)
    .filter('duration', funcDurationFilter);

StatusApp.controller("statusCtrl", function ($rootScope, $scope, $http , $cookieStore) {
    $scope.journal = [];
    $scope.osdControl =0;

    $scope.refreshPG = true;
    $scope.refreshPGcontrolClass = "icon-pause";

    $scope.viewControlPanel = false;
    $scope.viewMonitorModule = testAndSetCookie('viewMonitorModule',true);
    $scope.viewCapacityModule = testAndSetCookie('viewCapacityModule',true);
    $scope.viewPoolModule = testAndSetCookie('viewPoolModule',true);
    $scope.viewOsdModule = testAndSetCookie('viewOsdModule',true);
    $scope.viewPgStatusModule = testAndSetCookie('viewPgStatusModule',true);
    $scope.viewMdsModule = testAndSetCookie('viewMdsModule',true);

    function testAndSetCookie(param,defaultValue) {
        var value = $cookieStore.get(param);
        if (typeof value ==="undefined") {
            $cookieStore.put(param,defaultValue);
            value = defaultValue;
        }
        return value;
    }

    // instantiate our graph!
    var graph = new Rickshaw.Graph( {
        element: document.getElementById("iopschart"),
        width: 300,
        height: 30,
        renderer: 'line',
        series: new Rickshaw.Series.FixedDuration([{ name: 'read' },{ name: 'write' },{ name: 'recovery' }], undefined, {
            timeInterval: 3000,
            maxDataPoints: 100,
            timeBase: new Date().getTime() / 1000
        })
    } );
    var hoverDetail = new Rickshaw.Graph.HoverDetail( {
        graph: graph,
        xFormatter: function(x) { return  ""; },
        yFormatter: function(y) { return  funcBytes(y)+ "/s" ;}
    } );
    var yAxis = new Rickshaw.Graph.Axis.Y({
        graph: graph,
        height: 30,
        orientation: 'left',
        tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
        element: document.getElementById('y_axis')
    });
    yAxis.render();
    graph.render();

    //refresh data every x seconds
    refreshData();
    refreshPGData();
    setInterval(function () {
        refreshData()
    }, 5 * 1000);
    setInterval(function () {
        refreshPGData()
    }, 10 * 1000);

    function refreshPGData() {
        $scope.date = new Date();
        $http({method: "get", url: cephRestApiURL + "df.json",timeout:8000})
            .success(function (data, status) {
                $scope.nbPools = data.output.pools.length;;
            });
        $http({method: "get", url: cephRestApiURL + "pg/dump_stuck.json",timeout:8000})
            .success(function (data, status) {
                // fetching stuck pg list
                var pg_stats = data.output;
                var pools = [];
                for (var i = 0; i < pg_stats.length; i++) {
                    var pg = pg_stats[i];
                    //console.log(pg.pgid + " : " + pg.state)
                    var numPool = pg.pgid.split(".")[0];
                    pools[numPool] = false;
                }
                var cnt = 0;
                for (var i = 0; i < pools.length; i++) {
                    if (typeof pools[i] !== "undefined") {
                        ++cnt;
                    }
                }
                $scope.uncleanPools = cnt;
                if (typeof $scope.nbPools !== "undefined") $scope.cleanPools = $scope.nbPools -cnt;
            });
    };

    function refreshData() {
        //console.log("refreshing data...");
        $scope.date = new Date();
        $http({method: "get", url: cephRestApiURL + "status.json",timeout:4000})
            .success(function (data) {
                $scope.pgmap = data.output.pgmap;
                if ( typeof  data.output.pgmap.degraded_objects === "undefined" ) $scope.pgmap.degraded_objects=0;

                if (typeof data.output.mdsmap !== "undefined"){
                    $scope.mdsmap = data.output.mdsmap;
                    $scope.mdsmap.up_standby = data.output.mdsmap["up:standby"];
                }
                else {
                    $scope.mdsmap = data.output.fsmap;
                    $scope.mdsmap.up_standby = data.output.fsmap["up:standby"];
                }
                $scope.percentUsed = $scope.pgmap.bytes_used / $scope.pgmap.bytes_total;

                if ($scope.refreshPG) $scope.pgsByState = $scope.pgmap.pgs_by_state;

                $scope.read = (data.output.pgmap.read_bytes_sec ? data.output.pgmap.read_bytes_sec : 0);
                $scope.write = (data.output.pgmap.write_bytes_sec ? data.output.pgmap.write_bytes_sec : 0);
                $scope.recovery = (data.output.pgmap.recovering_bytes_per_sec ? data.output.pgmap.recovering_bytes_per_sec : 0);

                var iopsdata = { read: $scope.read , write : $scope.write , recovery : $scope.recovery };
                graph.series.addData(iopsdata);
                yAxis.render();
                graph.render();

                $scope.health = {};
                $scope.health.severity = data.output.health.overall_status;
                // there may be several messages under data.output.health.summary
                $scope.health.summary="";
                var i = 0;
                while(typeof data.output.health.summary[i] !== "undefined"){
                    if ($scope.health.summary!="") $scope.health.summary+=" | ";
                    $scope.health.summary += data.output.health.summary[i].summary;
                    i++;
                }
                if ($scope.health.summary==""){
                    if (data.output.health.detail[0])
                        $scope.health.summary = data.output.health.detail[0];
                    else
                        //remove HEALTH_ in severity
                        $scope.health.summary = $scope.health.severity.substring(7);
                }
                $rootScope.healthSeverity = $scope.health.severity;
                historise();

                $scope.mons = data.output.monmap.mons;

                for (var i = 0; i < $scope.mons.length; i++) {
                    var mon = $scope.mons[i];
                    mon.health = "HEALTH_UNKNOWN"; // default for styling purpose
                    mon.quorum = "out";          // default for styling purpose
                    for (var j = 0; j < data.output.quorum_names.length; j++) {
                        if (mon.name == data.output.quorum_names[j]) {
                            mon.quorum = "in";
                            break
                        }
                    }
                    if (data.output.health.timechecks.mons) //not always defined
                        for (var j = 0; j < data.output.health.timechecks.mons.length; j++) {
                            mon2 = data.output.health.timechecks.mons[j];
                            if (mon.name == mon2.name) {
                                for (key in mon2) mon[key] = mon2[key];
                                break
                            }
                        }
                    for (var j = 0; j < data.output.health.health.health_services[0].mons.length; j++) {
                        mon2 = data.output.health.health.health_services[0].mons[j];
                        if (mon.name == mon2.name) {
                            for (key in mon2) {
                                if (( key == "health") && (mon[key]+"" != "undefined"))
                                    mon[key] =healthCompare(mon[key],mon2[key]);
                                else
                                    mon[key] = mon2[key];
                            }
                            break
                        }
                    }
                }

                function healthCompare(h1,h2){
                    if ((h1 == "HEALTH_ERROR")||(h2 == "HEALTH_ERROR")) return "HEALTH_ERROR";
                    if ((h1 == "HEALTH_WARN")||(h2 == "HEALTH_WARN")) return "HEALTH_WARN";
                    if ((h1 == "HEALTH_OK")||(h2 == "HEALTH_OK")) return "HEALTH_OK";
                    return "HEALTH_UNKNOWN";
                }

                var osdmap = data.output.osdmap.osdmap;
                $scope.osdsUp = osdmap.num_up_osds;
                $scope.osdsIn = parseInt(osdmap.num_in_osds);
                $scope.osdsOut = osdmap.num_osds - osdmap.num_in_osds;
                $scope.osdsDown = $scope.osdsIn - $scope.osdsUp + $scope.osdsOut;
                $scope.osdsNearFull = osdmap.nearfull ?1:0;
                $scope.osdsFull = osdmap.full ?1:0;
            })
            .error(function (data) {
                $scope.health = {};
                $scope.health.severity = "HEALTH_WARN";
                $scope.health.summary = "Status not available";
            });
    }

    $scope.refreshPGcontrol = function(){
        $scope.refreshPG = !$scope.refreshPG;
        if ($scope.refreshPG)
            $scope.refreshPGcontrolClass = "icon-pause";
        else
            $scope.refreshPGcontrolClass = "icon-play";
    }

    $scope.badgeClass = function (type, count) {
        if ((count == 0) || (count + "" == "undefined"))
            return "health_status_HEALTH_UNKNOWN mybadge";
        else
            return "health_status_HEALTH_" + type + " mybadge";
    }

    $scope.showModule = function(module,view){
        $cookieStore.put(module,view);
        $scope[module]=view;
    }

    $scope.getPgmapMessage=function(){
        if (typeof  $scope.pgmap ==="undefined") return "";
        if ((typeof  $scope.pgmap.degraded_objects ==="undefined" )||($scope.pgmap.degraded_objects==0)) return "";
        return $scope.pgmap.degraded_objects +" objects degraded on "+$scope.pgmap.degraded_total +" ("+ $scope.pgmap.degraded_ratio +"%)";
    }

    function historise() {
        if ($scope.last_health_summary + "" == "undefined") {
            $scope.last_health_summary = $scope.health.summary;
            $scope.journal.unshift({"date": new Date(), "summary": $scope.health.summary});
            return;
        }
        if ($scope.last_health_summary != $scope.health.summary) {
            $scope.journal.unshift({"date": new Date(), "summary": $scope.health.summary});
            $scope.last_health_summary = $scope.health.summary;
        }
    }

});

StatusApp.controller('ModalDemoCtrl', function ($scope, $modal, $log) {
    $scope.open = function (size) {

        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

StatusApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $http) {
    $scope.refresh = function () {
        $scope.details = ["fetching details ..."];
        $http({method: "get", url: cephRestApiURL + "health.json?detail",timeout:8000})
            .success(function (data, status) {
                $scope.details = data.output.detail;
                for (var i=0;i<$scope.details.length;i++){
                    var txt = $scope.details[i];
                    /([0-9]+\.[0-9a-f]+)/.exec(txt);
                    var pgid = RegExp.$1;
                    if (pgid != null)
                        //$scope.details[i] = txt.replace(pgid,""+pgid+"");
                        $scope.details[i] = txt.replace("pg "+pgid,"pg "+pgid+"");
                    // ceph-rest-api/tell/<pgid>/query.json
                }
            })
            .error(function (data, status) {
                $scope.details = ["details not available"];
            }
        );
    };
    $scope.refresh();

    $scope.close = function () {
        $modalInstance.dismiss('cancel');
    };
});

<|endoftext|>


<commit_before>var tweets = {

    searchByPhrase: function(inputPhrase) {

        var phrase = inputPhrase || 'lazy'

        // $.get("http://socialtrends.herokuapp.com/application/rate_limit_status.json?trends=place", function(data) {

        //     $.get("/twitter/tweets/list.jade", function(template) {
        //             var html = jade.render(template, {
        //                 data: data
        //             })
        //             $("#list").html(html)
        //         })
        // })

        $.get("http://socialtrends.herokuapp.com/trends/place.json?id=1", function(data) {
             data = data.trends

            // var items=JSON.parse(data)

                $.get("/twitter/tweets/list.jade", function(template) {
                    var html = jade.render(template, {
                        data: data
                    })
                    $("#list").html(html)
                })
        })

        // $.get("https://socialtrends.herokuapp.com/trends/available.json", function(data) {
        //      data = data

        //     // var items=JSON.parse(data)

        //         $.get("/twitter/tweets/list.jade", function(template) {
        //             var html = jade.render(template, {
        //                 data: data
        //             })
        //             $("#list").html(html)
        //         })
        // })

    },

    load: function() {

        $.get("/twitter/tweets/ui.jade", function(template) {
            var html = jade.render(template)
            $("#ui").html(html)
        })

        // default search results
        // tweets.searchByPhrase('1')

    }

}<commit_msg>twitter api not working<commit_after>var tweets = {

    searchByPhrase: function(inputPhrase) {

        var phrase = inputPhrase || 'lazy'

        // $.get("http://socialtrends.herokuapp.com/application/rate_limit_status.json?trends=place", function(data) {

        //     $.get("/twitter/tweets/list.jade", function(template) {
        //             var html = jade.render(template, {
        //                 data: data
        //             })
        //             $("#list").html(html)
        //         })
        // })

        $.get("http:/api.twitter.com/1.1/trends/place.json?id=1", function(data) {
             data = data.trends

            // var items=JSON.parse(data)

                $.get("/twitter/tweets/list.jade", function(template) {
                    var html = jade.render(template, {
                        data: data
                    })
                    $("#list").html(html)
                })
        })

        // $.get("https://socialtrends.herokuapp.com/trends/available.json", function(data) {
        //      data = data

        //     // var items=JSON.parse(data)

        //         $.get("/twitter/tweets/list.jade", function(template) {
        //             var html = jade.render(template, {
        //                 data: data
        //             })
        //             $("#list").html(html)
        //         })
        // })

    },

    load: function() {

        $.get("/twitter/tweets/ui.jade", function(template) {
            var html = jade.render(template)
            $("#ui").html(html)
        })

        // default search results
        // tweets.searchByPhrase('1')

    }

}<|endoftext|>


<commit_before>var dbAddress = "http://ajaxgb.github.io/CursedWords/db/",
	db = {index:{}}, markupInput, plainInput,
	manualInput, preferChaptersBelow4Input, wordRE = /\S+/g,
	missingSkullPair = [{markup:"(X)"},{markup:"(X)"}];

window.addEventListener("load",function(){
	markupInput = document.getElementById("markupInput");
	plainInput = document.getElementById("plainInput");
	manualInput = document.getElementById("manualCheck");
	preferChaptersBelow4Input = document.getElementById("preferCh4Check");

	document.getElementById("markupButton").addEventListener("click",markupToPlain);
	markupInput.addEventListener("keydown",function(e){
		if((e.key === "Enter" || e.keyCode === 13) && e.ctrlKey){
			markupToPlain();
			e.preventDefault();
		}
	});

	document.getElementById("plainButton").addEventListener("click",plainToMarkup);
	plainInput.addEventListener("keydown",function(e){
		if((e.key === "Enter" || e.keyCode === 13) && e.ctrlKey){
			plainToMarkup();
			e.preventDefault();
		}
	});
});

function markupToPlain(){
	var skulls = getSkullArray(markupInput.value);
	markupInput.value = plainInput.value = "";
	if(manualInput.checked){
		var pagesToOpen = {};
	}else{
		var outputArr = new Array(Math.floor(skulls.length/2));
		outputArr.filled = 0;
	}
	for(var i=1;i<skulls.length;i+=2){ // By twos
		var skull1 = skulls[i-1], skull2 = skulls[i];
		if(skull1.missing || skull2.missing){
			if(manualInput.checked){
				plainInput.value += "{NOTFOUND} ";
			}else{
				setPlainWord(outputArr,(i-1)/2,"{NOTFOUND}");
			}
		}else if(skull1.piece == 1 || skull2.piece == 1){
			if(manualInput.checked){
				plainInput.value += "{monkey} ";
			}else{
				setPlainWord(outputArr,(i-1)/2,"MONKEY");
			}
		}else{
			var chapter = parseInt(skull1.eyes + skull2.eyes,10);
			var page = parseInt(skull1.horns + "" + skull1.teeth,10);
			var word = parseInt(skull2.horns + "" + skull2.teeth,10);
			if(manualInput.checked){
				plainInput.value += "{chap:"+chapter+",page:"+page+",word:"+word+"} ";
				var address = "http://www.paranatural.net/comic/chapter-" + chapter
				+ "-page-" + page;
				pagesToOpen[address] = true;
			}else{
				var errStr = "{chap:"+chapter+",page:"+page+",word:"+word+"}";
				outputArr[(i-1)/2] = errStr;
				requestWord(chapter,page,word,outputArr,(i-1)/2);
			}
		}
		markupInput.value += skull1.markup+" "+skull2.markup;
		if(i<skulls.length-2){
			if(i%4==1) markupInput.value += "  ";
			else markupInput.value += "\n";
		}
	}
	if(skulls.length%2!=0){
		markupInput.value += "\n\n"+skulls[skulls.length-1].markup;
	}
	if(manualInput.checked){
		for(var add in pagesToOpen){
			window.open(add).blur();
		}
		window.focus();
	}else{
		plainInput.value = outputArr.join(" ");
	}
}

function plainToMarkup(){
	var input = plainInput.value.toLowerCase().trim().match(wordRE);
	if(!input) return;
	input.filled = 0;
	for(var i=0;i<input.length;++i){
		if(input[i].charAt(0)=="{" && input[i].charAt(input[i].length-1)=="}"){
			var explicit = input[i].slice(1,-1).split(",");
			if(explicit.length == 3){
				setSkullPair(input,i,skullPairFromCPW(
				explicit[0].slice(explicit[0].lastIndexOf(':')+1),
				explicit[1].slice(explicit[1].lastIndexOf(':')+1),
				explicit[2].slice(explicit[2].lastIndexOf(':')+1)));
				continue;
			}else if(explicit[0].toUpperCase() === "NOTFOUND"){
				setSkullPair(input,i);
				continue;
			}
		}
		requestSkulls(input[i],input,i);
	}
	markupInput.value = skullPairsToString(input);
	updateSkullDisplay();
}

function getSkullArray(text){
	var skullRE = /([.!]*|\uD83D\uDC52)\(([oO0.]*|[xX])\)(\d?)/g;
	var skulls = [];
	var dat;
	while ((dat = skullRE.exec(text)) !== null) {
		skulls.push(new Skull(dat[1],dat[2],dat[3],dat[0]));
	}
	return skulls;
}

function setPlainWord(outputArr,index,value){
	if(value!==undefined){
		outputArr[index] = value.toUpperCase();
		plainInput.value = outputArr.join(" ");
	}
	if(++(outputArr.filled)>=outputArr.length){
		return true;
	}
	return false;
}

function setSkullPair(outputArr,index,skullpair){
	outputArr[index] = skullpair || missingSkullPair;
	markupInput.value = skullPairsToString(outputArr);
	updateSkullDisplay();
	if(++(outputArr.filled)>=outputArr.length){
		return true;
	}
	return false;
}

function skullPairFromCPW(chapter,page,word){
	var chapP1 = Math.floor(chapter/2),
		chapP2 = chapP1;
	if(chapter%2==1){ //odd
		if(Math.random() >= 0.5) ++chapP1;
		else ++chapP2;
	}
	return [new Skull(Math.floor(page/10),chapP1,page%10),
		new Skull(Math.floor(word/10),chapP2,word%10)];
}

function skullPairsToString(arr){
	var result = "";
	for(var i=0;i<arr.length;++i){
		if(arr[i] instanceof Array) result += arr[i][0].markup+" "+arr[i][1].markup;
		else result += "() ()";
		if(i<arr.length-1){
			if(i%2==0) result += "  ";
			else result += "\n";
		}
	}
	return result;
}

// "Database" functions go here.

function requestWord(chapter,page,word,outputArr,index){
	if(chapter<1||page<1||word<1){
		setPlainWord(outputArr, index);
		return;
	}
	if(db[chapter]===undefined) db[chapter] = {};
	if(page >= db[chapter].deadPage ||
			(db[chapter][page] && word >= db[chapter][page].deadWord)){
		console.log(chapter,page,word,"known dead");
		setPlainWord(outputArr, index);
	}else if(db[chapter][page]===undefined || db[chapter][page][word-1]===undefined){
		var req = dbAddress+"ch"+chapter+"/p"+page+".txt";
		console.log("retrieving",req);
		var xhttp = new XMLHttpRequest();
		xhttp.indices = [{i:index,w:word}];
		xhttp.addEventListener("load",(function(x,oA,c,p,w){
			return function(){
				if(x.status>=200 && x.status<300){ //success code
					db[c][p] = x.responseText.match(wordRE);
					db[c][p].deadWord = db[c][p].length + 1;
					for(var i=0;i<x.indices.length;++i){
						if(setPlainWord(oA,
							x.indices[i].i,
							db[c][p][x.indices[i].w-1] || undefined)) break;
					}
				}else{
					delete db[c][p];
					if(!(p > db[c].deadPage)) db[c].deadPage = p;
					for(var i=0;i<x.indices.length;++i){
						if(setPlainWord(oA, x.indices[i].i)) break;
					}
				}
			};
		})(xhttp,outputArr,chapter,page,word));
		var couldNotLoad = (function(x,oA,c,p){
			return function(){
				delete db[c][p];
				if(!(p > db[c].deadPage)) db[c].deadPage = p;
				for(var i=0;i<x.indices.length;++i){
					if(setPlainWord(oA, x.indices[i].i)) break;
				}
			};
		})(xhttp,outputArr,chapter,page);
		xhttp.addEventListener("abort",couldNotLoad);
		xhttp.addEventListener("error",couldNotLoad);
		xhttp.addEventListener("timeout",couldNotLoad);
		xhttp.open("GET", req, true);
		db[chapter][page] = xhttp;
		xhttp.send();
	}else if(db[chapter][page] instanceof XMLHttpRequest){
		console.log("tacked on to",db[chapter][page]);
		db[chapter][page].indices.push({i:index,w:word});
	}else{
		console.log(chapter,page,word,"already loaded");
		setPlainWord(outputArr, index, db[chapter][page][word-1] || undefined);
	}
}

var nonAlphaRE = /[^A-Za-z]/;
function requestSkulls(word,outputArr,index){
	if(db.index[word]===undefined){
		var folder = word[0];
		if(nonAlphaRE.test(folder)){
			folder = "0";
		}
		var req = dbAddress+"index/"+folder+"/"+encodeWord(word)+".txt";
		console.log("retrieving",req);
		var xhttp = new XMLHttpRequest();
		xhttp.indices = [index];
		xhttp.addEventListener("load",(function(x,oA,w){
			return function(){
				if(x.status>=200 && x.status<300){ //success code
					db.index[w] = [];
					x.responseText.match(wordRE).forEach(function(v,i){
						var occs = v.split(",");
						db.index[w][i] = occs;
						if(!db[occs[0]])
							db[occs[0]] = {};
						if(!db[occs[0]][occs[1]])
							db[occs[0]][occs[1]] = [];
						db[occs[0]][occs[1]][occs[2]-1] = w;
					});
					chooseSkulls(oA, x.indices, db.index[w]);
				}else{
					delete db.index[w];
					for(var i=0;i<x.indices.length;++i){
						if(setSkullPair(oA, x.indices[i])) break;
					}
				}
			};
		})(xhttp,outputArr,word));
		var couldNotLoad = (function(x,oA,w){
			return function(){
				delete db.index[w];
				for(var i=0;i<x.indices.length;++i){
					if(setSkullPair(oA, x.indices[i])) break;
				}
			};
		})(xhttp,outputArr,word);
		xhttp.addEventListener("abort",couldNotLoad);
		xhttp.addEventListener("error",couldNotLoad);
		xhttp.addEventListener("timeout",couldNotLoad);
		xhttp.open("GET", req, true);
		db.index[word] = xhttp;
		xhttp.send();
	}else if(db.index[word] instanceof XMLHttpRequest){
		console.log("tacked on to",db.index[word]);
		db.index[word].indices.push(index);
	}else{
		console.log(word,"already loaded");
		chooseSkulls(outputArr,[index],db.index[word]);
	}
}

var badCharRE = /[^A-Za-z0-9]/;
function encodeWord(word){
	fileName = "";
	for(var i=0;i<word.length;++i){
		if(word.charAt(i).match(badCharRE))
			fileName += "-" + word.charCodeAt(i) + "-";
		else
			fileName += word.charAt(i);
	}
	return fileName;
}

function chooseSkulls(outputArr,indices,occurences){
	var range = -1;
	if(preferChaptersBelow4Input.checked){
		for(var i=occurences.length-1;i>=0;--i){
			if(occurences[i][0] <= 4){ // chapter <= 4
				range = i+1;
				break;
			}
		}
	}
	if(range<0){ // pref not set, or all entries above chapter 4
		range = occurences.length;
	}
	for(var i=0;i<indices.length;++i){
		var choice = occurences[Math.floor(Math.random() * range)];
		if(setSkullPair(outputArr, indices[i], skullPairFromCPW(choice[0],choice[1],choice[2])))
			break;
	}
}<commit_msg>Fixed absolute address to use https<commit_after>var dbAddress = "https://ajaxgb.github.io/CursedWords/db/",
	db = {index:{}}, markupInput, plainInput,
	manualInput, preferChaptersBelow4Input, wordRE = /\S+/g,
	missingSkullPair = [{markup:"(X)"},{markup:"(X)"}];

window.addEventListener("load",function(){
	markupInput = document.getElementById("markupInput");
	plainInput = document.getElementById("plainInput");
	manualInput = document.getElementById("manualCheck");
	preferChaptersBelow4Input = document.getElementById("preferCh4Check");

	document.getElementById("markupButton").addEventListener("click",markupToPlain);
	markupInput.addEventListener("keydown",function(e){
		if((e.key === "Enter" || e.keyCode === 13) && e.ctrlKey){
			markupToPlain();
			e.preventDefault();
		}
	});

	document.getElementById("plainButton").addEventListener("click",plainToMarkup);
	plainInput.addEventListener("keydown",function(e){
		if((e.key === "Enter" || e.keyCode === 13) && e.ctrlKey){
			plainToMarkup();
			e.preventDefault();
		}
	});
});

function markupToPlain(){
	var skulls = getSkullArray(markupInput.value);
	markupInput.value = plainInput.value = "";
	if(manualInput.checked){
		var pagesToOpen = {};
	}else{
		var outputArr = new Array(Math.floor(skulls.length/2));
		outputArr.filled = 0;
	}
	for(var i=1;i<skulls.length;i+=2){ // By twos
		var skull1 = skulls[i-1], skull2 = skulls[i];
		if(skull1.missing || skull2.missing){
			if(manualInput.checked){
				plainInput.value += "{NOTFOUND} ";
			}else{
				setPlainWord(outputArr,(i-1)/2,"{NOTFOUND}");
			}
		}else if(skull1.piece == 1 || skull2.piece == 1){
			if(manualInput.checked){
				plainInput.value += "{monkey} ";
			}else{
				setPlainWord(outputArr,(i-1)/2,"MONKEY");
			}
		}else{
			var chapter = parseInt(skull1.eyes + skull2.eyes,10);
			var page = parseInt(skull1.horns + "" + skull1.teeth,10);
			var word = parseInt(skull2.horns + "" + skull2.teeth,10);
			if(manualInput.checked){
				plainInput.value += "{chap:"+chapter+",page:"+page+",word:"+word+"} ";
				var address = "http://www.paranatural.net/comic/chapter-" + chapter
				+ "-page-" + page;
				pagesToOpen[address] = true;
			}else{
				var errStr = "{chap:"+chapter+",page:"+page+",word:"+word+"}";
				outputArr[(i-1)/2] = errStr;
				requestWord(chapter,page,word,outputArr,(i-1)/2);
			}
		}
		markupInput.value += skull1.markup+" "+skull2.markup;
		if(i<skulls.length-2){
			if(i%4==1) markupInput.value += "  ";
			else markupInput.value += "\n";
		}
	}
	if(skulls.length%2!=0){
		markupInput.value += "\n\n"+skulls[skulls.length-1].markup;
	}
	if(manualInput.checked){
		for(var add in pagesToOpen){
			window.open(add).blur();
		}
		window.focus();
	}else{
		plainInput.value = outputArr.join(" ");
	}
}

function plainToMarkup(){
	var input = plainInput.value.toLowerCase().trim().match(wordRE);
	if(!input) return;
	input.filled = 0;
	for(var i=0;i<input.length;++i){
		if(input[i].charAt(0)=="{" && input[i].charAt(input[i].length-1)=="}"){
			var explicit = input[i].slice(1,-1).split(",");
			if(explicit.length == 3){
				setSkullPair(input,i,skullPairFromCPW(
				explicit[0].slice(explicit[0].lastIndexOf(':')+1),
				explicit[1].slice(explicit[1].lastIndexOf(':')+1),
				explicit[2].slice(explicit[2].lastIndexOf(':')+1)));
				continue;
			}else if(explicit[0].toUpperCase() === "NOTFOUND"){
				setSkullPair(input,i);
				continue;
			}
		}
		requestSkulls(input[i],input,i);
	}
	markupInput.value = skullPairsToString(input);
	updateSkullDisplay();
}

function getSkullArray(text){
	var skullRE = /([.!]*|\uD83D\uDC52)\(([oO0.]*|[xX])\)(\d?)/g;
	var skulls = [];
	var dat;
	while ((dat = skullRE.exec(text)) !== null) {
		skulls.push(new Skull(dat[1],dat[2],dat[3],dat[0]));
	}
	return skulls;
}

function setPlainWord(outputArr,index,value){
	if(value!==undefined){
		outputArr[index] = value.toUpperCase();
		plainInput.value = outputArr.join(" ");
	}
	if(++(outputArr.filled)>=outputArr.length){
		return true;
	}
	return false;
}

function setSkullPair(outputArr,index,skullpair){
	outputArr[index] = skullpair || missingSkullPair;
	markupInput.value = skullPairsToString(outputArr);
	updateSkullDisplay();
	if(++(outputArr.filled)>=outputArr.length){
		return true;
	}
	return false;
}

function skullPairFromCPW(chapter,page,word){
	var chapP1 = Math.floor(chapter/2),
		chapP2 = chapP1;
	if(chapter%2==1){ //odd
		if(Math.random() >= 0.5) ++chapP1;
		else ++chapP2;
	}
	return [new Skull(Math.floor(page/10),chapP1,page%10),
		new Skull(Math.floor(word/10),chapP2,word%10)];
}

function skullPairsToString(arr){
	var result = "";
	for(var i=0;i<arr.length;++i){
		if(arr[i] instanceof Array) result += arr[i][0].markup+" "+arr[i][1].markup;
		else result += "() ()";
		if(i<arr.length-1){
			if(i%2==0) result += "  ";
			else result += "\n";
		}
	}
	return result;
}

// "Database" functions go here.

function requestWord(chapter,page,word,outputArr,index){
	if(chapter<1||page<1||word<1){
		setPlainWord(outputArr, index);
		return;
	}
	if(db[chapter]===undefined) db[chapter] = {};
	if(page >= db[chapter].deadPage ||
			(db[chapter][page] && word >= db[chapter][page].deadWord)){
		console.log(chapter,page,word,"known dead");
		setPlainWord(outputArr, index);
	}else if(db[chapter][page]===undefined || db[chapter][page][word-1]===undefined){
		var req = dbAddress+"ch"+chapter+"/p"+page+".txt";
		console.log("retrieving",req);
		var xhttp = new XMLHttpRequest();
		xhttp.indices = [{i:index,w:word}];
		xhttp.addEventListener("load",(function(x,oA,c,p,w){
			return function(){
				if(x.status>=200 && x.status<300){ //success code
					db[c][p] = x.responseText.match(wordRE);
					db[c][p].deadWord = db[c][p].length + 1;
					for(var i=0;i<x.indices.length;++i){
						if(setPlainWord(oA,
							x.indices[i].i,
							db[c][p][x.indices[i].w-1] || undefined)) break;
					}
				}else{
					delete db[c][p];
					if(!(p > db[c].deadPage)) db[c].deadPage = p;
					for(var i=0;i<x.indices.length;++i){
						if(setPlainWord(oA, x.indices[i].i)) break;
					}
				}
			};
		})(xhttp,outputArr,chapter,page,word));
		var couldNotLoad = (function(x,oA,c,p){
			return function(){
				delete db[c][p];
				if(!(p > db[c].deadPage)) db[c].deadPage = p;
				for(var i=0;i<x.indices.length;++i){
					if(setPlainWord(oA, x.indices[i].i)) break;
				}
			};
		})(xhttp,outputArr,chapter,page);
		xhttp.addEventListener("abort",couldNotLoad);
		xhttp.addEventListener("error",couldNotLoad);
		xhttp.addEventListener("timeout",couldNotLoad);
		xhttp.open("GET", req, true);
		db[chapter][page] = xhttp;
		xhttp.send();
	}else if(db[chapter][page] instanceof XMLHttpRequest){
		console.log("tacked on to",db[chapter][page]);
		db[chapter][page].indices.push({i:index,w:word});
	}else{
		console.log(chapter,page,word,"already loaded");
		setPlainWord(outputArr, index, db[chapter][page][word-1] || undefined);
	}
}

var nonAlphaRE = /[^A-Za-z]/;
function requestSkulls(word,outputArr,index){
	if(db.index[word]===undefined){
		var folder = word[0];
		if(nonAlphaRE.test(folder)){
			folder = "0";
		}
		var req = dbAddress+"index/"+folder+"/"+encodeWord(word)+".txt";
		console.log("retrieving",req);
		var xhttp = new XMLHttpRequest();
		xhttp.indices = [index];
		xhttp.addEventListener("load",(function(x,oA,w){
			return function(){
				if(x.status>=200 && x.status<300){ //success code
					db.index[w] = [];
					x.responseText.match(wordRE).forEach(function(v,i){
						var occs = v.split(",");
						db.index[w][i] = occs;
						if(!db[occs[0]])
							db[occs[0]] = {};
						if(!db[occs[0]][occs[1]])
							db[occs[0]][occs[1]] = [];
						db[occs[0]][occs[1]][occs[2]-1] = w;
					});
					chooseSkulls(oA, x.indices, db.index[w]);
				}else{
					delete db.index[w];
					for(var i=0;i<x.indices.length;++i){
						if(setSkullPair(oA, x.indices[i])) break;
					}
				}
			};
		})(xhttp,outputArr,word));
		var couldNotLoad = (function(x,oA,w){
			return function(){
				delete db.index[w];
				for(var i=0;i<x.indices.length;++i){
					if(setSkullPair(oA, x.indices[i])) break;
				}
			};
		})(xhttp,outputArr,word);
		xhttp.addEventListener("abort",couldNotLoad);
		xhttp.addEventListener("error",couldNotLoad);
		xhttp.addEventListener("timeout",couldNotLoad);
		xhttp.open("GET", req, true);
		db.index[word] = xhttp;
		xhttp.send();
	}else if(db.index[word] instanceof XMLHttpRequest){
		console.log("tacked on to",db.index[word]);
		db.index[word].indices.push(index);
	}else{
		console.log(word,"already loaded");
		chooseSkulls(outputArr,[index],db.index[word]);
	}
}

var badCharRE = /[^A-Za-z0-9]/;
function encodeWord(word){
	fileName = "";
	for(var i=0;i<word.length;++i){
		if(word.charAt(i).match(badCharRE))
			fileName += "-" + word.charCodeAt(i) + "-";
		else
			fileName += word.charAt(i);
	}
	return fileName;
}

function chooseSkulls(outputArr,indices,occurences){
	var range = -1;
	if(preferChaptersBelow4Input.checked){
		for(var i=occurences.length-1;i>=0;--i){
			if(occurences[i][0] <= 4){ // chapter <= 4
				range = i+1;
				break;
			}
		}
	}
	if(range<0){ // pref not set, or all entries above chapter 4
		range = occurences.length;
	}
	for(var i=0;i<indices.length;++i){
		var choice = occurences[Math.floor(Math.random() * range)];
		if(setSkullPair(outputArr, indices[i], skullPairFromCPW(choice[0],choice[1],choice[2])))
			break;
	}
}<|endoftext|>


<commit_before>var page = require('webpage').create(),
    system = require('system'),
    config = require('../bin/config'),
    lastReceived = new Date().getTime(),
    requestCount = 0,
    responseCount = 0,
    requestIds = [],
    minResponses,
    checkComplete,
    checkCompleteInterval,
    minContentLength;

page.viewportSize = { width: 1024, height: 10000 };

page.loadImages = config.loadImages;

page.onResourceReceived = function (response) {
    if(requestIds.indexOf(response.id) !== -1) {
        if (config.debug) {
          console.error('Received: ' + response.id + ' ' +
            response.contentType + ' ' +
            response.url + ' ' +
            response.bodySize + ' ' +
            response.stage + ' ' +
            response.status + ' ' +
            response.statusText + ' ' +
            response.redirectURL
          );
        }
        if (response.id === 1) { // first response
          minContentLength = response.bodySize;
        }
        if (responseCount === 1) { // second response
          minResponses = requestCount;
        }
        lastReceived = new Date().getTime();
        responseCount++;
        requestIds[requestIds.indexOf(response.id)] = null;
    }
};
page.onResourceRequested = function (request, req) {
    if ((/https?:\/\/.+?\.css/gi).test(request.url) || request['Content-Type'] == 'text/css'
      || (/https?:\/\/.+?\.(jpg|gif|png|jpeg)/gi).test(request.url)) {
      req.abort();
    } else if(requestIds.indexOf(request.id) === -1) {
        if (config.debug) {
          console.error('Requested: ' + request.id + ' ' + request.method + ' ' + request.url);
        }
        requestIds.push(request.id);
        requestCount++;
    }
};

// Error controls
if (config.logErrors) {
  var fs = require('fs');

  page.onResourceError = function(resourceError) {
      if (!fs.exists('errors')) {
        fs.makeDirectory('errors');
      }

      var date = new Date();
      var msg = '['+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()+'] Unable to load resource (#' + resourceError.id + ' URL:' + resourceError.url + ') ';
      msg += 'Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString+'\n';

      fs.write('errors/'+date.getFullYear()+date.getMonth()+date.getDate()+"_error.log", msg, 'a');

      if (config.debug) {
        console.log(msg);
      }
  };
}

page.open(system.args[1], function () {

});

checkComplete = function () {
  var timeDiff = new Date().getTime() - lastReceived;
  if (responseCount >= minResponses &&
    page.content.length >= minContentLength &&
    timeDiff > config.checkCompleteTimeDiff &&
    requestCount === responseCount){
    clearInterval(checkCompleteInterval);
    console.log(page.content);
    phantom.exit(0);
  } else {
    if (timeDiff > config.checkCompleteTimeout) {
      if (config.debug) {
        console.error(
          'requestCount: ' + requestCount +
            ' !== responseCount: ' + responseCount + '.' +
            ' You might have a synchronous ajax call that is NOT being captured by onResourceReceived.' +
            ' See: https://github.com/ariya/phantomjs/issues/11284'
        );
        console.error('FORCED EXIT STATUS 10. Incomplete in ' + timeDiff + ' seconds.');
      }
      phantom.exit(10);
    }
  }
}
checkCompleteInterval = setInterval(checkComplete, 1);
<commit_msg>Closes the page after the content is sent to the parent process, to clean the memory for other sibling processes.<commit_after>var page = require('webpage').create(),
    system = require('system'),
    config = require('../bin/config'),
    lastReceived = new Date().getTime(),
    requestCount = 0,
    responseCount = 0,
    requestIds = [],
    minResponses,
    checkComplete,
    checkCompleteInterval,
    minContentLength;

page.viewportSize = { width: 1024, height: 10000 };

page.loadImages = config.loadImages;

page.onResourceReceived = function (response) {
    if(requestIds.indexOf(response.id) !== -1) {
        if (config.debug) {
          console.error('Received: ' + response.id + ' ' +
            response.contentType + ' ' +
            response.url + ' ' +
            response.bodySize + ' ' +
            response.stage + ' ' +
            response.status + ' ' +
            response.statusText + ' ' +
            response.redirectURL
          );
        }
        if (response.id === 1) { // first response
          minContentLength = response.bodySize;
        }
        if (responseCount === 1) { // second response
          minResponses = requestCount;
        }
        lastReceived = new Date().getTime();
        responseCount++;
        requestIds[requestIds.indexOf(response.id)] = null;
    }
};
page.onResourceRequested = function (request, req) {
    if ((/https?:\/\/.+?\.css/gi).test(request.url) || request['Content-Type'] == 'text/css'
      || (/https?:\/\/.+?\.(jpg|gif|png|jpeg)/gi).test(request.url)) {
      req.abort();
    } else if(requestIds.indexOf(request.id) === -1) {
        if (config.debug) {
          console.error('Requested: ' + request.id + ' ' + request.method + ' ' + request.url);
        }
        requestIds.push(request.id);
        requestCount++;
    }
};

// Error controls
if (config.logErrors) {
  var fs = require('fs');

  page.onResourceError = function(resourceError) {
      if (!fs.exists('errors')) {
        fs.makeDirectory('errors');
      }

      var date = new Date();
      var msg = '['+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()+'] Unable to load resource (#' + resourceError.id + ' URL:' + resourceError.url + ') ';
      msg += 'Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString+'\n';

      fs.write('errors/'+date.getFullYear()+date.getMonth()+date.getDate()+"_error.log", msg, 'a');

      if (config.debug) {
        console.log(msg);
      }
  };
}

page.open(system.args[1], function () {

});

checkComplete = function () {
  var timeDiff = new Date().getTime() - lastReceived;
  if (responseCount >= minResponses &&
    page.content.length >= minContentLength &&
    timeDiff > config.checkCompleteTimeDiff &&
    requestCount === responseCount){
    clearInterval(checkCompleteInterval);
    console.log(page.content);
    page.close();
    phantom.exit(0);
  } else {
    if (timeDiff > config.checkCompleteTimeout) {
      if (config.debug) {
        console.error(
          'requestCount: ' + requestCount +
            ' !== responseCount: ' + responseCount + '.' +
            ' You might have a synchronous ajax call that is NOT being captured by onResourceReceived.' +
            ' See: https://github.com/ariya/phantomjs/issues/11284'
        );
        console.error('FORCED EXIT STATUS 10. Incomplete in ' + timeDiff + ' seconds.');
      }
      page.close();
      phantom.exit(10);
    }
  }
}
checkCompleteInterval = setInterval(checkComplete, 1);
<|endoftext|>


<commit_before>define(['jquery'], function ($) {

  var _DATA_FIELD_KEY = '_data_dk_button_object';

  // Button extends the HTML button element, giving default behaviors.
  // Arguments:
  //   domID: A CSS style id selector.
  var Button = function (domID) {
    this._$element = $(domID);
    this._toggleable = this._$element.hasClass('dk-toggleable-button') ||
        this._$element.hasClass('dk-toggleable-button-active');
    this._toggled = this._toggleable &&
        this._$element.hasClass('dk-toggleable-button-active');
    this._handlers = Object.create(null);
    this._mouseDown = false;
    this._onClickHandlers = [];

    this._handlers.mousePress = this._handlePress.bind(this);
    this._handlers.mouseRelease = this._handleRelease.bind(this);
    this._handlers.mouseLeave = this._handleLeave.bind(this);

    this._$element.bind('mousedown', this._handlers.mousePress);
    this._$element.bind('mouseup', this._handlers.mouseRelease);
    this._$element.bind('mouseleave', this._handlers.mouseLeave);

    this._$element.data(_DATA_FIELD_KEY, this);

    if (!this._isDKButton()) {
      this._$element.addClass('dk-button');
    }
  };

  // addClickHandler registers a function to handle click events on the button.
  // Arguments:
  //   handler: Function that takes a boolean argument, whether the button is
  //       active (toggled) or not.
  Button.prototype.addClickHandler = function (handler) {
    if (this._onClickHandlers.indexOf(handler) === -1) {
      this._onClickHandlers.push(handler);
    }
  };

  // click initiates the handling of a UI click on the button.
  Button.prototype.click = function () {
    this._handlePress();
    this._handleRelease();
  };

  // destroy removes all callback handlers from the element
  Button.prototype.destroy = function () {
    this._$element.unbind('mousedown', this._handlers.mousePress);
    this._$element.unbind('mouseup', this._handlers.mouseRelease);
    this._$element.unbind('mouseleave', this._handlers.mouseLeave);

    this._$element.data(_DATA_FIELD_KEY, null);
  };

  // getToggleState returns whether the button is active or not.
  Button.prototype.getToggleState = function () {
    return this._toggleable && this._toggled;
  };

  // mousedown handler
  Button.prototype._handlePress = function () {
    if (this._toggleable) {
      if (this._toggled) {
        this._$element.addClass('dk-toggleable-button-active-pressed');
        this._$element.removeClass('dk-toggleable-button-active');
      } else {
        this._$element.addClass('dk-toggleable-button-pressed');
        this._$element.removeClass('dk-toggleable-button');
      }
    } else {
      this._$element.addClass('dk-button-pressed');
      this._$element.removeClass('dk-button');
    }

    this._mouseDown = true;
  };

  // mouseup handler
  Button.prototype._handleRelease = function () {
    if (this._toggleable) {
      this._toggled = !this._toggled;

      if (this._toggled) {
        this._$element.addClass('dk-toggleable-button-active');
        this._$element.removeClass('dk-toggleable-button-pressed');
      } else {
        this._$element.addClass('dk-toggleable-button');
        this._$element.removeClass('dk-toggleable-button-active-pressed');
      }
    } else {
      this._$element.addClass('dk-button');
      this._$element.removeClass('dk-button-pressed');
    }

    this._mouseDown = false;

    for (var i = 0; i < this._onClickHandlers.length; i++) {
      this._onClickHandlers[i](this._toggled);
    }
  };

  // mouseleave handler
  Button.prototype._handleLeave = function () {
    if (this._mouseDown) {
      if (this._toggleable) {
        if (this._toggled) {
          this._$element.addClass('dk-toggleable-button-active');
          this._$element.removeClass('dk-toggleable-button-active-pressed');
        } else {
          this._$element.addClass('dk-toggleable-button');
          this._$element.removeClass('dk-toggleable-button-pressed');
        }
      } else {
        this._$element.addClass('dk-button');
        this._$element.removeClass('dk-button-pressed');
      }
    }

    this._mouseDown = false;
  };

  // _isDKButton verifies that the element the Button instance is bound to
  // has a dk-button or related CSS class.
  Button.prototype._isDKButton = function () {
    return this._$element.hasClass('dk-button') ||
      this._$element.hasClass('dk-toggleable-button') ||
      this._$element.hasClass('dk-toggleable-button-active');
  };

  // isToggleable returns whether the button is a toggleable button or a
  // standard button.
  Button.prototype.isToggleable = function () {
    return this._toggleable;
  };

  // removeClickHandler unregisters a function that handles click events on the
  // button.
  // Arguments:
  //   handler: Function that takes a boolean argument, whether the button is
  //       active (toggled) or not.
  Button.prototype.removeClickHandler = function (handler) {
    var handlerIndex = this._onClickHandlers.indexOf(handler);
    if (handlerIndex === -1) return;
    this._onClickHandlers.splice(handlerIndex, 1);
  };

  // setToggleState updates the button's toggle state to the desired boolean.
  // Arguments:
  //     toggled: Boolean, whether the button will be toggled or not.
  Button.prototype.setToggleState = function (toggled) {
    if (this._toggleable && this._toggled != toggled) this.click();
  };

  // create returns a Button instance for the given domID. If the instance
  // already exists then the instance is returned, if not then a new instance
  // is returned.
  // Arguments:
  //   domID: A CSS style id selector.
  Button.create = function (domID) {
    var $element = $(domID);
    var buttonInstance = $element.data(_DATA_FIELD_KEY);
    return buttonInstance ? buttonInstance : new Button(domID);
  };

  return Button;
});
<commit_msg>update Button API to match desired Toggleable API<commit_after>define(['jquery'], function ($) {

  var _DATA_FIELD_KEY = '_data_dk_button_object';

  // Button extends the HTML button element, giving default behaviors.
  // Arguments:
  //   domID: A CSS style id selector.
  var Button = function (domID) {
    this._$element = $(domID);
    this._toggleable = this._$element.hasClass('dk-toggleable-button') ||
        this._$element.hasClass('dk-toggleable-button-active');
    this._toggled = this._toggleable &&
        this._$element.hasClass('dk-toggleable-button-active');
    this._handlers = Object.create(null);
    this._mouseDown = false;
    this._onClickHandlers = [];

    this._handlers.mousePress = this._handlePress.bind(this);
    this._handlers.mouseRelease = this._handleRelease.bind(this);
    this._handlers.mouseLeave = this._handleLeave.bind(this);

    this._$element.bind('mousedown', this._handlers.mousePress);
    this._$element.bind('mouseup', this._handlers.mouseRelease);
    this._$element.bind('mouseleave', this._handlers.mouseLeave);

    this._$element.data(_DATA_FIELD_KEY, this);

    if (!this._isDKButton()) {
      this._$element.addClass('dk-button');
    }
  };

  // addClickHandler registers a function to handle click events on the button.
  // Arguments:
  //   handler: Function that takes a boolean argument, whether the button is
  //       active (toggled) or not.
  Button.prototype.addClickHandler = function (handler) {
    if (this._onClickHandlers.indexOf(handler) === -1) {
      this._onClickHandlers.push(handler);
    }
  };

  // addStateHandler is an alias for addClickHandler
  Button.prototype.addStateHandler = Button.prototype.addClickHandler;

  // click initiates the handling of a UI click on the button.
  Button.prototype.click = function () {
    this._handlePress();
    this._handleRelease();
  };

  // destroy removes all callback handlers from the element
  Button.prototype.destroy = function () {
    this._$element.unbind('mousedown', this._handlers.mousePress);
    this._$element.unbind('mouseup', this._handlers.mouseRelease);
    this._$element.unbind('mouseleave', this._handlers.mouseLeave);

    this._$element.data(_DATA_FIELD_KEY, null);
  };

  // getState returns whether the button is active or not.
  Button.prototype.getState = function () {
    return this._toggleable && this._toggled;
  };

  // _handlePress mousedown handler
  Button.prototype._handlePress = function () {
    if (this._toggleable) {
      if (this._toggled) {
        this._$element.addClass('dk-toggleable-button-active-pressed');
        this._$element.removeClass('dk-toggleable-button-active');
      } else {
        this._$element.addClass('dk-toggleable-button-pressed');
        this._$element.removeClass('dk-toggleable-button');
      }
    } else {
      this._$element.addClass('dk-button-pressed');
      this._$element.removeClass('dk-button');
    }

    this._mouseDown = true;
  };

  // _handleRelease mouseup handler
  Button.prototype._handleRelease = function () {
    if (this._toggleable) {
      this._toggled = !this._toggled;

      if (this._toggled) {
        this._$element.addClass('dk-toggleable-button-active');
        this._$element.removeClass('dk-toggleable-button-pressed');
      } else {
        this._$element.addClass('dk-toggleable-button');
        this._$element.removeClass('dk-toggleable-button-active-pressed');
      }
    } else {
      this._$element.addClass('dk-button');
      this._$element.removeClass('dk-button-pressed');
    }

    this._mouseDown = false;

    for (var i = 0; i < this._onClickHandlers.length; i++) {
      this._onClickHandlers[i](this._toggled);
    }
  };

  // _handleLeave mouseleave handler
  Button.prototype._handleLeave = function () {
    if (this._mouseDown) {
      if (this._toggleable) {
        if (this._toggled) {
          this._$element.addClass('dk-toggleable-button-active');
          this._$element.removeClass('dk-toggleable-button-active-pressed');
        } else {
          this._$element.addClass('dk-toggleable-button');
          this._$element.removeClass('dk-toggleable-button-pressed');
        }
      } else {
        this._$element.addClass('dk-button');
        this._$element.removeClass('dk-button-pressed');
      }
    }

    this._mouseDown = false;
  };

  // _isDKButton verifies that the element the Button instance is bound to
  // has a dk-button or related CSS class.
  Button.prototype._isDKButton = function () {
    return this._$element.hasClass('dk-button') ||
      this._$element.hasClass('dk-toggleable-button') ||
      this._$element.hasClass('dk-toggleable-button-active');
  };

  // isToggleable returns whether the button is a toggleable button or a
  // standard button.
  Button.prototype.isToggleable = function () {
    return this._toggleable;
  };

  // removeClickHandler unregisters a function that handles click events on the
  // button.
  // Arguments:
  //   handler: Function that takes a boolean argument, whether the button is
  //       active (toggled) or not.
  Button.prototype.removeClickHandler = function (handler) {
    var handlerIndex = this._onClickHandlers.indexOf(handler);
    if (handlerIndex === -1) return;
    this._onClickHandlers.splice(handlerIndex, 1);
  };

  // removeStateHandler is an alias for removeClickHandler
  Button.prototype.removeStateHandler = Button.prototype.removeClickHandler;

  // setState updates the button's toggle state to the desired boolean.
  // Arguments:
  //     toggled: Boolean, whether the button will be toggled or not.
  Button.prototype.setState = function (toggled) {
    if (this._toggleable && this._toggled != toggled) this.click();
  };

  // create returns a Button instance for the given domID. If the instance
  // already exists then the instance is returned, if not then a new instance
  // is returned.
  // Arguments:
  //   domID: A CSS style id selector.
  Button.create = function (domID) {
    var $element = $(domID);
    var buttonInstance = $element.data(_DATA_FIELD_KEY);
    return buttonInstance ? buttonInstance : new Button(domID);
  };

  return Button;
});
<|endoftext|>


<commit_before>/*!
 * qwebs service
 */
"use strict";

const qwebs = require("../../lib/qwebs");

class ApplicationService {
    constructor($qjimp) {
        this.$qjimp = $qjimp;
        this.data = [
            { name: "Paris" },
            { name: "Lyon" },
            { name: "Marseille" }
        ];
    };

    index(request, response) {
        return qwebs.reroute("/template.html", request, response); //reroute to asset
    };

    cities(request, response) {
        return response.send({ request: request, content: this.data });
    };

    city(request, response) {
        this.data.push(request.body);
        return response.send({ request: request, content: request.body });
    };

    toJpeg(request, response) {
        let match = /data:(\S*);(\S*),(.+)/.exec(request.body.datauri);

        if (!match) throw new Error("Bad format.");

        let contentType = match[1];
        let data64 = match[3];

        let buffer = new Buffer(data64, "base64");
        return this.$qjimp.toImage(buffer).then(image => {
            return this.$qjimp.toBuffer(image, "image/jpeg").then(newBuffer => {
                let header = {
                    "Content-Type": "image/jpeg",
                    "Expires": new Date(Date.now() + 604800000).toString(), /* 1000 * 60 * 60 * 24 * 7 (7 days)*/
                    "Etag": '"0.0.1"'
                };
                return response.send({ header: header, request: request, content: newBuffer })
            });
        });
    };
};

exports = module.exports = ApplicationService;<commit_msg>replace Buffer constructor<commit_after>/*!
 * qwebs service
 */
"use strict";

const qwebs = require("../../lib/qwebs");

class ApplicationService {
    constructor($qjimp) {
        this.$qjimp = $qjimp;
        this.data = [
            { name: "Paris" },
            { name: "Lyon" },
            { name: "Marseille" }
        ];
    };

    index(request, response) {
        return qwebs.reroute("/template.html", request, response); //reroute to asset
    };

    cities(request, response) {
        return response.send({ request: request, content: this.data });
    };

    city(request, response) {
        this.data.push(request.body);
        return response.send({ request: request, content: request.body });
    };

    toJpeg(request, response) {
        let match = /data:(\S*);(\S*),(.+)/.exec(request.body.datauri);

        if (!match) throw new Error("Bad format.");

        let contentType = match[1];
        let data64 = match[3];

        let buffer = Buffer.from(data64, "base64");
        return this.$qjimp.toImage(buffer).then(image => {
            return this.$qjimp.toBuffer(image, "image/jpeg").then(newBuffer => {
                let header = {
                    "Content-Type": "image/jpeg",
                    "Expires": new Date(Date.now() + 604800000).toString(), /* 1000 * 60 * 60 * 24 * 7 (7 days)*/
                    "Etag": '"0.0.1"'
                };
                return response.send({ header: header, request: request, content: newBuffer })
            });
        });
    };
};

exports = module.exports = ApplicationService;<|endoftext|>


<commit_before>// Boiler
// Versão: 1.0.0
// Autor: Victor Bastos

if (typeof exports === 'object' && typeof define !== 'function') {
	var define = function (factory) {
		factory(require, exports, module);
	};
}

define(function (require, exports, module) {
	var	$ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone'),
		regionManager = new (require('marionette')).RegionManager(),
		loading,
		loadingView;

	// Boiler Controller
	var Controller = _.extend(Backbone.Router.prototype, {
		before: function() {},
		after: function() {},
		showView: showView,
		extend: function(methods) {
			var controller = this;

			_(methods).each(function(fn, fnName) {
				if(fnName !== 'before' && fnName !== 'after') {
					methods[fnName] = (function() {
						return function() {
							if(controller.before.apply(controller, [fnName, location.hash]) !== false) {
								if(fn.apply(controller, arguments) !== false) {
									controller.after.apply(controller, [fnName, location.hash]);
								}
							}
						};
					})();
				}
			});

			return _.extend(this, methods);
		}
	});

	// Boiler showView
	function showView(region, view, options) {
		if(!regionManager.get(region)) {
			regionManager.addRegion(region, region);
		}

		if(typeof(view) === 'string') {
			view = new (require('../application/' + view))(options);
		}

		if(typeof(view) === 'function') {
			view = new view(options);
		}

		regionManager.get(region).show(view);

		return view;
	}

	// Boiler registerRoutes
	function registerRoutes(routes) {
		var router = new Backbone.Router({});

		_(routes).each(function(callback, route) {
			router.route(route, callback);
		});

		Backbone.history.start();
	}

	// Insere o método showView no Backbone Router
	Backbone.Router.prototype.showView = showView;

	// Configura a view a ser renderizada no loading das requisições ajax
	function setLoadingView(view, region) {
		$(document).ajaxStart(function() {
			loading = setTimeout(function() {
				loadingView = this.showView(region, view);
			}.bind(this), 1000);
		}.bind(this));

		$(document).ajaxComplete(function() {
			clearTimeout(loading);
			try {
				loadingView.destroy();
			} catch(err) {}
		});
	}

	// Configura a view a ser renderizada no erro das requisições ajax
	function setErrorView(view, region) {
		$(document).ajaxError(function(event, error) {
			clearTimeout(loading);
			this.showView(region, view, {model: new Backbone.Model(error)});
		}.bind(this));
	}

	module.exports = {
		Controller: Controller,
		showView: showView,
		registerRoutes: registerRoutes,
		setLoadingView: setLoadingView,
		setErrorView: setErrorView
	};
});<commit_msg>Correção de bug que permitia executar os filtros before mesmo em controllers que não tinham esse filtro.<commit_after>// Boiler
// Versão: 1.0.0
// Autor: Victor Bastos

if (typeof exports === 'object' && typeof define !== 'function') {
	var define = function (factory) {
		factory(require, exports, module);
	};
}

define(function (require, exports, module) {
	var	$ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone'),
		regionManager = new (require('marionette')).RegionManager(),
		loading,
		loadingView;

	// Boiler Controller
	var Controller = _.extend({
		before: function() {},
		after: function() {},
		showView: showView,
		extend: function(methods) {
			var controller = this;

			_(methods).each(function(fn, fnName) {
				if(fnName !== 'before' && fnName !== 'after') {
					methods[fnName] = (function() {
						return function() {
							if(methods['before']) {
								if(controller.before.apply(controller, [fnName, location.hash]) !== false) {
									if(fn.apply(controller, arguments) !== false) {
										if(methods['after']) {
											controller.after.apply(controller, [fnName, location.hash]);
										}
									}
								}
							} else {
								if(fn.apply(controller, arguments) !== false) {
									if(methods['after']) {
										controller.after.apply(controller, [fnName, location.hash]);
									}
								}
							}
						};
					})();
				}
			});

			return _.extend(this, methods);
		}
	});

	// Boiler showView
	function showView(region, view, options) {
		if(!regionManager.get(region)) {
			regionManager.addRegion(region, region);
		}

		if(typeof(view) === 'string') {
			view = new (require('../application/' + view))(options);
		}

		if(typeof(view) === 'function') {
			view = new view(options);
		}

		regionManager.get(region).show(view);

		return view;
	}

	// Boiler registerRoutes
	function registerRoutes(routes) {
		var router = new Backbone.Router({});

		_(routes).each(function(callback, route) {
			router.route(route, callback);
		});

		Backbone.history.start();
	}

	// Insere o método showView no Backbone Router
	Backbone.Router.prototype.showView = showView;

	// Configura a view a ser renderizada no loading das requisições ajax
	function setLoadingView(view, region) {
		$(document).ajaxStart(function() {
			loading = setTimeout(function() {
				loadingView = this.showView(region, view);
			}.bind(this), 1000);
		}.bind(this));

		$(document).ajaxComplete(function() {
			clearTimeout(loading);
			try {
				loadingView.destroy();
			} catch(err) {}
		});
	}

	// Configura a view a ser renderizada no erro das requisições ajax
	function setErrorView(view, region) {
		$(document).ajaxError(function(event, error) {
			clearTimeout(loading);
			this.showView(region, view, {model: new Backbone.Model(error)});
		}.bind(this));
	}

	module.exports = {
		Controller: Controller,
		showView: showView,
		registerRoutes: registerRoutes,
		setLoadingView: setLoadingView,
		setErrorView: setErrorView
	};
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
*
*
* Installs sitemon as a Windows Service using NSSM (http://www.nssm.cc/)
*
*
*/

var prompt = require("prompt"),
	path = require("path"),
	exec = require("child_process").exec,
	os = require("os");

if (os.platform() != 'win32') {
	console.error("Windows is the only supported operating system for this utility");
	process.exit(1);
}

prompt.message = "";
prompt.delimiter = "";
prompt.start();

prompt.get({
	properties: {
		servicename: {
			description: "Service Name",
			default: "Site Monitor",
			type: "string",
			required: true
		},
		servicedescription: {
			description: "Service Description",
			default: "Monitors a URL and, if non-respsonsive, executes a command.",
			type: "string",
			required: true
		},
		pathtonssm: {
			description: "Path to nssm.exe?",
			default: "c:\\nssm-2.23\\win64\\nssm.exe",
			type: "string",
			required: true
		}
	}
}, function(err, result){

	var siteMonPath = path.normalize(__dirname + "/bin/sitemon");
	var nodePath = process.execPath;
	var logDir = path.dirname(path.dirname(siteMonPath));

	var nssmPath = result.pathtonssm;
	var nssmServiceName = result.servicename;
	var nssmServiceDescription = result.servicedescription;
	var nssmInstallCommand = nssmPath + ' install "' + nssmServiceName + '" "' + nodePath + '" "' + siteMonPath + '"';
	var nssmErrorLogPath = path.normalize(logDir + '/stderr.log');
	var nssmOutLogPath = path.normalize(logDir + '/stdout.log');

	var runCommand = function(command, cb) {
		exec(command, function(err, stdout, stderr){
			if (err) console.error(err);
			if (stdout) console.log(stdout);
			if (stderr) console.log(stderr);
			if (cb) {
				cb();
			}
		});
	}

	var setNSSMServiceProperty = function(servicename, property, value, cb) {
		runCommand(nssmPath + ' set "' + servicename + '" ' + property + ' "' + value + '"', function(){
			if (cb) {
				cb();
			}
		});
	}

	runCommand(nssmInstallCommand, function(){
		setNSSMServiceProperty(nssmServiceName, 'Description', nssmServiceDescription, function(){
			setNSSMServiceProperty(nssmServiceName, 'AppStderr', nssmErrorLogPath, function(){
				setNSSMServiceProperty(nssmServiceName, 'AppStdout', nssmOutLogPath, function(){
					console.log("Complete!");
				});
			});
		});
	});

});<commit_msg>set the proper working dir<commit_after>#!/usr/bin/env node

/**
*
*
* Installs sitemon as a Windows Service using NSSM (http://www.nssm.cc/)
*
*
*/

var prompt = require("prompt"),
	path = require("path"),
	exec = require("child_process").exec,
	os = require("os");

if (os.platform() != 'win32') {
	console.error("Windows is the only supported operating system for this utility");
	process.exit(1);
}

prompt.message = "";
prompt.delimiter = "";
prompt.start();

prompt.get({
	properties: {
		servicename: {
			description: "Service Name",
			default: "Site Monitor",
			type: "string",
			required: true
		},
		servicedescription: {
			description: "Service Description",
			default: "Monitors a URL and, if non-respsonsive, executes a command.",
			type: "string",
			required: true
		},
		pathtonssm: {
			description: "Path to nssm.exe?",
			default: "c:\\nssm-2.23\\win64\\nssm.exe",
			type: "string",
			required: true
		}
	}
}, function(err, result){

	var siteMonPath = path.normalize(__dirname + "/bin/sitemon");
	var nodePath = process.execPath;
	var logDir = path.dirname(path.dirname(siteMonPath));

	var nssmPath = result.pathtonssm;
	var nssmServiceName = result.servicename;
	var nssmAppDirectory = path.dirname(siteMonPath);
	var nssmServiceDescription = result.servicedescription;
	var nssmInstallCommand = nssmPath + ' install "' + nssmServiceName + '" "' + nodePath + '" "' + siteMonPath + '"';
	var nssmErrorLogPath = path.normalize(logDir + '/stderr.log');
	var nssmOutLogPath = path.normalize(logDir + '/stdout.log');

	var runCommand = function(command, cb) {
		exec(command, function(err, stdout, stderr){
			if (err) console.error(err);
			if (stdout) console.log(stdout);
			if (stderr) console.log(stderr);
			if (cb) {
				cb();
			}
		});
	}

	var setNSSMServiceProperty = function(servicename, property, value, cb) {
		runCommand(nssmPath + ' set "' + servicename + '" ' + property + ' "' + value + '"', function(){
			if (cb) {
				cb();
			}
		});
	}

	runCommand(nssmInstallCommand, function(){
		setNSSMServiceProperty(nssmServiceName, 'Description', nssmServiceDescription, function(){
			setNSSMServiceProperty(nssmServiceName, 'AppDirectory', nssmAppDirectory, function(){
				setNSSMServiceProperty(nssmServiceName, 'AppStderr', nssmErrorLogPath, function(){
					setNSSMServiceProperty(nssmServiceName, 'AppStdout', nssmOutLogPath, function(){
						console.log("Complete!");
					});
				});
			});
		});
	});

});<|endoftext|>


<commit_before>define(function(require, exports, module) {

module.exports = function(session, options){
    session.introduction = require("text!./intro.html");
    session.preInstallScript = require("text!./check-deps.sh");

    // Node.js
    var NODEVERSION = "v0.10.28";
    var nodeName = "node-" + NODEVERSION + "-"
        + options.platform + "-" + options.arch;

    session.install({
        "name": "Node.js",
        "description": "Node.js " + NODEVERSION
    }, [
        {
            "tar.gz": {
                "url": "http://nodejs.org/dist/" + NODEVERSION + "/" + nodeName + ".tar.gz",
                "target": "~/.c9/node",
                "dir": nodeName
            }
        },
        {
            "bash": require("text!./node.sh")
        }
    ]);

    // Pty.js
    session.install({
        "name": "Pty.js",
        "description": "Pseudo Terminal support. Used by the Cloud9 Terminal",
        "cwd": "~/.c9"
    }, {
        "npm": ["node-gyp", "pty.js@0.2.3"]
    }, function(done){
        session.exec(
            '"~/.c9/node/bin/node" -e "console.log(require(\'pty.js\'))"',
            function(err, stdout, stderr){
                if (!stdout || stdout.indexOf("createTerminal") == -1)
                    err = new Error("Unknown exception installing pty.js: " + stdout);
                done(err);
            });
    });

    // Tmux
    session.install({
        "name": "tmux",
        "description": "Tmux - the terminal multiplexer"
    }, [
        {
            "ubuntu": "tmux",
            "centos": "tmux"
        },
        {
             "bash": require("text!./tmux.sh")
        }
    ]);

    // Show the installation screen
    session.start();
};

});<commit_msg>Add install implicit command<commit_after>define(function(require, exports, module) {

module.exports = function(session, options){
    session.introduction = require("text!./intro.html");
    session.preInstallScript = require("text!./check-deps.sh");

    // // Node.js
    // var NODEVERSION = "v0.10.28";
    // var nodeName = "node-" + NODEVERSION + "-"
    //     + options.platform + "-" + options.arch;

    // session.install({
    //     "name": "Node.js",
    //     "description": "Node.js " + NODEVERSION
    // }, [
    //     {
    //         "tar.gz": {
    //             "url": "http://nodejs.org/dist/" + NODEVERSION + "/" + nodeName + ".tar.gz",
    //             "target": "~/.c9/node",
    //             "dir": nodeName
    //         }
    //     },
    //     {
    //         "bash": require("text!./node.sh")
    //     }
    // ]);

    // // Pty.js
    // session.install({
    //     "name": "Pty.js",
    //     "description": "Pseudo Terminal support. Used by the Cloud9 Terminal",
    //     "cwd": "~/.c9"
    // }, {
    //     "npm": ["node-gyp", "pty.js@0.2.3"]
    // }, function(done){
    //     session.exec(
    //         '"~/.c9/node/bin/node" -e "console.log(require(\'pty.js\'))"',
    //         function(err, stdout, stderr){
    //             if (!stdout || stdout.indexOf("createTerminal") == -1)
    //                 err = new Error("Unknown exception installing pty.js: " + stdout);
    //             done(err);
    //         });
    // });

    // Tmux
    session.install({
        "name": "tmux",
        "description": "Tmux - the terminal multiplexer",
        "cwd": "~/.c9"
    }, {
        "install": [
            {
                "ubuntu": "tmux",
                "centos": "tmux"
            },
            {
                "bash": 'ln -sf $(which tmux) ~/.c9/bin/tmux'
            }
        ],
        "bash": require("text!./tmux.sh")
    });

    // Show the installation screen
    session.start();
};

});<|endoftext|>


<commit_before>var ical = {};
var parser = require('ical');

ical.load = function(args, next) {
  parser.fromURL(args.url, {}, function(err, data) {
    var planStartDate, checkRange, outputFormat;
    var outputs = [];

    checkRange = args.within * 3600 * 1000;

    for(var plan in data) {
      planStartDate = data[plan].start;
      dateDiff = planStartDate - Date.now();

      if (dateDiff < 0) continue;
      if (dateDiff > checkRange) break;

      outputs.push(data[plan].summary + " - " + data[plan].start.toLocaleString());
    }

    next(false, outputs);
  });
}
module.exports = ical;
<commit_msg>iCalフォーマットの開始時刻にタイムゾーンが無い場合の対応 offsetパラメータで任意のオフセットを追加できる様にした<commit_after>var ical = {};
var parser = require('ical');
var moment = require('moment');

ical.load = function(args, next) {
  parser.fromURL(args.url, {}, function(err, data) {
    var planStartDate, checkRange, outputFormat;
    var outputs = [];

    checkRange = args.within * 3600 * 1000;

    for(var plan in data) {
      if (typeof data[plan].start == "undefined") continue;

      planStartDate = moment(data[plan].start);

      if (args.offset) {
        planStartDate.add(args.offset, "hours");
      }

      dateDiff = planStartDate.diff(Date.now());

      if (dateDiff < 0) continue;
      if (dateDiff > checkRange) break;

      outputs.push(data[plan].summary + " - " + data[plan].start.toLocaleString());
    }

    next(false, outputs);
  });
}
module.exports = ical;
<|endoftext|>