<commit_before>jQuery(function ($) {

    var prog_hidden = true,
        loc = window.location,
        $prog_container = $(".progress"),
        $prog = $(".progress-bar"),
        $email = $("#email"),
        $pass = $("#password"),
        $submit = $("#submit"),
        $auth_form = $("#auth-form"),
        $auth_fields = $auth_form.find(":input"),
        $alert = $(".alert"),
        $sync_form = $("#sync-form"),
        $confim_form = $("#confirm-form"),
        $no_confirm_bttn = $confim_form.find("[type=cancel]"),
        rewrite_index = 0,
        rewrite_total = 0,
        feedback,
        num_messages,
        update_progress,
        hide_progress,
        ws = new WebSocket("ws://" + loc.host + (loc.port ? (":" + loc.port) : "")) + "/ws");

    hide_progress = function () {
        $prog_container.fadeOut();
        prog_hidden = true;
    };

    update_progress = function (cur, max) {

        if (prog_hidden) {
            $prog_container.fadeIn();
            prog_hidden = false;
        }

        if (!cur && !max) {

            $prog_container.addClass("progress-striped").addClass("active");
            $prog.attr("aria-valuenow", 1)
                .attr("aria-valuemax", 1)
                .css("width", "100%");

        } else {

            $prog_container.removeClass("progress-striped").removeClass("active");
            $prog.attr("aria-valuenow", cur)
                .attr("aria-valuemax", max)
                .css("width", ((cur / max) * 100) + "%");
        }
    };

    feedback = function (msg, additional_message) {

        $alert.removeClass("alert-info").removeClass("alert-warning");
        $alert.show();

        if (msg.ok) {

            $alert.addClass("alert-info");

        } else {

            $alert.addClass("alert-warning");

        }

        if (additional_message) {

            $alert.html("
" + msg.msg + "

" + additional_message + "
");

        } else {

            $alert.text(msg.msg);

        }
    };

    $auth_form.submit(function () {

        var params = JSON.stringify({
            "email": $email.val(),
            "pass": $pass.val(),
            "type": "connect",
            "limit": 0,
            "simultaneous": 10,
            "rewrite": 1
        });

        $auth_fields.attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $sync_form.submit(function () {

        var params = JSON.stringify({
            "type": "sync"
        });

        $(this).find("[type=submit]").attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $confim_form.submit(function () {

        var params = JSON.stringify({
            "type": "confirm",
        });

        $(this).find("button").attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $no_confirm_bttn.click(function () {

        feedback({msg: "Thank you for your participation in this study."});
        $confim_form.fadeOut();
        return false;
    });

    ws.onmessage = function (evt) {
        var msg = JSON.parse(evt.data);

        switch (msg['type']) {

            case "connect":
                feedback(msg);
                if (!msg.ok) {
                    $auth_fields.removeAttr("disabled");
                } else {
                    $auth_form.fadeOut();
                }
                break;

            case "count":
                feedback(msg);
                num_messages = msg.num;
                break;

            case "downloading":
                feedback(msg);
                update_progress(msg.num, num_messages);
                break;

            case "download-complete":
                feedback(msg, "Please delete any attachments you'd like removed from your GMail account from " + window.gmail.home);
                hide_progress();
                $sync_form.fadeIn();
                break;

            case "file-checking":
                feedback(msg);
                update_progress();
                $sync_form.fadeOut();
                break;

            case "file-checked":
                rewrite_total = msg.num;
                hide_progress();
                $alert.hide();
                $confim_form
                    .fadeIn()
                    .find("p")
                        .text("Are you sure you want to remove " + rewrite_total + " images from your email account?  This action is irreversable.");
                break;

            case "removing":
                $confim_form.fadeOut();
                feedback(msg);
                update_progress(++rewrite_index, rewrite_total);
                break;

            case "removed":
                feedback(msg);
                break;

            case "finished":
                feedback(msg);
                hide_progress();
                break;
        }
    };
});
<commit_msg>fix syntax error in ws location<commit_after>jQuery(function ($) {

    var prog_hidden = true,
        loc = window.location,
        $prog_container = $(".progress"),
        $prog = $(".progress-bar"),
        $email = $("#email"),
        $pass = $("#password"),
        $submit = $("#submit"),
        $auth_form = $("#auth-form"),
        $auth_fields = $auth_form.find(":input"),
        $alert = $(".alert"),
        $sync_form = $("#sync-form"),
        $confim_form = $("#confirm-form"),
        $no_confirm_bttn = $confim_form.find("[type=cancel]"),
        rewrite_index = 0,
        rewrite_total = 0,
        feedback,
        num_messages,
        update_progress,
        hide_progress,
        ws = new WebSocket("ws://" + loc.host + (loc.port ? (":" + loc.port) : "") + "/ws");

    hide_progress = function () {
        $prog_container.fadeOut();
        prog_hidden = true;
    };

    update_progress = function (cur, max) {

        if (prog_hidden) {
            $prog_container.fadeIn();
            prog_hidden = false;
        }

        if (!cur && !max) {

            $prog_container.addClass("progress-striped").addClass("active");
            $prog.attr("aria-valuenow", 1)
                .attr("aria-valuemax", 1)
                .css("width", "100%");

        } else {

            $prog_container.removeClass("progress-striped").removeClass("active");
            $prog.attr("aria-valuenow", cur)
                .attr("aria-valuemax", max)
                .css("width", ((cur / max) * 100) + "%");
        }
    };

    feedback = function (msg, additional_message) {

        $alert.removeClass("alert-info").removeClass("alert-warning");
        $alert.show();

        if (msg.ok) {

            $alert.addClass("alert-info");

        } else {

            $alert.addClass("alert-warning");

        }

        if (additional_message) {

            $alert.html("
" + msg.msg + "

" + additional_message + "
");

        } else {

            $alert.text(msg.msg);

        }
    };

    $auth_form.submit(function () {

        var params = JSON.stringify({
            "email": $email.val(),
            "pass": $pass.val(),
            "type": "connect",
            "limit": 0,
            "simultaneous": 10,
            "rewrite": 1
        });

        $auth_fields.attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $sync_form.submit(function () {

        var params = JSON.stringify({
            "type": "sync"
        });

        $(this).find("[type=submit]").attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $confim_form.submit(function () {

        var params = JSON.stringify({
            "type": "confirm",
        });

        $(this).find("button").attr("disabled", "disabled");
        ws.send(params);

        return false;
    });

    $no_confirm_bttn.click(function () {

        feedback({msg: "Thank you for your participation in this study."});
        $confim_form.fadeOut();
        return false;
    });

    ws.onmessage = function (evt) {
        var msg = JSON.parse(evt.data);

        switch (msg['type']) {

            case "connect":
                feedback(msg);
                if (!msg.ok) {
                    $auth_fields.removeAttr("disabled");
                } else {
                    $auth_form.fadeOut();
                }
                break;

            case "count":
                feedback(msg);
                num_messages = msg.num;
                break;

            case "downloading":
                feedback(msg);
                update_progress(msg.num, num_messages);
                break;

            case "download-complete":
                feedback(msg, "Please delete any attachments you'd like removed from your GMail account from " + window.gmail.home);
                hide_progress();
                $sync_form.fadeIn();
                break;

            case "file-checking":
                feedback(msg);
                update_progress();
                $sync_form.fadeOut();
                break;

            case "file-checked":
                rewrite_total = msg.num;
                hide_progress();
                $alert.hide();
                $confim_form
                    .fadeIn()
                    .find("p")
                        .text("Are you sure you want to remove " + rewrite_total + " images from your email account?  This action is irreversable.");
                break;

            case "removing":
                $confim_form.fadeOut();
                feedback(msg);
                update_progress(++rewrite_index, rewrite_total);
                break;

            case "removed":
                feedback(msg);
                break;

            case "finished":
                feedback(msg);
                hide_progress();
                break;
        }
    };
});
<|endoftext|>


<commit_before>/* Boid prototype */

function Boid(ctx) {
    this.x = Math.random() * ctx.canvas.width;
    this.y = Math.random() * ctx.canvas.height;
    this.heading = Math.random() * 2 * Math.PI - Math.PI;
}

Boid.prototype.radius = 6;
Boid.prototype.speed = 2;
Boid.prototype.radialSpeed = Math.PI / 60;
Boid.prototype.vision = 50;

Boid.prototype.draw = function(ctx) {
    var pointLen = this.radius * 2.5;
    ctx.fillStyle = "blue";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.beginPath();
    ctx.moveTo(this.x + Math.cos(this.heading + Math.PI / 2) * this.radius,
               this.y + Math.sin(this.heading + Math.PI / 2) * this.radius);
    ctx.lineTo(this.x + Math.cos(this.heading + Math.PI) * pointLen,
               this.y + Math.sin(this.heading + Math.PI) * pointLen);
    ctx.lineTo(this.x + Math.cos(this.heading - Math.PI / 2) * this.radius,
               this.y + Math.sin(this.heading - Math.PI / 2) * this.radius);
    ctx.fill();
};

Boid.prototype.distance = function(boid) {
    return Math.sqrt((this.x - boid.x) * (this.x - boid.x) +
                     (this.y - boid.y) * (this.y - boid.y));
};

Boid.prototype.getNeighbors = function(swarm) {
    var neighbors = [];
    for (var i = 0; i < swarm.boids.length; i++) {
        var boid = swarm.boids[i];
        if (this !== boid && this.distance(boid) < this.vision) {
            neighbors.push(boid);
        }
    }
    return neighbors;
};

Boid.wrap = function(value) {
    var min, max;
    if (arguments.length === 2) {
        min = 0;
        max = arguments[1];
    } else if (arguments.length === 3) {
        min = arguments[1];
        max = arguments[2];
    } else {
        throw new Error("wrong number of arguments");
    }
    while (value >= max) value -= (max - min);
    while (value < min) value += (max - min);
    return value;
};

Boid.trim = function(value, limit) {
    return Math.min(limit, Math.max(-limit, value));
};

Boid.meanAngle = function() {
    var sumx = 0, sumy = 0, len = arguments.length;
    for (var i = 0; i < len; i++) {
        sumx += Math.cos(arguments[i]);
        sumy += Math.sin(arguments[i]);
    }
    return Math.atan2(sumy / len, sumx / len);
};

Boid.prototype.step = function(swarm) {
    var neighbors = this.getNeighbors(swarm);
    if (neighbors.length > 0) {
        var meanhx = 0, meanhy = 0;
        var meanx = 0, meany = 0;
        var mindist = this.radius * 2, min = null;
        for (var i = 0; i < neighbors.length; i++) {
            var boid = neighbors[i];
            meanhx += Math.cos(boid.heading);
            meanhy += Math.sin(boid.heading);
            meanx += boid.x;
            meany += boid.y;
            var dist = this.distance(boid);
            if (dist < mindist) {
                mindist = dist;
                min = boid;
            }
        }
        meanhx /= neighbors.length;
        meanhy /= neighbors.length;
        meanx /= neighbors.length;
        meany /= neighbors.length;

        var target;
        if (min) {
            // Keep away!
            target = Math.atan2(this.y - min.y, this.x - min.x);
        } else {
            // Match heading and move towards center
            var meanh = Math.atan2(meanhy, meanhx);
            var center = Math.atan2(meany - this.y, meanx - this.x);
            target = Boid.meanAngle(meanh, meanh, meanh, center);
        }

        // Move in this direction
        var delta = Boid.wrap(target - this.heading, -Math.PI, Math.PI);
        delta = Boid.trim(delta, this.radialSpeed);
        this.heading = Boid.wrap(this.heading + delta, -Math.PI, Math.PI);
    }

    this.move(swarm);
};

Boid.prototype.move = function(swarm) {
    var padding = swarm.padding;
    var width = swarm.ctx.canvas.width, height = swarm.ctx.canvas.height;
    this.x = Boid.wrap(this.x + Math.cos(this.heading) * this.speed,
                       -padding, width + padding * 2);
    this.y = Boid.wrap(this.y + Math.sin(this.heading) * this.speed,
                       -padding, height + padding * 2);
};

/* Swam prototype. */

function Swarm(ctx) {
    this.ctx = ctx;
    this.boids = [];
    var swarm = this;
    this.animate = function() {
        Swarm.step(swarm);
    };
    this.padding = 8;
}

Swarm.prototype.createBoid = function(n) {
    for (var i = 0; i < (n || 1); i++) {
        this.boids.push(new Boid(this.ctx));
    }
};

Swarm.prototype.clear = function() {
    this.boids = [];
};

Swarm.step = function (swarm) {
    var ctx = swarm.ctx;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    for (var i = 0; i < swarm.boids.length; i++) {
        swarm.boids[i].step(swarm);
        swarm.boids[i].draw(ctx);
    }
    setTimeout(swarm.animate, 33);
};

/* Test */

var swarm; // defined globally for skewer
$("document").ready(function() {
    swarm = new Swarm($('#canvas').get(0).getContext("2d"));
    swarm.animate();
    swarm.clear();
    swarm.createBoid(200);
});
<commit_msg>Distance function handles wrap-around.<commit_after>/* Boid prototype */

function Boid(swarm) {
    this.x = Math.random() * swarm.width;
    this.y = Math.random() * swarm.height;
    this.heading = Math.random() * 2 * Math.PI - Math.PI;
}

Boid.prototype.radius = 6;
Boid.prototype.speed = 2;
Boid.prototype.radialSpeed = Math.PI / 60;
Boid.prototype.vision = 50;

Boid.prototype.draw = function(ctx) {
    var pointLen = this.radius * 2.5;
    ctx.fillStyle = "blue";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.beginPath();
    ctx.moveTo(this.x + Math.cos(this.heading + Math.PI / 2) * this.radius,
               this.y + Math.sin(this.heading + Math.PI / 2) * this.radius);
    ctx.lineTo(this.x + Math.cos(this.heading + Math.PI) * pointLen,
               this.y + Math.sin(this.heading + Math.PI) * pointLen);
    ctx.lineTo(this.x + Math.cos(this.heading - Math.PI / 2) * this.radius,
               this.y + Math.sin(this.heading - Math.PI / 2) * this.radius);
    ctx.fill();
};

Boid.prototype.distance = function(boid, width, height) {
    var x0 = Math.min(this.x, boid.x), x1 = Math.max(this.x, boid.x);
    var y0 = Math.min(this.y, boid.y), y1 = Math.max(this.y, boid.y);
    var dx = Math.min(x1 - x0, x0 + width - x1);
    var dy = Math.min(y1 - y0, y0 + height - y1);
    return Math.sqrt(dx * dx + dy * dy);
};

Boid.prototype.getNeighbors = function(swarm) {
    var w = swarm.width, h = swarm.height;
    var neighbors = [];
    for (var i = 0; i < swarm.boids.length; i++) {
        var boid = swarm.boids[i];
        if (this !== boid && this.distance(boid, w, h) < this.vision) {
            neighbors.push(boid);
        }
    }
    return neighbors;
};

Boid.wrap = function(value) {
    var min, max;
    if (arguments.length === 2) {
        min = 0;
        max = arguments[1];
    } else if (arguments.length === 3) {
        min = arguments[1];
        max = arguments[2];
    } else {
        throw new Error("wrong number of arguments");
    }
    while (value >= max) value -= (max - min);
    while (value < min) value += (max - min);
    return value;
};

Boid.trim = function(value, limit) {
    return Math.min(limit, Math.max(-limit, value));
};

Boid.meanAngle = function() {
    var sumx = 0, sumy = 0, len = arguments.length;
    for (var i = 0; i < len; i++) {
        sumx += Math.cos(arguments[i]);
        sumy += Math.sin(arguments[i]);
    }
    return Math.atan2(sumy / len, sumx / len);
};

Boid.prototype.step = function(swarm) {
    var w = swarm.width, h = swarm.height;
    var neighbors = this.getNeighbors(swarm);
    if (neighbors.length > 0) {
        var meanhx = 0, meanhy = 0;
        var meanx = 0, meany = 0;
        var mindist = this.radius * 2, min = null;
        for (var i = 0; i < neighbors.length; i++) {
            var boid = neighbors[i];
            meanhx += Math.cos(boid.heading);
            meanhy += Math.sin(boid.heading);
            meanx += boid.x;
            meany += boid.y;
            var dist = this.distance(boid, w, h);
            if (dist < mindist) {
                mindist = dist;
                min = boid;
            }
        }
        meanhx /= neighbors.length;
        meanhy /= neighbors.length;
        meanx /= neighbors.length;
        meany /= neighbors.length;

        var target;
        if (min) {
            // Keep away!
            target = Math.atan2(this.y - min.y, this.x - min.x);
        } else {
            // Match heading and move towards center
            var meanh = Math.atan2(meanhy, meanhx);
            var center = Math.atan2(meany - this.y, meanx - this.x);
            target = Boid.meanAngle(meanh, meanh, meanh, center);
        }

        // Move in this direction
        var delta = Boid.wrap(target - this.heading, -Math.PI, Math.PI);
        delta = Boid.trim(delta, this.radialSpeed);
        this.heading = Boid.wrap(this.heading + delta, -Math.PI, Math.PI);
    }

    this.move(swarm);
};

Boid.prototype.move = function(swarm) {
    var padding = swarm.padding;
    var width = swarm.width, height = swarm.height;
    this.x = Boid.wrap(this.x + Math.cos(this.heading) * this.speed,
                       -padding, width + padding * 2);
    this.y = Boid.wrap(this.y + Math.sin(this.heading) * this.speed,
                       -padding, height + padding * 2);
};

/* Swam prototype. */

function Swarm(ctx) {
    this.ctx = ctx;
    this.boids = [];
    var swarm = this;
    this.animate = function() {
        Swarm.step(swarm);
    };
    this.padding = 8;
}

Swarm.prototype.createBoid = function(n) {
    for (var i = 0; i < (n || 1); i++) {
        this.boids.push(new Boid(this));
    }
};

Swarm.prototype.clear = function() {
    this.boids = [];
};

Swarm.prototype.__defineGetter__("width", function() {
    return this.ctx.canvas.width;
});

Swarm.prototype.__defineGetter__("height", function() {
    return this.ctx.canvas.height;
});

Swarm.step = function (swarm) {
    var ctx = swarm.ctx;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, swarm.width, swarm.height);

    for (var i = 0; i < swarm.boids.length; i++) {
        swarm.boids[i].step(swarm);
        swarm.boids[i].draw(ctx);
    }
    setTimeout(swarm.animate, 33);
};

/* Test */

var swarm; // defined globally for skewer
$("document").ready(function() {
    swarm = new Swarm($('#canvas').get(0).getContext("2d"));
    swarm.animate();
    swarm.clear();
    swarm.createBoid(200);
});
<|endoftext|>


<commit_before>(function() {
  "use strict";
  RxController.$inject = [ "$http", "$routeParams", "RxFactory" ];
  function RxController($http, $routeParams, RxFactory) {
    var a = this;
    RxFactory.getRx(function(data) {
      a.Rx = data;
      a.rxGenTotalPMT(a.Rx);
      a.getRxCui(a.Rx[0]);
      console.log(a.Rx)
    })
    a.rxGenTotalPMT = function(phy) {
      a.RxPMTTotal = 0;
      $(phy).each(function(index) {
        a.RxPMTTotal = a.RxPMTTotal + Number(phy[index].total_amount_of_payment_usdollars, 2);
      })
    }
    a.hyphenateNDC = function(ref) {
      a.NDC = ref.ndc_of_associated_covered_drug_or_biological1;
      a.NDCArr = [];
      for ( var i = 0; i < 12; i++ ) {
        if (i === 4 || i === 9) {
          a.NDCArr.push("-")
        } else if (i < 4) {
          a.NDCArr.push(String(a.NDC.charAt(i)));
        } else if (i < 9) {
          a.NDCArr.push(String(a.NDC.charAt(i - 1 )));
        } else if (i < 12) {
          a.NDCArr.push(String(a.NDC.charAt(i - 2)));
        }
      }
      a.NDCArr = a.NDCArr.join("");
      return a.NDCArr;
    }
    a.getRxCui = function(ref) {
      a.hyphenNDC = a.hyphenateNDC(ref);
      var url = "http://rxnav.nlm.nih.gov/REST/rxcui.json?idtype=NDC&id=",
      style = {
        b: 5,
        c: 4,
        d: 3
      } ;
      $http.get(url + a.hyphenNDC)
      .success(function(data) {
        a.rxNorm = data.idGroup.rxnormId;
        console.log(a.rxNorm, data);
      })
      .error(function(err) {
        console.log(err);
      })
    }
  }
  angular.module("myApp")
  .controller  ("RxController", RxController)
}());
<commit_msg>RxCui validate for 4-4-2 working<commit_after>(function() {
  "use strict";
  RxController.$inject = [ "$http", "$routeParams", "RxFactory" ];
  function RxController($http, $routeParams, RxFactory) {
    var a = this;
    a.rxNorm = 0;
    RxFactory.getRx(function(data) {
      a.Rx = data;
      a.rxGenTotalPMT(a.Rx);
      a.validateRxCui(a.Rx[0]);
      console.log(a.Rx)
    })
    a.rxGenTotalPMT = function(phy) {
      a.RxPMTTotal = 0;
      $(phy).each(function(index) {
        a.RxPMTTotal = a.RxPMTTotal + Number(phy[index].total_amount_of_payment_usdollars, 2);
      })
    }
    a.hyphenateNDC = function(ref) {
      a.NDC = ref.ndc_of_associated_covered_drug_or_biological1;
      a.NDCArr = [];
      for ( var i = 0; i < 12; i++ ) {
        if (i === 4 || i === 9) {
          a.NDCArr.push("-")
        } else if (i < 4) {
          a.NDCArr.push(String(a.NDC.charAt(i)));
        } else if (i < 9) {
          a.NDCArr.push(String(a.NDC.charAt(i - 1 )));
        } else if (i < 12) {
          a.NDCArr.push(String(a.NDC.charAt(i - 2)));
        }
      }
      a.NDCArr = a.NDCArr.join("");
      return a.NDCArr;
    }
    a.validateRxCui = function(ref) {
      var hyphen = {
        b: 5,
        c: 4,
        d: 3
      };
      if (typeof  a.rxNorm === "undefined") {
        console.log("error with 4-4-2");
      } else {
        console.log("success");
      }
    }
    a.getRxCui = function(ref) {
      a.hyphenNDC = a.hyphenateNDC(ref);
      var url = "http://rxnav.nlm.nih.gov/REST/rxcui.json?idtype=NDC&id=";
      $http.get(url + a.hyphenNDC)
      .success(function(data) {
        a.rxNorm = data.idGroup.rxnormId;
        console.log(a.rxNorm, data);
      })
      .error(function(err) {
        console.log(err);
      })
    }
  }
  angular.module("myApp")
  .controller  ("RxController", RxController)
}());
<|endoftext|>


<commit_before>/**
 * Allow to select on which tree to work and manage creation and deletion of trees
 * File: jstree.tree_selector.js
 *
 * @author    Benoit Jacquemont <benoit@akeneo.com>
 * @copyright 2012 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/MIT  MIT
 *
 * Right now needs the following configuration on the json_data plugin, in order
 * to have a working root node which text and id will be replaced by the data from
 * the selected tree.
 *  "json_data" : {
 *      "data" : [
 *          {
 *              "data": "Loading root...",
 *              "state": "closed",
 *              "attr" : { "id" : "node_1"}
 *          }
 *      ],
 *      "ajax" : {
 *          "url" : "children",
 *          "data" : function (node) {
 *              return {
 *                  "id" : node.attr("id").replace('node_','')
 *              };
 *          }
 *      }
 *  }
 */
/* Group: jstree tree_selector plugin */
(function ($) {
    var tree_select_id = "tree_select";

    $.jstree.plugin("tree_selector", {
        __init : function () {
            this.get_container()
                // Create the tree toolbar and load trees in tree selector
                .bind("init.jstree", $.proxy(function () {
                    var settings = this._get_settings().tree_selector;
                    this.data.tree_selector.ajax = settings.ajax;
                    this.data.tree_selector.data = settings.data;
                    this.data.tree_selector.auto_open_root = settings.auto_open_root;
                    this.data.tree_selector.no_tree_message = settings.no_tree_message;

                    var tree_toolbar = $('
', {
                        id: 'tree_toolbar',
                        class: 'jstree-tree-toolbar'
                    });

                    var tree_select = $('<select>', {
                        id: tree_select_id,
                        class: 'jstree-tree-select',
                        style: 'width:90%'
                    });

                    var this_jstree = this;
                    tree_select.bind('change', function() {
                        this_jstree.switch_tree();
                    });

                    tree_toolbar.html(tree_select);
                    this.get_container_ul().before(tree_toolbar);

                    this.load_trees();

                }, this))
                // Rewrite the root node to link it to the selected tree
                .bind("loaded.jstree", $.proxy(function () {
                    this.switch_tree();

                }, this));
        },
        defaults : {
            ajax : false,
            data : false,
            tree_selector_buttons : false,
            no_tree_message : false
        },
        _fn : {
            refresh : function(obj) {
                this.refresh_trees();

                return this.__call_old();
            },
            switch_tree : function () {
                // Create new root node, place it into the tree and
                // open it if setup to auto_open_root
                var selected_tree = this.get_tree_select().find(':selected');
                var root_node_id = $(selected_tree).attr('value');

                if (!root_node_id) {
                    return null;
                }

                root_node = this._prepare_node(
                    root_node_id,
                    selected_tree.text()
                );

                this.get_container_ul().empty();
                this.get_container_ul().append(root_node);

                this.close_node(root_node);
                this.clean_node();

                if (this.data.tree_selector.auto_open_root) {
                    this.open_node(root_node);
                }
            },
            get_tree_select : function () {
                return $("#" + tree_select_id);
            },
            load_trees: function () {
                var trees;

                if (this.data.tree_selector.data) {
                    trees = this._load_data_trees();
                } else if (this.data.tree_selector.ajax) {
                    trees = this._load_ajax_trees();
                } else {
                    throw "jquery.jstree.tree_selector : Neither data nor ajax settings supplied for trees.";
                }

                this.get_tree_select().empty();

                // In case of no tree loaded, display the no_tree_message
                // if setup
                if (trees.length === 0 && this.data.tree_selector.no_tree_message) {
                    var no_tree_option = $('<option>', {
                        text: this.data.tree_selector.no_tree_message,
                        value: -1,
                        disabled: true,
                        selected: true
                    });
                    this.get_tree_select().append(no_tree_option);
                }

                var this_jstree = this;
                $.each(trees, function (index, tree) {
                    var option = $('<option>', {
                        value: tree.id,
                        text: tree.title
                    });
                    if (index === 0) {
                        option.prop('defaultSelected', true);
                    }
                    this_jstree.get_tree_select().append(option);
                });

                this.get_container().trigger('trees_loaded.jstree', tree_select_id);
            },
            _load_data_trees: function () {
                var trees_data = this.data.tree_selector.data;

                return $.parseJSON(trees_data);
            },
            _load_ajax_trees: function () {
                var trees_url = this.data.tree_selector.ajax.url;
                var trees = [];

                $.ajax({
                    url: trees_url,
                    async: false,
                    dataType: 'json'
                }).done( function(ajax_trees) {
                    trees = ajax_trees;
                });

                return trees;

            },
            _prepare_node: function (id, node_name) {
                var node = $('
', {
                    id: id,
                    rel: 'folder'
                });

                // Make the node "openable" by switching back to initial state
                node.prepend(" ");
                node.removeClass('jstree-leaf');
                node.addClass('jstree-close');
                node.addClass('jstree-closed');

                var node_link = $('', {
                    text: node_name
                });

                node_link.prepend(" ");
                node.append(node_link);

                return node;
            },
            refresh_trees: function() {
                this.get_tree_select().empty();
                this.load_trees();
                this.switch_tree();
            },
            get_tree_id: function() {
                root_node = this.get_container_ul().find('li')[0];

                return $(root_node).attr('id');

            }
        }
    });
    // include the tree_selector plugin by default on available plugins list
    $.jstree.defaults.plugins.push("tree_selector");
})(jQuery);
<commit_msg>BAP-117 The jstree plugin is to specific to segmentation tree, moving it there<commit_after><|endoftext|>


<commit_before>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(studid, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log("studid: " + id);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<commit_msg>inactief zetten van link<commit_after>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(studid, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log("studid: " + studid);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>describe("System module JS test starts here", function () {

    describe("System module - setting directly test starts here", function () {

        if (isApplePlatform()) {
            it("VT300-003 | should set applicationIconBadge to 1", function () {
                Rho.System.applicationIconBadge = 1;
                expect(Rho.System.applicationIconBadge).toEqual(1);
            });

            it("VT300-004 | should set applicationIconBadge to 0", function () {
                Rho.System.applicationIconBadge = 0;
                expect(Rho.System.applicationIconBadge).toEqual(0);
            });
        }

        if (isAnyWindowsFamilyPlatform()) {
            it("VT300-022 | call getProperty with httpProxyURI (RhoSimpulator support it only on Windows)| 'http://wwwgate0.mot.com:1080'", function () {

                Rho.System.httpProxyURI = 'http://wwwgate0.mot.com:1080';
                var data = Rho.System.getProperty('httpProxyURI');
                expect(data).toEqual('http://wwwgate0.mot.com:1080');

            });
        }

        if (isWindowsDesktopPlatform()) {

            it("VT300-033 | set lockWindowSize as True, call getProperty with lockWindowSize (RhoSimpulator support it only on Windows)| true", function () {

                Rho.System.lockWindowSize = true;
                var data = Rho.System.getProperty('lockWindowSize');
                expect(data).toEqual('true');

            });

            it("VT300-034 | set lockWindowSize as false, call getProperty with lockWindowSize (RhoSimpulator support it only on Windows)| false", function () {

                Rho.System.lockWindowSize = false;
                var data = Rho.System.getProperty('lockWindowSize');
                expect(data).toEqual('false');

            });

        }

        if (isAndroidOrApplePlatform()) {

            it("VT300-046 | set screenAutoRotate as false, call getProperty with screenAutoRotate | false", function () {

                Rho.System.screenAutoRotate = false;
                var data = Rho.System.getProperty('screenAutoRotate');
                expect(data).toEqual('false');
            });

            it("VT300-047 | set screenAutoRotate as true, call getProperty with screenAutoRotate | true", function () {

                Rho.System.screenAutoRotate = true;
                var data = Rho.System.getProperty('screenAutoRotate');
                expect(data).toEqual('true');

            });

            it("VT300-054 | set screenSleeping as true, call getProperty with screenSleeping | true", function () {

                Rho.System.screenSleeping = true;
                var data = Rho.System.getProperty('screenSleeping');
                expect(data).toEqual('true');

            });

            it("VT300-055 | set screenSleeping as false, call getProperty with screenSleeping | false", function () {

                Rho.System.screenSleeping = false;
                var data = Rho.System.getProperty('screenSleeping');
                expect(data).toEqual('false');

            });
        }

        if (isWindowsMobileOrWindowsDesktopPlatform()) {

            it("VT278-187 | call getRegistrySetting with hive as HKLM type as MULTISZ subkey as Software setting as Rhoelements value as hello world , call setRegistrySetting with hive, subkey and setting | hello world", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'MULTISZ', key: 'Software', setting: 'RhoElementsTest', value: 'hello world', persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software', setting: 'RhoElementsTest'});
                expect(data).toEqual('hello world');

            });

            it("VT278-189 | call setRegistrySetting with hive, subkey and setting and check the ret value | 10101010", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'Rho', value: '10101010', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'Rho'});
                expect(data).toEqual("10101010");

            });

            it("VT278-190 | call setRegistrySetting with invalid key and check the ret value | 1010101", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Honey', setting: 'RhoElementsTest', value: '1010101', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Honey', setting: 'RhoElementsTest'});
                expect(data).toEqual("1010101");

            });

            it("VT278-191 | call deleteRegistrySetting  with Persistence  check the return value | Test123", function () {

                Rho.System.setRegistrySetting({hive: 'HKCU', type: 'String', key: 'Software', setting: 'RhoElementsTest', value: 'Test123', persistent: true});
                var actual = Rho.System.deleteRegistrySetting({hive: 'HKCU', key: 'Software', setting: 'RhoElementsTest'});
                expect(actual).toEqual(true);
            });

            it("VT278-192 | call deleteRegistrySetting with settings not exist  | false", function () {

                var data = Rho.System.deleteRegistrySetting({hive: 'HKLM', key: 'Softy', setting: 'RhoElementsTest', persistent: true});
                expect(data).toEqual(false);

            });

            it("VT278-193 | set and getRegistry setting with HKU and persistence as True and type MultiSZ | hello world", function () {

                Rho.System.setRegistrySetting({hive: 'HKU', type: 'MultiSZ', key: 'Software', setting: 'RhoElementsTest', value: "StringA\\nStringB\\nStringC", persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKU', key: 'Software', setting: 'RhoElementsTest'});
                expect(data).toEqual("StringA\nStringB\nStringC");

            });

            it("VT278-194 | set and getRegistry setting with HKCU and persistence as False and Type as String | Test123", function () {

                Rho.System.setRegistrySetting({hive: 'HKCU', type: 'String', key: 'Software', setting: 'Motorola', value: 'Test123', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKCU', key: 'Software', setting: 'Motorola'});
                expect(data).toEqual('Test123');

            });

            it("VT278-195 | set and getRegistry setting with HKCR and persistence as False and Type as DWORD | 12345", function () {

                Rho.System.setRegistrySetting({hive: 'HKCR', type: 'DWORD', key: 'Software', setting: 'Symbol', value: '12345', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKCR', key: 'Software', setting: 'Symbol'});
                expect(data).toEqual('12345');

            });

            it("VT278-196 | set and getRegistry setting with HKLM and persistence True and Type as Binary | 111111", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'RhoTnV', value: '111111', persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software', setting: 'RhoTnV'});
                expect(data).toEqual('111111');

            });

            it("VT278-197 | set and getRegistry setting with HKLM and persistence False and Type as Binary and key as multilevel path | 111111", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software\Symbol\Audio', setting: 'Rhoelement', value: '111111', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software\Symbol\Audio', setting: 'Rhoelement'});
                expect(data).toEqual('111111');

            });

            it("VT278-198 | call getRegistry setting with invalid properties | ", function () {

                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Boo', setting: 'Rhoelement'});
                expect(data).toEqual('');

            });

        }

    });

    describe("System module - setProperty / getProperhy tests starts Here", function () {

        for (var i = 0; i < sys_setget_property.length; i++) {
            (function (idx) {

                var record = sys_setget_property[i];
                var testName = record['testName'];
                var suitablePlatforms = record['osType'];
                var propertyName = record['propertyName'];
                var stringValue = record['propertyValue'];
                var expectedValue = record['expectedResult'];

                if (isTestApplicable(suitablePlatforms)) {
                    it(testName, function () {
                        Rho.System.setProperty(propertyName, stringValue)

                        var actual = Rho.System.getProperty(propertyName);
                        expect(actual).toEqual(expectedValue);
                    });
                }
            })(i);
        }
    });

    describe("System module - setProperties / getProperties test starts here", function () {

        for (var i = 0; i < sys_setget_properties.length; i++) {
            (function (idx) {

                var record = sys_setget_property[i];
                var testName = record['testName'];
                var suitablePlatforms = record['osType'];
                var propertyName = record['propertyName'];
                var stringValue = record['propertyValue'];
                var expectedValue = record['expectedResult'];

                if (isTestApplicable(suitablePlatforms)) {
                    it(sys_setget_properties[idx]['testName'], function () {

                        var propertyValue = stringValue;
                        if (["true", "false"].indexOf(stringValue) != -1) {
                            propertyValue = (stringValue == "true" ? true : false);
                        }
                        if (/^\d+$/.test(stringValue)) {
                            propertyValue = parseInt(stringValue);
                        }
                        var obj = {};
                        obj[propertyName] = propertyValue;
                        Rho.System.setProperties(obj);

                        var readedObj =  Rho.System.getProperties([propertyName]);
                        expect(readedObj[propertyName]).toEqual(expectedValue);
                    });
                }
            })(i);
        }
    });

});<commit_msg>Moved tests for System.zip/unzip from systemRE1Spec.js to system_js_spec.js<commit_after>describe("System module JS test starts here", function () {

    describe("System module - setting directly test starts here", function () {

        if (isApplePlatform()) {
            it("VT300-003 | should set applicationIconBadge to 1", function () {
                Rho.System.applicationIconBadge = 1;
                expect(Rho.System.applicationIconBadge).toEqual(1);
            });

            it("VT300-004 | should set applicationIconBadge to 0", function () {
                Rho.System.applicationIconBadge = 0;
                expect(Rho.System.applicationIconBadge).toEqual(0);
            });
        }

        if (isAnyWindowsFamilyPlatform()) {
            it("VT300-022 | call getProperty with httpProxyURI (RhoSimpulator support it only on Windows)| 'http://wwwgate0.mot.com:1080'", function () {

                Rho.System.httpProxyURI = 'http://wwwgate0.mot.com:1080';
                var data = Rho.System.getProperty('httpProxyURI');
                expect(data).toEqual('http://wwwgate0.mot.com:1080');

            });
        }

        if (isWindowsDesktopPlatform()) {

            it("VT300-033 | set lockWindowSize as True, call getProperty with lockWindowSize (RhoSimpulator support it only on Windows)| true", function () {

                Rho.System.lockWindowSize = true;
                var data = Rho.System.getProperty('lockWindowSize');
                expect(data).toEqual('true');

            });

            it("VT300-034 | set lockWindowSize as false, call getProperty with lockWindowSize (RhoSimpulator support it only on Windows)| false", function () {

                Rho.System.lockWindowSize = false;
                var data = Rho.System.getProperty('lockWindowSize');
                expect(data).toEqual('false');

            });

        }

        if (isAndroidOrApplePlatform()) {

            it("VT300-046 | set screenAutoRotate as false, call getProperty with screenAutoRotate | false", function () {

                Rho.System.screenAutoRotate = false;
                var data = Rho.System.getProperty('screenAutoRotate');
                expect(data).toEqual('false');
            });

            it("VT300-047 | set screenAutoRotate as true, call getProperty with screenAutoRotate | true", function () {

                Rho.System.screenAutoRotate = true;
                var data = Rho.System.getProperty('screenAutoRotate');
                expect(data).toEqual('true');

            });

            it("VT300-054 | set screenSleeping as true, call getProperty with screenSleeping | true", function () {

                Rho.System.screenSleeping = true;
                var data = Rho.System.getProperty('screenSleeping');
                expect(data).toEqual('true');

            });

            it("VT300-055 | set screenSleeping as false, call getProperty with screenSleeping | false", function () {

                Rho.System.screenSleeping = false;
                var data = Rho.System.getProperty('screenSleeping');
                expect(data).toEqual('false');

            });
        }

        if (isWindowsMobileOrWindowsDesktopPlatform()) {

            it("VT278-187 | call getRegistrySetting with hive as HKLM type as MULTISZ subkey as Software setting as Rhoelements value as hello world , call setRegistrySetting with hive, subkey and setting | hello world", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'MULTISZ', key: 'Software', setting: 'RhoElementsTest', value: 'hello world', persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software', setting: 'RhoElementsTest'});
                expect(data).toEqual('hello world');

            });

            it("VT278-189 | call setRegistrySetting with hive, subkey and setting and check the ret value | 10101010", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'Rho', value: '10101010', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'Rho'});
                expect(data).toEqual("10101010");

            });

            it("VT278-190 | call setRegistrySetting with invalid key and check the ret value | 1010101", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Honey', setting: 'RhoElementsTest', value: '1010101', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Honey', setting: 'RhoElementsTest'});
                expect(data).toEqual("1010101");

            });

            it("VT278-191 | call deleteRegistrySetting  with Persistence  check the return value | Test123", function () {

                Rho.System.setRegistrySetting({hive: 'HKCU', type: 'String', key: 'Software', setting: 'RhoElementsTest', value: 'Test123', persistent: true});
                var actual = Rho.System.deleteRegistrySetting({hive: 'HKCU', key: 'Software', setting: 'RhoElementsTest'});
                expect(actual).toEqual(true);
            });

            it("VT278-192 | call deleteRegistrySetting with settings not exist  | false", function () {

                var data = Rho.System.deleteRegistrySetting({hive: 'HKLM', key: 'Softy', setting: 'RhoElementsTest', persistent: true});
                expect(data).toEqual(false);

            });

            it("VT278-193 | set and getRegistry setting with HKU and persistence as True and type MultiSZ | hello world", function () {

                Rho.System.setRegistrySetting({hive: 'HKU', type: 'MultiSZ', key: 'Software', setting: 'RhoElementsTest', value: "StringA\\nStringB\\nStringC", persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKU', key: 'Software', setting: 'RhoElementsTest'});
                expect(data).toEqual("StringA\nStringB\nStringC");

            });

            it("VT278-194 | set and getRegistry setting with HKCU and persistence as False and Type as String | Test123", function () {

                Rho.System.setRegistrySetting({hive: 'HKCU', type: 'String', key: 'Software', setting: 'Motorola', value: 'Test123', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKCU', key: 'Software', setting: 'Motorola'});
                expect(data).toEqual('Test123');

            });

            it("VT278-195 | set and getRegistry setting with HKCR and persistence as False and Type as DWORD | 12345", function () {

                Rho.System.setRegistrySetting({hive: 'HKCR', type: 'DWORD', key: 'Software', setting: 'Symbol', value: '12345', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKCR', key: 'Software', setting: 'Symbol'});
                expect(data).toEqual('12345');

            });

            it("VT278-196 | set and getRegistry setting with HKLM and persistence True and Type as Binary | 111111", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software', setting: 'RhoTnV', value: '111111', persistent: true});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software', setting: 'RhoTnV'});
                expect(data).toEqual('111111');

            });

            it("VT278-197 | set and getRegistry setting with HKLM and persistence False and Type as Binary and key as multilevel path | 111111", function () {

                Rho.System.setRegistrySetting({hive: 'HKLM', type: 'Binary', key: 'Software\Symbol\Audio', setting: 'Rhoelement', value: '111111', persistent: false});
                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Software\Symbol\Audio', setting: 'Rhoelement'});
                expect(data).toEqual('111111');

            });

            it("VT278-198 | call getRegistry setting with invalid properties | ", function () {

                var data = Rho.System.getRegistrySetting({hive: 'HKLM', key: 'Boo', setting: 'Rhoelement'});
                expect(data).toEqual('');

            });

        }

    });

    describe("System module - setProperty / getProperhy tests starts Here", function () {

        for (var i = 0; i < sys_setget_property.length; i++) {
            (function (idx) {

                var record = sys_setget_property[i];
                var testName = record['testName'];
                var suitablePlatforms = record['osType'];
                var propertyName = record['propertyName'];
                var stringValue = record['propertyValue'];
                var expectedValue = record['expectedResult'];

                if (isTestApplicable(suitablePlatforms)) {
                    it(testName, function () {
                        Rho.System.setProperty(propertyName, stringValue)

                        var actual = Rho.System.getProperty(propertyName);
                        expect(actual).toEqual(expectedValue);
                    });
                }
            })(i);
        }
    });

    describe("System module - setProperties / getProperties test starts here", function () {

        for (var i = 0; i < sys_setget_properties.length; i++) {
            (function (idx) {

                var record = sys_setget_property[i];
                var testName = record['testName'];
                var suitablePlatforms = record['osType'];
                var propertyName = record['propertyName'];
                var stringValue = record['propertyValue'];
                var expectedValue = record['expectedResult'];

                if (isTestApplicable(suitablePlatforms)) {
                    it(sys_setget_properties[idx]['testName'], function () {

                        var propertyValue = stringValue;
                        if (["true", "false"].indexOf(stringValue) != -1) {
                            propertyValue = (stringValue == "true" ? true : false);
                        }
                        if (/^\d+$/.test(stringValue)) {
                            propertyValue = parseInt(stringValue);
                        }
                        var obj = {};
                        obj[propertyName] = propertyValue;
                        Rho.System.setProperties(obj);

                        var readedObj =  Rho.System.getProperties([propertyName]);
                        expect(readedObj[propertyName]).toEqual(expectedValue);
                    });
                }
            })(i);
        }
    });

    describe("FileSystem tests", function () {

        var tempDirectory = Rho.RhoFile.join(Rho.Application.userFolder, 'tempDirectory');
        var target = Rho.RhoFile.join(tempDirectory, 'target.zip');
        var sourceA = Rho.RhoFile.join(Rho.Application.publicFolder, 'do not remove me.txt');
        var sourceB = Rho.RhoFile.join(Rho.Application.publicFolder, 'do not remove me too.txt');

        beforeEach(function () {
            Rho.RhoFile.makeDir(tempDirectory);
        });

        afterEach(function () {
            Rho.RhoFile.deleteRecursive(tempDirectory);
        });

        it(" | should zip file without password", function () {
            expect(Rho.RhoFile.exists(target)).toEqual(false);

            Rho.System.zipFile(target, sourceA);
            expect(Rho.RhoFile.exists(target)).toEqual(true);
        });

        it(" | it should zip file with password", function () {
            expect(Rho.RhoFile.exists(target)).toEqual(false);

            Rho.System.zipFile(target, sourceA, 'password');
            expect(Rho.RhoFile.exists(target)).toEqual(true);
        });

        it("| it should unzip file without password", function () {
            Rho.System.zipFile(target, sourceA);

            Rho.System.unzipFile(target);
            expect(Rho.RhoFile.exists(Rho.RhoFile.join(tempDirectory, 'do not remove me.txt'))).toEqual(true);
        });

        it("| it should unzip file with password", function () {
            Rho.System.zipFile(target, sourceA, 'password');

            Rho.System.unzipFile(target, 'password');
            expect(Rho.RhoFile.exists(Rho.RhoFile.join(tempDirectory, 'do not remove me.txt'))).toEqual(true);
        });

        it("Test zipFiles method without password", function () {
            expect(Rho.RhoFile.exists(target)).toEqual(false);

            var sources = [];
            sources[0] = sourceA;
            sources[1] = sourceB;

            Rho.System.zipFiles(target, tempDirectory, sources);
            expect(Rho.RhoFile.exists(target)).toEqual(true);
        });

        it("Test zipFiles method with password", function () {
            expect(Rho.RhoFile.exists(target)).toEqual(false);

            var sources = [];
            sources[0] = sourceA;
            sources[1] = sourceB;

            var result = Rho.System.zipFiles(target, tempDirectory, sources, 'password');
            expect(result).toEqual(0);
            expect(Rho.RhoFile.exists(target)).toEqual(true);
        });
    });

});<|endoftext|>


<commit_before>var url = require('url');

function startsWith(a, b) {
    return a.indexOf(b) === 0;
}

function parseLink(link) {
    // var re = /.*stackoverflow.com\/questions\/(\d+)\//;
    var parsed = url.parse(link);

    parsed.hostname
}

module.exports = parseLink;
<commit_msg>Add missing semicolon<commit_after>var url = require('url');

function startsWith(a, b) {
    return a.indexOf(b) === 0;
}

function parseLink(link) {
    // var re = /.*stackoverflow.com\/questions\/(\d+)\//;
    var parsed = url.parse(link);

    parsed.hostname;
}

module.exports = parseLink;
<|endoftext|>


<commit_before>const rollupPluginIstanbul = require('rollup-plugin-istanbul');
const rollupPluginBabel = require('rollup-plugin-babel');
const { execSync } = require('child_process');
const { browserStack, saucelabs } = require('./karma.browsers');

module.exports = (config) => {
  const options = {
    reporters: ['progress', 'coverage'],
    frameworks: ['mocha'],
    files: [
      { pattern: require.resolve('chai/chai'), watched: false },
      { pattern: require.resolve('vue/dist/vue'), watched: false },
      'https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame',
      { pattern: require.resolve('js-polyfills/typedarray.js'), watched: false },
      { pattern: require.resolve('three'), watched: false },
      { pattern: 'test/index.js', watched: false },
      { pattern: 'test/**/*.spec.js' },
      { pattern: 'test/helvetiker_regular.typeface.json', included: false, watched: false },
      { pattern: 'test/helvetiker_bold.typeface.json', included: false, watched: false },
      { pattern: 'test/sample_texture.png', included: false, watched: false },
    ],
    preprocessors: {
      'test/index.js': ['rollup'],
      'test/**/*.spec.js': ['babel'],
    },
    rollupPreprocessor: {
      output: {
        format: 'iife',
        name: 'VueGL',
        globals: {
          three: 'THREE',
        },
        sourcemap: 'inline',
      },
      intro: execSync('babel-external-helpers -t var'),
      external: 'three',
      plugins: [
        rollupPluginIstanbul({ include: 'src/**' }),
        rollupPluginBabel(),
      ],
    },
    coverageReporter: {
      type: 'text-summary',
    },
  };

  if (process.env.CI) {
    options.junitReporter = { outputDir: 'junit' };
    options.coverageReporter = { type: 'lcovonly', dir: 'coverage' };
    options.reporters = ['coverage', 'junit', 'dots'];
    options.browserNoActivityTimeout = 30000;
    options.client = { mocha: { timeout : 10000 } };
    if (process.env.CIRCLE_BRANCH === 'master') {
      options.concurrency = 4;
      options.reporters.push('saucelabs');
      options.sauceLabs = {
        testName: 'VueGL unit test',
        recordScreenshots: false,
        public: 'public restricted',
      };
      options.customLaunchers = saucelabs;
    } else {
      options.concurrency = 2;
      options.reporters.push('BrowserStack');
      options.browserStack = {
        startTunnel: true,
        video: false,
      };
      options.customLaunchers = browserStack;
    }
    options.browsers = Object.keys(options.customLaunchers);
    options.singleRun = true;
  }

  config.set(options);
};
<commit_msg>style: Remove an extra space after the object key.<commit_after>const rollupPluginIstanbul = require('rollup-plugin-istanbul');
const rollupPluginBabel = require('rollup-plugin-babel');
const { execSync } = require('child_process');
const { browserStack, saucelabs } = require('./karma.browsers');

module.exports = (config) => {
  const options = {
    reporters: ['progress', 'coverage'],
    frameworks: ['mocha'],
    files: [
      { pattern: require.resolve('chai/chai'), watched: false },
      { pattern: require.resolve('vue/dist/vue'), watched: false },
      'https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame',
      { pattern: require.resolve('js-polyfills/typedarray.js'), watched: false },
      { pattern: require.resolve('three'), watched: false },
      { pattern: 'test/index.js', watched: false },
      { pattern: 'test/**/*.spec.js' },
      { pattern: 'test/helvetiker_regular.typeface.json', included: false, watched: false },
      { pattern: 'test/helvetiker_bold.typeface.json', included: false, watched: false },
      { pattern: 'test/sample_texture.png', included: false, watched: false },
    ],
    preprocessors: {
      'test/index.js': ['rollup'],
      'test/**/*.spec.js': ['babel'],
    },
    rollupPreprocessor: {
      output: {
        format: 'iife',
        name: 'VueGL',
        globals: {
          three: 'THREE',
        },
        sourcemap: 'inline',
      },
      intro: execSync('babel-external-helpers -t var'),
      external: 'three',
      plugins: [
        rollupPluginIstanbul({ include: 'src/**' }),
        rollupPluginBabel(),
      ],
    },
    coverageReporter: {
      type: 'text-summary',
    },
  };

  if (process.env.CI) {
    options.junitReporter = { outputDir: 'junit' };
    options.coverageReporter = { type: 'lcovonly', dir: 'coverage' };
    options.reporters = ['coverage', 'junit', 'dots'];
    options.browserNoActivityTimeout = 30000;
    options.client = { mocha: { timeout: 10000 } };
    if (process.env.CIRCLE_BRANCH === 'master') {
      options.concurrency = 4;
      options.reporters.push('saucelabs');
      options.sauceLabs = {
        testName: 'VueGL unit test',
        recordScreenshots: false,
        public: 'public restricted',
      };
      options.customLaunchers = saucelabs;
    } else {
      options.concurrency = 2;
      options.reporters.push('BrowserStack');
      options.browserStack = {
        startTunnel: true,
        video: false,
      };
      options.customLaunchers = browserStack;
    }
    options.browsers = Object.keys(options.customLaunchers);
    options.singleRun = true;
  }

  config.set(options);
};
<|endoftext|>


<commit_before>/* jslint node: true */
'use strict';

//var SegfaultHandler = require('segfault-handler');
//SegfaultHandler.registerHandler('enigma-bbs-segfault.log');

//	ENiGMA½
let conf		= require('./config.js');
let logger		= require('./logger.js');
let miscUtil	= require('./misc_util.js');
let database	= require('./database.js');
let clientConns	= require('./client_connections.js');

let paths		= require('path');
let async		= require('async');
let util		= require('util');
let _			= require('lodash');
let assert		= require('assert');
let mkdirp 		= require('mkdirp');

//	our main entry point
exports.bbsMain	= bbsMain;

function bbsMain() {
	async.waterfall(
		[
			function processArgs(callback) {
				const args = process.argv.slice(2);

				var configPath;

				if(args.indexOf('--help') > 0) {
					//	:TODO: display help
				} else {
					let argCount = args.length;
					for(let i = 0; i < argCount; ++i) {
						const arg = args[i];
						if('--config' === arg) {
							configPath = args[i + 1];
						}
					}
				}

				callback(null, configPath || conf.getDefaultPath(), _.isString(configPath));
			},
			function initConfig(configPath, configPathSupplied, callback) {
				conf.init(configPath, function configInit(err) {

					//
					//	If the user supplied a path and we can't read/parse it
					//	then it's a fatal error
					//
					if(err) {
						if('ENOENT' === err.code)  {
							if(configPathSupplied) {
								console.error('Configuration file does not exist: ' + configPath);
							} else {
								configPathSupplied = null;	//	make non-fatal; we'll go with defaults
							}
						} else {
							console.error(err.toString());
						}
					}
					callback(err);
				});
			},
			function initSystem(callback) {
				initialize(function init(err) {
					if(err) {
						console.error('Error initializing: ' + util.inspect(err));
					}
					callback(err);
				});
			},
			function listenConnections(callback) {
				startListening(callback);
			}
		],
		function complete(err) {
			if(err) {
				logger.log.error(err);
			}
		}
	);
}

function initialize(cb) {
	async.series(
		[
			function createMissingDirectories(callback) {
				async.each(Object.keys(conf.config.paths), function entry(pathKey, next) {
					mkdirp(conf.config.paths[pathKey], function dirCreated(err) {
						if(err) {
							console.error('Could not create path: ' + conf.config.paths[pathKey] + ': ' + err.toString());
						}
						next(err);
					});
				}, function dirCreationComplete(err) {
					callback(err);
				});
			},
			function basicInit(callback) {
				logger.init();

				process.on('SIGINT', function onSigInt() {
					logger.log.info('Process interrupted, shutting down...');

					var activeConnections = clientConns.getActiveConnections();
					var i = activeConnections.length;
					while(i--) {
						activeConnections[i].term.write('\n\nServer is shutting down NOW! Disconnecting...\n\n');
						clientConns.removeClient(activeConnections[i]);
					}

					process.exit();
				});

				//	Init some extensions
				require('string-format').extend(String.prototype, require('./string_util.js').stringFormatExtensions);

				callback(null);
			},
			function initDatabases(callback) {
				database.initializeDatabases(callback);
			},
			function initSystemProperties(callback) {
				require('./system_property.js').loadSystemProperties(callback);
			},
			function initThemes(callback) {
				//	Have to pull in here so it's after Config init
				var theme = require('./theme.js');
				theme.initAvailableThemes(function onThemesInit(err, themeCount) {
					logger.log.info({ themeCount : themeCount }, 'Themes initialized');
					callback(err);
				});
			},
			function loadSysOpInformation(callback) {
				//
				//	If user 1 has been created, we have a SysOp. Cache some information
				//	into Config.
				//
				var user = require('./user.js');	//	must late load

				user.getUserName(1, function unLoaded(err, sysOpUsername) {
					if(err) {
						callback(null);	//	non-fatal here
					} else {
						//
						//	Load some select properties to cache
						//
						var propLoadOpts = {
							userId	: 1,
							names	: [ 'real_name', 'sex', 'email_address' ],
						};

						user.loadProperties(propLoadOpts, function propsLoaded(err, props) {
							if(!err) {
								conf.config.general.sysOp = {
									username	: sysOpUsername,
									properties	: props,
								};

								logger.log.info( { sysOp : conf.config.general.sysOp }, 'System Operator information cached');
							}
							callback(null);	//	any error is again, non-fatal here
						});
					}
				});
			},
			function readyMessageNetworkSupport(callback) {
				require('./msg_network.js').startup(callback);
			}
		],
		function onComplete(err) {
			cb(err);
		}
	);
}

function startListening(cb) {
	if(!conf.config.servers) {
		//	:TODO: Log error ... output to stderr as well. We can do it all with the logger
		//logger.log.error('No servers configured');
		cb(new Error('No servers configured'));
		return;
	}

	let moduleUtil = require('./module_util.js');	//	late load so we get Config

	moduleUtil.loadModulesForCategory('servers', (err, module) => {
		if(err) {
			logger.log.info(err);
			return;
		}

		const port = parseInt(module.runtime.config.port);
		if(isNaN(port)) {
			logger.log.error( { port : module.runtime.config.port, server : module.moduleInfo.name }, 'Cannot load server (Invalid port)');
			return;
		}

		const moduleInst	= new module.getModule();
		const server		= moduleInst.createServer();

		//	:TODO: handle maxConnections, e.g. conf.maxConnections

		server.on('client', function newClient(client, clientSock) {
			//
			//	Start tracking the client. We'll assign it an ID which is
			//	just the index in our connections array.
			//
			if(_.isUndefined(client.session)) {
				client.session = {};
			}

			client.session.serverName 	= module.moduleInfo.name;
			client.session.isSecure		= module.moduleInfo.isSecure || false;

			clientConns.addNewClient(client, clientSock);

			client.on('ready', function clientReady(readyOptions) {

				client.startIdleMonitor();

				//	Go to module -- use default error handler
				prepareClient(client, function clientPrepared() {
					require('./connect.js').connectEntry(client, readyOptions.firstMenu);
				});
			});

			client.on('end', function onClientEnd() {
				clientConns.removeClient(client);
			});

			client.on('error', function onClientError(err) {
				logger.log.info({ clientId : client.session.id }, 'Connection error: %s' % err.message);
			});

			client.on('close', function onClientClose(hadError) {
				var l = hadError ? logger.log.info : logger.log.debug;
				l( { clientId : client.session.id }, 'Connection closed');

				clientConns.removeClient(client);
			});

			client.on('idle timeout', function idleTimeout() {
				client.log.info('User idle timeout expired');

				client.menuStack.goto('idleLogoff', function goMenuRes(err) {
					if(err) {
						//	likely just doesn't exist
						client.term.write('\nIdle timeout expired. Goodbye!\n');
						client.end();
					}
				});
			});
		});

		server.on('error', function serverErr(err) {
			logger.log.info(err);	//	'close' should be handled after
		});

		server.listen(port);

		logger.log.info(
			{ server : module.moduleInfo.name, port : port }, 'Listening for connections');
	}, err => {
		cb(err);
	});
}

function prepareClient(client, cb) {
	var theme = require('./theme.js');

	//	:TODO: it feels like this should go somewhere else... and be a bit more elegant.

	if('*' === conf.config.preLoginTheme) {
		client.user.properties.theme_id = theme.getRandomTheme() || '';
	} else {
		client.user.properties.theme_id = conf.config.preLoginTheme;
	}

    theme.setClientTheme(client, client.user.properties.theme_id);
    cb(null);   //  note: currently useless to use cb here - but this may change...again...
}<commit_msg>Catch exception @ createServer() e.g. if no PK exists for ssh.js<commit_after>/* jslint node: true */
'use strict';

//var SegfaultHandler = require('segfault-handler');
//SegfaultHandler.registerHandler('enigma-bbs-segfault.log');

//	ENiGMA½
let conf		= require('./config.js');
let logger		= require('./logger.js');
let miscUtil	= require('./misc_util.js');
let database	= require('./database.js');
let clientConns	= require('./client_connections.js');

let paths		= require('path');
let async		= require('async');
let util		= require('util');
let _			= require('lodash');
let assert		= require('assert');
let mkdirp 		= require('mkdirp');

//	our main entry point
exports.bbsMain	= bbsMain;

function bbsMain() {
	async.waterfall(
		[
			function processArgs(callback) {
				const args = process.argv.slice(2);

				var configPath;

				if(args.indexOf('--help') > 0) {
					//	:TODO: display help
				} else {
					let argCount = args.length;
					for(let i = 0; i < argCount; ++i) {
						const arg = args[i];
						if('--config' === arg) {
							configPath = args[i + 1];
						}
					}
				}

				callback(null, configPath || conf.getDefaultPath(), _.isString(configPath));
			},
			function initConfig(configPath, configPathSupplied, callback) {
				conf.init(configPath, function configInit(err) {

					//
					//	If the user supplied a path and we can't read/parse it
					//	then it's a fatal error
					//
					if(err) {
						if('ENOENT' === err.code)  {
							if(configPathSupplied) {
								console.error('Configuration file does not exist: ' + configPath);
							} else {
								configPathSupplied = null;	//	make non-fatal; we'll go with defaults
							}
						} else {
							console.error(err.toString());
						}
					}
					callback(err);
				});
			},
			function initSystem(callback) {
				initialize(function init(err) {
					if(err) {
						console.error('Error initializing: ' + util.inspect(err));
					}
					callback(err);
				});
			},
			function listenConnections(callback) {
				startListening(callback);
			}
		],
		function complete(err) {
			if(err) {
				logger.log.error(err);
			}
		}
	);
}

function initialize(cb) {
	async.series(
		[
			function createMissingDirectories(callback) {
				async.each(Object.keys(conf.config.paths), function entry(pathKey, next) {
					mkdirp(conf.config.paths[pathKey], function dirCreated(err) {
						if(err) {
							console.error('Could not create path: ' + conf.config.paths[pathKey] + ': ' + err.toString());
						}
						next(err);
					});
				}, function dirCreationComplete(err) {
					callback(err);
				});
			},
			function basicInit(callback) {
				logger.init();

				process.on('SIGINT', function onSigInt() {
					logger.log.info('Process interrupted, shutting down...');

					var activeConnections = clientConns.getActiveConnections();
					var i = activeConnections.length;
					while(i--) {
						activeConnections[i].term.write('\n\nServer is shutting down NOW! Disconnecting...\n\n');
						clientConns.removeClient(activeConnections[i]);
					}

					process.exit();
				});

				//	Init some extensions
				require('string-format').extend(String.prototype, require('./string_util.js').stringFormatExtensions);

				callback(null);
			},
			function initDatabases(callback) {
				database.initializeDatabases(callback);
			},
			function initSystemProperties(callback) {
				require('./system_property.js').loadSystemProperties(callback);
			},
			function initThemes(callback) {
				//	Have to pull in here so it's after Config init
				var theme = require('./theme.js');
				theme.initAvailableThemes(function onThemesInit(err, themeCount) {
					logger.log.info({ themeCount : themeCount }, 'Themes initialized');
					callback(err);
				});
			},
			function loadSysOpInformation(callback) {
				//
				//	If user 1 has been created, we have a SysOp. Cache some information
				//	into Config.
				//
				var user = require('./user.js');	//	must late load

				user.getUserName(1, function unLoaded(err, sysOpUsername) {
					if(err) {
						callback(null);	//	non-fatal here
					} else {
						//
						//	Load some select properties to cache
						//
						var propLoadOpts = {
							userId	: 1,
							names	: [ 'real_name', 'sex', 'email_address' ],
						};

						user.loadProperties(propLoadOpts, function propsLoaded(err, props) {
							if(!err) {
								conf.config.general.sysOp = {
									username	: sysOpUsername,
									properties	: props,
								};

								logger.log.info( { sysOp : conf.config.general.sysOp }, 'System Operator information cached');
							}
							callback(null);	//	any error is again, non-fatal here
						});
					}
				});
			},
			function readyMessageNetworkSupport(callback) {
				require('./msg_network.js').startup(callback);
			}
		],
		function onComplete(err) {
			cb(err);
		}
	);
}

function startListening(cb) {
	if(!conf.config.servers) {
		//	:TODO: Log error ... output to stderr as well. We can do it all with the logger
		//logger.log.error('No servers configured');
		cb(new Error('No servers configured'));
		return;
	}

	let moduleUtil = require('./module_util.js');	//	late load so we get Config

	moduleUtil.loadModulesForCategory('servers', (err, module) => {
		if(err) {
			logger.log.info(err);
			return;
		}

		const port = parseInt(module.runtime.config.port);
		if(isNaN(port)) {
			logger.log.error( { port : module.runtime.config.port, server : module.moduleInfo.name }, 'Cannot load server (Invalid port)');
			return;
		}

		const moduleInst	= new module.getModule();
        let server;
        try {
		    server		= moduleInst.createServer();
        } catch(e) {
            logger.log.warn(e, 'Exception caught creating server!');
            return;
        }

		//	:TODO: handle maxConnections, e.g. conf.maxConnections

		server.on('client', function newClient(client, clientSock) {
			//
			//	Start tracking the client. We'll assign it an ID which is
			//	just the index in our connections array.
			//
			if(_.isUndefined(client.session)) {
				client.session = {};
			}

			client.session.serverName 	= module.moduleInfo.name;
			client.session.isSecure		= module.moduleInfo.isSecure || false;

			clientConns.addNewClient(client, clientSock);

			client.on('ready', function clientReady(readyOptions) {

				client.startIdleMonitor();

				//	Go to module -- use default error handler
				prepareClient(client, function clientPrepared() {
					require('./connect.js').connectEntry(client, readyOptions.firstMenu);
				});
			});

			client.on('end', function onClientEnd() {
				clientConns.removeClient(client);
			});

			client.on('error', function onClientError(err) {
				logger.log.info({ clientId : client.session.id }, 'Connection error: %s' % err.message);
			});

			client.on('close', function onClientClose(hadError) {
				var l = hadError ? logger.log.info : logger.log.debug;
				l( { clientId : client.session.id }, 'Connection closed');

				clientConns.removeClient(client);
			});

			client.on('idle timeout', function idleTimeout() {
				client.log.info('User idle timeout expired');

				client.menuStack.goto('idleLogoff', function goMenuRes(err) {
					if(err) {
						//	likely just doesn't exist
						client.term.write('\nIdle timeout expired. Goodbye!\n');
						client.end();
					}
				});
			});
		});

		server.on('error', function serverErr(err) {
			logger.log.info(err);	//	'close' should be handled after
		});

		server.listen(port);

		logger.log.info(
			{ server : module.moduleInfo.name, port : port }, 'Listening for connections');
	}, err => {
		cb(err);
	});
}

function prepareClient(client, cb) {
	var theme = require('./theme.js');

	//	:TODO: it feels like this should go somewhere else... and be a bit more elegant.

	if('*' === conf.config.preLoginTheme) {
		client.user.properties.theme_id = theme.getRandomTheme() || '';
	} else {
		client.user.properties.theme_id = conf.config.preLoginTheme;
	}

    theme.setClientTheme(client, client.user.properties.theme_id);
    cb(null);   //  note: currently useless to use cb here - but this may change...again...
}<|endoftext|>


<commit_before>'use strict';

var matchType = require('../common').matchType,
    errorFactory = require('../common').errorFactory;

module.exports = function(lines, options, errors) {
    var ticket = new RegExp(options.issuePattern);
    var whetherIssueIsMandatory = false,
        wheterMatchAnyIssueRef = false;

    lines.forEach(function (line) {
        line = line.trim();
        if (line === "") {
            return;
        }

        if (matchType(options.typesWithMandatoryIssue, line)) {
            whetherIssueIsMandatory = true;
        }

        if (ticket.test(line)) {
            wheterMatchAnyIssueRef = true;
            return;
        }
    });

    if (!whetherIssueIsMandatory && !wheterMatchAnyIssueRef) {
        errors.push(errorFactory(
            'The issue reference for (' + options.typesWithMandatoryIssue.join(', ') + ') types is mandatory!\n',
            'List any ISSUES CLOSED by this change. E.g: Closes #31, Closes #45'));
    }
}<commit_msg>fix(hooks): check only first line about the type<commit_after>'use strict';

var matchType = require('../common').matchType,
    errorFactory = require('../common').errorFactory;

module.exports = function(lines, options, errors) {
    var ticket = new RegExp(options.issuePattern);
    var whetherIssueIsMandatory = false,
        wheterMatchAnyIssueRef = false;

    if (matchType(options.typesWithMandatoryIssue, lines[0])) {
        whetherIssueIsMandatory = true;
    }

    lines.forEach(function (line) {
        line = line.trim();
        if (line === "") {
            return;
        }

        if (ticket.test(line)) {
            wheterMatchAnyIssueRef = true;
            return;
        }
    });

    if (whetherIssueIsMandatory && !wheterMatchAnyIssueRef) {
        errors.push(errorFactory(
            'The issue reference for (' + options.typesWithMandatoryIssue.join(', ') + ') types is mandatory!\n',
            'List any ISSUES CLOSED by this change. E.g: Closes #31, Closes #45'));
    }
}<|endoftext|>