text:
function PythonToBlocks() {
}

function xmlToString(xml) {
    return new XMLSerializer().serializeToString(xml);
}

PythonToBlocks.prototype.convertSource = function(python_source) {
    var xml = document.createElement("xml");
    if (python_source.trim() === "") {
        return {"xml": xmlToString(xml), "error": null};
    }
    this.source = python_source.split("\n");
    var filename = 'user_code.py';
    // Attempt parsing - might fail!
    var parse, ast, symbol_table, error;
    try {
        parse = Sk.parse(filename, python_source);
        ast = Sk.astFromParse(parse.cst, filename, parse.flags);
        symbol_table = Sk.symboltable(ast, filename, python_source, filename, parse.flags);
    } catch (e) {
        error = e;
        xml.appendChild(raw_block(python_source))
        return {"xml": xmlToString(xml), "error": error};
    }
    this.measureNode(ast);
    var converted = this.convert(ast);
    if (converted !== null) {
        for (var block = 0; block < converted.length; block+= 1) {
            xml.appendChild(converted[block]);
        }
    }
    return {"xml": xmlToString(xml), "error": null};
}

PythonToBlocks.prototype.identifier = function(node) {
    return Sk.ffi.remapToJs(node);
}

PythonToBlocks.prototype.recursiveMeasure = function(node, nextBlockLine) {
    if (node === undefined)  {
        return;
    }
    var myNext = nextBlockLine;
    if ("orelse" in node && node.orelse.length > 0) {
        if (node.orelse.length == 1 && node.orelse[0]._astname == "If") {
            myNext = node.orelse[0].lineno-1;
        } else {
            myNext = node.orelse[0].lineno-1-1;
        }
    }
    this.heights.push(nextBlockLine);
    if ("body" in node) {
        for (var i = 0; i < node.body.length; i++) {
            var next;
            if (i+1 == node.body.length) {
                next = myNext;
            } else {
                next = node.body[i+1].lineno-1;
            }
            this.recursiveMeasure(node.body[i], next);
        }
    }
    if ("orelse" in node) {
        for (var i = 0; i < node.orelse.length; i++) {
            var next;
            if (i == node.orelse.length) {
                next = nextBlockLine;
            } else {
                next = 1+(node.orelse[i].lineno-1);
            }
            this.recursiveMeasure(node.orelse[i], next);
        }
    }
}

PythonToBlocks.prototype.measureNode = function(node) {
    this.heights = [];
    this.recursiveMeasure(node, this.source.length-1);
    this.heights.shift();
}

PythonToBlocks.prototype.getSourceCode = function(from, to) {
    var lines = this.source.slice(from-1, to);
    // Strip out any starting indentation.
    if (lines.length > 0) {
        var indentation = lines[0].search(/\S/);
        for (var i = 0; i < lines.length; i++) {
            lines[i] = lines[i].substring(indentation);
        }
    }
    return lines.join("\n");
}

PythonToBlocks.prototype.convertBody = function(node, is_top_level) {
    // Empty body. Boring!
    if (node.length == 0) {
        return null;
    }

    // This is tricked by semicolons. Hard to get around that...
    // TODO: Force semicolon breaks in a preprocessor, and extract comments too

    // Build the actual blocks
    var from = node[0].lineno;
    var to = this.heights.shift();

    // Walk through and convert the blocks to statements
    var children = [];
    var currentChild = null,
        firstChild = null;
    for (var i = 0; i < node.length; i++) {
        from = node[i].lineno;
        to = this.heights.shift();
        var newChild = this.convertStatement(node[i], this.getSourceCode(from, to), is_top_level);

        // Skip null blocks (e.g., imports)
        if (newChild !== null) {
            if (is_top_level && newChild.constructor == Array) {
                // Add non-statement expressions to the end
                children.push(newChild[0]);
            } else if (is_top_level && children.length > 0) {
                children.push(newChild);
            } else {
                if (newChild.constructor == Array) {
                    newChild = newChild[0];
                }
                if (firstChild == null) {
                    firstChild = newChild;
                    currentChild = newChild;
                } else {
                    var nextElement = document.createElement("next");
                    nextElement.appendChild(newChild);
                    currentChild.appendChild(nextElement);
                    currentChild = newChild;
                }
            }
        }
    }
    // Actually add that first child to the start
    if (firstChild !== null) {
        children.unshift(firstChild);
    }
    return children;
}

function block(type, fields, values, settings, mutations, statements) {
    var newBlock = document.createElement("block");
    // Settings
    newBlock.setAttribute("type", type);
    for (var setting in settings) {
        var settingValue = settings[setting];
        newBlock.setAttribute(setting, settingValue);
    }
    // Mutations
    if (mutations !== undefined && Object.keys(mutations).length > 0) {
        var newMutation = document.createElement("mutation");
        for (var mutation in mutations) {
            var mutationValue = mutations[mutation];
            if (mutation.charAt(0) == '@') {
                newMutation.setAttribute(mutation.substr(1), mutationValue);
            } else if (mutationValue.constructor === Array) {
                for (var i = 0; i < mutationValue.length; i++) {
                    var mutationNode = document.createElement(mutation);
                    mutationNode.setAttribute("name", mutationValue[i]);
                    newMutation.appendChild(mutationNode);
                }
            } else {
                var mutationNode = document.createElement("arg");
                mutationNode.setAttribute("name", mutation);
                mutationNode.appendChild(mutationValue);
                newMutation.appendChild(mutationNode);
            }
        }
        newBlock.appendChild(newMutation);
    }
    // Fields
    for (var field in fields) {
        var fieldValue = fields[field];
        var newField = document.createElement("field");
        newField.setAttribute("name", field);
        newField.appendChild(document.createTextNode(fieldValue));
        newBlock.appendChild(newField);
    }
    // Values
    for (var value in values) {
        var valueValue = values[value];
        var newValue = document.createElement("value");
        if (valueValue !== null) {
            newValue.setAttribute("name", value);
            newValue.appendChild(valueValue);
            newBlock.appendChild(newValue);
        }
    }
    // Statements
    if (statements !== undefined && Object.keys(statements).length > 0) {
        for (var statement in statements) {
            var statementValue = statements[statement];
            if (statementValue == null) {
                continue;
            } else {
                for (var i = 0; i < statementValue.length; i += 1) {
                    // In most cases, you really shouldn't ever have more than
                    //  one statement in this list. I'm not sure Blockly likes
                    //  that.
                    var newStatement = document.createElement("statement");
                    newStatement.setAttribute("name", statement);
                    newStatement.appendChild(statementValue[i]);
                    newBlock.appendChild(newStatement);
                }
            }
        }
    }
    return newBlock;
}

raw_block = function(text) {
    return block("raw_block", { "TEXT": text });
}

PythonToBlocks.prototype.convert = function(node, is_top_level) {
    return this[node._astname](node, is_top_level);
}

function arrayMax(array) {
  return array.reduce(function(a, b) {
    return Math.max(a, b);
  });
}

function arrayMin(array) {
  return array.reduce(function(a, b) {
    return Math.min(a, b);
  });
}

PythonToBlocks.prototype.convertStatement = function(node, full_source, is_top_level) {
    try {
        return this.convert(node, is_top_level);
    } catch (e) {
        heights = this.getChunkHeights(node);
        extractedSource = this.getSourceCode(arrayMin(heights), arrayMax(heights));
        return raw_block(extractedSource);
    }
}

PythonToBlocks.prototype.getChunkHeights = function(node) {
    var lineNumbers = [];
    if (node.hasOwnProperty("lineno")) {
        lineNumbers.push(node.lineno);
    }
    if (node.hasOwnProperty("body")) {
        for (var i = 0; i < node.body.length; i += 1) {
            var subnode = node.body[i];
            lineNumbers = lineNumbers.concat(this.getChunkHeights(subnode));
        }
    }
    if (node.hasOwnProperty("orelse")) {
        for (var i = 0; i < node.orelse.length; i += 1) {
            var subnode = node.orelse[i];
            lineNumbers = lineNumbers.concat(this.getChunkHeights(subnode));
        }
    }
    return lineNumbers;
}

/* ----- Nodes ---- */
/*
 * NO LINE OR COLUMN NUMBERS
 * Module
 * body: asdl_seq
 */
PythonToBlocks.prototype.Module = function(node)
{
    return this.convertBody(node.body, true);
}

/*
 * NO LINE OR COLUMN NUMBERS
 * Interactive
 * body: asdl_seq
 */
PythonToBlocks.prototype.Interactive = function(body)
{
    return this.convertBody(node.body);
}

/*
 * NO LINE OR COLUMN NUMBERS
 * TODO
 * body: expr_ty
 */
PythonToBlocks.prototype.Expression = function(body)
{
    this.body = body;
}

/*
 * NO LINE OR COLUMN NUMBERS
 *
 * body: asdl_seq
 */
PythonToBlocks.prototype.Suite = function(body)
{
    this.asdl_seq(node.body);
}

/*
 *
 * name: identifier
 * args: arguments__ty
 * body: asdl_seq
 * decorator_list: asdl_seq
 */
PythonToBlocks.prototype.FunctionDef = function(node)
{
    var name = node.name;
    var args = node.args;
    var body = node.body;
    var decorator_list = node.decorator_list;
    if (decorator_list.length > 0) {
        throw new Error("Decorators are not implemented.");
    }
    return block("procedures_defnoreturn", {
        "NAME": this.identifier(name)
    }, {
    }, {
        "inline": "false"
    }, {
        "arg": this.arguments_(args)
    }, {
        "STACK": this.convertBody(body)
    });
}

/*
 * name: identifier
 * args: arguments__ty
 * bases: asdl_seq
 * body: asdl_seq
 * decorator_list: asdl_seq
 */
PythonToBlocks.prototype.ClassDef = function(node)
{
    this.name = name;
    this.bases = bases;
    this.body = body;
    this.decorator_list = decorator_list;
    throw new Error("Not implemented");
}

/*
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.Return = function(node)
{
    var value = node.value;
    // No field, one title, one setting
    return block("procedures_return", {}, {
        "VALUE": this.convert(value)
    }, {
        "inline": "false"
    });
}

/*
 * targets: asdl_seq
 *
 */
PythonToBlocks.prototype.Delete = function(/* {asdl_seq *} */ targets)
{
    this.targets = targets;
    // TODO
    throw new Error("Delete is not implemented");
}

/*
 * targets: asdl_seq
 * value: expr_ty
 */
PythonToBlocks.prototype.Assign = function(node)
{
    var targets = node.targets;
    var value = node.value;
    if (targets.length == 0) {
        throw new Error("Nothing to assign to!");
    } else if (targets.length == 1) {
        return block("variables_set", {
            "VAR": this.Name_str(targets[0]) //targets
        }, {
            "VALUE": this.convert(value)
        });
    } else {
        //TODO
        throw new Error("Multiple Assigment Targets Not implemented");
    }
}

/*
 * target: expr_ty
 * op: operator_ty
 * value: expr_ty
 */
PythonToBlocks.prototype.AugAssign = function(node)
{
    var target = node.target;
    var op = node.op;
    var value = node.value;
    if (op.name != "Add") {
        //TODO
        throw new Error("Only addition is currently supported for augmented assignment!");
    } else {
        return block("math_change", {
            "VAR": this.Name_str(target)
        }, {
            "DELTA": this.convert(value)
        });
    }
}

/*
 * dest: expr_ty
 * values: asdl_seq
 * nl: bool
 *
 */
PythonToBlocks.prototype.Print = function(node)
{
    var dest = node.dest;
    var values = node.values;
    var nl = node.nl;

    if (values.length == 1) {
        return block("text_print", {}, {
            "TEXT": this.convert(values[0])
        });
    } else {
        return block("text_print_multiple", {},
            this.convertElements("PRINT", values),
        {
            "inline": "true"
        }, {
            "@items": values.length
        });
    }
}

/*
 * target: expr_ty
 * iter: expr_ty
 * body: asdl_seq
 * orelse: asdl_seq
 *
 */
PythonToBlocks.prototype.For = function(node) {
    var target = node.target;
    var iter = node.iter;
    var body = node.body;
    var orelse = node.orelse;

    if (orelse.length > 0) {
        // TODO
        throw new Error("Or-else block of For is not implemented.");
    }

    return block("controls_forEach", {
        "VAR": this.Name_str(target)
    }, {
        "LIST": this.convert(iter)
    }, {
        "inline": "false"
    }, {}, {
        "DO": this.convertBody(body)
    });
}

/*
 * test: expr_ty
 * body: asdl_seq
 * orelse: asdl_seq
 */
PythonToBlocks.prototype.While = function(node) {
    var test = node.test;
    var body = node.body;
    var orelse = node.orelse;
    if (orelse.length > 0) {
        // TODO
        throw new Error("Or-else block of While is not implemented.");
    }
    return block("controls_while", {}, {
        "BOOL": this.convert(test)
    }, {}, {}, {
        "DO": this.convertBody(body)
    });
}

/*
 * test: expr_ty
 * body: asdl_seq
 * orelse: asdl_seq
 *
 */
PythonToBlocks.prototype.If = function(node)
{
    var test = node.test;
    var body = node.body;
    var orelse = node.orelse;

    var IF_values = {"IF0": this.convert(test)};
    var DO_values = {"DO0": this.convertBody(body)};

    var elseifCount = 0;
    var elseCount = 0;
    var potentialElseBody = null;

    // Handle weird orelse stuff
    if (orelse !== undefined) {
        if (orelse.length == 1 && orelse[0]._astname == "If") {
            // This is an 'ELIF'
            while (orelse.length == 1  && orelse[0]._astname == "If") {
                this.heights.shift();
                elseifCount += 1;
                body = orelse[0].body;
                test = orelse[0].test;
                orelse = orelse[0].orelse;
                DO_values["DO"+elseifCount] = this.convertBody(body, false);
                if (test !== undefined) {
                    IF_values["IF"+elseifCount] = this.convert(test);
                }
            }
        }
        if (orelse !== undefined && orelse.length > 0) {
            // Or just the body of an Else statement
            elseCount += 1;
            DO_values["ELSE"] = this.convertBody(orelse);
        }
    }

    return block("controls_if", {
    }, IF_values, {
        "inline": "false"
    }, {
        "@elseif": elseifCount,
        "@else": elseCount
    }, DO_values);
}

/*
 * context_expr: expr_ty
 * optional_vars: expr_ty
 * body: asdl_seq
 */
PythonToBlocks.prototype.With = function(node)
{
    var context_expr = node.context_expr;
    var optional_vars = node.optional_vars;
    var body = node.body;
    throw new Error("With_ not implemented");
}

/*
 * type: expr_ty
 * inst: expr_ty
 * tback: expr_ty
 */
PythonToBlocks.prototype.Raise = function(node)
{
    var type = node.type;
    var inst = node.inst;
    var tback = node.tback;
    throw new Error("Raise not implemented");
}

/*
 * body: asdl_seq
 * handlers: asdl_seq
 * orelse: asdl_seq
 *
 */
PythonToBlocks.prototype.TryExcept = function(node)
{
    var body = node.body;
    var handlers = node.handlers;
    var orelse = node.orelse;
    throw new Error("TryExcept not implemented");
}

/*
 * body: asdl_seq
 * finalbody: asdl_seq
 *
 */
PythonToBlocks.prototype.TryFinally = function(node)
{
    var body = node.body;
    var finalbody = node.finalbody;
    throw new Error("TryExcept not implemented");
}

/*
 * test: expr_ty
 * msg: expr_ty
 */
PythonToBlocks.prototype.Assert = function(node)
{
    var test = node.test;
    var msg = node.msg;
    throw new Error("Assert not implemented");
}

/*
 * names: asdl_seq
 *
 */
PythonToBlocks.prototype.Import = function(node)
{
    var names = node.names;
    // The import statement isn't used in blockly because it happens implicitly
    return null;
}

/*
 * module: identifier
 * names: asdl_seq
 * level: int
 *
 */
PythonToBlocks.prototype.ImportFrom = function(node)
{
    var module = node.module;
    var names = node.names;
    var level = node.level;
    // The import statement isn't used in blockly because it happens implicitly
    return null;
}

/*
 * body: expr_ty
 * globals: expr_ty
 * locals: expr_ty
 *
 */
PythonToBlocks.prototype.Exec = function(node) {
    var body = node.body;
    var globals = node.globals;
    var locals = node.locals;
    throw new Error("Exec not implemented");
}

/*
 * names: asdl_seq
 *
 */
PythonToBlocks.prototype.Global = function(node)
{
    var names = node.names;
    throw new Error("Globals not implemented");
}

/*
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.Expr = function(node, is_top_level) {
    var value = node.value;

    var converted = this.convert(value);
    if (converted.constructor == Array) {
        return converted[0];
    } else if (is_top_level === true) {
        return [this.convert(value)];
    } else {
        return block("raw_empty", {}, {
            "VALUE": this.convert(value)
        });
    }
}

/*
 *
 *
 */
PythonToBlocks.prototype.Pass = function() {
    return null; //block("controls_pass");
}

/*
 *
 *
 */
PythonToBlocks.prototype.Break = function() {
    return block("controls_flow_statements", {
        "FLOW": "BREAK"
    });
}

/*
 *
 *
 */
PythonToBlocks.prototype.Continue = function() {
    return block("controls_flow_statements", {
        "FLOW": "CONTINUE"
    });
}

/*
 * TODO: what does this do?
 *
 */
PythonToBlocks.prototype.Debugger = function() {
    return null;
}

PythonToBlocks.prototype.booleanOperator = function(op) {
    switch (op.name) {
        case "And": return "AND";
        case "Or": return "OR";
        default: throw new Error("Operator not supported:"+op.name);
    }
}

/*
 * op: boolop_ty
 * values: asdl_seq
 */
PythonToBlocks.prototype.BoolOp = function(node) {
    var op = node.op;
    var values = node.values;
    // TODO: is there ever a case where it's != 2 values?
    return block("logic_operation", {
        "OP": this.booleanOperator(op)
    }, {
        "A": this.convert(values[0]),
        "B": this.convert(values[1])
    }, {
        "inline": "true"
    });
}

PythonToBlocks.prototype.binaryOperator = function(op) {
    switch (op.name) {
        case "Add": return "ADD";
        case "Sub": return "MINUS";
        case "Div": case "FloorDiv": return "DIVIDE";
        case "Mult": return "MULTIPLY";
        case "Pow": return "POWER";
        case "Mod": return "MODULO";
        default: throw new Error("Operator not supported:"+op.name);
    }
}

/*
 * left: expr_ty
 * op: operator_ty
 * right: expr_ty
 */
PythonToBlocks.prototype.BinOp = function(node)
{
    var left = node.left;
    var op = node.op;
    var right = node.right;
    return block("math_arithmetic", {
        "OP": this.binaryOperator(op) // TODO
    }, {
        "A": this.convert(left),
        "B": this.convert(right)
    }, {
        "inline": true
    });
}

/*
 * op: unaryop_ty
 * operand: expr_ty
 */
PythonToBlocks.prototype.UnaryOp = function(node)
{
    var op = node.op;
    var operand = node.operand;
    if (op.name == "Not") {
        return block("logic_negate", {}, {
            "BOOL": this.convert(operand)
        }, {
            "inline": "false"
        });
    } else {
        throw new Error("Other unary operators are not implemented yet.");
    }
}

/*
 * args: arguments__ty
 * body: expr_ty
 */
PythonToBlocks.prototype.Lambda = function(node) {
    var args = node.args;
    var body = node.body;
    throw new Error("Lambda functions are not implemented yet.");
}

/*
 * test: expr_ty
 * body: expr_ty
 * orelse: expr_ty
 */
PythonToBlocks.prototype.IfExp = function(node)
{
    var test = node.test;
    var body = node.body;
    var orelse = node.orelse;
    throw new Error("Inline IF expressions are not implemented yet.");
}

/*
 * keys: asdl_seq
 * values: asdl_seq
 */
PythonToBlocks.prototype.Dict = function(node) {
    var keys = node.keys;
    var values = node.values;

    var keyList = [];
    var valueList = [];
    for (var i = 0; i < keys.length; i+= 1) {
        if (keys[i]._astname != "Str") {
            throw new Error("Dictionary Keys should be Strings.");
        }
        keyList["KEY"+i] = this.Str_value(keys[i]);
        valueList["VALUE"+i] = this.convert(values[i]);
    }

    return block("dicts_create_with", keyList, valueList, {
        "inline": "false"
    }, {
        "@items": keys.length
    });
}

/*
 * elts: asdl_seq
 *
 */
PythonToBlocks.prototype.Set = function(node)
{
    var elts = node.elts;
    throw new Error("Sets are not implemented");
}

/*
 * elt: expr_ty
 * generators: asdl_seq
 */
PythonToBlocks.prototype.ListComp = function(node)
{
    var elt = node.elt;
    var generators = node.generators;
    throw new Error("List Comprehensions are not implemented");
}

/*
 * elt: expr_ty
 * generators: asdl_seq
 */
PythonToBlocks.prototype.SetComp = function(node)
{
    var elt = node.elt;
    var generators = node.generators;
    throw new Error("Set Comprehensions are not implemented");
}

/*
 * key: expr_ty
 * value: expr_ty
 * generators: asdl_seq
 */
PythonToBlocks.prototype.DictComp = function(node)
{
    var key = node.key;
    var value = node.value;
    var generators = node.generators;
    throw new Error("Dictionary Comprehensions are not implemented");
}

/*
 * elt: expr_ty
 * generators: asdl_seq
 */
PythonToBlocks.prototype.GeneratorExp = function(node) {
    var elt = node.elt;
    var generators = node.generators;
    throw new Error("Generator Expresions are not implemented");
}

/*
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.Yield = function(node)
{
    var value = value;
    throw new Error("Yield expression is not implemented");
}

PythonToBlocks.prototype.compareOperator = function(op) {
    switch (op.name) {
        case "Eq": return "EQ";
        case "NotEq": return "NEQ";
        case "Lt": return "LT";
        case "Gt": return "GT";
        case "LtE": return "LTE";
        case "GtE": return "GTE";
        case "In": return "IN";
        case "NotIn": return "NOTIN";
        // Is, IsNot, In, NotIn
        default: throw new Error("Operator not supported:"+op.name);
    }
}

/*
 * left: expr_ty
 * ops: asdl_int_seq
 * asdl_seq: comparators
 */
PythonToBlocks.prototype.Compare = function(node)
{
    var left = node.left;
    var ops = node.ops;
    var comparators = node.comparators;

    if (ops.length != 1) {
        throw new Error("Only one comparison operator is supported");
    } else if (ops[0].name == "In" || ops[0].name == "NotIn") {
        return block("logic_isIn", {
            "OP": this.compareOperator(ops[0])
        }, {
            "ITEM": this.convert(left),
            "LIST": this.convert(comparators[0])
        }, {
            "inline": "true"
        });
    } else {
        return block("logic_compare", {
            "OP": this.compareOperator(ops[0])
        }, {
            "A": this.convert(left),
            "B": this.convert(comparators[0])
        }, {
            "inline": "true"
        });
    }

}

convertStockSymbols = function(symbol) {
    switch (symbol) {
        case 'FB': case "Facebook":
            return "Facebook";
        case "AAPL": case "Apple":
            return "Apple";
        case "MSFT": case "Microsoft":
            return "Microsoft";
        case "GOOG": case "Google":
            return "Google";
        default:
            throw new Error("Unknown Stock Symbol.");
    }
}

toTitleCase = function(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

PythonToBlocks.prototype.KNOWN_MODULES = {
    "weather": {
        "get_temperature": ["weather_temperature", "CITY"],
        "get_report": ["weather_report", "CITY"],
        "get_forecasts": ["weather_forecasts", "CITY"],
        "get_highs_lows": ["weather_highs_lows", "CITY"],
        "get_all_forecasted_temperatures": ["weather_all_forecasts"],
        "get_forecasted_reports": ["weather_report_forecasts", "CITY"]
    },
    "earthquakes": {
        "get": ["earthquake_get", "PROPERTY"],
        "get_both": ["earthquake_both"],
        "get_all": ["earthquake_all"]
    },
    "stocks": {
        "get_current": ["stocks_current", ["TICKER", convertStockSymbols]],
        "get_past": ["stocks_past", ["TICKER", convertStockSymbols]]
    },
    "crime": {
        // STATE = toTitleCase
        "get_property_crimes": ["crime_state", ["STATE", toTitleCase],
                                              ["TYPE", "property"]],
        "get_violent_crimes": ["crime_state",  ["STATE", toTitleCase],
                                              ["TYPE", "violent"]],
        "get_by_year": ["crime_year", "YEAR"],
        "get_all": ["crime_all"]
    },
    "books": {
        "get_all": ["books_get"]
    },
    "plt": {
        "title": ["*plot_title", "TEXT"],
        "show": ["*plot_show"]
    }
};
PythonToBlocks.prototype.KNOWN_FUNCTIONS = ["append", "strip", "rstrip", "lstrip"];
PythonToBlocks.prototype.CallAttribute = function(func, args, keywords, starargs, kwargs) {
    var name = this.identifier(func.attr);
    if (func.value._astname == "Name") {
        var module = this.identifier(func.value.id);
        if (module == "plt" && name == "plot") {
            if (args.length == 1) {
                return [block("plot_line", {}, {
                    "y_values": this.convert(args[0])
                }, {"inline": "false"})];
            } else if (args.length == 2) {
                return [block("plot_lineXY", {}, {
                    "x_values": this.convert(args[0]),
                    "y_values": this.convert(args[1])
                }, {"inline": "false"})];
            } else {
                throw new Error("Incorrect number of arguments to plt.plot");
            }
        } else if (module in this.KNOWN_MODULES && name in this.KNOWN_MODULES[module]) {
            var definition = this.KNOWN_MODULES[module][name];
            var blockName = definition[0];
            var isExpression = true;
            if (blockName.charAt(0) == "*") {
                blockName = blockName.slice(1);
                isExpression = false;
            }
            var fields = {};
            for (var i = 0; i < args.length; i++) {
                var argument = definition[1+i];
                if (typeof argument ==  "string") {
                    fields[argument] = this.Str_value(args[i]);
                } else {
                    var argumentName = argument[0];
                    var argumentMapper = argument[1];
                    fields[argumentName] = argumentMapper(this.Str_value(args[i]));
                }
            }
            for (var i = 1+args.length; i < definition.length; i++) {
                var first = definition[i][0];
                var second = definition[i][1];
                fields[first] = second;
            }
            if (isExpression) {
                return block(blockName, fields);
            } else {
                return [block(blockName, fields)];
            }
        }
    }
    if (this.KNOWN_FUNCTIONS.indexOf(name) > -1) {
        switch (name) {
            case "append":
                if (args.length !== 1) {
                    throw new Error("Incorrect number of arguments to .append");
                }
                // Return as statement
                return [block("lists_append", {}, {
                    "ITEM": this.convert(args[0]),
                    "LIST": this.convert(func.value)
                }, {
                    "inline": "true"
                })];
            case "strip":
                return block("text_trim", { "MODE": "BOTH" },
                    { "TEXT": this.convert(func.value) });
            case "lstrip":
                return block("text_trim", { "MODE": "LEFT" },
                    { "TEXT": this.convert(func.value) });
            case "rstrip":
                return block("text_trim", { "MODE": "RIGHT" },
                    { "TEXT": this.convert(func.value) });
            default: throw new Error("Unknown function call!");
        }
    } else {
        console.log(func, args, keywords, starargs, kwargs);

        /*
        var arguments = {};
        for (var i = 0; i < args.length; i++) {
            arguments["ARGUMENT"+i] = this.convert(args[i]);
        }
        return block("function_call", {"NAME": name}, arguments);*/
        //throw new Error("Unknown function call or not implemented");
    }
}

/*
 * func: expr_ty
 * args: asdl_seq
 * keywords: asdl_seq
 * starargs: expr_ty
 * kwargs: expr_ty
 *
 */
PythonToBlocks.prototype.Call = function(node) {
    var func = node.func;
    var args = node.args;
    var keywords = node.keywords;
    var starargs = node.starargs;
    var kwargs = node.kwargs;

    switch (func._astname) {
        case "Name":
            switch (this.identifier(func.id)) {
                case "print":
                    if (args.length == 1) {
                        return [block("text_print", {}, {
                            "TEXT": this.convert(args[0])})];
                    } else {
                        return [block("text_print_multiple", {},
                            this.convertElements("PRINT", args),
                            {"inline": "true"
                            }, { "@items": args.length})];
                    }
                case "abs":
                    return block("math_single", {"OP": "ABS"}, {"NUM": this.convert(args[0])})
                case "round":
                    return block("math_round", {"OP": "ROUND"}, {"NUM": this.convert(args[0])})
                case "sum":
                    return block("math_on_list", {"OP": "SUM"}, {"LIST": this.convert(args[0])})
                case "min":
                    return block("math_on_list", {"OP": "MIN"}, {"LIST": this.convert(args[0])})
                case "max":
                    return block("math_on_list", {"OP": "MAX"}, {"LIST": this.convert(args[0])})
                case "len":
                    return block("lists_length", {}, {"VALUE": this.convert(args[0])})
                default:
                    if (starargs !== null && starargs.length > 0) {
                        throw new Error("*args (variable arguments) are not implemented yet.");
                    } else if (kwargs !== null && kwargs.length > 0) {
                        throw new Error("**args (keyword arguments) are not implemented yet.");
                    }
                    var arguments = {};
                    var argumentsMutation = {"@name": this.identifier(func.id)};
                    for (var i = 0; i < args.length; i+= 1) {
                        arguments["ARG"+i] = this.convert(args[i]);
                        argumentsMutation[i] = this.convert(args[i]);
                    }
                    return block("procedures_callreturn", {}, arguments, {
                        "inline": "false"
                    }, argumentsMutation);
            }
        // Direct function call
        case "Attribute":
        // Module function call
            return this.CallAttribute(func, args, keywords, starargs, kwargs);
    }
}

/*
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.Repr = function(node)
{
    var value = node.value;
    throw new Error("Repr is not yet implemented");
}

/*
 * n: object
 *
 */
PythonToBlocks.prototype.Num = function(node)
{
    var n = node.n;
    return block("math_number", {"NUM": Sk.ffi.remapToJs(n)});
}

/*
 * s: string
 *
 */
PythonToBlocks.prototype.Str = function(node)
{
    var s = node.s;
    return block("text", {"TEXT": Sk.ffi.remapToJs(s)});
}

PythonToBlocks.prototype.Str_value = function(node) {
    var s = node.s;
    return Sk.ffi.remapToJs(s);
}

/*
 * value: expr_ty
 * attr: identifier
 * ctx: expr_context_ty
 *
 */
PythonToBlocks.prototype.Attribute = function(node)
{
    var value = node.value;
    var attr = node.attr;
    var ctx = node.ctx;

    throw new Error("Attribute access not implemented");
}

/*
 * value: expr_ty
 * slice: slice_ty
 * ctx: expr_context_ty
 *
 */
PythonToBlocks.prototype.Subscript = function(node)
{
    var value = node.value;
    var slice = node.slice;
    var ctx = node.ctx;

    if (slice.value._astname == "Str") {
        return block("dict_get_literal", {
            "ITEM": this.Str_value(slice.value)
        }, {
            "DICT": this.convert(value)
        });
    } else if (slice.value._astname == "Num") {
        return block("lists_index", {}, {
            "ITEM": this.convert(slice.value),
            "LIST": this.convert(value),
        });
    }

    throw new Error("This kind of subscript is not supported.");
}

/*
 * id: identifier
 * ctx: expr_context_ty
 */
PythonToBlocks.prototype.Name = function(node)
{
    var id = node.id;
    var ctx = node.ctx;
    switch (this.Name_str(node)) {
        case "True":
            return block("logic_boolean", {"BOOL": "TRUE"});
        case "False":
            return block("logic_boolean", {"BOOL": "FALSE"});
        case "___":
            return null;
        default:
            return block('variables_get', {
                "VAR": this.identifier(id)
            });
    }
}

/*
 * id: identifier
 * ctx: expr_context_ty
 */
PythonToBlocks.prototype.Name_str = function(node)
{
    var id = node.id;
    var ctx = node.ctx;
    return this.identifier(id);
}

PythonToBlocks.prototype.convertElements = function(key, values) {
    var output = {};
    for (var i = 0; i < values.length; i++) {
        output[key+i] = this.convert(values[i]);
    }
    return output;
}

/*
 * elts: asdl_seq
 * ctx: expr_context_ty
 *
 */
PythonToBlocks.prototype.List = function(node) {
    var elts = node.elts;
    var ctx = node.ctx;

    return block("lists_create_with", {},
        this.convertElements("ADD", elts)
    , {
        "inline": "false"
    }, {
        "@items": elts.length
    });
}

/*
 * elts: asdl_seq
 * ctx: expr_context_ty
 */
PythonToBlocks.prototype.Tuple = function(node)
{
    var elts = node.elts;
    var ctx = node.ctx;

    throw new Error("Tuples not implemented");
}

/*
 *
 *
 */
PythonToBlocks.prototype.Ellipsis = function() {
    throw new Error("Ellipsis not implemented");
}

/*
 * lower: expr_ty
 * upper: expr_ty
 * step: expr_ty
 *
 */
PythonToBlocks.prototype.Slice = function(node)
{
    var lower = node.lower;
    var upper = node.upper;
    var step = node.step;

    throw new Error("Slices not implemented");
}

/*
 * dims: asdl_seq
 *
 */
PythonToBlocks.prototype.ExtSlice = function(node)
{
    var dims = node.dims;

    throw new Error("ExtSlice is not implemented.");
}

/*
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.Index = function(value)
{
    var value = node.value;

    throw new Error("Index is not implemented");
}

/*
 * target: expr_ty
 * iter: expr_ty
 * ifs: asdl_seq
 *
 */
PythonToBlocks.prototype.comprehension = function(node)
{
    var target = node.target;
    var iter = node.iter;
    var ifs = node.ifs;

    throw new Error("Comprehensions not implemented.");
}

/*
 * type: expr_ty
 * name: expr_ty
 * body: asdl_seq
 *
 */
PythonToBlocks.prototype.ExceptHandler = function(node)
{
    var type = node.type;
    var name = node.name;
    var body = node.boy;

    throw new Error("Except handlers are not implemented");
}

PythonToBlocks.prototype.argument_ = function(node) {
    var id = node.id;
    return this.identifier(id);
}

/*
 * args: asdl_seq
 * vararg: identifier
 * kwarg: identifier
 * defaults: asdl_seq
 *
 */
PythonToBlocks.prototype.arguments_ = function(node)
{
    var args = node.args;
    var vararg = node.vararg;
    var kwarg = node.kwarg;
    var defaults = node.defaults;

    var allArgs = [];
    for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        allArgs.push(this.argument_(arg));
    }
    return allArgs;
}

/*
 * arg: identifier
 * value: expr_ty
 *
 */
PythonToBlocks.prototype.keyword = function(node)
{
    var arg = node.arg;
    var value = node.value;

    throw new Error("Keywords are not implemented");
}

/*
 * name: identifier
 * asname: identifier
 *
 */
PythonToBlocks.prototype.alias = function(node)
{
    var name = node.name;
    var asname = node.asname;

    throw new Error("Aliases are not implemented");
}

/* ----- expr_context ----- */
/*
Load
Store
Del
AugLoad
AugStore
Param
*/

/* ----- operator ----- */
/*
Add
Sub
Mult
Div
Mod
Pow
LShift
RShift
BitOr
BitXor
BitAnd
FloorDiv
*/

/* ----- unaryop ----- */
/*
Invert
Not
UAdd
USub
*/


text:
package fi.csc.chipster.rest.exception;

import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

import org.hibernate.ObjectNotFoundException;

/**
 * Don't log client errors
 *
 * @author klemela
 */
@Provider
public class ObjectNotFoundExceptionMapper implements ExceptionMapper<ObjectNotFoundException> {

	@Override
	public Response toResponse(ObjectNotFoundException e) {
		// client error, no need to log
		return Response.status(Status.NOT_FOUND).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sysds.conf;

import org.apache.hadoop.mapred.JobConf;
import org.apache.sysds.conf.CompilerConfig.ConfigType;
import org.apache.sysds.lops.Compression.CompressConfig;

/**
 * Singleton for accessing the parsed and merged system configuration.
 *
 * NOTE: parallel execution of multiple DML scripts (in the same JVM) with different configurations
 *       would require changes/extensions of this class.
 */
public class ConfigurationManager
{
	/** Global cached job conf for read-only operations */
	private static JobConf _rJob = null;

	/** Global DML configuration (read or defaults) */
	private static DMLConfig _dmlconf = null;

	/** Local DML configuration for thread-local config updates */
	private static ThreadLocalDMLConfig _ldmlconf = new ThreadLocalDMLConfig();

	/** Global compiler configuration (defaults) */
	private static CompilerConfig _cconf = null;

	/** Local compiler configuration for thead-local config updates */
	private static ThreadLocalCompilerConfig _lcconf = new ThreadLocalCompilerConfig();

	//global static initialization
	static {
		_rJob = new JobConf();

		//initialization after job conf in order to prevent cyclic initialization issues
		//ConfigManager -> OptimizerUtils -> InfrastructureAnalyer -> ConfigManager
 		_dmlconf = new DMLConfig();
		_cconf = new CompilerConfig();
	}

	/**
	 * Returns a cached JobConf object, intended for global use by all operations
	 * with read-only access to job conf. This prevents to read the hadoop conf files
	 * over and over again from classpath. However,
	 *
	 * @return the cached JobConf
	 */
	public static JobConf getCachedJobConf() {
		return _rJob;
	}

	public static void setCachedJobConf(JobConf job) {
		_rJob = job;
	}

	/**
	 * Sets a global configuration as a basis for any thread-local configurations.
	 * NOTE: This global configuration should never be accessed directly but only
	 * through its thread-local derivatives.
	 *
	 * @param conf the configuration
	 */
	public synchronized static void setGlobalConfig( DMLConfig conf ) {
		_dmlconf = conf;

		//reinitialize thread-local dml configs w/ _dmlconf
		_ldmlconf = new ThreadLocalDMLConfig();
	}

	/**
	 * Sets the current thread-local dml configuration to the given config.
	 *
	 * @param conf the configuration
	 */
	public static void setLocalConfig( DMLConfig conf ) {
		_ldmlconf.set(conf);
	}

	/**
	 * Gets the current thread-local dml configuration.
	 *
	 * @return the dml configuration
	 */
	public static DMLConfig getDMLConfig() {
		return _ldmlconf.get();
	}

	public synchronized static void setGlobalConfig( CompilerConfig conf ) {
		_cconf = conf;

		//reinitialize thread-local compiler configs w/ _cconf
		_lcconf = new ThreadLocalCompilerConfig();
	}

	/**
	 * Sets the current thread-local compiler configuration to the given config.
	 *
	 * @param conf the compiler configuration
	 */
	public static void setLocalConfig( CompilerConfig conf ) {
		_lcconf.set(conf);
	}

	/**
	 * Removes the thread-local dml and compiler configurations, leading to
	 * a reinitialization on the next get unless set in between.
	 */
	public static void clearLocalConfigs() {
		_ldmlconf.remove();
		_lcconf.remove();
	}

	/**
	 * Gets the current thread-local compiler configuration.
	 *
	 * @return the compiler configuration
	 */
	public static CompilerConfig getCompilerConfig() {
		return _lcconf.get();
	}

	/**
	 * Get a boolean compiler config in a robust manner,
	 * returning false if config not existing.
	 *
	 * @param key config type
	 * @return compiler config flag
	 */
	public static boolean getCompilerConfigFlag(ConfigType key) {
		CompilerConfig cconf = getCompilerConfig();
		return (cconf!=null) ? cconf.getBool(key) : false;
	}

	/////////////////////////////////////
	// shorthand methods for common local configurations

	public static String getScratchSpace() {
		return getDMLConfig().getTextValue(DMLConfig.SCRATCH_SPACE);
	}

	public static int getBlocksize() {
		return getCompilerConfig().getInt(ConfigType.BLOCK_SIZE);
	}

	public static boolean isDynamicRecompilation() {
		return getCompilerConfigFlag(ConfigType.ALLOW_DYN_RECOMPILATION);
	}

	public static boolean isParallelMatrixOperations() {
		return getCompilerConfigFlag(ConfigType.PARALLEL_CP_MATRIX_OPERATIONS);
	}

	public static boolean isParallelTransform() {
		return getDMLConfig().getBooleanValue(DMLConfig.PARALLEL_ENCODE);
	}

	public static boolean isStagedParallelTransform() {
		return getDMLConfig().getBooleanValue(DMLConfig.PARALLEL_ENCODE_STAGED);
	}

	public static int getParallelApplyBlocks(){
		return getDMLConfig().getIntValue(DMLConfig.PARALLEL_ENCODE_APPLY_BLOCKS);
	}

	public static int getParallelBuildBlocks(){
		return getDMLConfig().getIntValue(DMLConfig.PARALLEL_ENCODE_BUILD_BLOCKS);
	}

	public static int getNumThreads() {
		return getDMLConfig().getIntValue(DMLConfig.PARALLEL_ENCODE_NUM_THREADS);
	}

	public static boolean isParallelParFor() {
		return getCompilerConfigFlag(ConfigType.PARALLEL_LOCAL_OR_REMOTE_PARFOR);
	}

	public static boolean isCodegenEnabled() {
		return (getDMLConfig().getBooleanValue(DMLConfig.CODEGEN)
			|| getCompilerConfigFlag(ConfigType.CODEGEN_ENABLED));
	}

	public static boolean isCompressionEnabled(){
		CompressConfig compress = CompressConfig.valueOf(getDMLConfig().getTextValue(DMLConfig.COMPRESSED_LINALG).toUpperCase());
		return compress.isEnabled();
	}

	///////////////////////////////////////
	// Thread-local classes

	private static class ThreadLocalDMLConfig extends ThreadLocal<DMLConfig> {
		@Override
		protected DMLConfig initialValue() {
			//currently initialize by reference to avoid unnecessary deep copy via clone.
			if( _dmlconf != null )
				return _dmlconf;
			return null;
		}
	}

	private static class ThreadLocalCompilerConfig extends ThreadLocal<CompilerConfig> {
		@Override
		protected CompilerConfig initialValue() {
			if( _cconf != null )
				return _cconf.clone();
			return null;
		}
	}
}


text:
A [Notational Velocity][nv] inspired mode for [vim][].

## Requirements
This should work on any recent vim compiled with `+python3`. You will also need the [xapian][] library and python bindings.

## Installation
Easiest way is to use [pathogen][]:

````
cd ~/.vim/bundle
git clone git://github.com/cwoac/nvvim.git
````

Or if you manage things yourself, copy `nvvim.vim` into your `~/.vim/plugins` directory and `nvvim.py` into `~/.vim/python`

### Script

NVim is not intended to be used in every vim session you open; to this end it will not be activated until you `:Nvim`

There is a supplied script `nvvim` which will open vim and call this to drop you directly into nvvim mode; simply copy it to somewhere on your path

## Usage

I've made a quick screencast [here](http://showterm.io/3668688fe06b53482da16) outlining basic usage.

nvvim stores its notes and database within a single directory. Either:

* export `NVIM_HOME=path/to/directory` and run `nvvim`.
* run `nvvim path/to/directory` or
* run `nvvim` from within that directory.

You will then be presented with two windows - on the right is the main pane where the note is displayed; on the left the list of search results.
The first line of the search box is the current search term.

Use `[[` to trigger vim's auto-complete with the list of available titles.

nvvim binds several keys, all combos are started with the user's defined `<leader>` key. If you haven't changed this, then it is `\` by default.

* `\<F5>`  Invoke NVIM on the current directory. This is the only key bound until NVIM has been invoked once. Hitting it a second time will do nothing.
* `\<cr>`  This will follow a '[[...]]' link from within a note.
* `\l` Move the cursor to the search area ready for changes.
* `\i` As `\l`, but clears the current search term first (equivalent to `<esc>` on NV as remapping escape in vim is... unwise)
* `\d` Delete a note. **warning** This will delete the note pointed to by the search bar. Under normal usage this should be correct.
 It does not currently ask confirmation.
* `\r` Rename a note. This will *not* update any links in other notes.

Note that if you try an load a note that does not exist, the system will create a new one.

The full range of vim commands are available to you, but there are a couple of things to bear in mind:

* Autosave is turned on
* You can create new windows via splits or whatever as you wish - when a note is loaded from the search results it will be loaded into the most recently used window.
* If you close the results window (or all windows apart from the results window) you will need to close and reopen vim.
* If you delete a note or alter the contents of notes outside of nvvim, then you can refresh the database as under _importing_ below.

### Configuration
Most of the configuration is handled at the top of `nvvim.vim`. These are:

* `NVIM_extension` - the extension to use for files, and hence vim filetype detection. nvvim will ignore any files in the directory that do not end with this.
* `NVIM_language` - the language stemmer to use when parsing notes (requires xapian 1.1+). The list of availiable languages/stemmers depends on your version of xapian, but the normal set is listed [here](http://xapian.org/docs/apidoc/html/classXapian_1_1Stem.html#0f8f250587dfef35d47f13f0ec0028fb).
* `NVIM_side` - which side of the screen the sidebar should be on. Defaults to the left.
* `NVIM_database` - the name for the directory used to store note metadata. You probably shouldn't change this unless you are fairly sure you know what you are doing.
* `NVIM_interactive` - Whether to map the leader based commands in interactive mode.

If you use vim under a different name (e.g. `mvim` for macvim) then you can still use the nvvim script by setting the `NVIM_EDITOR` environment variable.

by default nvvim allows multiple note directories. The downside to this is it requires being run from the directory containing all your notes.
If you would rather have a single note directory, then you can shorthand this by setting the `NVIM_HOME` environment variable and using the nvvim script.

### Importing
If you have a bunch of notes already, then execute the following command to import them `:python nvimdb.rebuild_database()`.

## Contributing
Contributions are welcome; just submit a normal pull request. By doing so you assert that these changes are yours to submit and that you are providing these changes 'as-is' and that I may do whatever I wish with them.

## Renaming
Due to the ever increasing popularity of Neovim and it's choice to pick nvim as it's shortname, I have renamed this to nvvim to avoid conflicts.

### Contributors
Thanks to:

[@Nixon](https://github.com/Nixon)
[@AzizLight](https://github.com/AzizLight)
[@Keithbsmiley](https://github.com/Keithbsmiley)
[@colons](https://github.com/colons)
[@shoaibkamil](https://github.com/shoaibkamil)
[@eklenske](https://github.com/eklenske)

### dynamic python (i.e. Arch Linux)
If your installation of vim is compiled using dynamic linking (e.g. Arch linux), then nvvim requires libpython3.so to be preloaded or it won't work. the `nvvim` script should handle this for you. If you are invoking nvvim by hand, set `LD_PRELOAD=/path/to/libpython3.so`. The script assumes this file is in `/usr/lib/libpython3.so`, which is the normal location. If for some reason it is elsewhere, then you will need to set the `NVIM_PYTHON3_SO` environment variable accordingly.
This may have some additional unintended consequences - for one thing, plugins which depend on python2 will almost certainly crash vim while using nvvim via dynamic python3.

### Nixos

I have added a default.nix for development under nixos. To use, switch to the src directory and run `nix-shell --pure`

## TODO
Quite a few things, although the code is quite usable as-is.

* Allow hiding/reshowing the search results
* Some proper documentation (screencasts!)

 [nv]: http://www.notational.net
 [vim]: http://www.vim.org
 [xapian]: http://xapian.org
 [pathogen]: https://github.com/tpope/vim-pathogen


text:
#include "Dlg_StructureEditor.h"
#include <QString>

Dlg_StructureEditor::Dlg_StructureEditor(CQDM_Edit* pEditIn, QWidget *parent)
	: QWidget(parent)
{
	pEdit = pEditIn;
	ui.setupUi(this);

	QGLFormat format; // double buffering and depth buffering is turned on in the default format, so no need to reset those
	pGLWin = new CQOpenGL(format);
	ui.horizontalLayout->addWidget(pGLWin);
	resize(500, 300);
	SetupRef3DWindow();

////
//	connect(GLWindow, SIGNAL(FindDims(Vec3D*)), &MainObj, SLOT(GetDim(Vec3D*)));
//	connect(GLWindow, SIGNAL(DrawGL()), this, SLOT(DrawCurScene()));
//	connect(GLWindow, SIGNAL(MousePressIndex(int)), this, SLOT(SetGLSelected(int)));
//
//	//mouse handling
//	connect(GLWindow, SIGNAL(WantGLIndex(bool*)), this, SLOT(WantGLIndex(bool*)));
//	connect(GLWindow, SIGNAL(WantCoord3D(bool*)), this, SLOT(WantCoord3D(bool*)));
//
//	connect(GLWindow, SIGNAL(MouseMoveHover(float, float, float)), this, SLOT(HoverMove(float, float, float)));
//	connect(GLWindow, SIGNAL(LMouseMovePressed(float, float, float)), this, SLOT(LMouseDownMove(float, float, float)));
//	connect(GLWindow, SIGNAL(LMouseDown(float, float, float)), this, SLOT(LMouseDown(float, float, float)));
//	connect(GLWindow, SIGNAL(LMouseUp(float, float, float)), this, SLOT(LMouseUp(float, float, float)));
//	connect(GLWindow, SIGNAL(PressedEscape()), this, SLOT(PressedEscape()));
//	connect(GLWindow, SIGNAL(CtrlWheelRoll(bool)), this, SLOT(CtrlMouseRoll(bool)));
////

	connect(pGLWin, SIGNAL(FindDims(Vec3D<>*, Vec3D<>*)), pEdit, SLOT(GetDim(Vec3D<>*, Vec3D<>*)));
	connect(pGLWin, SIGNAL(DrawGL(bool)), pEdit, SLOT(DrawSceneEdit(bool)));

	connect(pGLWin, SIGNAL(WantGLIndex(bool*)), this, SLOT(WantGLIndex(bool*)));
	connect(pGLWin, SIGNAL(WantCoord3D(bool*)), this, SLOT(WantCoord3D(bool*)));
//	connect(pGLWin, SIGNAL(IsExtScene2D(bool*)), this, SLOT(IsEditMode(bool*)));

	connect(pGLWin, SIGNAL(MouseMoveHover(float, float, float)), this, SLOT(HoverMove(float, float, float)));
	connect(pGLWin, SIGNAL(LMouseMovePressed(float, float, float)), this, SLOT(LMouseDownMove(float, float, float)));
	connect(pGLWin, SIGNAL(LMouseDown(float, float, float, bool)), this, SLOT(LMouseDown(float, float, float, bool)));
	connect(pGLWin, SIGNAL(LMouseUp(float, float, float)), this, SLOT(LMouseUp(float, float, float)));
	connect(pGLWin, SIGNAL(PressedEscape()), this, SLOT(PressedEscape()));
	connect(pGLWin, SIGNAL(CtrlWheelRoll(bool)), this, SLOT(CtrlMouseRoll(bool)));

	connect(pEdit, SIGNAL(UpdateGLWindows()), this, SLOT(UpdateGLWins()));
	connect(pEdit, SIGNAL(GetCurMaterial(int*)), this, SLOT(CurMaterial(int*)));

	//connect this! void GetCurMaterial(int* MatIndex);

	//UI handlers:
	connect(ui.pencilButton, SIGNAL(clicked()), this, SLOT(ClickedPencil()));
	connect(ui.squareButton, SIGNAL(clicked()), this, SLOT(ClickedBox()));
	connect(ui.ellipseButton, SIGNAL(clicked()), this, SLOT(ClickedEllipse()));
	connect(ui.layerbackButton, SIGNAL(clicked()), this, SLOT(ClickedLayerBack()));
	connect(ui.layerforwardButton, SIGNAL(clicked()), this, SLOT(ClickedLayerForward()));
	connect(ui.refviewButton, SIGNAL(clicked(bool)), this, SLOT(ClickedRefView(bool)));

	IniUpdateUI();

}

Dlg_StructureEditor::~Dlg_StructureEditor()
{
}

void Dlg_StructureEditor::IniUpdateUI()
{
	pGLWin->SetViewTop();
	pGLWin->GLCenterView(); //necessary because view is already top...
	pEdit->SetV2DTop();
	pEdit->SetSectionView();

	//initial ui update (things that won't change...)
	ui.MatList->clear();
	for (int i=0; i<pEdit->GetNumMaterials(); i++){
		QString Name = QString(pEdit->Palette[i].GetName().c_str());
		ui.MatList->addItem(Name);
		QPixmap tmpMap = QPixmap(16, 16);
		tmpMap.fill(QColor(pEdit->Palette[i].GetRedi(), pEdit->Palette[i].GetGreeni(), pEdit->Palette[i].GetBluei()));
		ui.MatList->item(i)->setIcon(QIcon(tmpMap));
		if (Name.endsWith("(Editing)", Qt::CaseInsensitive)) ui.MatList->item(i)->setFlags(NULL);
		if (Name.endsWith("(Recursive)", Qt::CaseInsensitive)) ui.MatList->item(i)->setFlags(NULL);
	}
	ui.MatList->setCurrentRow(0); //set to erase material
	UpdateUI();
}

void Dlg_StructureEditor::ClickedPencil(void)
{
	pEdit->SetDrawPencil();
	UpdateUI();

}

void Dlg_StructureEditor::ClickedBox(void)
{
	pEdit->SetDrawRectangle();
	UpdateUI();
}

void Dlg_StructureEditor::ClickedEllipse(void)
{
	pEdit->SetDrawCircle();
	UpdateUI();
}

void Dlg_StructureEditor::ClickedLayerBack(void)
{
	pEdit->LayerBack();
	UpdateUI();

}

void Dlg_StructureEditor::ClickedLayerForward(void)
{
	pEdit->LayerForward();
	UpdateUI();

}

void Dlg_StructureEditor::ClickedRefView(bool State)
{
	if (RefWin->isVisible()) RefWin->hide();
	else {
		GLRef3DWin->GLCenterView();
		RefWin->show();
	}
}

void Dlg_StructureEditor::UpdateUI()
{
	ui.pencilButton->setChecked(false);
	ui.ellipseButton->setChecked(false);
	ui.squareButton->setChecked(false);

	if (pEdit->GetCurDrawTool() == DT_PEN) ui.pencilButton->setChecked(true);
	if (pEdit->GetCurDrawTool() == DT_BOX) ui.squareButton->setChecked(true);
	if (pEdit->GetCurDrawTool() == DT_ELLIPSE) ui.ellipseButton->setChecked(true);

	UpdateGLWins();
}

void Dlg_StructureEditor::SetupRef3DWindow(void)
{
	RefWin = new QDialog(this);
	QHBoxLayout* HorLayout = new QHBoxLayout(RefWin);

	QGLFormat format; // double buffering and depth buffering is turned on in the default format, so no need to reset those
	GLRef3DWin = new CQOpenGL(format);
	HorLayout->addWidget(GLRef3DWin);
	GLRef3DWin->SetViewCustom1();
	GLRef3DWin->setWindowTitle("3D View");

	connect(GLRef3DWin, SIGNAL(FindDims(Vec3D<>*, Vec3D<>*)), pEdit, SLOT(GetDim(Vec3D<>*, Vec3D<>*)));
	connect(GLRef3DWin, SIGNAL(DrawGL(bool)), pEdit, SLOT(DrawSceneView(bool)));

	QRect GLFrame = pGLWin->geometry();
	RefWin->setGeometry(GLFrame.x()+400, GLFrame.y()+50, 300, 200);

	//GLRef3DWin->
//	GLRef3DWin->hide();
//	GLRef3DWin->setFloating(true);
//	GLRef3DWin->setGeometry (Ref3DDockWidget->parentWidget()->geometry().x()+10,Ref3DDockWidget->parentWidget()->geometry().y()+80,340,280 );

}


text:
Data.UnhostedGraph = function(graph) {
  this.graph = new Data.Graph(graph);

  this.dirtyNodes = [];
}

_.extend(Data.UnhostedGraph.prototype, _.Events {

  set: function(n) {
    var node = this.graph.set(n);
    return node ? this.dirtyNodes.push(node) : null;
  },

  get: function(id) {
    return this.graph.get(id);
  },

  sync: function() {
    // send dirty nodes to the server.
  }
});


text:
package io.rsocket;

import static io.rsocket.FrameType.CANCEL;
import static io.rsocket.FrameType.KEEPALIVE;
import static io.rsocket.FrameType.NEXT_COMPLETE;
import static io.rsocket.FrameType.REQUEST_RESPONSE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

import io.reactivex.subscribers.TestSubscriber;
import io.rsocket.exceptions.ApplicationException;
import io.rsocket.exceptions.RejectedSetupException;
import io.rsocket.util.PayloadImpl;
import java.util.ArrayList;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Mono;

public class RSocketClientTest {

  @Rule public final ClientSocketRule rule = new ClientSocketRule();

  //@Test(timeout = 2_000)
  public void testKeepAlive() throws Exception {
    rule.keepAliveTicks.onNext(1L);
    assertThat("Unexpected frame sent.", rule.connection.awaitSend().getType(), is(KEEPALIVE));
  }

  @Test(timeout = 2_000)
  public void testInvalidFrameOnStream0() throws Throwable {
    rule.connection.addToReceivedBuffer(Frame.RequestN.from(0, 10));
    assertThat("Unexpected errors.", rule.errors, hasSize(1));
    assertThat(
        "Unexpected error received.",
        rule.errors,
        contains(instanceOf(IllegalStateException.class)));
  }

  @Test(timeout = 2_000)
  public void testHandleSetupException() throws Throwable {
    rule.connection.addToReceivedBuffer(Frame.Error.from(0, new RejectedSetupException("boom")));
    assertThat("Unexpected errors.", rule.errors, hasSize(1));
    assertThat(
        "Unexpected error received.",
        rule.errors,
        contains(instanceOf(RejectedSetupException.class)));
  }

  @Test(timeout = 2_000)
  public void testHandleApplicationException() throws Throwable {
    rule.connection.clearSendReceiveBuffers();
    Publisher<Payload> response = rule.socket.requestResponse(PayloadImpl.EMPTY);
    TestSubscriber<Payload> responseSub = TestSubscriber.create();
    response.subscribe(responseSub);

    int streamId = rule.getStreamIdForRequestType(REQUEST_RESPONSE);
    rule.connection.addToReceivedBuffer(
        Frame.Error.from(streamId, new ApplicationException(PayloadImpl.EMPTY)));

    responseSub.assertError(ApplicationException.class);
  }

  @Test(timeout = 2_000)
  public void testHandleValidFrame() throws Throwable {
    Publisher<Payload> response = rule.socket.requestResponse(PayloadImpl.EMPTY);
    TestSubscriber<Payload> responseSub = TestSubscriber.create();
    response.subscribe(responseSub);

    int streamId = rule.getStreamIdForRequestType(REQUEST_RESPONSE);
    rule.connection.addToReceivedBuffer(
        Frame.PayloadFrame.from(streamId, NEXT_COMPLETE, PayloadImpl.EMPTY));

    responseSub.assertValueCount(1);
    responseSub.assertComplete();
  }

  @Test
  public void testRequestReplyWithCancel() throws Throwable {
    rule.connection.clearSendReceiveBuffers(); // clear setup frame
    Publisher<Payload> response = rule.socket.requestResponse(PayloadImpl.EMPTY);
    TestSubscriber<Payload> responseSub = TestSubscriber.create(0);
    response.subscribe(responseSub);
    responseSub.cancel();

    responseSub.assertValueCount(0);
    responseSub.assertNotTerminated();

    assertThat(
        "Unexpected frame sent on the connection.",
        rule.connection.awaitSend().getType(),
        is(REQUEST_RESPONSE));
    assertThat(
        "Unexpected frame sent on the connection.",
        rule.connection.awaitSend().getType(),
        is(CANCEL));
  }

  @Test(timeout = 2_000)
  public void testRequestReplyErrorOnSend() throws Throwable {
    rule.connection.setAvailability(0); // Fails send
    Mono<Payload> response = rule.socket.requestResponse(PayloadImpl.EMPTY);
    TestSubscriber<Payload> responseSub = TestSubscriber.create();
    response.subscribe(responseSub);

    responseSub.assertError(RuntimeException.class);
  }

  @Test
  public void testLazyRequestResponse() throws Exception {
    Publisher<Payload> response = rule.socket.requestResponse(PayloadImpl.EMPTY);
    int streamId = sendRequestResponse(response);
    rule.connection.clearSendReceiveBuffers();
    int streamId2 = sendRequestResponse(response);
    assertThat("Stream ID reused.", streamId2, not(equalTo(streamId)));
  }

  public int sendRequestResponse(Publisher<Payload> response) {
    TestSubscriber<Payload> sub = TestSubscriber.create();
    response.subscribe(sub);
    int streamId = rule.getStreamIdForRequestType(REQUEST_RESPONSE);
    rule.connection.addToReceivedBuffer(
        Frame.PayloadFrame.from(streamId, NEXT_COMPLETE, PayloadImpl.EMPTY));
    sub.assertValueCount(1).assertNoErrors();
    return streamId;
  }

  public static class ClientSocketRule extends AbstractSocketRule<RSocketClient> {

    private final DirectProcessor<Long> keepAliveTicks = DirectProcessor.create();

    @Override
    protected RSocketClient newRSocket() {
      return new RSocketClient(
          connection, throwable -> errors.add(throwable), StreamIdSupplier.clientSupplier());
    }

    public int getStreamIdForRequestType(FrameType expectedFrameType) {
      assertThat("Unexpected frames sent.", connection.getSent(), hasSize(greaterThanOrEqualTo(1)));
      List<FrameType> framesFound = new ArrayList<>();
      for (Frame frame : connection.getSent()) {
        if (frame.getType() == expectedFrameType) {
          return frame.getStreamId();
        }
        framesFound.add(frame.getType());
      }
      throw new AssertionError(
          "No frames sent with frame type: "
              + expectedFrameType
              + ", frames found: "
              + framesFound);
    }
  }
}


text:
Method Reflect
---------------

© Danny Purcell 2014 | MIT license

Gives Ruby Methods some deeper self-knowledge.

Features
---------------

Loading this gem adds several instance methods to the core Method class so methods can tell you more about themselves.

Leverages [YARD](https://github.com/lsegal/yard) and [method_source](https://github.com/banister/method_source) to
provide easy access to everything you might want to know about a method.

Installation
---------------

#### Install with Gem
* Available on [Rubygems](https://rubygems.org/gems/method_reflect)
* Be sure one of your gem sources is `source 'https://rubygems.org'`
* Run `gem install method_reflect`

#### Building locally
* Fork the repository if you wish
* Clone repository locally
    * If using the main repo: `git clone https://github.com/dannypurcell/method_reflect.git`
* Run `rake install` if installing for the first time
* If updating to the latest version run the following commands
    * `git checkout master`
    * `git pull origin master`
        * If that causes any problems `git reset --hard origin/master`
    * `rake upgrade`


text:
'use strict';

module.exports = {
    websocket: require('./trans-websocket.js')
};


text:
function SmartProperty(property, name, options) {
    this.property = property;
    this.name = name;
    this.options = options;
    this.value = options.value || undefined;
    var beforeGet = typeof options.beforeGet == 'function' ? options.beforeGet : function(val) {return val;};
    var beforeSet = typeof options.beforeSet == 'function' ? options.beforeSet : function(val) {return val;};
    var afterSet = typeof options.afterSet == 'function' ? options.afterSet : function(val) {return val;};

    var value = this.value;
    Object.defineProperty(property, name, {
        enumerable: true,
        get : function() {
            var val = beforeGet(value);
            return val;
        },
        set : function(val) {
            val = beforeSet(val);
            value = val;
            afterSet(value);
        }
    });
}


text:
using namespace hect;

MemoryWriteStream::MemoryWriteStream(ByteVector& data) :
    _data(data),
    _position(data.size())
{
}

void MemoryWriteStream::write(const uint8_t* bytes, size_t byte_count)
{
    assert(bytes);

    while (_position + byte_count > _data.size())
    {
        _data.push_back(0);
    }

    std::memcpy(&_data[_position], bytes, byte_count);
    _position += byte_count;
}

size_t MemoryWriteStream::position() const
{
    return _position;
}

void MemoryWriteStream::seek(size_t position)
{
    size_t length = _data.size();

    if (position >= length + 1)
    {
        throw InvalidOperation("Attempt to seek past end of data");
    }

    _position = position;
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>QSqlQuery Class Reference</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

QSqlQuery Class Reference

[com.trolltech.qt.sql package]

Constructor

void QSqlQuery(QSqlDatabase db)

void QSqlQuery(QSqlResult r)

void QSqlQuery(QSqlQuery other)

void QSqlQuery(String query, QSqlDatabase db)

Constructor Properties

prototype: The QSqlQuery prototype object

ValuesAsRows

ValuesAsColumns

BatchExecutionMode( value )

Prototype Object Properties

void addBindValue(Object val, ParamType type)

int at()

void bindValue(String placeholder, Object val, ParamType type)

Object boundValue(String placeholder)

SortedMap boundValues()

void clear()

QSqlDriver driver()

bool exec()

bool execBatch(BatchExecutionMode mode)

String executedQuery()

void finish()

bool first()

bool isActive()

bool isForwardOnly()

bool isNull(int field)

bool isSelect()

bool isValid()

bool last()

QSqlError lastError()

Object lastInsertId()

String lastQuery()

bool next()

bool nextResult()

int numRowsAffected()

NumericalPrecisionPolicy numericalPrecisionPolicy()

bool prepare(String query)

bool previous()

QSqlRecord record()

QSqlResult result()

bool seek(int i, bool relative)

void setForwardOnly(bool forward)

void setNumericalPrecisionPolicy(NumericalPrecisionPolicy precisionPolicy)

int size()

Object value(String name)

Instance Properties

QSqlQuery objects have no special properties beyond those inherited from the QSqlQuery prototype object.


text:
import { sendMessage, UserAction, TargetAngle } from './communicationLayer';
import { globalState, renderer } from './globals';

var mouseDown = false;
var lastTargetAngle = null;

const KEY_SPACE = 32;
const KEY_UP    = 38;
const KEY_LEFT  = 37;
const KEY_RIGHT = 39;
const KEY_W     = 87;
const KEY_A     = 65;
const KEY_D     = 68;
const KEY_SHIFT = 16;

const keysDown = new Map();

keysDown.set(KEY_SPACE, false);
keysDown.set(KEY_UP,    false);
keysDown.set(KEY_LEFT,  false);
keysDown.set(KEY_RIGHT, false);
keysDown.set(KEY_W, false);
keysDown.set(KEY_A, false);
keysDown.set(KEY_D, false);
keysDown.set(KEY_SHIFT, false);

const updateKeysState = (keyCode, isPressed) => {
  const lastState = keysDown.get(keyCode);
  if (lastState === undefined) {
    return;
  }

  if (lastState !== isPressed) {
    keysDown.set(keyCode, isPressed);
    sendInput(keyCode, isPressed);
  }
}

const updateMouseState = (isDown) => {
  if (mouseDown !== isDown) {
    mouseDown = isDown;

    let userAction = new UserAction(isDown ? "TURRET_FIRE_START" : "FIRE_STOP");
    sendMessage(userAction);
  }
}

const updateMousePosition = (event) => {
  globalState.crosshair.update(event.x, event.y);
}

const sendInput = (keyCode, isPressed) => {
  let userInput = "CENTER"

  switch(keyCode) {
  case KEY_UP:
  case KEY_W:
    userInput = isPressed ? "THRUST_ON" : "THRUST_OFF";
    break;
  case KEY_LEFT:
  case KEY_A:
    userInput = isPressed ? "LEFT" : "CENTER";
    break;
  case KEY_RIGHT:
  case KEY_D:
    userInput = isPressed ? "RIGHT" : "CENTER";
    break;
  case KEY_SPACE:
    userInput = isPressed ? "STRAIGHT_FIRE_START" : "FIRE_STOP";
    break;
  case KEY_SHIFT:
    userInput = isPressed ? "BOOST_ON" : "BOOST_OFF";
    break;
  }

  let userAction = new UserAction(userInput);

  sendMessage(userAction);
}

export const initializeControls = () => {
  addEventListener("keydown", function (e) {
    updateKeysState(e.keyCode, true);
  }, false);

  addEventListener("keyup", function (e) {
    updateKeysState(e.keyCode, false);
  }, false);

  addEventListener("mousedown", function() {
    updateMouseState(true);
  }, false);

  addEventListener("mouseup", function() {
    updateMouseState(false);
  }, false);

  addEventListener("mousemove", function(e) {
    updateMousePosition(e);
  }, false);
};

window.setInterval(function() {
  var mousePosition = renderer.plugins.interaction.mouse.global;

  let x = mousePosition.x - renderer.width / 2;
  let y = mousePosition.y - renderer.height / 2;
  let targetAngle = Math.atan2(y, x);

  if (lastTargetAngle != targetAngle) {
    lastTargetAngle = targetAngle;

    let targetAngleMsg = new TargetAngle(targetAngle);
    sendMessage(targetAngleMsg);
  }
}, 100)


text: ps ax | grep -i 'zookeeper' | grep -v grep | awk '{print $1}' | xargs kill -SIGINT


text:
import {
  test,
  moduleForModel
} from "ember-qunit";
import Pretender from "pretender";
import Ember from "ember";

var server;

moduleForModel('moose', 'Metadata', {
  needs: ['serializer:application', 'adapter:application'],
  teardown: function(){
    if (server) {
      server.shutdown();
      server = null;
    }
  }
});

test('loads meta data from top-level non-reserved keys for collection resources', function(){
  server = new Pretender(function(){
    this.get('/mooses', function(){
      return [200, {}, {
        page: 1,
        total_pages: 2,
        _embedded: {
          mooses: [{
            id: 'moose-9000',
            _links: {
              self: {
                href: "http://example.com/mooses/moose-9000"
              }
            }
          }]
        }
      }];
    });
  });

  var store = this.store();
  return store.find('moose').then(function(mooses){
    var meta = store.metadataFor('moose');

    deepEqual(meta, {page: 1, total_pages: 2});
  });
});

test('loads meta data from explicit `meta` key for collections', function(){
  server = new Pretender(function(){
    this.get('/mooses', function(){
      return [200, {}, {
        meta: {
          page: 1,
          total_pages: 2,
        },
        _embedded: {
          mooses: [{
            id: 'moose-9000',
            _links: {
              self: {
                href: "http://example.com/mooses/moose-9000"
              }
            }
          }]
        }
      }];
    });
  });

  var store = this.store();
  return store.find('moose').then(function(mooses){
    var meta = store.metadataFor('moose');

    deepEqual(meta, {page: 1, total_pages: 2});
  });
});

test('includes links in meta data for collections', function(){
  server = new Pretender(function(){
    this.get('/mooses', function(){
      return [200, {}, {
        _links: {
          self: { href: '/mooses' }
        },
        some_meta_val: 42,
        _embedded: {
          mooses: [{
            id: 'moose-9000',
            _links: {
              self: {
                href: "http://example.com/mooses/moose-9000"
              }
            }
          }]
        }
      }];
    });
  });

  var store = this.store();
  return store.find('moose').then(function(mooses){
    var meta = store.metadataFor('moose');

    deepEqual(meta,
              {links: {self: '/mooses'},
               some_meta_val: 42});
  });
});

test('loads meta data from explicit `meta` key for single resources', function(){
  server = new Pretender(function(){
    this.get('/mooses/moose-9000', function(){
      return [200, {}, {
        meta: {
          page: 1,
          total_pages: 2,
        },
        _links: {
          self: { href: '/mooses/1' }
        },
        id: 'moose-9000'
      }];
    });
  });

  var store = this.store();
  return Ember.run(function(){
    store.find('moose', 'moose-9000').then(function(mooses){
      var meta = store.metadataFor('moose');

      deepEqual(meta, {page: 1, total_pages: 2});
    });
  });
});


text:
package cypress

import (
	"bufio"
	"bytes"
	"compress/zlib"
	"io"

	"github.com/golang/snappy"
)

// No compression is applied
var NONE = StreamHeader_NONE

// Snappy compression is used
var SNAPPY = StreamHeader_SNAPPY

// ZLib compression is used
var ZLIB = StreamHeader_ZLIB

const defaultSnappyChunkBuffer = 1024 * 10

type snappyWriter struct {
	*snappy.Writer

	chunkBuffer int
	buf         bytes.Buffer
}

func (s *snappyWriter) Write(data []byte) (int, error) {
	n, err := s.buf.Write(data)
	if err != nil {
		return 0, err
	}

	if s.buf.Len() < s.chunkBuffer {
		return n, nil
	}

	_, err = s.Writer.Write(s.buf.Bytes())
	if err != nil {
		return 0, err
	}

	s.buf.Reset()

	return n, nil
}

func (s *snappyWriter) Flush() error {
	if s.buf.Len() > 0 {
		_, err := s.Writer.Write(s.buf.Bytes())
		s.buf.Reset()
		return err
	}

	return nil
}

func (s *snappyWriter) Close() error {
	return s.Flush()
}

type bufWriter struct {
	*bufio.Writer
}

func (b *bufWriter) Close() error {
	return b.Flush()
}

// Given a compression level, return a wrapped Writer
func WriteCompressed(w io.WriteCloser, comp StreamHeader_Compression) io.WriteCloser {
	switch comp {
	case StreamHeader_NONE:
		return &bufWriter{bufio.NewWriter(w)}
	case StreamHeader_SNAPPY:
		return &snappyWriter{
			Writer:      snappy.NewWriter(w),
			chunkBuffer: defaultSnappyChunkBuffer,
		}
	case StreamHeader_ZLIB:
		return zlib.NewWriter(w)
	default:
		panic("unknown compression requested")
	}
}

// Given a compression level, return a wrapped Reader
func ReadCompressed(r io.Reader, comp StreamHeader_Compression) io.Reader {
	switch comp {
	case StreamHeader_NONE:
		return r
	case StreamHeader_SNAPPY:
		return snappy.NewReader(r)
	case StreamHeader_ZLIB:
		zw, err := zlib.NewReader(r)
		if err != nil {
			panic(err)
		}

		return zw
	default:
		panic("unknown compression requested")
	}
}


text:
package com.amazonaws.services.mediaconvert.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.mediaconvert.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * MinTopRenditionSize JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MinTopRenditionSizeJsonUnmarshaller implements Unmarshaller<MinTopRenditionSize, JsonUnmarshallerContext> {

    public MinTopRenditionSize unmarshall(JsonUnmarshallerContext context) throws Exception {
        MinTopRenditionSize minTopRenditionSize = new MinTopRenditionSize();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("height", targetDepth)) {
                    context.nextToken();
                    minTopRenditionSize.setHeight(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("width", targetDepth)) {
                    context.nextToken();
                    minTopRenditionSize.setWidth(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return minTopRenditionSize;
    }

    private static MinTopRenditionSizeJsonUnmarshaller instance;

    public static MinTopRenditionSizeJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new MinTopRenditionSizeJsonUnmarshaller();
        return instance;
    }
}


text:
import $ from 'jquery';
import { isEmpty } from 'lodash';

// From: http://jsfiddle.net/joshdmiller/NDFHg/
function EditInPlace() {
  return {
    restrict: 'E',
    scope: {
      value: '=',
      ignoreBlanks: '=',
      editable: '=',
      done: '=',
    },
    template(tElement, tAttrs) {
      const elType = tAttrs.editor || 'input';
      const placeholder = tAttrs.placeholder || 'Click to edit';

      let viewMode = '';

      if (tAttrs.markdown === 'true') {
        viewMode = '';
      } else {
        viewMode = '';
      }

      const placeholderSpan = `${placeholder}`;
      const editor = '<{elType} ng-model="value" class="rd-form-control"></{elType}>'.replace('{elType}', elType);

      return viewMode + placeholderSpan + editor;
    },
    link($scope, element) {
      // Let's get a reference to the input element, as we'll want to reference it.
      const inputElement = $(element.children()[2]);
      const keycodeEnter = 13;
      const keycodeEscape = 27;

      // This directive should have a set class so we can style it.
      element.addClass('edit-in-place');

      // Initially, we're not editing.
      $scope.editing = false;

      // ng-click handler to activate edit-in-place
      $scope.edit = () => {
        $scope.oldValue = $scope.value;

        $scope.editing = true;

        // We control display through a class on the directive itself. See the CSS.
        element.addClass('active');

        // And we must focus the element.
        // `angular.element()` provides a chainable array, like jQuery so to access
        // a native DOM function, we have to reference the first element in the array.
        inputElement[0].focus();
      };

      function save() {
        if ($scope.editing) {
          if ($scope.ignoreBlanks && isEmpty($scope.value)) {
            $scope.value = $scope.oldValue;
          }
          $scope.editing = false;
          element.removeClass('active');

          if ($scope.value !== $scope.oldValue) {
            if ($scope.done) {
              $scope.done();
            }
          }
        }
      }

      $(inputElement).keydown((e) => {
        // 'return' or 'enter' key pressed
        // allow 'shift' to break lines
        if (e.which === keycodeEnter && !e.shiftKey) {
          e.preventDefault();
          save();
        } else if (e.which === keycodeEscape) {
          $scope.value = $scope.oldValue;
          $scope.$apply(() => {
            $(inputElement[0]).blur();
          });
        }
      }).blur(() => {
        save();
      });
    },
  };
}

export default function init(ngModule) {
  ngModule.directive('editInPlace', EditInPlace);
}


text:
/*include:js/core/namespace.js*/

(function (global) {
    'use strict';
    wd.assets = (function () {

        function image(id) {
            return document.getElementById(id);
        }

        return {
            image: image
        };
    }());
}(this));


text:
package main
func f(){
	var x = 10;
	y := x
	type person struct{
		first, last string
		age, height int }
	var z []person;
	var w [20]person;
	var daniel.shoes = "White"; // invalid

	return "Damn Daniel..."
}


text:
package godef

import (
	"bytes"
	"errors"
	"fmt"
	"go/build"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"

	"go/token"

	"go/printer"

	"go/ast"

	"github.com/sourcegraph/go-langserver/langserver/internal/godef/go/parser"
	"github.com/sourcegraph/go-langserver/langserver/internal/godef/go/types"
)

type Result struct {
	// Start and end positions of the definition (only if not an import statement).
	Start, End token.Pos

	// Package in question, only present if an import statement OR package selector
	// ('http' in 'http.Router').
	Package *build.Package
}

var ErrNoIdentifierFound = errors.New("no identifier found")

func Godef(fset *token.FileSet, offset int, filename string, src []byte) (*Result, error) {
	pkgScope := ast.NewScope(parser.Universe)
	f, err := parser.ParseFile(fset, filename, src, 0, pkgScope, types.DefaultImportPathToName)
	if f == nil {
		return nil, fmt.Errorf("cannot parse %s: %v", filename, err)
	}

	o := findIdentifier(fset, f, offset)
	if o == nil {
		return nil, ErrNoIdentifierFound
	}
	switch e := o.(type) {
	case *ast.ImportSpec:
		path, err := importPath(e)
		if err != nil {
			return nil, err
		}
		pkg, err := build.Default.Import(path, filepath.Dir(filename), build.FindOnly)
		if err != nil {
			return nil, fmt.Errorf("error finding import path for %s: %s", path, err)
		}
		return &Result{Package: pkg}, nil
	case ast.Expr:
		result := func(obj *ast.Object) (*Result, error) {
			p := types.DeclPos(obj)
			r := &Result{Start: p, End: p + token.Pos(len(obj.Name))}
			if imp, ok := obj.Decl.(*ast.ImportSpec); ok {
				path, err := importPath(imp)
				if err != nil {
					return nil, err
				}
				pkg, err := build.Default.Import(path, filepath.Dir(fset.Position(p).Filename), build.FindOnly)
				if err != nil {
					return nil, fmt.Errorf("error finding import path for %s: %s", path, err)
				}
				r.Package = pkg
			}
			return r, nil
		}
		importer := types.DefaultImporter(fset)
		// try local declarations only
		if obj, _ := types.ExprType(e, importer, fset); obj != nil {
			return result(obj)
		}

		// add declarations from other files in the local package and try again
		pkg, err := parseLocalPackage(fset, filename, f, pkgScope, types.DefaultImportPathToName)
		if pkg == nil {
			log.Printf("parseLocalPackage error: %v\n", err)
		}
		if obj, _ := types.ExprType(e, importer, fset); obj != nil {
			return result(obj)
		}
		return nil, fmt.Errorf("no declaration found for %v", pretty{fset, e})
	}
	return nil, fmt.Errorf("unreached")
}

func importPath(n *ast.ImportSpec) (string, error) {
	p, err := strconv.Unquote(n.Path.Value)
	if err != nil {
		return "", fmt.Errorf("invalid string literal %q in ast.ImportSpec", n.Path.Value)
	}
	return p, nil
}

// findIdentifier looks for an identifier at byte-offset searchpos
// inside the parsed source represented by node.
// If it is part of a selector expression, it returns
// that expression rather than the identifier itself.
//
// As a special case, if it finds an import
// spec, it returns ImportSpec.
//
func findIdentifier(fset *token.FileSet, f *ast.File, searchpos int) ast.Node {
	ec := make(chan ast.Node)
	found := func(startPos, endPos token.Pos) bool {
		start := fset.Position(startPos).Offset
		end := start + int(endPos-startPos)
		return start <= searchpos && searchpos <= end
	}
	go func() {
		var visit func(ast.Node) bool
		visit = func(n ast.Node) bool {
			var startPos token.Pos
			switch n := n.(type) {
			default:
				return true
			case *ast.Ident:
				startPos = n.NamePos
			case *ast.SelectorExpr:
				startPos = n.Sel.NamePos
			case *ast.ImportSpec:
				startPos = n.Pos()
			case *ast.StructType:
				// If we find an anonymous bare field in a
				// struct type, its definition points to itself,
				// but we actually want to go elsewhere,
				// so assume (dubiously) that the expression
				// works globally and return a new node for it.
				for _, field := range n.Fields.List {
					if field.Names != nil {
						continue
					}
					t := field.Type
					if pt, ok := field.Type.(*ast.StarExpr); ok {
						t = pt.X
					}
					if id, ok := t.(*ast.Ident); ok {
						if found(id.NamePos, id.End()) {
							e, err := parseExpr(fset, f.Scope, id.Name)
							if err != nil {
								log.Println(err) // TODO(slimsag): return to caller
							}
							ec <- e
							runtime.Goexit()
						}
					}
				}
				return true
			}
			if found(startPos, n.End()) {
				ec <- n
				runtime.Goexit()
			}
			return true
		}
		ast.Walk(visitorFunc(visit), f)
		ec <- nil
	}()
	return <-ec
}

func parseExpr(fset *token.FileSet, s *ast.Scope, expr string) (ast.Expr, error) {
	n, err := parser.ParseExpr(fset, "<arg>", expr, s, types.DefaultImportPathToName)
	if err != nil {
		return nil, fmt.Errorf("cannot parse expression: %v", err)
	}
	switch n := n.(type) {
	case *ast.Ident, *ast.SelectorExpr:
		return n, nil
	}
	return nil, fmt.Errorf("no identifier found in expression")
}

type visitorFunc func(n ast.Node) bool

func (f visitorFunc) Visit(n ast.Node) ast.Visitor {
	if f(n) {
		return f
	}
	return nil
}

var errNoPkgFiles = errors.New("no more package files found")

// parseLocalPackage reads and parses all go files from the
// current directory that implement the same package name
// the principal source file, except the original source file
// itself, which will already have been parsed.
//
func parseLocalPackage(fset *token.FileSet, filename string, src *ast.File, pkgScope *ast.Scope, pathToName parser.ImportPathToName) (*ast.Package, error) {
	pkg := &ast.Package{src.Name.Name, pkgScope, nil, map[string]*ast.File{filename: src}}
	d, f := filepath.Split(filename)
	if d == "" {
		d = "./"
	}
	fd, err := os.Open(d)
	if err != nil {
		return nil, err
	}
	defer fd.Close()

	list, err := fd.Readdirnames(-1)
	if err != nil {
		return nil, errNoPkgFiles
	}

	for _, pf := range list {
		file := filepath.Join(d, pf)
		if !strings.HasSuffix(pf, ".go") ||
			pf == f ||
			pkgName(fset, file) != pkg.Name {
			continue
		}
		src, err := parser.ParseFile(fset, file, nil, 0, pkg.Scope, types.DefaultImportPathToName)
		if err == nil {
			pkg.Files[file] = src
		}
	}
	if len(pkg.Files) == 1 {
		return nil, errNoPkgFiles
	}
	return pkg, nil
}

// pkgName returns the package name implemented by the
// go source filename.
//
func pkgName(fset *token.FileSet, filename string) string {
	prog, _ := parser.ParseFile(fset, filename, nil, parser.PackageClauseOnly, nil, types.DefaultImportPathToName)
	if prog != nil {
		return prog.Name.Name
	}
	return ""
}

type pretty struct {
	fset *token.FileSet
	n    interface{}
}

func (p pretty) String() string {
	var b bytes.Buffer
	printer.Fprint(&b, p.fset, p.n)
	return b.String()
}


text: OpenSource Enterprise