text:
/*
 * jquery.graphview.js
 *
 * displays graph data results retrieved by querying a specified index
 *
 * created by Mark MacGillivray - mark@cottagelabs.com
 *
 * copyheart 2013
 *
 * VERSION 0.3.0
 *
 *
 */

/* this software comes with some defaults for building a UI on the page, for
binding actions to that UI, for reading and sending a query to the target,
for building results onto the page when the response is retrieved. All of these
can be overwritten. See the defaults for some overview and look at the individual
default functions defined below to figure out how to copy and augment one.

For example provide custom uitemplate and uibindings functions to build specific
UIs. Then provide custom query and executequery functions to read the query from
the UI and to execute it with some cleaning. Then provide custom showresults to
put them on the page as desired. Or some combination of the lot. */

// Deal with indexOf issue in <IE9
// provided by commentary in repo issue - https://github.com/okfn/facetview/issues/18
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

(function($){
    $.fn.graphview = function(options) {

        // ===============================================
        // ===============================================
        //
        // set defaults
        //
        // ===============================================
        // ===============================================

        var defaults = {
            "target": 'http://localhost:5005/everything', // the ES _search endpoint address to query
            "ajaxtype": "GET",
            "datatype": "JSONP", // ajax datatype

            // probably remove graphable from example altogether, as it relies on CL backend stuff.
            "graphable": { // if customised graphable endpoint is available, configure it here
                "enabled": false,
                "ignore":[],
                "only":[],
                "promote":{'record':['keywords','tags']},
                "links":{'wikipedia':['topic'],'reference':['_parents'],'record':['children']},
                "ignoreisolated":false,
                "dropfacets":true,
                "drophits":true,
                "remote_source": "http://129.67.24.26:9200/test/record/_search"
            },

            "suggestsize": 100, // how many suggestions to show in search area dropdowns
            "nodesize": 100, // default number of nodes of each type to show
            "titlefield": "title.exact", // which field from result object is default title field

            "defaultquery": { // define the starting query here - see ES docs
                "query": {
                    "bool": {
                        "must":[]
                    }
                },
                "fields": "*",
                "partial_fields": [],
                "from":0,
                "size":100,
                "facets":{
                    // ES facet settings, plus suggest:true to add to freetext dropdown controller
                    // and node:true to add as a node type for viewing in the graphview
                    "journals": {"term":{"field":"journal.name.exact","suggest": true, "node": true}},
                    "authors": {"term":{"field":"author.name.exact","suggest": true, "node": true}},
                    "titles": {"term":{"field":"title.exact","suggest": true, "node": true}},
                    "keywords": {"term":{"field":"keyword.exact","suggest": true, "node": false}},
                    "range": {"date_histogram": {"interval": "month", "field": "date"}}
                }
            },

            "nested": [],
            "sort":[],
            "default_operator": "AND", // ES default operator param
            "query_string_fuzzify": "*", // this and default_operator are used by default query function

            "fill": "a function that provides colors to be used on the bubbles. default defined below",

            "showresults": "a function that displays the query results - takes data obj as param (default defined below)",
            "response": "the default showresults writes the query results object into this key, for further access",
            "nodes": "for building a force graph, the node data is required. the default showresults calculates and stores here",
            "links": "links data is also required for the default force graph. default showresults calculates and stores here",
            "linksindex": "and similarly an index of links and what nodes they attach to, at various depths",
            "afterresults": false, // define a callback function to run once the default showresults is finished

            "dragging": false, // the default UI and query allow nodes to be dragged on the search. A dragged node can be found here
            "query": "is a function that returns the current query object (default defined below)",
            "executequery": "the function to run when a query should be executed (the default is defined below)",

            "uitemplate": "a function that returns a template (e.g. a bunch of html) for the UI controls to be created (default defined below)",
            "uibindings": "things to be bound to the ui template once it has been appended to the target element. Limit the bindings to obj",

            "sharesave": true, // shows a button that provides the current query for copying
            "sharesave_include_facets": false, // include facets in above or not (longer querystring)

            "searchonload": true, // run default search as soon as page loads
            "searchhintline": "type search terms and click enter to search, choose a suggestion type to get search term hints",
            "pushstate": false, // put current query state in url whenever it updates
            "focusdepth": 1 // how many nodes removed to highlight during hover
            // more than depth 1 is probably a bad idea unless the depths are calculated server-side...
            // if there are sufficiently complex relations it can take a long time to process in the client

        };

        // ===============================================
        // ===============================================
        //
        // force directed network graph functions
        //
        // these are used by the default results display
        //
        // ===============================================
        // ===============================================

        defaults.fill = d3.scale.category10();

        var label = function(d) {
            // calculate a label
            var label = '';
            if ( d.value ) { d.value > 1 ? label += '(' + d.value + ') ' : false; }
            if ( d.className ) {
                if ( isNaN(d.className) ) {
                    label += d.className;//.substr(0,35);
                    if ( d.className.length == 0 || d.className == "\n" ) {
                        label += 'No title';
                    }
                    d.className.length > 35 ? label += '...' : false;
                } else if ( Date.parse(d.className) ) {
                    var date = new Date(d.className);
                    label += date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
                } else if (date = new Date(d.className) ) {
                    if ( date.getDate() && date.getMonth() && date.getFullYear() ) {
                        label += date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
                    } else {
                        label += d.className;
                    }
                } else {
                    label += d.className;
                }
            }
            return label;
        }

        var force = function() {

            // a function to check the dict of linked things
            function isConnected(a, b) {
                return options.linksindex.d1[a.index + "," + b.index] || options.linksindex.d1[b.index + "," + a.index] || a.index == b.index || options.linksindex.d2[a.index + "," + b.index] || options.linksindex.d2[b.index + "," + a.index] || options.linksindex.d3[a.index + "," + b.index] || options.linksindex.d3[b.index + "," + a.index];
            }
            // when a node is hovered, opacify any nodes / links not connected to it
            var highlight = function(opacity) {
                return function(d) {
                    //$('.nodetitle').remove();
                    node.style("stroke","transparent").style("stroke", function(o) {
                        thisOpacity = d === o && opacity != 1 ? "#333" : "transparent";
                        //opacity != 1 && thisOpacity == "#333" ? showtitle(this) : false;
                        return thisOpacity;
                    });

                    link.style("stroke", function(o) {
                        return opacity == 1 ? "#ccc" : "#333";
                    }).style("stroke", function(o) {
                        return isConnected(d,o.source) && isConnected(d,o.target) && opacity != 1 ? "#333" : "#ccc";
                    }).style("stroke-width", function(o) {
                        return opacity == 1 ? 1 : 1.5;
                    }).style("stroke-width", function(o) {
                        return isConnected(d,o.source) && isConnected(d,o.target) && opacity != 1 ? 1.5 : 1;
                    });
                    opacity == .1 ? setTimeout(function() {options.dragging = false;}, 200) : false;
                };
            };

            // build the vis area
            var w = obj.width();
            var h = obj.height();
            var vis = d3.select(".graphview_panel")
                .append("svg:svg")
                .attr("width", w)
                .attr("height", h)
                .attr("pointer-events", "all")
                .append('svg:g')
                .call(d3.behavior.zoom().on("zoom", redraw))
                .append('svg:g');

            vis.append('svg:rect')
                .attr('width', w)
                .attr('height', h)
                .attr('fill', 'transparent');

            // fade in whenever transitions occur
            vis.style("opacity", 1e-6)
                .transition()
                .duration(1000)
                .style("opacity", 1);

            // redraw on zoom
            function redraw() {
                vis.attr("transform",
                    "translate(" + d3.event.translate + ")"
                    + " scale(" + d3.event.scale + ")"
                );
            }

            // start the force layout
            var force = d3.layout.force()
                .charge(-160)
                .linkDistance(100)
                .nodes(options.nodes)
                .links(options.links)
                .size([w, h])
                .start();

            // put links on it
            var link = vis.selectAll("line.link")
                .data(options.links)
                .enter().append("svg:line")
                .attr("class", "link")
                .attr("stroke", "#ddd")
                .attr("stroke-opacity", 0.8)
                .style("stroke-width", function(d) { return Math.sqrt(d.value); })
                .attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            // put the nodes on it
            var dom = d3.extent(options.nodes, function(d) {
                return d.value;
            });
            var cr = d3.scale.sqrt().range([5, 25]).domain(dom);
            var node = vis.selectAll("circle.node")
                .data(options.nodes)
                .enter().append("svg:circle")
                .attr("class", "node")
                .attr("name", function(d) { return label(d); })
                .attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; })
                .attr("r", function(d) { return cr(d.value); })
                .style("fill", function(d) { return options.fill(d.group); })
                .call(force.drag)
                .on("mouseover", highlight(.1))
                .on("mouseout", highlight(1))
                .on("mousedown",function(d) { options.dragging = d });

            // put a hover a label on
            node.append("svg:title")
                .text(function(d) { return label(d); });

            // make the cursor a click pointer whenever hovering a node
            $('.node').css({"cursor":"pointer"});

            // put a label next to each node
            // TODO: change this to be part of highlight so that only hovered / related nodes have labels
            /*var texts = vis.selectAll("text.label")
                .data(options.nodes)
                .enter().append("text")
                .attr("class", "svglabel")
                .attr("fill", "#bbb")
                .text(function(d) {  return label(d); });*/

            // define the changes that happen when the diagram ticks over
            force.on("tick", function() {
                link.attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                node.attr("cx", function(d) { return d.x; })
                    .attr("cy", function(d) { return d.y; });

                /*texts.attr("transform", function(d) {
                    return "translate(" + (d.x - cr(d.value) + 15) + "," + (d.y + cr(d.value) + 5) + ")";
                });*/

            });

        };

        // ===============================================
        // ===============================================
        //
        // visualisation data prep functions
        //
        // ===============================================
        // ===============================================

        // loop  over an object with a dot notation route to its value if found
        // used in the following setnodesandlinks() function
        var findthis = function(routeparts,o,matcher) {
            // first check if there is a field named with the concatenation of parts, which can be the case with specified fields
            if ( o[routeparts[0]] ) {
                if ( typeof(o[routeparts[0]]) == 'object' ) {
                    if ( $.isArray(o[routeparts[0]]) ) {
                        if ( typeof(o[routeparts[0]][0]) == 'object' ) {
                            var matched = false;
                            for ( var i in o[routeparts[0]] ) {
                                !matched ? matched = findthis(routeparts.slice(1),o[routeparts[0]][i],matcher) : false;
                            }
                            return matched;
                        } else {
                            if ( o[routeparts[0]].indexOf(matcher) != -1 ) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } else {
                        return findthis(routeparts.slice(1),o[routeparts[0]],matcher);
                    }
                } else {
                    if ( $.isArray(o[routeparts[0]]) ) {
                        if ( typeof(o[routeparts[0]][0]) == 'object' ) {
                            var matched = false;
                            for ( var i in o[routeparts[0]] ) {
                                !matched ? matched = findthis(routeparts.slice(1),o[routeparts[0]][i],matcher) : false;
                            }
                            return matched;
                        } else {
                            if ( o[routeparts[0]].indexOf(matcher) != -1 ) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } else if ( matcher == o[routeparts[0]] ) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } else if ( o[routeparts.join('.')] ) {
                return findthis([routeparts.join('.')],o,matcher);
            } else {
                return false;
            }
        }

        // calculate nodes and links from a result set
        var setnodesandlinks = function() {
            options.nodes = [];
            for ( var i in options.response.hits.hits ) {
                //var rec = options.response.hits.hits[i]._source;
                //rec == undefined ? rec = options.response.hits.hits[i].fields : false;
                var rec = options.response.hits.hits[i]._source !== undefined ? options.response.hits.hits[i]._source : options.response.hits.hits[i].fields;
                rec === undefined ? rec = {} : false;
                rec[options.titlefield] === undefined ? rec[options.titlefield] = "No name" : false;
                var arr = {
                    "record":rec,
                    "className": rec[options.titlefield],
                    "group": "records",
                    "value": 0,
                    "facet": "none"
                }
                //arr.className == undefined ? arr.className = indata.projectComposition.project.title : false; // ADDED FOR GTR
                options.nodes.push(arr);
            };
            var links = [];
            $('.graphview_facetsizer').remove();
            $('.graphview_nodetype:checked', obj).each(function() {
                var key = $(this).attr('data-field');
                var obj = options.response.facets[key];
                var facetcount = ' <input id="' + key.replace(/\./g,'_') + '_graphview_facetsize" class="graphview_facetsizer" style="width:30px;padding:0;margin:0;font-size:10px;" type="text" value="' + obj.terms.length + '" />';
                $(this).parent().append(facetcount);
                for ( var item in obj.terms ) {
                    var trec = obj.terms;
                    var arr = {
                        "className": trec[item].term,
                        "group": key,
                        "value": trec[item].count,
                        "facet": key
                    }
                    options.nodes.push(arr);

                    for ( var x = 0; x < options.response.hits.hits.length; x++ ) {
                        var record = options.nodes[x].record;
                        var route = key; //.replace('.exact','');
                        var source = options.nodes.length-1;
                        var target = x;
                        var value = 1;
                        if ( findthis(route.split('.'), record, trec[item].term) ) {
                            links.push({"source":source,"target":target,"value":value});
                        }
                    };
                };
            });
            $('.graphview_facetsizer').bind('change',options.executequery);
            options.links = links;

            // build a dict that tells us which things are linked
            options.linksindex = {'d1':{},'d2':{},'d3':{}};
            options.links.forEach(function(d) {
                options.linksindex.d1[d.source + "," + d.target] = 1;
                if ( options.focusdepth > 1 ) {
                    options.links.forEach(function(d2) {
                        if ( d2.target == d.target && d2.source != d.source ) {
                            options.linksindex.d2[d.source + "," + d2.source] = 1;
                        }
                        if ( d2.source == d.source && d2.target != d.target ) {
                            options.linksindex.d2[d.target + "," + d2.target] = 1;
                        }
                        if ( options.focusdepth > 2 ) {
                            options.links.forEach(function(d3) {
                                if ( d3.target == d2.target && d3.source != d2.source ) {
                                    options.linksindex.d3[d.source + "," + d3.source] = 1;
                                }
                                if ( d3.source == d2.source && d3.target != d2.target ) {
                                    options.linksindex.d3[d.target + "," + d3.target] = 1;
                                }

                            });
                        }
                    });
                }
            });

        }

        // ===============================================
        // ===============================================
        //
        // default results display
        //
        // ===============================================
        // ===============================================

        defaults.showresults = function(data) {
            // put the response data in the response option
            data ? options.response = data : false;
            // do some cleaning
            $('.graphview_panel', obj).html('');
            $('.graphview_panel', obj).css({"overflow":"visible"});
            $('.graphview_total', obj).html(options.response.hits.total);

            // when graphable backend is available, get the nodes and links from it
            if ( options.graphable.enabled ) {
                options.nodes = options.response.nodes;
                options.links = options.response.links;
                // options.linksindex = options.response.linksindex; TODO: make this work on the backend and pass depth params
            } else {
                // otherwise generate them
                setnodesandlinks();
            }
            force();
            typeof options.afterresults == 'function' ? options.afterresults.call(this) : false;
            $('.graphview_loading', obj).hide();
        };

        // ===============================================
        // ===============================================
        //
        // default query functions
        //
        // defaults.query() builds and returns a query object
        // from current page state
        //
        // defaults.executequery() sends the query to the
        // target and calls showresults when a suitable
        // response is retrieved
        //
        // ===============================================
        // ===============================================

        defaults.query = function() {
            // fuzzify the freetext search query terms if required
            var fuzzify = function(querystr) {
                var rqs = querystr;
                if ( options.query_string_fuzzify !== undefined ) {
                    if ( options.query_string_fuzzify == "*" || options.query_string_fuzzify == "~" ) {
                        if ( querystr.indexOf('*') == -1 && querystr.indexOf('~') == -1 && querystr.indexOf(':') == -1 ) {
                            var optparts = querystr.split(' ');
                            pq = "";
                            for ( var oi = 0; oi < optparts.length; oi++ ) {
                                var oip = optparts[oi];
                                if ( oip.length > 0 ) {
                                    oip = oip + options.query_string_fuzzify;
                                    options.query_string_fuzzify == "*" ? oip = "*" + oip : false;
                                    pq += oip + " ";
                                }
                            };
                            rqs = pq;
                        };

                    };
                };
                return rqs;
            };

            // TODO: find things in the obj with attr data-something
            // this should tell if it is a query_string, a facet value, a setting of some sort
            // set them all into the options.currentstate
            // they will be used to build the elasticsearch query
            options.defaultquery.size = parseInt($('.graphview_to', obj).val()) - parseInt($('.graphview_from', obj).val());
            options.defaultquery.from = $('.graphview_from', obj).val();
            // copy the default query
            var qry = $.extend(true, {}, options.defaultquery);
            qry["facets"] = {};
            // add any selections to the query
            var vals = $('.query_string', obj).select2("val");
            if ( vals.length != 0 ) {
                for ( var i in vals ) {
                    var kv = vals[i].split('__________');
                    if ( kv.length == 1 ) {
                        qry.query.bool.must.push({"query_string":{"query":fuzzify(kv[0]), "default_operator": options.default_operator}});
                    } else {
                        var qobj = {"term":{}};
                        qobj.term[kv[0]] = kv[1];
                        qry.query.bool.must.push(qobj);
                    }
                }
            } else {
                qry.query.bool.must.push({"match_all":{}});
            }
            // check for any ranged values to add to the bool
            if ( $('.lowvalue', obj).val() || $('.highvalue', obj).val() ) {
                var ranged = {
                    'range': {
                        'year': {
                        }
                    }
                };
                $('.lowvalue',obj).val().length ? ranged.range.year.from = endater( $('.lowvalue', obj).val() ) : false;
                $('.highvalue',obj).val().length ? ranged.range.year.to = endater( $('.highvalue', obj).val() ) : false;
                qry.query.bool.must.push(ranged);
            };

            // request facets for the selected nodetypes
            $('.graphview_nodetype:checked', obj).each(function() {
                var bb = $(this).attr('data-field');
                if ( bb.length != 0 ) {
                    var size = options.nodesize;
                    if ( $('#' + bb.replace(/\./g,'_') + '_graphview_facetsize', obj).val() ) {
                        size = $('#' + bb.replace(/\./g,'_') + '_graphview_facetsize', obj).val();
                    };
                    var f = {
                        "terms": {
                            "field": bb,
                            "order": "count",
                            "size": size
                        }
                    }
                    qry.facets[bb] = f;
                };
            });
            // add graphing parameters if the backend supports graphing
            options.graphable.enabled ? qry.graph = options.graphable : false;
            return qry;
        };

        defaults.executequery = function(event) {
            // do nothing if triggered by mouseover when nothing is being dragged
            if ( !(event !== undefined && event.type == "mouseover" && !options.dragging) ) {
                // show the loading image
                $('.graphview_loading', obj).show();
                // get the current dataset of the select box
                var selectdata = $('.query_string',obj).select2("data");
                // check if a new search term is being dragged onto the search area
                if ( options.dragging ) {
                    if ( options.dragging.group == "records" ) {
                        var did = options.dragging.className
                    } else {
                        var did = options.dragging.group + "__________" + options.dragging.className
                    }
                    selectdata.push({
                        "id":did,
                        "text": options.dragging.className
                    });
                    $('.query_string', obj).select2("data",selectdata);
                    options.dragging = false;
                }
                // remove numbers from choices and set their colors to match their types
                $('.select2-search-choice', obj).each(function(i) {
                    var kv = selectdata[i]['id'].split('__________');
                    if ( kv.length > 1 ) {
                        $(this).css({"color":options.fill(kv[0])});
                    }
                    var nonumber = $(this).children('div').text().replace(/ \([0-9]*\)/,'');
                    $(this).children('div').text(nonumber);
                });
                // put the current query state into the URL if set
                options.pushstate ? window.history.pushState("", "search", '?source=' + JSON.stringify(options.query())): false;
                // set the ajax options then execute
                var ajaxopts = {
                    type: options.ajaxtype,
                    url: options.target,
                    //contentType: "application/json; charset=utf-8",
                    dataType: options.datatype,
                    success: options.showresults
                };
                if ( options.ajaxtype != 'POST' ) {
                    ajaxopts.url += '?source=' + JSON.stringify(options.query());
                } else {
                    // TODO: add the query as data to the ajax opts
                }
                $.ajax(ajaxopts);
            };
        };

        // ===============================================
        // ===============================================
        // ranged date functions
        // ===============================================
        // ===============================================

        var endater = function(d) {
            var reg = /(\d{2})-(\d{2})-(\d{4})/;
            var dateArray = reg.exec(d);
            var dateObject = new Date(
                (+dateArray[3]),
                (+dateArray[2])-1,
                (+dateArray[1]),
                (+00),
                (+00),
                (+00)
            );
            return dateObject;
        };

        var ranged = function() {

            var dater = function(d) {
                var day = d.getDate();
                var month = d.getMonth() + 1;
                var year = d.getFullYear();
                var date = day + "-" + month + "-" + year;
                date = date.toString();
                var parts = date.split('-');
                parts[0].length == 1 ? parts[0] = '0' + parts[0] : "";
                parts[1].length == 1 ? parts[1] = '0' + parts[1] : "";
                date = parts[0] + '-' + parts[1] + '-' + parts[2];
                return date;
            };

            if ( $('.dateranged', obj).length == 0 ) {
                $('.graphview', obj).append('<div class="dateranged" style="position:absolute;bottom:-5px;left:5%;z-index:1000;width:90%;"> \
                    <div style="width:10%;float:left;"> \
                        <input type="text" class="lowvalue" style="width:100%;" placeholder="from date" /> \
                    </div> \
                    <div style="width:70%;float:left;margin:0 20px 0 35px;"><div class="ranged" style="margin-top:8px;"></div></div> \
                    <div style="width:10%;float:left;"><input type="text" class="highvalue" style="width:100%;" placeholder="to date" /></div> \
                    </div>');

                var ranged_values = [];
                var entries = options.response.facets.ranged.entries;
                for ( var i=0, len=entries.length; i < len; i++ ) {
                    ranged_values.push(new Date(entries[i].time));
                };

                var opts = {
                    inline: true,
                    dateFormat: 'dd-mm-yy',
                    defaultDate: dater(ranged_values[0]),
                    minDate: dater(ranged_values[0]),
                    maxDate: dater(new Date()),
                    changeYear: true
                };

                $('.lowvalue', obj).datepicker(opts);
                $('.highvalue', obj).datepicker(opts);
                $('.lowvalue', obj).bind('change',options.executequery);
                $('.highvalue', obj).bind('change',options.executequery);
                $('.resolution', obj).val("year");
                $('.ranged', obj).slider({
                    range: true,
                    min: 0,
                    max: ranged_values.length-1,
                    values: [0, ranged_values.length-1],
                    slide: function( event, ui ) {
                        $('.lowvalue', obj).val( dater(ranged_values[ ui.values[0] ]) );
                        $('.highvalue', obj).val( dater(ranged_values[ ui.values[1] ]) ).trigger('change');
                    }
                });

            }
        }

        // ===============================================
        // ===============================================
        //
        // the graphview default UI
        //
        // defaults.uitemplate() and defaults.uibindings()
        //
        // ===============================================
        // ===============================================

        /*
         * TODO: For putting option changers on pages, give them an attribute called
         * data-option, with a value of the name of the option e.g. options.defaultquery.size
         * it will then automatically update when a query is performed
         */

        defaults.uitemplate = function() {
            var ui = '<div class="graphview" style="width:100%;height:100%;position:relative;">';

            ui += '<div class="graphview_searcharea" style="-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;position:absolute;top:5px;left:5px;z-index:1000;">';
            ui += '<select class="graphview_suggest" style="display:inline;width:180px;height:29px;margin-right:-2px;background:#eee;border-radius:5px 0px 0px 5px;">';
            ui += '<option style="color:' + options.fill("records") + ';" data-value="records">search everything</option>';
            for ( var key in options.defaultquery.facets ) {
                var obj = options.defaultquery.facets[key];
                if ( key != "range" && obj.term.suggest ) { // TODO: change this in case it is not a term facet?
                    ui += '<option data-value="' + obj.term.field + '" style="color:' + options.fill(obj.term.field) + ';">suggest ' + key + '</option>';
                    ui += ', ';
                }
            }
            ui += '</select>';
            ui += '<input type="text" class="query_string" style="width:400px;" data-option="query.bool.must.query_string.query" placeholder="mix and match some search terms" />';
            ui += ' <img class="graphview_loading" style="width:30px;margin-top:-10px;" src="loading.gif" />';
            ui += '</div>'; // closes searcharea

            ui += '<div class="graphview_optionsarea" style="position:absolute;top:40px;left:5px;z-index:1000;">';
            ui += '<input class="graphview_from" type="text" value="';
            ui += options.defaultquery.from;
            ui += '" style="width:40px;margin:-5px 0 0 0;padding:1px 1px 0 0;font-size:14px;color:#666;text-align:center;" />';
            ui += ' to ';
            ui += '<input class="graphview_to" type="text" value="';
            ui += options.defaultquery.size;
            ui += '" style="width:40px;margin:-5px 0 0 0;padding:1px 1px 0 0;font-size:14px;color:#666;text-align:center;" /> of \
                <span class="graphview_total" style="font-size:16px;font-weight:bold;color:#999;"></span>';
            ui += '</div>'; // closes optionsarea

            ui += '<div class="graphview_nodesarea" style="position:absolute;top:62px;left:5px;z-index:1000;">';
            for ( var key in options.defaultquery.facets ) {
                if ( key != "range" && options.defaultquery.facets[key].term.node ) { // TODO: change this in case the facet is not a term type?
                    var node = options.defaultquery.facets[key].term;
                    ui += '<div style="margin-right:2px;color:' + options.fill(node.field) + ';"><input type="checkbox" class="graphview_nodetype" data-field="' + node.field + '" /> ' + key + '</div>';
                }
            };
            ui += '</div>'; // closes nodesarea

            ui += '<div class="graphview_panel" style="position:absolute;top:0;left:0;"></div>';

            ui += '</div>'; // closes graphview

            return ui;
        }

        defaults.uibindings = function() {
            // attach select2 functionality to the query string input
            $('.query_string', obj).select2({
                "formatNoMatches": function() { return options.searchhintline;},
                "tags": function(q) {
                    var field = options.suggest;
                    var qry = {
                        "query": {
                            "match_all": {}
                        },
                        "size": 0
                    };
                    if ( field !== undefined ) {
                        qry.facets = {
                            "tags":{
                                "terms": {
                                    "field": field,
                                    "order": "count",
                                    "size": options.suggestsize
                                }
                            }
                        };
                        if ( options.graphable.enabled ) {
                            qry.graph = options.graphable;
                            qry.graph.dropfacets = false;
                        };
                        qry.facets.tags.facet_filter = {"query": options.query().query };
                        var dropdownfilter = true;
                        if ( q.term.length ) {
                            if ( q.term.length == 1 ) {
                                var ts = {
                                    "bool":{
                                        "should":[
                                            {"prefix":{}},
                                            {"prefix":{}}
                                        ]
                                    }
                                };
                                ts.bool.should[0].prefix[field] = q.term.toLowerCase();
                                ts.bool.should[1].prefix[field] = q.term.toUpperCase();
                                qry.facets.tags.facet_filter.query.bool.must.push(ts);
                                qry.facets.tags.terms.order = "term";
                            } else {
                                if ( q.term.indexOf('*') != -1 || q.term.indexOf('~') != -1 || q.term.indexOf(':') != -1 ) {
                                    var qs = q.term;
                                    dropdownfilter = false;
                                } else if ( q.term.indexOf(' ') == -1 ) {
                                    var qs = '*' + q.term + '*';
                                } else {
                                    var qs = q.term.replace(/ /g,' AND ') + '*';
                                }
                                var ts = {
                                    "query_string":{
                                        "query": qs,
                                        "default_field": field.replace('.exact','')//,
                                        //"analyzer":"simple"
                                    }
                                };
                                qry.facets.tags.facet_filter.query.bool.must.push(ts);
                            }
                        };
                        if ( qry.facets.tags.facet_filter.query.bool.must.length == 0 ) {
                            delete qry.facets.tags.facet_filter;
                        };
                    };

                    $.ajax({
                        type: options.ajaxtype,
                        url: options.target + '?source=' + JSON.stringify(qry),
                        //contentType: "application/json; charset=utf-8",
                        dataType: options.datatype,
                        q: q,
                        field: field,
                        dropdownfilter: dropdownfilter,
                        success: function(data) {
                            var qa = this.q;
                            var t = qa.term, filtered = {results: []};
                            var tags = [];
                            if ( field !== undefined ) {
                                var terms = data.facets.tags.terms;
                                for ( var item in terms ) {
                                    tags.push({'id':this.field + '__________' + terms[item].term,'text':terms[item].term + ' (' + terms[item].count + ')'});
                                };
                            };
                            $(tags).each(function () {
                                var isObject = this.text !== undefined,
                                    text = isObject ? this.text : this;
                                if ( this.dropdownfilter ) {
                                    if (t === "" || qa.matcher(t, text)) {
                                        filtered.results.push(isObject ? this : {id: this, text: this});
                                    }
                                } else {
                                    filtered.results.push(isObject ? this : {id: this, text: this});
                                };
                            });
                            qa.callback(filtered);
                        }
                    });
                },
                "tokenSeparators":[","],
                "width":"element",
            });

            // add some customisation to select2 css
            $('.select2-choices', obj).css({
                "-webkit-border-radius":"3px",
                "-moz-border-radius":"3px",
                "border-radius":"3px",
                "border":"1px solid #ccc"
            });

            // put some bindings to execute queries and so on onto the template
            $('.graphview_nodetype', obj).bind('change',options.executequery);
            $('.query_string', obj).bind('change',options.executequery);
            $('.query_string', obj).bind('mouseover',options.executequery);
            $('.graphview_to', obj).bind('change',options.executequery);
            $('.graphview_from', obj).bind('change', function(event) {
                $(this).val() > options.response.hits.total ? $(this).val(options.response.hits.total - 1) : false;
                options.defaultquery.from = $(this).val();
                var to = parseInt(options.defaultquery.from) + parseInt(options.defaultquery.size);
                to > options.response.hits.total ? to = options.response.hits.total : false;
                $('.graphview_to', obj).val(to).trigger('change');
            });
            $('.graphview_suggest', obj).bind('change', function(event) {
                options.suggest = $('option:selected',this).attr('data-value');
                $('.select2-input', obj).focus().trigger('mousedown');
            });

        }

        // ===============================================
        // ===============================================
        //
        // now set the options from the defaults and those provided
        // and create the plugin on the target element
        // and bind everything up for starting
        //
        // ===============================================
        // ===============================================
        $.fn.graphview.options = $.extend(defaults, options);
        var options = $.fn.graphview.options;
        options.defaultquery.size == undefined ? options.defaultquery.size = 10 : false;
        options.defaultquery.from == undefined ? options.defaultquery.from = 0 : false;

        var obj = undefined;
        return this.each(function() {
            obj = $(this);
            obj.append(options.uitemplate());
            options.uibindings();
            options.searchonload ? options.executequery() : false;

        });

    };

    // define options here then they are written to above, then they become available externally
    $.fn.graphview.options = {};

})(jQuery);


text:
class Buffer {
  enum {kDefaultStorage = 16 * 1024};
  char* buffer_;
  int   length_;
  int   storage_;

  Buffer(const Buffer&);
  Buffer& operator =(const Buffer&);
public:
  explicit Buffer(void);
  ~Buffer(void);

  inline const char* buffer(void) const
  {
    return buffer_;
  }

  inline int length(void) const
  {
    return length_;
  }

  inline char* free_buffer(void) const
  {
    return (buffer_ + length_);
  }

  inline int free_length(void) const
  {
    return (storage_ - length_);
  }
public:
  bool Init(int storage = kDefaultStorage);
  void Destroy(void);

  int Put(const char* buffer, int bytes);
  int Get(int bytes, char* buffer);
  int Increment(int bytes);
  int Decrement(int bytes);

  bool Regrow(void);
};

#endif  //! __BUFFER_HEADER_H__

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\CatalogSearch\Model\Indexer\Fulltext;

use Magento\Framework\Indexer\AbstractProcessor;
use Magento\CatalogSearch\Model\Indexer\Fulltext;

/**
 * Class Processor
 */
class Processor extends AbstractProcessor
{
    /**
     * Indexer ID
     */
    const INDEXER_ID = Fulltext::INDEXER_ID;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/treeview_even_level_yellow_bg" android:state_pressed="true"></item>
    <item android:drawable="@drawable/treeview_even_level_yellow_bg"></item>
</selector>


text:
module Mtdevise
  class User < ::User

    # Gravatar Support
    include Gravtastic
    gravtastic

    # User API Tokens
    acts_as_token_authenticatable

    # Relationship
    has_many :accounts, :class_name => "Mtdevise::Account", :foreign_key => "owner_id"

    # Define Devise
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable

  end
end


text:
name: closure-warnings/j2cl-checks
---

## Summary


text:
package org.apache.druid.client.indexing;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

/**
 * org.apache.druid.indexing.common.task.Task representation for clients
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(value = {
    @Type(name = "kill", value = ClientKillQuery.class),
    @Type(name = "compact", value = ClientCompactQuery.class)
})
public interface ClientQuery
{
  String getType();

  String getDataSource();
}


text:
using System;
using System.Collections.Generic;

namespace Bitretsmah.Core.Models
{
    [Serializable]
    public class Directory : Node
    {
        public Directory()
        {
            InnerNodes = new List<Node>();
        }

        public List<Node> InnerNodes { get; set; }

        public override void SetAllStates(NodeState state)
        {
            base.SetAllStates(state);
            InnerNodes.ForEach(x => x.SetAllStates(state));
        }

        public override ICollection<Node> StructureToList()
        {
            var list = new List<Node>() { this };
            InnerNodes.ForEach(x => list.AddRange(x.StructureToList()));
            return list;
        }
    }
}


text:
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

from lib.core.common import Backend
from lib.core.common import randomStr
from lib.core.common import safeSQLIdentificatorNaming
from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
from lib.core.exception import SqlmapMissingMandatoryOptionException
from lib.core.exception import SqlmapNoneDataException
from lib.core.settings import CURRENT_DB
from lib.utils.pivotdumptable import pivotDumpTable
from plugins.generic.enumeration import Enumeration as GenericEnumeration

class Enumeration(GenericEnumeration):
    def __init__(self):
        GenericEnumeration.__init__(self)

        kb.data.processChar = lambda x: x.replace('_', ' ') if x else x

    def getPasswordHashes(self):
        warnMsg = "on SAP MaxDB it is not possible to enumerate the user password hashes"
        logger.warn(warnMsg)

        return {}

    def getDbs(self):
        if len(kb.data.cachedDbs) > 0:
            return kb.data.cachedDbs

        infoMsg = "fetching database names"
        logger.info(infoMsg)

        rootQuery = queries[Backend.getIdentifiedDbms()].dbs
        randStr = randomStr()
        query = rootQuery.inband.query
        retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.schemaname' % randStr], blind=True)

        if retVal:
            kb.data.cachedDbs = retVal[0].values()[0]

        if kb.data.cachedDbs:
            kb.data.cachedDbs.sort()

        return kb.data.cachedDbs

    def getTables(self, bruteForce=None):
        if len(kb.data.cachedTables) > 0:
            return kb.data.cachedTables

        self.forceDbmsEnum()

        if conf.db == CURRENT_DB:
            conf.db = self.getCurrentDb()

        if conf.db:
            dbs = conf.db.split(",")
        else:
            dbs = self.getDbs()

        for db in filter(None, dbs):
            dbs[dbs.index(db)] = safeSQLIdentificatorNaming(db)

        infoMsg = "fetching tables for database"
        infoMsg += "%s: %s" % ("s" if len(dbs) > 1 else "", ", ".join(db if isinstance(db, basestring) else db[0] for db in sorted(dbs)))
        logger.info(infoMsg)

        rootQuery = queries[Backend.getIdentifiedDbms()].tables

        for db in dbs:
            randStr = randomStr()
            query = rootQuery.inband.query % (("'%s'" % db) if db != "USER" else 'USER')
            retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.tablename' % randStr], blind=True)

            if retVal:
                for table in retVal[0].values()[0]:
                    if db not in kb.data.cachedTables:
                        kb.data.cachedTables[db] = [table]
                    else:
                        kb.data.cachedTables[db].append(table)

        for db, tables in kb.data.cachedTables.items():
            kb.data.cachedTables[db] = sorted(tables) if tables else tables

        return kb.data.cachedTables

    def getColumns(self, onlyColNames=False):
        self.forceDbmsEnum()

        if conf.db is None or conf.db == CURRENT_DB:
            if conf.db is None:
                warnMsg = "missing database parameter. sqlmap is going "
                warnMsg += "to use the current database to enumerate "
                warnMsg += "table(s) columns"
                logger.warn(warnMsg)

            conf.db = self.getCurrentDb()

        elif conf.db is not None:
            if  ',' in conf.db:
                errMsg = "only one database name is allowed when enumerating "
                errMsg += "the tables' columns"
                raise SqlmapMissingMandatoryOptionException(errMsg)

        conf.db = safeSQLIdentificatorNaming(conf.db)

        if conf.tbl:
            tblList = conf.tbl.split(",")
        else:
            self.getTables()

            if len(kb.data.cachedTables) > 0:
                tblList = kb.data.cachedTables.values()

                if isinstance(tblList[0], (set, tuple, list)):
                    tblList = tblList[0]
            else:
                errMsg = "unable to retrieve the tables "
                errMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
                raise SqlmapNoneDataException(errMsg)

        for tbl in tblList:
            tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True)

        rootQuery = queries[Backend.getIdentifiedDbms()].columns

        for tbl in tblList:
            if conf.db is not None and len(kb.data.cachedColumns) > 0 \
              and conf.db in kb.data.cachedColumns and tbl in \
              kb.data.cachedColumns[conf.db]:
                infoMsg = "fetched tables' columns on "
                infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
                logger.info(infoMsg)

                return {conf.db: kb.data.cachedColumns[conf.db]}

            infoMsg = "fetching columns "
            infoMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl)
            infoMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
            logger.info(infoMsg)

            randStr = randomStr()
            query = rootQuery.inband.query % (unsafeSQLIdentificatorNaming(tbl), ("'%s'" % unsafeSQLIdentificatorNaming(conf.db)) if unsafeSQLIdentificatorNaming(conf.db) != "USER" else 'USER')
            retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.columnname' % randStr, '%s.datatype' % randStr, '%s.len' % randStr], blind=True)

            if retVal:
                table = {}
                columns = {}

                for columnname, datatype, length in zip(retVal[0]["%s.columnname" % randStr], retVal[0]["%s.datatype" % randStr], retVal[0]["%s.len" % randStr]):
                    columns[safeSQLIdentificatorNaming(columnname)] = "%s(%s)" % (datatype, length)

                table[tbl] = columns
                kb.data.cachedColumns[conf.db] = table

        return kb.data.cachedColumns

    def getPrivileges(self, *args):
        warnMsg = "on SAP MaxDB it is not possible to enumerate the user privileges"
        logger.warn(warnMsg)

        return {}

    def searchDb(self):
        warnMsg = "on SAP MaxDB it is not possible to search databases"
        logger.warn(warnMsg)

        return []

    def getHostname(self):
        warnMsg = "on SAP MaxDB it is not possible to enumerate the hostname"
        logger.warn(warnMsg)


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class AudioSubtitles : MonoBehaviour {

    public Toggle audioSubToggle;
    public Button resetOptions;
    public AudioSubManager audioSubManager;

    public void AudioSubsToggle()
    {
        if (audioSubToggle.isOn)
            SaveManager.Save_Menu_AudioSubs(1);
        else
            SaveManager.Save_Menu_AudioSubs(0);

        if (SceneManager.GetActiveScene().name != "Loading")
        {
            if (audioSubToggle.isOn)
            {
                audioSubManager.audioSubsOn = true;
            }
            else
            {
                audioSubManager.audioSubsOn = false;
            }
        }
        resetOptions.interactable = true;
    }
}


text:
:: Purpose:       Installs a package
:: Requirements:  Run this script with Administrator rights
:: Author:        vocatus on reddit.com/r/sysadmin ( vocatus.gate@gmail.com ) // PGP key ID: 0x07d1490f82a211a2
:: History:       1.0.1 + Add proper console and logfile logging
::                1.0.0 + Initial write

::::::::::
:: Prep :: -- Don't change anything in this section
::::::::::
@echo off
set SCRIPT_VERSION=1.0.1
set SCRIPT_UPDATED=2020-02-05
:: Get the date into ISO 8601 standard date format (yyyy-mm-dd) so we can use it
FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO set DTS=%%a
set CUR_DATE=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%

:: This is useful if we start from a network share; converts CWD to a drive letter
pushd "%~dp0"
cls

:::::::::::::::
:: Variables :: -- Set these to your desired values
:::::::::::::::
:: Log location and name. Do not use trailing slashes (\)
set LOGPATH=%SystemDrive%\logs
set LOGFILE=%COMPUTERNAME%_Palemoon_x86_install.log

:: Package to install. Do not use trailing slashes (\)
set BINARY=Palemoon x86.exe
set FLAGS=-ms

:: Create the log directory if it doesn't exist
if not exist %LOGPATH% mkdir %LOGPATH%

:: Get into the correct directory
cd "%~dp0"

::::::::::::::::::
:: INSTALLATION ::
::::::::::::::::::
:: Kill Pale Moon
echo %CUR_DATE% %TIME% Killing any running Palemoon instsances, please wait...
echo %CUR_DATE% %TIME% Killing any running Palemoon instsances, please wait...>> "%LOGPATH%\%LOGFILE%" 2>NUL
%SystemDrive%\windows\system32\taskkill.exe /F /IM palemoon.exe /T 2>NUL
wmic process where name="palemoon.exe" call terminate 2>NUL
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Install palemoon
echo %CUR_DATE% %TIME% Installing package...
echo %CUR_DATE% %TIME% Installing package...>> "%LOGPATH%\%LOGFILE%" 2>NUL
"%BINARY%" %FLAGS%
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

echo %CUR_DATE% %TIME% Finishing configuration and cleaning up...
echo %CUR_DATE% %TIME% Finishing configuration and cleaning up...>> "%LOGPATH%\%LOGFILE%" 2>NUL
:: Install 32-bit customisations
if exist "%programfiles%\Pale Moon\" copy /Y "override.ini" "%programfiles%\Pale Moon\browser\"
if exist "%programfiles%\Pale Moon\" copy /Y "Pale-Moon-custom-settings.js" "%programfiles%\Pale Moon\"
if exist "%programfiles%\Pale Moon\" copy /Y "local-settings.js" "%programfiles%\Pale Moon\defaults\pref"

:: Install 64-bit customisations
if exist "%ProgramFiles(x86)%\Pale Moon\" copy /Y "override.ini" "%ProgramFiles(x86)%\Pale Moon\browser"
if exist "%ProgramFiles(x86)%\Pale Moon\" copy /Y "Pale-Moon-custom-settings.js" "%ProgramFiles(x86)%\Pale Moon\"
if exist "%ProgramFiles(x86)%\Pale Moon\" copy /Y "local-settings.js" "%ProgramFiles(x86)%\Pale Moon\defaults\pref"

:: Remove Pale Moon Desktop Icon - Windows XP
if exist "%allusersprofile%\Desktop\Pale Moon.lnk" del "%allusersprofile%\Desktop\Pale Moon.lnk"

:: Remove Pale Moon Desktop Icon - Windows 7
if exist "%public%\Desktop\Pale Moon.lnk" del "%public%\Desktop\Pale Moon.lnk"

echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Pop back to original directory. This isn't necessary in stand-alone runs of the script, but is needed when being called from another script
popd

:: Return exit code to SCCM/PDQ Deploy/etc
exit /B %EXIT_CODE%


text:
using System;
using System.Collections;
using System.Web.UI.WebControls;

namespace System.Web.UI
{
	internal class ContentPlaceHolderBuilder: ControlBuilder
	{
	}
}

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin
   id="com.mentor.nucleus.bp.io.mdl"
   name="BridgePoint Model Plug-in"
   version="4.2.0"
   provider-name="xtUML.org"
   class="com.mentor.nucleus.bp.io.mdl.MdlPlugin">

   <runtime>
      <library name="mdl.jar">
         <export name="*"/>
      </library>
   </runtime>
   <requires>
      <import plugin="org.eclipse.core.runtime"/>
      <import plugin="org.eclipse.ui"/>
      <import plugin="org.eclipse.ui.ide"/>
      <import plugin="org.eclipse.core.resources"/>
      <import plugin="com.mentor.nucleus.bp.core"/>
      <import plugin="com.mentor.nucleus.bp.io.core"/>
      <import plugin="com.mentor.nucleus.bp.ui.canvas"/>
      <import plugin="com.mentor.nucleus.bp.ui.text"/>
      <import plugin="com.mentor.nucleus.bp.ui.explorer"/>
      <import plugin="com.mentor.nucleus.bp.als.oal"/>
   </requires>

   <extension
         point="org.eclipse.ui.exportWizards">
      <category
            id="com.mentor.nucleus.bp.exportWizards.category"
            name="xtUML">
      </category>
      <wizard
            category="com.mentor.nucleus.bp.exportWizards.category"
            class="com.mentor.nucleus.bp.io.mdl.wizards.ModelExportWizard"
            icon="platform:/plugin/com.mentor.nucleus.bp.core/icons/green-bp.gif"
            id="com.mentor.nucleus.ExportWizard1"
            name="xtUML Model">
         <description>
            Export model data to a xtUML Model file
         </description>
      </wizard>
   </extension>
   <extension
         point="org.eclipse.ui.importWizards">
      <category
            id="com.mentor.nucleus.bp.importWizards.category"
            name="xtUML">
      </category>
      <wizard
            category="com.mentor.nucleus.bp.importWizards.category"
            class="com.mentor.nucleus.bp.io.mdl.wizards.ModelImportWizard"
            icon="platform:/plugin/com.mentor.nucleus.bp.core/icons/green-bp.gif"
            id="com.mentor.nucleus.bp.ModelImportWizard"
            name="xtUML Model">
         <description>
            Import model data from a xtUML model file
         </description>
      </wizard>
   </extension>

</plugin>


text:
import numpy as np
from functools import reduce
from operator import mul

from deepx.core import ShapedLayer, Layer
from deepx.backend import T

class Reshape(ShapedLayer):

    def is_initialized(self):
        return True

    def initialize(self):
        pass

    def _forward(self, X, **kwargs):
        return T.reshape(X, [-1] + self.dim_out)

    def shape_inference(self):
        shape_in = self.get_shape_in()
        dim_in, dim_out = self.get_dim_in(), self.get_dim_out()
        if shape_in is not None:
            assert len(shape_in) == 1, "Cannot pass multiple inputs into layer"
            shape_in = shape_in[0]
            if dim_in is not None:
                if dim_in != shape_in[-len(dim_in):]:
                    raise Exception("Shape inference error")
            self.dim_in = shape_in[1:]
            assert dim_out is not None
        else:
            if dim_in is not None:
                self.set_shape_in([[None] + dim_in])
        if self.get_shape_in() is not None:
            self.set_shape_out([self.get_shape_in()[0][:len(self.get_dim_in())] + dim_out])
        if not self.initialized and self.get_shape_in() is not None and self.get_shape_out() is not None:
            self.initialize()
            self.initialized = True

class Flatten(Layer):

    def __init__(self, leading_dim=1):
        super(Flatten, self).__init__()
        self.leading_dim = 1

    def is_initialized(self):
        return self.get_shape_out() is not None

    def initialize(self):
        pass

    def shape_inference(self):
        shape_in = self.get_shape_in()
        if shape_in is not None:
            assert len(shape_in) == 1
            shape_in = shape_in[0]
            out_dim = reduce(mul, shape_in[self.leading_dim:], 1)
            self.set_shape_out([shape_in[:self.leading_dim] + [out_dim]])

    def _forward(self, X, **kwargs):
        return T.reshape(X, [-1, np.prod(self.get_shape_out()[0][1:])])

    def __repr__(self):
        shape_in, shape_out = self.get_shape_in(), self.get_shape_out()
        if shape_in is not None:
            shape_in = self.get_shape_in()[0][self.leading_dim:]
        if shape_out is not None:
            shape_out = self.get_shape_out()[0][self.leading_dim:]
        return "Flatten({}, {})".format(
            shape_in, shape_out
        )


text:
import FilePlayer from './FilePlayer'

const RESOLVE_URL = 'https://api.vid.me/videoByUrl/'
const MATCH_URL = /^https?:\/\/vid.me\/([a-z0-9]+)$/i

const cache = {} // Cache song data requests

export default class Vidme extends FilePlayer {
  static displayName = 'Vidme'
  static canPlay = url => MATCH_URL.test(url)

  getData (url) {
    const { onError } = this.props
    const id = url.match(MATCH_URL)[1]
    if (cache[id]) {
      return Promise.resolve(cache[id])
    }
    return window.fetch(RESOLVE_URL + id)
      .then(response => {
        if (response.status === 200) {
          cache[id] = response.json()
          return cache[id]
        } else {
          onError(new Error('Vidme track could not be resolved'))
        }
      })
  }
  getURL ({ video }) {
    const { config } = this.props
    if (config.vidme.format && video.formats && video.formats.length !== 0) {
      const index = video.formats.findIndex(f => f.type === config.vidme.format)
      if (index !== -1) {
        return video.formats[index].uri
      } else {
        console.warn(`Vidme format "${config.vidme.format}" was not found for ${video.full_url}`)
      }
    }
    return video.complete_url
  }
  load (url) {
    const { onError } = this.props
    this.stop()
    this.getData(url).then(data => {
      if (!this.player) return
      this.player.src = this.getURL(data)
    }, onError)
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.sandbox.sysreg.Sem2SLS — statsmodels 0.6.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="top" title="statsmodels 0.6.1 documentation" href="../index.html" />
    <link rel="up" title="Sandbox" href="../sandbox.html" />
    <link rel="next" title="statsmodels.sandbox.sysreg.Sem2SLS.fit" href="statsmodels.sandbox.sysreg.Sem2SLS.fit.html" />
    <link rel="prev" title="statsmodels.sandbox.sysreg.SUR.whiten" href="statsmodels.sandbox.sysreg.SUR.whiten.html" />
<link rel="stylesheet" href="../../_static/facebox.css" type="text/css" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />

Navigation

          index

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Sandbox |

statsmodels.sandbox.sysreg.Sem2SLS¶

class statsmodels.sandbox.sysreg.Sem2SLS(sys, indep_endog=None, instruments=None)[source]¶

Two-Stage Least Squares for Simultaneous equations

<col class="field-name" />
<col class="field-body" />

Parameters:
sys : list

[endog1, exog1, endog2, exog2,...] It will be of length 2 x M,
where M is the number of equations endog = exog.

indep_endog : dict

A dictionary mapping the equation to the column numbers of the
the independent endogenous regressors in each equation.
It is assumed that the system is inputed as broken up into
LHS and RHS. For now, the values of the dict have to be sequences.
Note that the keys for the equations should be zero-indexed.

instruments : array

Array of the exogenous independent variables.

Notes

This is unfinished, and the design should be refactored.
Estimation is done by brute force and there is no exploitation of
the structure of the system.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

fit()

whiten(Y)
Runs the first stage of the 2SLS.

Previous topic

statsmodels.sandbox.sysreg.SUR.whiten

Next topic

statsmodels.sandbox.sysreg.Sem2SLS.fit

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

        © Copyright 2009-2013, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.3.1.


text: Solutions to [Javascripting](https://github.com/workshopper/javascripting) exercises.


text:
package io.seata.server.storage.db.store;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.sql.DataSource;

import io.seata.common.exception.StoreException;
import io.seata.common.loader.EnhancedServiceLoader;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.StringUtils;
import io.seata.config.Configuration;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.model.GlobalStatus;
import io.seata.core.store.BranchTransactionDO;
import io.seata.core.store.GlobalTransactionDO;
import io.seata.core.store.LogStore;
import io.seata.core.store.db.DataSourceProvider;
import io.seata.server.session.GlobalSession;
import io.seata.server.session.SessionCondition;
import io.seata.server.store.AbstractTransactionStoreManager;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.TransactionStoreManager;
import io.seata.server.storage.SessionConverter;

import static io.seata.core.constants.RedisKeyConstants.DEFAULT_LOG_QUERY_LIMIT;

/**
 * The type Database transaction store manager.
 *
 * @author zhangsen
 */
public class DataBaseTransactionStoreManager extends AbstractTransactionStoreManager
    implements TransactionStoreManager {

    private static volatile DataBaseTransactionStoreManager instance;

    /**
     * The constant CONFIG.
     */
    protected static final Configuration CONFIG = ConfigurationFactory.getInstance();

    /**
     * The Log store.
     */
    protected LogStore logStore;

    /**
     * The Log query limit.
     */
    protected int logQueryLimit;

    /**
     * Get the instance.
     */
    public static DataBaseTransactionStoreManager getInstance() {
        if (instance == null) {
            synchronized (DataBaseTransactionStoreManager.class) {
                if (instance == null) {
                    instance = new DataBaseTransactionStoreManager();
                }
            }
        }
        return instance;
    }

    /**
     * Instantiates a new Database transaction store manager.
     */
    private DataBaseTransactionStoreManager() {
        logQueryLimit = CONFIG.getInt(ConfigurationKeys.STORE_DB_LOG_QUERY_LIMIT, DEFAULT_LOG_QUERY_LIMIT);
        String datasourceType = CONFIG.getConfig(ConfigurationKeys.STORE_DB_DATASOURCE_TYPE);
        //init dataSource
        DataSource logStoreDataSource = EnhancedServiceLoader.load(DataSourceProvider.class, datasourceType).provide();
        logStore = new LogStoreDataBaseDAO(logStoreDataSource);
    }

    @Override
    public boolean writeSession(LogOperation logOperation, SessionStorable session) {
        if (LogOperation.GLOBAL_ADD.equals(logOperation)) {
            return logStore.insertGlobalTransactionDO(SessionConverter.convertGlobalTransactionDO(session));
        } else if (LogOperation.GLOBAL_UPDATE.equals(logOperation)) {
            return logStore.updateGlobalTransactionDO(SessionConverter.convertGlobalTransactionDO(session));
        } else if (LogOperation.GLOBAL_REMOVE.equals(logOperation)) {
            return logStore.deleteGlobalTransactionDO(SessionConverter.convertGlobalTransactionDO(session));
        } else if (LogOperation.BRANCH_ADD.equals(logOperation)) {
            return logStore.insertBranchTransactionDO(SessionConverter.convertBranchTransactionDO(session));
        } else if (LogOperation.BRANCH_UPDATE.equals(logOperation)) {
            return logStore.updateBranchTransactionDO(SessionConverter.convertBranchTransactionDO(session));
        } else if (LogOperation.BRANCH_REMOVE.equals(logOperation)) {
            return logStore.deleteBranchTransactionDO(SessionConverter.convertBranchTransactionDO(session));
        } else {
            throw new StoreException("Unknown LogOperation:" + logOperation.name());
        }
    }

    /**
     * Read session global session.
     *
     * @param transactionId the transaction id
     * @return the global session
     */
    public GlobalSession readSession(Long transactionId) {
        //global transaction
        GlobalTransactionDO globalTransactionDO = logStore.queryGlobalTransactionDO(transactionId);
        if (globalTransactionDO == null) {
            return null;
        }
        //branch transactions
        List<BranchTransactionDO> branchTransactionDOs = logStore.queryBranchTransactionDO(
            globalTransactionDO.getXid());
        return getGlobalSession(globalTransactionDO, branchTransactionDOs);
    }

    /**
     * Read session global session.
     *
     * @param xid the xid
     * @return the global session
     */
    @Override
    public GlobalSession readSession(String xid) {
        return this.readSession(xid, true);
    }

    /**
     * Read session global session.
     *
     * @param xid the xid
     * @param withBranchSessions the withBranchSessions
     * @return the global session
     */
    @Override
    public GlobalSession readSession(String xid, boolean withBranchSessions) {
        //global transaction
        GlobalTransactionDO globalTransactionDO = logStore.queryGlobalTransactionDO(xid);
        if (globalTransactionDO == null) {
            return null;
        }
        //branch transactions
        List<BranchTransactionDO> branchTransactionDOs = null;
        //reduce rpc with db when branchRegister and getGlobalStatus
        if (withBranchSessions) {
            branchTransactionDOs = logStore.queryBranchTransactionDO(globalTransactionDO.getXid());
        }
        return getGlobalSession(globalTransactionDO, branchTransactionDOs);
    }

    @Override
    public List<GlobalSession> readSortByTimeoutBeginSessions(boolean withBranchSessions) {
        return readSession(new GlobalStatus[] {GlobalStatus.Begin}, withBranchSessions);
    }

    /**
     * Read session list.
     *
     * @param statuses the statuses
     * @return the list
     */
    @Override
    public List<GlobalSession> readSession(GlobalStatus[] statuses, boolean withBranchSessions) {
        int[] states = new int[statuses.length];
        for (int i = 0; i < statuses.length; i++) {
            states[i] = statuses[i].getCode();
        }
        //global transaction
        List<GlobalTransactionDO> globalTransactionDOs = logStore.queryGlobalTransactionDO(states, logQueryLimit);
        Map<String, List<BranchTransactionDO>> branchTransactionDOsMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(globalTransactionDOs)) {
            List<String> xids =
                globalTransactionDOs.stream().map(GlobalTransactionDO::getXid).collect(Collectors.toList());
            if (withBranchSessions) {
                List<BranchTransactionDO> branchTransactionDOs = logStore.queryBranchTransactionDO(xids);
                branchTransactionDOsMap = branchTransactionDOs.stream().collect(
                    Collectors.groupingBy(BranchTransactionDO::getXid, LinkedHashMap::new, Collectors.toList()));
            }
        }
        Map<String, List<BranchTransactionDO>> finalBranchTransactionDOsMap = branchTransactionDOsMap;
        return globalTransactionDOs.stream()
            .map(globalTransactionDO -> getGlobalSession(globalTransactionDO,
                    finalBranchTransactionDOsMap.get(globalTransactionDO.getXid()), withBranchSessions))
            .collect(Collectors.toList());
    }

    @Override
    public List<GlobalSession> readSession(SessionCondition sessionCondition) {
        if (StringUtils.isNotBlank(sessionCondition.getXid())) {
            GlobalSession globalSession = readSession(sessionCondition.getXid());
            if (globalSession != null) {
                List<GlobalSession> globalSessions = new ArrayList<>();
                globalSessions.add(globalSession);
                return globalSessions;
            }
        } else if (sessionCondition.getTransactionId() != null) {
            GlobalSession globalSession = readSession(sessionCondition.getTransactionId());
            if (globalSession != null) {
                List<GlobalSession> globalSessions = new ArrayList<>();
                globalSessions.add(globalSession);
                return globalSessions;
            }
        } else if (CollectionUtils.isNotEmpty(sessionCondition.getStatuses())) {
            return readSession(sessionCondition.getStatuses(), !sessionCondition.isLazyLoadBranch());
        }
        return null;
    }

    private GlobalSession getGlobalSession(GlobalTransactionDO globalTransactionDO,
        List<BranchTransactionDO> branchTransactionDOs) {
        return getGlobalSession(globalTransactionDO, branchTransactionDOs, true);
    }

    private GlobalSession getGlobalSession(GlobalTransactionDO globalTransactionDO,
        List<BranchTransactionDO> branchTransactionDOs, boolean withBranchSessions) {
        GlobalSession globalSession = SessionConverter.convertGlobalSession(globalTransactionDO, !withBranchSessions);
        // branch transactions
        if (CollectionUtils.isNotEmpty(branchTransactionDOs)) {
            for (BranchTransactionDO branchTransactionDO : branchTransactionDOs) {
                globalSession.add(SessionConverter.convertBranchSession(branchTransactionDO));
            }
        }
        return globalSession;
    }

    /**
     * Sets log store.
     *
     * @param logStore the log store
     */
    public void setLogStore(LogStore logStore) {
        this.logStore = logStore;
    }

    /**
     * Sets log query limit.
     *
     * @param logQueryLimit the log query limit
     */
    public void setLogQueryLimit(int logQueryLimit) {
        this.logQueryLimit = logQueryLimit;
    }
}


text:
package entry

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestNilFieldGet(t *testing.T) {
	entry := &Entry{}
	nilField := NewNilField()
	value, ok := nilField.Get(entry)
	require.True(t, ok)
	require.Nil(t, value)
}

func TestNilFieldSet(t *testing.T) {
	entry := &Entry{}
	nilField := NewNilField()
	err := nilField.Set(entry, "value")
	require.NoError(t, err)
	require.Equal(t, *entry, Entry{})
}

func TestNilFieldDelete(t *testing.T) {
	entry := &Entry{}
	nilField := NewNilField()
	value, ok := nilField.Delete(entry)
	require.True(t, ok)
	require.Nil(t, value)
	require.Equal(t, *entry, Entry{})
}

func TestNilFieldString(t *testing.T) {
	nilField := NewNilField()
	require.Equal(t, "$nil", nilField.String())
}


text:
/**
 * TumblrPostLink.js
 * -----------------
 * Represents a Tumblr post of type 'link'
 */

/**
 * @constructor
 * @param {object} data Data for post from Tumblr
 */
function TumblrPostLink(data)
{
  TumblrPost.call(this, data);
}

// subclass
TumblrPostLink.prototype = inherit(TumblrPost.prototype);
/** Constructor of original object */
TumblrPostLink.prototype.constructor = TumblrPostLink;

// ********************
// * instance methods *
// ********************

/**
 * Renders a link post to the output element specified
 * @param {string} outputElem Page element to output to
 */
TumblrPostLink.prototype.render = function(outputElem)
{
  $(outputElem).text('This is a link');
};


text:
"""Fichier contenant la fonction temps."""

import re
from datetime import datetime

from primaires.scripting.fonction import Fonction
from primaires.scripting.instruction import ErreurExecution

# Constantes
RE_TEMPS = re.compile(
        r"^(r|m)([x0-9]{1,4})\-([x0-9]{2})\-([x0-9]{2}) " \
        "([x0-9]{2})\:([x0-9]{2})$", re.I)

class ClasseFonction(Fonction):

    """Retourne le temps indiqué.

    Sans paramètre, cette fonciton retourne le temps actuel. Ce
    temps retourné peut être affiché soit en format IG (in-game),
    soit en format réel (comme "le vendredi 15 avril 2016 à 03:00".
    Le temps retourné peut être également comparé à d'autres temps.
    Il est également possible de retourner un temps spécifique, soit
    à un temps IRL, soit à un temps IG.

    """

    @classmethod
    def init_types(cls):
        cls.ajouter_types(cls.temps)
        cls.ajouter_types(cls.temps_param, "str")

    @staticmethod
    def temps():
        """Retourne le temps actuel.

        Le temps courant est retourné, c'est-à-dire le temps IRL ou IG correpsondant au moment ou la fonction s'exécute. Vous pouvez conserver ce temps (dans une mémoire ou dans une structure, par exemple). Pour l'afficher, vous aurez besoin de la fonction 'afficher_temps()'.

        Paramètres à entrer :

          Aucun

        Exemple d'utilisation :

          # Récupère le temps actuel
          temps = temps()
          # L'affiche en format IG
          ig = afficher_temps(temps, "ig")
          dire personnage "Le temps IG est ${ig}."
          # Affiche maintenant le temps réel
          irl = afficher_temps(temps, "irl")
          dire personnage "Le temps IRL est ${irl}."
          # Compare des temps entre eux
          premier = temps()
          attendre 3
          second = temps()
          si premier < second:
              # Oui, second a au moins 3 secondes de plus que premier
          finsi

        """
        return importeur.temps.variable

    @staticmethod
    def temps_param(chaine):
        """Retourne le temps modifié par la chaîne.

        La chaîne peut préciser un modificateur de temps IG ou IRL. Le format est précisé ci-dessous.

        Paramètre :

          * chaine : la chaîne indiquant le modificateur de temps

        La première lettre de la chaîne doit être "m" ou "r" pour indiquer le type de format. "m" indique que le format de temps qui suit est précisé en temps IG, "r" que le temps qui suit est exprimé en format réel.

        Après cette lettre doivent se trouver les informations suivantes :

          * 1 à 4 chiffres représentant l'année ;
          * Un signe tiret (-) ;
          * Deux chiffres représentant le mois ;
          * Un signe tiret (-) ;
          * Deux chiffres représentant le jour ;
          * Un espace ( ) ;
          * Deux chiffres représentant l'heure ;
          * Un signe deux points (:) ;
          * Deux chiffres représentant les minutes.

        Vous pouvez remplacer une information par des X à la place
        des chiffres pour indiquer que le temps actuel doit être
        utilisé. Par exemple, "rxxxx-01-01 00:00" veut dire "cette
        année réelle, le premier janvier à minuit."

        Exemples possibles :

          # On veut avoir le temps du 1 janvier 2017 à minuit
          nouvel_an = temps("r2017-01-01 00:00")
          # Que l'on peut convertir ensuite
          ig = afficher_temps(nouvel_an, "ig")
          # ... ou dans l'autre sens
          # Le temps du jour 1 du mois 1 de l'année 50 à minuit
          nouvel_an = temps("m50-01-01 00:00")
          # Et pour récupérer le format en temps IRL
          irl = afficher_temps(nouvel_an, "irl")

        """
        temps = importeur.temps.variable
        format = RE_TEMPS.search(chaine.lower())
        if format is None:
            raise ErreurExecution("Format de temps {} incorrect.".format(
                    repr(chaine)))
        cnv, annee, mois, jour, heure, minute = format.groups()
        mtn = datetime.now()
        r_annee = mtn.year
        r_mois = mtn.month
        r_jour = mtn.day
        r_heure = mtn.hour
        r_minute = mtn.minute
        m_annee = temps.annee
        m_mois = temps.mois + 1
        m_jour = temps.jour + 1
        m_heure = temps.heure
        m_minute = temps.minute

        # On remplit les format par défaut
        if cnv == "m":
            annee = int(annee) if "x" not in annee else m_annee
            mois = int(mois) if "x" not in mois else m_mois
            jour = int(jour) if "x" not in jour else m_jour
            heure = int(heure) if "x" not in heure else m_heure
            minute = int(minute) if "x" not in minute else m_minute
            mois -= 1
            jour -= 1
            temps.changer_IG(annee, mois, jour, heure, minute)
        else:
            annee = int(annee) if "x" not in annee else r_annee
            mois = int(mois) if "x" not in mois else r_mois
            jour = int(jour) if "x" not in jour else r_jour
            heure = int(heure) if "x" not in heure else r_heure
            minute = int(minute) if "x" not in minute else r_minute
            temps.changer_IRL(annee, mois, jour, heure, minute)

        return temps


text:
package com.ams.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ Add_UserBySuperTest.class, AssetDefaultEmail_Test.class,
		Create_New_Asset_Test.class, Forgot_Password_Test.class, Invalid_Login_Test.class,
		LoginFunctionality_Test.class, RequestAssetUITest.class, SignInTest.class,
		SignUp_ValidationTest.class, SignUpFieldEmptyTest.class, SignUpFieldsVisibleTest.class, SignUpLinkTest.class,
		SignUpPlaceHolderTest.class, Test_Logout.class, Test_SignUp.class })
public class AllTests {

}


text:
package com.cloud.hypervisor.kvm.resource.wrapper;

import com.cloud.agent.api.Answer;
import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.hypervisor.kvm.resource.LibvirtVmDef.InterfaceDef;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;

import java.util.List;

import org.libvirt.Connect;
import org.libvirt.LibvirtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ResourceWrapper(handles = SecurityGroupRulesCmd.class)
public final class LibvirtSecurityGroupRulesCommandWrapper
        extends CommandWrapper<SecurityGroupRulesCmd, Answer, LibvirtComputingResource> {

    private static final Logger s_logger = LoggerFactory.getLogger(LibvirtSecurityGroupRulesCommandWrapper.class);

    @Override
    public Answer execute(final SecurityGroupRulesCmd command, final LibvirtComputingResource libvirtComputingResource) {
        String vif = null;
        String brname = null;
        try {
            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();

            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
            final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());

            vif = nics.get(0).getDevName();
            brname = nics.get(0).getBrName();
        } catch (final LibvirtException e) {
            return new SecurityGroupRuleAnswer(command, false, e.toString());
        }

        final boolean result = libvirtComputingResource.addNetworkRules(command.getVmName(),
                Long.toString(command.getVmId()), command.getGuestIp(), command.getSignature(),
                Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname,
                command.getSecIpsString());

        if (!result) {
            s_logger.warn("Failed to program network rules for vm " + command.getVmName());
            return new SecurityGroupRuleAnswer(command, false, "programming network rules failed");
        } else {
            s_logger.debug("Programmed network rules for vm " + command.getVmName() + " guestIp=" + command.getGuestIp()
                    + ",ingress numrules="
                    + command.getIngressRuleSet().length + ",egress numrules=" + command.getEgressRuleSet().length);
            return new SecurityGroupRuleAnswer(command);
        }
    }
}


text:
//
//  FileHandling.h
//  CMakeProject
//
//  Created by blasse on 7/26/13.
//
//

#ifndef FILEHANDLING_H
#define FILEHANDLING_H

#include <dirent.h>
#include <string>

namespace PreprocessingPipeline {

  ////////////////////////////////////////////////////////////////////////////////
  /*
   struct including all output folders
   */

  struct OutputDirs {
    DIR * rootDir;
    DIR * flatFieldDir;
    DIR * constrastAdjDir;
    DIR * stitchedDir;
    std::string rootPath;
    std::string flatFieldPath;
    std::string contrastAdjPath;
    std::string stitchedPath;
  };

  ////////////////////////////////////////////////////////////////////////////////
  /*
   Function to create all output folders

   @param outputDirPath:  path to the parent output folder
   */

  OutputDirs MakeOutputDirs (std::string outputDirPath);

}

#endif


text:
package org.eclipse.bpel.ui.editparts.borders;

import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ImageFigure;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Image;

public class RoundRectangleBorderWithDecoration extends RoundRectangleBorder {
	Image decoration;

	private int decoXOffset;
	private int decoYOffset;

	private IFigure decorationFigure;

	public RoundRectangleBorderWithDecoration(IFigure parent, Image decoration) {
		this(parent,decoration,new Insets(5,5,5,5));
	}
	public RoundRectangleBorderWithDecoration(IFigure parent, Image decoration, Insets insets) {
		super(insets);
		this.decoration = decoration;
		decoXOffset = 0;
		decoYOffset = -(decoration.getBounds().height/2);

		this.decorationFigure = new ImageFigure(decoration);
		this.decorationFigure.setParent(parent);
	}

	public void paint(IFigure figure, Graphics graphics, Insets insets) {
		super.paint(figure, graphics, insets);
		if (decoration != null) {
			Rectangle r = figure.getBounds();
			graphics.pushState();
			Rectangle decoBounds = new Rectangle(r.x+decoXOffset,r.y+decoYOffset,decoration.getBounds().width,decoration.getBounds().height);
			decorationFigure.setBounds(decoBounds);
			graphics.setClip(decoBounds);
			decorationFigure.paint(graphics);
			graphics.popState();
		}
	}

	public int getDecoXOffset() {
		return decoXOffset;
	}
	public int getDecoYOffset() {
		return decoYOffset;
	}
	public Image getDecoration() {
		return decoration;
	}
	public IFigure getDecorationFigure() {
		return decorationFigure;
	}
}


text:
from bottle import request, get, post, static_file, route, run, template
import ibm_db_dbi as dbi
from itoolkit import *
from itoolkit.lib.ilibcall import *     #for local jobs

version = tuple(map(int, dbi.__version__.split('.')))
if version < (2, 0, 5, 5):
    raise Exception("Need ibm_db_dbi 2.0.5.5 or higher to run, you have " + dbi.__version__)

@route('/sample')
def sample():
    return static_file('sample.html', root='.')

@route('/query', method='POST')
def query_ibm_db():
    statement = request.forms.get('sql')

    conn = dbi.connect()
    cur = conn.cursor()
    cur.execute(statement)

    headers = [descr[0] for descr in cur.description]

    return template('query', headers=headers, rows=cur)

@route('/cmd', method='POST')
def cmd_toolkit():
    cl_statement = request.forms.get('cl')

    # xmlservice
    itool = iToolKit()
    itransport = iLibCall()
    itool.add(iCmd5250(cl_statement, cl_statement))
    itool.call(itransport)

    # results from list
    data = ''
    for output_outer in itool.list_out():
        for output_inner in output_outer:
            data += output_inner

    return template('cmd', data=data)

run(host='0.0.0.0', port=9000, debug=True, reloader=True)


text:
namespace kv {
	namespace rocks {
		class env : public node::ObjectWrap {
		public:
			static void setup_export(v8::Handle<v8::Object>& exports);

		private:
			template <class K, class V> friend class db;

		private:
			static NAN_METHOD(ctor);
			static NAN_METHOD(open);

		private:
			env();
			~env();

		private:
			int register_db(const rocksdb::ColumnFamilyDescriptor& desc);

		private:
			rocksdb::DB *_db;
			std::vector<rocksdb::ColumnFamilyDescriptor> _desc;
			std::vector<rocksdb::ColumnFamilyHandle*> _handles;
		};
	} // namespace rocks
} // namespace kv


text:
import DatePicker from './DatePicker';
import Registry from '@ui-autotools/registry';

const metadata = Registry.getComponentMetadata(DatePicker);

metadata.exportInfo = {
  path: 'src/DatePicker/DatePicker.js',
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace FlappyBird
{
    class Bird
    {
        public string[] bird={" __ ",
                       "/  \\",
                       "   *>" ,
                      "\\__/"};
        public Point position=new Point();

    }
}


text:
use ruma_api::ruma_api;
use ruma_events::EventType;
use ruma_identifiers::RoomId;
use serde_json::value::RawValue as RawJsonValue;

ruma_api! {
    metadata {
        description: "Get state events associated with a given key.",
        method: GET,
        name: "get_state_events_for_key",
        path: "/_matrix/client/r0/rooms/:room_id/state/:event_type/:state_key",
        rate_limited: false,
        requires_authentication: true,
    }

    request {
        /// The room to look up the state for.
        #[ruma_api(path)]
        pub room_id: RoomId,

        /// The type of state to look up.
        #[ruma_api(path)]
        pub event_type: EventType,

        /// The key of the state to look up.
        #[ruma_api(path)]
        pub state_key: String,
    }

    response {
        /// The content of the state event.
        #[ruma_api(body)]
        pub content: Box<RawJsonValue>,
    }

    error: crate::Error
}


text:
const fs = require('fs');

module.exports.pageNumberJsonBuilder = function(number){
  var array ={count:[]};
  for(var i=0; i<number; i++){
    array.count.push(i+1);
  }
  return array;
}

module.exports.cleanUploadFiles = function(filename, callback){
  fs.unlink('uploadFiles/' + filename, (err)=>{
      if(err) callback(err);
      else callback(null);
    });
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>
  <script src="../../dist/modular/js/core.js" type="text/javascript"></script>
  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <link href="../../dist/modular/css/dropdown.css" rel="stylesheet" type="text/css">
  <script src="../../dist/modular/js/dropdown.js"></script>
</head>
<body style="padding: 8px;">
 <select id="dropdown" width="200"></select>
 <script>
     var dropdown = $('#dropdown').dropdown({
         dataSource: '/Locations/Get',
         uiLibrary: 'bootstrap4',
         iconsLibrary: 'fontawesome',
         valueField: 'id'
     });
 </script>
</body>
</html>


text:
package com.example.administrator.zhihu.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * Created by Administrator on 2016/8/12 0012.
 */
public class SaveUtils {
    private  static  SharedPreferences sp =ApplicationUtil.getContext().getSharedPreferences("zhihu.txt",Context.MODE_PRIVATE);;
    public static  void saveString(String key,String value){
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
       boolean flag =  editor.commit();
        Log.d("tag12",flag+"是否成功写入");
    }
    public static  String getString(String key){
        String value = sp.getString(key, "");
        return value;
    }
    public static  void saveBoolean(String key,Boolean value){
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key,value);
        editor.commit();
    }
    public static boolean getBoolean(String key){
        Boolean value = sp.getBoolean(key,true);
        return  value;

    }

}


text:
use syntax::ast;
use syntax::ast::{LitKind, MetaItemKind};

pub fn prepare_line(input: String) -> String {
    let mut result = input;

    // TODO: only replace if at line beginning
    result = result.replace("//! ", "");
    result = result.replace("//!", "");
    result = result.replace("/// ", "");
    result = result.replace("///", "");
    result = result.replace("// ", "");
    result = result.replace("//", "");

    result
}

pub fn to_text_block(attrs: &[ast::Attribute]) -> String {
    let maybe_lines: Vec<Option<String>> = attrs.iter().map(|attr|
        match attr.value.node {
            MetaItemKind::NameValue(ref spanned) => {
                match spanned.node {
                    LitKind::Str(text, _) => {
                        let mut test_text = text.as_str().to_string();
                        test_text = prepare_line(test_text);

                        return Some(test_text);
                    },
                    _ => None,
                }
            },
            _ => None,
        }
    ).collect();

    let lines: Vec<_> = maybe_lines.into_iter().filter_map(|l| l).collect();
    let text_block = lines.join("\n");

    text_block
}


text:
from guizero import App, Drawing
from turtle import RawTurtle

app = App()
drawing = Drawing(app)
turtle = RawTurtle(drawing.tk)
turtle.forward(100)
turtle.left(720)

app.display()