<commit_before>"use strict"

var typeindex = 0;
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var typeStack = [];

var ExecutionStack = [];

var lastnode;

var sugg = {}; // suggestions for autocompletion of node names

var ANALYSIS_NODE_START = 'ANALYSIS_NODE_START';
var ANALYSIS_LINK = 'ANALYSIS_LINK';

function autoSuggestAddName(name)
{
    /* note that name can contain spaces - this is ok. We might want to limit this though? */
    if(name.split(" ").length > 1) {
        sugg['"' + name + '"'] = 1;
    } else {
        sugg[name] = 1;
    }
}

function autocompleteCallback(request, response_callback)
{
    var ret = [];
    if (request.term === "" || request.term) {
        for (var name in sugg) {
            if (name.indexOf(request.term) == 0) {
                ret.push(name);
            }
        }
    }
    response_callback(ret);
}

function same_up_to_one_letter(s1, s2)
{
    return ((s1.length == s2.length + 1 && s1.substr(0, s2.length) == s2) ||
            (s2.length == s1.length + 1 && s2.substr(0, s1.length) == s1));
}

function up_to_two_renames(graph, old_id, new_id)
{
    var not_one_letter = false;
    var k;

    if (old_id.length != new_id.length) {
        console.log('bug: up_to_two_renames: not equal inputs');
        return;
    }
    if (old_id.length > 2) {
        console.log('bug: up_to_two_renames: input length 2 < ' + old_id.length);
        return;
    }
    if (old_id.length == 2) {
        if (same_up_to_one_letter(old_id[0], new_id[1]) &&
            same_up_to_one_letter(old_id[1], new_id[0])) {
            old_id = [old_id[1], old_id[0]];
        } else {
            if (!same_up_to_one_letter(old_id[0], new_id[0]) ||
                !same_up_to_one_letter(old_id[1], new_id[1])) {
                not_one_letter = true;
            }
        }
    }
    if (not_one_letter) {
        console.log('bug: up_to_two_renames: not one letter changes');
        console.log(old_id);
        console.log(new_id);
        return;
    }
    for (k = 0 ; k < old_id.length ; ++k) {
        graph.editName(old_id[k], null, new_id[k]);
    }
}

/*
 * textAnalyser2
 *
 * Input:
 *  @newtext - new sentence
 *  @finalize - is this an intermediate editing state or are we editing the graph
 *
 * Output:
 *  none
 *
 * Side effect:
 *  updating graph (global)
 *
 * Implementation notes:
 *  There is no well defined grammer. The translation goes from obvious to not
 *  so much for more complex sentences involving more then two nodes (two '#'
 *  marks).
 *
 */
var textAnalyser2 = function (newtext, finalize) {
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    var linkindex = 0;
    var nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";
    var ret = {'nodes': [], 'links': []};
    var m;
    var word;
    var completeSentence;
    var typesetter, abnormalGraph;
    var verb;
    var l, n, j;
    var link_hash = {};
    var yell_bug = false; // TODO: fix both issues

    function addNode(id, type, state) {
        ret.nodes.push({'id':id, 'type':type, 'state':state});
    }
    function addLink(src, dst, name, state) {
        if (!src || !dst) {
            if (yell_bug) {
                console.log('bug - adding link (' + src + ', ' + dst + ')');
            }
            return;
        }
        if (link_hash[src] && link_hash[src][dst]) {
            if (yell_bug) {
                console.log('bug - adding link twice (' + src + ', ' + dst + ')');
            }
            return;
        }
        if (!link_hash[src]) {
            link_hash[src] = {};
        }
        link_hash[src][dst] = 1;
        ret.links.push({'sourceId':src, 'targetId':dst, 'name':name ? name.trim() : "", 'state':state});
    }

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

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (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 += (prefix.length > 0 ? ' ' : '') + sentence[m];
            }
            break;
        }
    }

    //PREFIX not null case - put complete sentence in first link.
    if (prefix) {
        newlinks[1] = prefix + " " + newnodes[0] +
        (newlinks[1] !== undefined || newnodes[1] !== undefined ?
        " " : "")
        + (newlinks[1] !== undefined ? newlinks[1] : "")
        + (newnodes[1] !== undefined ? newnodes[1] : "");
    }

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    word = "";
    completeSentence = prefix.length > 0 ? String(prefix) + " " : "";
    for (m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            if(newnodes[nodeindex].split(" ").length>1){
                completeSentence += '"'+newnodes[nodeindex]+'"' + " ";
            }else{
                completeSentence += newnodes[nodeindex] + " ";
            }
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }
    completeSentence = completeSentence.trim();

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

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

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

    abnormalGraph = (newlinks.length - ANDcount) >= 2;

    //0-N ORDER STACK
    for (m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if (!typeStack[nodeindex]) {
                    typeStack[nodeindex] = nodetypes[typeindex];
                }
                break;
            case "NODE":
                addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) {
                    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];
            addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_NODE_START;
            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                ANDconnect(newnodes[nodeindex]);
            }
            break;
        case "LINK":
            linkindex++;
            addNode("new node", "empty", "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_LINK;
            break;
    }

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

            }
        }
    }

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

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

    ret.drop_conjugator_links = ANDcount < linkindex;

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

    ret.applyToGraph = function(graph) {
        window.ret = ret;
        var comp = graph.compareSubset('temp', ret.nodes.filter(
            function(node) {
                return !graph.hasNode(node.id, "perm");
            }).map(function (node) {
                return node.id;
            }), ret.links.map(
            function (link) {
                return [link.sourceId.toLowerCase(), link.targetId.toLowerCase()];
            }
        ));
        var k, n, l;
        if (comp.graph_same && !finalize) {
            if (comp.old_id && comp.new_id) {
                up_to_two_renames(graph, comp.old_id, comp.new_id);
            }
            for (k in ret.links) {
                l = ret.links[k];
                graph.addLink(l.sourceId, l.targetId, l.name, l.state, ret.drop_conjugator_links);
            }
        } else {
            //REINITIALISE GRAPH (DUMB BUT IT WORKS)
            graph.removeNodes("temp");
            graph.removeLinks("temp");
            for (k in ret.nodes) {
                n = ret.nodes[k];
                graph.addNode(n.id, n.type, n.state);
            }
            for (k in ret.links) {
                l = ret.links[k];
                graph.addLink(l.sourceId, l.targetId, l.name, l.state, ret.drop_conjugator_links);
            }
        }
        //UPDATE GRAPH ONCE
        graph.update(!finalize && comp.graph_same);
    }

    return ret;
}
<commit_msg>Revert "Allow chainlink when no last node is there"<commit_after>"use strict"

var typeindex = 0;
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var typeStack = [];

var ExecutionStack = [];

var lastnode;

var sugg = {}; // suggestions for autocompletion of node names

var ANALYSIS_NODE_START = 'ANALYSIS_NODE_START';
var ANALYSIS_LINK = 'ANALYSIS_LINK';

function autoSuggestAddName(name)
{
    /* note that name can contain spaces - this is ok. We might want to limit this though? */
    if(name.split(" ").length > 1) {
        sugg['"' + name + '"'] = 1;
    } else {
        sugg[name] = 1;
    }
}

function autocompleteCallback(request, response_callback)
{
    var ret = [];
    if (request.term === "" || request.term) {
        for (var name in sugg) {
            if (name.indexOf(request.term) == 0) {
                ret.push(name);
            }
        }
    }
    response_callback(ret);
}

function same_up_to_one_letter(s1, s2)
{
    return ((s1.length == s2.length + 1 && s1.substr(0, s2.length) == s2) ||
            (s2.length == s1.length + 1 && s2.substr(0, s1.length) == s1));
}

function up_to_two_renames(graph, old_id, new_id)
{
    var not_one_letter = false;
    var k;

    if (old_id.length != new_id.length) {
        console.log('bug: up_to_two_renames: not equal inputs');
        return;
    }
    if (old_id.length > 2) {
        console.log('bug: up_to_two_renames: input length 2 < ' + old_id.length);
        return;
    }
    if (old_id.length == 2) {
        if (same_up_to_one_letter(old_id[0], new_id[1]) &&
            same_up_to_one_letter(old_id[1], new_id[0])) {
            old_id = [old_id[1], old_id[0]];
        } else {
            if (!same_up_to_one_letter(old_id[0], new_id[0]) ||
                !same_up_to_one_letter(old_id[1], new_id[1])) {
                not_one_letter = true;
            }
        }
    }
    if (not_one_letter) {
        console.log('bug: up_to_two_renames: not one letter changes');
        console.log(old_id);
        console.log(new_id);
        return;
    }
    for (k = 0 ; k < old_id.length ; ++k) {
        graph.editName(old_id[k], null, new_id[k]);
    }
}

/*
 * textAnalyser2
 *
 * Input:
 *  @newtext - new sentence
 *  @finalize - is this an intermediate editing state or are we editing the graph
 *
 * Output:
 *  none
 *
 * Side effect:
 *  updating graph (global)
 *
 * Implementation notes:
 *  There is no well defined grammer. The translation goes from obvious to not
 *  so much for more complex sentences involving more then two nodes (two '#'
 *  marks).
 *
 */
var textAnalyser2 = function (newtext, finalize) {
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    var linkindex = 0;
    var nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";
    var ret = {'nodes': [], 'links': []};
    var m;
    var word;
    var completeSentence;
    var typesetter, abnormalGraph;
    var verb;
    var l, n, j;
    var link_hash = {};
    var yell_bug = false; // TODO: fix both issues

    function addNode(id, type, state) {
        ret.nodes.push({'id':id, 'type':type, 'state':state});
    }
    function addLink(src, dst, name, state) {
        if (!src || !dst) {
            if (yell_bug) {
                console.log('bug - adding link (' + src + ', ' + dst + ')');
            }
            return;
        }
        if (link_hash[src] && link_hash[src][dst]) {
            if (yell_bug) {
                console.log('bug - adding link twice (' + src + ', ' + dst + ')');
            }
            return;
        }
        if (!link_hash[src]) {
            link_hash[src] = {};
        }
        link_hash[src][dst] = 1;
        ret.links.push({'sourceId':src, 'targetId':dst, 'name':name ? name.trim() : "", 'state':state});
    }

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

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (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 += (prefix.length > 0 ? ' ' : '') + sentence[m];
            }
            break;
        }
    }

    //PREFIX not null case - put complete sentence in first link.
    if (prefix) {
        newlinks[1] = prefix + " " + newnodes[0] +
        (newlinks[1] !== undefined || newnodes[1] !== undefined ?
        " " : "")
        + (newlinks[1] !== undefined ? newlinks[1] : "")
        + (newnodes[1] !== undefined ? newnodes[1] : "");
    }

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    word = "";
    completeSentence = prefix.length > 0 ? String(prefix) + " " : "";
    for (m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            if(newnodes[nodeindex].split(" ").length>1){
                completeSentence += '"'+newnodes[nodeindex]+'"' + " ";
            }else{
                completeSentence += newnodes[nodeindex] + " ";
            }
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }
    completeSentence = completeSentence.trim();

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

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

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

    abnormalGraph = (newlinks.length - ANDcount) >= 3;

    //0-N ORDER STACK
    for (m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if (!typeStack[nodeindex]) {
                    typeStack[nodeindex] = nodetypes[typeindex];
                }
                break;
            case "NODE":
                addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) {
                    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];
            addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_NODE_START;
            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                ANDconnect(newnodes[nodeindex]);
            }
            break;
        case "LINK":
            linkindex++;
            addNode("new node", "empty", "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_LINK;
            break;
    }

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

            }
        }
    }

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

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

    ret.drop_conjugator_links = ANDcount < linkindex;

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

    ret.applyToGraph = function(graph) {
        window.ret = ret;
        var comp = graph.compareSubset('temp', ret.nodes.filter(
            function(node) {
                return !graph.hasNode(node.id, "perm");
            }).map(function (node) {
                return node.id;
            }), ret.links.map(
            function (link) {
                return [link.sourceId.toLowerCase(), link.targetId.toLowerCase()];
            }
        ));
        var k, n, l;
        if (comp.graph_same && !finalize) {
            if (comp.old_id && comp.new_id) {
                up_to_two_renames(graph, comp.old_id, comp.new_id);
            }
            for (k in ret.links) {
                l = ret.links[k];
                graph.addLink(l.sourceId, l.targetId, l.name, l.state, ret.drop_conjugator_links);
            }
        } else {
            //REINITIALISE GRAPH (DUMB BUT IT WORKS)
            graph.removeNodes("temp");
            graph.removeLinks("temp");
            for (k in ret.nodes) {
                n = ret.nodes[k];
                graph.addNode(n.id, n.type, n.state);
            }
            for (k in ret.links) {
                l = ret.links[k];
                graph.addLink(l.sourceId, l.targetId, l.name, l.state, ret.drop_conjugator_links);
            }
        }
        //UPDATE GRAPH ONCE
        graph.update(!finalize && comp.graph_same);
    }

    return ret;
}
<|endoftext|>


<commit_before>var Trello = require('node-trello');
var encryption = require('./encryption.js');
var db = require('./mlab-login.js').db();
var Promise = require("bluebird");

var key = process.env.HUBOT_TRELLO_KEY;
var trello = {};
var tP = {};

db.bind('trelloTokens');
db.trelloTokens.find().toArrayAsync()
    .then(function (records) {
        let length = Object.keys(records).length;
        let i = 0;
        for (i = 0; i < length; i++) {
            let token = encryption.decrypt(records[i].token);
            let userId = records[i].id;
            let t = new Trello(key, token)
            trello[userId] = Promise.promisifyAll(t)
            trello[userId].get('/1/members/me', function (err, data) {
                if (err) throw err;
                console.log(data);
            })
        }
    })
    .catch(error => {
        console.log(error)
    })

module.exports = trello
<commit_msg>trello login<commit_after>var Trello = require('node-trello');
var encryption = require('./encryption.js');
var db = require('./mlab-login.js').db();
var Promise = require("bluebird");

var key = process.env.HUBOT_TRELLO_KEY;
var trello = {};
var tP = {};

db.bind('trelloTokens');
db.trelloTokens.find().toArrayAsync()
    .then(function (records) {
        let length = Object.keys(records).length;
        let i = 0;
        for (i = 0; i < length; i++) {
            let token = encryption.decrypt(records[i].token);
            let userId = records[i].id;
            let t = new Trello(key, token);
            trello[userId] = Promise.promisifyAll(t);

            // in some way CHECK TOKEN VALIDATION
            trello[userId].get('/1/tokens/'+token, function (err, data) {
                if (err) throw err;
                console.log(data);
            })
        }
    })
    .catch(error => {
        console.log(error)
    })

module.exports = trello
<|endoftext|>


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

/*
* Parse an existing Query dump, metadata records, to find any invalid PID refs and fix them.
* @author seaton
*
*/

var mg = require('mongoose');
var jsonpath = require('jsonpath-plus');
var _ = require('underscore');

var config = require('../data/config.json');
var utils = require('../lib/utils.js');

var handle = config.get('escidoc_handle');
var queryTarget = config.get('targetQuery');
var session = null;

var db = mg.connect(config.get('mongoose_auth'));

var schema = require('../lib/schema.js');
var QueryModel = schema.models.Query;
var SessionModel = schema.models.Session;

var openSession = function(session, callback) {
  session = session;
  callback(queryId);
};

var findQuery = function(queryId) {
  if(!mg.Types.ObjectId.isValid(queryId))
    throw new Error("Query Id is invalid.");

  Query.findById(queryId)
    .populate("result_collection")
    .populate({
      path: '_session',
      select: '_id'
    })
    .exec(function(err, query) {
      if (query != null && query._session == session._id.toString()) { // Session match
        parseQuery(query, function(invalidPID, idRef, type) {
          // match id ref with content PID refs url (resolve)
          // if true
          // skip over
          // otherwise
          // update PID with content PID with corrected url ref
          // PID-manager POST
        });
      } else {
        throw new Error("No Query found for Session: " + session._id);
      }
    });
};

var parseQuery = function(queryResult, callback) {
  _u.each(query.result_collection, function(record) {
      var resourceProxyPath = "/CMD/Resources/ResourceProxyList/ResourceProxy"
      parseRecord(record, resourceProxyPath, function(val) {
          console.log('result:: ' + val.id, val.ResourceRef['$t']);
      });
  });
};

// parse records, iterate over resource proxies (pid refs)
var parseRecord = function(record, callback) {
  JSONPath({
    json: record,
    path: path,
    callback: callback
  });
};

// Use existing user session (escidoc_handle)
utils.getSession(schema.models.Session, function(res, err) { if(!err) openSession(res, queryTarget); else throw err; });
<commit_msg>Load session by eSciDoc handle token (set config).<commit_after>#!/usr/bin/env node

/*
* Parse an existing Query dump, metadata records, to find any invalid PID refs and fix them.
* @author seaton
*
*/

var mg = require('mongoose');
var jsonpath = require('jsonpath-plus');
var _ = require('underscore');

var config = require('../data/config.json');

var handle = config.get('escidoc_handle');
var queryTarget = config.get('targetQuery');
var session = null;

var db = mg.connect(config.get('mongoose_auth'));

var schema = require('../lib/schema.js');
var QueryModel = schema.models.Query;
var SessionModel = schema.models.Session;

var openSession = function(session, callback) {
  session = session;
  callback(queryId);
};

var getSession = function(sessionModel, callback) {
  sessionModel.findByHandle(handle, function(err, res) {
    if(!err)
          if(res != null) callback(res);
        else callback(res, new Error("No valid Session exists for set handle: " + handle));
    else
        throw new Error("Error opening Session: " + err);
  });
};

var findQuery = function(queryId) {
  if(!mg.Types.ObjectId.isValid(queryId))
    throw new Error("Query Id is invalid.");

  Query.findById(queryId)
    .populate("result_collection")
    .populate({
      path: '_session',
      select: '_id'
    })
    .exec(function(err, query) {
      if (query != null && query._session == session._id.toString()) { // Session match
        parseQuery(query, function(invalidPID, idRef, type) {
          // match id ref with content PID refs url (resolve)
          // if true
          // skip over
          // otherwise
          // update PID with content PID with corrected url ref
          // PID-manager POST
        });
      } else {
        throw new Error("No Query found for Session: " + session._id);
      }
    });
};

var parseQuery = function(queryResult, callback) {
  _u.each(query.result_collection, function(record) {
      var resourceProxyPath = "/CMD/Resources/ResourceProxyList/ResourceProxy"
      parseRecord(record, resourceProxyPath, function(val) {
          console.log('result:: ' + val.id, val.ResourceRef['$t']);
      });
  });
};

// parse records, iterate over resource proxies (pid refs)
var parseRecord = function(record, callback) {
  JSONPath({
    json: record,
    path: path,
    callback: callback
  });
};

// Use existing user session (escidoc_handle)
getSession(schema.models.Session, function(res, err) { if(!err) openSession(res, queryTarget); else throw err; });
<|endoftext|>


<commit_before>/*!
{
  "name": "History API",
  "property": "history",
  "caniuse": "history",
  "tags": ["history"],
  "authors": ["Hay Kranen", "Alexander Farkas"],
  "notes": [{
    "name": "W3C Spec",
    "href": "http://www.w3.org/TR/html51/browsers.html#the-history-interface"
  }, {
    "name": "MDN documentation",
    "href": "https://developer.mozilla.org/en-US/docs/Web/API/window.history"
  }],
  "polyfills": ["historyjs", "html5historyapi"]
}
!*/
/* DOC
Detects support for the History API for manipulating the browser session history.
*/
define(['Modernizr'], function( Modernizr ) {
  Modernizr.addTest('history', function() {
    // Issue #733
    // The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support
    // Unfortunately support is really buggy and there is no clean way to detect
    // these bugs, so we fall back to a user agent sniff :(
    var ua = navigator.userAgent;

    // We only want Android 2 and 4.0, stock browser, and not Chrome which identifies
    // itself as 'Mobile Safari' as well
    if ((ua.indexOf('Android 2.') !== -1 ||
        (ua.indexOf('Android 4.0') !== -1)) &&
        ua.indexOf('Mobile Safari') !== -1 &&
        ua.indexOf('Chrome') === -1) {
      return false;
    }

    // Return the regular check
    return (window.history && 'pushState' in window.history);
  });
});
<commit_msg>Update UA check to fix false negative on WP 8.1<commit_after>/*!
{
  "name": "History API",
  "property": "history",
  "caniuse": "history",
  "tags": ["history"],
  "authors": ["Hay Kranen", "Alexander Farkas"],
  "notes": [{
    "name": "W3C Spec",
    "href": "http://www.w3.org/TR/html51/browsers.html#the-history-interface"
  }, {
    "name": "MDN documentation",
    "href": "https://developer.mozilla.org/en-US/docs/Web/API/window.history"
  }],
  "polyfills": ["historyjs", "html5historyapi"]
}
!*/
/* DOC
Detects support for the History API for manipulating the browser session history.
*/
define(['Modernizr'], function( Modernizr ) {
  Modernizr.addTest('history', function() {
    // Issue #733
    // The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support
    // Unfortunately support is really buggy and there is no clean way to detect
    // these bugs, so we fall back to a user agent sniff :(
    var ua = navigator.userAgent;

    // We only want Android 2 and 4.0, stock browser, and not Chrome which identifies
    // itself as 'Mobile Safari' as well, nor Windows Phone (issue #1471).
    if ((ua.indexOf('Android 2.') !== -1 ||
        (ua.indexOf('Android 4.0') !== -1)) &&
        ua.indexOf('Mobile Safari') !== -1 &&
        ua.indexOf('Chrome') === -1 &&
        ua.indexOf('Windows Phone') === -1) {
      return false;
    }

    // Return the regular check
    return (window.history && 'pushState' in window.history);
  });
});
<|endoftext|>


<commit_before>import co from 'co'

import SCENE_MANAGER  from 'bemuse/scene-manager'
import query          from 'bemuse/utils/query'
import React          from 'react'
import LoadingScene   from './ui/loading-scene.jsx'
import GameShellScene from './ui/game-shell-scene.jsx'
import GameScene      from './game-scene'

import URLResource            from 'bemuse/resources/url'
import BemusePackageResources from 'bemuse/resources/bemuse-package'
import { unmuteAudio }        from 'bemuse/sampling-master'
import audioContext           from 'audio-context'

import { resolve } from 'url'

import * as GameLoader from './loaders/game-loader'

export function main() {

  // iOS
  window.addEventListener('touchstart', function unmute() {
    unmuteAudio(audioContext)
    window.removeEventListener('touchstart', unmute)
  })

  let displayShell = function(options) {
    return new Promise(function(_resolve) {
      let scene = React.createElement(GameShellScene, {
        options: options,
        play: function(data) {
          _resolve(data)
        },
      })
      SCENE_MANAGER.display(scene).done()
    })
  }

  let getSong = co.wrap(function*() {
    let options = {
      url: query.bms || '/music/[snack]ddddevelopers/dddd_sph.bme',
      game: {
        audioInputLatency: +query.audioInputLatency || 0,
      },
      players: [
        {
          speed:      +query.speed || 3.5,
          autoplay:   !!query.autoplay,
          placement:  'center',
        }
      ],
    }
    options = yield displayShell(options)
    let url = options.url
    let assetsUrl = resolve(url, 'assets/')
    let metadata = {
      title: 'Loading',
      subtitles: [],
      artist: '',
      genre: '',
      subartists: [],
    }
    let loadSpec = {
      bms:      options.resource  || new URLResource(url),
      assets:   options.resources || new BemusePackageResources(assetsUrl),
      metadata: metadata,
      options:  Object.assign({ }, options.game, { players: options.players }),
    }
    return loadSpec
  })

  co(function*() {
    let loadSpec = yield getSong()
    let { tasks, promise } = GameLoader.load(loadSpec)
    yield SCENE_MANAGER.display(React.createElement(LoadingScene, {
      tasks: tasks,
      song: loadSpec.metadata,
    }))
    let controller = yield promise
    yield SCENE_MANAGER.display(new GameScene(controller.display))
    controller.start()
  })
  .done()
}
<commit_msg>feat(GameShell): allow keyboard setting via query parameter<commit_after>import co from 'co'

import SCENE_MANAGER  from 'bemuse/scene-manager'
import query          from 'bemuse/utils/query'
import React          from 'react'
import LoadingScene   from './ui/loading-scene.jsx'
import GameShellScene from './ui/game-shell-scene.jsx'
import GameScene      from './game-scene'

import URLResource            from 'bemuse/resources/url'
import BemusePackageResources from 'bemuse/resources/bemuse-package'
import { unmuteAudio }        from 'bemuse/sampling-master'
import audioContext           from 'audio-context'

import { resolve } from 'url'

import * as GameLoader from './loaders/game-loader'

export function main() {

  // iOS
  window.addEventListener('touchstart', function unmute() {
    unmuteAudio(audioContext)
    window.removeEventListener('touchstart', unmute)
  })

  let displayShell = function(options) {
    return new Promise(function(_resolve) {
      let scene = React.createElement(GameShellScene, {
        options: options,
        play: function(data) {
          _resolve(data)
        },
      })
      SCENE_MANAGER.display(scene).done()
    })
  }

  let getSong = co.wrap(function*() {
    let kbm = (query.keyboard || '').split(',').map(x => +x)
    let options = {
      url: query.bms || '/music/[snack]ddddevelopers/dddd_sph.bme',
      game: {
        audioInputLatency: +query.audioInputLatency || 0,
      },
      players: [
        {
          speed:      +query.speed || 3.5,
          autoplay:   !!query.autoplay,
          placement:  'center',
          input: {
            keyboard: {
              '1':  kbm[0] || 83,
              '2':  kbm[1] || 68,
              '3':  kbm[2] || 70,
              '4':  kbm[3] || 32,
              '5':  kbm[4] || 74,
              '6':  kbm[5] || 75,
              '7':  kbm[6] || 76,
              'SC': kbm[7] || 65,
            },
          },
        }
      ],
    }
    options = yield displayShell(options)
    let url = options.url
    let assetsUrl = resolve(url, 'assets/')
    let metadata = {
      title: 'Loading',
      subtitles: [],
      artist: '',
      genre: '',
      subartists: [],
    }
    let loadSpec = {
      bms:      options.resource  || new URLResource(url),
      assets:   options.resources || new BemusePackageResources(assetsUrl),
      metadata: metadata,
      options:  Object.assign({ }, options.game, { players: options.players }),
    }
    return loadSpec
  })

  co(function*() {
    let loadSpec = yield getSong()
    let { tasks, promise } = GameLoader.load(loadSpec)
    yield SCENE_MANAGER.display(React.createElement(LoadingScene, {
      tasks: tasks,
      song: loadSpec.metadata,
    }))
    let controller = yield promise
    yield SCENE_MANAGER.display(new GameScene(controller.display))
    controller.start()
  })
  .done()
}
<|endoftext|>


<commit_before>import * as PIXI from 'pixi.js';
import RouteNode from './routenode';
import RouteSegment from './routesegment';
import Log from './log';
import LogDeposit from './logdeposit';
import { endpointByStartPointDistanceAndAngle, distance } from './helpers';
import {LogType} from './logtypes'

export default class Level {
  constructor(map) {
    this.map = map;
<<<<<<< HEAD
    this.stage = new PIXI.Container();
    this.routeContainer = new PIXI.Container();
    this.stage.addChild(this.routeContainer);
=======
    this.stage = stage;
>>>>>>> origin/master
    this.routeNodes = new Map();
    this.routeSegments = [];
    this.logs = [];
    this.logDeposits = [];
    this.routeTexture = PIXI.Texture.fromImage('/static/road.png');

    if (map) {
      this.parseRouteNodes();
      this.parseLogs();
      this.parseLogDeposits();

      this.generateRouteSegments();
      this.drawRoutes();
    }

  }

  getStage() {
    return this.stage;
  }

  // used by map editor
  getRouteNodes() {
    return this.routeNodes;
  }

  // used by map editor
  getNextRouteNodeId() {
    return this.routeNodes.size + 1;
  }

  drawRoutes() {
    const roadSpriteLength = 50;

<<<<<<< HEAD
    for(var j = 0; j < this.routeSegments.length; ++j) {
      var spos = this.routeSegments[j].startNode.getPos();
      var epos = this.routeSegments[j].endNode.getPos();

      var angle = Math.atan2(epos.y - spos.y, epos.x - spos.x) + Math.PI/2;
      var currentPos = {x: spos.x, y: spos.y};
      var roadSprite;
      var distanceToEnd = 0;
      var tilingSprite = new PIXI.extras.TilingSprite(
        this.routeTexture,
        roadSpriteLength,
        distance(spos, epos)
      );
      tilingSprite.anchor.set(0.5, 0.0);
      tilingSprite.tileScale.set(0.1);
      tilingSprite.rotation = angle + Math.PI;
      tilingSprite.x = currentPos.x;
      tilingSprite.y = currentPos.y;
      this.stage.addChild(tilingSprite);
=======
    var texture = PIXI.Texture.fromImage('/static/road.png');
    for(let [id, routeNode] of this.routeNodes) {
      var segments = routeNode.getSegments();
      for(var j = 0; j < segments.length; ++j) {
        var spos = segments[j].startNode.getPos();
        var epos = segments[j].endNode.getPos();

        var angle = Math.atan2(epos.y - spos.y, epos.x - spos.x) + Math.PI/2;
        var currentPos = {x: spos.x, y: spos.y};
        var roadSprite;
        var distanceToEnd = 0;
        var tilingSprite = new PIXI.extras.TilingSprite(
          texture,
          roadSpriteLength,
          distance(spos, epos)
        );
        tilingSprite.anchor.set(0.5, 0.0);
        tilingSprite.tileScale.set(0.1);
        tilingSprite.rotation = angle + Math.PI;
        tilingSprite.x = currentPos.x;
        tilingSprite.y = currentPos.y;
        this.stage.addChild(tilingSprite);
      }
>>>>>>> origin/master
    }

    for(let [id, routeNode] of this.routeNodes) {
      var intersectionSprite = new PIXI.Sprite.fromImage('./static/road_intersection.png');
      intersectionSprite.anchor.set(0.5, 0.5);
      intersectionSprite.scale.set(0.1);
      intersectionSprite.x = routeNode.getPos().x;
      intersectionSprite.y = routeNode.getPos().y;
      this.stage.addChild(intersectionSprite);
    }
  }

  pastEndPosition(spos, epos, cpos) {
    if ((spos.x < epos.x && cpos.x > epos.x) ||
        (spos.x > epos.x && cpos.x < epos.x) ||
        (spos.y < epos.y && cpos.y > epos.y) ||
        (spos.y > epos.y && cpos.y < epos.y)) {
      return true;
    }
    return false;
  }

  parseRouteNodes() {
    for (var i = 0; i < this.map.routes.length; ++i) {
      var routeNodeData = this.map.routes[i];
      var id = routeNodeData.route_node;
      var pos = {x: routeNodeData.x, y: routeNodeData.y };
      var to = routeNodeData.to;
      this.addRouteNode(id, pos, to);
    }
  }

  addRouteNode(id, pos, to) {
    this.routeNodes.set(id, new RouteNode(id, pos, to));
  }

  // used by map editor
  refreshRoutes() {
    this.routeSegments = [];
    this.routeContainer.removeChildren();

    // reset, mainly to remove segments from them
    for (let [id, node] of this.routeNodes) {
      node.reset(id, node.point, node.to);
    }

    this.generateRouteSegments();
    this.drawRoutes();
  }

  generateRouteSegments() {

    for (let [id, startNode] of this.routeNodes) {
      var endNode = null;
      var segment = null;
      // checking if there is multiple routes from this node
      // if not we just use default settings

      /** REMOVED SUPPORT FOR AUTOMATIC NEXT NODE **/
      /** It was removed because there were some interesting problems with dublicate segments **/
      // if(!startNode.getPos().to && i < this.routeNodes.length-1) {
      //   endNode = this.routeNodes[i+1];
      //   segment = new RouteSegment(startNode, endNode);
      //   this.routeNodes[i].addSegment(segment);
      //   this.routeSegments.push(segment);
      //
      // } else

      // check if node has any waypoints and create segments between them
      if(Array.isArray(startNode.getTo())) {
        for(var j = 0; j < startNode.getTo().length; ++j) {
          var toNodeId = startNode.getTo()[j];
          endNode = this.routeNodes.get(toNodeId);

          // don't add segment twice if already connected
          if (startNode.hasSegmentWithNodes(endNode, startNode))
            continue;

          segment = new RouteSegment(startNode, endNode);
          startNode.addSegment(segment);
          endNode.addSegment(segment);
          this.routeSegments.push(segment);
        }
      }
    }

    // calculating segments for nodes
    // for(i = 0; i < this.routeNodes.length; ++i) {
    //   for(j = 0; j < this.routeSegments.length; ++j) {
    //     if(this.routeNodes[i] === this.routeSegments[j].getPreviousNode() || this.routeNodes[i] === this.routeSegments[j].getNextNode())
    //       this.routeNodes[i].addSegment(this.routeSegments[j]);
    //   }
    // }

    // var previousSegment = null;
    // for (var i = 0; i < this.map.routes.length; i++) {
    //   for (var j = 0; j < this.map.routes[i].length - 1; j++) {
    //     var startPos = this.map.routes[i][j];
    //     var endPos = this.map.routes[i][j + 1];
    //
    //     var segment = new RouteSegment(startPos, endPos, null, previousSegment);
    //     this.routeSegments.push(segment);
    //     if (previousSegment !== null) {
    //       previousSegment.setNext(segment);
    //     }
    //
    //     previousSegment = segment;
    //
    //   }
    // }
  }

  addLog(position, rotation, type) {
    var log = new Log(position, rotation, type, this.stage);
    this.logs.push(log);
  }

  parseLogs() {
    for (var i = 0; i < this.map.logs.length; ++i) {
      var logData = this.map.logs[i];
      this.addLog({x: logData.x, y: logData.y}, logData.rot, logData.type);
    }
  }

  addDeposit(position, rotation, type) {
    var logDeposit = new LogDeposit(position, rotation, type, this.stage);
    this.logDeposits.push(logDeposit);
  }

  parseLogDeposits() {
    for (var i = 0; i < this.map.logdeposits.length; ++i) {
      var depoData = this.map.logdeposits[i];
      this.addDeposit({x: depoData.x, y: depoData.y}, depoData.rot, depoData.type);
    }
  }

  getRouteSegments() {
    return this.routeSegments;
  }

  getStartingSegment() {
    return this.routeSegments[0];
  }

  getLogs() {
    return this.logs;
  }

  getLogDeposits() {
    return this.logDeposits;
  }

  serialize() {
    var routes = [];
    for (let [id, node] of this.routeNodes) {
      var pos = node.getPos();
      routes.push({route_node: id, x: pos.x, y: pos.y, to: node.to});
    }

    var logs = []
    for (var log of this.logs) {
      var pos = log.getPosition();
      logs.push({x: pos.x, y: pos.y, rot: log.getRotation(), type: log.type});
    }

    var deposits = [];
    for (var deposit of this.logDeposits) {
      var pos = deposit.getPosition();
      deposits.push({x: pos.x, y: pos.y, rot: deposit.getRotation(), type: deposit.type});
    }

    return {
      startpoint: this.getStartingSegment().getPositionAt(0),
      routes: routes,
      logs: logs,
      logdeposits: deposits
    };
  }

  getInfo() {

    var pileTypes = [];
    for (var log of this.logs) {
      for (var pileType of pileTypes) {
        if (pileTypes.type === log.type) {
          pileTypes.amount += 1;
          break;
        }
      }

      pileTypes.push({name: LogType[log.type].name, type: log.type, amount: 1});
    }

    var totalRouteLength = 0;
    for (var segment of this.routeSegments) {
      totalRouteLength += segment.getLength();
    }

    return {
      pileTypes: pileTypes,
      routeLength: Math.round(totalRouteLength),
      storageAreas: this.logDeposits.length,
      passingLimit: false
    };

  }
}
<commit_msg>Resolve unresolved conflicts...<commit_after>import * as PIXI from 'pixi.js';
import RouteNode from './routenode';
import RouteSegment from './routesegment';
import Log from './log';
import LogDeposit from './logdeposit';
import { endpointByStartPointDistanceAndAngle, distance } from './helpers';
import {LogType} from './logtypes'

export default class Level {
  constructor(map) {
    this.map = map;
    this.stage = new PIXI.Container();
    this.routeContainer = new PIXI.Container();
    this.stage.addChild(this.routeContainer);
    this.routeNodes = new Map();
    this.routeSegments = [];
    this.logs = [];
    this.logDeposits = [];
    this.routeTexture = PIXI.Texture.fromImage('/static/road.png');

    if (map) {
      this.parseRouteNodes();
      this.parseLogs();
      this.parseLogDeposits();

      this.generateRouteSegments();
      this.drawRoutes();
    }

  }

  getStage() {
    return this.stage;
  }

  // used by map editor
  getRouteNodes() {
    return this.routeNodes;
  }

  // used by map editor
  getNextRouteNodeId() {
    return this.routeNodes.size + 1;
  }

  drawRoutes() {
    const roadSpriteLength = 50;

    for(var j = 0; j < this.routeSegments.length; ++j) {
      var spos = this.routeSegments[j].startNode.getPos();
      var epos = this.routeSegments[j].endNode.getPos();

      var angle = Math.atan2(epos.y - spos.y, epos.x - spos.x) + Math.PI/2;
      var currentPos = {x: spos.x, y: spos.y};
      var roadSprite;
      var distanceToEnd = 0;
      var tilingSprite = new PIXI.extras.TilingSprite(
        this.routeTexture,
        roadSpriteLength,
        distance(spos, epos)
      );
      tilingSprite.anchor.set(0.5, 0.0);
      tilingSprite.tileScale.set(0.1);
      tilingSprite.rotation = angle + Math.PI;
      tilingSprite.x = currentPos.x;
      tilingSprite.y = currentPos.y;
      this.stage.addChild(tilingSprite);
    }

    for(let [id, routeNode] of this.routeNodes) {
      var intersectionSprite = new PIXI.Sprite.fromImage('./static/road_intersection.png');
      intersectionSprite.anchor.set(0.5, 0.5);
      intersectionSprite.scale.set(0.1);
      intersectionSprite.x = routeNode.getPos().x;
      intersectionSprite.y = routeNode.getPos().y;
      this.stage.addChild(intersectionSprite);
    }
  }

  pastEndPosition(spos, epos, cpos) {
    if ((spos.x < epos.x && cpos.x > epos.x) ||
        (spos.x > epos.x && cpos.x < epos.x) ||
        (spos.y < epos.y && cpos.y > epos.y) ||
        (spos.y > epos.y && cpos.y < epos.y)) {
      return true;
    }
    return false;
  }

  parseRouteNodes() {
    for (var i = 0; i < this.map.routes.length; ++i) {
      var routeNodeData = this.map.routes[i];
      var id = routeNodeData.route_node;
      var pos = {x: routeNodeData.x, y: routeNodeData.y };
      var to = routeNodeData.to;
      this.addRouteNode(id, pos, to);
    }
  }

  addRouteNode(id, pos, to) {
    this.routeNodes.set(id, new RouteNode(id, pos, to));
  }

  // used by map editor
  refreshRoutes() {
    this.routeSegments = [];
    this.routeContainer.removeChildren();

    // reset, mainly to remove segments from them
    for (let [id, node] of this.routeNodes) {
      node.reset(id, node.point, node.to);
    }

    this.generateRouteSegments();
    this.drawRoutes();
  }

  generateRouteSegments() {

    for (let [id, startNode] of this.routeNodes) {
      var endNode = null;
      var segment = null;
      // checking if there is multiple routes from this node
      // if not we just use default settings

      /** REMOVED SUPPORT FOR AUTOMATIC NEXT NODE **/
      /** It was removed because there were some interesting problems with dublicate segments **/
      // if(!startNode.getPos().to && i < this.routeNodes.length-1) {
      //   endNode = this.routeNodes[i+1];
      //   segment = new RouteSegment(startNode, endNode);
      //   this.routeNodes[i].addSegment(segment);
      //   this.routeSegments.push(segment);
      //
      // } else

      // check if node has any waypoints and create segments between them
      if(Array.isArray(startNode.getTo())) {
        for(var j = 0; j < startNode.getTo().length; ++j) {
          var toNodeId = startNode.getTo()[j];
          endNode = this.routeNodes.get(toNodeId);

          // don't add segment twice if already connected
          if (startNode.hasSegmentWithNodes(endNode, startNode))
            continue;

          segment = new RouteSegment(startNode, endNode);
          startNode.addSegment(segment);
          endNode.addSegment(segment);
          this.routeSegments.push(segment);
        }
      }
    }

    // calculating segments for nodes
    // for(i = 0; i < this.routeNodes.length; ++i) {
    //   for(j = 0; j < this.routeSegments.length; ++j) {
    //     if(this.routeNodes[i] === this.routeSegments[j].getPreviousNode() || this.routeNodes[i] === this.routeSegments[j].getNextNode())
    //       this.routeNodes[i].addSegment(this.routeSegments[j]);
    //   }
    // }

    // var previousSegment = null;
    // for (var i = 0; i < this.map.routes.length; i++) {
    //   for (var j = 0; j < this.map.routes[i].length - 1; j++) {
    //     var startPos = this.map.routes[i][j];
    //     var endPos = this.map.routes[i][j + 1];
    //
    //     var segment = new RouteSegment(startPos, endPos, null, previousSegment);
    //     this.routeSegments.push(segment);
    //     if (previousSegment !== null) {
    //       previousSegment.setNext(segment);
    //     }
    //
    //     previousSegment = segment;
    //
    //   }
    // }
  }

  addLog(position, rotation, type) {
    var log = new Log(position, rotation, type, this.stage);
    this.logs.push(log);
  }

  parseLogs() {
    for (var i = 0; i < this.map.logs.length; ++i) {
      var logData = this.map.logs[i];
      this.addLog({x: logData.x, y: logData.y}, logData.rot, logData.type);
    }
  }

  addDeposit(position, rotation, type) {
    var logDeposit = new LogDeposit(position, rotation, type, this.stage);
    this.logDeposits.push(logDeposit);
  }

  parseLogDeposits() {
    for (var i = 0; i < this.map.logdeposits.length; ++i) {
      var depoData = this.map.logdeposits[i];
      this.addDeposit({x: depoData.x, y: depoData.y}, depoData.rot, depoData.type);
    }
  }

  getRouteSegments() {
    return this.routeSegments;
  }

  getStartingSegment() {
    return this.routeSegments[0];
  }

  getLogs() {
    return this.logs;
  }

  getLogDeposits() {
    return this.logDeposits;
  }

  serialize() {
    var routes = [];
    for (let [id, node] of this.routeNodes) {
      var pos = node.getPos();
      routes.push({route_node: id, x: pos.x, y: pos.y, to: node.to});
    }

    var logs = []
    for (var log of this.logs) {
      var pos = log.getPosition();
      logs.push({x: pos.x, y: pos.y, rot: log.getRotation(), type: log.type});
    }

    var deposits = [];
    for (var deposit of this.logDeposits) {
      var pos = deposit.getPosition();
      deposits.push({x: pos.x, y: pos.y, rot: deposit.getRotation(), type: deposit.type});
    }

    return {
      startpoint: this.getStartingSegment().getPositionAt(0),
      routes: routes,
      logs: logs,
      logdeposits: deposits
    };
  }

  getInfo() {

    var pileTypes = [];
    for (var log of this.logs) {
      for (var pileType of pileTypes) {
        if (pileTypes.type === log.type) {
          pileTypes.amount += 1;
          break;
        }
      }

      pileTypes.push({name: LogType[log.type].name, type: log.type, amount: 1});
    }

    var totalRouteLength = 0;
    for (var segment of this.routeSegments) {
      totalRouteLength += segment.getLength();
    }

    return {
      pileTypes: pileTypes,
      routeLength: Math.round(totalRouteLength),
      storageAreas: this.logDeposits.length,
      passingLimit: false
    };

  }
}
<|endoftext|>


<commit_before>/**
 * Twitcher v0.0.1
 *
 * Copyright (c) 2009 Mark Wunsch
 * Licensed under the MIT License.
 * http://creativecommons.org/licenses/MIT/
**/

;(function(){
  var window = this;
  var Twitcher = function(query, parameters) {
    this.init(query, parameters);
  };

  Twitcher.VERSION = function(){
    return "0.0.1";
  };

  Twitcher.URL = function(){
    return "http://search.twitter.com/search.json";
  };

  Twitcher.Extensions = {
    jsonp: function(url, callback, callback_name) {
      var head = document.getElementsByTagName("head")[0];
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = url;

      window[callback_name] = function(data) {
        callback(data);
        window[callback_name] = undefined;
        try{ delete window[callback_name]; } catch(e){}
        head.removeChild(script);
      };

      head.appendChild(script);
    },

    extend: function(target, object) {
      for (var i in object) {
        target[i] = object[i];
      }
    }
  };

  Twitcher.prototype = {
    init: function(query, params) {
      var self = this;

      self.setup.query_string = query || "";
      self.url = self.compose_url();
      if (query) {
        self.load(function(data){
          console.log(data);
        });
      }

      return self;
    },

    compose_url: function(query){
      query = query || this.setup.query_string
      return Twitcher.URL() + "?" + "q=" + encodeURIComponent(query);
    },

    setup: {
      query_string: "",
      parameters: {
        "lang": "",
        "locale": "",
        "rpp": "",
        "page": "",
        "since_id": "",
        "geocode": "",
        "show_user": ""
      },

      callback: "twitcher_load",
    },

    successful: false,

    complete: false,

    response: null,

    tweets: function(lambda) {
      if (this.response) {
        var tweets = this.response.results;
        if (tweets) {
          if (!lambda) {
            return tweets;
          } else {
            for (i=0; i < tweets.length; i += 1) {
              lambda(tweets[i]);
            }
          }
        } else {
          return null;
        }
      } else {
        return null;
      }
    },

    count: function(){
      var tweets = this.tweets();
      if (tweets) {
        return this.tweets().length;
      } else {
        return null;
      }
    },

    each_tweet: function(lambda){
      this.tweets(lambda);
    },

    load: function(lambda) {
      var ext = Twitcher.Extensions;
      var caller = this;
      var nonce = Date.now();
      var url = caller.url;
      var callback = caller.setup.callback + "_" + nonce;

      var func = function(data) {
        if (lambda) {
         lambda(data);
        }
        caller.response = data;
        caller.complete = true;
        if (!data.error) {
          caller.successful = true;
        }
      };

      url += "&callback=" + callback;
      ext.jsonp(url, func, callback);
    }
  };

  window.Twitcher = function(query, parameters) {
    return new Twitcher(query,parameters);
  };
  Twitcher.Extensions.extend(window.Twitcher, Twitcher);

})();
<commit_msg>setting up params<commit_after>/**
 * Twitcher v0.0.1
 *
 * Copyright (c) 2009 Mark Wunsch
 * Licensed under the MIT License.
 * http://creativecommons.org/licenses/MIT/
**/

;(function(){
  var window = this;
  var Twitcher = function(query, parameters) {
    this.init(query, parameters);
  };

  Twitcher.VERSION = function(){
    return "0.0.1";
  };

  Twitcher.URL = function(){
    return "http://search.twitter.com/search.json";
  };

  Twitcher.Extensions = {
    jsonp: function(url, callback, callback_name) {
      var head = document.getElementsByTagName("head")[0];
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = url;

      window[callback_name] = function(data) {
        callback(data);
        window[callback_name] = undefined;
        try{ delete window[callback_name]; } catch(e){}
        head.removeChild(script);
      };

      head.appendChild(script);
    },

    extend: function(target, object) {
      for (var i in object) {
        target[i] = object[i];
      }
    }
  };

  Twitcher.prototype = {
    init: function(query, params) {
      var self = this;

      self.setup.query_string = query || "";
      self.setup.parameters = self.build_params(params);
      self.url = self.compose_url();

      if (query) {
        self.load(function(data){
          console.log(data);
        });
      }

      return self;
    },

    build_params: function(params){
      var setup = this.setup.parameters;
      var new_params = {};

      if (!params) {
        return new_params;
      }

      for (name in params) {
        if (setup[name]) {
          new_params[name] = params[name] + '';
        }
      }

      return new_params;
    },

    compose_url: function(query, params){
      query = query || this.setup.query_string;

      return Twitcher.URL() + "?" + "q=" + encodeURIComponent(query);
    },

    setup: {
      query_string: "",
      parameters: {
        "lang": true,
        "locale": true,
        "rpp": true,
        "page": true,
        "since_id": true,
        "geocode": true,
        "show_user": true
      },

      callback: "twitcher_load",
    },

    successful: false,

    complete: false,

    response: null,

    tweets: function(lambda) {
      if (this.response) {
        var tweets = this.response.results;
        if (tweets) {
          if (!lambda) {
            return tweets;
          } else {
            for (i=0; i < tweets.length; i += 1) {
              lambda(tweets[i]);
            }
          }
        } else {
          return null;
        }
      } else {
        return null;
      }
    },

    count: function(){
      var tweets = this.tweets();
      if (tweets) {
        return this.tweets().length;
      } else {
        return null;
      }
    },

    each_tweet: function(lambda){
      this.tweets(lambda);
    },

    load: function(lambda) {
      var ext = Twitcher.Extensions;
      var caller = this;
      var nonce = Date.now();
      var url = caller.url;
      var callback = caller.setup.callback + "_" + nonce;

      var func = function(data) {
        if (lambda) {
         lambda(data);
        }
        caller.response = data;
        caller.complete = true;
        if (!data.error) {
          caller.successful = true;
        }
      };

      url += "&callback=" + callback;
      ext.jsonp(url, func, callback);
    }
  };

  window.Twitcher = function(query, parameters) {
    return new Twitcher(query,parameters);
  };
  Twitcher.Extensions.extend(window.Twitcher, Twitcher);

})();
<|endoftext|>


<commit_before>'use strict';

//Native modules
import fs from 'fs';
import path from 'path';

//Vendor modules
import normalizePath from 'normalize-path';
import recursive from 'tail-call/core';
import {
  existsAsync,
  mkdirAsync,
  writeFileAsync,
  removeAsync
} from 'fs-extra-promise';

//Source modules
import Validations from './lines-validations';

const validator = new Validations();
const tailCall = recursive.recur;

let structureCreation = {
  generated: 0,
  notGenerated: 0
};

const logNonGenerated = tailCall((lineInfo) => {

  if (lineInfo.children.length > 0) {
    lineInfo.children.forEach((line) => {
      if (line.inferType === 'file') {
        structureCreation.notGenerated = structureCreation.notGenerated + 1;
      } else {
        logNonGenerated(line);
      }
    });
  } else {
    structureCreation.notGenerated = structureCreation.notGenerated + 1;
  }
});

//Convert createStructure into a tail recursive function
let createStructureTC = null;
const createStructure = (lineInfo, rootPath,
  contentLineCount, resolve) => {
  console.log("\n\n----");
  console.log("lineInfo.structureName", lineInfo.structureName);
  console.log("lineInfo.isTopLine", lineInfo.isTopLine);

  let {
    structureName,
    inferType,
    nameDetails,
    isTopLine,
    childRepeatedLine
  } = lineInfo;

  let name = nameDetails.sanitizedName ||
    structureName,
    structureRoughPath = path.join(rootPath, name),
    structureCreatePath = normalizePath(structureRoughPath);

  if (inferType === 'file') {

    console.log("inferType", inferType);
    console.log("childRepeatedLine", childRepeatedLine);

    if (!childRepeatedLine) {
      structureCreation.generated = structureCreation.generated + 1;
      console.log("file structureCreation", structureCreation);
      //Create the file type
      (async function () {
        await writeFileAsync(structureCreatePath);
      })();

    }

  } else {
    let parentPath = path.join(rootPath, (nameDetails.sanitizedName || structureName));

    console.log("folder parentPath", parentPath);

    (async function () {
      await mkdirAsync(parentPath);
    })();

    structureCreation.generated = structureCreation.generated + 1;

    console.log("structureCreation after wait folder gen", structureCreation);
    console.log("--------------------------\n\n");

    if (lineInfo.children.length > 0) {
      lineInfo.children.forEach((line) => {

        console.log("line name", line.structureName);
        console.log("right after structureCreation.notGenerated", structureCreation.notGenerated);
        // console.log("line", line);
        console.log("line.isTopLine", line.isTopLine);

        //&&  !isTopLine
        if (typeof childRepeatedLine === 'undefined') {
          createStructureTC(line, parentPath,
            contentLineCount, resolve);
        } else {
          // structureCreation.notGenerated = structureCreation.notGenerated + 1;
          console.log("folder structureCreation", structureCreation);
          logNonGenerated(line);
        }

      });
    }
  }

  if (structureCreation.generated + structureCreation.notGenerated
=== contentLineCount) {
    console.log("resolved");
    resolve();
  }

};

createStructureTC = tailCall(createStructure);

export default (linesInfo, rootPath) => {

  //The total number of lines that are possible to generate
  let contentLineCount = linesInfo.contentLineCount;

  let structureGenerating = new Promise((resolve, reject) => {

    //Take the outer-most level of elements which
    //serves as the initial generation set
    console.log("``````````````contentLineCount", contentLineCount);
    for (let i = 0; i < contentLineCount; i++) {
      if (typeof linesInfo.topLevel[i].repeatedLine === 'undefined') {
        let topLevelLine = linesInfo.topLevel[i];
        createStructureTC(topLevelLine, rootPath,
          contentLineCount, resolve);
      } else {
        logNonGenerated(line);
        console.log("last non-gen structureCreation", structureCreation);
      }

    }
  });

  return structureGenerating;
};
<commit_msg>Proper tracking of non-consecutive top level structure repeats<commit_after>'use strict';

//Native modules
import fs from 'fs';
import path from 'path';

//Vendor modules
import normalizePath from 'normalize-path';
import recursive from 'tail-call/core';
import {
  existsAsync,
  mkdirAsync,
  writeFileAsync,
  removeAsync
} from 'fs-extra-promise';

//Source modules
import Validations from './lines-validations';

const validator = new Validations();
const tailCall = recursive.recur;

let structureCreation = {
  generated: 0,
  notGenerated: 0
};

const logNonGenerated = tailCall((lineInfo, structureCreation) => {
  console.log("structureCreation", structureCreation);
  structureCreation.notGenerated = structureCreation.notGenerated + 1;
  console.log(">>>>>>>>>>>in logNonGenerated");
  //
  // if (lineInfo.children.length > 0) {
  //   lineInfo.children.forEach((line) => {
  //     if (line.inferType === 'file') {
  //       structureCreation.notGenerated = structureCreation.notGenerated + 1;
  //     } else {
  //       logNonGenerated(line);
  //     }
  //   });
  // } else {
  //   structureCreation.notGenerated = structureCreation.notGenerated + 1;
  // }
});

//Convert createStructure into a tail recursive function
let createStructureTC = null;
const createStructure = (lineInfo, rootPath,
  contentLineCount, resolve) => {
  console.log("\n\n----");
  console.log("lineInfo.structureName", lineInfo.structureName);
  console.log("lineInfo.isTopLine", lineInfo.isTopLine);

  let {
    structureName,
    inferType,
    nameDetails,
    isTopLine,
    childRepeatedLine
  } = lineInfo;

  let name = nameDetails.sanitizedName ||
    structureName,
    structureRoughPath = path.join(rootPath, name),
    structureCreatePath = normalizePath(structureRoughPath);

  if (inferType === 'file') {

    console.log("inferType", inferType);
    console.log("childRepeatedLine", childRepeatedLine);

    if (!childRepeatedLine) {
      structureCreation.generated = structureCreation.generated + 1;
      console.log("file structureCreation", structureCreation);
      //Create the file type
      (async function () {
        await writeFileAsync(structureCreatePath);
      })();

    } else {
      logNonGenerated(lineInfo, structureCreation);
    }

  } else {

    //TODO: check for childRepeatedLine before actual folder generation
    console.log("//////////folder childRepeatedLine", childRepeatedLine);
    let parentPath = path.join(rootPath, (nameDetails.sanitizedName || structureName));

    console.log("folder parentPath", parentPath);

    //Only generate folder if it is not a repeat
    if (!childRepeatedLine) {
      (async function () {
        await mkdirAsync(parentPath);
      })();

      structureCreation.generated = structureCreation.generated + 1;
    } else {
      logNonGenerated(lineInfo, structureCreation);
    }

    console.log("structureCreation after wait folder gen", structureCreation);
    console.log("--------------------------\n\n");

    if (lineInfo.children.length > 0) {
      lineInfo.children.forEach((line) => {

        console.log("line name", line.structureName);
        console.log("right after structureCreation.notGenerated", structureCreation.notGenerated);
        // console.log("line", line);
        console.log("line.isTopLine", line.isTopLine);
        console.log("lineInfo.nameDetails.line", lineInfo.nameDetails.line);

        //&&  !isTopLine
        if (typeof lineInfo.childRepeatedLine === 'undefined') {
          createStructureTC(line, parentPath,
            contentLineCount, resolve);
        } else {
          // structureCreation.notGenerated = structureCreation.notGenerated + 1;
          console.log("+++++++++++++++++++++++folder structureCreation", structureCreation);
          logNonGenerated(line, structureCreation);
        }

      });
    }
  }

  if (structureCreation.generated + structureCreation.notGenerated
=== contentLineCount) {
    console.log("resolved");
    resolve();
  }

};

createStructureTC = tailCall(createStructure);

export default (linesInfo, rootPath) => {

  //The total number of lines that are possible to generate
  let contentLineCount = linesInfo.contentLineCount;

  let structureGenerating = new Promise((resolve, reject) => {

    //Take the outer-most level of elements which
    //serves as the initial generation set
    console.log("``````````````contentLineCount", contentLineCount);
    for (let i = 0; i < contentLineCount; i++) {
      console.log("linesInfo.topLevel[i].structureName", linesInfo.topLevel[i].structureName);
      if (typeof linesInfo.topLevel[i].repeatedLine === 'undefined') {
        let topLevelLine = linesInfo.topLevel[i];
        createStructureTC(topLevelLine, rootPath,
          contentLineCount, resolve);
      } else {

        console.log("last non-gen structureCreation", structureCreation);
        logNonGenerated(line, structureCreation);
      }

    }
  });

  return structureGenerating;
};
<|endoftext|>


<commit_before>var Vue = require('vue')
var VueRouter = require('vue-router')

Vue.use(VueRouter)
Vue.use(require('bootstrap-vue'))

Vue.component('fragment-navbar', require('./fragments/navbar.vue'))
Vue.component('fragment-nsi-services', require('./fragments/nsi-services.vue'))
Vue.component('fragment-service', require('./fragments/service.vue'))

var router = new VueRouter({
  routes: require('./routes')
})

var layout = require('./layout.vue')

layout.router = router

var ui = new Vue(layout)

module.exports = ui
<commit_msg>fix build<commit_after>var Vue = require('vue')
var VueRouter = require('vue-router')

Vue.use(VueRouter)
Vue.use(require('bootstrap-vue'))

Vue.component('fragment-navbar', require('./fragments/navbar.vue'))
Vue.component('fragment-service', require('./fragments/service.vue'))

var router = new VueRouter({
  routes: require('./routes')
})

var layout = require('./layout.vue')

layout.router = router

var ui = new Vue(layout)

module.exports = ui
<|endoftext|>


<commit_before>"use strict";

var CSLEDIT = CSLEDIT || {};

CSLEDIT.uiConfig = {};

// if creating an empty node, populate with these attributes
CSLEDIT.uiConfig.defaultAttributes = {
	"text" : {
		"value" : ""
	},
	"if" : {
		"type" : "article",
		"match" : "any"
	},
	"else-if" : {
		"type" : "article",
		"match" : "any"
	},
	"date" : {
		"form" : "text",
		"date-parts" : "year-month-day",
		"variable" : "issued"
	},
	"date-part" : {
		"name" : "year"
	}
};

CSLEDIT.uiConfig.attributeGroups = {
	"Text formatting" : [
		"fontFormattingControls",
		"display",
		"text-case"
	],
	"Affixes" : [
		"prefix",
		"suffix",
		"delimiter"
	]
};

CSLEDIT.uiConfig.fieldOrder = [
	"type",
	"title",
	"author",
	"editor",
	"translator",
	"issued",
	"container-title",
	"volume",
	"issue",
	"chapter",
	"page",
	"publisher"
];

// for jstree
CSLEDIT.uiConfig.nodeIcons = {
	"default" : "/external/famfamfam-icons/bullet_black.png",
	"text" : "/external/famfamfam-icons/style.png",
	"macro" : "/external/famfamfam-icons/brick.png",
	"info" : "/external/famfamfam-icons/information.png",
	"choose" : "/external/fugue-icons/question-white.png",
	"date" : "/external/famfamfam-icons/date.png",
	"style" : "/external/famfamfam-icons/cog.png",
	"citation" : "/external/famfamfam-icons/page_white_edit.png",
	"bibliography" : "/external/famfamfam-icons/text_list_numbers.png",
	"sort" : "/external/fugue-icons/sort-alphabet.png",
	"number" : "/external/fugue-icons/edit-number.png",
	"layout" : "/external/famfamfam-icons/page_white_stack.png",
	"group" : "/external/famfamfam-icons/page_white_stack.png"
};

CSLEDIT.uiConfig.capitaliseFirstLetter = function (string) {
	return string.charAt(0).toUpperCase() + string.slice(1);
};

CSLEDIT.uiConfig.displayNameFromNode = function (node) {
	if (node.name in CSLEDIT.uiConfig.displayNames) {
		return CSLEDIT.uiConfig.displayNames[node.name](node);
	}

	// fall back to using the node name
	return CSLEDIT.uiConfig.capitaliseFirstLetter(node.name);
};

// generates display names for 'if' and 'else-if' tree view nodes
//   e.g. If article OR book
CSLEDIT.uiConfig.conditionalDisplayName = function (node) {
	var displayName = "",
		elideLimit = 30,
		match,
		terms = [],
		join = "";

	match = CSLEDIT.schema.attributes("choose/if").match.defaultValue;
	if (match === "") {
		match = "all"; // becuase it's not specified in MLZ schema, TODO: ask Frank
	}

	$.each(node.attributes, function (i, attribute) {
		if (attribute.enabled) {
			if (attribute.key === "match") {
				match = attribute.value;
			} else {
				$.each(attribute.value.split(" "), function (i, val) {
					terms.push(val);
				});
			}
		}
	});

	if (node.name === "if") {
		displayName = "If ";
	} else {
		displayName = "Else-If ";
	}

	if (match === "any") {
		displayName += terms.join(" OR ");
	} else if (match === "all") {
		displayName += terms.join(" AND ");
	} else if (match === "none") {
		displayName += "NOT (" + terms.join(" OR ") + ")";
	} else {
		assert(false);
	}

	if (displayName.length > elideLimit) {
		displayName = displayName.substr(0, elideLimit - 3) + "...";
	}

	return displayName;
};

CSLEDIT.uiConfig.displayNames = {
		"macro" : function (node) {
			return "Macro: " + new CSLEDIT.CslNode(node).getAttr("name");
		},
		"text" : function (node) {
			var cslNode = new CSLEDIT.CslNode(node),
				macro = cslNode.getAttr("macro"),
				term = cslNode.getAttr("term"),
				value = cslNode.getAttr("value"),
				variable = cslNode.getAttr("variable");

			if (macro !== "") {
				return  macro + " (macro)";
			} else if (term !== "") {
				return term + " (term)";
			} else if (value !== "") {
				return value + " (value)";
			} else if (variable !== "") {
				return variable + " (variable)";
			}
			return "Text";
		},
		"label" : function (node) {
			var variable = new CSLEDIT.CslNode(node).getAttr("variable"),
				displayName = "Label";

			if (variable !== "") {
				displayName = variable + " (Label)";
			}
			return displayName;
		},
		"number" : function (node) {
			var variable = new CSLEDIT.CslNode(node).getAttr("variable");

			if (variable !== "") {
				return variable;
			}
			return "Number";
		},
		"if" : CSLEDIT.uiConfig.conditionalDisplayName,
		"else-if" : CSLEDIT.uiConfig.conditionalDisplayName,
		"citation" : function () {
			return "Inline Citations";
		},
		"bibliography" : function () {
			return "Bibliography";
		},
		"choose" : function () {
			return "Conditional";
		},
		"style" : function () {
			return "Global Formatting Options";
		}
	};
<commit_msg>change 'label' to lower case for consistency with 'variable'<commit_after>"use strict";

var CSLEDIT = CSLEDIT || {};

CSLEDIT.uiConfig = {};

// if creating an empty node, populate with these attributes
CSLEDIT.uiConfig.defaultAttributes = {
	"text" : {
		"value" : ""
	},
	"if" : {
		"type" : "article",
		"match" : "any"
	},
	"else-if" : {
		"type" : "article",
		"match" : "any"
	},
	"date" : {
		"form" : "text",
		"date-parts" : "year-month-day",
		"variable" : "issued"
	},
	"date-part" : {
		"name" : "year"
	}
};

CSLEDIT.uiConfig.attributeGroups = {
	"Text formatting" : [
		"fontFormattingControls",
		"display",
		"text-case"
	],
	"Affixes" : [
		"prefix",
		"suffix",
		"delimiter"
	]
};

CSLEDIT.uiConfig.fieldOrder = [
	"type",
	"title",
	"author",
	"editor",
	"translator",
	"issued",
	"container-title",
	"volume",
	"issue",
	"chapter",
	"page",
	"publisher"
];

// for jstree
CSLEDIT.uiConfig.nodeIcons = {
	"default" : "/external/famfamfam-icons/bullet_black.png",
	"text" : "/external/famfamfam-icons/style.png",
	"macro" : "/external/famfamfam-icons/brick.png",
	"info" : "/external/famfamfam-icons/information.png",
	"choose" : "/external/fugue-icons/question-white.png",
	"date" : "/external/famfamfam-icons/date.png",
	"style" : "/external/famfamfam-icons/cog.png",
	"citation" : "/external/famfamfam-icons/page_white_edit.png",
	"bibliography" : "/external/famfamfam-icons/text_list_numbers.png",
	"sort" : "/external/fugue-icons/sort-alphabet.png",
	"number" : "/external/fugue-icons/edit-number.png",
	"layout" : "/external/famfamfam-icons/page_white_stack.png",
	"group" : "/external/famfamfam-icons/page_white_stack.png"
};

CSLEDIT.uiConfig.capitaliseFirstLetter = function (string) {
	return string.charAt(0).toUpperCase() + string.slice(1);
};

CSLEDIT.uiConfig.displayNameFromNode = function (node) {
	if (node.name in CSLEDIT.uiConfig.displayNames) {
		return CSLEDIT.uiConfig.displayNames[node.name](node);
	}

	// fall back to using the node name
	return CSLEDIT.uiConfig.capitaliseFirstLetter(node.name);
};

// generates display names for 'if' and 'else-if' tree view nodes
//   e.g. If article OR book
CSLEDIT.uiConfig.conditionalDisplayName = function (node) {
	var displayName = "",
		elideLimit = 30,
		match,
		terms = [],
		join = "";

	match = CSLEDIT.schema.attributes("choose/if").match.defaultValue;
	if (match === "") {
		match = "all"; // becuase it's not specified in MLZ schema, TODO: ask Frank
	}

	$.each(node.attributes, function (i, attribute) {
		if (attribute.enabled) {
			if (attribute.key === "match") {
				match = attribute.value;
			} else {
				$.each(attribute.value.split(" "), function (i, val) {
					terms.push(val);
				});
			}
		}
	});

	if (node.name === "if") {
		displayName = "If ";
	} else {
		displayName = "Else-If ";
	}

	if (match === "any") {
		displayName += terms.join(" OR ");
	} else if (match === "all") {
		displayName += terms.join(" AND ");
	} else if (match === "none") {
		displayName += "NOT (" + terms.join(" OR ") + ")";
	} else {
		assert(false);
	}

	if (displayName.length > elideLimit) {
		displayName = displayName.substr(0, elideLimit - 3) + "...";
	}

	return displayName;
};

CSLEDIT.uiConfig.displayNames = {
		"macro" : function (node) {
			return "Macro: " + new CSLEDIT.CslNode(node).getAttr("name");
		},
		"text" : function (node) {
			var cslNode = new CSLEDIT.CslNode(node),
				macro = cslNode.getAttr("macro"),
				term = cslNode.getAttr("term"),
				value = cslNode.getAttr("value"),
				variable = cslNode.getAttr("variable");

			if (macro !== "") {
				return  macro + " (macro)";
			} else if (term !== "") {
				return term + " (term)";
			} else if (value !== "") {
				return value + " (value)";
			} else if (variable !== "") {
				return variable + " (variable)";
			}
			return "Text";
		},
		"label" : function (node) {
			var variable = new CSLEDIT.CslNode(node).getAttr("variable"),
				displayName = "Label";

			if (variable !== "") {
				displayName = variable + " (label)";
			}
			return displayName;
		},
		"number" : function (node) {
			var variable = new CSLEDIT.CslNode(node).getAttr("variable");

			if (variable !== "") {
				return variable;
			}
			return "Number";
		},
		"if" : CSLEDIT.uiConfig.conditionalDisplayName,
		"else-if" : CSLEDIT.uiConfig.conditionalDisplayName,
		"citation" : function () {
			return "Inline Citations";
		},
		"bibliography" : function () {
			return "Bibliography";
		},
		"choose" : function () {
			return "Conditional";
		},
		"style" : function () {
			return "Global Formatting Options";
		}
	};
<|endoftext|>


<commit_before>/*
 * Author: Remy Alain Ticona Carbajal http://realtica.org
 * Description: The main objective of ng-uploader is to have a user control,
 * clean, simple, customizable, and above all very easy to implement.
 * Licence: MIT
 */

angular.module('ui.uploader', []).service('uiUploader', uiUploader);

uiUploader.$inject = ['$log'];

function uiUploader($log) {

    /*jshint validthis: true */
    var self = this;
    self.files = [];
    self.options = {};
    self.activeUploads = 0;
    self.uploadedFiles = 0;
    $log.info('uiUploader loaded');

    function addFiles(files) {
        for (var i = 0; i < files.length; i++) {
            self.files.push(files[i]);
        }
    }

    function getFiles() {
        return self.files;
    }

    function startUpload(options) {
        self.options = options;
        for (var i = 0; i < self.files.length; i++) {
            if (self.activeUploads == self.options.concurrency) {
                break;
            }
            if (self.files[i].active)
                continue;
            ajaxUpload(self.files[i], self.options.url, self.options.data);
        }
    }

    function removeFile(file) {
        self.files.splice(self.files.indexOf(file), 1);
    }

    function removeAll() {
        self.files.splice(0, self.files.length);
    }

    return {
        addFiles: addFiles,
        getFiles: getFiles,
        files: self.files,
        startUpload: startUpload,
        removeFile: removeFile,
        removeAll: removeAll
    };

    function getHumanSize(bytes) {
        var sizes = ['n/a', 'bytes', 'KiB', 'MiB', 'GiB', 'TB', 'PB', 'EiB', 'ZiB', 'YiB'];
        var i = (bytes === 0) ? 0 : +Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, i)).toFixed(i ? 1 : 0) + ' ' + sizes[isNaN(bytes) ? 0 : i + 1];
    }

    function isFunction(entity) {
        return typeof(entity) === typeof(Function);
    }

    function ajaxUpload(file, url, data) {
        var xhr, formData, prop, key = '' || 'file';
        data = data || {};

        self.activeUploads += 1;
        file.active = true;
        xhr = new window.XMLHttpRequest();

        // To account for sites that may require CORS
        if (data.withCredentials === true) {
            xhr.withCredentials = true;
        }

        formData = new window.FormData();
        xhr.open('POST', url);

        // Triggered when upload starts:
        xhr.upload.onloadstart = function() {
        };

        // Triggered many times during upload:
        xhr.upload.onprogress = function(event) {
            if (!event.lengthComputable) {
                return;
            }
            // Update file size because it might be bigger than reported by
            // the fileSize:
            //$log.info("progres..");
            //console.info(event.loaded);
            file.loaded = event.loaded;
            file.humanSize = getHumanSize(event.loaded);
            if (isFunction(self.options.onProgress)) {
                self.options.onProgress(file);
            }
        };

        // Triggered when upload is completed:
        xhr.onload = function() {
            self.activeUploads -= 1;
            self.uploadedFiles += 1;
            startUpload(self.options);
            if (isFunction(self.options.onCompleted)) {
                self.options.onCompleted(file, xhr.responseText, xhr.status);
            }
            if (self.uploadedFiles === self.files.length) {
                self.uploadedFiles = 0;
                if (isFunction(self.options.onCompletedAll)) {
                    self.options.onCompletedAll(self.files);
                }
            }
        };

        // Triggered when upload fails:
        xhr.onerror = function(e) {
            if (isFunction(self.options.onError)) {
                self.options.onError(e);
            }
        };

        // Append additional data if provided:
        if (data) {
            for (prop in data) {
                if (data.hasOwnProperty(prop)) {
                    formData.append(prop, data[prop]);
                }
            }
        }

        // Append file data:
        formData.append(key, file, file.name);

        // Initiate upload:
        xhr.send(formData);

        return xhr;
    }

}
<commit_msg>simplify value initialization; fixes #4<commit_after>/*
 * Author: Remy Alain Ticona Carbajal http://realtica.org
 * Description: The main objective of ng-uploader is to have a user control,
 * clean, simple, customizable, and above all very easy to implement.
 * Licence: MIT
 */

angular.module('ui.uploader', []).service('uiUploader', uiUploader);

uiUploader.$inject = ['$log'];

function uiUploader($log) {

    /*jshint validthis: true */
    var self = this;
    self.files = [];
    self.options = {};
    self.activeUploads = 0;
    self.uploadedFiles = 0;
    $log.info('uiUploader loaded');

    function addFiles(files) {
        for (var i = 0; i < files.length; i++) {
            self.files.push(files[i]);
        }
    }

    function getFiles() {
        return self.files;
    }

    function startUpload(options) {
        self.options = options;
        for (var i = 0; i < self.files.length; i++) {
            if (self.activeUploads == self.options.concurrency) {
                break;
            }
            if (self.files[i].active)
                continue;
            ajaxUpload(self.files[i], self.options.url, self.options.data);
        }
    }

    function removeFile(file) {
        self.files.splice(self.files.indexOf(file), 1);
    }

    function removeAll() {
        self.files.splice(0, self.files.length);
    }

    return {
        addFiles: addFiles,
        getFiles: getFiles,
        files: self.files,
        startUpload: startUpload,
        removeFile: removeFile,
        removeAll: removeAll
    };

    function getHumanSize(bytes) {
        var sizes = ['n/a', 'bytes', 'KiB', 'MiB', 'GiB', 'TB', 'PB', 'EiB', 'ZiB', 'YiB'];
        var i = (bytes === 0) ? 0 : +Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, i)).toFixed(i ? 1 : 0) + ' ' + sizes[isNaN(bytes) ? 0 : i + 1];
    }

    function isFunction(entity) {
        return typeof(entity) === typeof(Function);
    }

    function ajaxUpload(file, url, data) {
        var xhr, formData, prop, key = 'file';
        data = data || {};

        self.activeUploads += 1;
        file.active = true;
        xhr = new window.XMLHttpRequest();

        // To account for sites that may require CORS
        if (data.withCredentials === true) {
            xhr.withCredentials = true;
        }

        formData = new window.FormData();
        xhr.open('POST', url);

        // Triggered when upload starts:
        xhr.upload.onloadstart = function() {
        };

        // Triggered many times during upload:
        xhr.upload.onprogress = function(event) {
            if (!event.lengthComputable) {
                return;
            }
            // Update file size because it might be bigger than reported by
            // the fileSize:
            //$log.info("progres..");
            //console.info(event.loaded);
            file.loaded = event.loaded;
            file.humanSize = getHumanSize(event.loaded);
            if (isFunction(self.options.onProgress)) {
                self.options.onProgress(file);
            }
        };

        // Triggered when upload is completed:
        xhr.onload = function() {
            self.activeUploads -= 1;
            self.uploadedFiles += 1;
            startUpload(self.options);
            if (isFunction(self.options.onCompleted)) {
                self.options.onCompleted(file, xhr.responseText, xhr.status);
            }
            if (self.uploadedFiles === self.files.length) {
                self.uploadedFiles = 0;
                if (isFunction(self.options.onCompletedAll)) {
                    self.options.onCompletedAll(self.files);
                }
            }
        };

        // Triggered when upload fails:
        xhr.onerror = function(e) {
            if (isFunction(self.options.onError)) {
                self.options.onError(e);
            }
        };

        // Append additional data if provided:
        if (data) {
            for (prop in data) {
                if (data.hasOwnProperty(prop)) {
                    formData.append(prop, data[prop]);
                }
            }
        }

        // Append file data:
        formData.append(key, file, file.name);

        // Initiate upload:
        xhr.send(formData);

        return xhr;
    }

}
<|endoftext|>