<commit_before>// ==UserScript==
// @name          Inline accessible wikipedia math
// @namespace     http://www.talkingcatsoftware.com/gmscripts
// @description   Makes math authored with the "math" template accessible by adding a MathML equivalent to the template output
// @include       https://*.wikipedia.org/*
// @require       https://raw.githubusercontent.com/slevithan/xregexp/master/xregexp-all.js
// @version       0.1.0
// @icon         http://www.example.net/icon.png
// ==/UserScript==

NodeList.prototype.toArray = function () {
    return Array.prototype.slice.call(this);
}

///// [Data Structures]

function Node(_type, _value, _children) {
    this.type = _type || "";
    this.value = _value || "";
    this.children = _children || [];
}

Node.prototype.stringify = function (level) {
    level = level || 0;
    return "  ".repeat(level) + this.type + ":" + this.value + "\n" + this.children.map(function (child) {
        return child.stringify(level + 1);
    }).reduce(function (string, sum) {
        return string + sum;
    }, "");
};

///// [End Data Structures]

///// [Templates]

function GetTreeFromElement(element) {
    if (CheckSqrtTemplate(element))
        return GetTreeFromSqrtElement(element);
    if (CheckRadicTemplate(element))
        return GetTreeFromRadicElement(element);
    if (CheckFractionTemplate(element))
        return GetTreeFromFractionTemplate(element);
    if (CheckIntegralTemplate(element))
        return GetTreeFromIntegralTemplate(element);
    if (CheckSubTemplate(element))
        return GetTreeFromSubTemplate(element);
    if (CheckSupTemplate(element))
        return GetTreeFromSupTemplate(element);

    if (element.childNodes.length > 0) {
        return CreateRowNode(element);
    }

    // Parse text
    var re = XRegExp("\\s*([0-9]+|\\pL+|[^\\s])\\s*");
    var tokens = [];
    var m;
    var pos = 0;
    while (m = XRegExp.exec(element.textContent, re, pos, "sticky")) {
        tokens.push(m[1]);
        pos = m.index + m[0].length;
    }

    if (tokens.length === 1) {
        return new Node("text", tokens[0]);
    } else {
        return new Node("row", "", tokens.map(function (token) {
            return new Node("text", token);
        }));
    }
}

function CheckSqrtTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "nowrap"
            && element.childNodes.length === 2
            && element.childNodes[0].nodeName === "#text"
            && element.childNodes[0].data === "√";
}

function CheckRadicTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "nowrap"
            && element.childNodes.length === 3
            && element.childNodes[1].nodeName === "#text"
            && element.childNodes[1].data === "√";
}

function CheckFractionTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "sfrac nowrap"
            && element.childNodes.length === 3;
}

function CheckIntegralTemplate(element) {
    return element.nodeName === "SPAN"
            && element.childNodes.length === 2
            && element.childNodes[0].childNodes.length === 1
            && element.childNodes[0].childNodes[0].data === "∫";
}

function CheckSubTemplate(element) {
    return element.nodeName === "SUB";
}

function CheckSupTemplate(element) {
    return element.nodeName === "SUP";
}

function GetTreeFromSqrtElement(element) {
    return new Node("sqrt", "", [GetTreeFromElement(element.childNodes[1])]);
}

function GetTreeFromRadicElement(element) {
    return new Node("radic", "", [GetTreeFromElement(element.childNodes[0].childNodes[0]),
        GetTreeFromElement(element.childNodes[2])]);
}

function GetTreeFromFractionTemplate(element) {
    return new Node("frac", "", [GetTreeFromElement(element.childNodes[0].childNodes[0]),
        GetTreeFromElement(element.childNodes[2].childNodes[0])]);
}

function GetTreeFromIntegralTemplate(element) {
    var elementData = element.childNodes[1].childNodes.toArray();
    var brIndex = elementData.length;
    for (var i=0; i<elementData.length; ++i) {
      if (elementData[i].nodeName === "BR") {
        brIndex = i;
        break;
      }
    }
    var upper = elementData.slice(0, brIndex);
    var lower = elementData.slice(brIndex+1);
    var upperElement = null;
    if (upper.length > 1) {
      upperElement = new Node("row", "", upper.map(GetTreeFromElement));
    } else if (upper.length === 1) {
      upperElement = GetTreeFromElement(upper[0]);
    }

    var lowerElement = null;
    if (lower.length > 1) {
      lowerElement = new Node("row", "", lower.map(GetTreeFromElement));
    } else if (lower.length === 1) {
      lowerElement = GetTreeFromElement(lower[0]);
    }

    var children = [];
    if (lowerElement) children.push(lowerElement);
    if (upperElement) children.push(upperElement);

    return new Node("integral", "", children);
}

function GetTreeFromSubTemplate(element) {
    return new Node("sub", "", [CreateRowNode(element)]);
}

function GetTreeFromSupTemplate(element) {
    return new Node("sup", "", [CreateRowNode(element)]);
}

function CreateRowNode(element) {
    if (element.childNodes.length === 1) {
        return GetTreeFromElement(element.childNodes[0]);
    } else {
        return new Node("row", "", element.childNodes.toArray().map(GetTreeFromElement));
    }
}

///// [End Templates]

///// [Post Processing]

function TreePostProcessing(node) {
    RemoveNestedRows(node);
    MatchFences(node);
    FixSubSup(node);
}

function RemoveNestedRows(node) {
    if (node.type === "row") {
        while (node.children.some(function (child) {
            return child.type === "row";
        })) {
            node.children = [].concat.apply([], node.children.map(function (child) {
                if (child.type === "row") {
                    return child.children;
                } else {
                    return [child];
                }
            }));
        }
    }
    node.children.forEach(RemoveNestedRows);
}

function MatchFences(node) {
    var openFences = ["(", "[", "{"];
    var closeFences = [")", "]", "}"];

    while (node.children.some(function (child) {
        return child.type === "text" && openFences.includes(child.value);
    })) {
        var lastFencePos = -1;
        var lastFenceType = "";
        for (var i = 0; i < node.children.length; i++) {
            var child = node.children[i];
            if (child.type === "text" && openFences.includes(child.value)) {
                lastFencePos = i;
                lastFenceType = child.value;
            } else if (child.type === "text" && closeFences.includes(child.value) && lastFencePos !== -1) {
                var newNode = new Node("fence", lastFenceType + child.value, node.children.splice(lastFencePos, i - lastFencePos + 1).slice(1, -1));
                node.children.splice(lastFencePos, 0, newNode);
                break;
            }
        }
    }
    node.children.forEach(MatchFences);
}

function FixSubSup(node) {
    for (var i = 1; i < node.children.length; i++) {
        var child = node.children[i];
        if (child.type === "sub" || child.type === "sup") {
            if (child.children.length === 1) {
                i--;
                child.children.unshift(node.children.splice(i, 1)[0]);
            }
        }
    }
    node.children.forEach(FixSubSup);
}

///// [End Post Processing]

function TreeToMathML(node) {
    var children = node.children.map(TreeToMathML).reduce(function (a, b) {
        return a + b;
    }, "");

    switch (node.type) {
        case "row":
            return "<mrow>" + children + "</mrow>";
        case "sqrt":
            return "<msqrt>" + children + "</msqrt>";
        case "radic":
            return "<mroot>" + children + "</mroot>";
        case "frac":
            return "<mfrac>" + children + "</mfrac>";
        case "integral":
            return "<msubsup><mo>∫</mo>" + children + "</msubsup>"
        case "sub":
            return "<msub>" + children + "</msub>";
        case "sup":
            return "<msup>" + children + "</msup>";
        case "fence":
            if (node.children.length === 1) {
                return "<mrow><mo>" + node.value.charAt(0) + "</mo>" + children + "<mo>" + node.value.charAt(1) + "</mo></mrow>";
            } else {
                return "<mrow><mo>" + node.value.charAt(0) + "</mo><mrow>" + children + "</mrow><mo>" + node.value.charAt(1) + "</mo></mrow>";
            }
        case "text":
            if (true) {
                return "<mi>" + node.value + "</mi>";
            } else if (true) {
                return "<mo>" + node.value + "</mn>";
            } else {
                return "<mo>" + node.value + "</mo>";
            }
    }
}

function GetMathMLFromElement(element) {
    // Converts the span and its children into a MathML string
    // Returns a string representing the MathML or an empty string
    //   if it can’t do the conversion
    var node = GetTreeFromElement(element);
    TreePostProcessing(node);
    //console.log(node.stringify() + "\n\n\n\n");
    return "<math>" + TreeToMathML(node) + "</math>";
}

function CreateInvisibleMathMLNode(mathmlText) {
    // Creates a span node with attrs
    //   class="mwe-math-mathml-inline mwe-math-mathml-a11y"
    //   style="display: none;"}
    // The child of the span is mathml string converted to XML
    // Returns a span element
    var spanElement = document.createElement("SPAN");
    spanElement.setAttribute("class", "mwe-math-mathml-inline mwe-math-mathml-a11y");
//    spanElement.setAttribute("class", "mwe-math-mathml-inline");
    //spanElement.setAttribute("style", "display: none;");
    spanElement.innerHTML = mathmlText;
    return spanElement;
}

function Main() {
    //console.log("Running Main()");
    var texhtmlElements = document.getElementsByClassName("texhtml");
    //console.log("Found " + texhtmlElements.length + " texhtml elements to change")
    var i;
    for (i = 0; i < texhtmlElements.length; i++) {
        var element = texhtmlElements[i];
        var mathmlText = GetMathMLFromElement(element);
        if (mathmlText) {
            element.setAttribute("aria-hidden", "true");
            var mathmlSpan = CreateInvisibleMathMLNode(mathmlText);
            element.parentElement.insertBefore(mathmlSpan, element);
        }
        //console.log("All done");
    }
}

try {
    Main();
} catch (e) {
    console.error(e);
}
<commit_msg>Tweaked things<commit_after>// ==UserScript==
// @name          Inline accessible wikipedia math
// @namespace     http://www.talkingcatsoftware.com/gmscripts
// @description   Makes math authored with the "math" template accessible by adding a MathML equivalent to the template output
// @include       https://*.wikipedia.org/*
// @require       https://raw.githubusercontent.com/slevithan/xregexp/master/xregexp-all.js
// @version       0.1.0
// @icon         http://www.example.net/icon.png
// ==/UserScript==

NodeList.prototype.toArray = function () {
    return Array.prototype.slice.call(this);
}

///// [Data Structures]

function Node(_type, _value, _children) {
    this.type = _type || "";
    this.value = _value || "";
    this.children = _children || [];
}

Node.prototype.stringify = function (level) {
    level = level || 0;
    return "  ".repeat(level) + this.type + ":" + this.value + "\n" + this.children.map(function (child) {
        return child.stringify(level + 1);
    }).reduce(function (string, sum) {
        return string + sum;
    }, "");
};

///// [End Data Structures]

///// [Templates]

function GetTreeFromElement(element) {
    if (CheckSqrtTemplate(element))
        return GetTreeFromSqrtElement(element);
    if (CheckRadicTemplate(element))
        return GetTreeFromRadicElement(element);
    if (CheckFractionTemplate(element))
        return GetTreeFromFractionTemplate(element);
    if (CheckIntegralTemplate(element))
        return GetTreeFromIntegralTemplate(element);
    if (CheckSubTemplate(element))
        return GetTreeFromSubTemplate(element);
    if (CheckSupTemplate(element))
        return GetTreeFromSupTemplate(element);

    if (element.childNodes.length > 0) {
        return CreateRowNode(element);
    }

    // Parse text
    var re = XRegExp("\\s*([0-9]+|\\pL+|[^\\s])\\s*");
    var tokens = [];
    var m;
    var pos = 0;
    while (m = XRegExp.exec(element.textContent, re, pos, "sticky")) {
        tokens.push(m[1]);
        pos = m.index + m[0].length;
    }

    if (tokens.length === 1) {
        return new Node("text", tokens[0]);
    } else {
        return new Node("row", "", tokens.map(function (token) {
            return new Node("text", token);
        }));
    }
}

function CheckSqrtTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "nowrap"
            && element.childNodes.length === 2
            && element.childNodes[0].nodeName === "#text"
            && element.childNodes[0].data === "√";
}

function CheckRadicTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "nowrap"
            && element.childNodes.length === 3
            && element.childNodes[1].nodeName === "#text"
            && element.childNodes[1].data === "√";
}

function CheckFractionTemplate(element) {
    return element.nodeName === "SPAN"
            && element.className === "sfrac nowrap"
            && element.childNodes.length === 3;
}

function CheckIntegralTemplate(element) {
    return element.nodeName === "SPAN"
            && element.childNodes.length === 2
            && element.childNodes[0].childNodes.length === 1
            && element.childNodes[0].childNodes[0].data === "∫";
}

function CheckSubTemplate(element) {
    return element.nodeName === "SUB";
}

function CheckSupTemplate(element) {
    return element.nodeName === "SUP";
}

function GetTreeFromSqrtElement(element) {
    return new Node("sqrt", "", [GetTreeFromElement(element.childNodes[1])]);
}

function GetTreeFromRadicElement(element) {
    return new Node("radic", "", [GetTreeFromElement(element.childNodes[0].childNodes[0]),
        GetTreeFromElement(element.childNodes[2])]);
}

function GetTreeFromFractionTemplate(element) {
    return new Node("frac", "", [GetTreeFromElement(element.childNodes[0].childNodes[0]),
        GetTreeFromElement(element.childNodes[2].childNodes[0])]);
}

function GetTreeFromIntegralTemplate(element) {
    var elementData = element.childNodes[1].childNodes.toArray();
    var brIndex = elementData.length;
    for (var i=0; i<elementData.length; ++i) {
      if (elementData[i].nodeName === "BR") {
        brIndex = i;
        break;
      }
    }
    var upper = elementData.slice(0, brIndex);
    var lower = elementData.slice(brIndex+1);
    var upperElement = null;
    if (upper.length > 1) {
      upperElement = new Node("row", "", upper.map(GetTreeFromElement));
    } else if (upper.length === 1) {
      upperElement = GetTreeFromElement(upper[0]);
    }

    var lowerElement = null;
    if (lower.length > 1) {
      lowerElement = new Node("row", "", lower.map(GetTreeFromElement));
    } else if (lower.length === 1) {
      lowerElement = GetTreeFromElement(lower[0]);
    }

    var children = [];
    if (lowerElement) children.push(lowerElement);
    if (upperElement) children.push(upperElement);

    return new Node("integral", "", children);
}

function GetTreeFromSubTemplate(element) {
    return new Node("sub", "", [CreateRowNode(element)]);
}

function GetTreeFromSupTemplate(element) {
    return new Node("sup", "", [CreateRowNode(element)]);
}

function CreateRowNode(element) {
    if (element.childNodes.length === 1) {
        return GetTreeFromElement(element.childNodes[0]);
    } else {
        return new Node("row", "", element.childNodes.toArray().map(GetTreeFromElement));
    }
}

///// [End Templates]

///// [Post Processing]

function TreePostProcessing(node) {
    RemoveNestedRows(node);
    MatchFences(node);
    FixSubSup(node);
}

function RemoveNestedRows(node) {
    if (node.type === "row") {
        while (node.children.some(function (child) {
            return child.type === "row";
        })) {
            node.children = [].concat.apply([], node.children.map(function (child) {
                if (child.type === "row") {
                    return child.children;
                } else {
                    return [child];
                }
            }));
        }
    }
    node.children.forEach(RemoveNestedRows);
}

function MatchFences(node) {
    var openFences = ["(", "[", "{"];
    var closeFences = [")", "]", "}"];

    while (node.children.some(function (child) {
        return child.type === "text" && openFences.includes(child.value);
    })) {
        var lastFencePos = -1;
        var lastFenceType = "";
        for (var i = 0; i < node.children.length; i++) {
            var child = node.children[i];
            if (child.type === "text" && openFences.includes(child.value)) {
                lastFencePos = i;
                lastFenceType = child.value;
            } else if (child.type === "text" && closeFences.includes(child.value) && lastFencePos !== -1) {
                var newNode = new Node("fence", lastFenceType + child.value, node.children.splice(lastFencePos, i - lastFencePos + 1).slice(1, -1));
                node.children.splice(lastFencePos, 0, newNode);
                break;
            }
        }
    }
    node.children.forEach(MatchFences);
}

function FixSubSup(node) {
    for (var i = 1; i < node.children.length; i++) {
        var child = node.children[i];
        if (child.type === "sub" || child.type === "sup") {
            if (child.children.length === 1) {
                i--;
                child.children.unshift(node.children.splice(i, 1)[0]);
            }
        }
    }
    node.children.forEach(FixSubSup);
}

///// [End Post Processing]

function TreeToMathML(node) {
    var children = node.children.map(TreeToMathML).reduce(function (a, b) {
        return a + b;
    }, "");

    switch (node.type) {
        case "row":
            return "<mrow>" + children + "</mrow>";
        case "sqrt":
            return "<msqrt>" + children + "</msqrt>";
        case "radic":
            return "<mroot>" + children + "</mroot>";
        case "frac":
            return "<mfrac>" + children + "</mfrac>";
        case "integral":
            return "<msubsup><mo>∫</mo>" + children + "</msubsup>"
        case "sub":
            return "<msub>" + children + "</msub>";
        case "sup":
            return "<msup>" + children + "</msup>";
        case "fence":
            if (node.children.length === 1) {
                return "<mrow><mo>" + node.value.charAt(0) + "</mo>" + children + "<mo>" + node.value.charAt(1) + "</mo></mrow>";
            } else {
                return "<mrow><mo>" + node.value.charAt(0) + "</mo><mrow>" + children + "</mrow><mo>" + node.value.charAt(1) + "</mo></mrow>";
            }
        case "text":
            if (true) {
                return "<mi>" + node.value + "</mi>";
            } else if (true) {
                return "<mo>" + node.value + "</mn>";
            } else {
                return "<mo>" + node.value + "</mo>";
            }
    }
}

function GetMathMLFromElement(element) {
    // Converts the span and its children into a MathML string
    // Returns a string representing the MathML or an empty string
    //   if it can’t do the conversion
    var node = GetTreeFromElement(element);
    TreePostProcessing(node);
    //console.log(node.stringify() + "\n\n\n\n");
    return "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">" + TreeToMathML(node) + "</math>";
}

function CreateInvisibleMathMLNode(mathmlText) {
    // Creates a span node with attrs
    //   class="mwe-math-mathml-inline mwe-math-mathml-a11y"
    //   style="display: none;"}
    // The child of the span is mathml string converted to XML
    // Returns a span element
    var spanElement = document.createElement("SPAN");
    //spanElement.setAttribute("class", "mwe-math-mathml-inline mwe-math-mathml-a11y");
    //spanElement.setAttribute("class", "mwe-math-mathml-inline");
    //spanElement.setAttribute("style", "display: none;");
    spanElement.innerHTML = mathmlText;
    return spanElement;
}

function Main() {
    //console.log("Running Main()");
    var texhtmlElements = document.getElementsByClassName("texhtml");
    //console.log("Found " + texhtmlElements.length + " texhtml elements to change")
    var i;
    for (i = 0; i < texhtmlElements.length; i++) {
        var element = texhtmlElements[i];
        var mathmlText = GetMathMLFromElement(element);
        if (mathmlText) {
            element.setAttribute("aria-hidden", "true");
            var mathmlSpan = CreateInvisibleMathMLNode(mathmlText);
            element.parentElement.insertBefore(mathmlSpan, element);
        }
        //console.log("All done");
    }
}

try {
    Main();
} catch (e) {
    console.error(e);
}
<|endoftext|>


<commit_before>// Parse a simple SPARL-Update subset syntax for patches.
//
//  This parses
//   WHERE {xxx} DELETE {yyy} INSERT DATA {zzz}
// (not necessarily in that order)
// as though it were the n3
//   <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}.

$rdf.sparqlUpdateParser = function(str, kb, base) {
    var i,j,k;
    var keywords = [ 'INSERT', 'DELETE', 'WHERE' ]
    var SQNS = $rdf.Namespace('http://www.w3.org/ns/pim/patch#');
    var p = $rdf.N3Parser(kb, kb, base, base, null, null, "", null);
    var clauses = {};

    var badSyntax = function (uri, lines, str, i, why) {
        return  ("Line " +  ( lines + 1 ) + " of <" + uri + ">: Bad syntax:\n   " +
                why + "\n   at: \"" + str.slice(i, (i + 30))  + "\"" ) ;
    };

    var check = function(next, last, message) {
        if (next < 0) {
            throw badSyntax(p._thisDoc, p.lines, str, j, last, message);
        };
        return next;
    };

    i = 0;
    var query = kb.sym(base+ '#query');  // Invent a URI for the query
    clauses['query'] = query; // A way of accessing it in its N3 model.

    while (true) {
        // console.log("A Now at i = " + i)
        var j = p.skipSpace(str, i);
        if (j < 0) {
            return clauses
        }
        // console.log("B After space at j= " + j)
        if (str[j] === ';') {
            i = skipSpace(str, j + 1);
            if ( i < 0) {
                return clauses ; // Allow end in a ;
            }
            j = i;
        }
        var found = false;
        for (k=0;  k< keywords.length; k++) {
            key = keywords[k];
            if (str.slice(j, j + key.length) === key) {
                // console.log("C got one " + key);
                i = p.skipSpace(str, j+ key.length);
                // console.log("D after space at i= " + i);
                if (i < 0) {
                    throw badSyntax(p._thisDoc, p.lines, str, j+ key.length, "found EOF, needed {...} after "+key);
                };
                if (((key === 'INSERT') || (key === 'DELETE')) && str.slice(i, i+4) === 'DATA') { // Some wanted 'DATA'. Whatever
                    j = p.skipSpace(str, i+4);
                    if (j < 0) {
                        throw badSyntax(p._thisDoc, p.lines, str, i+4, "needed {...} after INSERT DATA "+key);
                    };
                    i = j;
                }
                var res2 = [];
                var j = p.node(str, i, res2);
                // console.log("M Now at j= " + j + " i= " + i)

                if (j < 0) {
                    throw badSyntax(p._thisDoc, p.lines, str, i,
                            "bad syntax or EOF in {...} after " + key);
                }
                clauses[key.toLowerCase()] = res2[0];
                // print("res2[0] for "+key+ " is " + res2[0]);  //   @@ debug @@@@@@
                kb.add(query, SQNS(key.lower), res2[0]);
                // key is the keyword and res2 has the contents
                found = true;
                i = j;
            }
        };
        if (!found  && str.slice(j, j+7) === '@prefix') {
            var i = p.directive(str, j);
            if (i < 0) {
            throw badSyntax(p._thisDoc, p.lines, str, i,
                    "bad syntax or EOF after @prefix ");
            }
            // console.log("P before dot i= " + i)
            i = p.checkDot(str, i);
            // console.log("Q after dot i= " + i)
            found = true;
        }
        if (!found) {
            // console.log("Bad syntax " + j)
            throw badSyntax(p._thisDoc, p.lines, str, j,
                    "Unknown syntax at start of statememt: '" + str.slice(j).slice(0,20) +"'")
        }

    } // while
    //return clauses

}; // End of spaqlUpdateParser

// ends
<commit_msg>Ignore semicolons after clauses - oops<commit_after>// Parse a simple SPARL-Update subset syntax for patches.
//
//  This parses
//   WHERE {xxx} DELETE {yyy} INSERT DATA {zzz}
// (not necessarily in that order)
// as though it were the n3
//   <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}.

$rdf.sparqlUpdateParser = function(str, kb, base) {
    var i,j,k;
    var keywords = [ 'INSERT', 'DELETE', 'WHERE' ]
    var SQNS = $rdf.Namespace('http://www.w3.org/ns/pim/patch#');
    var p = $rdf.N3Parser(kb, kb, base, base, null, null, "", null);
    var clauses = {};

    var badSyntax = function (uri, lines, str, i, why) {
        return  ("Line " +  ( lines + 1 ) + " of <" + uri + ">: Bad syntax:\n   " +
                why + "\n   at: \"" + str.slice(i, (i + 30))  + "\"" ) ;
    };

    var check = function(next, last, message) {
        if (next < 0) {
            throw badSyntax(p._thisDoc, p.lines, str, j, last, message);
        };
        return next;
    };

    i = 0;
    var query = kb.sym(base+ '#query');  // Invent a URI for the query
    clauses['query'] = query; // A way of accessing it in its N3 model.

    while (true) {
        // console.log("A Now at i = " + i)
        var j = p.skipSpace(str, i);
        if (j < 0) {
            return clauses
        }
        // console.log("B After space at j= " + j)
        if (str[j] === ';') {
            i = p.skipSpace(str, j + 1);
            if ( i < 0) {
                return clauses ; // Allow end in a ;
            }
            j = i;
        }
        var found = false;
        for (k=0;  k< keywords.length; k++) {
            key = keywords[k];
            if (str.slice(j, j + key.length) === key) {
                // console.log("C got one " + key);
                i = p.skipSpace(str, j+ key.length);
                // console.log("D after space at i= " + i);
                if (i < 0) {
                    throw badSyntax(p._thisDoc, p.lines, str, j+ key.length, "found EOF, needed {...} after "+key);
                };
                if (((key === 'INSERT') || (key === 'DELETE')) && str.slice(i, i+4) === 'DATA') { // Some wanted 'DATA'. Whatever
                    j = p.skipSpace(str, i+4);
                    if (j < 0) {
                        throw badSyntax(p._thisDoc, p.lines, str, i+4, "needed {...} after INSERT DATA "+key);
                    };
                    i = j;
                }
                var res2 = [];
                var j = p.node(str, i, res2);
                // console.log("M Now at j= " + j + " i= " + i)

                if (j < 0) {
                    throw badSyntax(p._thisDoc, p.lines, str, i,
                            "bad syntax or EOF in {...} after " + key);
                }
                clauses[key.toLowerCase()] = res2[0];
                // print("res2[0] for "+key+ " is " + res2[0]);  //   @@ debug @@@@@@
                kb.add(query, SQNS(key.lower), res2[0]);
                // key is the keyword and res2 has the contents
                found = true;
                i = j;
            }
        };
        if (!found  && str.slice(j, j+7) === '@prefix') {
            var i = p.directive(str, j);
            if (i < 0) {
            throw badSyntax(p._thisDoc, p.lines, str, i,
                    "bad syntax or EOF after @prefix ");
            }
            // console.log("P before dot i= " + i)
            i = p.checkDot(str, i);
            // console.log("Q after dot i= " + i)
            found = true;
        }
        if (!found) {
            // console.log("Bad syntax " + j)
            throw badSyntax(p._thisDoc, p.lines, str, j,
                    "Unknown syntax at start of statememt: '" + str.slice(j).slice(0,20) +"'")
        }

    } // while
    //return clauses

}; // End of spaqlUpdateParser

// ends
<|endoftext|>


<commit_before>function get(url) {
  try {
    var xhr = new XMLHttpRequest();;
    xhr.open('GET', url, false);
    xhr.send();
    return xhr.responseText;
  } catch (e) {
    return 'Erreur'+e;; // turn all errors into empty results
  }
  }

function ExecuterEncore(data){
postMessage(data);
ExecuterEncore(get(URL));
}

this.onmessage = function (event) {
URL=event.data;
ExecuterEncore(get(URL));
};

/*
 * var thread = new Worker('threadRecuperation.js');
   function postDataToThread(donnes) {
     thread.postMessage(donnes);
   }
thread.onmessage = function (event) {
     var data = event.data
     }
 */<commit_msg>Thread recupération données version modifié<commit_after>function get(url) {
  try {
    var xhr = new XMLHttpRequest();;
    xhr.open('GET', url, false);
    xhr.send();
    return xhr.responseText;
  } catch (e) {
    return 'Erreur'+e;; // turn all errors into empty results
  }
  }

function ExecuterEncore(data){
postMessage(data);
console.log(data);
ExecuterEncore(get(URL));
}

this.onmessage = function (event) {
URL=event.data;
ExecuterEncore(get(URL));
};

/*
 * var thread = new Worker('threadRecuperation.js');
   function postDataToThread(donnes) {
     thread.postMessage(donnes);
   }
thread.onmessage = function (event) {
     var data = event.data
     }
 */<|endoftext|>


<commit_before>"use strict";

describe("relation", function() {
  var confCustomization = {
    getConfAndDelegate: function(obj) {
      var relations = {
        labels: {
          PRED : { short: "PRED", long: "predicate" },
          OBJ : { short: "OBJ", long: "object" },
          COORD : { short: "COORD", long: "coordination" }
        }
      };
      obj.conf = { relations: relations };
    }
  };

  var relation, state;

  beforeEach(function() {
    module("arethusa.core", function($provide) {
      $provide.value('configurator', arethusaMocks.configurator(confCustomization));
    });

    module("arethusa.relation");

    inject(function(_relation_, _state_) {
      state = _state_;
      state.initServices();
      state.tokens = arethusaMocks.tokens();
      relation = _relation_;
      relation.init();
    });
  });

  describe('label handling', function() {
    describe('this.buildLabel', function() {
      describe('build a label from prefix and suffix values', function () {
        it('combines a prefix and a suffix label to one, joined by an underscore', function() {
          var relationLabel = { prefix: "PRED", suffix: "CO" };
          relation.buildLabel(relationLabel);
          expect(relationLabel.label).toEqual("PRED_CO");
        });
      });

      it("doesn't add unnecessary underscores", function() {
        var relationLabel = { prefix: "ATR" };
        relation.buildLabel(relationLabel);
        expect(relationLabel.label).toEqual("ATR");
      });
    });

    describe('this.expandRelation', function() {
      describe('with two labels', function () {
        it('splits a label like PRED_CO into PRED and CO', function() {
          var relationLabel = { label: "PRED_CO" };
          relation.expandRelation(relationLabel);
          expect(relationLabel.prefix).toEqual("PRED");
          expect(relationLabel.suffix).toEqual("CO");
        });
      });

      describe('with one label', function () {
        it('does not affect single labels like PRED', function() {
          var relationLabel = { label: "PRED" };
          relation.expandRelation(relationLabel);
          expect(relationLabel.prefix).toEqual("PRED");
          expect(relationLabel.suffix).toEqual('');
        });
      });
    });
  });

  describe('multi changes', function() {
    describe('this.multiChangePossible', function() {
      it('is false when there is no selected token', function() {
        expect(relation.multiChangePossible()).toBeFalsy();
      });

      it('needs a valid multiChanger model', function() {
        state.selectToken('01', 'click');
        expect(relation.multiChangePossible()).toBeFalsy();

        relation.multiChanger = { prefix: "ATR" };
        expect(relation.multiChangePossible()).toBeTruthy();
      });
    });

    describe('this.applyMultiChanger', function() {
      it('changes the relation value of all selected tokens', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var newRel = { label: "ATR", prefix: 'ATR', suffix: '' };
        relation.multiChanger = newRel;
        relation.applyMultiChanger();

        expect(state.tokens['01'].relation.label).toEqual("ATR");
        expect(state.tokens['02'].relation.label).toEqual("ATR");
      });

      it('passes on unique relation objects', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var newRel = { label: "ATR" };
        relation.multiChanger = newRel;
        relation.applyMultiChanger();

        var rel1 = state.tokens['01'].relation;
        var rel2 = state.tokens['02'].relation;
        expect(rel1).not.toBe(rel2);
      });
    });
  });

  describe('working with selections', function() {
    describe('this.selectLabel', function() {
      it('selects tokens by label', function() {
        relation.selectByLabel('OBJ_CO');
        expect(state.isSelected('01')).toBeTruthy();
        expect(state.isSelected('02')).toBeTruthy();
        expect(state.isSelected('03')).toBeFalsy();
        expect(state.isSelected('04')).toBeFalsy();

        relation.selectByLabel('COORD');
        expect(state.isSelected('01')).toBeFalsy();
        expect(state.isSelected('02')).toBeFalsy();
        expect(state.isSelected('03')).toBeTruthy();
        expect(state.isSelected('04')).toBeFalsy();
      });
    });

    describe('this.currentLabels', function() {
      it('returns obj of all selected tokens with their id, string and relation obj', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var res = relation.currentLabels();

        var rel1 = { string: 'Arma',  relation: state.tokens['01'].relation };
        var rel2 = { string: 'virum', relation: state.tokens['02'].relation };

        expect(res['01']).toEqual(rel1);
        expect(res['02']).toEqual(rel2);
        expect(res['03']).toBeUndefined();
        expect(res['04']).toBeUndefined();
      });
    });
  });

  describe('this.buildLabelAndSearch', function() {
    it('builds a label on an obj and searches for it afterwards', function() {
      var relObj = { prefix: 'OBJ', suffix: 'CO' };
      relation.buildLabelAndSearch(relObj);
      expect(state.isSelected('01')).toBeTruthy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('when no obj is given, the searchedLabel model is used instead', function() {
      relation.searchedLabel = { prefix: 'OBJ', suffix: 'CO' };
      relation.buildLabelAndSearch();
      expect(state.isSelected('01')).toBeTruthy();
      expect(state.isSelected('02')).toBeTruthy();
    });
  });

  describe('init functions', function() {
    describe('this.createInternalState', function() {
      it('sets an internal state, which is a selection of the tokens string and relation obj', function() {
        var res = relation.createInternalState();

        var rel1 = { string: 'Arma',  relation: state.tokens['01'].relation };
        var rel2 = { string: 'virum', relation: state.tokens['02'].relation };
        var rel3 = { string: '-que',  relation: state.tokens['03'].relation };
        var rel4 = { string: 'cano',  relation: state.tokens['04'].relation };

        expect(res['01']).toEqual(rel1);
        expect(res['02']).toEqual(rel2);
        expect(res['03']).toEqual(rel3);
        expect(res['04']).toEqual(rel4);
      });
    });
  });
});
<commit_msg>Fix relation spec<commit_after>"use strict";

describe("relation", function() {
  var confCustomization = {
    getConfAndDelegate: function(obj) {
      var relations = {
        labels: {
          PRED : { short: "PRED", long: "predicate" },
          OBJ : { short: "OBJ", long: "object" },
          COORD : { short: "COORD", long: "coordination" }
        }
      };
      obj.conf = { relations: relations };
    }
  };

  var relation, state;

  beforeEach(function() {
    module("arethusa.core", function($provide) {
      $provide.value('configurator', arethusaMocks.configurator(confCustomization));
    });

    module("arethusa.relation");

    inject(function(_relation_, _state_) {
      state = _state_;
      state.initServices();
      state.tokens = arethusaMocks.tokens();
      relation = _relation_;
      relation.init();
    });
  });

  describe('label handling', function() {
    describe('this.buildLabel', function() {
      describe('build a label from prefix and suffix values', function () {
        it('combines a prefix and a suffix label to one, joined by an underscore', function() {
          var relationLabel = { prefix: "PRED", suffix: "CO" };
          relation.buildLabel(relationLabel);
          expect(relationLabel.label).toEqual("PRED_CO");
        });
      });

      it("doesn't add unnecessary underscores", function() {
        var relationLabel = { prefix: "ATR" };
        relation.buildLabel(relationLabel);
        expect(relationLabel.label).toEqual("ATR");
      });
    });

    describe('this.expandRelation', function() {
      describe('with two labels', function () {
        it('splits a label like PRED_CO into PRED and CO', function() {
          var relationLabel = { label: "PRED_CO" };
          relation.expandRelation(relationLabel);
          expect(relationLabel.prefix).toEqual("PRED");
          expect(relationLabel.suffix).toEqual("CO");
        });
      });

      describe('with one label', function () {
        it('does not affect single labels like PRED', function() {
          var relationLabel = { label: "PRED" };
          relation.expandRelation(relationLabel);
          expect(relationLabel.prefix).toEqual("PRED");
          expect(relationLabel.suffix).toEqual('');
        });
      });
    });
  });

  describe('multi changes', function() {
    describe('this.multiChangePossible', function() {
      it('is false when there is no selected token', function() {
        expect(relation.multiChangePossible()).toBeFalsy();
      });

      it('needs a valid multiChanger model', function() {
        state.selectToken('01', 'click');
        expect(relation.multiChangePossible()).toBeFalsy();

        relation.multiChanger = { prefix: "ATR" };
        expect(relation.multiChangePossible()).toBeTruthy();
      });
    });

    describe('this.applyMultiChanger', function() {
      it('changes the relation value of all selected tokens', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var newRel = { label: "ATR", prefix: 'ATR', suffix: '' };
        relation.multiChanger = newRel;
        relation.applyMultiChanger();

        expect(state.tokens['01'].relation.label).toEqual("ATR");
        expect(state.tokens['02'].relation.label).toEqual("ATR");
      });

      it('passes on unique relation objects', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var newRel = { label: "ATR" };
        relation.multiChanger = newRel;
        relation.applyMultiChanger();

        var rel1 = state.tokens['01'].relation;
        var rel2 = state.tokens['02'].relation;
        expect(rel1).not.toBe(rel2);
      });
    });
  });

  describe('working with selections', function() {
    describe('this.selectLabel', function() {
      it('selects tokens by label', function() {
        relation.selectByLabel('OBJ_CO');
        expect(state.isSelected('01')).toBeTruthy();
        expect(state.isSelected('02')).toBeTruthy();
        expect(state.isSelected('03')).toBeFalsy();
        expect(state.isSelected('04')).toBeFalsy();

        relation.selectByLabel('COORD');
        expect(state.isSelected('01')).toBeFalsy();
        expect(state.isSelected('02')).toBeFalsy();
        expect(state.isSelected('03')).toBeTruthy();
        expect(state.isSelected('04')).toBeFalsy();
      });
    });

    describe('this.currentLabels', function() {
      it('returns obj of all selected tokens with their id, string and relation obj', function() {
        state.selectToken('01', 'ctrl-click');
        state.selectToken('02', 'ctrl-click');
        var res = relation.currentLabels();

        var rel1 = { string: 'Arma',  relation: state.tokens['01'].relation };
        var rel2 = { string: 'virum', relation: state.tokens['02'].relation };

        expect(res['01']).toEqual(rel1);
        expect(res['02']).toEqual(rel2);
        expect(res['03']).toBeUndefined();
        expect(res['04']).toBeUndefined();
      });
    });
  });

  describe('this.buildLabelAndSearch', function() {
    describe('with exact matching', function() {
      beforeEach(function() { relation.exactSearchMatch = true; });

      it('builds a label on an obj and searches for it afterwards', function() {
        var relObj = { prefix: 'OBJ', suffix: 'CO' };
        relation.buildLabelAndSearch(relObj);
        expect(state.isSelected('01')).toBeTruthy();
        expect(state.isSelected('02')).toBeTruthy();
      });

      it('when no obj is given, the searchedLabel model is used instead', function() {
        relation.searchedLabel = { prefix: 'OBJ', suffix: 'CO' };
        relation.buildLabelAndSearch();
        expect(state.isSelected('01')).toBeTruthy();
        expect(state.isSelected('02')).toBeTruthy();
      });
    });

    describe('without exact matching', function() {
      it('searches successful when only prefix matches', function() {

      });
    });
  });

  describe('init functions', function() {
    describe('this.createInternalState', function() {
      it('sets an internal state, which is a selection of the tokens string and relation obj', function() {
        var res = relation.createInternalState();

        var rel1 = { string: 'Arma',  relation: state.tokens['01'].relation };
        var rel2 = { string: 'virum', relation: state.tokens['02'].relation };
        var rel3 = { string: '-que',  relation: state.tokens['03'].relation };
        var rel4 = { string: 'cano',  relation: state.tokens['04'].relation };

        expect(res['01']).toEqual(rel1);
        expect(res['02']).toEqual(rel2);
        expect(res['03']).toEqual(rel3);
        expect(res['04']).toEqual(rel4);
      });
    });
  });
});
<|endoftext|>


<commit_before>function OAuthServiceOAuthSandbox(options) {
    var parent = OAuthServiceOAuthSandbox.prototype;

    var name = 'sandbox';

    if (arguments.length > 0) {
        this.init(options);
    }

    this.init = function(options) {
        parent.init.apply(this, arguments);
    };

    this.signature_method = 'PLAINTEXT';

    this.realm = 'http://oauth-sandbox.sevengoslings.net/';
    this.requestTokenUrl = this.realm + 'request_token';
    this.authorizationUrl = this.realm + 'authorize';
    this.accessTokenUrl = this.realm + 'access_token';

    this.twoLegged = function() {
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var url = 'http://oauth-sandbox.sevengoslings.net/two_legged';

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url + '?' + this.getRequestString(), false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(null);
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            alert(xhr.responseText);
        }
    };

    this.threeLegged = function() {
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var url = 'http://oauth-sandbox.sevengoslings.net/three_legged';

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url + '?' + this.getRequestString(), false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(null);
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            alert(xhr.responseText);
        }
    };
}

OAuthServiceOAuthSandbox.prototype = new OAuthService();
<commit_msg>brought upto date with new API<commit_after>function OAuthServiceOAuthSandbox(options) {
    var parent = OAuthServiceOAuthSandbox.prototype;

    var _private = {
		debug: false
	};

    this.init = function(options) {
		_private.debug = 'debug' in options ? options.debug : _private.debug;
        parent.init.apply(this, arguments);
    };

    this.signature_method = 'PLAINTEXT';

    this.realm = 'http://oauth-sandbox.sevengoslings.net/';
    this.requestTokenUrl = this.realm + 'request_token';
    this.authorizationUrl = this.realm + 'authorize';
    this.accessTokenUrl = this.realm + 'access_token';

	this.twoLegged = function() {
		if (_private.debug) {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
		}

		var header_params = this.getAuthorizationHeaderParameters();

		var request = new OAuthRequest({
			method: 'GET',
			url: 'http://oauth-sandbox.sevengoslings.net/two_legged',
			query: {},
			authorization_header_params: header_params
		});

		var signature = new OAuthConsumer.signatureMethods[this.signature_method]().sign(
			request, this.getConsumerToken().secret, this.getAccessToken().secret
		);

		request.setAuthorizationHeaderParam('oauth_signature', signature);

		var header_string = 'OAuth ' + request.toHeaderString();

		var xhr = new XMLHttpRequest();
		xhr.open(request.getMethod(), request.getUrl(), false);
		xhr.setRequestHeader('Authorization', header_string);
		xhr.send(request.toQueryString());
		if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
			alert(xhr.responseText);
		}
	};

    this.threeLegged = function() {
		if (_private.debug) {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
		}

		var header_params = this.getAuthorizationHeaderParameters();

		var request = new OAuthRequest({
			method: 'GET',
			url: 'http://oauth-sandbox.sevengoslings.net/three_legged',
			query: {},
			authorization_header_params: header_params
		});

		var signature = new OAuthConsumer.signatureMethods[this.signature_method]().sign(
			request, this.getConsumerToken().secret, this.getAccessToken().secret
		);

		request.setAuthorizationHeaderParam('oauth_signature', signature);

		var header_string = 'OAuth ' + request.toHeaderString();

		var xhr = new XMLHttpRequest();
		xhr.open(request.getMethod(), request.getUrl(), false);
		xhr.setRequestHeader('Authorization', header_string);
		xhr.send(request.toQueryString());
		if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
			alert(xhr.responseText);
		}
	};

	if (arguments.length > 0) {
        this.init(options);
    }
}

OAuthServiceOAuthSandbox.prototype = new OAuthService();
<|endoftext|>


<commit_before>/* eslint-env es6 */
/* global THREE, Indices */
window.translateBoxVertices = (function() {
  'use strict';

  const vector = new THREE.Vector3();
  const zero = new THREE.Vector3();

  return function translate( geometry, vectors ) {
    Object.keys( vectors ).forEach( key => {
      const delta = vectors[ key ];
      const indices = Indices[ key.toUpperCase() ];

      if ( Array.isArray( delta ) ) {
        vector.fromArray( delta );
      } else if ( typeof delta === 'object' ) {
        Object.assign( vector, zero, delta );
      } else if ( typeof delta === 'number' ) {
        vector.setScalar( delta );
      } else {
        return;
      }

      if ( Array.isArray( indices ) ) {
        indices.forEach( index =>
          geometry.vertices[ index ].add( vector )
        );
      } else {
        geometry.vertices[ indices ].add( vector );
      }
    });

    return geometry;
  };
}());
<commit_msg>lathe[cuboid]: Generalize BoxGeometry translation helpers to scaling.<commit_after>/* eslint-env es6 */
/* global THREE, Indices */
function transformBoxVertices( method ) {
  'use strict';

  const vector = new THREE.Vector3();
  const zero = new THREE.Vector3();

  return function transform( geometry, vectors ) {
    Object.keys( vectors ).forEach( key => {
      const delta = vectors[ key ];
      const indices = Indices[ key.toUpperCase() ];

      if ( Array.isArray( delta ) ) {
        vector.fromArray( delta );
      } else if ( typeof delta === 'object' ) {
        Object.assign( vector, zero, delta );
      } else if ( typeof delta === 'number' ) {
        vector.setScalar( delta );
      } else {
        return;
      }

      if ( Array.isArray( indices ) ) {
        indices.forEach( index =>
          geometry.vertices[ index ][ method ]( vector )
        );
      } else {
        geometry.vertices[ indices ][ method ]( vector );
      }
    });

    return geometry;
  };
}

window.translateBoxVertices = transformBoxVertices( 'add' );
window.scaleBoxVertices = transformBoxVertices( 'multiply' );
<|endoftext|>


<commit_before>"use strict";

var path = require('path');

module.exports = {
    // Whether or not to automatically throttle and blacklist abusive requests.
    // This works best if `upstreamRequestLog` is also set.
    autoThrottle: true,

    // Domain to use for CDN requests to RawGit.
    cdnDomain: 'cdn.rawgit.com',

    // GitHub "username/repo" from which RawGit's own static assets should be
    // loaded via the CDN. Set this to a falsy value to disable loading static
    // assets from the CDN.
    cdnRepo: 'rgrove/rawgit',

    // Git tag that points to the GitHub commit from which RawGit's own static
    // assets should be loaded via the CDN. Set this to a falsy value to disable
    // loading static assets from the CDN.
    cdnTag: 'cdn-20150421',

    // Domain to use for dev requests to RawGit.
    devDomain: 'rawgit.com',

    // Whitelist of file extensions that will be proxied through RawGit. All
    // others will be redirected to raw.githubusercontent.com.
    //
    // Requests to the cdnDomain will bypass this whitelist and proxy all file
    // types. Please keep this list alphabetized.
    extensionWhitelist: {
        '.appcache'   : true,
        '.coffee'     : true,
        '.css'        : true,
        '.eot'        : true,
        '.geojson'    : true,
        '.handlebars' : true,
        '.hbs'        : true,
        '.htm'        : true,
        '.html'       : true,
        '.js'         : true,
        '.json'       : true,
        '.jsonld'     : true,
        '.kml'        : true,
        '.md'         : true,
        '.n3'         : true,
        '.nt'         : true,
        '.otf'        : true,
        '.pdf'        : true,
        '.rdf'        : true,
        '.rss'        : true,
        '.svg'        : true,
        '.swf'        : true,
        '.ttc'        : true,
        '.ttf'        : true,
        '.ttl'        : true,
        '.woff'       : true,
        '.woff2'      : true,
        '.xht'        : true,
        '.xhtml'      : true,
        '.xml'        : true,
        '.yaml'       : true,
        '.yml'        : true
    },

    // Whether we're running in a production environment (true) or
    // development/test (false).
    isProduction: process.env.NODE_ENV === 'production',

    // This multiplier is used to determine the naughtiness of a given request
    // based on internal stats about the requested file and the referrer.
    //
    // Naughtiness for files is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier
    //
    // Naughtiness for referrers is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier *
    //         referrerNaughtinessMultiplier
    //
    // Referrers get a little more leeway since they're often legitimately
    // requesting multiple files per page.
    //
    // The end result is that large files requested rarely are fine. Small files
    // requested frequently but not too often are fine. But large files
    // requested often and small files requested abusively often are not fine.
    //
    // This multiplier is calibrated such that a naughtiness score of >= 0.5
    // probably indicates requests should be throttled, and a score of >= 1.0
    // probably indicates requests should be blacklisted.
    naughtinessMultiplier: 0.0000002,

    // Public directory containing static files.
    publicDir: path.join(__dirname, '/../public'),

    // Additional multiplier to use when determining the naughtiness of a
    // referrer. This is used to give referrers more leeway than individual
    // files, since they're often legitimately requesting multiple files per
    // page.
    referrerNaughtinessMultiplier: 0.3,

    // Array of request header names that should be relayed from the user to
    // GitHub.
    relayRequestHeaders: [
        'If-Modified-Since',
        'If-None-Match',
        'User-Agent'
    ],

    // Array of response header names that should be relayed from GitHub to the
    // user.
    relayResponseHeaders: [
        'Date',
        'ETag'
    ],

    // Hash of paths that should not be included in stats. This is mainly useful
    // if you use monitoring tools that ping a given URL every few minutes and
    // you don't want them affecting stats rankings.
    statsIgnorePaths: {
        '/rgrove/rawgit/master/web.js': true
    },

    // If RawGit is fronted by Nginx, Apache, or something else that generates
    // logs in Common/Combined Log Format, set the path to that file here to
    // have RawGit tail the log and use it for accurate request statistics.
    //
    // If this is not set or if the file doesn't exist or isn't readable, RawGit
    // will track requests internally (but this may result in inaccurate stats
    // if you're fronting RawGit with a caching proxy).
    upstreamRequestLog: '/data/logs/rawgit.com-access.log',

    // Number of historical log entries to parse from the upstream request log
    // on startup. This is useful in order to retain recent stats after the
    // RawGit process is restarted.
    upstreamRequestLogScrollback: 100000
};
<commit_msg>:lipstick:<commit_after>"use strict";

var path = require('path');

module.exports = {
    // Whether or not to automatically throttle and blacklist abusive requests.
    // This works best if `upstreamRequestLog` is also set.
    autoThrottle: true,

    // Domain to use for CDN requests to RawGit.
    cdnDomain: 'cdn.rawgit.com',

    // GitHub "username/repo" from which RawGit's own static assets should be
    // loaded via the CDN. Set this to a falsy value to disable loading static
    // assets from the CDN.
    cdnRepo: 'rgrove/rawgit',

    // Git tag that points to the GitHub commit from which RawGit's own static
    // assets should be loaded via the CDN. Set this to a falsy value to disable
    // loading static assets from the CDN.
    cdnTag: 'cdn-20150421',

    // Domain to use for dev requests to RawGit.
    devDomain: 'rawgit.com',

    // Whitelist of file extensions that will be proxied through RawGit. All
    // others will be redirected to raw.githubusercontent.com.
    //
    // Requests to the cdnDomain will bypass this whitelist and proxy all file
    // types. Please keep this list alphabetized.
    extensionWhitelist: {
        '.appcache'  : true,
        '.coffee'    : true,
        '.css'       : true,
        '.eot'       : true,
        '.geojson'   : true,
        '.handlebars': true,
        '.hbs'       : true,
        '.htm'       : true,
        '.html'      : true,
        '.js'        : true,
        '.json'      : true,
        '.jsonld'    : true,
        '.kml'       : true,
        '.md'        : true,
        '.n3'        : true,
        '.nt'        : true,
        '.otf'       : true,
        '.pdf'       : true,
        '.rdf'       : true,
        '.rss'       : true,
        '.svg'       : true,
        '.swf'       : true,
        '.ttc'       : true,
        '.ttf'       : true,
        '.ttl'       : true,
        '.woff'      : true,
        '.woff2'     : true,
        '.xht'       : true,
        '.xhtml'     : true,
        '.xml'       : true,
        '.yaml'      : true,
        '.yml'       : true
    },

    // Whether we're running in a production environment (true) or
    // development/test (false).
    isProduction: process.env.NODE_ENV === 'production',

    // This multiplier is used to determine the naughtiness of a given request
    // based on internal stats about the requested file and the referrer.
    //
    // Naughtiness for files is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier
    //
    // Naughtiness for referrers is determined by this formula:
    //
    //     requests * requestsPerSecond * totalKilobytes * multiplier *
    //         referrerNaughtinessMultiplier
    //
    // Referrers get a little more leeway since they're often legitimately
    // requesting multiple files per page.
    //
    // The end result is that large files requested rarely are fine. Small files
    // requested frequently but not too often are fine. But large files
    // requested often and small files requested abusively often are not fine.
    //
    // This multiplier is calibrated such that a naughtiness score of >= 0.5
    // probably indicates requests should be throttled, and a score of >= 1.0
    // probably indicates requests should be blacklisted.
    naughtinessMultiplier: 0.0000002,

    // Public directory containing static files.
    publicDir: path.join(__dirname, '/../public'),

    // Additional multiplier to use when determining the naughtiness of a
    // referrer. This is used to give referrers more leeway than individual
    // files, since they're often legitimately requesting multiple files per
    // page.
    referrerNaughtinessMultiplier: 0.3,

    // Array of request header names that should be relayed from the user to
    // GitHub.
    relayRequestHeaders: [
        'If-Modified-Since',
        'If-None-Match',
        'User-Agent'
    ],

    // Array of response header names that should be relayed from GitHub to the
    // user.
    relayResponseHeaders: [
        'Date',
        'ETag'
    ],

    // Hash of paths that should not be included in stats. This is mainly useful
    // if you use monitoring tools that ping a given URL every few minutes and
    // you don't want them affecting stats rankings.
    statsIgnorePaths: {
        '/rgrove/rawgit/master/web.js': true
    },

    // If RawGit is fronted by Nginx, Apache, or something else that generates
    // logs in Common/Combined Log Format, set the path to that file here to
    // have RawGit tail the log and use it for accurate request statistics.
    //
    // If this is not set or if the file doesn't exist or isn't readable, RawGit
    // will track requests internally (but this may result in inaccurate stats
    // if you're fronting RawGit with a caching proxy).
    upstreamRequestLog: '/data/logs/rawgit.com-access.log',

    // Number of historical log entries to parse from the upstream request log
    // on startup. This is useful in order to retain recent stats after the
    // RawGit process is restarted.
    upstreamRequestLogScrollback: 100000
};
<|endoftext|>


<commit_before>import Piece from './piece';

export default class Board {
  constructor() {
    this.setBoard(this.initialUsiBoard());
  }

  initialUsiBoard() {
    return (
      [
        ['l', 'n', 's', 'g', 'k', 'g', 's', 'n', 'l'],
        ['*', 'b', '*', '*', '*', '*', '*', 'r', '*'],
        ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
        ['*', 'B', '*', '*', '*', '*', '*', 'R', '*'],
        ['L', 'N', 'S', 'G', 'K', 'G', 'S', 'N', 'L']
      ]
    );
  }

  setBoard(board) {
    this.board = this.createBoard(board);
  }

  createBoard(board) {
    var _board = board.map((row, y) => {
      var yCor = y + 1;
      var rows = row.map((type, x) => {
        var xCor = 10 - x - 1;
        return (
          new Piece({ type: type, x: xCor, y: yCor })
        );
      });
      return(rows);
    });

    return _board;
  }

  enhanceMovablePoint(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    // if piece of argument is not match piece in the board, throw exception
    //
    if (
      typeof this.findPiece(x, y) === 'undefined' ||
        !this.findPiece(x, y).equals(
          new Piece({
            x: piece.x,
            y: piece.y,
            type: piece.type,
            movable: piece.movable
          })
        )
    ) {
      var pos = `xCor = ${xCor}, yCor = ${yCor}`;
      throw new Error(`Does not match coordinates in board. ${pos}`);
    }

    // if moveDef has just property, piece moves just coordinates on board.
    //
    if (moveDef.just) {
      this.movablePointsByJust(piece);
    }

    // if moveDef has fly property, piece moves recursion on board.
    //
    if (moveDef.fly) {
      this.movablePointsByFly(piece);
    }
  }

  // if moveDef has just property, piece moves just coordinates on board.
  //
  movablePointsByJust(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    moveDef.just.forEach((def) => {
      var [defX, defY] = def;
      var piece = this.findPiece(x + defX, y + defY);
      if (piece) { piece.movable = true; }
    });
  }

  movablePointsByFly(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    moveDef.fly.forEach((def) => {
      var [defX, defY] = def;
      var dx, dy;

      dx = x + defX;
      dy = y + defY;

      var piece = this.findPiece(dx, dy);

      while (piece) {
        piece.movable = true;
        dx = dx + defX;
        dy = dy + defY;

        piece = this.findPiece(dx, dy);

        if (piece && piece.type !== '*') {
          piece.movable = true;
          break;
        }
      }
    });
  }

  invertToIndexX(xCor) {
    return 9 - xCor;
  }

  invertToIndexY(yCor) {
    return yCor - 1;
  }

  invertCor(xCor, yCor) {
    return [this.invertToIndexX(xCor), this.invertToIndexY(yCor)];
  }

  findPiece(xIndex, yIndex) {
    var row = this.board[yIndex];
    return row ? row[xIndex] : undefined;
  }

  // transposeToCorX(xIndex) {
  // }

  // transposeToCorY(xIndex) {
  // }
};
<commit_msg>Refactor<commit_after>import Piece from './piece';

export default class Board {
  constructor() {
    this.setBoard(this.initialUsiBoard());
  }

  initialUsiBoard() {
    return (
      [
        ['l', 'n', 's', 'g', 'k', 'g', 's', 'n', 'l'],
        ['*', 'b', '*', '*', '*', '*', '*', 'r', '*'],
        ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['*', '*', '*', '*', '*', '*', '*', '*', '*'],
        ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
        ['*', 'B', '*', '*', '*', '*', '*', 'R', '*'],
        ['L', 'N', 'S', 'G', 'K', 'G', 'S', 'N', 'L']
      ]
    );
  }

  setBoard(board) {
    this.board = this.createBoard(board);
  }

  createBoard(board) {
    var _board = board.map((row, y) => {
      var yCor = y + 1;
      var rows = row.map((type, x) => {
        var xCor = 10 - x - 1;
        return (
          new Piece({ type: type, x: xCor, y: yCor })
        );
      });
      return(rows);
    });

    return _board;
  }

  enhanceMovablePoint(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    // if piece of argument is not match piece in the board, throw exception
    //
    if (! this.matchPiece(piece)) {
      var pos = `xCor = ${xCor}, yCor = ${yCor}`;
      throw new Error(`Does not match coordinates in board. ${pos}`);
    }

    // if moveDef has just property, piece moves just coordinates on board.
    //
    if (moveDef.just) {
      this.movablePointsByJust(piece);
    }

    // if moveDef has fly property, piece moves recursion on board.
    //
    if (moveDef.fly) {
      this.movablePointsByFly(piece);
    }
  }

  // if piece of argument is match in the board, return true, else return false
  //
  matchPiece(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var [x, y] = this.invertCor(xCor, yCor);

    var isUndefined = typeof this.findPiece(x, y) === 'undefined';
    var isEqualPiece = this.findPiece(x, y).equals(
      new Piece({
        x: piece.x,
        y: piece.y,
        type: piece.type,
        movable: piece.movable
      })
    );

    return (isUndefined || isEqualPiece);
  }

  // if moveDef has just property, piece moves just coordinates on board.
  //
  movablePointsByJust(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    moveDef.just.forEach((def) => {
      var [defX, defY] = def;
      var piece = this.findPiece(x + defX, y + defY);
      if (piece) { piece.movable = true; }
    });
  }

  movablePointsByFly(piece) {
    var [xCor, yCor] = [piece.x, piece.y];
    var moveDef = piece.moveDef();
    var [x, y] = this.invertCor(xCor, yCor);

    moveDef.fly.forEach((def) => {
      var [defX, defY] = def;
      var dx, dy;

      dx = x + defX;
      dy = y + defY;

      var piece = this.findPiece(dx, dy);

      while (piece) {
        piece.movable = true;
        dx = dx + defX;
        dy = dy + defY;

        piece = this.findPiece(dx, dy);

        if (piece && piece.type !== '*') {
          piece.movable = true;
          break;
        }
      }
    });
  }

  invertToIndexX(xCor) {
    return 9 - xCor;
  }

  invertToIndexY(yCor) {
    return yCor - 1;
  }

  invertCor(xCor, yCor) {
    return [this.invertToIndexX(xCor), this.invertToIndexY(yCor)];
  }

  findPiece(xIndex, yIndex) {
    var row = this.board[yIndex];
    return row ? row[xIndex] : undefined;
  }

  // transposeToCorX(xIndex) {
  // }

  // transposeToCorY(xIndex) {
  // }
};
<|endoftext|>


<commit_before>const configurator = require("@nteract/webpack-configurator");
const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
const webpack = require("webpack");
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");

const nodeEnv = process.env.NODE_ENV || "development";
const isProd = nodeEnv === "production";

const plugins = [
  new MonacoWebpackPlugin(),
  new webpack.IgnorePlugin(
    /^((fs)|(path)|(os)|(crypto)|(source-map-support))$/,
    /vs\/language\/typescript\/lib/
  )
];

if (isProd) {
  plugins.push(new LodashModuleReplacementPlugin());
} else {
  plugins.push(new webpack.HotModuleReplacementPlugin());
}

module.exports = {
  externals: ["canvas", "fs"],
  mode: isProd ? "production" : "development",
  devtool: isProd ? "hidden-source-map" : "cheap-eval-source-map",
  entry: {
    app: "./app/index.tsx"
  },
  devServer: isProd
    ? {}
    : {
        publicPath: "/nteract/static/dist/",
        hot: true,
        headers: { "Access-Control-Allow-Origin": "*" }
      },
  target: "web",
  output: {
    chunkFilename: isProd ? "[name]-[chunkhash].bundle.js" : "[name].bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              transpileOnly: true,
              compilerOptions: {
                noEmit: false
              }
            }
          }
        ]
      }
    ]
  },
  resolve: {
    mainFields: ["nteractDesktop", "module", "main"],
    extensions: [".ts", ".tsx", ".js"],
    alias: configurator.mergeDefaultAliases()
  },
  plugins
};
<commit_msg>Update Webpack config for fs package<commit_after>const configurator = require("@nteract/webpack-configurator");
const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
const webpack = require("webpack");
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");

const nodeEnv = process.env.NODE_ENV || "development";
const isProd = nodeEnv === "production";

const plugins = [
  new MonacoWebpackPlugin(),
  new webpack.IgnorePlugin(
    /^((fs)|(path)|(os)|(crypto)|(source-map-support))$/,
    /vs\/language\/typescript\/lib/
  )
];

if (isProd) {
  plugins.push(new LodashModuleReplacementPlugin());
} else {
  plugins.push(new webpack.HotModuleReplacementPlugin());
}

module.exports = {
  externals: ["canvas"],
  mode: isProd ? "production" : "development",
  devtool: isProd ? "hidden-source-map" : "cheap-eval-source-map",
  entry: {
    app: "./app/index.tsx"
  },
  devServer: isProd
    ? {}
    : {
        publicPath: "/nteract/static/dist/",
        hot: true,
        headers: { "Access-Control-Allow-Origin": "*" }
      },
  target: "web",
  output: {
    chunkFilename: isProd ? "[name]-[chunkhash].bundle.js" : "[name].bundle.js"
  },
  node: {
    fs: "empty"
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              transpileOnly: true,
              compilerOptions: {
                noEmit: false
              }
            }
          }
        ]
      }
    ]
  },
  resolve: {
    mainFields: ["nteractDesktop", "module", "main"],
    extensions: [".ts", ".tsx", ".js"],
    alias: configurator.mergeDefaultAliases()
  },
  plugins
};
<|endoftext|>


<commit_before>import {
  each,
  isString
} from "./utils";
import Queue from "./queue";

function DeferredActionQueues(queueNames, options) {
  var queues = this.queues = {};
  this.queueNames = queueNames = queueNames || [];

  this.options = options;

  each(queueNames, function(queueName) {
    queues[queueName] = new Queue(queueName, options[queueName], options);
  });
}

function noSuchQueue(name) {
  throw new Error("You attempted to schedule an action in a queue (" + name + ") that doesn't exist");
}

DeferredActionQueues.prototype = {
  schedule: function(name, target, method, args, onceFlag, stack) {
    var queues = this.queues;
    var queue = queues[name];

    if (!queue) { noSuchQueue(name); }

    if (onceFlag) {
      return queue.pushUnique(target, method, args, stack);
    } else {
      return queue.push(target, method, args, stack);
    }
  },

  invoke: function(target, method, args, _, _errorRecordedForStack) {
    if (args && args.length > 0) {
      method.apply(target, args);
    } else {
      method.call(target);
    }
  },

  invokeWithOnError: function(target, method, args, onError, errorRecordedForStack) {
    try {
      if (args && args.length > 0) {
        method.apply(target, args);
      } else {
        method.call(target);
      }
    } catch(error) {
      onError(error, errorRecordedForStack);
    }
  },

  flush: function() {
    var queues = this.queues;
    var queueNames = this.queueNames;
    var queueName, queue, queueItems, priorQueueNameIndex;
    var queueNameIndex = 0;
    var numberOfQueues = queueNames.length;
    var options = this.options;
    var onError = options.onError || (options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]);
    var invoke = onError ? this.invokeWithOnError : this.invoke;

    while (queueNameIndex < numberOfQueues) {
      queueName = queueNames[queueNameIndex];
      queue = queues[queueName];
      queueItems = queue._queueBeingFlushed = queue._queue.slice();
      queue._queue = [];
      queue.targetQueues = Object.create(null);

      var queueOptions = queue.options; // TODO: write a test for this
      var before = queueOptions && queueOptions.before;
      var after = queueOptions && queueOptions.after;
      var target, method, args, errorRecordedForStack;
      var queueIndex = 0;
      var numberOfQueueItems = queueItems.length;

      if (numberOfQueueItems && before) {
        before();
      }

      while (queueIndex < numberOfQueueItems) {
        target                = queueItems[queueIndex];
        method                = queueItems[queueIndex+1];
        args                  = queueItems[queueIndex+2];
        errorRecordedForStack = queueItems[queueIndex+3]; // Debugging assistance

        if (isString(method)) {
          method = target[method];
        }

        // method could have been nullified / canceled during flush
        if (method) {
          invoke(target, method, args, onError, errorRecordedForStack);
        }

        queueIndex += 4;
      }

      queue._queueBeingFlushed = null;
      if (numberOfQueueItems && after) {
        after();
      }

      if ((priorQueueNameIndex = indexOfPriorQueueWithActions(this, queueNameIndex)) !== -1) {
        queueNameIndex = priorQueueNameIndex;
      } else {
        queueNameIndex++;
      }
    }
  }
};

function indexOfPriorQueueWithActions(daq, currentQueueIndex) {
  var queueName, queue;

  for (var i = 0, l = currentQueueIndex; i <= l; i++) {
    queueName = daq.queueNames[i];
    queue = daq.queues[queueName];
    if (queue._queue.length) { return i; }
  }

  return -1;
}

export default DeferredActionQueues;
<commit_msg>add helpfully message to developers who end up here via the stack explorer<commit_after>import {
  each,
  isString
} from "./utils";
import Queue from "./queue";

function DeferredActionQueues(queueNames, options) {
  var queues = this.queues = {};
  this.queueNames = queueNames = queueNames || [];

  this.options = options;

  each(queueNames, function(queueName) {
    queues[queueName] = new Queue(queueName, options[queueName], options);
  });
}

function noSuchQueue(name) {
  throw new Error("You attempted to schedule an action in a queue (" + name + ") that doesn't exist");
}

DeferredActionQueues.prototype = {
  schedule: function(name, target, method, args, onceFlag, stack) {
    var queues = this.queues;
    var queue = queues[name];

    if (!queue) { noSuchQueue(name); }

    if (onceFlag) {
      return queue.pushUnique(target, method, args, stack);
    } else {
      return queue.push(target, method, args, stack);
    }
  },

  invoke: function(target, method, args, _, _errorRecordedForStack) {
    if (args && args.length > 0) {
      method.apply(target, args);
    } else {
      method.call(target);
    }
  },

  invokeWithOnError: function(target, method, args, onError, errorRecordedForStack) {
    try {
      if (args && args.length > 0) {
        method.apply(target, args);
      } else {
        method.call(target);
      }
    } catch(error) {
      onError(error, errorRecordedForStack);
    }
  },

  flush: function() {
    var queues = this.queues;
    var queueNames = this.queueNames;
    var queueName, queue, queueItems, priorQueueNameIndex;
    var queueNameIndex = 0;
    var numberOfQueues = queueNames.length;
    var options = this.options;
    var onError = options.onError || (options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]);
    var invoke = onError ? this.invokeWithOnError : this.invoke;

    while (queueNameIndex < numberOfQueues) {
      queueName = queueNames[queueNameIndex];
      queue = queues[queueName];
      queueItems = queue._queueBeingFlushed = queue._queue.slice();
      queue._queue = [];
      queue.targetQueues = Object.create(null);

      var queueOptions = queue.options; // TODO: write a test for this
      var before = queueOptions && queueOptions.before;
      var after = queueOptions && queueOptions.after;
      var target, method, args, errorRecordedForStack;
      var queueIndex = 0;
      var numberOfQueueItems = queueItems.length;

      if (numberOfQueueItems && before) {
        before();
      }

      while (queueIndex < numberOfQueueItems) {
        target                = queueItems[queueIndex];
        method                = queueItems[queueIndex+1];
        args                  = queueItems[queueIndex+2];
        errorRecordedForStack = queueItems[queueIndex+3]; // Debugging assistance

        //

        if (isString(method)) {
          method = target[method];
        }

        // method could have been nullified / canceled during flush
        if (method) {
          //
          //    ** Attention intrepid developer **
          //
          //    To find out the stack of this task when it was scheduled onto
          //    the run loop, add the following to your app.js:
          //
          //    Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production.
          //
          //    Once that is in place, when you are at a breakpoint and navigate
          //    here in the stack explorer, you can look at `errorRecordedForStack.stack`,
          //    which will be the captured stack when this job was scheduled.
          //
          invoke(target, method, args, onError, errorRecordedForStack);
        }

        queueIndex += 4;
      }

      queue._queueBeingFlushed = null;
      if (numberOfQueueItems && after) {
        after();
      }

      if ((priorQueueNameIndex = indexOfPriorQueueWithActions(this, queueNameIndex)) !== -1) {
        queueNameIndex = priorQueueNameIndex;
      } else {
        queueNameIndex++;
      }
    }
  }
};

function indexOfPriorQueueWithActions(daq, currentQueueIndex) {
  var queueName, queue;

  for (var i = 0, l = currentQueueIndex; i <= l; i++) {
    queueName = daq.queueNames[i];
    queue = daq.queues[queueName];
    if (queue._queue.length) { return i; }
  }

  return -1;
}

export default DeferredActionQueues;
<|endoftext|>


<commit_before>import models from '../models';
import DocumentControllerHelper
from '../helpers/controllers/documentControllerHelper';

const Document = models.Documents;
const User = models.Users;
const createQuery = DocumentControllerHelper.createQueryForList;
const isDocumentList = DocumentControllerHelper.isDocumentList;
const isGetUserDocuments = DocumentControllerHelper.isGetUserDocuments;
const isRetrieveDocuments = DocumentControllerHelper.isRetrieveDocuments;
const isDestroyDocuments = DocumentControllerHelper.isDestroyDocuments;
const isUpdateDocuments = DocumentControllerHelper.isUpdateDocuments;

export default {
  create(req, res) {
    return Document
      .create({
        title: req.body.title,
        body: req.body.body,
        access: req.body.access,
        userId: req.params.userId || req.decoded.data.id,
        ownerRoleId: req.decoded.data.roleId,
      })
      .then(document => res.status(201)
        .json({
          success: true,
          message: 'Document created successfully.',
          document,
        }))
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'An error occured while creating this document.',
          error,
        }));
  },

  update(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isUpdateDocuments(document, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error encountered while updating',
          error,
        }));
  },

  destroy(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isDestroyDocuments(document, res);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error encountered while deleting user',
          error,
        }));
  },

  retrieve(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isRetrieveDocuments(document, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error retrieving document',
          error,
        }));
  },

  list(req, res) {
    const query = createQuery(req);
    return Document
      .findAll(query)
      .then((document) => {
        const response = isDocumentList(document, res);
        return response;
      })
      .catch(error => res.status(400)
        .send(error));
  },

  getUserDocuments(req, res) {
    User.findById(req.params.userId)
      .then((user) => {
        const response = isGetUserDocuments(user, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error retrieving document',
          error,
        }));
  },
};
<commit_msg>feature(server/controllers/document.js) fix bug with dynamic query<commit_after>import models from '../models';
import DocumentControllerHelper
from '../helpers/controllers/documentControllerHelper';

const Document = models.Documents;
const User = models.Users;
const createQuery = DocumentControllerHelper.createQueryForList;
const isDocumentList = DocumentControllerHelper.isDocumentList;
const isGetUserDocuments = DocumentControllerHelper.isGetUserDocuments;
const isRetrieveDocuments = DocumentControllerHelper.isRetrieveDocuments;
const isDestroyDocuments = DocumentControllerHelper.isDestroyDocuments;
const isUpdateDocuments = DocumentControllerHelper.isUpdateDocuments;

export default {
  create(req, res) {
    return Document
      .create({
        title: req.body.title,
        body: req.body.body,
        access: req.body.access,
        userId: req.params.userId || req.decoded.data.id,
        ownerRoleId: req.decoded.data.roleId,
      })
      .then(document => res.status(201)
        .json({
          success: true,
          message: 'Document created successfully.',
          document,
        }))
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'An error occured while creating this document.',
          error,
        }));
  },

  update(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isUpdateDocuments(document, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error encountered while updating',
          error,
        }));
  },

  destroy(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isDestroyDocuments(document, res);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error encountered while deleting user',
          error,
        }));
  },

  retrieve(req, res) {
    return Document
      .find({
        where: {
          id: req.params.documentId,
        },
      })
      .then((document) => {
        const response = isRetrieveDocuments(document, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error retrieving document',
          error,
        }));
  },

  list(req, res) {
    const query = createQuery(req);
    return Document
      .findAll({
        where: query.where,
        offset: query.offset,
        limit: query.limit,
        include: [models.Users],
      })
      .then((document) => {
        const response = isDocumentList(document, res);
        return response;
      })
      .catch(error => res.status(400)
        .send(error));
  },

  getUserDocuments(req, res) {
    User.findById(req.params.userId)
      .then((user) => {
        const response = isGetUserDocuments(user, res, req);
        return response;
      })
      .catch(error => res.status(400)
        .json({
          success: false,
          message: 'Error retrieving document',
          error,
        }));
  },
};
<|endoftext|>