text:
<title>global.js</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

global.js

'use strict';

angular.module('tocsinApp')
    .controller('GlobalCtrl', function ($scope, $rootScope, configManager) {
        if($rootScope.SpineFMID === undefined){
            window.location.href = '#/';
            return;
        }
        $scope.displayConfigNames = false;
        $scope.spineFMNewName = null;
        $scope.openSetSpineNameModal = false;
        $scope.selectedNode = null;
        $scope.showInfo = false;
        $scope.isNodeSelected = false;
        $scope.selectedState = '';
        $scope.showGenarationLoading = false;
        $scope.showMouseConfiguration = false;
        $scope.helpModal = false;
        $scope.compatiblesConfigs = [];
        $scope.info = '';   // info to display in accordion body
        $scope.header = ''; // info to display on accordion header

        /**
         * set info visibility in accordion object
         */
        $scope.setInfoVisibility = function(){
            if($scope.showInfo === false){
                $scope.showInfo = true;
            }
            else{
                $scope.showInfo =false;
            }
        };
        /**
         * get the number of created configs
         * @returns {number}
         */
        $scope.getNbConfigsTotal = function(){
            var total = 0;
            for(var de in $rootScope.configurations){
                total += $rootScope.configurations[de].partialConfig.number;
                total += $rootScope.configurations[de].validConfig.number;
            }
            return total;
        };

        /**
         * get properties of selected node to display on top (in accordion)
         * @param node
         */
        $scope.getInfoFromSelectedNode = function(node){
            $scope.isNodeSelected = true;
            $scope.header = node.de + ' : '+ node.name;
            var prop = $scope.getProperties(node);
            $scope.info = $scope.getDEToLinkText(prop.deToLink);
            $scope.info += prop.nbConfigCompatibles  + ' configuration(s) compatible(s)';
            if(node.isValid === false){
                $scope.selectedState = $rootScope.colorsState.notFinishedConfig;
            }
            else{
                if(node.isLinked === true){
                    $scope.selectedState = $rootScope.colorsState.finishedLinkedConfig;
                }
                else{
                    $scope.selectedState = $rootScope.colorsState.finishedNotLinkedConfig;
                }
            }

        };

        /**
         * check if generation is allowed
         */
        $scope.checkIsGenerateAllowed = function(){
            configManager.checkIsGenerateAllowed($rootScope.SpineFMID).then(function (response) {
                    if(response.toString() === 'false'){
                        $rootScope.isGenerateAllowed = true;
                    }
                    else{
                        $rootScope.isGenerateAllowed = false;
                    }
                },
                function(){
                    window.alert('checkIsGenerateAllowed failed');
                });
        };

        /**
         * get DE of the linked Configurations
         * @param configSrc
         */
        $scope.getDESOfLinkedConfig = function(configSrc){
            var domain = [];
            for(var i = 0; i< $rootScope.links.length; i++){
                var link = $rootScope.links[i];
                if(link.source === configSrc){
                    var currentDE = $scope.getDEOfConfig(link.target);
                    domain.push(currentDE);
                }
                else if(link.target === configSrc){
                    var myDE = $scope.getDEOfConfig(link.source);
                    domain.push(myDE);
                }
            }
            return domain;
        };

        /**
         * get the DE on the given config
         * @param configID
         * @returns {null}
         */
        $scope.getDEOfConfig = function(configID){
            var response  = null;
            for(var de in $rootScope.configurations){
                var deConfig = $rootScope.configurations[de];
                for(var id in deConfig.validConfig.listConfigs){
                    if(id === configID){
                        response = de;
                    }
                }
            }
            return response;
        };

        /**
         * get text of unlinked config
         * @param toLink
         * @returns {string}
         */
        $scope.getDEToLinkText = function(toLink){
            var text = '';
            if(toLink.length> 0){
                text = 'Liens absents : [';
                for(var z = 0; z<toLink.length; z++){
                    if(z === toLink.length -1){
                        text += toLink[z] + '] ; ';
                    }
                    else{
                        text += toLink[z]+ ', ';
                    }
                }
            }
            return text;
        };

        /**
         * get the given node's properties
         * @param node
         * @returns {{nbConfigCompatibles: number, deToLink: Array}}
         */
        $scope.getProperties = function(node){
            var nb = 0;
            var toLink = [];
            var properties = {nbConfigCompatibles : 0, deToLink:[]};
            if($rootScope.compatiblesDES[node.de]) {
                if(node.isValid === false){
                    toLink = $rootScope.compatiblesDES[node.de];
                    for(var t = 0; t< $rootScope.compatiblesDES[node.de].length; t++ ){
                        var de = $rootScope.compatiblesDES[node.de][t];
                        if($rootScope.configurations[de]){
                            nb += $rootScope.configurations[de].partialConfig.number;
                            nb += $rootScope.validConfigs[de].linked;
                            nb += $rootScope.validConfigs[de].notLinked;
                        }
                    }
                }
                else{
                    for(var i = 0; i< $rootScope.compatiblesDES[node.de].length; i++ ){
                        var linkedDES = $scope.getDESOfLinkedConfig(node.id);
                        var currentDE = $rootScope.compatiblesDES[node.de][i];
                        if(linkedDES.indexOf(currentDE) < 0){
                            toLink.push(currentDE);
                        }
                        var compt = $scope.getConfigCompatibles(currentDE, node.id);
                        nb += compt.length;
                    }
                }
                properties.nbConfigCompatibles = nb;
                properties.deToLink = toLink;
            }
            return properties;
        };

        /**
         * display all node's names
         */
        $scope.displayNames = function(){
            var allCircles = document.getElementsByTagName('circle');
            if($scope.displayConfigNames === true){
                $scope.displayConfigNames = false;
                for (var i = 0 ; i < allCircles.length; i++) { $(allCircles[i]).data('tooltipsy').hide(); }
            }
            else {
                $scope.displayConfigNames = true;
                for(var y = 0 ; y < allCircles.length; y++) { $(allCircles[y]).data('tooltipsy').show(); }

            }
        } ;

        /**
         * check if a configurations is linkable with a the given de's configurations
         * @param configID
         * @param de
         * @returns {boolean}
         */
        $scope.isConfigLinkable = function(configID, de){
            var isLinkable = false;
            configManager.checkIsConfigLinkable($rootScope.SpineFMID, configID, de).then(function (linkable) {
                    isLinkable = linkable;
                },
                function(){
                    window.alert('Echec de check config compatible with');
                });

            return isLinkable;
        };

        /**
         * Get configs from the given domain which are compatibles with the given config
         * @param DeTarget
         * @param confID
         */
        $scope.getConfigCompatibles = function(DeTarget, confID){

            var compatibles = [];
            var isLinkable = $scope.isConfigLinkable(confID, DeTarget);
            if(isLinkable === true){
                configManager.getCompatiblesConfigurations($rootScope.SpineFMID, DeTarget, confID).then(function (configCompatibles) {

                        compatibles = configCompatibles;
                    },
                    function(){
                        window.alert('Echec du chargement des configurations compatibles');
                    });
            }

            return compatibles;
        };

        /**
         * handle compatibles configs between nodes
         */
        $scope.handleCompatiblesConfigurations = function(nodes){
            for(var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                if (node.isValid === true) {
                    $scope.compatiblesConfigs[node.id] = [];
                    if($rootScope.compatiblesDES[node.de]) {
                        for(var j = 0; j < $rootScope.compatiblesDES[node.de].length; j++) {
                            var domain = $rootScope.compatiblesDES[node.de][j];
                            $scope.checkCompatiblesConfigurations(node, domain);
                        }
                    }
                }
            }
        };

        /**
         * check compatibles configurations
         * @param node
         * @param de
         */
        $scope.checkCompatiblesConfigurations = function (node, de) {
            configManager.checkIsConfigLinkable($rootScope.SpineFMID, node.id, de).then(function (linkable) {
                    if(linkable.toString() === 'true') {
                        configManager.getLinkedConfigurations($rootScope.SpineFMID, de, node.id).then(function (linkedConfigs) {
                                var multiplicity = $scope.getMultiplicityBetweenDE(node.de, de);
                                if(linkedConfigs.length  !==  multiplicity){
                                    configManager.getCompatiblesConfigurations($rootScope.SpineFMID, de, node.id).then(function (configCompatibles) {
                                            for(var i=0; i < configCompatibles.length; i++) {
                                                $scope.compatiblesConfigs[node.id].push(configCompatibles[i]);
                                            }
                                        },
                                        function(){
                                            //window.alert('Echec du chargement des configurations compatibles');
                                    });
                                }
                            },
                            function(){
                                window.alert('get linked in compatibles failed');
                            });
                    }
                },
                function (){
                    window.alert('Echec de check config compatible with');
                });
        };

        /**
         * link 2 given configurations
         * @param deSource
         * @param configSource
         * @param deTarget
         * @param configTarget
         */
        $scope.linkConfigurations = function(deSource, configSource, deTarget, configTarget){

            configManager.linkConfigurations($rootScope.SpineFMID, configSource, configTarget).then(function (result) {

                    $rootScope.links.push({'source':configSource, 'target': configTarget});
                    $scope.checkIsLinked(deSource,configSource);
                    $scope.checkIsLinked(deTarget,configTarget);
                    if(result.deletedContext){
                        $scope.handleChanges(result);
                    }
                },
                function(){
                    window.alert(' link configurations failed');
                });
        };

        /**
         * check if config is linked
         * @param de
         * @param configID
         */
        $scope.checkIsLinked = function(de, configID){
            if($rootScope.configurations[de].validConfig.listConfigs[configID]){
                configManager.checkIsConfigLinked($rootScope.SpineFMID, configID).then(function (linked) {
                        if(linked.toString() === 'true') {

                            $rootScope.configurations[de].validConfig.listConfigs[configID].isLinked = true;
                            var noNewAllowed = $scope.isAddNewAllowed(de);
                            if(noNewAllowed.toString() === 'false') {
                                if ($rootScope.validConfigs[de].linked === 1) {
                                    $rootScope.validConfigs[de].linked += 0;
                                    $rootScope.validConfigs[de].notLinked += 0;
                                }
                                else{
                                    $rootScope.validConfigs[de].linked += 1;
                                    $rootScope.validConfigs[de].notLinked += -1;
                                }
                            }
                            else {
                                $rootScope.validConfigs[de].linked += 1;
                                $rootScope.validConfigs[de].notLinked += -1;
                            }
                        }

                    },
                    function(){
                        window.alert('Echec de check config is linked');
                    });
            }
        };

        /**
         *  handle change Context when we link configurations between them
         * @param change
         */
        $scope.handleChanges = function(change){

            var ctxIDToDelete = change.deletedContext;
            var newCtxID = change.replacedBy;

            for(var de in $rootScope.configurations){
                var deConfig = $rootScope.configurations[de];
                if(deConfig.partialConfig.listConfigs[ctxIDToDelete] !== undefined){
                    var config = deConfig.partialConfig.listConfigs[ctxIDToDelete];

                    if(deConfig.partialConfig.listConfigs[newCtxID] === undefined){
                        config.url = '#/de/'+de+'/ctx/'+newCtxID;
                        config.ctxID =  newCtxID;
                        $rootScope.configurations[de].partialConfig.listConfigs[newCtxID] = config;
                        delete $rootScope.configurations[de].partialConfig.listConfigs[ctxIDToDelete];
                    }
                }
            }

        };

        /**
         *  check if the given config is linked or not
         * @param configID
         * @returns {boolean}
         */
        $scope.isConfigLinked = function(configID){
            var isLinked= false;
            configManager.checkIsConfigLinked($rootScope.SpineFMID, configID).then(function (linked) {
                    isLinked = linked;
                },
                function(){
                    window.alert('Echec de is linked');
                });

            return isLinked;
        };

        /**
         *   Get multiplicity between given domains
         * @param deSrc
         * @param deTarget
         * @returns {number}
         */
        $scope.getMultiplicityBetweenDE = function(deSrc, deTarget) {
            var mult = 0;
            if($rootScope.DEProperties[deSrc]){
                if($rootScope.DEProperties[deSrc].target){
                    for(var i = 0; i < $rootScope.DEProperties[deSrc].target.length; i++){
                        var target = $rootScope.DEProperties[deSrc].target[i];
                        if(target !== null && target !== undefined){
                            if(target.de === deTarget) {
                                mult = target.linkMultiplicity.upperBound;
                            }
                        }
                    }
                }
            }
            return mult;
        };

// $$$$$$$$$$$$$$$$$$$$$$$$$  START D3 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
        /**
         * active context menu (on right click)
         */
        $('#d3viz').contextMenu('context-menu-1', {
            'Link ': {
                click: function() {
                    if($scope.selectedNode !== null){
                        dragLine
                            .style('marker-end', 'url(#end-arrow)')
                            .classed('hidden', false)
                            .attr('d', 'M' +$scope.selectedNode.x + ',' + $scope.selectedNode.y + 'L' + $scope.selectedNode.x + ',' + $scope.selectedNode.y);
                    }
                },
                klass: 'menu-item-1' // a custom css class for this menu item (usable for styling)
            },
            'See configuration': {
                click: function() {
                    if($scope.selectedNode !== null){
                        window.location.href = $scope.selectedNode.url;
                    }
                },
                klass: 'menu-item-1' // a custom css class for this menu item (usable for styling)
            },
            'See Domain assessment': {
                click: function(){
                    if($scope.selectedNode !== null){
                        window.location.href = '#/bilan/'+$scope.selectedNode.de;
                    }
                },
                klass: 'second-menu-item'
            }
        });

        var isCompatiblesWithSelectedNode = function(selectedNode, currentNode) {
            var response = false;
            if(selectedNode !== null && currentNode!== null) {
                if ($scope.compatiblesConfigs[selectedNode.id]){
                    response = $scope.compatiblesConfigs[selectedNode.id].indexOf(currentNode.id) >= 0;
                }
                else if ($scope.compatiblesConfigs[currentNode.id]) {
                    response = $scope.compatiblesConfigs[currentNode.id].indexOf(selectedNode.id) >= 0;
                }
            }
            return response;
        };

        var getColorOfConfig = function(config){
            var color;
            if(config.isValid === true){
                if(config.isLinked === true){
                    color = 'green';
                }
                else {
                    color = 'orange';
                }
            }
            else{
                color = 'red';
            }
            return color;
        };

        var getListOfNodes = function () {
            var num = 0;
            var result = [];
            for (var i = 0; i < $rootScope.domainElements.length; i++) {
                var de = $rootScope.domainElements[i];
                var symbol = de.substring(0,1).toUpperCase();
                var listConfigs = $rootScope.configurations[de].validConfig.listConfigs;
                var partialConfigs = $rootScope.configurations[de].partialConfig.listConfigs;
                for (var configID in listConfigs) {
                    result.push({'number': symbol+num, 'id':configID, 'name':listConfigs[configID].name, 'de':de, 'isLinked':listConfigs[configID].isLinked, isValid: true, 'ctxID':listConfigs[configID].ctxID, 'url': listConfigs[configID].url });
                    num += 1;
                }

                for (var partialID in partialConfigs) {
                    result.push({'number': symbol+num, 'id':partialConfigs[partialID].name, 'name':partialConfigs[partialID].name, 'ctxID':partialConfigs[partialID].ctxID, 'de':de, isValid: false, 'url': partialConfigs[partialID].url });
                    num += 1;
                }
            }
            return result;
        };

        var getConfigsLinked = function(noeuds) {
            var result = [];

            for(var i = 0; i< $rootScope.links.length; i++){
                var link = $rootScope.links[i];
                var nodeSource = null;
                var nodeTarget = null;
                for(var y = 0; y < noeuds.length; y++){
                    var node = noeuds[y];
                    if(node.id === link.source){
                        nodeSource = node;
                    }
                    else  if(node.id === link.target){
                        nodeTarget = node;
                    }
                }

                if(nodeSource !== null && nodeTarget !== null){

                    result.push({source:nodeSource, target: nodeTarget, left:false, right:true, isPartial:false});

                }
            }
            for(var z = 0; z<$rootScope.configsToLink.length; z++){
                var toLink = $rootScope.configsToLink[z];
                var nodeSrc = null;
                var nodeTg = null;
                for(var t = 0; t < noeuds.length; t++){
                    var currentNode = noeuds[t];
                    if(currentNode.id === toLink.configID){
                        nodeSrc = currentNode;
                    }
                    else if(currentNode.ctxID === toLink.ctxID){
                        nodeTg = currentNode;
                    }
                }

                if(nodeSrc !== null && nodeTg !== null){

                    result.push({source:nodeSrc, target: nodeTg, left:false, right:true, isPartial:true});

                }
            }
            return result;
        };

        // set up SVG for D3
        var width  = 400,
            height = 500;

        var divViz = document.getElementById('d3viz');
        var svg = d3.select(divViz)
            .append('svg')
            .attr('width', divViz.offsetWidth)
            .attr('height', 500);

// set up initial nodes and links
//  - nodes are known by 'id', not by index in array.
//  - reflexive edges are indicated on the node (as a bold black circle).
//  - links are always source < target; edge directions are set by 'left' and 'right'.
        var nodes = getListOfNodes();
        var links = getConfigsLinked(nodes);
        $scope.checkIsGenerateAllowed();
        $scope.header =  'Nombre de configurations : '+ $scope.getNbConfigsTotal();

        function tick() {
            // draw directed edges with proper padding from node centers
            path.attr('d', function(d) {
                var deltaX = d.target.x - d.source.x,
                    deltaY = d.target.y - d.source.y,
                    dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
                    normX = deltaX / dist,
                    normY = deltaY / dist,
                    sourcePadding = d.left ? 17 : 12,
                    targetPadding = d.right ? 17 : 12,
                    sourceX = d.source.x + (sourcePadding * normX),
                    sourceY = d.source.y + (sourcePadding * normY),
                    targetX = d.target.x - (targetPadding * normX),
                    targetY = d.target.y - (targetPadding * normY);
                return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
            });

            circle.attr('transform', function(d) {
                return 'translate(' + d.x + ',' + d.y + ')';
            });
        }

// init D3 force layout
        var force = d3.layout.force()
            .nodes(nodes)
            .links(links)
            .size([width, height])
            .linkDistance(150)
            .charge(-500)
            .on('tick', tick);

// define arrow markers for graph links
        svg.append('svg:defs').append('svg:marker')
            .attr('id', 'end-arrow')
            .attr('viewBox', '0 -5 10 10')
            .attr('refX', 6)
            .attr('markerWidth', 3)
            .attr('markerHeight', 3)
            .attr('orient', 'auto')
            .append('svg:path')
            .attr('d', 'M0,-5L10,0L0,5')
            .attr('fill', '#000');

        svg.append('svg:defs').append('svg:marker')
            .attr('id', 'start-arrow')
            .attr('viewBox', '0 -5 10 10')
            .attr('refX', 4)
            .attr('markerWidth', 3)
            .attr('markerHeight', 3)
            .attr('orient', 'auto')
            .append('svg:path')
            .attr('d', 'M10,-5L0,0L10,5')
            .attr('fill', '#000');

// line displayed when dragging new nodes
        var dragLine = svg.append('svg:path')
            .attr('class', 'link dragline hidden')
            .attr('d', 'M0,0L0,0');

// handles to link and node element groups
        var path = svg.append('svg:g').selectAll('path'),
            circle = svg.append('svg:g').selectAll('g');

// mouse event vars
        var selectedNode = null,
            selectedLink = null,
            mousedownLink = null,
            mousedownNode = null,
            mouseupNode = null,
            mouseoverNode  = null;

        function resetMouseVars() {
            mousedownNode = null;
            mouseupNode = null;
            mousedownLink = null,
            mouseoverNode  = null;
        }

// update force layout (called automatically each iteration)

// update graph (called when needed)
        function restart() {

            // path (link) group
            path = path.data(links);

            // update existing links

            path.classed('selected', function(d) { return (d === selectedLink || d.isPartial === true); })
                .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
                .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

            // add new links
            path.enter().append('svg:path')
                .attr('class', 'link')
                .classed('selected', function(d) { return (d === selectedLink || d.isPartial === true); })
                .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
                .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
                .on('mousedown', function(d) {
                    if(d3.event.ctrlKey) {
                        return;
                    }

                    // select link
                    mousedownLink = d;
                    if(mousedownLink === selectedLink) {
                        selectedLink = null;
                    }
                    else {
                        selectedLink = mousedownLink;
                    }
                    selectedNode = null;
                    restart();
                });

            // remove old links
            path.exit().remove();

            // circle (node) group
            // NB: the function arg is crucial here! nodes are known by id, not by index!
            circle = circle.data(nodes, function(d) { return d.id; });

            // update existing nodes (reflexive & selected visual states)
            circle.selectAll('circle')
                .style('fill', function(d) {
                    var isCompatibleWithSelected = isCompatiblesWithSelectedNode(selectedNode,d);
                    return (d === selectedNode || isCompatibleWithSelected === true) ? d3.rgb(getColorOfConfig(d)).brighter().toString() : getColorOfConfig(d);
                });

            // add new nodes
            var g = circle.enter().append('svg:g');

            g.append('svg:circle')
                .attr('class', 'node')
                .attr('r', 20)
                .attr('title', function(d) { return 'Name : '+d.name; })
                .style('fill', function(d) {
                    var isCompatibleWithSelected = isCompatiblesWithSelectedNode(selectedNode,d);
                    return (d === selectedNode || isCompatibleWithSelected === true) ? d3.rgb(getColorOfConfig(d)).brighter().toString() : getColorOfConfig(d);
                })
                .style('stroke', function() { return 'grey'; })
                //.style('stroke', function(d) { return d3.rgb(getColorOfConfig(d)).darker().toString(); })
                .on('mouseover', function(d) {
                    mouseoverNode = d;
                    if(!mousedownNode || d === mousedownNode) {
                        return;
                    }
                    // enlarge target node
                    d3.select(this).attr('transform', 'scale(1.1)');

                })
                .on('mouseout', function(d) {
                    if(!mousedownNode || d === mousedownNode) {
                        return;
                    }
                    // unenlarge target node
                    d3.select(this).attr('transform', '');
                })
                .on('mousedown', function(d) {

                    if(d3.event.ctrlKey) {
                        return;
                    }
                    $scope.getInfoFromSelectedNode(d);

                    // select node
                    mousedownNode = d;
                    $scope.selectedNode = d;
                    if(mousedownNode === selectedNode) {
                        selectedNode = null;
                    }
                    else {
                        selectedNode = mousedownNode;
                    }
                    selectedLink = null;

                    // reposition drag line
                    if(mousedownNode.isValid === false){
                        dragLine
                            .style('marker-end', 'url(#end-arrow)')
                            .classed('hidden', true)
                            .attr('d', 'M' + mousedownNode.x + ',' + mousedownNode.y + 'L' + mousedownNode.x + ',' + mousedownNode.y);
                    }

                    restart();
                })
                .on('mouseup', function(d) {
                    if(!mousedownNode) {
                        return;
                    }

                    // needed by FF
                    dragLine
                        .classed('hidden', true)
                        .style('marker-end', '');

                    // check for drag-to-self
                    mouseupNode = d;
                    if(mouseupNode === mousedownNode) { resetMouseVars(); return; }

                    // check if the 2 configs are not in the same de
                    if(mousedownNode.de === mouseupNode.de){
                        window.alert('Opération interdite pour les configurations d\'un même domaine');
                        resetMouseVars();
                        return;
                    }

                    var isCompatibles = isCompatiblesWithSelectedNode(mousedownNode, mouseupNode);
                    if(isCompatibles === false){
                        window.alert('Configurations incompatibles');
                        resetMouseVars();
                        return;
                    }
                    // unenlarge target node
                    d3.select(this).attr('transform', '');

                    // add link to graph (update if exists)
                    // NB: links are strictly source < target; arrows separately specified by booleans
                    var source, target, direction;
                    if(mousedownNode.number < mouseupNode.number) {
                        source = mousedownNode;
                        target = mouseupNode;
                        direction = 'right';
                    } else {
                        source = mouseupNode;
                        target = mousedownNode;
                        direction = 'left';
                    }

                    var link;
                    link = links.filter(function(l) {
                        return (l.source === source && l.target === target);
                    })[0];

                    if(link) {
                        link[direction] = true;
                    } else {
                        link = {source: source, target: target, left: false, right: false , isPartial:false};
                        link[direction] = true;
                        links.push(link);
                        $scope.linkConfigurations(source.de,source.id, target.de,target.id);
                        $scope.checkIsGenerateAllowed();
                    }

                    // select new link
                    selectedLink = link;
                    selectedNode = null;
                    restart();
                });

            // show node IDs
            g.append('svg:text')
                .attr('x', 0)
                .attr('y', 4)
                .attr('class', 'id')
                .text(function(d) {
                    return d.number;
                });

            // remove old nodes
            circle.exit().remove();
            $('svg circle').tooltipsy({
                alignTo: 'element',
                className: 'tipsy-inner'
            });
            // set the graph in motion
            force.start();
        }

        /**
         * mouse down callback
         */
        function mousedown() {
            if(mousedownNode === null){
                $scope.isNodeSelected = false;
                $scope.header =  'Nombre de configurations '+ $scope.getNbConfigsTotal();
                $scope.info = '';
            }
            console.log('Mousedown desactive');
        }

        /**
         * mouse over callback
         */
        function mouseover() {
            console.log('MouseOver desactive');
        }

        /**
         * mouse move callback
         */
        function mousemove() {
            if(!mousedownNode) {
                return;
            }

            // update drag line
            var self = divViz;
            dragLine.attr('d', 'M' + mousedownNode.x + ',' + mousedownNode.y + 'L' + d3.mouse(self)[0] + ',' + d3.mouse(self)[1]);

            restart();
        }

        /**
         * mouse up callback
         */
        function mouseup() {
            if(mousedownNode) {
                // hide drag line
                dragLine
                    .classed('hidden', true)
                    .style('marker-end', '');
            }

            // because :active only works in WebKit?
            svg.classed('active', false);

            // clear mouse event vars
            resetMouseVars();
        }

// app starts here
        svg.on('mousedown', mousedown)
            .on('mousemove', mousemove)
            .on('mouseover', mouseover)
            .on('mouseup', mouseup);
        d3.select(window);
            //.on('keydown', keydown)
            //.on('keyup', keyup);
        restart();
        $scope.handleCompatiblesConfigurations(nodes);
        circle.exit().remove();
    });
// $$$$$$$$$$$$$$$$$$$$$$$$$  END D3 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


text:
import { isFocusable } from "../isFocusable";

describe("isFocusable", () => {
  it("should default to programmatic focus type", () => {
    const element = document.createElement("div");
    element.tabIndex = -1;

    expect(isFocusable(element)).toBe(true);
    expect(isFocusable(element, "tab")).toBe(false);
    expect(isFocusable(element, "programmatic")).toBe(true);
  });

  it("should work correctly for anchors and areas", () => {
    const anchor = document.createElement("a");
    const area = document.createElement("area");

    expect(isFocusable(anchor, "tab")).toBe(false);
    expect(isFocusable(area, "tab")).toBe(false);
    expect(isFocusable(anchor, "programmatic")).toBe(false);
    expect(isFocusable(area, "programmatic")).toBe(false);

    anchor.href = "#";
    area.href = "#";
    expect(isFocusable(anchor, "tab")).toBe(true);
    expect(isFocusable(area, "tab")).toBe(true);
    expect(isFocusable(anchor, "programmatic")).toBe(true);
    expect(isFocusable(area, "programmatic")).toBe(true);
  });

  it("should work correctly for disable-able elements", () => {
    const button = document.createElement("button");
    const select = document.createElement("select");
    const textarea = document.createElement("textarea");
    const input = document.createElement("input");
    input.type = "text";

    expect(isFocusable(button, "tab")).toBe(true);
    expect(isFocusable(select, "tab")).toBe(true);
    expect(isFocusable(textarea, "tab")).toBe(true);
    expect(isFocusable(input, "tab")).toBe(true);
    expect(isFocusable(button, "programmatic")).toBe(true);
    expect(isFocusable(select, "programmatic")).toBe(true);
    expect(isFocusable(textarea, "programmatic")).toBe(true);
    expect(isFocusable(input, "programmatic")).toBe(true);

    button.disabled = true;
    select.disabled = true;
    textarea.disabled = true;
    input.disabled = true;
    expect(isFocusable(button, "tab")).toBe(false);
    expect(isFocusable(select, "tab")).toBe(false);
    expect(isFocusable(textarea, "tab")).toBe(false);
    expect(isFocusable(input, "tab")).toBe(false);
    expect(isFocusable(button, "programmatic")).toBe(false);
    expect(isFocusable(select, "programmatic")).toBe(false);
    expect(isFocusable(textarea, "programmatic")).toBe(false);
    expect(isFocusable(input, "programmatic")).toBe(false);
  });

  it("should never include hidden inputs", () => {
    const hidden = document.createElement("input");
    hidden.type = "hidden";

    expect(isFocusable(hidden, "tab")).toBe(false);
    expect(isFocusable(hidden, "programmatic")).toBe(false);
  });

  it("should allow for elements with a tab index to be focusable", () => {
    const div = document.createElement("div");

    expect(isFocusable(div, "tab")).toBe(false);
    expect(isFocusable(div, "programmatic")).toBe(false);

    div.tabIndex = -1;
    expect(isFocusable(div, "tab")).toBe(false);
    expect(isFocusable(div, "programmatic")).toBe(true);

    div.tabIndex = 0;
    expect(isFocusable(div, "tab")).toBe(true);
    expect(isFocusable(div, "programmatic")).toBe(true);
  });
});

redpajama_set_name: RedPajamaGithub


text:
from neutron.cmd.sanity import checks
from neutron.tests import base
from neutron.tests.functional import base as functional_base

class SanityTestCase(base.BaseTestCase):
    """Sanity checks that do not require root access.

    Tests that just call checks.some_function() are to ensure that
    neutron-sanity-check runs without throwing an exception, as in the case
    where someone modifies the API without updating the check script.
    """

    def test_nova_notify_runs(self):
        checks.nova_notify_supported()

    def test_dnsmasq_version(self):
        checks.dnsmasq_version_supported()

    def test_dibbler_version(self):
        checks.dibbler_version_supported()

    def test_ipset_support(self):
        checks.ipset_supported()

    def test_ip6tables_support(self):
        checks.ip6tables_supported()

class SanityTestCaseRoot(functional_base.BaseSudoTestCase):
    """Sanity checks that require root access.

    Tests that just call checks.some_function() are to ensure that
    neutron-sanity-check runs without throwing an exception, as in the case
    where someone modifies the API without updating the check script.
    """

    def test_ovs_vxlan_support_runs(self):
        checks.ovs_vxlan_supported()

    def test_ovs_geneve_support_runs(self):
        checks.ovs_geneve_supported()

    def test_iproute2_vxlan_support_runs(self):
        checks.iproute2_vxlan_supported()

    def test_ovs_patch_support_runs(self):
        checks.patch_supported()

    def test_arp_responder_runs(self):
        checks.arp_responder_supported()

    def test_arp_header_match_runs(self):
        checks.arp_header_match_supported()

    def test_icmpv6_header_match_runs(self):
        checks.icmpv6_header_match_supported()

    def test_vf_management_runs(self):
        checks.vf_management_supported()

    def test_vf_extended_management_runs(self):
        checks.vf_extended_management_supported()

    def test_namespace_root_read_detection_runs(self):
        checks.netns_read_requires_helper()

    def test_ovsdb_native_supported_runs(self):
        checks.ovsdb_native_supported()

    def test_keepalived_ipv6_support(self):
        checks.keepalived_ipv6_supported()


text:
package classe;

class A {
	int x = 5;

	public A() {
		System.out.println("In A construct");
	}

	public int getX() {
		return x;
	}
}

class B extends A {
	int x = 6;

	public B() {
		System.out.println("In B construct");
	}

	public int getX() {
		return x;
	}
}

public class CovariantTest {
	public A getObject() {
		System.out.println("In CovariantTest.getObject");
		return new A();
	}

	public static void main(String[] args) {
		/**
		 * O código abaixo imprimira 5 por causa do tipo de c1 ser usado da
		 * superclasse. O método executado será da subclasse, porém o tipo do
		 * retorno está no tipo da superclasse.
		 */
		CovariantTest c1 = new SubCovariantTest();
		System.out.println(((A) c1.getObject()).x);
	}
}

class SubCovariantTest extends CovariantTest {
	public B getObject() {
		System.out.println("In SubCovariantTest.getObject");
		return new B();
	}
}


text:
import sys

# Should be in EXACT same order as from mongoc-handshake-private.h.
# The values are implicit (so we assume 1st entry is 1 << 0,
# second entry is 1 << 1 and so on).
MD_FLAGS = [
    "MONGOC_MD_FLAG_ENABLE_CRYPTO",
    "MONGOC_MD_FLAG_ENABLE_CRYPTO_CNG",
    "MONGOC_MD_FLAG_ENABLE_CRYPTO_COMMON_CRYPTO",
    "MONGOC_MD_FLAG_ENABLE_CRYPTO_LIBCRYPTO",
    "MONGOC_MD_FLAG_ENABLE_CRYPTO_SYSTEM_PROFILE",
    "MONGOC_MD_FLAG_ENABLE_SASL",
    "MONGOC_MD_FLAG_ENABLE_SSL",
    "MONGOC_MD_FLAG_ENABLE_SSL_OPENSSL",
    "MONGOC_MD_FLAG_ENABLE_SSL_SECURE_CHANNEL",
    "MONGOC_MD_FLAG_ENABLE_SSL_SECURE_TRANSPORT",
    "MONGOC_MD_FLAG_EXPERIMENTAL_FEATURES",
    "MONGOC_MD_FLAG_HAVE_SASL_CLIENT_DONE",
    "MONGOC_MD_FLAG_HAVE_WEAK_SYMBOLS",
    "MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS",
    "MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL",
    "MONGOC_MD_FLAG_ENABLE_SASL_CYRUS",
    "MONGOC_MD_FLAG_ENABLE_SASL_SSPI",
    "MONGOC_MD_FLAG_HAVE_SOCKLEN",
]

def main():
    flag_to_number = {s: 2 ** i for i,s in enumerate(MD_FLAGS)}

    if len(sys.argv) < 2:
        print "Usage: python {0} config-bitfield".format(sys.argv[0])
        print "Example: python parse_handshake_cfg.py 0x3e65"
        return

    config_bitfield_string = sys.argv[1]
    config_bitfield_num = int(config_bitfield_string, 0)
    print "Decimal value: {}".format(config_bitfield_num)

    for flag, num in flag_to_number.iteritems():
        v = "true" if config_bitfield_num & num else "false"
        print "{:<50}: {}".format(flag, v)

if __name__ == "__main__":
    main()


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'chrome://resources/cr_elements/hidden_style_css.m.js';
import 'chrome://resources/cr_elements/icons.m.js';
import './icons.js';
import './viewer-zoom-button.js';

import {isRTL} from 'chrome://resources/js/util.m.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {FittingType} from '../constants.js';

import {ViewerZoomButtonElement} from './viewer-zoom-button.js';
import {getTemplate} from './viewer-zoom-toolbar.html.js';

const FIT_TO_PAGE_BUTTON_STATE = 0;
const FIT_TO_WIDTH_BUTTON_STATE = 1;

export interface ViewerZoomToolbarElement {
  $: {
    fitButton: ViewerZoomButtonElement,
  };
}

export class ViewerZoomToolbarElement extends PolymerElement {
  static get is() {
    return 'viewer-zoom-toolbar';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      keyboardNavigationActive_: {
        type: Boolean,
        value: false,
      },

      visible_: {
        type: Boolean,
        reflectToAttribute: true,
      },
    };
  }

  private keyboardNavigationActive_: boolean;
  private visible_: boolean;

  override ready() {
    super.ready();
    this.addEventListener('focus', this.onFocus_);
    this.addEventListener('keyup', this.onKeyUp_);
    this.addEventListener('pointerdown', this.onPointerDown_);
  }

  private fire_(eventName: string, detail?: any): void {
    this.dispatchEvent(
        new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
  }

  isVisible(): boolean {
    return this.visible_;
  }

  private onFocus_(): void {
    if (this.visible_) {
      return;
    }

    // For Print Preview, ensure the parent element knows that keyboard
    // navigation is now active and show the toolbar.
    this.fire_('keyboard-navigation-active', true);
    this.show();
  }

  private onKeyUp_(): void {
    this.fire_('keyboard-navigation-active', true);
    this.keyboardNavigationActive_ = true;
  }

  private onPointerDown_(): void {
    this.fire_('keyboard-navigation-active', false);
    this.keyboardNavigationActive_ = false;
  }

  /** Handle clicks of the fit-button. */
  fitToggle() {
    this.fireFitToChangedEvent_(
        this.$.fitButton.activeIndex === FIT_TO_WIDTH_BUTTON_STATE ?
            FittingType.FIT_TO_WIDTH :
            FittingType.FIT_TO_PAGE);
  }

  /** Handle the keyboard shortcut equivalent of fit-button clicks. */
  fitToggleFromHotKey() {
    this.fitToggle();

    // Toggle the button state since there was no mouse click.
    const button = this.$.fitButton;
    button.activeIndex =
        (button.activeIndex === FIT_TO_WIDTH_BUTTON_STATE ?
             FIT_TO_PAGE_BUTTON_STATE :
             FIT_TO_WIDTH_BUTTON_STATE);
  }

  /**
   * Handle forcing zoom via scripting to a fitting type.
   * @param fittingType Page fitting type to force.
   */
  forceFit(fittingType: FittingType) {
    // Set the button state since there was no mouse click.
    const nextButtonState =
        (fittingType === FittingType.FIT_TO_WIDTH ? FIT_TO_PAGE_BUTTON_STATE :
                                                    FIT_TO_WIDTH_BUTTON_STATE);
    this.$.fitButton.activeIndex = nextButtonState;
  }

  /**
   * Fire a 'fit-to-changed' {CustomEvent} with the given FittingType as detail.
   * @param fittingType to include as payload.
   */
  private fireFitToChangedEvent_(fittingType: FittingType) {
    this.fire_('fit-to-changed', fittingType);
  }

  /** Handle clicks of the zoom-in-button. */
  zoomIn() {
    this.fire_('zoom-in');
  }

  /** Handle clicks of the zoom-out-button. */
  zoomOut() {
    this.fire_('zoom-out');
  }

  show() {
    this.visible_ = true;
  }

  hide() {
    this.visible_ = false;
  }

  /**
   * Offsets the toolbar position so that it doesn't move if scrollbars appear.
   */
  shiftForScrollbars(
      hasScrollbars: {horizontal: boolean, vertical: boolean},
      scrollbarWidth: number) {
    const verticalScrollbarWidth = hasScrollbars.vertical ? scrollbarWidth : 0;
    const horizontalScrollbarWidth =
        hasScrollbars.horizontal ? scrollbarWidth : 0;

    // Shift the zoom toolbar to the left by half a scrollbar width. This
    // gives a compromise: if there is no scrollbar visible then the toolbar
    // will be half a scrollbar width further left than the spec but if there
    // is a scrollbar visible it will be half a scrollbar width further right
    // than the spec. In RTL layout normally, the zoom toolbar is on the left
    // left side, but the scrollbar is still on the right, so this is not
    // necessary.
    if (!isRTL()) {
      this.style.right = -verticalScrollbarWidth + (scrollbarWidth / 2) + 'px';
    }
    // Having a horizontal scrollbar is much rarer so we don't offset the
    // toolbar from the bottom any more than what the spec says. This means
    // that when there is a scrollbar visible, it will be a full scrollbar
    // width closer to the bottom of the screen than usual, but this is ok.
    this.style.bottom = -horizontalScrollbarWidth + 'px';
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'viewer-zoom-toolbar': ViewerZoomToolbarElement;
  }
}

customElements.define(ViewerZoomToolbarElement.is, ViewerZoomToolbarElement);


text:
using namespace cv;

void BlurSuperFastCorreceted2(Mat& imgSource, Mat& imgResult);
void BlurSuperFastCorreceted(Mat& imgSource, Mat& imgResult);
void BlurSuperFast(Mat& imgSource, Mat& imgResult);
void BlurFast( Mat& src,  Mat& dst);
void blurWiktor(Mat& imgSource, Mat& imgResult);
void blurTwoPass(Mat& imgSource, Mat& imgResult);
void blur(Mat& imgSource, Mat& imgResult);

#endif


text:
"""
peer.py

Created by Thomas Mangin on 2009-08-25.
Copyright (c) 2009-2013 Exa Networks. All rights reserved.
"""

import time
#import traceback

from exabgp.bgp.timer import Timer
from exabgp.bgp.message import Message
from exabgp.bgp.message.open.capability.id import CapabilityID,REFRESH
from exabgp.bgp.message.nop import NOP
from exabgp.bgp.message.update import Update
from exabgp.bgp.message.refresh import RouteRefresh
from exabgp.bgp.message.notification import Notification, Notify
from exabgp.reactor.protocol import Protocol
from exabgp.reactor.network.error import NetworkError
from exabgp.reactor.api.processes import ProcessError

from exabgp.rib.change import Change

from exabgp.configuration.environment import environment
from exabgp.logger import Logger,FakeLogger,LazyFormat

from exabgp.util.counter import Counter
from exabgp.util.trace import trace

from exabgp.util.enumeration import Enumeration

STATE = Enumeration (
	'idle',
	'active',
	'connect',
	'opensent',
	'openconfirm',
	'established',
)

ACTION = Enumeration (
	'close',
	'later',
	'immediate',
	)

SEND = Enumeration (
	'done',
	'normal',
	'refresh',
)

# As we can not know if this is our first start or not, this flag is used to
# always make the program act like it was recovering from a failure
# If set to FALSE, no EOR and OPEN Flags set for Restart will be set in the
# OPEN Graceful Restart Capability
FORCE_GRACEFUL = True

class Interrupted (Exception): pass

# Present a File like interface to socket.socket

class Peer (object):
	def __init__ (self,neighbor,reactor):
		try:
			self.logger = Logger()
			# We only to try to connect via TCP once
			self.once = environment.settings().tcp.once
			self.bind = True if environment.settings().tcp.bind else False
		except RuntimeError:
			self.logger = FakeLogger()
			self.once = True

		self.reactor = reactor
		self.neighbor = neighbor
		# The next restart neighbor definition
		self._neighbor = None

		# The peer should restart after a stop
		self._restart = True
		# The peer was restarted (to know what kind of open to send for graceful restart)
		self._restarted = FORCE_GRACEFUL
		self._reset_skip()

		# We want to send all the known routes
		self._resend_routes = SEND.done
		# We have new routes for the peers
		self._have_routes = True

		# We have been asked to teardown the session with this code
		self._teardown = None

		self._ = {'in':{},'out':{}}

		self._['in']['state'] = STATE.idle
		self._['out']['state'] = STATE.idle

		# value to reset 'generator' to
		self._['in']['enabled'] = False
		self._['out']['enabled'] = None if not self.neighbor.passive else False

		# the networking code
		self._['out']['proto'] = None
		self._['in']['proto'] = None

		# the networking code
		self._['out']['code'] = self._connect
		self._['in']['code'] = self._accept

		# the generator used by the main code
		# * False, the generator for this direction is down
		# * Generator, the code to run to connect or accept the connection
		# * None, the generator must be re-created
		self._['in']['generator'] = self._['in']['enabled']
		self._['out']['generator'] = self._['out']['enabled']

	def _reset (self,direction,message='',error=''):
		self._[direction]['state'] = STATE.idle

		if self._restart:
			if self._[direction]['proto']:
				self._[direction]['proto'].close('%s loop reset %s %s' % (direction,message,str(error)))
			self._[direction]['proto'] = None
			self._[direction]['generator'] = self._[direction]['enabled']
			self._teardown = None
			self._more_skip(direction)
			self.neighbor.rib.reset()

			# If we are restarting, and the neighbor definition is different, update the neighbor
			if self._neighbor:
				self.neighbor = self._neighbor
				self._neighbor = None
		else:
			self._[direction]['generator'] = False
			self._[direction]['proto'] = None

	def _stop (self,direction,message):
		self._[direction]['generator'] = False
		self._[direction]['proto'].close('%s loop stop %s' % (direction,message))
		self._[direction]['proto'] = None

	# connection delay

	def _reset_skip (self):
		# We are currently not skipping connection attempts
		self._skip_time = time.time()
		# when we can not connect to a peer how many time (in loop) should we back-off
		self._next_skip = 0

	def _more_skip (self,direction):
		if direction != 'out':
			return
		self._skip_time = time.time() + self._next_skip
		self._next_skip = int(1+ self._next_skip*1.2)
		if self._next_skip > 60:
			self._next_skip = 60

	# logging

	def me (self,message):
		return "peer %s ASN %-7s %s" % (self.neighbor.peer_address,self.neighbor.peer_as,message)

	def _output (self,direction,message):
		return "%s %s" % (self._[direction]['proto'].connection.name(),self.me(message))

	def _log (self,direction):
		def inner (message):
			return self._output(direction,message)
		return inner

	# control

	def stop (self):
		self._teardown = 3
		self._restart = False
		self._restarted = False
		self._reset_skip()

	def resend (self):
		self._resend_routes = SEND.normal
		self._reset_skip()

	def send_new (self,changes=None,update=None):
		if changes:
			self.neighbor.rib.outgoing.update(changes)
		self._have_routes = self.neighbor.flush if update is None else update

	def restart (self,restart_neighbor=None):
		# we want to tear down the session and re-establish it
		self._teardown = 3
		self._restart = True
		self._restarted = True
		self._resend_routes = SEND.normal
		self._neighbor = restart_neighbor
		self._reset_skip()

	def teardown (self,code,restart=True):
		self._restart = restart
		self._teardown = code
		self._reset_skip()

	# sockets we must monitor

	def sockets (self):
		ios = []
		for direction in ['in','out']:
			proto = self._[direction]['proto']
			if proto and proto.connection and proto.connection.io:
				ios.append(proto.connection.io)
		return ios

	def incoming (self,connection):
		# if the other side fails, we go back to idle
		if self._['in']['proto'] not in (True,False,None):
			self.logger.network('we already have a peer at this address')
			return False

		self._['in']['proto'] = Protocol(self).accept(connection)
		# Let's make sure we do some work with this connection
		self._['in']['generator'] = None
		self._['in']['state'] = STATE.connect
		return True

	def _accept (self):
		# we can do this as Protocol is a mutable object
		proto = self._['in']['proto']

		# send OPEN
		for message in proto.new_open(self._restarted):
			if ord(message.TYPE) == Message.Type.NOP:
				yield ACTION.immediate

		proto.negotiated.sent(message)

		self._['in']['state'] = STATE.opensent

		# Read OPEN
		wait = environment.settings().bgp.openwait
		opentimer = Timer(self._log('in'),wait,1,1,'waited for open too long, we do not like stuck in active')
		# Only yield if we have not the open, otherwise the reactor can run the other connection
		# which would be bad as we need to do the collission check without going to the other peer
		for message in proto.read_open(self.neighbor.peer_address.ip):
			opentimer.tick(message)
			if ord(message.TYPE) == Message.Type.NOP:
				yield ACTION.later

		self._['in']['state'] = STATE.openconfirm
		proto.negotiated.received(message)
		proto.validate_open()

		if self._['out']['state'] == STATE.openconfirm:
			self.logger.network('incoming connection finds the outgoing connection is in openconfirm')
			local_id = self.neighbor.router_id.packed
			remote_id = proto.negotiated.received_open.router_id.packed

			if local_id < remote_id:
				self.logger.network('closing the outgoing connection')
				self._stop('out','collision local id < remote id')
				yield ACTION.later
			else:
				self.logger.network('aborting the incoming connection')
				stop = Interrupted()
				stop.direction = 'in'
				raise stop

		# Send KEEPALIVE
		for message in self._['in']['proto'].new_keepalive('OPENCONFIRM'):
			yield ACTION.immediate

		# Start keeping keepalive timer
		self.timer = Timer(self._log('in'),proto.negotiated.holdtime,4,0)
		# Read KEEPALIVE
		for message in proto.read_keepalive('ESTABLISHED'):
			self.timer.tick(message)
			yield ACTION.later

		self._['in']['state'] = STATE.established
		# let the caller know that we were sucesfull
		yield ACTION.immediate

	def _connect (self):
		# try to establish the outgoing connection

		proto = Protocol(self)
		generator = proto.connect()

		connected = False
		try:
			while not connected:
				connected = generator.next()
				# we want to come back as soon as possible
				yield ACTION.immediate
		except StopIteration:
			# Connection failed
			if not connected:
				proto.close('connection to peer failed')
			# A connection arrived before we could establish !
			if not connected or self._['in']['proto']:
				stop = Interrupted()
				stop.direction = 'out'
				raise stop

		self._['out']['state'] = STATE.connect
		self._['out']['proto'] = proto

		# send OPEN
		# Only yield if we have not the open, otherwise the reactor can run the other connection
		# which would be bad as we need to set the state without going to the other peer
		for message in proto.new_open(self._restarted):
			if ord(message.TYPE) == Message.Type.NOP:
				yield ACTION.immediate

		proto.negotiated.sent(message)

		self._['out']['state'] = STATE.opensent

		# Read OPEN
		wait = environment.settings().bgp.openwait
		opentimer = Timer(self._log('out'),wait,1,1,'waited for open too long, we do not like stuck in active')
		for message in self._['out']['proto'].read_open(self.neighbor.peer_address.ip):
			opentimer.tick(message)
			# XXX: FIXME: change the whole code to use the ord and not the chr version
			# Only yield if we have not the open, otherwise the reactor can run the other connection
			# which would be bad as we need to do the collission check
			if ord(message.TYPE) == Message.Type.NOP:
				yield ACTION.later

		self._['out']['state'] = STATE.openconfirm
		proto.negotiated.received(message)
		proto.validate_open()

		if self._['in']['state'] == STATE.openconfirm:
			self.logger.network('outgoing connection finds the incoming connection is in openconfirm')
			local_id = self.neighbor.router_id.packed
			remote_id = proto.negotiated.received_open.router_id.packed

			if local_id < remote_id:
				self.logger.network('aborting the outgoing connection')
				stop = Interrupted()
				stop.direction = 'out'
				raise stop
			else:
				self.logger.network('closing the incoming connection')
				self._stop('in','collision local id < remote id')
				yield ACTION.later

		# Send KEEPALIVE
		for message in proto.new_keepalive('OPENCONFIRM'):
			yield ACTION.immediate

		# Start keeping keepalive timer
		self.timer = Timer(self._log('out'),self._['out']['proto'].negotiated.holdtime,4,0)
		# Read KEEPALIVE
		for message in self._['out']['proto'].read_keepalive('ESTABLISHED'):
			self.timer.tick(message)
			yield ACTION.immediate

		self._['out']['state'] = STATE.established
		# let the caller know that we were sucesfull
		yield ACTION.immediate

	def _main (self,direction):
		"yield True if we want to come back to it asap, None if nothing urgent, and False if stopped"

		if self._teardown:
			raise Notify(6,3)

		proto = self._[direction]['proto']

		# Announce to the process BGP is up
		self.logger.network('Connected to peer %s (%s)' % (self.neighbor.name(),direction))
		if self.neighbor.api.neighbor_changes:
			try:
				self.reactor.processes.up(self.neighbor.peer_address)
			except ProcessError:
				# Can not find any better error code than 6,0 !
				# XXX: We can not restart the program so this will come back again and again - FIX
				# XXX: In the main loop we do exit on this kind of error
				raise Notify(6,0,'ExaBGP Internal error, sorry.')

		send_eor = True
		new_routes = None
		self._resend_routes = SEND.normal
		send_families = []

		# Every last asm message should be re-announced on restart
		for family in self.neighbor.asm:
			if family in self.neighbor.families():
				self.neighbor.messages.appendleft(self.neighbor.asm[family])

		counter = Counter(self.logger,self._log(direction))
		need_keepalive = False
		keepalive = None
		operational = None
		refresh = None

		while not self._teardown:
			for message in proto.read_message():
				# Update timer
				self.timer.tick(message)

				# Give information on the number of routes seen
				counter.display()

				# Received update
				if message.TYPE == Update.TYPE:
					counter.increment(len(message.nlris))

					for nlri in message.nlris:
						self.neighbor.rib.incoming.insert_received(Change(nlri,message.attributes))
						self.logger.routes(LazyFormat(self.me(''),str,nlri))
				elif message.TYPE == RouteRefresh.TYPE:
					if message.reserved == RouteRefresh.request:
						self._resend_routes = SEND.refresh
						send_families.append((message.afi,message.safi))

				# SEND KEEPALIVES
				need_keepalive |= self.timer.keepalive()

				if need_keepalive and not keepalive:
					keepalive = proto.new_keepalive()
					need_keepalive = False

				if keepalive:
					try:
						keepalive.next()
					except StopIteration:
						keepalive = None

				# SEND OPERATIONAL
				if self.neighbor.operational:
					if not operational:
						new_operational = self.neighbor.messages.popleft() if self.neighbor.messages else None
						if new_operational:
							operational = proto.new_operational(new_operational,proto.negotiated)

					if operational:
						try:
							operational.next()
						except StopIteration:
							operational = None

				# SEND REFRESH
				if self.neighbor.route_refresh:
					if not refresh:
						new_refresh = self.neighbor.refresh.popleft() if self.neighbor.refresh else None
						if new_refresh:
							enhanced_negotiated = True if proto.negotiated.refresh == REFRESH.enhanced else False
							refresh = proto.new_refresh(new_refresh,enhanced_negotiated)

					if refresh:
						try:
							refresh.next()
						except StopIteration:
							refresh = None

				# Take the routes already sent to that peer and resend them
				if self._resend_routes != SEND.done:
					enhanced_refresh = True if self._resend_routes == SEND.refresh and proto.negotiated.refresh == REFRESH.enhanced else False
					self._resend_routes = SEND.done
					self.neighbor.rib.outgoing.resend(send_families,enhanced_refresh)
					self._have_routes = True
					send_families = []

				# Need to send update
				if self._have_routes and not new_routes:
					self._have_routes = False
					# XXX: in proto really. hum to think about ?
					new_routes = proto.new_update()

				if new_routes:
					try:
						count = 20
						while count:
							# This can raise a NetworkError
							new_routes.next()
							count -= 1
					except StopIteration:
						new_routes = None

				elif send_eor:
					send_eor = False
					for eor in proto.new_eors():
						yield ACTION.immediate
					self.logger.message(self.me('>> EOR(s)'))

				# Go to other Peers
				yield ACTION.immediate if new_routes or message.TYPE != NOP.TYPE or self.neighbor.messages else ACTION.later

				# read_message will loop until new message arrives with NOP
				if self._teardown:
					break

		# If graceful restart, silent shutdown
		if self.neighbor.graceful_restart and proto.negotiated.sent_open.capabilities.announced(CapabilityID.GRACEFUL_RESTART):
			self.logger.network('Closing the session without notification','error')
			proto.close('graceful restarted negotiated, closing without sending any notification')
			raise NetworkError('closing')

		# notify our peer of the shutdown
		raise Notify(6,self._teardown)

	def _run (self,direction):
		"yield True if we want the reactor to give us back the hand with the same peer loop, None if we do not have any more work to do"
		try:
			for action in self._[direction]['code']():
				yield action

			for action in self._main(direction):
				yield action

		# CONNECTION FAILURE
		except NetworkError, e:
			self._reset(direction,'closing connection')

			# we tried to connect once, it failed, we stop
			if self.once:
				self.logger.network('only one attempt to connect is allowed, stoping the peer')
				self.stop()
			return

		# NOTIFY THE PEER OF AN ERROR
		except Notify, n:
			for direction in ['in','out']:
				if self._[direction]['proto']:
					try:
						generator = self._[direction]['proto'].new_notification(n)
						try:
							maximum = 20
							while maximum:
								generator.next()
								maximum -= 1
								yield ACTION.immediate if maximum > 10 else ACTION.later
						except StopIteration:
							pass
					except (NetworkError,ProcessError):
						self.logger.network(self._output(direction,'NOTIFICATION NOT SENT'),'error')
						pass
					self._reset(direction,'notification sent (%d,%d)' % (n.code,n.subcode),n)
				else:
					self._reset(direction)
			return

		# THE PEER NOTIFIED US OF AN ERROR
		except Notification, n:
			self._reset(direction,'notification received (%d,%d)' % (n.code,n.subcode),n)
			return

		# RECEIVED a Message TYPE we did not expect
		except Message, m:
			self._reset(direction,'unexpected message received',m)
			return

		# PROBLEM WRITING TO OUR FORKED PROCESSES
		except ProcessError, e:
			self._reset(direction,'process problem',e)
			return

		# ....
		except Interrupted, i:
			self._reset(i.direction)
			return

		# UNHANDLED PROBLEMS
		except Exception, e:
			# Those messages can not be filtered in purpose
			self.logger.error(self.me('UNHANDLED PROBLEM, please report'),'reactor')
			self.logger.error(self.me(str(type(e))),'reactor')
			self.logger.error(self.me(str(e)),'reactor')
			self.logger.error(trace())

			self._reset(direction)
			return
	# loop

	def run (self):
		#if self.reactor.processes.broken(self.neighbor.peer_address):
			# XXX: we should perhaps try to restart the process ??
			#self.logger.processes('ExaBGP lost the helper process for this peer - stopping','error')
			#self.stop()
			#return True

		back = ACTION.later if self._restart else ACTION.close

		for direction in ['in','out']:
			opposite = 'out' if direction == 'in' else 'in'

			generator = self._[direction]['generator']
			if generator:
				try:
					# This generator only stops when it raises
					r = generator.next()

					if r is ACTION.immediate: status = 'immediate callback'
					elif r is ACTION.later:   status = 'when possible'
					elif r is ACTION.close:   status = 'stop'
					else: status = 'buggy'
					self.logger.network('%s loop %18s, state is %s' % (direction,status,self._[direction]['state']),'debug')

					if r == ACTION.immediate:
						back = ACTION.immediate
					elif r == ACTION.later:
						back == ACTION.later if back != ACTION.immediate else ACTION.immediate
				except StopIteration:
					# Trying to run a closed loop, no point continuing
					self._[direction]['generator'] = self._[direction]['enabled']

			elif generator is None:
				if self._[opposite]['state'] in [STATE.openconfirm,STATE.established]:
					self.logger.network('%s loop, stopping, other one is established' % direction,'debug')
					self._[direction]['generator'] = False
					continue
				if direction == 'out' and self._skip_time > time.time():
					self.logger.network('%s loop, skipping, not time yet' % direction,'debug')
					back = ACTION.later
					continue
				if self._restart:
					self.logger.network('%s loop, intialising' % direction,'debug')
					self._[direction]['generator'] = self._run(direction)
					back = ACTION.immediate

		return back


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Using as: Gnu_attribute</title>

<meta name="description" content="Using as: Gnu_attribute">
<meta name="keywords" content="Using as: Gnu_attribute">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Pseudo-Ops.html#Pseudo-Ops" rel="up" title="Pseudo Ops">
<link href="Hidden.html#Hidden" rel="next" title="Hidden">
<link href="Global.html#Global" rel="prev" title="Global">

Next: Hidden, Previous: Global, Up: Pseudo Ops   [Contents][Index]

7.58 .gnu_attribute <var>tag</var>,<var>value</var>

Record a GNU object attribute for this file.  See Object Attributes.


text:
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HttpClientModule } from '@angular/common/http';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { MoviesPage } from '../pages/movies/movies';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    MoviesPage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp, {
      pageTransition: "md-transition"
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    MoviesPage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    HttpClientModule,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


text:
export var ClickMode;
(function (ClickMode) {
    ClickMode["bubble"] = "bubble";
    ClickMode["push"] = "push";
    ClickMode["remove"] = "remove";
    ClickMode["repulse"] = "repulse";
})(ClickMode || (ClickMode = {}));


text:
package org.dasein.persist;

import java.io.PrintWriter;

public interface ExportHook<T> {
    public boolean prepareExport(PrintWriter output, T item) throws PersistenceException;
}


text:
namespace ash {
namespace holding_space_util {

gfx::Size GetMaxImageSizeForType(HoldingSpaceItem::Type type) {
  gfx::Size max_size;
  switch (type) {
    case HoldingSpaceItem::Type::kArcDownload:
    case HoldingSpaceItem::Type::kDiagnosticsLog:
    case HoldingSpaceItem::Type::kDownload:
    case HoldingSpaceItem::Type::kLacrosDownload:
    case HoldingSpaceItem::Type::kNearbyShare:
    case HoldingSpaceItem::Type::kPinnedFile:
    case HoldingSpaceItem::Type::kPrintedPdf:
    case HoldingSpaceItem::Type::kScan:
    case HoldingSpaceItem::Type::kPhoneHubCameraRoll:
      max_size =
          gfx::Size(kHoldingSpaceChipIconSize, kHoldingSpaceChipIconSize);
      break;
    case HoldingSpaceItem::Type::kScreenRecording:
    case HoldingSpaceItem::Type::kScreenshot:
      max_size = kHoldingSpaceScreenCaptureSize;
      break;
  }
  // To avoid pixelation, ensure that the holding space image size is at least
  // as large as the default tray icon preview size. The image will be scaled
  // down elsewhere if needed.
  max_size.SetToMax(gfx::Size(kHoldingSpaceTrayIconDefaultPreviewSize,
                              kHoldingSpaceTrayIconDefaultPreviewSize));
  return max_size;
}

}  // namespace holding_space_util
}  // namespace ash


text:
package org.hibernate.test.annotations.cid;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * @author Emmanuel Bernard
 */
@Entity
public class Product {
	@Id
    public String name;
}


text:
package iso20022

// Card payment transaction choice between cancellation, authorisation request and authorisation response.
type CardPaymentDataSetTransaction3Choice struct {

	// Completed card payment transaction to be captured.
	Completion *CardPaymentDataSetTransaction10 `xml:"Cmpltn"`

	// Cancelled card payment transaction to be captured.
	Cancellation *CardPaymentDataSetTransaction11 `xml:"Cxl"`

	// Card payment transaction including an authorisation request.
	AuthorisationRequest *CardPaymentDataSetTransaction12 `xml:"AuthstnReq"`

	// Card payment transaction including an authorisation response.
	AuthorisationResponse *CardPaymentDataSetTransaction13 `xml:"AuthstnRspn"`
}

func (c *CardPaymentDataSetTransaction3Choice) AddCompletion() *CardPaymentDataSetTransaction10 {
	c.Completion = new(CardPaymentDataSetTransaction10)
	return c.Completion
}

func (c *CardPaymentDataSetTransaction3Choice) AddCancellation() *CardPaymentDataSetTransaction11 {
	c.Cancellation = new(CardPaymentDataSetTransaction11)
	return c.Cancellation
}

func (c *CardPaymentDataSetTransaction3Choice) AddAuthorisationRequest() *CardPaymentDataSetTransaction12 {
	c.AuthorisationRequest = new(CardPaymentDataSetTransaction12)
	return c.AuthorisationRequest
}

func (c *CardPaymentDataSetTransaction3Choice) AddAuthorisationResponse() *CardPaymentDataSetTransaction13 {
	c.AuthorisationResponse = new(CardPaymentDataSetTransaction13)
	return c.AuthorisationResponse
}


text:
author: slowe
categories: Information
comments: false
date: 2005-08-13T22:16:18Z
slug: technical-document-posted
tags:
- Interoperability
- ActiveDirectory
- Linux
title: Technical Document Posted
url: /2005/08/13/technical-document-posted/
wordpress_id: 75
---

I posted a write-up of my Active Directory-Linux integration as a technical document on the [Mercurion Systems](http://www.mercurionsystems.com/) web site. You can find the document in the [Downloads](http://www.mercurionsystems.com/downloads/index.html) area. I hope it proves useful to someone.


text:
package com.gilpereda.streethistory;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.postgis.PGgeometry;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.gilpereda.streethistory.domain.Photo;
import com.gilpereda.streethistory.service.PhotoService;

/**
 * @author "Javier Gil Pereda"
 *
 */
public class TestGIS {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		ctx.load("classpath:it-app-context.xml");
		ctx.refresh();

		DataSource dataSource = ctx.getBean("dataSource", DataSource.class);
		Connection conn = dataSource.getConnection();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select location from photo");
		while (rs.next()) {
			PGgeometry geom = (PGgeometry)rs.getObject(1);
			System.out.println(geom.toString());
		}

		PhotoService photoService = ctx.getBean("photoService", PhotoService.class);
		List<Photo> photos = photoService.findAll();
		for (Photo photo: photos) {
			System.out.println(photo);
		}

	}

}


text:
package com.navercorp.pinpoint.plugin.mongo;

import com.mongodb.WriteConcern;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.common.util.StringStringValue;
import org.bson.BsonType;

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

/**
 * @author Roy Kim
 */
public final class MongoUtil {

    public static final String SEPARATOR = ",";
    private static final MongoWriteConcernMapper mongoWriteConcernMapper = new MongoWriteConcernMapper();

    private static final boolean decimal128Enabled = decimal128Enabled();

    private MongoUtil() {
    }

    //since Mongo Java Driver 3.4
    private static boolean decimal128Enabled() {
        for (BsonType bsonType : BsonType.values()) {
            if (bsonType.name().equalsIgnoreCase("DECIMAL128")) {
                return true;
            }
        }
        return false;
    }

    public static void recordMongoCollection(SpanEventRecorder recorder, String collectionName, String readPreferenceOrWriteConcern) {
        recorder.recordAttribute(MongoConstants.MONGO_COLLECTION_INFO, collectionName);
        recorder.recordAttribute(MongoConstants.MONGO_COLLECTION_OPTION, readPreferenceOrWriteConcern);
    }

    public static String getWriteConcern0(WriteConcern writeConcern) {

        return mongoWriteConcernMapper.getName(writeConcern);
    }

    public static void recordParsedBson(SpanEventRecorder recorder, NormalizedBson normalizedBson) {
        if (normalizedBson != null) {
            StringStringValue stringStringValue = new StringStringValue(normalizedBson.getNormalizedBson(), normalizedBson.getParameter());
            recorder.recordAttribute(MongoConstants.MONGO_JSON_DATA, stringStringValue);
        }
    }

    public static NormalizedBson parseBson(Object[] args, boolean traceBsonBindValue) {

        if (args == null) {
            return null;
        }

        final List<String> parsedJson = new ArrayList<String>(2);
        final List<String> jsonParameter = new ArrayList<String>(16);

        for (Object arg : args) {

            WriteContext writeContext = new WriteContext(jsonParameter, decimal128Enabled, traceBsonBindValue);

            String documentString = writeContext.parse(arg);

            if(!documentString.equals(WriteContext.UNTRACED)) {
                parsedJson.add(documentString);
            }
        }

        String parsedJsonString = StringJoiner.join(parsedJson, SEPARATOR);
        String jsonParameterString = StringJoiner.join(jsonParameter, SEPARATOR);
        return new NormalizedBson(parsedJsonString, jsonParameterString);
    }
}


text:
<?php
namespace golib\Types;

/**
 * Description of PropIgnoreCase
 *
 * @author tziegler
 *
 * properties that ignores case sesnitive keys
 * to solve renaming issues
 */
class PropIgnoreCase extends Props{

    public function __construct($data = NULL) {

        foreach ($this as $key => $dummy){
            $this->findMatch($key, $data);
        }

        parent::__construct($data);
    }

    private function findMatch($origin ,array &$data){
        $lower = strtolower($origin);
        foreach ($data as $key => $value){
            if ($lower == strtolower($key)){
                unset($data[$key]);
                $data[$origin] = $value;
            }
        }
    }
}


text:
var navigationbar = createView.childView["navigationbar"];
var selectedCategory = navigationbar._subViews[0];
utils.generateChildViews(selectedCategory)

// Hide all categories icon in navigationbar
for (var i in selectedCategory.childView) {
	selectedCategory.childView[i].visible = false;
}

// Generate content subviews
var createContentView = createView.childView["content"];
utils.generateChildViews(createContentView);

// Create inputs for name and description fields
createContentView.childView["name"].html = '<input type="text" class="field" placeholder="Nombre del plan">';
createContentView.childView["description"].html = '<input type="text" class="field" placeholder="Descripción">';

// Category colors
var categoryColors  = {
	pubs: "#f1b71a",
	concert: "#df4985",
	party: "#15c7ac",
	sport: "#4bc533",
	restaurant: "#e65647",
	cinema: "#6250cd",
	travel: "#8bc820",
	cultural: "#a856f5",
	meeting: "#9b8258",
	birthday: "#469fe4",
	dating:"#f556b4",
	other: "#fca829"
}

// Show create view function
var showCreateView = function(category) {

	// Set navigationBar color & icon from category
	navigationbar.style.backgroundColor = categoryColors[category];
	selectedCategory.childView["selected-"+category].visible = true;

	// Hide homeView
	shadowHome.visible = true;
	shadowHome.opacity = 0;
	shadowHome.animate({
		properties: {
			opacity: 1
		},
		curve: "ease-out",
		time: 150
	});
	homeView.animate({
		origin: "50% 0%",
		properties: {
			scale: 0.9,
			y: -100
		},
		curve: "ease-out",
		time: 100
	});

	// Show createView
	utils.delay(50, function() {
		categoryItem.name
		createView.visible = true;
		createView.opacity = 0;
		createView.scale = 0.8;
		createView.y = 300;
		createView.animate({
			origin: "50% 0%",
			properties: {
				opacity: 1,
				scale: 1,
				y: 0
			},
			curve: "spring(200, 20, 500)",
		});
	});
}