text:
///////////////////////////////////////////////////////////////////////////////
// Name:        wx/listbook.h
// Purpose:     wxListbook: wxListCtrl and wxNotebook combination
// Author:      Vadim Zeitlin
// Modified by:
// Created:     19.08.03
// Copyright:   (c) 2003 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

#ifndef _WX_LISTBOOK_H_
#define _WX_LISTBOOK_H_

#include "wx/defs.h"

#if wxUSE_LISTBOOK

#include "wx/bookctrl.h"
#include "wx/containr.h"

class WXDLLIMPEXP_FWD_CORE wxListView;
class WXDLLIMPEXP_FWD_CORE wxListEvent;

class wxBookCtrlEvent {};

wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_LISTBOOK_PAGE_CHANGED,  wxBookCtrlEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_LISTBOOK_PAGE_CHANGING, wxBookCtrlEvent );

/*
// wxListbook flags
#define wxLB_DEFAULT          wxBK_DEFAULT
#define wxLB_TOP              wxBK_TOP
#define wxLB_BOTTOM           wxBK_BOTTOM
#define wxLB_LEFT             wxBK_LEFT
#define wxLB_RIGHT            wxBK_RIGHT
#define wxLB_ALIGN_MASK       wxBK_ALIGN_MASK
*/

// ----------------------------------------------------------------------------
// wxListbook
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxListbook : public wxControl
{
public:
    wxListbook() { }

    wxListbook(wxWindow *parent,
               wxWindowID id,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxEmptyString)
    {
        (void)Create(parent, id, pos, size, style, name);
    }

    // quasi ctor
    bool Create(wxWindow *parent,
                wxWindowID id,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxString& name = wxEmptyString);

    // overridden base class methods
    virtual bool SetPageText(size_t n, const wxString& strText);
    virtual wxString GetPageText(size_t n) const;
    virtual int GetPageImage(size_t n) const;
    virtual bool SetPageImage(size_t n, int imageId);
    virtual bool InsertPage(size_t n,
                            wxWindow *page,
                            const wxString& text,
                            bool bSelect = false,
                            int imageId = -1);
    virtual int SetSelection(size_t n) { return DoSetSelection(n, SetSelection_SendEvent); }
    virtual int ChangeSelection(size_t n) { return DoSetSelection(n); }
    virtual int HitTest(const wxPoint& pt, long *flags = NULL) const;
    virtual void SetImageList(wxImageList *imageList);

    virtual bool DeleteAllPages();

    wxListView* GetListView() const { return (wxListView*)m_bookctrl; }

protected:
    virtual wxWindow *DoRemovePage(size_t page);

    void UpdateSelectedPage(size_t newsel);

    wxBookCtrlEvent* CreatePageChangingEvent() const;
    void MakeChangedEvent(wxBookCtrlEvent &event);

    // Get the correct wxListCtrl flags to use depending on our own flags.
    long GetListCtrlFlags() const;

    // event handlers
    void OnListSelected(wxListEvent& event);
    void OnSize(wxSizeEvent& event);
};

#endif // wxUSE_LISTBOOK

#endif // _WX_LISTBOOK_H_


text:
package org.ow2.contrail.common.oauth.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONException;
import org.json.JSONObject;
import org.ow2.contrail.common.oauth.client.exceptions.UnauthorizedException;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.net.URI;
import java.security.KeyStore;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CCFlowClient {
    private static Logger log = Logger.getLogger(CCFlowClient.class);
    private URI tokenEndpointUri;
    private String keystoreFile;
    private String keystorePass;
    private String truststoreFile;
    private String truststorePass;
    private String clientId;
    private String clientSecret;

    public CCFlowClient(URI tokenEndpointUri) throws Exception {
        if (tokenEndpointUri.getScheme().equals("https")) {
            throw new Exception("Keystore and truststore are required for https connection.");
        }
        this.tokenEndpointUri = tokenEndpointUri;
    }

    public CCFlowClient(URI tokenEndpointUri,
                        String keystoreFile, String keystorePass,
                        String truststoreFile, String truststorePass) {
        this.tokenEndpointUri = tokenEndpointUri;
        this.keystoreFile = keystoreFile;
        this.keystorePass = keystorePass;
        this.truststoreFile = truststoreFile;
        this.truststorePass = truststorePass;

        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public AccessToken requestAccessToken(String resourceOwner, String scope) throws Exception {

        // prepare post request
        HttpPost httpPost = new HttpPost(tokenEndpointUri);

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("grant_type", "client_credentials"));
        if (resourceOwner != null) {
            formParams.add(new BasicNameValuePair("resource_owner", resourceOwner));
        }
        if (scope != null) {
            formParams.add(new BasicNameValuePair("scope", scope));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
        httpPost.setEntity(entity);

        // set Authorization header
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(clientId, clientSecret);
        httpPost.addHeader(BasicScheme.authenticate(creds, "UTF-8", false));

        HttpClient httpClient;
        if (tokenEndpointUri.getScheme().equals("https")) {
            // read in the keystore from the filesystem, this should contain a single keypair
            KeyStore clientKeyStore = KeyStore.getInstance("JKS");
            clientKeyStore.load(new FileInputStream(keystoreFile), keystorePass.toCharArray());

            // read in the truststore from the filesystem, this should contain a single keypair
            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(new FileInputStream(truststoreFile), truststorePass.toCharArray());

            // set up the socketfactory, to use our keystore for client authentication.
            SSLSocketFactory socketFactory = new SSLSocketFactory(
                    SSLSocketFactory.TLS,
                    clientKeyStore,
                    keystorePass,
                    trustStore,
                    null,
                    null,
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            // create and configure scheme registry
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", tokenEndpointUri.getPort(), socketFactory));

            // create a client connection manager to use in creating httpclients
            ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);

            // create the client based on the manager, and use it to make the call
            httpClient = new DefaultHttpClient(mgr);
        }
        else {
            httpClient = new DefaultHttpClient();
        }

        // send post request to the Authorization Server
        HttpResponse httpResponse = httpClient.execute(httpPost);

        // parse response
        HttpEntity responseEntity = httpResponse.getEntity();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        responseEntity.writeTo(baos);
        String content = baos.toString();

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject json = null;
            try {
                json = new JSONObject(content);
            }
            catch (JSONException e) {
                String message = String.format(
                        "Invalid response received from the Authorization Server: %s", e.getMessage());
                log.error(message + ": " + content, e);
                throw new Exception(message);
            }

            AccessToken accessToken = new AccessToken();
            accessToken.setValue(json.getString("access_token"));
            Date now = new Date();
            int expiresIn = json.getInt("expires_in");
            Date expireTime = new Date(now.getTime() + expiresIn * 1000);
            accessToken.setExpiresIn(expiresIn);
            accessToken.setExpireTime(expireTime);
            log.debug("Access token has been obtained successfully: " + accessToken.toJson());
            return accessToken;
        }
        else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
            JSONObject json = null;
            try {
                json = new JSONObject(content);
            }
            catch (JSONException e) {
                String message = String.format(
                        "Invalid response received from the Authorization Server: %s", e.getMessage());
                log.error(message + ": " + content, e);
                throw new Exception(message);
            }

            String message = "Error response received from the Authorization Server: " + json.getString("error");
            if (json.has("error_description")) {
                message += ": " + json.getString("error_description");
            }
            log.debug(message);
            throw new UnauthorizedException(message);
        }
        else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            String message = "The request for access token has been refused" +
                    ((content != null) ? (": " + content) : ".");
            log.debug(message);
            throw new UnauthorizedException(message);
        }
        else {
            String message = "Unexpected response from the Authorization server: " + httpResponse.getStatusLine();
            log.debug(message + ": " + content);
            throw new Exception(message);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
document.addEventListener('mediascape-ready',function(e){

	var req;
	var value;
	var interval;
	var interval1;
	var timeout;
	var group;
	var url;
	var token;
	var sharedStates={};
	var serverUrl=window.location.host;
	var shakeGo=false;
	var applicationID = "mediascape";
	var map = mediascape.mappingService();

	document.getElementById("nwsCreate").onclick = function(){
		var event = new CustomEvent("createNWS", { "detail": "Generates Named Web Sockets Message." });
		document.dispatchEvent(event);
	};

	document.getElementById("qrCreate").onclick = function(){
		var event = new CustomEvent("createQr", { "detail": "Generates Qr code." });
		document.dispatchEvent(event);
	};

	document.getElementById("miniUrlCreate").onclick = function(){
		var event = new CustomEvent("createMiniUrl", { "detail": "Generates miniUrl." });
		document.dispatchEvent(event);
	};

	document.getElementById("bothCreate").onclick = function(){
		var event = new CustomEvent("createBoth", { "detail": "Generates both elements." });
		document.dispatchEvent(event);
	};

	document.getElementById("fskCreate").onclick = function(){
		var event = new CustomEvent("createFSK", { "detail": "Generates both elements." });
		document.dispatchEvent(event);
	};

	document.getElementById("shakeGoStart").onclick = function(){
		var event = new CustomEvent("startShakeGo", { "detail": "Generates both elements." });
		document.dispatchEvent(event);
	};

	document.getElementById("syncStart").onclick = function(){
		var event = new CustomEvent("startSync", { "detail": "Generates both elements." });
		document.dispatchEvent(event);
	};

	mediascape.discovery.isPresent('namedwebsockets').then(function(data){
		if(data.presence){
			delete value;
			delete interval;
			delete interval1;
			console.log("NamedWebSocket Proxy is active.");
			map.getGroupMapping(applicationID).then(function (data){
				console.log("getGroupMapping");
				group=data.group;
				url="http://"+location.host+location.pathname+"?"+group;
				connectSharedState('app', group);
				mediascape.association.doAssociation("nws","mediascape",url,false);
			});
		}else{
			$("#myModal").modal({
				show: true
			});
			document.getElementById("associationCodes").innerHTML = "";
			document.getElementById("associationCodes").innerHTML = "
It has been impossible to find the NamedWebSocket Proxy.

Remeber that you can associate using On Demand system.
";
			map.getGroupMapping(applicationID).then(function (data){
				console.log("getGroupMapping");
				group=data.group;
				url="http://"+location.host+location.pathname+"?"+group;
				connectSharedState('app', group);
			});
			timeout=setTimeout(function(){
				$("#myModal").modal("hide");
			}, 5000);
		}
	});

	document.addEventListener('createNWS', function(){
		mediascape.discovery.isPresent('namedwebsockets').then(function(data){
			if(data.presence){
				console.log("NamedWebSocket Proxy is active.");
				map.getGroupMapping(applicationID).then(function (data){
					console.log("getGroupMapping");
					group=data.group;
					url="http://"+location.host+location.pathname+"?"+group;
					connectSharedState('app', group);
					mediascape.association.doAssociation("nws","mediascape",url,false);
				});
			}else{
				$("#myModal").modal({
					show: true
				});
				document.getElementById("associationCodes").innerHTML = "";
				document.getElementById("associationCodes").innerHTML = "
It has been impossible to find the NamedWebSocket Proxy.

Remeber that you can associate using On Demand system.
";
				map.getGroupMapping(applicationID).then(function (data){
					console.log("getGroupMapping");
					group=data.group;
					url="http://"+location.host+location.pathname+"?"+group;
					connectSharedState('app', group);
				});
				timeout=setTimeout(function(){
					$("#myModal").modal("hide");
				}, 5000);
			}
		});
	});

	document.addEventListener('stopInterval', function(){
		if(value!==undefined){
			if(value.readyState == 1){
				console.log("Stop Intervals");
				if(interval!=null) clearInterval(interval);
				if(interval1!=null) clearInterval(interval1);
				if(value.id==value.peersIds[0]) value.send(JSON.stringify({"peersIds":value.peersIds}));
				value.close();
				document.getElementById("associationCodes").innerHTML = '';
			}
		}else{
			document.getElementById("associationCodes").className = '';
			document.getElementById("associationCodes").innerHTML = '';
		}
	});

	document.addEventListener('createQr', function(){
		console.log('createQr');
		document.getElementById("associationCodes").innerHTML = "";
		mediascape.association.doAssociation("qr","associationCodes",url,false).then(function(data){
			if(data!=undefined){
				$("#myModal").modal({
					show: true
				});
				visualize("associationCodes",url,"");
			}
		});
	});

	document.addEventListener('createMiniUrl', function(){
		document.getElementById("associationCodes").innerHTML = "";
		mediascape.association.doAssociation("text",url,true).then(function(data){
			if(data!=undefined){
				$("#myModal").modal({
					show: true
				});
				visualize("associationCodes",url, data.response);
			}else console.log("It has not been possible to minimize the url.");
		});
	});

	document.addEventListener('createBoth', function(){
		document.getElementById("associationCodes").innerHTML = "";
		mediascape.association.doAssociation("qr","associationCodes",url,true).then(function(data){
			$("#myModal").modal({
				show: true
			});
			visualize("associationCodes",url,data.response);
		});
	});

	function visualize(place,url,minimized){
		var shortedUrl = url;
		var asociationElement=document.getElementById(place);
		var associationCode = document.createElement("div");
		associationCode.id=place+"code";
		associationCode.appendChild(document.createElement("br"));
		if(minimized!==""){
			var urlElement1 = document.createElement("div");
			urlElement1.id="miniUrl";
			urlElement1.innerHTML=minimized;
			associationCode.appendChild(urlElement1);
			var urlElement3 = document.createElement("br");
			associationCode.appendChild(urlElement3);
		}
		var urlElement2 = document.createElement("div");
		urlElement2.id="url";
		urlElement2.innerHTML=url;
		associationCode.appendChild(urlElement2);
		asociationElement.appendChild(associationCode);
	}

	document.addEventListener('createFSK', function(){
		console.log("createFSK");
		shakeGo=false;
		$("#myModal").modal({
			show: true
		});
		console.log(url);
		document.getElementById("associationCodes").innerHTML = "";
		document.getElementById("associationCodes").innerHTML = "";
		mediascape.association.doAssociation("acoustic",url,true);
	});

	$('#myModal').on('hidden.bs.modal', function () {
		if(req!=undefined ) req.abort();
		if(timeout) clearTimeout(timeout);
		if(document.getElementsByTagName('img').length!=0){
			if(document.getElementsByTagName('img')[0].src.indexOf("icono_play.jpg")!=-1){
				mediascape.association.stopAssociation('acoustic').then(function(data){console.log(data);});
			}else mediascape.association.stopAssociation('');
		}else mediascape.association.stopAssociation('');
	});

	document.addEventListener('ended',function(){
		if(!shakeGo){
			setTimeout(function(){
				$('#myModal').modal('hide');
			},1000);
		}else {
			req = $.post("http://"+serverUrl+"/api/associated",{url:url}, function(data1){
				if(data1)
				{
					if(data1.response.indexOf('http://')!=-1||data1.response.indexOf('https://')!=-1){
						$("#myModal").modal({
							show: true
						});
						associationMessage(2);
						timeout=setTimeout(function(){
							$("#myModal").modal("hide");
						}, 5000);
					} else {
						errorMessage(2);
						timeout = setTimeout(function(){
							associationMessage(1);
							document.getElementById("associationCodes").innerHTML = "";
							mediascape.association.doAssociation("qr","associationCodes",url,true).then(function(data){
								$("#myModal").modal({
									show: true
								});
								visualize("associationCodes",url,data.response);
							});
						},5000);
					}
				}
			});
		}
	});

	document.addEventListener('startSync', function(){
		document.getElementById("associationCodes").innerHTML = "";
		associationMessage(1);
		$("#myModal").modal({
			show: true
		});
		mediascape.association.doAssociation("sync",url).then(function(data){
			if(data){
				if(data.response.indexOf('http://')!=-1||data.response.indexOf('https://')!=-1){
					$("#myModal").modal({
						show: true
					});
					associationMessage(2);
					timeout=setTimeout(function(){
						$("#myModal").modal("hide");
					}, 5000);
				} else {
					errorMessage(data.response);
					timeout = setTimeout(function(){
						$("#myModal").modal("hide");
					}, 5000);
				}
			}
		});
	});

	document.addEventListener('startShakeGo', function(){
		shakeGo=true;
		mediascape.association.on("shakeChange",function(data){
			if(data.response.show===true){
				$("#myModal").modal("show");
				if(data.response.type==="message") associationMessage(data.response.text);
				else if(data.response.type==="errorMessage") errorMessage(data.response.text);
					else errorMessage(data.response.type);
			}else if(data.response.show===false) $("#myModal").modal("hide");
		});
		mediascape.association.doAssociation("shake",url);
	});

	function connectSharedState(type, url) {
		console.log("connectSharedState");
		if (type && url) {
			if(sharedStates[type]==undefined) sharedStates[type] = mediascape.sharedState(url, "'"+token+"'");
			sharedStates[type].on('readystatechange', function (data) {
				if (data === 'open'){
					var keys = sharedStates[type].keys();
					if(keys.length!=0){
						for (var i = 0, len = keys.length; i < len; i++) {
							if(type=='app'){
								console.log(keys[i]);
								if(keys[i]=="users"||keys[i]=="vars"){
									var value;
									var result;
									if(keys[i]=="users") value=userID;
									if(keys[i]=="vars") value="z=3";
									var newValue = sharedStates[type].getItem(keys[i]);
									if(newValue.indexOf(value)==-1) result = newValue.concat([value]);
									else result=newValue;
									console.log(result);
									sharedStates[type].setItem(keys[i], result);
								}
							}else if(type=='user'){
								console.log(keys[i]);
								if(keys[i]=="applications"||keys[i]=="age"||keys[i]=="address"){
									var value;
									var result;
									if(keys[i]=="applications") value=applicationID;
									if(keys[i]=="age") value="24";
									if(keys[i]=="address") value="Heriz 42 1-C";
									var newValue = sharedStates[type].getItem(keys[i]);
									if(newValue.indexOf(value)==-1) result = newValue.concat([value]);
									else result=newValue;
									console.log(result);
									sharedStates[type].setItem(keys[i], result);
								}
							}
						}
					}else{
						console.log("Not Defined");
						if(type=='app'){
							sharedStates[type].setItem('users', [userID]);
							sharedStates[type].setItem('vars', ["x=4"]);
						}
						else if(type=='user'){
							sharedStates[type].setItem('applications', [applicationID]);
							sharedStates[type].setItem('age', ["23"]);
							sharedStates[type].setItem('address', ["Bera-Bera 109 2ºB"]);
						}
					}
				}
			});
		}
	}

	function errorMessage(message){
		console.log('errorMessage');
		document.getElementsByClassName('modal-title')[0].textContent="Association Error";
		document.getElementById("associationCodes").innerHTML = "";
		if(message==1) document.getElementById("associationCodes").innerHTML = "
It has been impossible to Associate.

FSK asssociation is going to start in 5 seconds.
";
		else if(message==2) document.getElementById("associationCodes").innerHTML = "
It has been impossible to Associate.

QR Code is going to appear in 5 seconds.
";
			else if(message==3) document.getElementById("associationCodes").innerHTML = "
It has been impossible to Associate.

QR Code and Audio catchers are going to start in 5 seconds.
";
				else if(message==4) document.getElementById("associationCodes").innerHTML = "
Named Web Socket Proxy has not been started.

Start Named Web Socket Proxy or use other technology.
";
					else document.getElementById("associationCodes").innerHTML = message;
	}
	function associationMessage(message){
		console.log('Message');
		if(message==1){
			document.getElementsByClassName('modal-title')[0].textContent="Associating ...";
			document.getElementById("associationCodes").innerHTML = "";
			document.getElementById("associationCodes").innerHTML = "";
		}else if(message==2){
				document.getElementsByClassName('modal-title')[0].textContent="Associated";
				document.getElementById("associationCodes").innerHTML = "";
				document.getElementById("associationCodes").innerHTML = "
Association process has been completed successfully
";
			}else if(message==3){
				document.getElementsByClassName('modal-title')[0].textContent="Associating ...";
				document.getElementById("associationCodes").innerHTML = "";
				document.getElementById("associationCodes").innerHTML = "";
			}
	}
},false);


text:
package network // import "github.com/docker/docker/daemon/network"

import (
	"net"

	networktypes "github.com/docker/docker/api/types/network"
	clustertypes "github.com/docker/docker/daemon/cluster/provider"
	"github.com/docker/go-connections/nat"
	"github.com/pkg/errors"
)

// Settings stores configuration details about the daemon network config
// TODO Windows. Many of these fields can be factored out.,
type Settings struct {
	Bridge                 string
	SandboxID              string
	HairpinMode            bool
	LinkLocalIPv6Address   string
	LinkLocalIPv6PrefixLen int
	Networks               map[string]*EndpointSettings
	Service                *clustertypes.ServiceConfig
	Ports                  nat.PortMap
	SandboxKey             string
	SecondaryIPAddresses   []networktypes.Address
	SecondaryIPv6Addresses []networktypes.Address
	IsAnonymousEndpoint    bool
	HasSwarmEndpoint       bool
}

// EndpointSettings is a package local wrapper for
// networktypes.EndpointSettings which stores Endpoint state that
// needs to be persisted to disk but not exposed in the api.
type EndpointSettings struct {
	*networktypes.EndpointSettings
	IPAMOperational bool
}

// AttachmentStore stores the load balancer IP address for a network id.
type AttachmentStore struct {
	//key: networkd id
	//value: load balancer ip address
	networkToNodeLBIP map[string]net.IP
}

// ResetAttachments clears any existing load balancer IP to network mapping and
// sets the mapping to the given attachments.
func (store *AttachmentStore) ResetAttachments(attachments map[string]string) error {
	store.ClearAttachments()
	for nid, nodeIP := range attachments {
		ip, _, err := net.ParseCIDR(nodeIP)
		if err != nil {
			store.networkToNodeLBIP = make(map[string]net.IP)
			return errors.Wrapf(err, "Failed to parse load balancer address %s", nodeIP)
		}
		store.networkToNodeLBIP[nid] = ip
	}
	return nil
}

// ClearAttachments clears all the mappings of network to load balancer IP Address.
func (store *AttachmentStore) ClearAttachments() {
	store.networkToNodeLBIP = make(map[string]net.IP)
}

// GetIPForNetwork return the load balancer IP address for the given network.
func (store *AttachmentStore) GetIPForNetwork(networkID string) (net.IP, bool) {
	ip, exists := store.networkToNodeLBIP[networkID]
	return ip, exists
}


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Phytologia 49:47. 1981

#### Original name
null

### Remarks
null


text:
namespace IMC
{
  //! Device Calibration State.
  class DevCalibrationState: public Message
  {
  public:
    //! Flags.
    enum FlagsBits
    {
      //! Previous Step Not Supported.
      DCS_PREVIOUS_NOT_SUPPORTED = 0x01,
      //! Next Step Not Supported.
      DCS_NEXT_NOT_SUPPORTED = 0x02,
      //! Waiting Device Calibration Control.
      DCS_WAITING_CONTROL = 0x04,
      //! Calibration Error.
      DCS_ERROR = 0x08,
      //! Calibration Procedure Completed.
      DCS_COMPLETED = 0x10
    };

    //! Total Steps.
    uint8_t total_steps;
    //! Current Step Number.
    uint8_t step_number;
    //! Description.
    std::string step;
    //! Flags.
    uint8_t flags;

    static uint16_t
    getIdStatic(void)
    {
      return 13;
    }

    static DevCalibrationState*
    cast(Message* msg__)
    {
      return (DevCalibrationState*)msg__;
    }

    DevCalibrationState(void)
    {
      m_header.mgid = DevCalibrationState::getIdStatic();
      clear();
    }

    DevCalibrationState*
    clone(void) const
    {
      return new DevCalibrationState(*this);
    }

    void
    clear(void)
    {
      total_steps = 0;
      step_number = 0;
      step.clear();
      flags = 0;
    }

    bool
    fieldsEqual(const Message& msg__) const
    {
      const IMC::DevCalibrationState& other__ = static_cast<const DevCalibrationState&>(msg__);
      if (total_steps != other__.total_steps) return false;
      if (step_number != other__.step_number) return false;
      if (step != other__.step) return false;
      if (flags != other__.flags) return false;
      return true;
    }

    uint8_t*
    serializeFields(uint8_t* bfr__) const
    {
      uint8_t* ptr__ = bfr__;
      ptr__ += IMC::serialize(total_steps, ptr__);
      ptr__ += IMC::serialize(step_number, ptr__);
      ptr__ += IMC::serialize(step, ptr__);
      ptr__ += IMC::serialize(flags, ptr__);
      return ptr__;
    }

    size_t
    deserializeFields(const uint8_t* bfr__, size_t size__)
    {
      const uint8_t* start__ = bfr__;
      bfr__ += IMC::deserialize(total_steps, bfr__, size__);
      bfr__ += IMC::deserialize(step_number, bfr__, size__);
      bfr__ += IMC::deserialize(step, bfr__, size__);
      bfr__ += IMC::deserialize(flags, bfr__, size__);
      return bfr__ - start__;
    }

    size_t
    reverseDeserializeFields(const uint8_t* bfr__, size_t size__)
    {
      const uint8_t* start__ = bfr__;
      bfr__ += IMC::deserialize(total_steps, bfr__, size__);
      bfr__ += IMC::deserialize(step_number, bfr__, size__);
      bfr__ += IMC::reverseDeserialize(step, bfr__, size__);
      bfr__ += IMC::deserialize(flags, bfr__, size__);
      return bfr__ - start__;
    }

    uint16_t
    getId(void) const
    {
      return DevCalibrationState::getIdStatic();
    }

    const char*
    getName(void) const
    {
      return "DevCalibrationState";
    }

    size_t
    getFixedSerializationSize(void) const
    {
      return 3;
    }

    size_t
    getVariableSerializationSize(void) const
    {
      return IMC::getSerializationSize(step);
    }

    void
    fieldsToJSON(std::ostream& os__, unsigned nindent__) const
    {
      IMC::toJSON(os__, "total_steps", total_steps, nindent__);
      IMC::toJSON(os__, "step_number", step_number, nindent__);
      IMC::toJSON(os__, "step", step, nindent__);
      IMC::toJSON(os__, "flags", flags, nindent__);
    }
  };
}

#endif


text:
<?php
namespace Robo\Task;

use Robo\Task\ValueProviderTask;

trait TestHelperTasks
{
    public function taskValueProvider()
    {
        return $this->task(ValueProviderTask::class);
    }
}


text:
<?php

namespace Symfony\Component\HttpClient\Exception;

use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 */
final class InvalidArgumentException extends \InvalidArgumentException implements TransportExceptionInterface
{
}


text:
template <class ElementType = long double>
class Matrix
{
 public:
  struct MatrixRow
  {
   private:
    std::vector<ElementType> contents_;

   public:
    size_t size() const { return contents_.size(); }
    ElementType operator[](size_t index) const { return contents_[index]; }
    ElementType& operator[](size_t index) { return contents_[index]; }

    typename std::vector<ElementType>::iterator begin()
    {
      return contents_.begin();
    }

    typename std::vector<ElementType>::iterator end()
    {
      return contents_.end();
    }

    explicit MatrixRow(size_t size) : contents_(size)
    { }

    MatrixRow(size_t size, const ElementType& default_value) :
      contents_(size, default_value)
    { }

    explicit MatrixRow(const std::vector<ElementType>& contents) :
      contents_(contents)
    { }
  };

 private:
  std::vector<MatrixRow> contents_;

 public:
  template <class Function>
  Matrix& apply(const Function& function)
  {
    for (MatrixRow& row : contents_)
    {
      for (ElementType& element : row)
      {
        element = function(element);
      }
    }
    return *this;
  }

  typename std::vector<MatrixRow>::iterator begin()
  {
    return contents_.begin();
  }

  typename std::vector<MatrixRow>::iterator end()
  {
    return contents_.end();
  }

  size_t width() const
  {
    return contents_.size() > 0 ? contents_.front().size() : 0;
  }

  size_t height() const
  {
    return contents_.size();
  }

  Matrix operator*(const Matrix& rhs)
  {
    if (width() != rhs.height())
    {
      throw std::invalid_argument(
          "Can't multiply matrices with not fitting dimensions");
    }
    Matrix result(height(), rhs.width());
    for (size_t row_index = 0; row_index < result.height(); ++row_index)
    {
      for (size_t column_index = 0;
          column_index < result.width();
          ++column_index)
      {
        for (size_t inner_index = 0; inner_index < width(); ++inner_index)
        {
          result[row_index][column_index] +=
            (*this)[row_index][inner_index] * rhs[inner_index][column_index];
        }
      }
    }
    return result;
  }

  Vector<ElementType> operator*(const Vector<ElementType>& rhs)
  {
    if (width() != rhs.size())
    {
      throw std::invalid_argument(
          "Can't multiply matrices with not fitting dimensions");
    }
    Vector<ElementType> result(height());
    for (size_t row_index = 0; row_index < result.size(); ++row_index)
    {
      for (size_t column_index = 0; column_index < width(); ++column_index)
      {
        result[row_index] +=
          (*this)[row_index][column_index] * rhs[column_index];
      }
    }
    return result;
  }

  MatrixRow operator[](size_t index) const
  {
    return contents_[index];
  }

  MatrixRow& operator[](size_t index)
  {
    return contents_[index];
  }

  Matrix(size_t height = 0, size_t width = 0) :
    contents_(height, MatrixRow(width))
  { }

  Matrix(size_t height, size_t width, const ElementType& default_value) :
    contents_(height, MatrixRow(width, default_value))
  { }

  Matrix(const Vector<ElementType>& vector) :
    contents_(vector.size(), MatrixRow(1))
  {
    for (size_t index = 0; index < vector.size(); ++index)
    {
      contents_[index][0] = vector[index];
    }
  }

  explicit Matrix(const std::vector<std::vector<ElementType>>& contents_) :
    contents_(contents_)
  { }

  friend std::ostream& operator<<(std::ostream& os, const Matrix& matrix)
  {
    for (size_t row_index = 0; row_index < matrix.height(); ++row_index)
    {
      for (size_t column_index = 0;
          column_index < matrix.width();
          ++column_index)
      {
        os << matrix[row_index][column_index] << ' ';
      }
      os << '\n';
    }
    return os;
  }
};

#endif


text:
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

// Copyright (c) 2006 Johan Rade
// Copyright (c) 2011 Paul A. Bristow

/*!
\file
\brief Basic tests of nonfinite loopback.

\detail Basic loopback test outputs using nonfinite facets
(output and input) and reads back in, and checks if loopback OK.

Expected to work portably on all platforms.

*/

#ifdef _MSC_VER
#   pragma warning(disable : 4702)
#   pragma warning(disable : 4127) // conditional expression is constant.
#endif

#include <boost/math/special_functions/nonfinite_num_facets.hpp>
using boost::math::nonfinite_num_get;
using boost::math::nonfinite_num_put;

#include <iostream>
using std::cout;
using std::endl;

#include <locale>
using std::locale;

#include <sstream>
using std::stringstream;
#include <limits>
using std::numeric_limits;

#include <assert.h>

int main()
{

  if((std::numeric_limits<double>::has_infinity == false) || (std::numeric_limits<double>::infinity() == 0))
  {
    std::cout << "Infinity not supported on this platform." << std::endl;
    return 0;
  }

  if((std::numeric_limits<double>::has_quiet_NaN == false) || (std::numeric_limits<double>::quiet_NaN() == 0))
  {
    std::cout << "NaN not supported on this platform." << std::endl;
    return 0;
  }
  //locale old_locale; // Current global locale.
  // Create tmp_locale and store the output nonfinite_num_put facet in it.
  //locale tmp_locale(old_locale, new nonfinite_num_put<char>);
  // Create new_locale and store the input nonfinite_num_get facet in it.
  //locale new_locale(tmp_locale, new nonfinite_num_get<char>);
  // Can only add one facet at a time, hence need a tmp_locale.
  // Unless we write:

  std::locale new_locale(std::locale(std::locale(std::locale(),
    new boost::math::nonfinite_num_put<char>),
    new boost::math::nonfinite_num_get<char>));

  stringstream ss; // Both input and output, so need both get and put facets.

  ss.imbue(new_locale);

  double inf = numeric_limits<double>::infinity();
  ss << inf; // Write out.
  double r;
  ss >> r; // Read back in.

  assert(inf == r); // OK MSVC <= 10.0!

} // int main()

/*

Output:

nonfinite_loopback_ok.vcxproj -> J:\Cpp\fp_facet\fp_facet\Debug\nonfinite_loopback_ok.exe

*/


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

    <title>POC-React-Invoice</title>

    <link href='//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700|Roboto+Slab:400,300' rel='stylesheet' type='text/css'>


text:
package policy

import (
	"fmt"

	"github.com/sirupsen/logrus"

	"github.com/cilium/cilium/pkg/identity"
	"github.com/cilium/cilium/pkg/labels"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/logging/logfields"
	"github.com/cilium/cilium/pkg/option"
	"github.com/cilium/cilium/pkg/policy/trafficdirection"
)

var (
	// localHostKey represents an ingress L3 allow from the local host.
	localHostKey = Key{
		Identity:         identity.ReservedIdentityHost.Uint32(),
		TrafficDirection: trafficdirection.Ingress.Uint8(),
	}
	// localRemoteNodeKey represents an ingress L3 allow from remote nodes.
	localRemoteNodeKey = Key{
		Identity:         identity.ReservedIdentityRemoteNode.Uint32(),
		TrafficDirection: trafficdirection.Ingress.Uint8(),
	}
	// allKey represents a key for unknown traffic, i.e., all traffic.
	allKey = Key{
		Identity: identity.IdentityUnknown.Uint32(),
	}
)

const (
	LabelKeyPolicyDerivedFrom   = "io.cilium.policy.derived-from"
	LabelAllowLocalHostIngress  = "allow-localhost-ingress"
	LabelAllowRemoteHostIngress = "allow-remotehost-ingress"
	LabelAllowAnyIngress        = "allow-any-ingress"
	LabelAllowAnyEgress         = "allow-any-egress"
	LabelVisibilityAnnotation   = "visibility-annotation"
)

// MapState is a state of a policy map.
type MapState map[Key]MapStateEntry

// Key is the userspace representation of a policy key in BPF. It is
// intentionally duplicated from pkg/maps/policymap to avoid pulling in the
// BPF dependency to this package.
type Key struct {
	// Identity is the numeric identity to / from which traffic is allowed.
	Identity uint32
	// DestPort is the port at L4 to / from which traffic is allowed, in
	// host-byte order.
	DestPort uint16
	// NextHdr is the protocol which is allowed.
	Nexthdr uint8
	// TrafficDirection indicates in which direction Identity is allowed
	// communication (egress or ingress).
	TrafficDirection uint8
}

// String returns a string representation of the Key
func (k Key) String() string {
	return fmt.Sprintf("Identity=%d,DestPort=%d,Nexthdr=%d,TrafficDirection=%d", k.Identity, k.DestPort, k.Nexthdr, k.TrafficDirection)
}

// IsIngress returns true if the key refers to an ingress policy key
func (k Key) IsIngress() bool {
	return k.TrafficDirection == trafficdirection.Ingress.Uint8()
}

// IsEgress returns true if the key refers to an egress policy key
func (k Key) IsEgress() bool {
	return k.TrafficDirection == trafficdirection.Egress.Uint8()
}

type Keys map[Key]struct{}

type MapStateOwner interface{}

// MapStateEntry is the configuration associated with a Key in a
// MapState. This is a minimized version of policymap.PolicyEntry.
type MapStateEntry struct {
	// The proxy port, in host byte order.
	// If 0 (default), there is no proxy redirection for the corresponding
	// Key. Any other value signifies proxy redirection.
	ProxyPort uint16

	// IsDeny is true when the policy should be denied.
	IsDeny bool

	// DerivedFromRules tracks the policy rules this entry derives from
	DerivedFromRules labels.LabelArrayList

	// Owners collects the keys in the map and selectors in the policy that require this key to be present.
	// TODO: keep track which selector needed the entry to be deny, redirect, or just allow.
	owners map[MapStateOwner]struct{}

	// dependents contains the keys for entries create based on this entry. These entries
	// will be deleted once all of the owners are deleted.
	dependents Keys
}

// NewMapStateEntry creates a map state entry. If redirect is true, the
// caller is expected to replace the ProxyPort field before it is added to
// the actual BPF map.
// 'cs' is used to keep track of which policy selectors need this entry. If it is 'nil' this entry
// will become sticky and cannot be completely removed via incremental updates. Even in this case
// the entry may be overridden or removed by a deny entry.
func NewMapStateEntry(cs MapStateOwner, derivedFrom labels.LabelArrayList, redirect, deny bool) MapStateEntry {
	var proxyPort uint16
	if redirect {
		// Any non-zero value will do, as the callers replace this with the
		// actual proxy listening port number before the entry is added to the
		// actual bpf map.
		proxyPort = 1
	}

	return MapStateEntry{
		ProxyPort:        proxyPort,
		DerivedFromRules: derivedFrom,
		IsDeny:           deny,
		owners:           map[MapStateOwner]struct{}{cs: {}},
	}
}

// AddDependent adds 'key' to the set of dependent keys.
func (e *MapStateEntry) AddDependent(key Key) {
	if e.dependents == nil {
		e.dependents = make(Keys, 1)
	}
	e.dependents[key] = struct{}{}
}

// RemoveDependent removes 'key' from the set of dependent keys.
func (e *MapStateEntry) RemoveDependent(key Key) {
	delete(e.dependents, key)
	// Nil the map when empty. This is mainly to make unit testing easier.
	if len(e.dependents) == 0 {
		e.dependents = nil
	}
}

// AddDependent adds 'key' to the set of dependent keys.
func (owner Key) AddDependent(keys MapState, key Key) {
	if e, exists := keys[owner]; exists {
		e.AddDependent(key)
		keys[owner] = e
	}
}

// RemoveDependent removes 'key' from the list of dependent keys.
// This is called when a dependent entry is being deleted.
func (keys MapState) RemoveDependent(owner Key, dependent Key) {
	if e, exists := keys[owner]; exists {
		e.RemoveDependent(dependent)
		keys[owner] = e
	}
}

// MergeReferences adds owners and dependents from entry 'entry' to 'e'. 'entry' is not modified.
func (e *MapStateEntry) MergeReferences(entry *MapStateEntry) {
	if e.owners == nil && len(entry.owners) > 0 {
		e.owners = make(map[MapStateOwner]struct{}, len(entry.owners))
	}
	for k, v := range entry.owners {
		e.owners[k] = v
	}

	// merge dependents
	for k := range entry.dependents {
		e.AddDependent(k)
	}
}

// IsRedirectEntry returns true if e contains a redirect
func (e *MapStateEntry) IsRedirectEntry() bool {
	return e.ProxyPort != 0
}

// DatapathEqual returns true of two entries are equal in the datapath's PoV,
// i.e., both Deny and ProxyPort are the same for both entries.
func (e *MapStateEntry) DatapathEqual(o *MapStateEntry) bool {
	if e == nil || o == nil {
		return e == o
	}

	return e.IsDeny == o.IsDeny && e.ProxyPort == o.ProxyPort
}

// String returns a string representation of the MapStateEntry
func (e MapStateEntry) String() string {
	return fmt.Sprintf("ProxyPort=%d", e.ProxyPort)
}

// DenyPreferredInsert inserts a key and entry into the map by given preference
// to deny entries, and L3-only deny entries over L3-L4 allows.
// This form may be used when a full policy is computed and we are not yet interested
// in accumulating incremental changes.
func (keys MapState) DenyPreferredInsert(newKey Key, newEntry MapStateEntry) {
	keys.denyPreferredInsertWithChanges(newKey, newEntry, nil, nil)
}

// addKeyWithChanges adds a 'key' with value 'entry' to 'keys' keeping track of incremental changes in 'adds' and 'deletes'
func (keys MapState) addKeyWithChanges(key Key, entry MapStateEntry, adds, deletes Keys) {
	// Keep all owners that need this entry so that it is deleted only if all the owners delete their contribution
	updatedEntry := entry
	oldEntry, exists := keys[key]
	if exists {
		// keep the existing owners of the old entry
		updatedEntry.owners = oldEntry.owners
		// keep the existing dependent entries
		updatedEntry.dependents = oldEntry.dependents
	} else if len(entry.owners) > 0 {
		// create a new owners map
		updatedEntry.owners = make(map[MapStateOwner]struct{}, len(entry.owners))
	}

	// TODO: Do we need to merge labels as well?
	// Merge new owner to the updated entry without modifying 'entry' as it is being reused by the caller
	updatedEntry.MergeReferences(&entry)
	// Update (or insert) the entry
	keys[key] = updatedEntry

	// Record an incremental Add if desired and entry is new or changed
	if adds != nil && (!exists || !oldEntry.DatapathEqual(&entry)) {
		adds[key] = struct{}{}
		// Key add overrides any previous delete of the same key
		if deletes != nil {
			delete(deletes, key)
		}
	}
}

// deleteKeyWithChanges deletes a 'key' from 'keys' keeping track of incremental changes in 'adds' and 'deletes'.
// The key is unconditionally deleted if 'cs' is nil, otherwise only the contribution of this 'cs' is removed.
func (keys MapState) deleteKeyWithChanges(key Key, owner MapStateOwner, adds, deletes Keys) {
	if entry, exists := keys[key]; exists {
		if owner != nil {
			// remove the contribution of the given selector only
			if _, exists = entry.owners[owner]; exists {
				// Remove the contribution of this selector from the entry
				delete(entry.owners, owner)
				if ownerKey, ok := owner.(Key); ok {
					keys.RemoveDependent(ownerKey, key)
				}
				// key is not deleted if other owners still need it
				if len(entry.owners) > 0 {
					return
				}
			} else {
				// 'owner' was not found, do not change anything
				return
			}
		}

		// Remove this key from all owners' dependents maps if no owner was given.
		// Owner is nil when deleting more specific entries (e.g., L3/L4) when
		// adding deny entries that cover them (e.g., L3-deny).
		if owner == nil {
			for owner := range entry.owners {
				if owner != nil {
					if ownerKey, ok := owner.(Key); ok {
						keys.RemoveDependent(ownerKey, key)
					}
				}
			}
		}

		// Check if dependent entries need to be deleted as well
		for k := range entry.dependents {
			keys.deleteKeyWithChanges(k, key, adds, deletes)
		}
		if deletes != nil {
			deletes[key] = struct{}{}
			// Remove a potential previously added key
			if adds != nil {
				delete(adds, key)
			}
		}

		delete(keys, key)
	}
}

// denyPreferredInsertWithChanges inserts a key and entry into the map by giving preference
// to deny entries, and L3-only deny entries over L3-L4 allows.
// Incremental changes performed are recorded in 'adds' and 'deletes', if not nil.
func (keys MapState) denyPreferredInsertWithChanges(newKey Key, newEntry MapStateEntry, adds, deletes Keys) {
	allCpy := allKey
	allCpy.TrafficDirection = newKey.TrafficDirection
	// If we have a deny "all" we don't accept any kind of map entry
	if v, ok := keys[allCpy]; ok && v.IsDeny {
		return
	}

	if newEntry.IsDeny {
		// case for an existing allow L4-only and we are inserting deny L3-only
		switch {
		case newKey.DestPort == 0 && newKey.Nexthdr == 0 && newKey.Identity != 0:
			l4OnlyAllows := MapState{}
			for k, v := range keys {
				if newKey.TrafficDirection == k.TrafficDirection &&
					!v.IsDeny &&
					k.Identity == 0 && (k.DestPort != 0 || k.Nexthdr != 0) {
					// create a deny L3-L4 with the same allowed L4 port and proto
					newKeyCpy := newKey
					newKeyCpy.DestPort = k.DestPort
					newKeyCpy.Nexthdr = k.Nexthdr
					l3l4DenyEntry := NewMapStateEntry(newKey, newEntry.DerivedFromRules, false, true)
					keys.addKeyWithChanges(newKeyCpy, l3l4DenyEntry, adds, deletes)
					// L3-only entries can be deleted incrementally so we need to track their
					// effects on other entries so that those effects can be reverted when the
					// identity is removed.
					newEntry.AddDependent(newKeyCpy)
					l4OnlyAllows[k] = v
				}
			}
			// Delete all L3-L4 if we are inserting a deny L3-only and
			// there aren't allow L4-only for the existing deny L3-L4
			for k := range keys {
				if k.TrafficDirection == newKey.TrafficDirection &&
					k.DestPort != 0 && k.Nexthdr != 0 &&
					k.Identity == newKey.Identity {

					kCpy := k
					kCpy.Identity = 0
					if _, ok := l4OnlyAllows[kCpy]; !ok {
						keys.deleteKeyWithChanges(k, nil, adds, deletes)
					}
				}
			}
		case allCpy == newKey:
			// If we adding a deny "all" entry, then we will remove all entries
			// from the map state for that direction.
			for k := range keys {
				if k.TrafficDirection == allCpy.TrafficDirection {
					keys.deleteKeyWithChanges(k, nil, adds, deletes)
				}
			}
		default:
			// Do not insert 'newKey' if the map state already denies traffic
			// which is a superset of (or equal to) 'newKey'
			newKeyCpy := newKey
			newKeyCpy.DestPort = 0
			newKeyCpy.Nexthdr = 0
			v, ok := keys[newKeyCpy]
			if ok && v.IsDeny {
				// Found a L3-only Deny so we won't accept any L3-L4 policies
				return
			}
		}

		keys.addKeyWithChanges(newKey, newEntry, adds, deletes)
		return
	} else if newKey.Identity == 0 && newKey.DestPort != 0 {
		// case for an existing deny L3-only and we are inserting allow L4-only
		for k, v := range keys {
			if newKey.TrafficDirection == k.TrafficDirection {
				if v.IsDeny && k.Identity != 0 && k.DestPort == 0 && k.Nexthdr == 0 {
					// create a deny L3-L4 with the same deny L3
					newKeyCpy := newKey
					newKeyCpy.Identity = k.Identity
					l3l4DenyEntry := NewMapStateEntry(k, v.DerivedFromRules, false, true)
					keys.addKeyWithChanges(newKeyCpy, l3l4DenyEntry, adds, deletes)
					// Mark the new entry as a dependent of 'v'
					v.AddDependent(newKeyCpy)
					keys[k] = v
				}
			}
		}
		keys.addKeyWithChanges(newKey, newEntry, adds, deletes)
		return
	}
	// branch for adding a new allow L3-L4

	newKeyCpy := newKey
	newKeyCpy.DestPort = 0
	newKeyCpy.Nexthdr = 0
	v, ok := keys[newKeyCpy]
	if ok && v.IsDeny {
		// Found a L3-only Deny so we won't accept any L3-L4 allow policies
		return
	}

	keys.redirectPreferredInsert(newKey, newEntry, adds, deletes)
}

// redirectPreferredInsert inserts a new entry giving priority to L7-redirects by
// not overwriting a L7-redirect entry with a non-redirect entry.
func (keys MapState) redirectPreferredInsert(key Key, entry MapStateEntry, adds, deletes Keys) {
	// Do not overwrite the entry, but only merge owners if the old entry is a deny or redirect.
	// This prevents an existing deny or redirect being overridden by a non-deny or a non-redirect.
	// Merging owners from the new entry to the existing one has no datapath impact so we skip
	// adding anything to 'adds' here.
	if oldEntry, exists := keys[key]; exists && (oldEntry.IsRedirectEntry() || oldEntry.IsDeny) {
		oldEntry.MergeReferences(&entry)
		keys[key] = oldEntry
		return
	}
	// Otherwise write the entry to the map
	keys.addKeyWithChanges(key, entry, adds, deletes)
}

var visibilityDerivedFromLabels = labels.LabelArray{
	labels.NewLabel(LabelKeyPolicyDerivedFrom, LabelVisibilityAnnotation, labels.LabelSourceReserved),
}

var visibilityDerivedFrom = labels.LabelArrayList{visibilityDerivedFromLabels}

func (keys MapState) insertIfNotExists(key Key, entry MapStateEntry) {
	if keys != nil {
		if _, exists := keys[key]; !exists {
			keys[key] = entry
		}
	}
}

// AddVisibilityKeys adjusts and expands PolicyMapState keys
// and values to redirect for visibility on the port of the visibility
// annotation while still denying traffic on this port for identities
// for which the traffic is denied.
//
// Datapath lookup order is, from highest to lowest precedence:
// 1. L3/L4
// 2. L4-only (wildcard L3)
// 3. L3-only (wildcard L4)
// 4. Allow-all
//
// This means that the L4-only allow visibility key can only be added if there is an
// allow-all key, and all L3-only deny keys are expanded to L3/L4 keys. If no
// L4-only key is added then also the L3-only allow keys need to be expanded to
// L3/L4 keys for visibility redirection. In addition the existing L3/L4 and L4-only
// allow keys need to be redirected to the proxy port, if not already redirected.
//
// The above can be accomplished by:
//
// 1. Change existing L4-only ALLOW key on matching port that does not already
//    redirect to redirect.
//    - e.g., 0:80=allow,0 -> 0:80=allow,<proxyport>
// 2. If allow-all policy exists, add L4-only visibility redirect key if the L4-only
//    key does not already exist.
//    - e.g., 0:0=allow,0 -> add 0:80=allow,<proxyport> if 0:80 does not exist
//      - this allows all traffic on port 80, but see step 5 below.
// 3. Change all L3/L4 ALLOW keys on matching port that do not already redirect to
//    redirect.
//    - e.g, <ID1>:80=allow,0 -> <ID1>:80=allow,<proxyport>
// 4. For each L3-only ALLOW key add the corresponding L3/L4 ALLOW redirect if no
//    L3/L4 key already exists and no L4-only key already exists and one is not added.
//    - e.g., <ID2>:0=allow,0 -> add <ID2>:80=allow,<proxyport> if <ID2>:80
//      and 0:80 do not exist
// 5. If a new L4-only key was added: For each L3-only DENY key add the
//    corresponding L3/L4 DENY key if no L3/L4 key already exists.
//    - e.g., <ID3>:0=deny,0 -> add <ID3>:80=deny,0 if <ID3>:80 does not exist
//
// With the above we only change/expand existing allow keys to redirect, and
// expand existing drop keys to also drop on the port of interest, if a new
// L4-only key allowing the port is added.
//
// 'adds' and 'oldValues' are updated with the changes made. 'adds' contains both the added and
// changed keys. 'oldValues' contains the old values for changed keys. This function does not
// delete any keys.
func (keys MapState) AddVisibilityKeys(e PolicyOwner, redirectPort uint16, visMeta *VisibilityMetadata, adds Keys, oldValues MapState) {
	direction := trafficdirection.Egress
	if visMeta.Ingress {
		direction = trafficdirection.Ingress
	}

	allowAllKey := Key{
		TrafficDirection: direction.Uint8(),
	}
	key := Key{
		DestPort:         visMeta.Port,
		Nexthdr:          uint8(visMeta.Proto),
		TrafficDirection: direction.Uint8(),
	}

	entry := NewMapStateEntry(nil, visibilityDerivedFrom, true, false)
	entry.ProxyPort = redirectPort

	_, haveAllowAllKey := keys[allowAllKey]
	l4Only, haveL4OnlyKey := keys[key]
	addL4OnlyKey := false
	if haveL4OnlyKey && !l4Only.IsDeny && l4Only.ProxyPort == 0 {
		// 1. Change existing L4-only ALLOW key on matching port that does not already
		//    redirect to redirect.
		e.PolicyDebug(logrus.Fields{
			logfields.BPFMapKey:   key,
			logfields.BPFMapValue: entry,
		}, "AddVisibilityKeys: Changing L4-only ALLOW key for visibility redirect")

		// keep the original value for reverting purposes
		oldValues.insertIfNotExists(key, l4Only)

		l4Only.ProxyPort = redirectPort
		l4Only.DerivedFromRules = append(l4Only.DerivedFromRules, visibilityDerivedFromLabels)
		keys[key] = l4Only
		adds[key] = struct{}{}
	}
	if haveAllowAllKey && !haveL4OnlyKey {
		// 2. If allow-all policy exists, add L4-only visibility redirect key if the L4-only
		//    key does not already exist.
		e.PolicyDebug(logrus.Fields{
			logfields.BPFMapKey:   key,
			logfields.BPFMapValue: entry,
		}, "AddVisibilityKeys: Adding L4-only ALLOW key for visibilty redirect")
		addL4OnlyKey = true
		keys[key] = entry
		adds[key] = struct{}{}
	}
	//
	// Loop through all L3 keys in the traffic direction of the new key
	//
	for k, v := range keys {
		if k.TrafficDirection != key.TrafficDirection || k.Identity == 0 {
			continue
		}
		if k.DestPort == key.DestPort && k.Nexthdr == key.Nexthdr {
			//
			// Same L4
			//
			if !v.IsDeny && v.ProxyPort == 0 {
				// 3. Change all L3/L4 ALLOW keys on matching port that do not
				//    already redirect to redirect.

				// keep the original value for reverting purposes
				oldValues.insertIfNotExists(k, v)

				v.ProxyPort = redirectPort
				v.DerivedFromRules = append(v.DerivedFromRules, visibilityDerivedFromLabels)
				e.PolicyDebug(logrus.Fields{
					logfields.BPFMapKey:   k,
					logfields.BPFMapValue: v,
				}, "AddVisibilityKeys: Changing L3/L4 ALLOW key for visibility redirect")
				keys[k] = v
				adds[k] = struct{}{}
			}
		} else if k.DestPort == 0 && k.Nexthdr == 0 {
			//
			// Wildcarded L4, i.e., L3-only
			//
			k2 := k
			k2.DestPort = key.DestPort
			k2.Nexthdr = key.Nexthdr
			if !v.IsDeny && !haveL4OnlyKey && !addL4OnlyKey {
				// 4. For each L3-only ALLOW key add the corresponding L3/L4
				//    ALLOW redirect if no L3/L4 key already exists and no
				//    L4-only key already exists and one is not added.
				if _, ok := keys[k2]; !ok {
					d2 := append(labels.LabelArrayList{visibilityDerivedFromLabels}, v.DerivedFromRules...)
					v2 := NewMapStateEntry(k, d2, true, false)
					v2.ProxyPort = redirectPort
					e.PolicyDebug(logrus.Fields{
						logfields.BPFMapKey:   k2,
						logfields.BPFMapValue: v2,
					}, "AddVisibilityKeys: Extending L3-only ALLOW key to L3/L4 key for visibilty redirect")
					keys[k2] = v2
					adds[k2] = struct{}{}

					// keep the original value for reverting purposes
					oldValues.insertIfNotExists(k, v)

					// Mark the new entry as a dependent of 'v'
					v.AddDependent(k2)
					keys[k] = v
					adds[k] = struct{}{} // dependent was added
				}
			} else if addL4OnlyKey && v.IsDeny {
				// 5. If a new L4-only key was added: For each L3-only DENY
				//    key add the corresponding L3/L4 DENY key if no L3/L4
				//    key already exists.
				if _, ok := keys[k2]; !ok {
					v2 := NewMapStateEntry(k, v.DerivedFromRules, false, true)
					e.PolicyDebug(logrus.Fields{
						logfields.BPFMapKey:   k2,
						logfields.BPFMapValue: v2,
					}, "AddVisibilityKeys: Extending L3-only DENY key to L3/L4 key to deny a port with visibility annotation")
					keys[k2] = v2
					adds[k2] = struct{}{}

					// keep the original value for reverting purposes
					oldValues.insertIfNotExists(k, v)

					// Mark the new entry as a dependent of 'v'
					v.AddDependent(k2)
					keys[k] = v
					adds[k] = struct{}{} // dependent was added
				}
			}
		}
	}
}

// DetermineAllowLocalhostIngress determines whether communication should be allowed
// from the localhost. It inserts the Key corresponding to the localhost in
// the desiredPolicyKeys if the localhost is allowed to communicate with the
// endpoint.
func (keys MapState) DetermineAllowLocalhostIngress() {
	if option.Config.AlwaysAllowLocalhost() {
		derivedFrom := labels.LabelArrayList{
			labels.LabelArray{
				labels.NewLabel(LabelKeyPolicyDerivedFrom, LabelAllowLocalHostIngress, labels.LabelSourceReserved),
			},
		}
		es := NewMapStateEntry(nil, derivedFrom, false, false)
		keys.DenyPreferredInsert(localHostKey, es)
		if !option.Config.EnableRemoteNodeIdentity {
			var isHostDenied bool
			v, ok := keys[localHostKey]
			isHostDenied = ok && v.IsDeny
			derivedFrom := labels.LabelArrayList{
				labels.LabelArray{
					labels.NewLabel(LabelKeyPolicyDerivedFrom, LabelAllowRemoteHostIngress, labels.LabelSourceReserved),
				},
			}
			es := NewMapStateEntry(nil, derivedFrom, false, isHostDenied)
			keys.DenyPreferredInsert(localRemoteNodeKey, es)
		}
	}
}

// AllowAllIdentities translates all identities in selectorCache to their
// corresponding Keys in the specified direction (ingress, egress) which allows
// all at L3.
func (keys MapState) AllowAllIdentities(ingress, egress bool) {
	if ingress {
		keyToAdd := Key{
			Identity:         0,
			DestPort:         0,
			Nexthdr:          0,
			TrafficDirection: trafficdirection.Ingress.Uint8(),
		}
		derivedFrom := labels.LabelArrayList{
			labels.LabelArray{
				labels.NewLabel(LabelKeyPolicyDerivedFrom, LabelAllowAnyIngress, labels.LabelSourceReserved),
			},
		}
		keys[keyToAdd] = NewMapStateEntry(nil, derivedFrom, false, false)
	}
	if egress {
		keyToAdd := Key{
			Identity:         0,
			DestPort:         0,
			Nexthdr:          0,
			TrafficDirection: trafficdirection.Egress.Uint8(),
		}
		derivedFrom := labels.LabelArrayList{
			labels.LabelArray{
				labels.NewLabel(LabelKeyPolicyDerivedFrom, LabelAllowAnyEgress, labels.LabelSourceReserved),
			},
		}
		keys[keyToAdd] = NewMapStateEntry(nil, derivedFrom, false, false)
	}
}

func (keys MapState) AllowsL4(policyOwner PolicyOwner, l4 *L4Filter) bool {
	port := uint16(l4.Port)
	proto := uint8(l4.U8Proto)

	// resolve named port
	if port == 0 && l4.PortName != "" {
		port = policyOwner.GetNamedPortLocked(l4.Ingress, l4.PortName, proto)
		if port == 0 {
			return false
		}
	}

	var dir uint8
	if l4.Ingress {
		dir = trafficdirection.Ingress.Uint8()
	} else {
		dir = trafficdirection.Egress.Uint8()
	}
	anyKey := Key{
		Identity:         0,
		DestPort:         0,
		Nexthdr:          0,
		TrafficDirection: dir,
	}
	// Are we explicitly denying any traffic?
	v, ok := keys[anyKey]
	if ok && v.IsDeny {
		return false
	}

	// Are we explicitly denying this L4-only traffic?
	anyKey.DestPort = port
	anyKey.Nexthdr = proto
	v, ok = keys[anyKey]
	if ok && v.IsDeny {
		return false
	}

	return true
}

func (pms MapState) GetIdentities(log *logrus.Logger) (ingIdentities, egIdentities []int64) {
	return pms.getIdentities(log, false)
}

func (pms MapState) GetDenyIdentities(log *logrus.Logger) (ingIdentities, egIdentities []int64) {
	return pms.getIdentities(log, true)
}

// GetIdentities returns the ingress and egress identities stored in the
// MapState.
func (pms MapState) getIdentities(log *logrus.Logger, denied bool) (ingIdentities, egIdentities []int64) {
	for policyMapKey, policyMapValue := range pms {
		if denied != policyMapValue.IsDeny {
			continue
		}
		if policyMapKey.DestPort != 0 {
			// If the port is non-zero, then the Key no longer only applies
			// at L3. AllowedIngressIdentities and AllowedEgressIdentities
			// contain sets of which identities (i.e., label-based L3 only)
			// are allowed, so anything which contains L4-related policy should
			// not be added to these sets.
			continue
		}
		switch trafficdirection.TrafficDirection(policyMapKey.TrafficDirection) {
		case trafficdirection.Ingress:
			ingIdentities = append(ingIdentities, int64(policyMapKey.Identity))
		case trafficdirection.Egress:
			egIdentities = append(egIdentities, int64(policyMapKey.Identity))
		default:
			td := trafficdirection.TrafficDirection(policyMapKey.TrafficDirection)
			log.WithField(logfields.TrafficDirection, td).
				Errorf("Unexpected traffic direction present in policy map state for endpoint")
		}
	}
	return ingIdentities, egIdentities
}

// MapChanges collects updates to the endpoint policy on the
// granularity of individual mapstate key-value pairs for both adds
// and deletes. 'mutex' must be held for any access.
type MapChanges struct {
	mutex   lock.Mutex
	changes []MapChange
}

type MapChange struct {
	Add   bool // false deletes
	Key   Key
	Value MapStateEntry
}

// AccumulateMapChanges accumulates the given changes to the
// MapChanges.
//
// The caller is responsible for making sure the same identity is not
// present in both 'adds' and 'deletes'.
func (mc *MapChanges) AccumulateMapChanges(cs CachedSelector, adds, deletes []identity.NumericIdentity,
	port uint16, proto uint8, direction trafficdirection.TrafficDirection,
	redirect, isDeny bool, derivedFrom labels.LabelArrayList) {
	key := Key{
		// The actual identity is set in the loops below
		Identity: 0,
		// NOTE: Port is in host byte-order!
		DestPort:         port,
		Nexthdr:          proto,
		TrafficDirection: direction.Uint8(),
	}

	value := NewMapStateEntry(cs, derivedFrom, redirect, isDeny)

	if option.Config.Debug {
		log.WithFields(logrus.Fields{
			logfields.EndpointSelector: cs,
			logfields.AddedPolicyID:    adds,
			logfields.DeletedPolicyID:  deletes,
			logfields.Port:             port,
			logfields.Protocol:         proto,
			logfields.TrafficDirection: direction,
			logfields.IsRedirect:       redirect,
		}).Debug("AccumulateMapChanges")
	}

	mc.mutex.Lock()
	for _, id := range adds {
		key.Identity = id.Uint32()
		mc.changes = append(mc.changes, MapChange{Add: true, Key: key, Value: value})
	}
	for _, id := range deletes {
		key.Identity = id.Uint32()
		mc.changes = append(mc.changes, MapChange{Add: false, Key: key, Value: value})
	}
	mc.mutex.Unlock()
}

// consumeMapChanges transfers the incremental changes from MapChanges to the caller,
// while applying the changes to PolicyMapState.
func (mc *MapChanges) consumeMapChanges(policyMapState MapState) (adds, deletes Keys) {
	mc.mutex.Lock()
	adds = make(Keys, len(mc.changes))
	deletes = make(Keys, len(mc.changes))

	for i := range mc.changes {
		if mc.changes[i].Add {
			// insert but do not allow non-redirect entries to overwrite a redirect entry,
			// nor allow non-deny entries to overwrite deny entries.
			// Collect the incremental changes to the overall state in 'mc.adds' and 'mc.deletes'.
			policyMapState.denyPreferredInsertWithChanges(mc.changes[i].Key, mc.changes[i].Value, adds, deletes)
		} else {
			// Delete the contribution of this cs to the key and collect incremental changes
			for cs := range mc.changes[i].Value.owners { // get the sole selector
				policyMapState.deleteKeyWithChanges(mc.changes[i].Key, cs, adds, deletes)
			}
		}
	}
	mc.changes = nil
	mc.mutex.Unlock()
	return adds, deletes
}


text:
//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package io.protostuff;

import java.io.IOException;

/**
 * The base io exception for all formats (protobuf/json/xml).
 *
 * @author David Yu
 * @created May 25, 2010
 */
public class ProtostuffException extends IOException
{

    private static final long serialVersionUID = 3969366848110070516L;

    public ProtostuffException()
    {
        super();
    }

    public ProtostuffException(String message)
    {
        super(message);
    }

    public ProtostuffException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ProtostuffException(Throwable cause)
    {
        super(cause);
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/conversion_calc_bg"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/banner"
        android:background="#aa007223"
        android:padding="@dimen/activity_vertical_margin"
        android:textColor="#ffffff"
        android:text="@string/app_name"
        android:layout_alignParentTop="true"/>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/banner">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <com.google.android.gms.ads.AdView
                android:id="@+id/adView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                ads:adSize="BANNER"
                ads:adUnitId="ca-app-pub-9576690340592468/1487347633" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/nav_container"
                android:background="#ff007223"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:layout_marginTop="@dimen/activity_vertical_margin"
                android:layout_marginRight="@dimen/activity_vertical_margin"
                android:layout_marginEnd="@dimen/activity_vertical_margin"
                android:paddingBottom="2dp"
                android:layout_below="@+id/adView">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:background="#575757">

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:id="@+id/distance_button"
                        android:layout_weight="1"
                        android:padding="@dimen/activity_half_margin"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:gravity="center"
                        android:background="#ffffff"
                        android:textColor="#ff007223"
                        android:textSize="@dimen/nav_text"
                        android:text="@string/distance"/>

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:id="@+id/volume_button"
                        android:layout_weight="1"
                        android:padding="@dimen/activity_half_margin"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:gravity="center"
                        android:background="#ffffff"
                        android:textColor="#ff007223"
                        android:textSize="@dimen/nav_text"
                        android:text="@string/volume"/>

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:id="@+id/weight_button"
                        android:layout_weight="1"
                        android:padding="@dimen/activity_half_margin"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:gravity="center"
                        android:background="#ffffff"
                        android:textColor="#ff007223"
                        android:textSize="@dimen/nav_text"
                        android:text="@string/weight"/>

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:id="@+id/temp_button"
                        android:layout_weight="1"
                        android:padding="@dimen/activity_half_margin"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:layout_marginEnd="2dp"
                        android:layout_marginRight="2dp"
                        android:gravity="center"
                        android:background="#ffffff"
                        android:textColor="#ff007223"
                        android:textSize="@dimen/nav_text"
                        android:text="@string/temp"/>

                </LinearLayout>

            </LinearLayout>

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/content"
                android:background="#99575757"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:layout_marginRight="@dimen/activity_vertical_margin"
                android:layout_marginEnd="@dimen/activity_vertical_margin"
                android:layout_below="@+id/nav_container"/>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/developer_buttons"
                android:layout_below="@+id/content">

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:id="@+id/more"
                    android:layout_weight="1"
                    android:textColor="#007223"
                    android:text="@string/more"
                    android:layout_margin="@dimen/activity_half_margin"/>

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:id="@+id/share"
                    android:layout_weight="1"
                    android:textColor="#007223"
                    android:text="@string/share"
                    android:layout_margin="@dimen/activity_half_margin"/>

            </LinearLayout>

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/request"
                android:layout_below="@+id/developer_buttons"
                android:textColor="#007223"
                android:text="@string/request"
                android:layout_marginLeft="@dimen/activity_half_margin"
                android:layout_marginStart="@dimen/activity_half_margin"
                android:layout_marginRight="@dimen/activity_half_margin"
                android:layout_marginEnd="@dimen/activity_half_margin"
                android:layout_marginBottom="@dimen/activity_half_margin"/>

        </RelativeLayout>

    </ScrollView>

</RelativeLayout>


text:
namespace rl
{
	namespace mdl
	{
		InverseKinematics::InverseKinematics(Kinematic* kinematic) :
			goals(),
			kinematic(kinematic)
		{
		}

		InverseKinematics::~InverseKinematics()
		{
		}

		void
		InverseKinematics::addGoal(const Goal& goal)
		{
			this->goals.push_back(goal);
		}

		void
		InverseKinematics::addGoal(const ::rl::math::Transform& x, const ::std::size_t& i)
		{
			this->addGoal(::std::make_pair(x, i));
		}

		void
		InverseKinematics::clearGoals()
		{
			this->goals.clear();
		}

		const ::std::vector<InverseKinematics::Goal>&
		InverseKinematics::getGoals() const
		{
			return this->goals;
		}
	}
}


text:
nodemon --watch actions \
        --watch config \
        --watch lib \
        --watch tasks \
        --watch initializers \
        --watch ../shared \
        --watch ../lib \
        --exec "run_mcapid.sh mcapid-${SERVERTYPE}"


text: This is the repository for ICL-GNSS containing its website and conference tools


text:
<?php
/**
 * Ejemplo del método que obtiene las operaciones pagadas que fueron devueltas para su organismo
 */

const ID_ORGANISMO = ""; //TODO: ccmpletar con el ID de organismo proporcionado
const ID_USUARIO   = ""; //TODO: ccmpletar con el ID de usuario proporcionado
const PASSWORD     = ""; //TODO: ccmpletar con el password proporcionado
const HASH         = ""; //TODO: ccmpletar con el hash proporcionado
const CONVENIO     = ""; //TODO: completar con el convenio proporcionado

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

require 'lib/epagos_api.class.php';

try {
  $epagos = new epagos_api(ID_ORGANISMO, ID_USUARIO);

  //
  // el SDK soporta dos entornos:
  // Testing    -> EPAGOS_ENTORNO_SANDBOX
  // Producción -> EPAGOS_ENTORNO_PRODUCCION
  //
  $epagos->set_entorno(EPAGOS_ENTORNO_SANDBOX);
  $ret = $epagos->obtener_token(PASSWORD, HASH);
  if (!$ret["token"]) {
    echo 'Error: generar_token: ';
    echo "
";
    print_r($ret);
    echo "
";
    exit;
  }

  //
  // consulta la documentación para ver los criterios de búsqueda posibles
  // Atención, el resultado se devolverá paginado, en la respuesta el atributo pagina y cantidadTotal ayudan a recorrerlo
  //
  $criterios = ["FechaNovedadAcreditacionDesde" => '2020-09-01',"FechaNovedadAcreditacionHasta" => '2020-09-20'];
  echo "
";
  $pagos = $epagos->obtener_devoluciones($criterios);
  echo "Resultado: obtener_devoluciones";
  echo "
";
  print_r($pagos);
  echo "
";

} catch (EPagos_Exception $e){
  echo "Error: ".$e->getMessage();
} /* try, catch */


text:
module ReportType
  class Environment < Base
    include SparqlBuilder::Environment

    class << self
      def count(meo_id: '', tax_id: '', bp_id: '', mf_id: '', cc_id: '', mpo_id: '')
        select_clause =  "SELECT COUNT(DISTINCT ?meo_id) AS ?hits_count"
        sparql = build_base_sparql(meo_id, tax_id, bp_id, mf_id, cc_id, mpo_id, select_clause)

        results = query(sparql)

        results.first[:hits_count]
      end

      def search(meo_id: '', tax_id: '', bp_id: '', mf_id: '', cc_id: '', mpo_id: '', limit: 25, offset: 0)
        select_clause, order_clause = "SELECT DISTINCT ?meo_id ?meo_name ?category ?category_name ?definition", "ORDER BY ?category_name"
        sparql = build_base_sparql(meo_id, tax_id, bp_id, mf_id, cc_id, mpo_id, select_clause, order_clause, limit, offset)

        results = query(sparql)

        return [] if results.empty?

        meos = results.map {|r| "<#{r[:meo_id]}>" }.uniq.join(' ')

        sparql = find_inhabitants_sparql(PREFIX, ONTOLOGY, meos)

        inhabitants = query(sparql)

        results.map do |result|
          select_inhabitants = inhabitants.find {|r| r[:meo_id] == result[:meo_id] }

          new(result, select_inhabitants)
        end
      end
    end

    def initialize(meo, inhabitants)
      @environment, @inhabitants = meo, inhabitants
    end

    def environment
      OpenStruct.new(
        uri:         @environment[:meo_id],
        name:        @environment[:meo_name],
        category:    @environment[:category_name],
        inhabitants: @inhabitants.try(:[], :count),
        definition:  @environment[:definition],
        id:          @environment[:meo_id].split('/').last
      )
    end
  end
end


text:
"""
    adapted from sphinxcontrib.autohttp.tornado

    The sphinx.ext.autodoc-style HTTP API reference builder (from Tornado)
    for sphinxcontrib.httpdomain.

    :copyright: Copyright 2013 by Rodrigo Machado
    :license: BSD, see LICENSE for details.

"""

from docutils import nodes
from docutils.statemachine import ViewList

from sphinx.util.compat import Directive
from sphinx.util.nodes import nested_parse_with_titles
from sphinx.util.docstrings import prepare_docstring

from sphinxcontrib import httpdomain
from sphinxcontrib.autohttp.common import http_directive

from functools import singledispatch
from voluptuous import (
    Required, Optional, All, Any, Length, Range, Coerce, UNDEFINED
)

from nthuion.introspect import r1
from nthuion.views.base import not_allowed

@singledispatch
def parse_left(obj):
    raise NotImplementedError(obj)

@parse_left.register(Required)
def _parse_left_required(obj):
    return obj.schema, True, obj.default

@parse_left.register(Optional)
def _parse_left_optional(obj):
    return obj.schema, False, obj.default

@singledispatch
def parse_right(obj):
    raise NotImplementedError(obj)

@parse_right.register(Coerce)
def _parse_right_coerce(obj):
    return parse_right(obj.type)

@parse_right.register(type)
def _parse_right_type(obj):
    return {
        int: 'integer',
        str: 'string',
        bool: 'boolean'
    }[obj]

@parse_right.register(type(None))
def _parse_right_null(obj):
    return '``null``'

@parse_right.register(Length)
def _parse_right_length(obj):
    if obj.min is None:
        return 'length ≤ {}'.format(obj.max)
    elif obj.max is None:
        return '{} ≤ length'.format(obj.min)
    else:
        return '{} ≤ length ≤ {}'.format(obj.min, obj.max)

@parse_right.register(Range)
def _parse_right_range(obj):
    if obj.min is None:
        return 'x ≤ {}'.format(obj.max)
    elif obj.max is None:
        return '{} ≤ x'.format(obj.min)
    else:
        return '{} ≤ x ≤ {}'.format(obj.min, obj.max)

@parse_right.register(int)
@parse_right.register(str)
def _parse_right_int_or_str(obj):
    # XXX sometimes we want strings quoted, sometimes not
    return '``{}``'.format(obj)

@parse_right.register(All)
def _parse_right_all(obj):
    return ', '.join(parse_right(validator) for validator in obj.validators)

@parse_right.register(Any)
def _parse_right_any(obj):
    return ' or '.join(parse_right(validator) for validator in obj.validators)

@parse_right.register(list)
def _parse_right_list(obj):
    assert len(obj) == 1
    return 'array of [{}]'.format(parse_right(obj[0]))

def schema_to_docstring(schema, directive='reqjson'):
    for l, r in sorted(schema.items()):
        key, required, default = parse_left(l)
        desc = parse_right(r)
        if default is UNDEFINED:
            default_desc = ''
        else:
            default_desc = ', default = ``{}``'.format(
                {None: 'null'}.get(default(), repr(default()))
            )
        required_desc = '' if required else 'optional '
        yield ':{} {}{}: {}{}'.format(
            directive, required_desc, key, desc, default_desc)

class AutoAPIDirective(Directive):

    has_content = True
    required_arguments = 1

    def make_rst(self):
        for name, path, vcallable in r1():

            if not path.startswith(self.arguments[0]):
                continue

            yield name.capitalize()
            yield '-' * len(name)
            yield vcallable.__doc__ or ''

            for method in ('get', 'post', 'put', 'delete'):

                implementation = getattr(vcallable, method)

                if implementation is not_allowed:
                    continue

                docstring = getattr(vcallable, method).__doc__ or ''
                # if not docstring and 'include-empty-docstring' not in self.options:  # noqa
                #     continue
                docstring = prepare_docstring(docstring)

                schema = getattr(implementation, 'schema', None)
                if schema is not None:
                    docstring += ['']
                    docstring += list(schema_to_docstring(schema))

                qs_schema = getattr(implementation, 'qs_schema', None)
                if qs_schema is not None:
                    docstring += ['']
                    docstring += list(schema_to_docstring(qs_schema, 'query'))

                reqp = getattr(implementation, 'requires_permission', None)
                if reqp is not None:
                    docstring = [
                        'requires permission: ``{}``'.format(reqp),
                        ''
                    ] + docstring

                for line in http_directive(method, path, docstring):
                    yield line

    def run(self):
        node = nodes.section()
        node.document = self.state.document
        result = ViewList()
        for line in self.make_rst():
            result.append(line, '<autoapi>')
        nested_parse_with_titles(self.state, result, node)
        return node.children

def setup(app):
    if 'http' not in app.domains:
        httpdomain.setup(app)
    app.add_directive('autoapi', AutoAPIDirective)


text:
#ifndef _CHECK_H_
#define _CHECK_H_

#include <libcasper.h>
#include <casper/cap_syslog.h>

enum { SUCCESS = 0, MOREDATA = 1, FAILURE = -1, TIMEOUT = -1 };

extern cap_channel_t *system_syslog$;
#define log(...) cap_syslog(system_syslog$, __VA_ARGS__)

#endif /* #ifndef _CHECK_H_ */


text:
<?php
namespace Employee\EmployeeBundle\Classes;

/**
 * HTTP I/O abstraction.
 *
 * Responsible for executing CURL requests.
 */
class Http
{
    /** Name of this Web browser */
    const USERAGENT = "ApiClient";
    /** The maximum number of seconds to allow cURL functions to execute. */
    const CURL_TIMEOUT = 60;
    /** The maximum number of seconds to wait for an established session */
    const CURL_CONNECTTIMEOUT = 60;

    /**
     * Send an HTTP request.
     *
     * @param string $url URL to call
     * @param array|NULL $post All post-variables to add (all is auto escaped)
     * @param boolean|String $cookieJar File to write cookie data to
     * @param array $flags Additional cURL-flags
     *
     * @throws \Exception When failing to interact with the server/cURL
     * @return String The CURL response
     */
    public static function get($url, array $post = NULL, $cookieJar = FALSE, array $flags = array())
    {
        /** @var bool $optSet variable that will be used to see if a curl option is successfully set */
        $optSet = TRUE;

        $ch = self::curlInit($url);

        // set curl options
        {
            if ($post !== NULL) {
                $optSet &= curl_setopt($ch, CURLOPT_POST, count($post));
                $optSet &= curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
            }
            $optSet &= curl_setopt($ch, CURLOPT_USERAGENT, self::USERAGENT);
            $optSet &= curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            if ($cookieJar !== FALSE) {
                if (strlen(file_get_contents($cookieJar)) == 0) {
                    $optSet &= curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieJar);
                } else {
                    $optSet &= curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieJar);
                }
            }
            $optSet &= curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CURL_CONNECTTIMEOUT);
            $optSet &= curl_setopt($ch, CURLOPT_TIMEOUT, self::CURL_TIMEOUT);
            foreach ($flags as $key => $value) {
                $optSet &= curl_setopt($ch, $key, $value);
            }

            if ($optSet === FALSE) {
                throw new \Exception("One or more cURL option-flags failed");
            }
        }

        return self::curlExec($ch, $url);
    }

    /**
     * Wrapper to gte a cURL handler with some error checking.
     *
     * @param string $url The URL
     *
     * @return resource cURL handle
     * @throws \Exception
     */
    private static function curlInit($url)
    {
        if (! function_exists("curl_init")) {
            throw new \Exception("cURL-library not available, please install/enable.");
        }

        $ch = curl_init($url);
        if ($ch === FALSE) {
            throw new \Exception("Error calling curl_init");
        }

        return $ch;
    }

    /**
     * Wrapper for curl_exec with some error handling.
     *
     * @param resource $ch cURL handle
     * @param string $url the URL called
     *
     * @return mixed the CURL result
     * @throws \Exception
     */
    private static function curlExec($ch, $url)
    {
        $result = curl_exec($ch);
        if ($result === FALSE) {
            throw new \Exception(
                sprintf("Error calling curl_exec #%d: %s (%s)", curl_errno($ch), curl_error($ch), $url)
            );
        }

        curl_close($ch);
        unset($ch);

        return $result;
    }
}


text:
using System;

namespace VimeoDotNet.Models
{
    /// <summary>
    /// Video stats
    /// </summary>
    [Serializable]
    public class VideoStats
    {
        /// <summary>
        /// Plays
        /// </summary>
        public int? plays { get; set; }
        /// <summary>
        /// Likes
        /// </summary>
        public int? likes { get; set; }
        /// <summary>
        /// Comments
        /// </summary>
        public int? comments { get; set; }
    }
}


text:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace Steam4NET
{

	public enum EStreamLauncherResult : int
	{
	};

}


text:
using System.Collections.Immutable;
using System.Globalization;
using System.Text.RegularExpressions;

using Microsoft.Recognizers.Definitions.Italian;
using Microsoft.Recognizers.Text.Number.Italian;

namespace Microsoft.Recognizers.Text.NumberWithUnit.Italian
{
    public abstract class ItalianNumberWithUnitExtractorConfiguration : INumberWithUnitExtractorConfiguration
    {
        protected ItalianNumberWithUnitExtractorConfiguration(CultureInfo ci)
        {
            this.CultureInfo = ci;
            this.UnitNumExtractor = new NumberExtractor();
            this.BuildPrefix = NumbersWithUnitDefinitions.BuildPrefix;
            this.BuildSuffix = NumbersWithUnitDefinitions.BuildSuffix;
            this.ConnectorToken = NumbersWithUnitDefinitions.ConnectorToken;
            this.CompoundUnitConnectorRegex = new Regex(NumbersWithUnitDefinitions.CompoundUnitConnectorRegex, RegexOptions.IgnoreCase);
        }

        public abstract string ExtractType { get; }

        public CultureInfo CultureInfo { get; }

        public IExtractor UnitNumExtractor { get; }

        public string BuildPrefix { get; }

        public string BuildSuffix { get; }

        public string ConnectorToken { get; }

        public Regex CompoundUnitConnectorRegex { get; set; }

        public abstract ImmutableDictionary<string, string> SuffixList { get; }

        public abstract ImmutableDictionary<string, string> PrefixList { get; }

        public abstract ImmutableList<string> AmbiguousUnitList { get; }
    }
}


text:
	<hc-pie-chart title="In-flight Sales Summary" data="foodData" isevent="true" callback-fn="changeData(arg1)">Placeholder for pie chart
	</hc-pie-chart>
	<hc-pie-chart title="Itemwise Sales Summary" data="fullperishabledata" >Placeholder for sub pie chart</hc-pie-chart>
	<hc-stack-chart title="Itemwise Stock Summary" data="fullperishabledata" >Placeholder for sub pie chart</hc-stack-chart>
	<hc-column-chart></hc-column-chart>


text:
package dotty.tools.dotc
package transform

import core._
import dotty.tools.dotc.transform.MegaPhase._
import Flags._
import Contexts._
import Symbols._
import dotty.tools.dotc.ast.tpd
import reporting._

import dotty.tools.dotc.transform.SymUtils._

/** A transformer that check that requirements of Static fields\methods are implemented:
  *  1. Only objects can have members annotated with `@static`
  *  2. The fields annotated with `@static` should precede any non-`@static` fields.
  *     This ensures that we do not introduce surprises for users in initialization order.
  *  3. If a member `foo` of an `object C` is annotated with `@static`,
  *     the companion class `C` is not allowed to define term members with name `foo`.
  *  4. If a member `foo` of an `object C` is annotated with `@static`, the companion class `C`
  *     is not allowed to inherit classes that define a term member with name `foo`.
  *  5. Only `@static` methods and vals are supported in companions of traits.
  *     Java8 supports those, but not vars, and JavaScript does not have interfaces at all.
  *  6. `@static` Lazy vals are currently unsupported.
  */
class CheckStatic extends MiniPhase {
  import ast.tpd._

  override def phaseName: String = CheckStatic.name

  override def description: String = CheckStatic.description

  override def transformTemplate(tree: tpd.Template)(using Context): tpd.Tree = {
    val defns = tree.body.collect{case t: ValOrDefDef => t}
    var hadNonStaticField = false
    for (defn <- defns)
      if (defn.symbol.isScalaStatic) {
        if (!ctx.owner.isStaticOwner)
          report.error(StaticFieldsOnlyAllowedInObjects(defn.symbol), defn.srcPos)
          defn.symbol.resetFlag(JavaStatic)

        if (defn.isInstanceOf[ValDef] && hadNonStaticField)
          report.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.srcPos)

        val companion = ctx.owner.companionClass
        def clashes = companion.asClass.membersNamed(defn.name)

        if (!companion.exists)
          report.error(MissingCompanionForStatic(defn.symbol), defn.srcPos)
        else if (clashes.exists)
          report.error(MemberWithSameNameAsStatic(), defn.srcPos)
        else if (defn.symbol.is(Flags.Mutable) && companion.is(Flags.Trait))
          report.error(TraitCompanionWithMutableStatic(), defn.srcPos)
        else if (defn.symbol.is(Flags.Lazy))
          report.error(LazyStaticField(), defn.srcPos)
        else if (defn.symbol.allOverriddenSymbols.nonEmpty)
          report.error(StaticOverridingNonStaticMembers(), defn.srcPos)
      }
      else hadNonStaticField = hadNonStaticField || defn.isInstanceOf[ValDef]

    tree
  }
}

object CheckStatic {
  val name: String = "checkStatic"
  val description: String = "check restrictions that apply to @static members"
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Datatable extends CI_Controller {

	public function __construct()
	{
        parent::__construct();
		// Set Property
		$this->title = 'Datatable';
    }

	public function index()
	{
		$data['title'] = $this->title;
		$this->load->view('datatable',$data);
	}

}


text:
<?php

namespace ABC\LoginBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ABCLoginBundle extends Bundle
{
}


text:
<?php

namespace App\Repository;

use App\Entity\Tweet;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class TweetRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Tweet::class);
    }
}