<commit_before>/**
 * Author: Samit Badle
 * Date: 13/Sep/2011
 */

/**
 * Controller for listbox which reorders the list items using drag and drop
 * The list box must be loaded before this controller object is created, i.e. call during or after the load event
 *
 * @author Samit Badle
 * @param listBox - element with list box (must have an id)
 * @param listItemsRa - array with string items to show and reorder in the listbox
 */
function DnDReorderedListbox(listBox, listItemsRa) {
  this.listBox = listBox;
  this.listBoxDnD = new ListboxDnDReorder(this.listBox, 'application/x-' + listBox.id);
  this.listItems = listItemsRa;
  this.reload();
}

/**
 * Reloads the list box and throws away user ordering
 *
 * @param [listItemsRa] - optionally replace the list items as well
 */
DnDReorderedListbox.prototype.reload = function(listItemsRa) {
  if (listItemsRa) {
    this.listItems = listItemsRa;
  }
  var list = this.listBox;
  //clear the listbox
  for (var i = list.getRowCount() - 1; i >= 0; i--) {
    list.removeItemAt(i);
  }
  //load the listbox with the list
  var listItems = this.listItems;
  for (var j = 0; j < listItems.length; j++) {
    list.appendItem(listItems[j], j);
  }
};

DnDReorderedListbox.prototype.getListItems = function() {
  var listItems = this.listItems;
  var newRa = new Array(listItems.length);
  var list = this.listBox;
  for (var i = list.itemCount - 1; i >= 0; i--) {
    newRa[i] = listItems[list.getItemAtIndex(i).value];
  }
  return newRa;
};

/**
 * Drag and drop reordering behaviour for the list Box
 * The list box must be loaded before this controller object is created, i.e. call during or after the load event
 * Note: The list item is removed and a new one is created using the label and value properties, all others are lost.
 *
 * @author Samit Badle
 * @param listBox
 * @param dataType
 */
function ListboxDnDReorder(listBox, dataType) {
  this.dataType = dataType; //for e.g. 'application/x-something'
  this.listBox = listBox;
  var self = this;
  listBox.addEventListener('dragstart', function(event) {self.dragStart(event)}, false);
  listBox.addEventListener('dragenter', function(event) {self.dragOver(event)}, false);
  listBox.addEventListener('dragover', function(event) {self.dragOver(event)}, false);
  listBox.addEventListener('dragleave', function(event) {self.dragLeave(event)}, false);
  listBox.addEventListener('drop', function(event) {self.drop(event)}, false);
  listBox.addEventListener('dragend', function(event) {self.dragEnd(event)}, false);
  listBox.draggable = 'true';
}

ListboxDnDReorder.prototype.dragStart = function(event) {
  this.itemCount = this.listBox.itemCount;
  if (this.itemCount > 1) {
    // You cannot rearrange a single or no items no matter how hard you try
    //cache some useful elements first
    this.selectedItem = this.listBox.selectedItem;
    this.lastListItem = this.listBox.getItemAtIndex(this.itemCount - 1);
    var rect = this.lastListItem.getBoundingClientRect();
    this.flipYPos = rect.top + (rect.height / 2);
    event.dataTransfer.setData(this.dataType, 'This text may be dragged');
  }
};

ListboxDnDReorder.prototype.dragOver = function(event) {
  //TODO: currently you can sort only drag and drop among displayed items, add auto scroll when at the top or bottom of displayed list
  if (event.dataTransfer.types.contains(this.dataType)) {
    // no point trying to let people drop text or other stuff here either
    var listItem = event.target;
    if (listItem.nodeName == 'listitem') {
      //if you are on an list item, give feedback that the drop will insert before the item
      if (listItem == this.lastListItem) {
        this._showDropPosition(listItem, event.clientY > this.flipYPos);
      } else {
        this._showDropPosition(listItem);
      }
      event.preventDefault();
    } else {
      if (this.itemCount > 1) {
        //if you are not on any item, give feedback that the drop will be at the end of the list
        this._showDropPosition(this.lastListItem, true);
        event.preventDefault();
      }
    }
  }
};

ListboxDnDReorder.prototype.dragLeave = function(event) {
  this._clearDropPosition();
};

ListboxDnDReorder.prototype.dragEnd = function(event) {
  this._clearDropPosition();
  this.selectedItem = null;
  this.curItem = null;
};

ListboxDnDReorder.prototype.drop = function(event) {
  var dropIndex = this.listBox.getIndexOfItem(this.curItem);
  if (this.dropAfter) {
    dropIndex++;
  }
  var selectedIndex = this.listBox.getIndexOfItem(this.selectedItem);
  this._clearDropPosition();
  if (selectedIndex < dropIndex) {
    dropIndex--;
  }
  if (selectedIndex != dropIndex) {
    var lbl = this.selectedItem.label;
    var userData = this.selectedItem.value;
    this.listBox.removeItemAt(selectedIndex);
    this.listBox.insertItemAt(dropIndex, lbl, userData);
  }
};

ListboxDnDReorder.prototype.dropStyle = '1px solid Highlight';

ListboxDnDReorder.prototype._showDropPosition = function(item, after) {
  if (this.curItem != item) {
    this._clearDropPosition();
    this.curItem = item;
    this.dropAfter = after;
    if (after) {
      this.curItem.style.borderBottom = this.dropStyle;
    } else {
      this.curItem.style.borderTop = this.dropStyle;
    }
  }
};

ListboxDnDReorder.prototype._clearDropPosition = function () {
  if (this.curItem) {
    this.curItem.style.borderTop = 'none';
    this.curItem.style.borderBottom = 'none';
    this.curItem = null;
  }
};
<commit_msg>DaveHunt: Explicitly convert dataType to lower case to avoid platform differences. Fixes issue #3267<commit_after>/**
 * Author: Samit Badle
 * Date: 13/Sep/2011
 */

/**
 * Controller for listbox which reorders the list items using drag and drop
 * The list box must be loaded before this controller object is created, i.e. call during or after the load event
 *
 * @author Samit Badle
 * @param listBox - element with list box (must have an id)
 * @param listItemsRa - array with string items to show and reorder in the listbox
 */
function DnDReorderedListbox(listBox, listItemsRa) {
  this.listBox = listBox;
  this.listBoxDnD = new ListboxDnDReorder(this.listBox, 'application/x-' + listBox.id.toLowerCase());
  this.listItems = listItemsRa;
  this.reload();
}

/**
 * Reloads the list box and throws away user ordering
 *
 * @param [listItemsRa] - optionally replace the list items as well
 */
DnDReorderedListbox.prototype.reload = function(listItemsRa) {
  if (listItemsRa) {
    this.listItems = listItemsRa;
  }
  var list = this.listBox;
  //clear the listbox
  for (var i = list.getRowCount() - 1; i >= 0; i--) {
    list.removeItemAt(i);
  }
  //load the listbox with the list
  var listItems = this.listItems;
  for (var j = 0; j < listItems.length; j++) {
    list.appendItem(listItems[j], j);
  }
};

DnDReorderedListbox.prototype.getListItems = function() {
  var listItems = this.listItems;
  var newRa = new Array(listItems.length);
  var list = this.listBox;
  for (var i = list.itemCount - 1; i >= 0; i--) {
    newRa[i] = listItems[list.getItemAtIndex(i).value];
  }
  return newRa;
};

/**
 * Drag and drop reordering behaviour for the list Box
 * The list box must be loaded before this controller object is created, i.e. call during or after the load event
 * Note: The list item is removed and a new one is created using the label and value properties, all others are lost.
 *
 * @author Samit Badle
 * @param listBox
 * @param dataType
 */
function ListboxDnDReorder(listBox, dataType) {
  this.dataType = dataType; //for e.g. 'application/x-something'
  this.listBox = listBox;
  var self = this;
  listBox.addEventListener('dragstart', function(event) {self.dragStart(event)}, false);
  listBox.addEventListener('dragenter', function(event) {self.dragOver(event)}, false);
  listBox.addEventListener('dragover', function(event) {self.dragOver(event)}, false);
  listBox.addEventListener('dragleave', function(event) {self.dragLeave(event)}, false);
  listBox.addEventListener('drop', function(event) {self.drop(event)}, false);
  listBox.addEventListener('dragend', function(event) {self.dragEnd(event)}, false);
  listBox.draggable = 'true';
}

ListboxDnDReorder.prototype.dragStart = function(event) {
  this.itemCount = this.listBox.itemCount;
  if (this.itemCount > 1) {
    // You cannot rearrange a single or no items no matter how hard you try
    //cache some useful elements first
    this.selectedItem = this.listBox.selectedItem;
    this.lastListItem = this.listBox.getItemAtIndex(this.itemCount - 1);
    var rect = this.lastListItem.getBoundingClientRect();
    this.flipYPos = rect.top + (rect.height / 2);
    event.dataTransfer.setData(this.dataType, 'This text may be dragged');
  }
};

ListboxDnDReorder.prototype.dragOver = function(event) {
  //TODO: currently you can sort only drag and drop among displayed items, add auto scroll when at the top or bottom of displayed list
  if (event.dataTransfer.types.contains(this.dataType)) {
    // no point trying to let people drop text or other stuff here either
    var listItem = event.target;
    if (listItem.nodeName == 'listitem') {
      //if you are on an list item, give feedback that the drop will insert before the item
      if (listItem == this.lastListItem) {
        this._showDropPosition(listItem, event.clientY > this.flipYPos);
      } else {
        this._showDropPosition(listItem);
      }
      event.preventDefault();
    } else {
      if (this.itemCount > 1) {
        //if you are not on any item, give feedback that the drop will be at the end of the list
        this._showDropPosition(this.lastListItem, true);
        event.preventDefault();
      }
    }
  }
};

ListboxDnDReorder.prototype.dragLeave = function(event) {
  this._clearDropPosition();
};

ListboxDnDReorder.prototype.dragEnd = function(event) {
  this._clearDropPosition();
  this.selectedItem = null;
  this.curItem = null;
};

ListboxDnDReorder.prototype.drop = function(event) {
  var dropIndex = this.listBox.getIndexOfItem(this.curItem);
  if (this.dropAfter) {
    dropIndex++;
  }
  var selectedIndex = this.listBox.getIndexOfItem(this.selectedItem);
  this._clearDropPosition();
  if (selectedIndex < dropIndex) {
    dropIndex--;
  }
  if (selectedIndex != dropIndex) {
    var lbl = this.selectedItem.label;
    var userData = this.selectedItem.value;
    this.listBox.removeItemAt(selectedIndex);
    this.listBox.insertItemAt(dropIndex, lbl, userData);
  }
};

ListboxDnDReorder.prototype.dropStyle = '1px solid Highlight';

ListboxDnDReorder.prototype._showDropPosition = function(item, after) {
  if (this.curItem != item) {
    this._clearDropPosition();
    this.curItem = item;
    this.dropAfter = after;
    if (after) {
      this.curItem.style.borderBottom = this.dropStyle;
    } else {
      this.curItem.style.borderTop = this.dropStyle;
    }
  }
};

ListboxDnDReorder.prototype._clearDropPosition = function () {
  if (this.curItem) {
    this.curItem.style.borderTop = 'none';
    this.curItem.style.borderBottom = 'none';
    this.curItem = null;
  }
};
<|endoftext|>


<commit_before>"use strict"

var text = "";
var sugg = ["AJAX", "Neo4J", "Rhizi", "Research", "CRI", "SageBionetworks", "Hero.coli", "CSS", "NodeJS", "HTML5", "Angular", "D3", "ProofOfConcept", "Graphs", "CloudComputing", "BigData", "ProblemSolving", "PHP", "Javascript", "BackBone", "Cooperation", "SemanticWeb"];
var typeindex = 0;
var names = ["Jean-ChristopheThalabard", "MaévaVignes", "AbdelElAbed", "ValérieTaly", "SébastienDutreuil", "AntoineBERGEL", "AntoineAngot", "JérômeFeret", "CharlèneGayrard", "HugoJimenezPerez", "CaterinaUrban", "GaëlleChevalon", "IanMarcus", "AntoineTALY", "ChantalLOTTON", "Ana-MariaLennon-Duménil", "FrédériqueCarlier-Grynkorn", "PascalMartin", "TamaraMilosevic", "NicolasCarpi", "StéphaneDaoudy", "DanijelaMaticVignjevic", "EugenioCinquemani", "VincentDAHIREL", "MartinLenz", "MaïlysChassagne", "AnneSchmidt", "SophieSacquinMora", "Richard-EmmanuelEastes", "MichelMorange", "EwaZlotek-Zlotkiewicz", "A.m.o.d.s.e.nC.h.o.t.i.a", "AlexandreVaugoux", "AnnemiekJMCornelissen", "ClémentNizak", "AntoineFrenoy", "ArielB.Lindner", "BenjaminBrogniart", "ChristopheZimmer", "ClaireRibrault", "DavidTareste", "DenisLafeuille", "DorGarbash", "DusanMISEVIC", "EddaNitschke", "FrançoisTaddei", "GregoryBatt", "JeanLucLebrun", "JesseHimmelstein", "KevinLhoste", "LauraCiriani", "LivioRiboli-Sasco", "NathalieSussfeld", "JakeEdwinWintermute", "MarlyneNogbou", "MatthieuPiel", "PascalHersen", "Pierre-YvesBourguignon", "TimoBetz", "RaphaëlGoujet", "StéphaneDebove", "VincentDanos", "TamKienDuong"];
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var nodeindex, linkindex;
var typeStack = [];

var ExecutionStack = [];

var lastnode;

$('#textanalyser').autocompleteTrigger({
    triggerStart: '#',
    triggerEnd: '',
    source: sugg
});

$("#textanalyser").keypress(function(e) {
     if (e.which == 13) {
        if(!suggestionChange){
            text = $('#textanalyser').val();
            $('#textanalyser').val("");
            TextAnalyser2(text, true);
            typeStack=[];
        }else{
            suggestionChange=false;
        }

    return false;
    }

    if (e.which == 9) {//TAB
        text = $('#textanalyser').val();
        $('#textanalyser').val(text+"        ");
        return false;
    }
});

$(document).keydown(function(e) {
    if (e.keyCode == 37) {//RIGHT
        e.preventDefault();
        changeType("up", lastnode);
        return false;
    }
    if (e.keyCode == 39) { //LEFT
        e.preventDefault();
        changeType("down", lastnode);
        return false;
    }
    if (e.keyCode == 38) {//UP
        suggestionChange=true;
    }
    if (e.keyCode == 40) {//DOWN
        suggestionChange=true;
    }

    if (e.keyCode == 9) {//TAB
        return false;
    }

});

function changeType(arg, id) {
    if (arg === 'up') {
        if (typeindex < 4) typeindex++;
        else typeindex = 0;
        graph.editType(id, null, nodetypes[typeindex]);
        $('.typeselection').html('

' + "Chosen Type: " + nodetypes[typeindex] + '

');
        graph.findCoordinates(lastnode,null);
    } else {
        if (typeindex > 0) typeindex--;
        else typeindex = 4;

        graph.editType(id, null, nodetypes[typeindex]);
        $('.typeselection').html('

' + "Chosen Type: " + nodetypes[typeindex] + '

');
        graph.findCoordinates(lastnode,null);

    }
    graph.updateGraph();
}

window.setInterval(function() {
    if ($('#textanalyser').val() != text) {
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);

        if(text.length*8>500)$('#textanalyser').css('width',text.length*8+20);
        // text changed
        text = $('#textanalyser').val();
        TextAnalyser2(text, false);
        suggestionChange=false;
    }
}, 5);

function TextAnalyser2(newtext, finalize) {
    var states = ["NOTHING", "NEWNODE", "EDITNODE", "CLOSENODE", "NEWLINK", "EDITLINK", "SPECIAL", "QUARTET"];
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    linkindex = 0;
    nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";

    //Sentence Sequencing
    //Build the words and cuts the main elements
    segment = newtext.split("#");
    for (var j = 0; j < segment.length; j++) {
        if (j !== 0) sentence.push("#");
        subsegment = segment[j].split(" ");
        if (subsegment.length === 0) {
            sentence.push(" ");
        }
        for (var k = 0; k < subsegment.length; k++) {
            if (subsegment[k] !== " " && subsegment[k] !== "") {
                if (subsegment[k].charAt(0) === '"') {
                    quoteword = "";
                    do {
                        quoteword += subsegment[k] + " ";
                        k++;
                    } while (k < subsegment.length && subsegment[k].charAt(subsegment[k].length - 1) !== '"');
                    if (k < subsegment.length) quoteword += subsegment[k];
                    sentence.push(quoteword.replace(/"/g, ""));
                } else {
                    sentence.push(subsegment[k]);
                }
            }
        }
    }

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (var m = 0; m < sentence.length; m++) {
        switch (sentence[m]) {
            case "#":
                orderStack.push("START");
                break;
            case "and":
            case "+":
            case ",":
            case "&":
                sentence[m]=" and ";
                ANDcount++;
                //orderStack.push("AND");
            default:
                if (orderStack[orderStack.length - 1] === "START") {
                    orderStack.push("NODE");
                    newnodes.push(sentence[m]);
                    linkindex++;
                } else if (orderStack[orderStack.length - 1] === "NODE") {
                    orderStack.push("LINK");
                    if (!newlinks[linkindex]) {
                        newlinks[linkindex] = sentence[m] + " ";
                    } else {
                        newlinks[linkindex] += sentence[m] + " ";
                    }
                } else {
                    if (!newlinks[linkindex]) {
                        newlinks[linkindex] = sentence[m] + " ";
                    } else {
                        newlinks[linkindex] += sentence[m] + " ";
                    }
                }
                if (newnodes.length === 0) prefix += sentence[m] + " ";
                break;
        }
    }

    //ATTACH SENTENCE PREFIX
    if (prefix) newlinks[1] += "(" + prefix + ")";

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    var word = "";
    var completeSentence = "";
    for (var m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            completeSentence += newnodes[nodeindex] + " ";
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }

    //REBUILD GRAPH
    linkindex = 0;
    nodeindex = 0;

    //CHANGE TO PERMANENT STATE AND UPDATE SUGGESTIONLIST
    var typesetter = "";
    if (finalize === true) {
        typesetter = "perm";
        for (var n = 0; n < newnodes.length; n++) {
            if (Unique(newnodes[n])) {
                sugg.push(newnodes[n]);
            }
        }
        sugg.push(text);
    } else {
        typesetter = "temp";
    }

    //REINITIALISE GRAPH (DUMB BUT IT WORKS)
    graph.removeNodes("temp");
    graph.removeLinks("temp");

    //ADD SURROUNDING BUBBLE
    if (orderStack.length > 0) graph.addNode("", "bubble", "temp");

    var abnormalGraph=false;
    if((newlinks.length- ANDcount)>=3 )abnormalGraph=true;

    //0-N ORDER STACK
    for (var m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if(!typeStack[nodeindex])typeStack[nodeindex]=nodetypes[typeindex];
                break;
            case "NODE":
                graph.addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) graph.addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                nodeindex++;
                break;
            case "LINK":
                linkindex++;
                break;
        }
    }

    //FINAL N ORDER
    switch (orderStack[orderStack.length - 1]) {
        case "START":
            typeStack[nodeindex]=nodetypes[typeindex];
            graph.addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph){graph.addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}
            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            graph.addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph){ graph.addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
            ANDconnect(newnodes[nodeindex]);}
            break;
        case "LINK":
            linkindex++;
            graph.addNode("new node", "empty", "temp");
            if (!abnormalGraph){ graph.addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}
            break;
    }

    //EXTERNAL AND CONNECTION CHECKING
    var verb = "";
    function ANDconnect(node) {
          for(var x=0;x<links.length;x++){
            if(newlinks[x])if(newlinks[x].replace(/ /g,"")!=="and"){
                verb=newlinks[x];
                for(var y=0; y<x ;y++){
                    for(var z=x; z<nodes.length ;z++){
                        graph.addLink(newnodes[y],newnodes[z],verb,typesetter);
                    }
                }
                break;
            }
        }

    }

    /*console.log(sentence);
    console.log(completeSentence);
    console.log(orderStack);*/

    //STAR CASE
    verb = "";
    if (abnormalGraph) {
        for (var l = 1; l < newlinks.length; l++) {
            if (newlinks[l])
                if (newlinks[l].replace(/ /g, "") !== "and") {
                    verb = newlinks[l];
                }
        }
        graph.addNode(completeSentence, "chainlink", typesetter);
        for (var n = 0; n < newnodes.length; n++) {
            graph.addLink(newnodes[n], completeSentence, verb, typesetter);
        }
    }

    //FOR THE EXTERNAL ARROW-TYPE CHANGER
    lastnode = newnodes[nodeindex];

    //UPDATE GRAPH ONCE
    graph.update();
}

function Unique(newnode) {
    var truth = true;
    for (var p = 0; p < sugg.length; p++) {
        if (sugg[p] === newnode) {
            truth = false;
        }
    }
    return truth;
}
<commit_msg>Issue #31<commit_after>"use strict"

var text = "";
var sugg = ["AJAX", "Neo4J", "Rhizi", "Research", "CRI", "SageBionetworks", "Hero.coli", "CSS", "NodeJS", "HTML5", "Angular", "D3", "ProofOfConcept", "Graphs", "CloudComputing", "BigData", "ProblemSolving", "PHP", "Javascript", "BackBone", "Cooperation", "SemanticWeb"];
var typeindex = 0;
var names = ["Jean-ChristopheThalabard", "MaévaVignes", "AbdelElAbed", "ValérieTaly", "SébastienDutreuil", "AntoineBERGEL", "AntoineAngot", "JérômeFeret", "CharlèneGayrard", "HugoJimenezPerez", "CaterinaUrban", "GaëlleChevalon", "IanMarcus", "AntoineTALY", "ChantalLOTTON", "Ana-MariaLennon-Duménil", "FrédériqueCarlier-Grynkorn", "PascalMartin", "TamaraMilosevic", "NicolasCarpi", "StéphaneDaoudy", "DanijelaMaticVignjevic", "EugenioCinquemani", "VincentDAHIREL", "MartinLenz", "MaïlysChassagne", "AnneSchmidt", "SophieSacquinMora", "Richard-EmmanuelEastes", "MichelMorange", "EwaZlotek-Zlotkiewicz", "A.m.o.d.s.e.nC.h.o.t.i.a", "AlexandreVaugoux", "AnnemiekJMCornelissen", "ClémentNizak", "AntoineFrenoy", "ArielB.Lindner", "BenjaminBrogniart", "ChristopheZimmer", "ClaireRibrault", "DavidTareste", "DenisLafeuille", "DorGarbash", "DusanMISEVIC", "EddaNitschke", "FrançoisTaddei", "GregoryBatt", "JeanLucLebrun", "JesseHimmelstein", "KevinLhoste", "LauraCiriani", "LivioRiboli-Sasco", "NathalieSussfeld", "JakeEdwinWintermute", "MarlyneNogbou", "MatthieuPiel", "PascalHersen", "Pierre-YvesBourguignon", "TimoBetz", "RaphaëlGoujet", "StéphaneDebove", "VincentDanos", "TamKienDuong"];
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var nodeindex, linkindex;
var typeStack = [];

var ExecutionStack = [];

var lastnode;

$('#textanalyser').autocompleteTrigger({
    triggerStart: '#',
    triggerEnd: '',
    source: sugg
});

$("#textanalyser").keypress(function(e) {
     if (e.which == 13) {
        if(!suggestionChange){
            text = $('#textanalyser').val();
            $('#textanalyser').val("");
            TextAnalyser2(text, true);
            typeStack=[];
        }else{
            suggestionChange=false;
        }

    return false;
    }

    if (e.which == 9) {//TAB
        text = $('#textanalyser').val();
        $('#textanalyser').val(text+"        ");
        return false;
    }
});

$(document).keydown(function(e) {
    if (e.keyCode == 37) {//RIGHT
        e.preventDefault();
        changeType("up", lastnode);
        return false;
    }
    if (e.keyCode == 39) { //LEFT
        e.preventDefault();
        changeType("down", lastnode);
        return false;
    }
    if (e.keyCode == 38) {//UP
        suggestionChange=true;
    }
    if (e.keyCode == 40) {//DOWN
        suggestionChange=true;
    }

    if (e.keyCode == 9) {//TAB
        return false;
    }

});

function changeType(arg, id) {
    if (arg === 'up') {
        if (typeindex < 4) typeindex++;
        else typeindex = 0;
        graph.editType(id, null, nodetypes[typeindex]);
        $('.typeselection').html('

' + "Chosen Type: " + nodetypes[typeindex] + '

');
        graph.findCoordinates(lastnode,null);
    } else {
        if (typeindex > 0) typeindex--;
        else typeindex = 4;

        graph.editType(id, null, nodetypes[typeindex]);
        $('.typeselection').html('

' + "Chosen Type: " + nodetypes[typeindex] + '

');
        graph.findCoordinates(lastnode,null);

    }
    graph.updateGraph();
}

window.setInterval(function() {
    if ($('#textanalyser').val() != text) {

        if(text.length*8>500)$('#textanalyser').css('width',text.length*8+20);
        // text changed
        text = $('#textanalyser').val();
        TextAnalyser2(text, false);
        suggestionChange=false;
    }
}, 5);

function TextAnalyser2(newtext, finalize) {
    var states = ["NOTHING", "NEWNODE", "EDITNODE", "CLOSENODE", "NEWLINK", "EDITLINK", "SPECIAL", "QUARTET"];
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    linkindex = 0;
    nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";

    //Sentence Sequencing
    //Build the words and cuts the main elements
    segment = newtext.split("#");
    for (var j = 0; j < segment.length; j++) {
        if (j !== 0) sentence.push("#");
        subsegment = segment[j].split(" ");
        if (subsegment.length === 0) {
            sentence.push(" ");
        }
        for (var k = 0; k < subsegment.length; k++) {
            if (subsegment[k] !== " " && subsegment[k] !== "") {
                if (subsegment[k].charAt(0) === '"') {
                    quoteword = "";
                    do {
                        quoteword += subsegment[k] + " ";
                        k++;
                    } while (k < subsegment.length && subsegment[k].charAt(subsegment[k].length - 1) !== '"');
                    if (k < subsegment.length) quoteword += subsegment[k];
                    sentence.push(quoteword.replace(/"/g, ""));
                } else {
                    sentence.push(subsegment[k]);
                }
            }
        }
    }

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (var m = 0; m < sentence.length; m++) {
        switch (sentence[m]) {
            case "#":
                orderStack.push("START");
                break;
            case "and":
            case "+":
            case ",":
            case "&":
                sentence[m]=" and ";
                ANDcount++;
                //orderStack.push("AND");
            default:
                if (orderStack[orderStack.length - 1] === "START") {
                    orderStack.push("NODE");
                    newnodes.push(sentence[m]);
                    linkindex++;
                } else if (orderStack[orderStack.length - 1] === "NODE") {
                    orderStack.push("LINK");
                    if (!newlinks[linkindex]) {
                        newlinks[linkindex] = sentence[m] + " ";
                    } else {
                        newlinks[linkindex] += sentence[m] + " ";
                    }
                } else {
                    if (!newlinks[linkindex]) {
                        newlinks[linkindex] = sentence[m] + " ";
                    } else {
                        newlinks[linkindex] += sentence[m] + " ";
                    }
                }
                if (newnodes.length === 0) prefix += sentence[m] + " ";
                break;
        }
    }

    //ATTACH SENTENCE PREFIX
    if (prefix) newlinks[1] += "(" + prefix + ")";

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    var word = "";
    var completeSentence = "";
    for (var m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            completeSentence += newnodes[nodeindex] + " ";
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }

    //REBUILD GRAPH
    linkindex = 0;
    nodeindex = 0;

    //CHANGE TO PERMANENT STATE AND UPDATE SUGGESTIONLIST
    var typesetter = "";
    if (finalize === true) {
        typesetter = "perm";
        for (var n = 0; n < newnodes.length; n++) {
            if (Unique(newnodes[n])) {
                sugg.push(newnodes[n]);
            }
        }
        sugg.push(text);
    } else {
        typesetter = "temp";
    }

    //REINITIALISE GRAPH (DUMB BUT IT WORKS)
    graph.removeNodes("temp");
    graph.removeLinks("temp");

    //ADD SURROUNDING BUBBLE
    if (orderStack.length > 0) graph.addNode("", "bubble", "temp");

    var abnormalGraph=false;
    if((newlinks.length- ANDcount)>=3 )abnormalGraph=true;

    //0-N ORDER STACK
    for (var m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if(!typeStack[nodeindex])typeStack[nodeindex]=nodetypes[typeindex];
                break;
            case "NODE":
                graph.addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) graph.addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                nodeindex++;
                break;
            case "LINK":
                linkindex++;
                break;
        }
    }

    //FINAL N ORDER
    switch (orderStack[orderStack.length - 1]) {
        case "START":
            typeStack[nodeindex]=nodetypes[typeindex];
            graph.addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph){graph.addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}
            $('.typeselection').css({top:window.innerHeight/2-115,left:window.innerWidth/2-325});
            $('.typeselection').html('

Use arrows to pick a type

');

            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            graph.addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph){ graph.addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
            ANDconnect(newnodes[nodeindex]);}
            break;
        case "LINK":
            linkindex++;
            graph.addNode("new node", "empty", "temp");
            if (!abnormalGraph){ graph.addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}

            $('.typeselection').css('top', -300);
            $('.typeselection').css('left', 0);
            break;
    }

    //EXTERNAL AND CONNECTION CHECKING
    var verb = "";
    function ANDconnect(node) {
          for(var x=0;x<links.length;x++){
            if(newlinks[x])if(newlinks[x].replace(/ /g,"")!=="and"){
                verb=newlinks[x];
                for(var y=0; y<x ;y++){
                    for(var z=x; z<nodes.length ;z++){
                        graph.addLink(newnodes[y],newnodes[z],verb,typesetter);
                    }
                }
                break;
            }
        }

    }

    /*console.log(sentence);
    console.log(completeSentence);
    console.log(orderStack);*/

    //STAR CASE
    verb = "";
    if (abnormalGraph) {
        for (var l = 1; l < newlinks.length; l++) {
            if (newlinks[l])
                if (newlinks[l].replace(/ /g, "") !== "and") {
                    verb = newlinks[l];
                }
        }
        graph.addNode(completeSentence, "chainlink", typesetter);
        for (var n = 0; n < newnodes.length; n++) {
            graph.addLink(newnodes[n], completeSentence, "", typesetter);
        }
    }

    //FOR THE EXTERNAL ARROW-TYPE CHANGER
    lastnode = newnodes[nodeindex];

    if(finalize){
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);
    }

    //UPDATE GRAPH ONCE
    graph.update();
}

function Unique(newnode) {
    var truth = true;
    for (var p = 0; p < sugg.length; p++) {
        if (sugg[p] === newnode) {
            truth = false;
        }
    }
    return truth;
}
<|endoftext|>


<commit_before>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var Promise = require('bluebird');
var mongo = require('mongoskin');

var uri = process.env.MONGODB_URI;
var trelloKey = process.env.HUBOT_TRELLO_KEY;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);
// connect to mLab database
var db = mongo.MongoClient.connect(uri);

var bcrypt = require('bcryptjs');
var request = require('request-promise');
var encryption = require('./encryption.js');

var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function (robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var scope = 'read,write,account'
    var TrelloOAuth = require('./trello-oauth.js')
    var tOAuth = new TrelloOAuth(app_key, oauth_secret, loginCallback, 'Hubot', scope);

    robot.respond(/trello auth/, function (res) {
        let userId = res.message.user.id;
        tOAuth.getRequestToken(function (err, data) {
            oauth_secrets['username'] = res.message.user.name;
            oauth_secrets['id'] = res.message.user.id;
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;

            res.reply(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function (req, res_r) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        tOAuth.getAccessToken(args, function (err, data) {
            if (err) throw err;
            let userName = oauth_secrets['username'];
            let userId = oauth_secrets['id'];
            let token = encryption.encrypt(data['oauth_access_token']); // encrypt token before storing it
            // TODO: encryption -> return promise
            // TODO: get trello username and save
                //TODO error
                var trelloUsername = data.username
                db.bind('users');
                db.users.update({ _id: userId},{'$set':{trello_username: trelloUsername, trello_token: token }}, {upsert: true}, function (err, result) {
                    if (err) throw err;
                    if (result) {
                        robot.logger.info(`User's Token Added to DB!`)
                    };
                })

        })
        res_r.redirect('/a');
    });

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello get token/i, function (res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${app_key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello add token (.*)/i, function (res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<commit_msg>db - findAndModify1<commit_after>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var Promise = require('bluebird');
var mongo = require('mongoskin');

var uri = process.env.MONGODB_URI;
var trelloKey = process.env.HUBOT_TRELLO_KEY;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);
// connect to mLab database
var db = mongo.MongoClient.connect(uri);

var bcrypt = require('bcryptjs');
var request = require('request-promise');
var encryption = require('./encryption.js');

var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function (robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var scope = 'read,write,account'
    var TrelloOAuth = require('./trello-oauth.js')
    var tOAuth = new TrelloOAuth(app_key, oauth_secret, loginCallback, 'Hubot', scope);

    robot.respond(/trello auth/, function (res) {
        let userId = res.message.user.id;
        tOAuth.getRequestToken(function (err, data) {
            oauth_secrets['username'] = res.message.user.name;
            oauth_secrets['id'] = res.message.user.id;
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;

            res.reply(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function (req, res_r) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        tOAuth.getAccessToken(args, function (err, data) {
            if (err) throw err;
            let userName = oauth_secrets['username'];
            let userId = oauth_secrets['id'];
            let token = encryption.encrypt(data['oauth_access_token']); // encrypt token before storing it
            // TODO: encryption -> return promise
            // TODO: get trello username and save
                //TODO error
                var trelloUsername = data.username
                db.bind('users');
                db.users.findAndModify({
                    query:{_id: userId},
                    update:{ trello_token: token },
                    upsert: true
                }, function (err, result) {
                    if (err) throw err;
                    if (result) {
                        robot.logger.info(`User's Token Added to DB!`)
                    };
                })

        })
        res_r.redirect('/a');
    });

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello get token/i, function (res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${app_key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello add token (.*)/i, function (res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<|endoftext|>


<commit_before><commit_msg>Fixed a bug in analyse bundle's startAnalyse.js<commit_after><|endoftext|>


<commit_before><commit_msg>can click on pattern while it's playing<commit_after><|endoftext|>


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

var cluster = require('cluster'),
	net = require('net'),
	fs = require('fs'),
	winston = require('winston'),
	logstash = require('winston-logstash'),
	async = require('async');

// Process configuration
var config = {
	sockfile: process.env.SOCK_FILE || '/tmp/zlog.sock',
	workers: process.env.WORKERS || require('os').cpus().length,
	statMonitor: process.env.STAT_MONITOR || false,
	statPulse: process.env.STAT_PULSE || 3000,
	chunkDelimiter: process.env.DELIMITER || ';;'
}

var statCount = 0,
	worker;

// Worker API
var workerApi = {
	logChunkContent: function(chunk) {
		var params, content;
		try {
			chunk = chunk.trim();
			if (!chunk) {
				return;
			}
			content = JSON.parse(chunk);
		} catch (error) {
			console.log('Invalid chunk JSON input:', chunk);
			return;
		}
		params = {
			grouper: content.grouper || 'default',
			category: content.category || 'default',
			source: content.source || 'default',
			meta: content.meta || {},
			timestamp: content.timestamp || new Date().getTime(),
		};

		winston.log(
			content.level || 'debug',
			content.message || '',
			params
		);
	}
}

var statApi = {
	lastCount: 0,
	check: function() {
		work = statCount - statApi.lastCount;
		console.log({
			time: new Date().getTime(),
			work: work,
			rate: work / (config.statPulse / 1000)
		});
		statApi.lastCount = statCount;
	}
}

if (cluster.isMaster) {

	process.title = 'zlogd';

	// Remove old socket files
	fs.unlink(config.sockfile, function (error) {
		if (error) {
			console.log('Error removing old sock file', error);
			return;
		}
	});

	console.log('Master process starting.');
	for (var i = config.workers; i > 0; i--) {
		worker = cluster.fork();
		console.log('Worker[' + worker.id + '] started.');
	}

	cluster.on('disconnect', function (worker) {
		console.log('Worker disconnected!');
	});

	cluster.on('exit', function (worker, code, signal) {
		console.error('Worker ' + worker.process.pid + ' died');
		if (worker.suicide) {
			cluster.fork();
		} else {
			if (Object.keys(cluster.workers).length <= 0) {
				console.error('No workers left, ending main process.');
				process.exit(1);
			}
		}
	});

	// Be a good master and listen to your workers!
	Object.keys(cluster.workers).forEach(function(id) {
		cluster.workers[id].on('message', function(workerMessage) {
			switch (workerMessage.type) {
				case 'complete':
					statCount += workerMessage.data;
					break;
				default:
					console.log('Master does not understand message.');
			}
		});
	});

	// Create the socket listener
	var server = net.createServer(function (socket) {
		var socketData = '', workToBeDone, split;
		socket.setEncoding('utf8');

		// Compile chunks for this request
		socket.on('data', function (data) {
			socketData += data;
		});

		// Delegate the work to the workers
		socket.on('end', function() {
			workToBeDone = socketData.split(config.chunkDelimiter);
			split = Math.ceil(workToBeDone.length / config.workers);
			for (var i in cluster.workers) {
				cluster.workers[i].send({
					type: 'work',
					data: workToBeDone.slice(0, split)
				});
				workToBeDone.splice(0, split);
			}
			socketData = '';
		});
	});

	// Start the server
	server.listen(config.sockfile, function () {
		fs.chmod(config.sockfile, parseInt('777', 8), function (error) {
			if (error) {
				console.log('Socket permission failed.', error);
			}
		});
		console.log('Master listening to socketfile: ' + config.sockfile);
	});

	// Statistics reporting
	if (config.statMonitor) {
		console.log('Stat monitor enabled. [' + config.statPulse + ']');
		setInterval(statApi.check, config.statPulse);
	} else {
		console.log('Stat monitor disabled.');
	}

} else {

	process.title = 'zlogd-worker';

	// Setup winston logging
	var transports = require(__dirname + '/../transports.json'),
		transportType,
		transportConfig;
	for (var i in transports) {
		switch (transports[i].type) {
			case 'file':
				transportType = winston.transports.File;
				transportConfig = transports[i].config;
				break;
			case 'logstash':
				transportType = winston.transports.Logstash;
				transportConfig = transports[i].config;
				break;
			default:
				console.log('Unknown transport: ' + transports[i].type);
		}
		winston.add(transportType, transportConfig);
	}
	winston.remove(winston.transports.Console);

	// Listen to messages from the master
	process.on('message', function(message) {
		// Master told me I have work to do!
		switch (message.type) {
			case 'work':
				async.each(message.data, workerApi.logChunkContent);
				if (config.statMonitor) {
					// Communicate completion statistics to master stat tracker
					process.send({
						type: 'complete',
						data: message.data.length
					});
				}
				break;
			default:
				console.log('Worker does not understand message.');
		}
	});

}
<commit_msg>Process to run as a daemon by default.<commit_after>#!/usr/bin/env node

var cluster = require('cluster'),
	net = require('net'),
	fs = require('fs'),
	winston = require('winston'),
	logstash = require('winston-logstash'),
	async = require('async');

// Process configuration
var config = {
	sockfile: process.env.SOCK_FILE || '/tmp/zlog.sock',
	workers: process.env.WORKERS || require('os').cpus().length,
	statMonitor: process.env.STAT_MONITOR || false,
	statPulse: process.env.STAT_PULSE || 3000,
	chunkDelimiter: process.env.DELIMITER || ';;'
}

var statCount = 0,
	worker,
	out = fs.openSync('./out.log', 'a'),
	err = fs.openSync('./out.log', 'a');

// Worker API
var workerApi = {
	logChunkContent: function(chunk) {
		var params, content;
		try {
			chunk = chunk.trim();
			if (!chunk) {
				return;
			}
			content = JSON.parse(chunk);
		} catch (error) {
			console.log('Invalid chunk JSON input:', chunk);
			return;
		}
		params = {
			grouper: content.grouper || 'default',
			category: content.category || 'default',
			source: content.source || 'default',
			meta: content.meta || {},
			timestamp: content.timestamp || new Date().getTime(),
		};

		winston.log(
			content.level || 'debug',
			content.message || '',
			params
		);
	}
}

var statApi = {
	lastCount: 0,
	check: function() {
		work = statCount - statApi.lastCount;
		console.log({
			time: new Date().getTime(),
			work: work,
			rate: work / (config.statPulse / 1000)
		});
		statApi.lastCount = statCount;
	}
}

if (cluster.isMaster) {

	process.title = 'zlogd';

	// Set off the process as a daemon
	if (!process.env.CHILD_FORKED) {
		var env = process.env;
		env.CHILD_FORKED = 1;
		var child = require('child_process').spawn('node', [__filename], {
			env: env,
			detached: false,
			stdio: [ 'ignore', out, err ]
		});
		child.unref();
		process.exit(0);
	}

	// Remove old socket files
	fs.unlink(config.sockfile, function (error) {
		if (error) {
			console.log('Error removing old sock file', error);
			return;
		}
	});

	console.log('Master process starting.');
	for (var i = config.workers; i > 0; i--) {
		worker = cluster.fork();
		console.log('Worker[' + worker.id + '] started.');
	}

	cluster.on('disconnect', function (worker) {
		console.log('Worker disconnected!');
	});

	cluster.on('exit', function (worker, code, signal) {
		console.error('Worker ' + worker.process.pid + ' died');
		if (worker.suicide) {
			cluster.fork();
		} else {
			if (Object.keys(cluster.workers).length <= 0) {
				console.error('No workers left, ending main process.');
				process.exit(1);
			}
		}
	});

	// Be a good master and listen to your workers!
	Object.keys(cluster.workers).forEach(function(id) {
		cluster.workers[id].on('message', function(workerMessage) {
			switch (workerMessage.type) {
				case 'complete':
					statCount += workerMessage.data;
					break;
				default:
					console.log('Master does not understand message.');
			}
		});
	});

	// Create the socket listener
	var server = net.createServer(function (socket) {
		var socketData = '', workToBeDone, split;
		socket.setEncoding('utf8');

		// Compile chunks for this request
		socket.on('data', function (data) {
			socketData += data;
		});

		// Delegate the work to the workers
		socket.on('end', function() {
			workToBeDone = socketData.split(config.chunkDelimiter);
			split = Math.ceil(workToBeDone.length / config.workers);
			for (var i in cluster.workers) {
				cluster.workers[i].send({
					type: 'work',
					data: workToBeDone.slice(0, split)
				});
				workToBeDone.splice(0, split);
			}
			socketData = '';
		});
	});

	// Start the server
	server.listen(config.sockfile, function () {
		fs.chmod(config.sockfile, parseInt('777', 8), function (error) {
			if (error) {
				console.log('Socket permission failed.', error);
			}
		});
		console.log('Master listening to socketfile: ' + config.sockfile);
	});

	// Statistics reporting
	if (config.statMonitor) {
		console.log('Stat monitor enabled. [' + config.statPulse + ']');
		setInterval(statApi.check, config.statPulse);
	} else {
		console.log('Stat monitor disabled.');
	}

} else {

	process.title = 'zlogd-worker';

	// Setup winston logging
	var transports = require(__dirname + '/../transports.json'),
		transportType,
		transportConfig;
	for (var i in transports) {
		switch (transports[i].type) {
			case 'file':
				transportType = winston.transports.File;
				transportConfig = transports[i].config;
				break;
			case 'logstash':
				transportType = winston.transports.Logstash;
				transportConfig = transports[i].config;
				break;
			default:
				console.log('Unknown transport: ' + transports[i].type);
		}
		winston.add(transportType, transportConfig);
	}
	winston.remove(winston.transports.Console);

	// Listen to messages from the master
	process.on('message', function(message) {
		// Master told me I have work to do!
		switch (message.type) {
			case 'work':
				async.each(message.data, workerApi.logChunkContent);
				if (config.statMonitor) {
					// Communicate completion statistics to master stat tracker
					process.send({
						type: 'complete',
						data: message.data.length
					});
				}
				break;
			default:
				console.log('Worker does not understand message.');
		}
	});

}
<|endoftext|>


<commit_before>/*   ./spec/bmi_ui_spec.js
*/
describe('BMI_UI - index.html', function() {
    beforeEach(function() {
        jasmine.getFixtures().fixturesPath = '.';
        loadFixtures('index.html');
        $.holdReady(false);
        $("input[type='radio']").get(0).checked = true;
        $('#weight').val(85);
        $('#height').val(185);
        $('#calculate').trigger('click');
    });

    it("displays metric BMI Value", function() {
        expect($('#display_value').text()).toBe('Your BMI is 24.84');
    });

    it("displays metric BMI Message", function() {
        expect($('#display_message').text()).toBe('and you are Normal');
    });

    it("displays imperial BMI Value", function() {
        $("input[type='radio']").get(1).checked = true;
        $('#weight').val(187);
        $('#height').val(72);
        $('#calculate').trigger('click');
        expect($('#display_value').text()).toBe('Your BMI is 25.36');
    });

    it("displays imperial BMI Message", function() {
        $('#weight').val('187');
        $('#height').val('72');
        $('#toggle').val('true');
        expect($('#display_message').text()).toBe('and you are Overweight');
    });
});
<commit_msg>add 'context' to imperial case by enclosing those tests in their own describe<commit_after>/*   ./spec/bmi_ui_spec.js
*/
describe('BMI_UI - index.html', function() {
    beforeEach(function() {
        jasmine.getFixtures().fixturesPath = '.';
        loadFixtures('index.html');
        $.holdReady(false);
        $("input[type='radio']").get(0).checked = true;
        $('#weight').val(85);
        $('#height').val(185);
        $('#calculate').trigger('click');
    });

    it("displays metric BMI Value", function() {
        expect($('#display_value').text()).toBe('Your BMI is 24.84');
    });

    it("displays metric BMI Message", function() {
        expect($('#display_message').text()).toBe('and you are Normal');
    });

    beforeEach(function (){
        $("input[type='radio']").get(1).checked = true;
        $('#weight').val(187);
        $('#height').val(72);
        $('#calculate').trigger('click');

        it("displays imperial BMI Value", function() {
            expect($('#display_value').text()).toBe('Your BMI is 25.36');
        });

        it("displays imperial BMI Message", function() {
            expect($('#display_message').text()).toBe('and you are Overweight');
        });
    });
});
<|endoftext|>


<commit_before><commit_msg>removing some dead code<commit_after><|endoftext|>


<commit_before><commit_msg>Remove the yui for creating and selecting nodes in the environment tests.<commit_after><|endoftext|>


<commit_before>var chai = require('chai').use(require('sinon-chai')),
    expect = chai.expect,
    sinon = require('sinon'),
    mongoose = require('mongoose'),
    eventful = require('./../')

describe('Model with mongoose-eventful plugin', function() {
  before(function(done) {
    mongoose.connect('mongodb://localhost/mongoose-eventful-test', function(err) {
      if (err) {
        console.error('MongoDB: ' + err.message)
        console.error('MongoDB is running? Is it accessible by this application?')
        return done(err)
      }
      mongoose.connection.db.dropDatabase(done)
    })
  })

  after(function(done) {
    mongoose.connection.close(done)
  })

  before(function() {
    this.EventfulSchema = new mongoose.Schema({}).plugin(eventful)
    this.EventfulModel = mongoose.model('EventfulModel', this.EventfulSchema)
  })

  it('emits created when document is created', function(done) {
    var callOnCreated = sinon.spy()
    this.EventfulModel.once('created', callOnCreated)
    this.EventfulModel.create({}, function() {
      expect(callOnCreated).to.have.been.called
      done()
    })
  })

  it('emits removed when document is removed', function(done) {
    var callOnRemoved = sinon.spy()
    this.EventfulModel.once('removed', callOnRemoved)
    this.EventfulModel.create({}, function(err, doc) {
      doc.remove(function(err) {
        expect(callOnRemoved).to.have.been.called
        done()
      })
    })
  })

  it('doesn\'t emit changed when document is created', function(done) {
    var callOnChanged = sinon.spy()
    this.EventfulModel.once('changed', callOnChanged)
    this.EventfulModel.create({}, function() {
      expect(callOnChanged).to.not.have.been.called
      done()
    })
  })

  describe('when emitChangedOnCreated option is true', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({}).plugin(eventful, {emitChangedOnCreated: true})
      this.EventfulModel = mongoose.model('EventfulModelWithEmitChangeOnCreatedOption', this.EventfulSchema)
    })

    it('emits changed when document is created', function(done) {
      var callOnChanged = sinon.spy()
      this.EventfulModel.once('changed', callOnChanged)
      this.EventfulModel.create({}, function() {
        expect(callOnChanged).to.have.been.called
        done()
      })
    })
  })

  describe('with a simple field', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({aSimpleField: 'string'}).plugin(eventful)
      this.EventfulModel = mongoose.model('EventfulModelWithSimpleField', this.EventfulSchema)
    })

    it('emits changed event when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aSimpleField: 'initial value'}, function(err, doc) {
        self.EventfulModel.once('changed', function(doc) {
          expect(doc.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('emits changed:<FieldName> when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aSimpleField: 'initial value'}, function(err, doc) {
        self.EventfulModel.once('changed:aSimpleField', function(doc) {
          expect(doc.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('doesn\'t emit changed:<FieldName> when document is created', function(done) {
      var callOnChanged = sinon.spy()
      this.EventfulModel.once('changed:aSimpleField', callOnChanged)
      this.EventfulModel.create({aSimpleField: 'initial value'}, function() {
        expect(callOnChanged).to.not.have.been.called
        done()
      })
    })
  })

  describe('with a nested field', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({aNestedField: {aSimpleField: 'string'}}).plugin(eventful)
      this.EventfulModel = mongoose.model('EventfulModelWithNestedField', this.EventfulSchema)
    })

    it('emits changed event when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aNestedField: {aSimpleField: 'initial value'}}, function(err, doc) {
        self.EventfulModel.once('changed', function(doc) {
          expect(doc.aNestedField.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aNestedField.aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('emits changed:<FieldName>.<FieldName> when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aNestedField: {aSimpleField: 'initial value'}}, function(err, doc) {
        self.EventfulModel.once('changed:aNestedField.aSimpleField', function(doc) {
          expect(doc.aNestedField.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aNestedField.aSimpleField', 'changed value')
        doc.save()
      })
    })
  })

  describe('with a virtual field', function() {
    describe('when emitChangedOnVirtualFields option is a list of virtual field paths', function() {
      before(function() {
        this.EventfulSchema = new mongoose.Schema(
          {aField: 'string', aSecondField: 'string'}
        )
        this.EventfulSchema.plugin(eventful, {emitChangedOnVirtualFields: 'aVirtualField'})
        this.EventfulSchema.virtual('aVirtualField').get(function() {
          return this.aField
        })
        this.EventfulModel = mongoose.model('EventfulModelWithVirtualField', this.EventfulSchema)
      })

      it('emits changed:<VirtualFieldName> when the virtual field is changed', function(done) {
        this.EventfulModel.once('changed:aVirtualField', function(doc) {
          expect(doc.aVirtualField).to.eql('changed value')
          done()
        })
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.set('aField', 'changed value')
          doc.save()
        })
      })

      it('emits changed:<VirtualFieldName> when dependent field is changed directly', function(done) {
        this.EventfulModel.once('changed:aVirtualField', function(doc) {
          expect(doc.aVirtualField).to.eql('changed value')
          done()
        })
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.aField = 'changed value'
          doc.save()
        })
      })

      it('doesn\'t emit changed:<VirtualFieldName> if the virtual field is not changed', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.set('aSecondField', 'changed value')
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })

      it('doen\'t emit changed:<VirtualFieldName> if nothing changed', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({}, function(err, doc) {
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })

      it('doen\'t emit changed:<VirtualFieldName> if nothing changed after creation', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })
    })
  })
})
<commit_msg>Remove amp escape in specs<commit_after>var chai = require('chai').use(require('sinon-chai')),
    expect = chai.expect,
    sinon = require('sinon'),
    mongoose = require('mongoose'),
    eventful = require('./../')

describe('Model with mongoose-eventful plugin', function() {
  before(function(done) {
    mongoose.connect('mongodb://localhost/mongoose-eventful-test', function(err) {
      if (err) {
        console.error('MongoDB: ' + err.message)
        console.error('MongoDB is running? Is it accessible by this application?')
        return done(err)
      }
      mongoose.connection.db.dropDatabase(done)
    })
  })

  after(function(done) {
    mongoose.connection.close(done)
  })

  before(function() {
    this.EventfulSchema = new mongoose.Schema({}).plugin(eventful)
    this.EventfulModel = mongoose.model('EventfulModel', this.EventfulSchema)
  })

  it('emits created when document is created', function(done) {
    var callOnCreated = sinon.spy()
    this.EventfulModel.once('created', callOnCreated)
    this.EventfulModel.create({}, function() {
      expect(callOnCreated).to.have.been.called
      done()
    })
  })

  it('emits removed when document is removed', function(done) {
    var callOnRemoved = sinon.spy()
    this.EventfulModel.once('removed', callOnRemoved)
    this.EventfulModel.create({}, function(err, doc) {
      doc.remove(function(err) {
        expect(callOnRemoved).to.have.been.called
        done()
      })
    })
  })

  it('does not emit changed when document is created', function(done) {
    var callOnChanged = sinon.spy()
    this.EventfulModel.once('changed', callOnChanged)
    this.EventfulModel.create({}, function() {
      expect(callOnChanged).to.not.have.been.called
      done()
    })
  })

  describe('when emitChangedOnCreated option is true', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({}).plugin(eventful, {emitChangedOnCreated: true})
      this.EventfulModel = mongoose.model('EventfulModelWithEmitChangeOnCreatedOption', this.EventfulSchema)
    })

    it('emits changed when document is created', function(done) {
      var callOnChanged = sinon.spy()
      this.EventfulModel.once('changed', callOnChanged)
      this.EventfulModel.create({}, function() {
        expect(callOnChanged).to.have.been.called
        done()
      })
    })
  })

  describe('with a simple field', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({aSimpleField: 'string'}).plugin(eventful)
      this.EventfulModel = mongoose.model('EventfulModelWithSimpleField', this.EventfulSchema)
    })

    it('emits changed event when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aSimpleField: 'initial value'}, function(err, doc) {
        self.EventfulModel.once('changed', function(doc) {
          expect(doc.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('emits changed:<FieldName> when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aSimpleField: 'initial value'}, function(err, doc) {
        self.EventfulModel.once('changed:aSimpleField', function(doc) {
          expect(doc.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('does not emit changed:<FieldName> when document is created', function(done) {
      var callOnChanged = sinon.spy()
      this.EventfulModel.once('changed:aSimpleField', callOnChanged)
      this.EventfulModel.create({aSimpleField: 'initial value'}, function() {
        expect(callOnChanged).to.not.have.been.called
        done()
      })
    })
  })

  describe('with a nested field', function() {
    before(function() {
      this.EventfulSchema = new mongoose.Schema({aNestedField: {aSimpleField: 'string'}}).plugin(eventful)
      this.EventfulModel = mongoose.model('EventfulModelWithNestedField', this.EventfulSchema)
    })

    it('emits changed event when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aNestedField: {aSimpleField: 'initial value'}}, function(err, doc) {
        self.EventfulModel.once('changed', function(doc) {
          expect(doc.aNestedField.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aNestedField.aSimpleField', 'changed value')
        doc.save()
      })
    })

    it('emits changed:<FieldName>.<FieldName> when the field is changed', function(done) {
      var self = this

      self.EventfulModel.create({aNestedField: {aSimpleField: 'initial value'}}, function(err, doc) {
        self.EventfulModel.once('changed:aNestedField.aSimpleField', function(doc) {
          expect(doc.aNestedField.aSimpleField).to.eql('changed value')
          done()
        })
        doc.set('aNestedField.aSimpleField', 'changed value')
        doc.save()
      })
    })
  })

  describe('with a virtual field', function() {
    describe('when emitChangedOnVirtualFields option is a list of virtual field paths', function() {
      before(function() {
        this.EventfulSchema = new mongoose.Schema(
          {aField: 'string', aSecondField: 'string'}
        )
        this.EventfulSchema.plugin(eventful, {emitChangedOnVirtualFields: 'aVirtualField'})
        this.EventfulSchema.virtual('aVirtualField').get(function() {
          return this.aField
        })
        this.EventfulModel = mongoose.model('EventfulModelWithVirtualField', this.EventfulSchema)
      })

      it('emits changed:<VirtualFieldName> when the virtual field is changed', function(done) {
        this.EventfulModel.once('changed:aVirtualField', function(doc) {
          expect(doc.aVirtualField).to.eql('changed value')
          done()
        })
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.set('aField', 'changed value')
          doc.save()
        })
      })

      it('emits changed:<VirtualFieldName> when dependent field is changed directly', function(done) {
        this.EventfulModel.once('changed:aVirtualField', function(doc) {
          expect(doc.aVirtualField).to.eql('changed value')
          done()
        })
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.aField = 'changed value'
          doc.save()
        })
      })

      it('does not emit changed:<VirtualFieldName> if the virtual field is not changed', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.set('aSecondField', 'changed value')
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })

      it('does not emit changed:<VirtualFieldName> if nothing changed', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({}, function(err, doc) {
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })

      it('does not emit changed:<VirtualFieldName> if nothing changed after creation', function(done) {
        var callOnChanged = sinon.spy()
        this.EventfulModel.once('changed:aVirtualField', callOnChanged)
        this.EventfulModel.create({aField: 'initial value', aSecondField: 'initial value'}, function(err, doc) {
          doc.save(function() {
            expect(callOnChanged).to.not.have.been.called
            done()
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before><commit_msg>添加备注并更改本位币小计的计算<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the Purple theme to be the same as it was before single app (#3418)<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for not eligible on the damaged pass page<commit_after><|endoftext|>


<commit_before><commit_msg>Update Form Validation<commit_after><|endoftext|>