text:
(function (global) {
    "use strict";

    var FUNCTION = "function";
    var UNDEFINED = "undefined";
    var EVT_BIND_TO = "bind-to";
    var EVT_BIND_ALTERNATE = "bind-alternate";
    var EVT_LOAD_WITH = "load-withThis";
    var EVT_LOAD = "load";
    var EVT_LIST = "load-list";
    var XML_ROOT = "templates";
    var XML_CHILD = "template";

    var trim = function (str) {
        return str.replace(/^\s+|\s+$/g, "");
    }
    var autoBlank = function (txt) {
        return (typeof txt === "undefined" || txt === null) ? "" : txt;
    }
    var replaceAll = function (find, replace, text) {
        return text.split(find).join(replace);
    }

    var removeChildren = function(element) {
        if (element.hasChildNodes()) {
            while (element.childNodes.length >= 1) {
                element.removeChild(element.firstChild);
            }
        }
    };

    var validListItem = function (o) {
        if (o.hasOwnProperty("template") && o.hasOwnProperty("data")) {
            return (o.data.constructor === Array);
        }
        return false;
    }

    var validTemplate = function (o) {
        return o.hasOwnProperty("name") && o.hasOwnProperty("text");
    }

    var toLower = function (txt) {
        if (typeof txt !== "undefined" && txt !== null) {
            return txt.toLowerCase();
        }

        return "";
    };

    var toDom = function (txt) {
        var temp = document.createElement("div");
        temp.innerHTML = trim(txt);
        return temp.firstChild;
    };

    function parseXml(text) {
        var xmlDoc;
        if (window.DOMParser) {
            var xmlParser = new DOMParser();
            xmlDoc = xmlParser.parseFromString(text, "text/xml");
        } else {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(text);
        }
        return xmlDoc;
    }

    var onload = function (callback) {
        var current = window.onload;
        if (typeof window.onload !== FUNCTION) {
            window.onload = callback;
        } else {
            if (typeof callback === FUNCTION) {
                window.onload = function () {
                    if (current) {
                        current();
                    }
                    callback();
                };
            }
        }
    };

    var readyExecuted = false;
    var onReady = null;
    var ready = function (callback) {
        ///
        /// Execute callback function when DOM is ready
        ///
        ///	<param name="callback" type="function">
        /// Function to execute.
        ///	</param>
        if (typeof onReady !== FUNCTION) {
            onReady = callback;
        } else {
            var current = onReady;
            onReady = function () {
                if (current) {
                    current();
                }
                callback();
            };
        }

        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", function () {
                if (!readyExecuted) {
                    onReady();
                    readyExecuted = true;
                }
            }, false);
        } else {
            onload(callback);
        }
    };

    var getTemplates = function (lst) {
        var result = [];
        if (lst !== null
            && typeof lst !== "undefined"
            && lst.constructor === Array) {
            for (var i = 0, max = lst.length; i < max; i++) {
                if (lst[i].hasOwnProperty("template")) {
                    if (typeof lst[i].template !== "undefined"
                        && lst[i].template !== null) {
                        result.push(lst[i].template);
                    }
                }
            }
        }
        return result;
    };

    var hasExtension = function (filename, ext) {
        if (typeof filename === "undefined" || filename === null) {
            return false;
        }
        return filename.toLowerCase().split(".").pop() === ext;
    };

    var usingInline = false;
    var templateList = [];

    var where = function (arr, fnCall) {
        var sub = [];
        (function (a) {
            for (var i = 0, max = a.length; i < max; i++) {
                if (fnCall(arr[i], i)) {
                    sub.push(arr[i]);
                }
            }
        })(arr);
        return sub;
    };

    var hasTemplate = function (tpl) {

        var sel = where(templateList, function (o) {

            return o.name === (validTemplate(tpl)
                              ? tpl.name : tpl);
        });

        return sel.length > 0;
    };

    var addTemplate = function (template) {
        if (!hasTemplate(template)) {
            templateList.push(template);
        }
    };

    var req = function (p) {
        (function (xH) {

            xH.onreadystatechange = function () {

                if (xH.readyState === 4) {
                    if (xH.responseText.length > 0) {
                        if (xH.status === 200) {
                            if (typeof p.callback === FUNCTION) {
                                p.callback(xH.responseText);
                            }
                        } else {
                            if (typeof p.error === FUNCTION) {
                                p.error(xH.status, xH.statusText);
                            }

                        }
                    }
                    xH = null;
                }
            };

            xH.open("GET", p.url, true);
            xH.send(null);

        })(new XMLHttpRequest());
    };

    var fetch = function (id, templateUrl, callback, asText) {
        if (id === null || !hasTemplate(id)) {
            req({
                url: templateUrl,
                callback: function (html) {
                    if (typeof callback === FUNCTION) {
                        if (typeof asText === "undefined") {
                            callback(toDom(html));
                        }
                        callback(html, id);
                    }
                }
            });
        }
    };

    var repository = "";
    var hasPreloaded = false;
    var thenQueue = {};
    var thenEvents = function (location, html) {
        this.then = function (callback) {
            if (hasPreloaded) {
                if (typeof callback === FUNCTION) {
                    if (typeof html !== "undefined") {
                        callback(html);
                    } else {
                        callback();
                    }
                }
            } else {
                if (typeof callback === FUNCTION) {
                    thenQueue[location] = callback;
                }
            }
        };
    };

    var assignRepo = function (repo) {

        if (repo.constructor === Array) {
            usingInline = true;
        } else {
            usingInline = false;
            if (repo.length > 0 && repo.substring(repo.length - 1) === "\\") {
                repo = repo.substring(0, repo.length - 1);
            }

            if (repo.length > 0 && repo.substring(repo.length - 1) !== "/") {
                repo = repo + "/";
            }

        }

        repository = repo;
    };

    var loadEvents = function () {

        this.withThis = function (lst) {
            /// <signature>
            ///   Template list
            ///   <param name="lst" type="array">Array of template names (ex. ["template1","teamplate2"])</param>
            /// </signature>
            /// <signature>
            ///   Template xml
            ///   <param name="lst" type="string">XML filename</param>
            /// </signature>
            /// <signature>
            ///   Javascript Array
            ///   <param name="lst" type="array">Name of the javascript array that holds the templates (ex. [{ name:"templatename", text:"template content"}]).</param>
            /// </signature>

            if (usingInline) {

                if (repository.constructor === Array) {

                if (lst.constructor !== Array) {
                    for (var ri = 0, rm = repository.length; ri < rm; ri++) {
                        if (validTemplate(repository[ri])) {
                            if (repository[ri].name === lst || lst === "*") {
                                templateList.push(repository[ri]);
                                if (lst !== "*") {
                                    break;
                                }
                            }

                        }
                    }
                } else {

                    for (var inl = 0, inlMax = lst.length; inl < inlMax; inl++) {
                        for (var ai = 0, am = repository.length; ai < am; ai++) {
                            if (validTemplate(repository[ai])) {
                                if (repository[ai].name === lst[inl]) {
                                    templateList.push(repository[ai]);
                                        break;
                                    }

                                }
                            }
                        }
                }

                }

                hasPreloaded = templateList.length > 0;
                if (typeof thenQueue[EVT_LOAD_WITH] === FUNCTION) {
                    thenQueue[EVT_LOAD_WITH]();
                }

            } else if (lst.constructor !== Array && hasExtension(lst, "xml")) {
                fetch(null, repository + lst, function (text) {

                    if (typeof text !== "undefined"
                        && text !== null
                        && text.length > 0) {

                        var xml = parseXml(text);

                        if (xml.hasChildNodes()
                            && toLower(xml.firstChild.localName) === XML_ROOT) {
                            var tpls = xml.firstChild;
                            if (tpls.hasChildNodes()) {
                                for (var tpl = 0, tplM = tpls.childNodes.length;
                                    tpl < tplM; tpl++) {
                                    if (toLower(tpls.childNodes[tpl].localName) === XML_CHILD) {
                                        var child = tpls.childNodes[tpl];
                                        var name = "generic-" + tpl;
                                        var templateContent = "";
                                        if (child.hasAttributes()) {
                                            name = child.attributes.getNamedItem("name").value;
                                        }
                                        if (child.hasChildNodes()) {
                                            for (var cld = 0, cldm = child.childNodes.length; cld < cldm; cld++) {
                                                if (toLower(child.childNodes[cld].nodeName) === "#cdata-section") {
                                                    templateContent = child.childNodes[cld].nodeValue;
                                                }
                                            }
                                        }

                                        if (templateContent.length > 0) {
                                            addTemplate({
                                                name: name,
                                                text: trim(templateContent)
                                            });
                                        }
                                    }
                                }

                                hasPreloaded = templateList.length > 0;
                                if (typeof thenQueue[EVT_LOAD_WITH] === FUNCTION) {
                                    thenQueue[EVT_LOAD_WITH]();
                                }

                            }
                        }

                    }

                }, false);
            } else {

                var processed = 0;
                for (var i = 0, max = lst.length; i < max; i++) {
                    fetch(lst[i], repository + lst[i], function (html, name) {
                        addTemplate({
                            name: name,
                            text: trim(html)
                        });
                        processed++;
                        if (processed === max) {
                            hasPreloaded = templateList.length > 0;
                            if (typeof thenQueue[EVT_LOAD_WITH] === FUNCTION) {
                                thenQueue[EVT_LOAD_WITH]();
                            }
                        }
                    }, true);
                }

            }

            return new thenEvents(EVT_LOAD_WITH);

        }
    };

    var load = function (name, asText) {
        ///
        ///	Load template as text withThis data biding
        ///
        ///	<param name="name" type="string">
        ///	 Name of the template file
        ///	</param>
        ///	<param name="callbacks" type="function">
        ///	 Function that will receive a template Instance. (ex. function(html){})
        ///	</param>

        var then = new thenEvents(EVT_LOAD);
        var done = false;

        if (typeof asText === "undefined") {
            asText = false;
        }

        if (hasPreloaded) {
            var sel = where(templateList, function (o) {
                return o.name === name;
            });

            if (sel.length > 0) {
                done = true;
                then = new thenEvents(EVT_LOAD, asText ? sel[0].text : toDom(sel[0].text));
            }
        }

        if (!done) {
            fetch(name, repository + name, function (html) {
                if (typeof thenQueue[EVT_LOAD] === FUNCTION) {
                    thenQueue[EVT_LOAD](asText ? html : toDom(html));
                }
            }, asText);
        }

        return then;
    };

    var loadFrom = function (repo) {
        ///
        ///	Set repositiory location and allow the withThis() method to preload the templates.
        ///
        ///	<param name="repo" type="string">
        ///	 Repository location
        ///	</param>

        assignRepo(repo);

        return new loadEvents();
    };

    var bindEvents = function (bindings) {

        this.alternate = function (templates, templateSource) {
            /// <signature>
            ///   Bind data alternating between templates
            ///   <param name="templates" type="array">Array of template names (ex. ["template1","teamplate2"])</param>
            /// </signature>
            /// <signature>
            ///   Bind data alternating between templates
            ///   <param name="template" type="array">Array of template names (ex. ["template1","teamplate2"])</param>
            ///   <param name="templateSource" type="string">Array of template names (ex. templates.xml )</param>
            /// </signature>

            var items = [];

            if (templates.constructor === Array) {

                var reqTemplates = templates;
                if (typeof templateSource !== "undefined") {
                    reqTemplates = templateSource;
                }

                loadFrom(repository)
                    .withThis(reqTemplates)
                    .then(function () {

                        var templateN = templates.length;
                        var current = 0;
                        if (bindings !== null
                            && typeof bindings !== "undefined"
                            && templateN > 0) {

                            for (var i = 0, max = bindings.length; i < max; i++) {

                                (function (oi) {
                                    if (current >= templateN) {
                                        current = 0;
                                    }
                                    load(templates[current], true).then(function (html) {

                                        current++;

                                        var temp = html;

                                        for (var p in bindings[oi]) {

                                            if (bindings[oi].hasOwnProperty(p)) {
                                                temp = replaceAll("{" + p + "}", autoBlank(bindings[oi][p]), autoBlank(temp));
                                            }

                                        }

                                        items.push(toDom(temp));

                                        if (typeof thenQueue[EVT_BIND_ALTERNATE] === FUNCTION) {
                                            thenQueue[EVT_BIND_ALTERNATE](items);
                                        }
                                    });

                                })(i);

                            }
                        }

                    });

            }

            return new thenEvents(EVT_BIND_ALTERNATE, items);
        };

        this.to = function (templateName) {

            var items = [];

            if (templateName.constructor === Array) {

                for (var t = 0, tmax = templateName.length; t < tmax; t++) {
                    load(templateName[t], true).then(function (html) {

                        if (bindings !== null
                                    && typeof bindings !== "undefined") {

                            for (var i = 0, max = bindings.length; i < max; i++) {
                                var temp = html;

                                for (var p in bindings[i]) {
                                    if (bindings[i].hasOwnProperty(p)) {
                                        temp = replaceAll("{" + p + "}", autoBlank(bindings[i][p]), autoBlank(temp));
                                    }
                                }
                                items.push(toDom(temp));
                            }

                            if (typeof thenQueue[EVT_BIND_TO] === FUNCTION) {
                                thenQueue[EVT_BIND_TO](items);
                            }

                        }

                    });
                }

            } else {

                load(templateName, true).then(function (html) {

                    if (bindings !== null
                                && typeof bindings !== "undefined") {

                        for (var i = 0, max = bindings.length; i < max; i++) {
                            var temp = html;

                            for (var p in bindings[i]) {
                                if (bindings[i].hasOwnProperty(p)) {
                                    temp = replaceAll("{" + p + "}", autoBlank(bindings[i][p]), autoBlank(temp));
                                }
                            }
                            items.push(toDom(temp));
                        }

                        if (typeof thenQueue[EVT_BIND_TO] === FUNCTION) {
                            thenQueue[EVT_BIND_TO](items);
                        }

                    }

                });

            }

            return new thenEvents(EVT_BIND_TO, items);
        };
    };

    var bind = function (bindings) {

        return new bindEvents(bindings);

    };

    var list = function (bindList, templateSource) {

        var items = [];

        if (typeof bindList !== "undefined"
           && bindList !== null) {

            var reqTemplates = getTemplates(bindList);
            if (typeof templateSource !== "undefined") {
                reqTemplates = templateSource;
            }

            loadFrom(repository)
                .withThis(reqTemplates)
                .then(function () {

                    for (var i = 0, max = bindList.length; i < max; i++) {

                        (function (t) {
                            if (validListItem(t)) {
                                bind(t.data)
                                    .to(t.template)
                                    .then(function (html) {
                                        for (var a = 0, amx = html.length; a < amx; a++) {
                                            items.push(html[a]);
                                        }
                                    });
                            }
                        })(bindList[i]);

                    }
                    if (typeof thenQueue[EVT_LIST] === FUNCTION) {
                        thenQueue[EVT_LIST](items);
                    }

                });

        }

        return new thenEvents(EVT_LIST, items);
    };

    var bloq = {
        ready: ready,
        templates: function () {
            return templateList;
        },
        fromRepo: function (repo) {
            ///
            ///	Set repositiory location without preloading the templates.
            ///
            ///	<param name="repo" type="string">
            ///	 Repository location
            ///	</param>
            assignRepo(repo);
            return this;
        },
        list: list,
        loadFrom: loadFrom,
        read: function (templateName, parameters) {
            if (typeof parameters === "undefined" || parameters === null) {
                parameters = {};
            }
            var asText = false;
            if (repository === null || typeof repository === "undefined" || repository.length === 0) {

                if (parameters.hasOwnProperty("repo")) {
                    assignRepo(parameters.repo);
                } else if (parameters.hasOwnProperty("repository")) {
                    assignRepo(parameters.repository);
                } else {
                    //Assume root
                    repository = "./";
                }
            }

            if (parameters.hasOwnProperty("asText")) {
                asText = parameters.asText;
            }

            return load(templateName, asText);
        },
        bind: bind
    };

    //#region "Binder"

    var ATT = {
        BLOCK: "bloq-area",
        PROPERTY: "bloq-field",
        TEMPLATE: "bloq-template",
        REPEATER: "bloq-repeat"
    };

    var TAG = {
        INPUT: "input",
        RADIO: "radio",
        TEXT_AREA: "textarea",
        SELECT: "select"
    }

    var setName = "";

    var select = function (parentElement, query) {
        if (parentElement !== null && typeof parentElement !== UNDEFINED) {
            return parentElement.querySelectorAll(query);
        }
        return null;
    };

    var processDefined = function (json, elem, arr) {
        for (var i = 0, max = arr.length; i < max; i++) {
            var c = trim(arr[i]);
            if (json.hasOwnProperty(c)) {
                if (typeof (json[c]) !== UNDEFINED) {
                    var currentTxt = elem.innerHTML;
                    elem.innerHTML = replaceAll("{" + c + "}",
                        typeof json[c] === FUNCTION ? json[c]() : json[c]
                        , currentTxt);
                }
            }
        }
    };

    var getNode = function (nodeName) {
        var nodes = document.querySelectorAll("[" + ATT.BLOCK + "=" + nodeName + "]");
        if (typeof nodes !== UNDEFINED && nodes !== null && nodes.length > 0) {
            return nodes[0];
        }
        return null;
    };

    var getNodeProperties = function (mappingType) {

        var container = getNode(setName);

        var nodeList = select(container, "[" + mappingType + "]");

        return nodeList;
    };

    var repeateIt = function (parentElement, child, obj) {
        for (var p in obj) {

            if (obj.hasOwnProperty(p)) {

                if (typeof (obj[p]) !== UNDEFINED) {

                    var currentTxt = child.innerHTML;
                    child.innerHTML = replaceAll("{" + p + "}",
                        (typeof obj[p] === FUNCTION) ? obj[p]() : obj[p]
                        , currentTxt);

                }
            }

        }

        parentElement.appendChild(child);

    };

    var parent = null;
    var template = null;
    var original = null;

    var repeatFn = function (set) {

        this.to = function (name) {
            if (parent === null) {
                parent = getNode(setName);
            }

            if (parent !== null && typeof parent !== UNDEFINED) {
                if (template === null) {
                    var holdTemplate = select(parent, "[" + ATT.REPEATER + " = " + name + "]");
                    if (holdTemplate.length > 0) {
                        template = holdTemplate[0];
                    }
                }

                if (template !== null && typeof template !== UNDEFINED) {

                    if (original === null) {
                        if (template.firstElementChild) {
                          original = template.firstElementChild.cloneNode(true);
                        }

                    }

                    removeChildren(template);

                    if (set.constructor === Array) {
                        for (var s = 0, sm = set.length; s < sm; s++) {
                            repeateIt(template, original.cloneNode(true), set[s]);
                        }

                    }

                }
            }
        }
    };

    var formatField = function(txt, format) {

        if (format.length > 0) {
            if (format.substr(0, 1) === "#") {

                if (format.indexOf("#UPPER") !== -1) {
                    return txt.toUpperCase();
                }

                if (format.indexOf("#LOWER")) {
                    return txt.toLowerCase();
                }
            }
        }

       return replaceAll("{0}", txt, format);
    };

    var repeat = function (set) {
        return new repeatFn(set);
    };
    var originalContainer = null;
    var fn = function (name) {

        setName = name;

        this.repeat = repeat;

        var takeFn = function (mappingType) {

            var set = {
            };

            var nodes = getNodeProperties(mappingType);
            if (typeof nodes !== "undefined" && nodes !== null && nodes.length > 0) {
                for (var i = 0; i < nodes.length; i++) {

                    var propName = nodes[i].attributes.getNamedItem(mappingType).value;

                    switch (nodes[i].tagName.toLowerCase()) {
                        case TAG.TEXT_AREA:
                        case TAG.INPUT:
                            var type = nodes[i].type;
                            switch (type.toLowerCase()) {
                                case TAG.RADIO:
                                    if (nodes[i].checked) {
                                        set[propName] = nodes[i].value;
                                    }
                                    break;
                                default:
                                    set[propName] = nodes[i].value;
                                    break;
                            }
                            break;
                        case TAG.SELECT:
                            if (typeof nodes[i].selectedIndex !== "undefined"
                                && nodes[i].selectedIndex !== -1) {
                                if (nodes[i].multiple) {
                                    var v = [];
                                    for (var oi = 0, m = nodes[i].length; oi < m; oi++) {
                                        if (nodes[i].options[oi].selected) {
                                            v.push(nodes[i].options[oi].value);
                                        }
                                    }
                                    set[propName] = v;
                                } else {
                                    set[propName] = nodes[i].options[nodes[i].selectedIndex].value;
                                }
                            }
                            break;
                        default:
                            if (typeof (nodes[i].innerHTML) !== "undefined") {
                                set[propName] = nodes[i].innerHTML;
                            }

                            break;
                    }
                }
            }

            return set;
        };

        this.takeTemplate = function () {
            return takeFn(ATT.TEMPLATE);
        };

        this.take = function() {
            return takeFn(ATT.PROPERTY);
        };

        this.put = function (json) {

            var container = getNode(setName);

            if (originalContainer === null) {
                originalContainer = container.cloneNode(true);
            } else {
                var parentContainer = container.parentNode;
                parentContainer.removeChild(container);
                container = originalContainer.cloneNode(true);
                parentContainer.appendChild(container);
            }

            if (container !== null) {

                //Process templates
                var templates = container.querySelectorAll("[" + ATT.TEMPLATE + "]");
                var processAll = [];
                if (templates.length > 0) {
                    for (var t = 0, tmax = templates.length; t < tmax; t++) {
                        var elem = templates[t].getAttribute(ATT.TEMPLATE);
                        if (trim(elem) === "*") {
                            processAll.push(templates[t]);
                        } else {
                            var fieldsArr = elem.split(",");
                            processDefined(json, templates[t], fieldsArr);
                        }
                    }
                }

                for (var p in json) {
                    if (json.hasOwnProperty(p)) {
                        if (typeof (json[p]) !== UNDEFINED) {

                            for (var all = 0, allMax = processAll.length; all < allMax; all++) {
                                var currentTxt = processAll[all].innerHTML;
                                processAll[all].innerHTML = replaceAll("{" + p + "}",
                                    (typeof json[p] === FUNCTION) ? json[p]() : json[p]
                                    , currentTxt);
                            }

                            var element = container.querySelectorAll("[" + ATT.PROPERTY + "=" + p + "]");

                            if (typeof element !== UNDEFINED && element.length > 0) {

                                for (var i = 0, max = element.length; i < max; i++) {
                                    var format = "";

                                    var current = (typeof json[p] === FUNCTION) ? json[p]() : json[p];

                                    if (element[i].getAttribute("bloq-format")) {
                                        format = element[i].getAttribute("bloq-format");
                                        current = formatField(current, format);
                                    }

                                    switch (element[i].tagName.toLowerCase()) {
                                        case TAG.TEXT_AREA:
                                        case TAG.INPUT:
                                            if (element[i].type.toLowerCase() === TAG.RADIO) {
                                                for (var ri = 0, rm = element.length; ri < rm; ri++) {
                                                    if (element[ri].value.toLowerCase() === current.toLowerCase()) {
                                                        element[ri].checked = true;
                                                    }
                                                }
                                            } else {
                                                element[i].value = current;
                                            }

                                            break;
                                        case TAG.SELECT:

                                            if (json[p].constructor !== Array) {
                                                for (var oi = 0, m = element[0].length; oi < m; oi++) {
                                                    if (element[i].options[oi].value.toLowerCase() === current.toLowerCase()) {
                                                        element[i].options[oi].selected = true;
                                                    }
                                                }
                                            } else {
                                                for (var ji = 0, jm = json[p].length; ji < jm; ji++) {
                                                    for (var ai = 0, am = element[i].length; ai < am; ai++) {
                                                        if (element[i].options[ai].value.toLowerCase() === current.toLowerCase()) {
                                                            element[i].options[ai].selected = true;
                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                        default:
                                            if (typeof (element[i].innerHTML) !== UNDEFINED) {
                                                element[i].innerHTML = current;
                                            }

                                            break;
                                    }

                                }

                            }

                        }
                    }
                }//json

            }

            return this;
        };

    };

    var bloqFn = function (name) {
        return new fn(name);
    };

    bloqFn.extend = function (extension) {
        ///
        ///	Extend the object literal.
        ///
        ///	<param name="extension" type="object">
        ///	 Object to be attached
        ///	</param>
        for (var p in extension) {
            if (extension.hasOwnProperty(p)) {
                if (typeof (extension[p]) !== UNDEFINED) {
                    bloqFn[p] = extension[p];
                }
            }
        }
    };

    bloqFn.extend(bloq);

    //#endregion

    if (!global.bloq) {
        global.bloq = global["bloq"] = bloqFn;
    }

})(window);


text:
layout: event
categories: eventolocale
title: "Viaggio al Polo: L'intelligenza secondo il Polo Galattico"
CL: Firenze
locandina: https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/58374867_10161768137195261_7408633292120915968_n.jpg?_nc_cat=105&_nc_ht=scontent-mxp1-1.xx&oh=721c3841919d4de2211e8c170c03b1d7&oe=5D736E62
articolo: "-"
report:
facebook:	https://www.facebook.com/events/375570093033998/
link:
---
 	Primo appuntamento del ciclo "Viaggio al Polo", serie di aperitivi scientifici organizzati all'interno del Polo Scientifico di Sesto Fiorentino. Lo scopo dell'evento è quello di stimolare e facilitare lo scambio tra studenti con un diverso bagaglio culturale e, a tal fine, abbiamo selezionato temi il più possibile interdisciplinari ed esperti provenienti da settori diversi. Nel primo incontro si parlerà di intelligenza: partendo da quella degli uomini, si passerà per l'intelligenza collettiva delle piante, fino ad approdare all'AI delle macchine.

redpajama_set_name: RedPajamaGithub


text:
#ifndef RESOURCE_NET_HH
#define	RESOURCE_NET_HH

#include "../Resource.hh"

namespace onode {

namespace resource {

class Net : public Resource {
public:
    Net(Sandbox *sandbox);
    virtual ~Net();

protected:
    CLASS_NAME("resource/net");

private:

};

}

}

#endif	/* RESOURCE_NET_HH */


text:
package iot.jcypher.database.remote;

import iot.jcypher.database.internal.DBUtil;
import iot.jcypher.query.result.JcError;
import iot.jcypher.transaction.internal.AbstractTransaction;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class RTransactionImpl extends AbstractTransaction {

	private static final String transactionalURLPostfix = "db/data/transaction";
	private static final String txCommit = "/commit";
	private static final String emptyJSON = "{\"statements\" : [ ]}";
	private Invocation.Builder invocationBuilder_open;
	private Invocation.Builder invocationBuilder_next;
	private String txLocation;

	/**
	 * @param dbAccess
	 */
	public RTransactionImpl(RemoteDBAccess dbAccess) {
		super(dbAccess);
	}

	@Override
	public List<JcError> close() {
		List<JcError> errors;
		if (isClosed())
			throw new RuntimeException(ERR_CLOSED);
		if (!isMyThread())
			throw new RuntimeException(ERR_THREAD);

		RemoteDBAccess rdba = getRDBAccess();
		rdba.removeTx();
		if (this.invocationBuilder_open != null) {
			Builder iBuilder;
			if (failed) {
				iBuilder = createNextInvocationBuilder();
			} else {
				WebTarget serverRootTarget = rdba.getRestClient().target(rdba.getServerRootUri());
				WebTarget transactionalTarget = serverRootTarget.path(this.txLocation.concat(txCommit));
				iBuilder = transactionalTarget.request(MediaType.APPLICATION_JSON_TYPE);
				if (rdba.getAuth() != null)
					iBuilder = iBuilder.header(RemoteDBAccess.authHeader, rdba.getAuth());
			}

			Response response = null;
			Throwable exception = null;
			try {
				if (failed)
					response = iBuilder.delete();
				else
					response = iBuilder.post(Entity.entity(emptyJSON, MediaType.APPLICATION_JSON_TYPE));
			} catch(Throwable e) {
				exception = e;
			}

			errors = DBUtil.buildErrorList(response, exception);
		} else
			errors = new ArrayList<JcError>();

		if (errors.size() > 0)
			failure();
		setClosed();

		return errors;
	}

	private RemoteDBAccess getRDBAccess() {
		return (RemoteDBAccess)getDBAccess();
	}

	public synchronized Invocation.Builder getInvocationBuilder() {
		Invocation.Builder ret;
		RemoteDBAccess rdba = getRDBAccess();
		if (this.invocationBuilder_open == null) {
			WebTarget serverRootTarget = rdba.getRestClient().target(rdba.getServerRootUri());
			WebTarget transactionalTarget = serverRootTarget.path(transactionalURLPostfix);
			this.invocationBuilder_open = transactionalTarget.request(MediaType.APPLICATION_JSON_TYPE);
			if (rdba.getAuth() != null)
				this.invocationBuilder_open = this.invocationBuilder_open.header(RemoteDBAccess.authHeader, rdba.getAuth());
			ret = this.invocationBuilder_open;
		} else if (this.invocationBuilder_next == null) {
			this.invocationBuilder_next = createNextInvocationBuilder();
			ret = this.invocationBuilder_next;
		} else {
			ret = this.invocationBuilder_next;
		}
		return ret;
	}

	public void setTxLocation(String txLoc) {
		if (this.txLocation == null) {
			int idx = txLoc.indexOf(transactionalURLPostfix);
			this.txLocation = txLoc.substring(idx);
		}
	}

	private Invocation.Builder createNextInvocationBuilder() {
		Invocation.Builder ret;
		RemoteDBAccess rdba = getRDBAccess();
		WebTarget serverRootTarget = rdba.getRestClient().target(rdba.getServerRootUri());
		WebTarget transactionalTarget = serverRootTarget.path(this.txLocation);
		ret = transactionalTarget.request(MediaType.APPLICATION_JSON_TYPE);
		if (rdba.getAuth() != null)
			ret = ret.header(RemoteDBAccess.authHeader, rdba.getAuth());
		return ret;
	}

}


text:
namespace Microsoft.AspNetCore.Mvc.Formatters.Xml;

/// <summary>
/// Wraps the object of type <see cref="Microsoft.AspNetCore.Mvc.SerializableError"/>.
/// </summary>
public class SerializableErrorWrapperProvider : IWrapperProvider
{
    /// <inheritdoc />
    public Type WrappingType => typeof(SerializableErrorWrapper);

    /// <inheritdoc />
    public object? Wrap(object? original)
    {
        if (original == null)
        {
            throw new ArgumentNullException(nameof(original));
        }

        var error = original as SerializableError;
        if (error == null)
        {
            throw new ArgumentException(
                Resources.FormatWrapperProvider_MismatchType(
                    typeof(SerializableErrorWrapper).Name,
                    original.GetType().Name),
                nameof(original));
        }

        return new SerializableErrorWrapper(error);
    }
}


text:
package gov.nih.nci.cabig.caaers.service.synchronizer;

import gov.nih.nci.cabig.caaers.dao.ConfigPropertyDao;
import gov.nih.nci.cabig.caaers.domain.ConfigPropertyType;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.domain.report.ReportType;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Sameer Sawant
 */
public class ReportDefinitionSynchronizer extends CompositeSynchronizer<ReportDefinition>{

	private ConfigPropertyDao configPropertyDao;
    private List<String> context = new ArrayList<String>();

	public void setConfigPropertyDao(ConfigPropertyDao configPropertyDao) {
		this.configPropertyDao = configPropertyDao;
	}

    @Override
    public List<String> contexts() {
        return context;
    }

	@Override
	/**
	 * Will sync the basic properties of the source ReportDefinition to destination ReportDefinition.
	 */
	public void preMigrate(ReportDefinition xmlReportDefinition, ReportDefinition dbReportDefinition,
		DomainObjectImportOutcome<ReportDefinition> outcome) {
		//Populate Class Level Attributes
		dbReportDefinition.setName(xmlReportDefinition.getName());
		dbReportDefinition.setLabel(xmlReportDefinition.getLabel());
		dbReportDefinition.setDescription(xmlReportDefinition.getDescription());
		dbReportDefinition.setAmendable(xmlReportDefinition.getAmendable());
		dbReportDefinition.setDuration(xmlReportDefinition.getDuration());
		dbReportDefinition.setPhysicianSignOff(xmlReportDefinition.getPhysicianSignOff());
		dbReportDefinition.setAttributionRequired(xmlReportDefinition.getAttributionRequired());
		dbReportDefinition.setTimeScaleUnitType(xmlReportDefinition.getTimeScaleUnitType());
		dbReportDefinition.setReportFormatType(xmlReportDefinition.getReportFormatType());

		//Populate Organization
		dbReportDefinition.setOrganization(xmlReportDefinition.getOrganization());

		//Populate Parent
		dbReportDefinition.setParent(xmlReportDefinition.getParent());
		dbReportDefinition.setWorkflowEnabled(xmlReportDefinition.getWorkflowEnabled());

		//populate the correct config property
		if(xmlReportDefinition.getGroup() == null){
			dbReportDefinition.setGroup(configPropertyDao.getByTypeAndCode(ConfigPropertyType.REPORT_GROUP,"RT_AdEERS"));
		}else{
			dbReportDefinition.setGroup(xmlReportDefinition.getGroup());
		}
		if(xmlReportDefinition.getReportType() == null){
			dbReportDefinition.setReportType(ReportType.REPORT);
		}else{
			dbReportDefinition.setReportType(xmlReportDefinition.getReportType());
		}
	}
}


text:
{% ckan_extends %}

{% block styles %}
  	{{ super() }}
	<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet">
	{% resource 'openbudgetsin_theme/openbudgetsin_theme_base.css' %}
{% endblock %}

{% block meta %}
      {{ super() }}
  <meta charset="utf-8">

{% block meta_description %}
    <meta name="description" content="Making India's Budgets Open, Usable and Easy to Comprehend. Find Union Budgets, State Budgets, RBI data and Municipal budgets across years. Gain inferences from Budget Data Visualizations. We are a comprehensive and user-friendly open data portal facilitating free, easy and timely access to relevant data on government budgets in India.">
{% endblock %}
{% block meta_abstract %}

{% endblock %}
{% block meta_keyword %}
<meta name="keywords" content="Open Budgets India, Union Budget, State Budgets, Municipal Budgets, OBI, Data Portal India, Open Budgets Data Portal, Open Data, Free Data, Open Budgets Data India, Data Science, Data Visualization, RBI, IPFS, CSV, Budget Data" />
{% endblock %}
    <meta name="application-name" content="openbudgetsindia.org">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@OpenBudgetsIn">
    <meta name="twitter:title" content="Open Budgets India">
    <meta name="twitter:description" content="Making India's Budgets Open, Usable and Easy to Comprehend. Find Union Budgets, State Budgets, RBI data and Municipal budgets across years. Gain inferences from Budget Data Visualizations. We are a comprehensive and user-friendly open data portal facilitating free, easy and timely access to relevant data on government budgets in India.">
    <meta name="twitter:url" content="https://openbudgetsindia.org/">
    <meta name="twitter:image:src" content="https://openbudgetsindia.org/metatags-29.png">

{% block og_objs %}
    <meta property="og:title" content="Open Budgets India" />
    <meta property="og:description" content="Making India's Budgets Open, Usable and Easy to Comprehend. Find Union Budgets, State Budgets, RBI data and Municipal budgets across years. Gain inferences from Budget Data Visualizations. We are a comprehensive and user-friendly open data portal facilitating free, easy and timely access to relevant data on government budgets in India.">
    <meta property="og:type" content="website" >
    <meta property="og:url" content="https://openbudgetsindia.org/" >
    <meta property="og:image" content="https://openbudgetsindia.org/metatags-28.png" >
    <meta property="og:site_name" content="Open Budgets India" >
{% endblock %}

    <meta name="apple-mobile-web-app-title" content="Open Budgets India">
{% endblock %}


text:
package client

import (
	"io"
	"net/http"
	"net/url"
	"strings"
)

// PutForm makes a PUT request with form values.
func PutForm(url string, data url.Values) (resp *http.Response, err error) {
	return Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}

// Put makes a PUT request.
func Put(url string, bodyType string, body io.Reader) (resp *http.Response, err error) {
	req, err := http.NewRequest("PUT", url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", bodyType)
	client := http.Client{}
	return client.Do(req)
}


text:
import java.util.ArrayList;
/**
 * Represents the schedule of a student.
 *
 * @author (Kush Kalra)
 * @version (1/6/2015)
 */
public class Schedule
{
    private String[][] sched;   // represents a week's schedule. rows represent periods (0-6)
    // and columns represent days of the week (0=Monday,1=Tuesday,...,4=Friday)
    private final int NUM_PERIODS = 7;
    private final int NUM_DAYS_IN_WEEK = 5;

    /**
     * Builds the schedule for a given student.
     * @param s the student whose schedule you wish to build
     */
    public Schedule(Student s)
    {
        sched=new String[NUM_PERIODS][NUM_DAYS_IN_WEEK];
        for (Course currentCourse: s.getCoursesTaken()) // your goal is to get the list of courses for the current student,
        {
            String block=currentCourse.getBlock();
            String name=currentCourse.getName();

            for (int i=0; i<block.length(); i++)
            {
                if (block.charAt(i)!=('x'))
                {

                    int period = Integer.parseInt(block.substring(i,i+1));
                    sched[period-1][i]=name;
                    // extract the schedule block from each course,
                    // and then populate the sched 2-D array with the NAME of the course at all its
                    // meeting times.
                    //
                    // Example: if Math 444 meets in the 123x2 block, then it meets Monday 1st period,
                    // Tuesday 2nd period, Wednesday 3rd period, not on Thursdays, and Friday 2nd period.
                    // After this constructor finishes running, sched should have been initialized such that:
                    // sched[0][0] == "Math 444"   // period 1 on Monday
                    // sched[1][1] == "Math 444"   // period 2 on Tuesday
                    // sched[2][2] == "Math 444"   // period 3 on Wednesday
                    // sched[1][4] == "Math 444"   // period 2 on Fridays
                }

            }
        }

    }

    // DO NOT MODIFY THE METHODS BELOW
    /**
     * Prints the schedule to the terminal window
     */
    public void printSchedule()
    {
        System.out.println("  #  |   MONDAY   |  TUESDAY   | WEDNESDAY  |  THURSDAY  |   FRIDAY   |");
        System.out.println("-----------------------------------------------------------------------");
        for (int p = 0; p < NUM_PERIODS; p++)
        {
            System.out.print("  " + (p+1) + "  |");
            for (int d = 0; d < NUM_DAYS_IN_WEEK; d++)
            {
                String curCourse = sched[p][d];
                if (curCourse == null)
                {
                    curCourse = "        ";
                }
                else
                {
                    curCourse += "        ";
                    curCourse = curCourse.substring(0,8);
                }
                System.out.print("  " + curCourse + "  |");
            }
            System.out.println();
            System.out.println("-----------------------------------------------------------------------");
        }
    }
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import os
import shutil
import subprocess
import sys

from pants.backend.codegen.targets.python_thrift_library import PythonThriftLibrary
from pants.backend.python.code_generator import CodeGenerator
from pants.base.build_environment import get_buildroot
from pants.util.dirutil import safe_mkdir, safe_walk
from pants.util.memo import memoized_property

class PythonThriftBuilder(CodeGenerator):
  """Generate Python code from thrift IDL files."""
  class UnknownPlatformException(CodeGenerator.Error):

    def __init__(self, platform):
      super(PythonThriftBuilder.UnknownPlatformException, self).__init__(
          'Unknown platform: {}!'.format(str(platform)))

  def __init__(self, thrift_binary_factory, workdir, target, root_dir, target_suffix=None):
    super(PythonThriftBuilder, self).__init__(workdir, target, root_dir,
                                              target_suffix=target_suffix)
    self._thrift_binary_factory = thrift_binary_factory
    self._workdir = os.path.join(workdir, 'py-thrift')

  @property
  def install_requires(self):
    return ['thrift']

  @memoized_property
  def _thrift_binary(self):
    return self._thrift_binary_factory().path

  def run_thrifts(self):
    """Generate Python thrift code.

    Thrift fields conflicting with Python keywords are suffixed with a trailing
    underscore (e.g.: from_).
    """

    def is_py_thrift(target):
      return isinstance(target, PythonThriftLibrary)

    all_thrifts = set()

    def collect_sources(target):
      abs_target_base = os.path.join(get_buildroot(), target.target_base)
      for source in target.payload.sources.relative_to_buildroot():
        source_root_relative_source = os.path.relpath(os.path.join(get_buildroot(), source), abs_target_base)
        all_thrifts.add((abs_target_base, source_root_relative_source))

    self.target.walk(collect_sources, predicate=is_py_thrift)

    copied_sources = set()
    for abs_base, relative_source in all_thrifts:
      abs_source = os.path.join(abs_base, relative_source)
      copied_source = os.path.join(self._workdir, relative_source)

      safe_mkdir(os.path.dirname(copied_source))
      shutil.copyfile(abs_source, copied_source)
      copied_sources.add(copied_source)

    for src in copied_sources:
      if not self._run_thrift(src):
        raise PythonThriftBuilder.CodeGenerationException(
          "Could not generate .py from {}!".format(src))

  def _run_thrift(self, source):
    args = [
        self._thrift_binary,
        '--gen',
        'py:new_style',
        '-o', self.codegen_root,
        '-I', self._workdir,
        os.path.abspath(source)]

    po = subprocess.Popen(args, cwd=self.chroot.path())
    rv = po.wait()
    if rv != 0:
      comm = po.communicate()
      print('thrift generation failed!', file=sys.stderr)
      print('STDOUT', file=sys.stderr)
      print(comm[0], file=sys.stderr)
      print('STDERR', file=sys.stderr)
      print(comm[1], file=sys.stderr)
    return rv == 0

  @property
  def package_dir(self):
    return "gen-py"

  def generate(self):
    # auto-generate the python files that we bundle up
    self.run_thrifts()

    # Thrift generates code with all parent namespaces with empty __init__.py's. Generally
    # speaking we want to drop anything w/o an __init__.py, and for anything with an __init__.py,
    # we want to explicitly make it a namespace package, hence the hoops here.
    for root, _, files in safe_walk(os.path.normpath(self.package_root)):
      reldir = os.path.relpath(root, self.package_root)
      if reldir == '.':  # skip root
        continue
      if '__init__.py' not in files:  # skip non-packages
        continue
      init_py_abspath = os.path.join(root, '__init__.py')
      module_path = self.path_to_module(reldir)
      self.created_packages.add(module_path)
      if os.path.getsize(init_py_abspath) == 0:  # empty __init__, translate to namespace package
        with open(init_py_abspath, 'wb') as f:
          f.write(b"__import__('pkg_resources').declare_namespace(__name__)")
        self.created_namespace_packages.add(module_path)
      else:
        # non-empty __init__, this is a leaf package, usually with ttypes and constants, leave as-is
        pass

    if not self.created_packages:
      raise self.CodeGenerationException('No Thrift structures declared in {}!'.format(self.target))


text:
package org.motechproject.scheduletracking.domain.exception;

/**
 * Thrown when adding floating alerts for the absolute schedules.
 */
public class InvalidScheduleDefinitionException extends RuntimeException {

    private static final long serialVersionUID = -8635795766665154050L;

    public InvalidScheduleDefinitionException(String s, String... args) {
        super(String.format(s, args));
    }
}


text:
class EventsController {
	constructor() {
		if(!(this instanceof EventsController)){
			return new EventsController();
		}
		this._events = Object.create(null);
	}

	add(el, type, handler, phrase = false) {
		el.addEventListener(type, handler, !!phrase);
		(this._events[type] || (this._events[type] = [])).push({
			el,
			type,
			handler
		});
		return this;
	}

	remove(type) {
		if(this._events[type]){
			const events = this._events[type];
			for(let event of events){
				event.el.removeEventListener(event.type, event.handler);
			}
			delete this._events[type];
		}
		return this;
	}

	destroy() {
		const events = this._events;
		for(let key in events){
			this.remove(key);
		}
		this._events = null;
		return null;
	}
}

module.exports = EventsController;


text:
import argparse
import sys

from getpass import getpass
from hashlib import md5

from mushi.core.db import db_session
from mushi.core.db.models import User
from mushi.core.exc import InvalidArgumentError
from mushi.factory import create_app

class Command():

    def __init__(self, argv, **kwargs):
        self.argv = argv

    def __call__(self):
        # Create an application context.
        app = create_app(__name__, [])
        ctx = app.test_request_context()
        ctx.push()

        parser = argparse.ArgumentParser(
            prog=self.argv[0],
            description="Manage the user's account.")
        subparsers = parser.add_subparsers(dest='subcommand')
        subparsers.required = True

        sub = subparsers.add_parser('add', help='add a user')
        sub.add_argument('email', action='store', help="the email of the new user's account")
        sub.add_argument(
            '-n', '--name', dest='name', action='store',
            help='the full name of the user (default: email address)')
        sub.add_argument(
            '-p', '--password', dest='password', action='store',
            help='the full name of the user (will be asked if not provided)')

        sub = subparsers.add_parser('list', help='list users')

        args = parser.parse_args(self.argv[1:])
        if args.subcommand == 'add':
            new_user = User()
            new_user.email = args.email
            new_user.name = args.name or args.email

            if args.password:
                password = args.password
            else:
                password = getpass('password: ')
                if getpass('confirm: ') != password:
                    raise InvalidArgumentError('Password do not match.')
            new_user.password = md5(password.encode()).hexdigest()

            db_session.add(new_user)
            db_session.commit()

        elif args.subcommand == 'list':
            for user in db_session.query(User):
                print('name: {:>15},    email: {:>15}'.format(user.name, user.email))

        ctx.pop()


text:
Profile.delete_all
User.delete_all

Profile.create!(
  domain: "localhost",
  from: "quotes@example.com",
  html: "<!DOCTYPE html>",
  intro: "Hello!",
  name: "Demo",
  subject: "Demo quote",
)

User.create!(
  admin: true,
  email: "admin@example.com",
  name: "Admin",
  password: "topsecret",
)


text:
package net.systran.platform.translation.client.model;

import net.systran.platform.translation.client.model.ErrorResponse;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty;

@ApiModel(description = "")
public class TranslationCancel  {

  private ErrorResponse error = null;

  /**
   * Error of the request
   **/
  @ApiModelProperty(value = "Error of the request")
  @JsonProperty("error")
  public ErrorResponse getError() {
    return error;
  }
  public void setError(ErrorResponse error) {
    this.error = error;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class TranslationCancel {\n");

    sb.append("  error: ").append(error).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
<?php

$total = count($attachments);

if ($total === 0)
{
  throw new Exception("Brak załączników do zaimportowania.");
}

exec_insert('emails', array(
  'createdAt' => time(),
  'from' => $from,
  'to' => $to,
  'subject' => $subject,
  'body' => $body
));

$emailId = $db->lastInsertId();

$sql = <<<SQL
INSERT INTO email_attachments
SET email=:email,
    name=:name,
    type=:type,
    size=:size,
    data=:data
SQL;

$stmt = prepare_stmt($sql);

foreach ($attachments as $attachment)
{
  exec_stmt($stmt, array(
    ':email' => $emailId,
    ':name' => $attachment['name'],
    ':type' => $attachment['type'],
    ':size' => $attachment['size'],
    ':data' => $attachment['data']
  ));
}

$replyText = "Zaimportowano {$total} plik(ów).";


text:
package com.gdxz.zhongbao.server.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.hibernate.hql.ast.tree.QueryNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gdxz.zhongbao.server.DAO.impl.DAOSupportImpl;
import com.gdxz.zhongbao.server.domain.Answer;
import com.gdxz.zhongbao.server.domain.Question;
import com.gdxz.zhongbao.server.domain.User;
import com.gdxz.zhongbao.server.domain.UserDynamic;
import com.gdxz.zhongbao.server.service.AnswerService;
import com.gdxz.zhongbao.server.service.QuestionService;
import com.gdxz.zhongbao.server.service.UserDynamicService;
import com.gdxz.zhongbao.server.service.UserService;
import com.gdxz.zhongbao.server.servlet.QuestionServlet;
import com.gdxz.zhongbao.server.utils.FileUtils;
import com.gdxz.zhongbao.server.utils.PropertiesUtils;

@Service("questionService")
public class QuestionServiceImpl extends DAOSupportImpl<Question> implements QuestionService
{

	@Autowired
	private UserService userService;
	@Autowired
	private UserDynamicService userDynamicService;
	@Autowired
	private AnswerService answerService;

	/**
	 * 根据category和pageNow获得数据 1:pageNow为返回对应为第几页
	 * 2:category确定返回的是什么类型的数据(最新发布,今日热榜,总排行榜)
	 */
	public List<Question> loadQuestionData(int pageNow, int category)
	{
		String hql = "";
		if (category == QuestionServlet.NEWLY_QUESTION)// 最新提问
		{
			hql = "from Question order by postTime desc";
			// hql="select author from Question";
		}
		else if (category == QuestionServlet.TODAY_HOT_RANKING)// 今日热榜
		{
			hql = "from Question order by todayReplyChange desc";
		}
		else if (category == QuestionServlet.TOTAL_RANKING)
		{
			hql = "from Question order by replyCount desc";
		}
		List<Question> list = getByPage(pageNow, QuestionServlet.PAGE_SIZE, hql, null);
		if (list != null)
		{
			return list;
		}
		return null;
	}

	/**
	 * 添加问题的浏览次数
	 */
	public void addBrowseCount(String questionId)
	{
		Question question = getById(Integer.parseInt(questionId));
		Integer browseCount = question.getBrowseCount();
		question.setBrowseCount((browseCount == null ? 0 : browseCount) + 1);
		update(question);

	}

	/**
	 * 添加问题的回复次数
	 */
	public void addReplyCount(String questionId)
	{
		Question question = getById(Integer.parseInt(questionId));
		Integer replyCount = question.getReplyCount();
		question.setReplyCount((replyCount == null ? 0 : replyCount) + 1);
		update(question);

	}

	/**
	 * 收藏一个问题
	 */
	public void followQuestion(int userId, int questionId)
	{
		Question question = getById(questionId);
		User user=userService.getById(userId);
		UserDynamic userDynamic = new UserDynamic();
		userDynamic.setUpdateTime(new Date());
		userDynamic.setQuestion(question);
		userDynamic.setUser(user);
		userDynamic.setType(UserDynamic.DYNAMIC_TYPE_FOLLOW);
		userDynamicService.save(userDynamic);
	}

	/**
	 * 查询用户是否关注了该问题
	 */
	public boolean hadFollow(int userId, int questionId)
	{
		System.out.println(userId + "," + questionId);
		String hql = "select count(*) from UserDynamic where userId=? and questionId=? and type=?";
		int count = queryCount(hql, new Object[] { userId, questionId,
				UserDynamic.DYNAMIC_TYPE_FOLLOW });
		if (count > 0)
		{
			return true;
		}
		return false;
	}

	/**
	 * 发布一个问题
	 */
	public String postQuestion(Iterator<FileItem> it, int userId, Question question)
			throws Exception
	{
		StringBuffer sb = new StringBuffer(question.getContent());
		boolean hasVoiceFile = false;
		boolean hasImageFile = false;
		File saveFile = null;
		List<String> files = new ArrayList<String>();
		User user = userService.getById(userId);
		int point = user.getPoint() == null ? 0 : user.getPoint();
		if (point - question.getRewardAmount() >= 0)
		{
			if (it != null)
			{
				while (it.hasNext())
				{
					FileItem fileItem = (FileItem) it.next();
					if (fileItem.isFormField())
					{
						continue;
					}
					else
					{
						String fileName = fileItem.getName();
						String fileType = fileName.substring(fileName.lastIndexOf("."),
								fileName.length());

						if (".amr".equals(fileType))
						{
							// 有语音文件
							hasVoiceFile = true;
							saveFile = FileUtils.createFile(
									PropertiesUtils.getProperty("uploadFileBasePath")
											+ Question.getQuestionVoiceBasePath(userId), fileType);
						}
						else
						{
							// 有图片文件
							hasImageFile = true;
							saveFile = FileUtils.createFile(
									PropertiesUtils.getProperty("uploadFileBasePath")
											+ Question.getQuestionImageBasePath(userId), fileType);
						}
						fileItem.write(saveFile);
						files.add(saveFile.getName());
					}
				}
				if (hasImageFile || hasVoiceFile)// 如果有图片文件或者,将文件名拼接到content的后面,格式为/文件名/
				{
					for (String fileName : files)
					{
						sb.append("/" + fileName + "/");
					}
				}
				question.setContent(sb.toString());
			}
			question.setAuthor(user);
			question.setPostTime(new Date());
			save(question);
			// 维护userDynamic表
			UserDynamic userDynamic = new UserDynamic();
			userDynamic.setQuestion(question);
			userDynamic.setType(UserDynamic.DYNAMIC_TYPE_ASK);
			userDynamic.setUser(question.getAuthor());
			userDynamic.setUpdateTime(question.getPostTime());
			userDynamicService.save(userDynamic);
			return null;
		}
		else
		{
			return "剩余积分不足";
		}
	}

	/**
	 * 根据id获得该问题所有的用户
	 */
	public List<User> getAnswerersByQuestionId(Integer id)
	{
		String hql = "from Answer where questionId=? ";
		List<Answer> answers = answerService.query(hql, new Object[] { id });
		List<User> answerers = new ArrayList<User>();
		for (Answer answer : answers)
		{
			answerers.add(answer.getAuthor());
		}
		return answerers;
	}

	/**
	 * 根据问题id获得最佳回答的用户
	 */
	public User getBestAnswerer(Integer id)
	{
		String hql = "from Answer where questionId=? ";
		List<Answer> answers = answerService.query(hql, new Object[] { id });
		User bestAnswerer = null;
		for (Answer answer : answers)
		{
			if (answer.getIsBest())
			{
				bestAnswerer = answer.getAuthor();
			}
		}
		return bestAnswerer;
	}

}


text:
using System;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace Authentication
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Require authenticated users
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();

            // Add Mvc types
            services.AddMvc(options =>
            {
                // Add global auth filter
                options.Filters.Add(new AuthorizeFilter(policy));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseRuntimeInfoPage();
                app.UseDeveloperExceptionPage();
            }

            // Use cookie authentication
            app.UseCookieAuthentication(options =>
            {
                options.AuthenticationScheme = "Cookies";
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                options.SlidingExpiration = true;
            });

            app.UseIISPlatformHandler();
            app.UseStaticFiles();
            app.UseMvc(routes =>
                routes.MapRoute("default",
                    "{controller=Home}/{action=Index}/{id?}"));
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}


text:
package net.haugr.cws.rest;

import static org.junit.jupiter.api.Assertions.assertEquals;

import net.haugr.cws.api.common.ReturnCode;
import net.haugr.cws.api.requests.SanityRequest;
import javax.ws.rs.core.Response;
import org.junit.jupiter.api.Test;

/**
 * @author Kim Jensen
 * @since CWS 1.0
 */
final class SanityServiceTest extends BeanSetup {

    @Test
    void testSanitized() {
        final SanityService service = prepareSanityService(settings, entityManager);
        final SanityRequest request = new SanityRequest();

        final Response response = service.sanitized(request);
        assertEquals(ReturnCode.SUCCESS.getHttpCode(), response.getStatus());
    }

    @Test
    void testFlawedSanitized() {
        final SanityService service = prepareSanityService();
        final SanityRequest request = new SanityRequest();

        final Response response = service.sanitized(request);
        assertEquals(ReturnCode.SUCCESS.getHttpCode(), response.getStatus());
    }
}


text:
<?php
include('includes/connection.php');
if(isset($_POST['login']))
{	$check=0;
	$email = mysqli_real_escape_string($con,$_POST['email']);
	$pass = mysqli_real_escape_string($con,$_POST['pass']);
	$get_email = "SELECT * FROM users WHERE user_email='$email' AND user_pass='$pass'";
	$run_user = mysqli_query($con,$get_email) or die(mysqli_error($con));
	$check = mysqli_num_rows($run_user);
	if($check==1)
	{
		$_SESSION['user_email']=$email;

		echo "<script> window.open('home.php','_self')</script>" ;
	}
	else
	{
	echo "<script> alert('Password or Email id is incorrect')</script>" ;
	}
}
?>


text:
package mytest

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

val mode = "production"

class BasicSimulation extends Simulation {

  val httpConf = http
    .baseURL("http://127.0.0.1/")
    .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-US,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")
    .userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")

  val scn =     scenario("BasicSimulation") .exec(
          http("request_1").post("some_action")
0          .formUpload("key", "tests/data/test1.csv")
1          .bodyPart(RawFileBodyPart("file", "tests/data/unicode_file").contentType("application/binary").fileName("unicode_file")).asMultipartForm
2          .body(RawFileBody("tests/json/dummy.json"))
3          .body(ELFileBody("tests/json/includes.json"))
4          .body(RawFileBodyPart("tests/json/get-post.json"))
5          .body(RawFileBodyPart("file_name", "tests/json/passfail.json"))
6          .body(ELFileBodyPart("tests/json/mock_start_err.json"))
7          .body(ELFileBodyPart("file_name", "tests/json/throughput.json"))

8!          csv("tests/json/gatling_" + mode + ".json")
9          csv("tests/json/gatling.json")
10          tsv("tests/json/get-post.json")
11          ssv("tests/json/merge2.json")
12          separatedValues("tests/json/reporting.json", "#")
13          jsonFile("tests/json/mock_normal.json")

      )

  setUp(
    scn.inject(atOnceUsers(10))
  ).protocols(httpConf)
}


text:
/**
 *
 * @creatTime 下午4:51:17
 * @author Eddy
 */
package org.eddy.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Eddy
 *
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValidateRule {

	/**
	 * 模板名称
	 * @return
	 * @creatTime 下午12:03:25
	 * @author Eddy
	 */
	String name();
}


text:
using System;
using Diskordia.UndoRedo.Invokations;
using Moq;
using Xunit;

namespace Diskordia.UndoRedo
{
    public class UndoManagerTests
    {
        [Fact]
        public void Constrcutor_TransactionFactoryNullReference_ThrowsException()
        {
            Assert.Throws<ArgumentNullException>(() => new UndoManager(null));
        }

        [Fact]
        public void RegisterInvocation_InvokationNullReference_ThrowsException()
        {
            var target = new UndoManager();

            Assert.Throws<ArgumentNullException>(() => target.RegisterInvokation((IInvokable)null));
        }

        [Fact]
        public void RegisterInvocation_Invokation_RegistersInvokation()
        {
            var target = new UndoManager();

            var invokableMock = new Mock<IInvokable>(MockBehavior.Strict);
            target.RegisterInvokation(invokableMock.Object);

            Assert.True(target.CanUndo);
            Assert.False(target.CanRedo);
        }

        [Fact]
        public void RegisterInvocation_DelegateNullReference_ThrowsException()
        {
            var target = new UndoManager();

            Assert.Throws<ArgumentNullException>(() => target.RegisterInvokation((Action<string>)null, string.Empty));
        }

        [Fact]
        public void RegisterInvocation_ActionArgumentNullReference_ThrowsException()
        {
            var target = new UndoManager();

            var targetMock = new Mock<ITarget>();

            Assert.Throws<ArgumentNullException>(() => target.RegisterInvokation(targetMock.Object.Add, (string)null));
        }

        [Fact]
        public void RegisterInvocation_ActionDelegate_RegistersAction()
        {
            var target = new UndoManager();

            var targetMock = new Mock<ITarget>();
            target.RegisterInvokation(targetMock.Object.Add, "test");

            Assert.True(target.CanUndo);
            Assert.False(target.CanRedo);
        }

        [Fact]
        public void RegisterInvocation_ExpressionNullReference_ThrowsException()
        {
            var target = new UndoManager();

            var targetMock = new Mock<ITarget>();

            Assert.Throws<ArgumentNullException>(() => target.RegisterInvokation(targetMock.Object, null));
        }

        [Fact]
        public void RegisterInvocation_TargetNullReference_ThrowsException()
        {
            var target = new UndoManager();

            var targetMock = new Mock<ITarget>();

            Assert.Throws<ArgumentNullException>(() => target.RegisterInvokation<ITarget>(null, t => t.UndoOperation()));
        }

        [Fact]
        public void RegisterInvocation_LambdaExpression_RegistersLambdaExpression()
        {
            var target = new UndoManager();
            var targetMock = new Mock<ITarget>();
            target.RegisterInvokation(targetMock.Object, t => t.UndoOperation());

            Assert.True(target.CanUndo);
            Assert.False(target.CanRedo);
        }

        [Fact]
        public void Undo_NoInvocationsRegistered_ThrowsException()
        {
            var target = new UndoManager();

            Assert.Throws<InvalidOperationException>(() => target.Undo());
        }

        [Fact]
        public void Undo_InvocationRegistered_InvokesUndoOperation()
        {
            var target = new UndoManager();

            var invokableMock = new Mock<IInvokable>(MockBehavior.Loose);
            target.RegisterInvokation(invokableMock.Object);

            target.Undo();

            invokableMock.Verify(i => i.Invoke(), Times.Once());
            Assert.False(target.CanUndo);
            Assert.False(target.CanRedo);
        }

        [Fact]
        public void Undo_UndoOperationRegistersInvocations_InvocationsAreRegisteredInRedoStack()
        {
            var target = new UndoManager();

            var invokableMock = new Mock<ITarget>(MockBehavior.Strict);
            invokableMock.Setup(i => i.UndoOperation())
                .Callback(() => target.RegisterInvokation(invokableMock.Object, i => i.RedoOperation()));

            target.RegisterInvokation(invokableMock.Object, i => i.UndoOperation());

            target.Undo();

            invokableMock.Verify(i => i.UndoOperation(), Times.Once());
            invokableMock.Verify(i => i.RedoOperation(), Times.Never());
            Assert.False(target.CanUndo);
            Assert.True(target.CanRedo);
        }

        [Fact]
        public void Redo_NoRedoInvocationsRegistered_ThrowsException()
        {
            var target = new UndoManager();

            Assert.Throws<InvalidOperationException>(() => target.Redo());
        }

        [Fact]
        public void Redo_RedoOperationAvailable_InvokesRedoOperation()
        {
            var target = new UndoManager();

            var invokableMock = new Mock<ITarget>(MockBehavior.Strict);
            invokableMock.Setup(i => i.UndoOperation())
                .Callback(() => target.RegisterInvokation(invokableMock.Object, i => i.RedoOperation()));
            invokableMock.Setup(i => i.RedoOperation());

            target.RegisterInvokation(invokableMock.Object, i => i.UndoOperation());

            target.Undo();
            target.Redo();

            invokableMock.Verify(i => i.UndoOperation(), Times.Once());
            invokableMock.Verify(i => i.RedoOperation(), Times.Once());
            Assert.False(target.CanUndo);
            Assert.False(target.CanRedo);
        }

        [Fact]
        public void Redo_RedoRegistersInvocation_InvocationsAreRegisteredInUndoStack()
        {
            var target = new UndoManager();

            var invokableMock = new Mock<ITarget>(MockBehavior.Strict);
            invokableMock.Setup(i => i.UndoOperation())
                .Callback(() => target.RegisterInvokation(invokableMock.Object, i => i.RedoOperation()));
            invokableMock.Setup(i => i.RedoOperation())
                .Callback(() => target.RegisterInvokation(invokableMock.Object, i => i.UndoOperation()));

            target.RegisterInvokation(invokableMock.Object, i => i.UndoOperation());

            target.Undo();
            target.Redo();

            invokableMock.Verify(i => i.UndoOperation(), Times.Once());
            invokableMock.Verify(i => i.RedoOperation(), Times.Once());
            Assert.True(target.CanUndo);
            Assert.False(target.CanRedo);
        }
    }
}


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn fiadd_1() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(IndirectScaledIndexed(BP, SI, One, Some(OperandSize::Dword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[218, 2], OperandSize::Word)
}

#[test]
fn fiadd_2() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(IndirectDisplaced(EBX, 1684295499, Some(OperandSize::Dword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[218, 131, 75, 79, 100, 100], OperandSize::Dword)
}

#[test]
fn fiadd_3() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(IndirectScaledIndexedDisplaced(RCX, RDI, Four, 409052741, Some(OperandSize::Dword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[218, 132, 185, 69, 166, 97, 24], OperandSize::Qword)
}

#[test]
fn fiadd_4() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(Indirect(DI, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[222, 5], OperandSize::Word)
}

#[test]
fn fiadd_5() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(IndirectScaledIndexedDisplaced(EDI, ESI, Four, 1260485731, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[222, 132, 183, 99, 124, 33, 75], OperandSize::Dword)
}

#[test]
fn fiadd_6() {
    run_test(&Instruction { mnemonic: Mnemonic::FIADD, operand1: Some(Indirect(RSI, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[222, 6], OperandSize::Qword)
}


text:
<application>
  <component name="VagrantSettings">
    <option name="vagrantExecutable" value="/usr/local/bin/vagrant" />
  </component>
</application>


text:
<?php

namespace Omnipay\Helcim\Message;

use Omnipay\Omnipay;
use Omnipay\Common\Message\AbstractRequest as OmnipayAbstractRequest;
use Guzzle\Http\Url;
use Omnipay\Common\Exception\InvalidRequestException;

/**
 * Helcim Abstract Request
 */
abstract class AbstractRequest extends OmnipayAbstractRequest
{
    /**
     * The parts used to construct the endpoint URL.
     * The developer accounts use a different domain to the active (live) accounts.
     * In addition, the active accounts can be run in live or test mode.
     * TODO: these should be constants.
     */
    protected $endpointScheme = 'https';

    protected $endpointDevDomain = 'gatewaytest.helcim.com';
    protected $endpointProdDomain = 'gateway.helcim.com';

    //protected $endpointPathHostedPages = '/hosted/';
    //protected $endpointPathDirectHistory = '/api/';
    //protected $endpointPathDirectActions = '/';
    //protected $endpointPathJS = '/js/version{version}.js';

    /**
     * The transaction action (type).
     * Values are: "purchase", "preauth", "capture", "refund" or "void".
     * Also "recurring", with a start date and special handling of the amount.
     * The Hosted Pages mode only supports preauth and purchase.
     */
    protected $action = 'preauth';

    /**
     * The endpoint URL depends on whether the mode is Direct or Hosted Pages.
     * TODO: at this point it may be worth adding another layer of AbstractRequest to
     * differentiate between the two (at the moment) modes. This would reduct conditional
     * checking and duplication on the mode property across multiple Request classes.
     */
    protected $mode = 'direct';

    /**
     *
     */

    public function setDeveloperMode($value)
    {
        return $this->setParameter('developerMode', $value);
    }

    public function getDeveloperMode()
    {
        return $this->getParameter('developerMode');
    }

    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }

    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }

    public function setAllowZeroAmount($value)
    {
        // Evaluate to true/false
        return $this->setParameter('allowZeroAmount', ! empty($value));
    }

    public function getAllowZeroAmount()
    {
        return $this->getParameter('allowZeroAmount');
    }

    public function setCardholderName($value)
    {
        return $this->setParameter('cardholderName', $value);
    }

    public function getCardholderName()
    {
        return $this->getParameter('cardholderName');
    }

    // The cardHolder Address and PostalCode feeds into address verification services.

    public function setCardholderAddress($value)
    {
        return $this->setParameter('cardholderAddress', $value);
    }

    public function getCardholderAddress()
    {
        return $this->getParameter('cardholderAddress');
    }

    public function setCardholderPostalCode($value)
    {
        return $this->setParameter('cardholderPostalCode', $value);
    }

    public function getCardholderPostalCode()
    {
        return $this->getParameter('cardholderPostalCode');
    }

    // OmniPay has set/getToken() already. Can we use that?
    // Perhaps it can be used to accept the "gateway-token|form-token" or something?

    public function setGatewayToken($value)
    {
        return $this->setParameter('gatewayToken', $value);
    }

    public function getGatewayToken()
    {
        return $this->getParameter('gatewayToken');
    }

    public function setFormToken($value)
    {
        return $this->setParameter('formToken', $value);
    }

    public function getFormToken()
    {
        return $this->getParameter('formToken');
    }

    public function setShippingAmount($value)
    {
        return $this->setParameter('shippingAmount', $value);
    }

    public function getShippingAmount()
    {
        return $this->getParameter('shippingAmount');
    }

    public function setTaxAmount($value)
    {
        return $this->setParameter('taxAmount', $value);
    }

    public function getTaxAmount()
    {
        return $this->getParameter('taxAmount');
    }

    public function setCustomerId($value)
    {
        return $this->setParameter('customerId', $value);
    }

    public function getCustomerId()
    {
        return $this->getParameter('customerId');
    }

    public function setCvvIndicator($value)
    {
        return $this->setParameter('cvvIndicator', $value);
    }

    public function getCvvIndicator()
    {
        return $this->getParameter('cvvIndicator');
    }

    /**
     * Workaround for https://github.com/thephpleague/omnipay-common/issues/13
     */
    public function setAmount($value)
    {
        if (is_float($value) && $value === 0.0) {
            $value = '0.00';
        }

        parent::setAmount($value);
    }

    // cardoken and carF4l4 can be sent as an alternative to the
    // credit card number, expiry and CVV.
    // Only needed for Direct payment and preauth transactions.

    public function setCardToken($value)
    {
        return $this->setParameter('cardToken', $value);
    }

    public function getCardToken()
    {
        return $this->getParameter('cardToken');
    }

    // The card first four and last four digits are needed for taking payments on
    // a tokenised card.

    public function setCardF4l4($value)
    {
        return $this->setParameter('cardF4l4', $value);
    }

    public function getCardF4l4()
    {
        return $this->getParameter('cardF4l4');
    }

    /**
     * The method can be left as GET for simple payments or POST for more complex payments.
     */
    public function getMethod()
    {
        return $this->getParameter('method');
    }

    public function setMethod($method)
    {
        // Normalise to GET or POST.
        $method = (strtoupper($method) === 'GET' ? 'GET' : 'POST');

        return $this->setParameter('method', $method);
    }

    protected function getBaseData()
    {
        $data = array();

        $data['merchantId'] = $this->getMerchantId();

        // The search action is indicated to Helcim by not supplying any "type" field.

        if ($this->action != 'search') {
            $data['type'] = $this->action;
        }

        // The test parameter will indicate this is a test transaction. This flag can be
        // used in the production environment. It differs from enabling "developer mode",
        // which switches to an alternative developer environment and operates on different
        // developer merchant accounts.

        if ($this->getTestMode()) {
            $data['test'] = '1';
        }

        return $data;
    }

    /**
     * The Direct base data includes the (secret) Gateway token.
     */

    protected function getDirectBaseData()
    {
        $data = $this->getBaseData();

        $data['token'] = $this->getGatewayToken();

        return $data;
    }

    /**
     * The Hosted Page base data includes the (public) Form token.
     */

    protected function getHostedPagesBaseData()
    {
        $data = $this->getBaseData();

        $data['token'] = $this->getFormToken();

        return $data;
    }

    /**
     * Get billing address, including the name, phone number and email.
     * All parts of the address are optional at the API level, though may be
     * marked as mandatory in the hosted form created on Helcim.
     */
    protected function getBillingAddressData()
    {
        $data = array();

        if ($card = $this->getCard()) {
            // Billing address/person details.

            // Single billing name, first and last joined.

            if ($card->getBillingName()) {
                $data['billingName'] = $card->getBillingName();
            }

            // Single address, 1 and 2 joined.
            // The hosted form provides a single line for this field, so we join with just a space.
            // CHECKME: are either address parts multi-line? May need to convert to a single line.

            if ($card->getBillingAddress1() || $card->getBillingAddress2()) {
                $data['billingAddress'] = trim($card->getBillingAddress1() . ' ' . $card->getBillingAddress2());
            }

            if ($card->getBillingCity()) {
                $data['billingCity'] = $card->getBillingCity();
            }

            if ($card->getBillingState()) {
                $data['billingProvince'] = $card->getBillingState();
            }

            if ($card->getBillingPostcode()) {
                $data['billingPostalCode'] = $card->getBillingPostcode();
            }

            // This is the country spelled out in full, not the ISO3166 code.

            if ($card->getBillingCountry()) {
                $data['billingCountry'] = $card->getBillingCountry();
            }

            if ($card->getBillingPhone()) {
                $data['billingPhoneNumber'] = $card->getBillingPhone();
            }

            // Note: omnipay supports no separate billing and shipping email addresses.

            if ($card->getEmail()) {
                $data['billingEmailAddress'] = $card->getEmail();
            }
        }

        return $data;
    }

    /**
     * Get shiping address, including the name, phone number and email.
     * All parts of the address are optional at the API level.
     */
    protected function getShippingAddressData()
    {
        $data = array();

        if ($card = $this->getCard()) {
            // Single shipping name, first and last joined.

            if ($card->getShippingName()) {
                $data['shippingName'] = $card->getShippingName();
            }

            // Single address, 1 and 2 joined.
            // The hosted form provides a single line for this field, so we join with just a space.

            if ($card->getShippingAddress1() || $card->getShippingAddress2()) {
                $data['shippingAddress'] = trim($card->getShippingAddress1() . ' ' . $card->getShippingAddress2());
            }

            if ($card->getShippingCity()) {
                $data['shippingCity'] = $card->getShippingCity();
            }

            if ($card->getShippingState()) {
                $data['shippingProvince'] = $card->getShippingState();
            }

            if ($card->getShippingPostcode()) {
                $data['shippingPostalCode'] = $card->getShippingPostcode();
            }

            // This is the country spelled out in full, not the ISO3166 code.

            if ($card->getShippingCountry()) {
                $data['shippingCountry'] = $card->getShippingCountry();
            }

            if ($card->getShippingPhone()) {
                $data['shippingPhoneNumber'] = $card->getShippingPhone();
            }

            // Note: there are no separate billing and shipping email addresses in omnipay.

            if ($card->getEmail()) {
                $data['shippingEmailAddress'] = $card->getEmail();
            }
        }

        return $data;
    }

    /**
     * Get the billing data for the transaction.
     * This includes mainly optional and some mandatory details.
     */
    protected function getBillingData()
    {
        $data = array();

        $data['amount'] = $this->getAmount();

        if ($this->getAllowZeroAmount()) {
            $data['allowZeroAmount'] = '1';
        } else {
            // A zero amount without this flag set will be invalid.
            if (isset($data['amount']) && (float)$data['amount'] === 0.0) {
                throw new InvalidRequestException("The amount must not be zero without allowZeroAmount being set");
            }
        }

        if ($this->getDescription()) {
            $data['comments'] = $this->getDescription();
        }

        // There is some difference in language here between OmniPay and Helcim,
        // where the the omnipay transactionId is generated by the application
        // but the Helcim transactionId is generated by Helcim. Just be aware.

        if ($this->getTransactionId()) {
            $data['orderId'] = $this->getTransactionId();
        }

        if ($this->getShippingAmount()) {
            $data['shippingAmount'] = $this->getShippingAmount();
        }

        if ($this->getTaxAmount()) {
            $data['taxAmount'] = $this->getTaxAmount();
        }

        if ($this->getCustomerId()) {
            $data['customerId'] = $this->getCustomerId();
        }

        return $data;
    }

    /**
     * Get the card data.
     * Only used for direct API mode.
     * Start date and issue number are not supported.
     */
    protected function getCardData()
    {
        $data = array();

        // As an alternative to the card data, the tokenised card can be used.
        // This consists of the token that was captured in an earlier transaction,
        // and the outside eight digits of the card number.

        if ($this->getCardToken() && $this->getCardF4l4()) {
            $data['cardToken'] = $this->getCardToken();
            $data['cardF4l4'] = $this->getCardF4l4();
        } else {
            if ($card = $this->getCard()) {
                // Make sure all necessary parts of the card are set.
                // Checks 'number', 'expiryMonth' and 'expiryYear' and will not go
                // any further if they are not set.
                $card->validate();

                // Mandatory fields.
                $data['cardNumber'] = $card->getNumber();
                $data['expiryDate'] = $card->getExpiryDate('my');

                // Optional card fields.
                $getCvv = $card->getCvv();
                if (isset($getCvv) && $getCvv != '') {
                    $data['cvv'] = $getCvv;
                }

                // A custom field for Helcim, indicates how CVV will be handled.
                // The documentation lists this as mandatory for direct mode.

                if ($this->getCvvIndicator()) {
                    $data['cvvIndicator'] = $this->getCvvIndicator();
                }
            }
        }

        return $data;
    }

    /**
     * Get the basket/cart data.
     * A fix is needed to support all the fields we need in basket items. See:
     * https://github.com/omnipay/common/issues/11
     */
    protected function getCartData()
    {
        $cart = array();

        $items = $this->getItems();

        // If no cart (no item bag of items) has been set, then return.

        if (!isset($items)) {
            return $cart;
        }

        $item_count = $items->count();

        // Each item must be sequentially numbered.
        $item_number = 1;

        foreach ($items as $item) {
            //$item_id = $item->getParameter('sku');
            $item_description = $item->getName();
            $item_quantity = $item->getQuantity();
            $item_price = $item->getPrice();
            //$item_total = $item->getParameter('total');

            if (isset($item_id) && $item_id != '') {
                $cart['itemId' . $item_number] = $item_id;
            }

            if (isset($item_description)) {
                $cart['itemDescription' . $item_number] = $item_description;
            }

            // The Helcim API requires the quantity to be at least one (so 0.5kg is, in theory, invalid).
            // However, I believe it is the Helcim documentation that is incorrect here.
            if (isset($item_quantity)) {
                $cart['itemQuantity' . $item_number] = $item_quantity;
            }

            if (isset($item_price)) {
                $cart['itemPrice' . $item_number] = $item_price;
            }

            if (isset($item_total) && $item_total != '') {
                $cart['itemTotal' . $item_number] = $item_total;
            } else {
                // Calculate the item total, if possible, from the quantity and per-item cost.
                if (is_numeric($item_quantity) && is_numeric($item_price)) {
                    $cart['itemTotal' . $item_number] = $item_quantity * $item_price;
                }
            }

            $item_number++;
        }

        return $cart;
    }

    /**
     * Get the AVS (Address Validation Service) fields.
     */
    protected function getAvsData()
    {
        $data = array();

        if ($this->getCardholderAddress()) {
            $data['cardholderAddress'] = $this->getCardholderAddress();
        }

        if ($this->getCardholderPostalCode()) {
            $data['cardholderPostalCode'] = $this->getCardholderPostalCode();
        }

        return $data;
    }

    /**
     * Get the path for the API.
     */
    abstract public function getPath();

    /**
     * The endpoint varies depending on developer mode, and whether the method is GET or POST.
     * If the method is GET, then the data needs to be added to the URL here. I've not found any
     * helper functions to construct URLs in omnipay, but they could be there.
     * It may also be possible to leave the URL construction to Guzzle, assuming Guzzle is able
     * to add an arbitrary list of query parameters to the endpoint that may already have some
     * query parameters.
     * CHECKME: it seems that Guzzle will accept an array containing a template and substitution
     * variables for its endpoint. This would avoid us needing to construct it here.
     */
    public function getEndpoint()
    {
        $domain = $this->getDeveloperMode() ? $this->endpointDevDomain : $this->endpointProdDomain;

        $path = $this->getPath();

        // Build the URL from the parts.
        // There is a dependency on Guzzle here, which OmniPay uses, but may be a
        // bit of an assumption in the longer term.

        $url = new Url($this->endpointScheme, $domain);
        $url->setPath($path);

        if ($this->getMethod() == 'GET') {
            $url->setQuery($this->getData());
        }

        return $url;
    }
}


text:
var options = {
    manager: require("../../../src/managers/master/color-type-manager"),
    model: require("dl-models").master.ColorType,
    util: require("../../data-util/master/color-type-data-util"),
    validator: require("dl-models").validator.master.colorType,
    createDuplicate: false,
    keys: []
};

var basicTest = require("../../basic-test-factory");
basicTest(options);