text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 com.cloud.hypervisor.vmware.mo;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.utils.ActionDelegate;
import com.cloud.utils.Pair;
import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
import com.cloud.utils.cisco.n1kv.vsm.PolicyMap;
import com.cloud.utils.cisco.n1kv.vsm.PortProfile;
import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.OperationType;
import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.vmware.vim25.BoolPolicy;
import com.vmware.vim25.DVPortgroupConfigInfo;
import com.vmware.vim25.DVSTrafficShapingPolicy;
import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.HostNetworkTrafficShapingPolicy;
import com.vmware.vim25.HostPortGroupSpec;
import com.vmware.vim25.HostVirtualSwitch;
import com.vmware.vim25.HttpNfcLeaseDeviceUrl;
import com.vmware.vim25.HttpNfcLeaseInfo;
import com.vmware.vim25.HttpNfcLeaseState;
import com.vmware.vim25.LongPolicy;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.OvfCreateImportSpecParams;
import com.vmware.vim25.OvfCreateImportSpecResult;
import com.vmware.vim25.OvfFileItem;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
import com.vmware.vim25.VirtualLsiLogicController;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineFileInfo;
import com.vmware.vim25.VirtualMachineVideoCard;
import com.vmware.vim25.VirtualSCSISharing;

public class HypervisorHostHelper {
    private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class);
    private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600;
    private static final String s_policyNamePrefix = "cloud.policy.";

    // make vmware-base loosely coupled with cloud-specific stuff, duplicate VLAN.UNTAGGED constant here
    private static final String UNTAGGED_VLAN_NAME = "untagged";

	public static VirtualMachineMO findVmFromObjectContent(VmwareContext context,
		ObjectContent[] ocs, String name) {

		if(ocs != null && ocs.length > 0) {
			for(ObjectContent oc : ocs) {
				DynamicProperty prop = oc.getPropSet(0);
				assert(prop != null);
				if(prop.getVal().toString().equals(name))
					return new VirtualMachineMO(context, oc.getObj());
			}
		}
		return null;
	}

	public static ManagedObjectReference findDatastoreWithBackwardsCompatibility(VmwareHypervisorHost hyperHost, String uuidName) throws Exception {
	    ManagedObjectReference morDs = hyperHost.findDatastore(uuidName.replace("-", ""));
	    if(morDs == null)
	        morDs = hyperHost.findDatastore(uuidName);

	    return morDs;
	}

	public static DatastoreMO getHyperHostDatastoreMO(VmwareHypervisorHost hyperHost, String datastoreName) throws Exception {
		ObjectContent[] ocs = hyperHost.getDatastorePropertiesOnHyperHost(new String[] { "name"} );
		if(ocs != null && ocs.length > 0) {
    		for(ObjectContent oc : ocs) {
		        DynamicProperty[] objProps = oc.getPropSet();
		        if(objProps != null) {
		        	for(DynamicProperty objProp : objProps) {
		        		if(objProp.getVal().toString().equals(datastoreName))
		        			return new DatastoreMO(hyperHost.getContext(), oc.getObj());
		        	}
		        }
    		}
		}
		return null;
	}

	public static String getPublicNetworkNamePrefix(String vlanId) {
	    if (UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
	        return "cloud.public.untagged";
	    } else {
	        return "cloud.public." + vlanId;
	    }
	}

	public static String composeCloudNetworkName(String prefix, String vlanId, Integer networkRateMbps, String vSwitchName) {
		StringBuffer sb = new StringBuffer(prefix);
		if(vlanId == null || UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId))
			sb.append(".untagged");
		else
			sb.append(".").append(vlanId);

		if(networkRateMbps != null && networkRateMbps.intValue() > 0)
			sb.append(".").append(String.valueOf(networkRateMbps));
		else
			sb.append(".0");
		sb.append(".").append(VersioningContants.PORTGROUP_NAMING_VERSION);
		sb.append("-").append(vSwitchName);

		return sb.toString();
	}

    public static Map<String, String> getValidatedVsmCredentials(VmwareContext context) throws Exception {
        Map<String, String> vsmCredentials = context.getStockObject("vsmcredentials");
        String msg;
        if (vsmCredentials == null || vsmCredentials.size() != 3) {
            msg = "Failed to retrieve required credentials of Nexus VSM from database.";
            s_logger.error(msg);
            throw new Exception(msg);
        }

        String vsmIp = vsmCredentials.containsKey("vsmip") ? vsmCredentials.get("vsmip") : null;
        String vsmUserName = vsmCredentials.containsKey("vsmusername") ? vsmCredentials.get("vsmusername") : null;
        String vsmPassword = vsmCredentials.containsKey("vsmpassword") ? vsmCredentials.get("vsmpassword") : null;
        if (vsmIp == null || vsmIp.isEmpty() || vsmUserName == null || vsmUserName.isEmpty() || vsmPassword == null
                || vsmPassword.isEmpty()) {
            msg = "Detected invalid credentials for Nexus 1000v.";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        return vsmCredentials;
    }

    public static void createPortProfile(VmwareContext context, String ethPortProfileName, String networkName,
            Integer vlanId, Integer networkRateMbps, long peakBandwidth, long burstSize) throws Exception {
        Map<String, String> vsmCredentials = getValidatedVsmCredentials(context);
        String vsmIp = vsmCredentials.get("vsmip");
        String vsmUserName = vsmCredentials.get("vsmusername");
        String vsmPassword = vsmCredentials.get("vsmpassword");
        String msg;

        NetconfHelper netconfClient;
        try {
            s_logger.info("Connecting to Nexus 1000v: " + vsmIp);
            netconfClient = new NetconfHelper(vsmIp, vsmUserName, vsmPassword);
            s_logger.info("Successfully connected to Nexus 1000v : " + vsmIp);
        } catch (CloudRuntimeException e) {
            msg = "Failed to connect to Nexus 1000v " + vsmIp + " with credentials of user " + vsmUserName
                    + ". Exception: " + e.toString();
            s_logger.error(msg);
            throw new CloudRuntimeException(msg);
        }

        String policyName = s_policyNamePrefix;
        int averageBandwidth = 0;
        if (networkRateMbps != null) {
            averageBandwidth = networkRateMbps.intValue();
            policyName += averageBandwidth;
        }

        try {
            // TODO(sateesh): Change the type of peakBandwidth & burstRate in
            // PolicyMap to long.
            if (averageBandwidth > 0) {
                s_logger.debug("Adding policy map " + policyName);
                netconfClient.addPolicyMap(policyName, averageBandwidth, (int) peakBandwidth, (int) burstSize);
            }
        } catch (CloudRuntimeException e) {
            msg = "Failed to add policy map of " + policyName + " with parameters " + "committed rate = "
                    + averageBandwidth + "peak bandwidth = " + peakBandwidth + "burst size = " + burstSize
                    + ". Exception: " + e.toString();
            s_logger.error(msg);
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            throw new CloudRuntimeException(msg);
        }

        List<Pair<OperationType, String>> params = new ArrayList<Pair<OperationType, String>>();
        if (vlanId != null) {
            // No need to update ethernet port profile for untagged vlans
            params.add(new Pair<OperationType, String>(OperationType.addvlanid, vlanId.toString()));
            try {
                s_logger.info("Updating Ethernet port profile " + ethPortProfileName + " with VLAN " + vlanId);
                netconfClient.updatePortProfile(ethPortProfileName, SwitchPortMode.trunk, params);
                s_logger.info("Added " + vlanId + " to Ethernet port profile " + ethPortProfileName);
            } catch (CloudRuntimeException e) {
                msg = "Failed to update Ethernet port profile " + ethPortProfileName + " with VLAN " + vlanId
                        + ". Exception: " + e.toString();
                s_logger.error(msg);
                if(netconfClient != null) {
                	netconfClient.disconnect();
                	s_logger.debug("Disconnected Nexus 1000v session.");
                }
                throw new CloudRuntimeException(msg);
            }
        }

        try {
            if (vlanId == null) {
                s_logger.info("Adding port profile configured over untagged VLAN.");
                netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, 0);
            } else {
                s_logger.info("Adding port profile configured over VLAN : " + vlanId.toString());
                netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, vlanId.intValue());
            }
        } catch (CloudRuntimeException e) {
            msg = "Failed to add vEthernet port profile " + networkName + "." + ". Exception: " + e.toString();
            s_logger.error(msg);
            if(netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            throw new CloudRuntimeException(msg);
        }

        try {
            if (averageBandwidth > 0) {
                s_logger.info("Associating policy map " + policyName + " with port profile " + networkName + ".");
                netconfClient.attachServicePolicy(policyName, networkName);
            }
        }
        catch(CloudRuntimeException e) {
            msg = "Failed to associate policy map " + policyName + " with port profile " + networkName
                    + ". Exception: " + e.toString();
            s_logger.error(msg);
            throw new CloudRuntimeException(msg);
        } finally {
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
        }
    }

    public static void updatePortProfile(VmwareContext context, String ethPortProfileName, String vethPortProfileName,
            Integer vlanId, Integer networkRateMbps, long peakBandwidth, long burstRate) throws Exception {
        NetconfHelper netconfClient = null;
        Map<String, String> vsmCredentials = getValidatedVsmCredentials(context);
        String vsmIp = vsmCredentials.get("vsmip");
        String vsmUserName = vsmCredentials.get("vsmusername");
        String vsmPassword = vsmCredentials.get("vsmpassword");

        String msg;
        try {
            netconfClient = new NetconfHelper(vsmIp, vsmUserName, vsmPassword);
        } catch (CloudRuntimeException e) {
            msg = "Failed to connect to Nexus 1000v " + vsmIp + " with credentials of user " + vsmUserName
                    + ". Exception: " + e.toString();
            s_logger.error(msg);
            throw new CloudRuntimeException(msg);
        }

        PortProfile portProfile = netconfClient.getPortProfileByName(vethPortProfileName);
        int averageBandwidth = 0;
        String policyName = s_policyNamePrefix;
        if (networkRateMbps != null) {
            averageBandwidth = networkRateMbps.intValue();
            policyName += averageBandwidth;
        }

        if (averageBandwidth > 0) {
            PolicyMap policyMap = netconfClient.getPolicyMapByName(portProfile.inputPolicyMap);
            if (policyMap.committedRate == averageBandwidth && policyMap.peakRate == peakBandwidth
                    && policyMap.burstRate == burstRate) {
                s_logger.debug("Detected that policy map is already applied to port profile " + vethPortProfileName);
                if (netconfClient != null) {
                    netconfClient.disconnect();
                    s_logger.debug("Disconnected Nexus 1000v session.");
                }
                return;
            } else {
                try {
                    // TODO(sateesh): Change the type of peakBandwidth &
                    // burstRate in PolicyMap to long.
                    s_logger.info("Adding policy map " + policyName);
                    netconfClient.addPolicyMap(policyName, averageBandwidth, (int) peakBandwidth, (int) burstRate);
                } catch (CloudRuntimeException e) {
                    msg = "Failed to add policy map of " + policyName + " with parameters " + "committed rate = "
                            + averageBandwidth + "peak bandwidth = " + peakBandwidth + "burst size = " + burstRate
                            + ". Exception: " + e.toString();
                    s_logger.error(msg);
                    if (netconfClient != null) {
                        netconfClient.disconnect();
                        s_logger.debug("Disconnected Nexus 1000v session.");
                    }
                    throw new CloudRuntimeException(msg);
                }

                try {
                    s_logger.info("Associating policy map " + policyName + " with port profile " + vethPortProfileName
                            + ".");
                    netconfClient.attachServicePolicy(policyName, vethPortProfileName);
                } catch (CloudRuntimeException e) {
                    msg = "Failed to associate policy map " + policyName + " with port profile " + vethPortProfileName
                            + ". Exception: " + e.toString();
                    s_logger.error(msg);
                    if (netconfClient != null) {
                        netconfClient.disconnect();
                        s_logger.debug("Disconnected Nexus 1000v session.");
                    }
                    throw new CloudRuntimeException(msg);
                }
            }
        }

        if (vlanId == null) {
            s_logger.info("Skipping update operation over ethernet port profile " + ethPortProfileName
                    + " for untagged VLAN.");
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            return;
        }

        String currentVlan = portProfile.vlan;
        String newVlan = Integer.toString(vlanId.intValue());
        if (currentVlan.equalsIgnoreCase(newVlan)) {
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            return;
        }

        List<Pair<OperationType, String>> params = new ArrayList<Pair<OperationType, String>>();
        params.add(new Pair<OperationType, String>(OperationType.addvlanid, newVlan));
        try {
            s_logger.info("Updating vEthernet port profile with VLAN " + vlanId.toString());
            netconfClient.updatePortProfile(ethPortProfileName, SwitchPortMode.trunk, params);
        } catch (CloudRuntimeException e) {
            msg = "Failed to update ethernet port profile " + ethPortProfileName + " with parameters "
                    + params.toString() + ". Exception: " + e.toString();
            s_logger.error(msg);
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            throw new CloudRuntimeException(msg);
        }

        try {
            netconfClient.updatePortProfile(vethPortProfileName, SwitchPortMode.access, params);
        } catch (CloudRuntimeException e) {
            msg = "Failed to update vEthernet port profile " + vethPortProfileName + " with parameters "
                    + params.toString() + ". Exception: " + e.toString();
            s_logger.error(msg);
            if (netconfClient != null) {
                netconfClient.disconnect();
                s_logger.debug("Disconnected Nexus 1000v session.");
            }
            throw new CloudRuntimeException(msg);
        }
    }

	/**
	 * @param ethPortProfileName
	 * @param namePrefix
	 * @param hostMo
	 * @param vlanId
	 * @param networkRateMbps
	 * @param networkRateMulticastMbps
	 * @param timeOutMs
	 * @return
	 * @throws Exception
	 */

    public static Pair<ManagedObjectReference, String> prepareNetwork(String ethPortProfileName, String namePrefix,
            HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs)
            throws Exception {
        ManagedObjectReference morNetwork = null;
        VmwareContext context = hostMo.getContext();
        ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter();
        DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);

        ManagedObjectReference morEthernetPortProfile = dataCenterMo.getDvPortGroupMor(ethPortProfileName);

        if (morEthernetPortProfile == null) {
            String msg = "Unable to find Ethernet port profile " + ethPortProfileName;
            s_logger.error(msg);
            throw new Exception(msg);
        }
        else {
            s_logger.info("Found Ethernet port profile " + ethPortProfileName);
        }

        boolean createGCTag = false;
        String networkName;
        Integer vid = null;

        if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
            createGCTag = true;
            vid = Integer.parseInt(vlanId);
        }

        networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, ethPortProfileName);

        // TODO(sateesh): Enable this for VMware DVS.
//        DVSTrafficShapingPolicy shapingPolicy = null;
//        if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
//            shapingPolicy = new DVSTrafficShapingPolicy();
//            BoolPolicy isEnabled = new BoolPolicy();
//            LongPolicy averageBandwidth = new LongPolicy();
//            LongPolicy peakBandwidth = new LongPolicy();
//            LongPolicy burstSize = new LongPolicy();
//
//            isEnabled.setValue(true);
//            averageBandwidth.setValue((long) networkRateMbps.intValue() * 1024L * 1024L);
//            // We chose 50% higher allocation than average bandwidth.
//            // TODO(sateesh): Also let user specify the peak coefficient
//            peakBandwidth.setValue((long) (averageBandwidth.getValue() * 1.5));
//            // TODO(sateesh): Also let user specify the burst coefficient
//            burstSize.setValue((long) (5 * averageBandwidth.getValue() / 8));
//
//            shapingPolicy.setEnabled(isEnabled);
//            shapingPolicy.setAverageBandwidth(averageBandwidth);
//            shapingPolicy.setPeakBandwidth(peakBandwidth);
//            shapingPolicy.setBurstSize(burstSize);
//        }
        DVPortgroupConfigInfo spec = dataCenterMo.getDvPortGroupSpec(networkName);
        long averageBandwidth = 0L;
        if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
            averageBandwidth = (long) (networkRateMbps.intValue() * 1024L * 1024L);
        }
        // We chose 50% higher allocation than average bandwidth.
        // TODO(sateesh): Also let user specify the peak coefficient
        long peakBandwidth = (long) (averageBandwidth * 1.5);
        // TODO(sateesh): Also let user specify the burst coefficient
        long burstSize = 5 * averageBandwidth / 8;

        boolean bWaitPortGroupReady = false;
        if (!dataCenterMo.hasDvPortGroup(networkName)) {
            s_logger.info("Port profile " + networkName + " not found.");
            createPortProfile(context, ethPortProfileName, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
            bWaitPortGroupReady = true;
        } else {
            s_logger.info("Port profile " + networkName + " found.");
            bWaitPortGroupReady = true;
            updatePortProfile(context, ethPortProfileName, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
        }
        // Wait for dvPortGroup on vCenter
        if(bWaitPortGroupReady)
            morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs);
        else
            morNetwork = dataCenterMo.getDvPortGroupMor(networkName);
        if (morNetwork == null) {
            String msg = "Failed to create guest network " + networkName;
            s_logger.error(msg);
            throw new Exception(msg);
        }

        if(createGCTag) {
            NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
            networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true");
            s_logger.debug("Added custom field : " + CustomFieldConstants.CLOUD_GC_DVP);
        }

        return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
    }

    private static ManagedObjectReference waitForDvPortGroupReady(
			DatacenterMO dataCenterMo, String dvPortGroupName, long timeOutMs) throws Exception {
		ManagedObjectReference morDvPortGroup = null;

		// if DvPortGroup is just created, we may fail to retrieve it, we
		// need to retry
		long startTick = System.currentTimeMillis();
		while (System.currentTimeMillis() - startTick <= timeOutMs) {
			morDvPortGroup = dataCenterMo.getDvPortGroupMor(dvPortGroupName);
			if (morDvPortGroup != null) {
				break;
			}

			s_logger.info("Waiting for dvPortGroup " + dvPortGroupName + " to be ready");
			Thread.sleep(1000);
		}
		return morDvPortGroup;
	}

    // This method would be used for VMware Distributed Virtual Switch.
	private static boolean isSpecMatch(DVPortgroupConfigInfo spec, Integer vid, DVSTrafficShapingPolicy shapingPolicy) {
		DVSTrafficShapingPolicy currentTrafficShapingPolicy;
		currentTrafficShapingPolicy = spec.getDefaultPortConfig().getInShapingPolicy();
		// TODO(sateesh): Extract and compare vendor specific configuration specification as well.
		// DistributedVirtualSwitchKeyedOpaqueBlob[] vendorSpecificConfig = spec.getVendorSpecificConfig();

		assert(currentTrafficShapingPolicy != null);

		LongPolicy averageBandwidth = currentTrafficShapingPolicy.getAverageBandwidth();
		LongPolicy burstSize = currentTrafficShapingPolicy.getBurstSize();
		LongPolicy peakBandwidth = currentTrafficShapingPolicy.getPeakBandwidth();
		BoolPolicy isEnabled = currentTrafficShapingPolicy.getEnabled();

		if(!isEnabled.getValue())
			return false;

		if(averageBandwidth != null && !averageBandwidth.equals(shapingPolicy.getAverageBandwidth())) {
			if(s_logger.isInfoEnabled()) {
				s_logger.info("Average bandwidth setting in shaping policy doesn't match with existing setting.");
			}
			return false;
		} else if(burstSize != null && !burstSize.equals(shapingPolicy.getBurstSize())) {
			if(s_logger.isInfoEnabled()) {
				s_logger.info("Burst size setting in shaping policy doesn't match with existing setting.");
			}
			return false;
		} else if(peakBandwidth != null && !peakBandwidth.equals(shapingPolicy.getPeakBandwidth())) {
			if(s_logger.isInfoEnabled()) {
				s_logger.info("Peak bandwidth setting in shaping policy doesn't match with existing setting.");
			}
			return false;
		}

		return true;
	}

	public static Pair<ManagedObjectReference, String> prepareNetwork(String vSwitchName, String namePrefix,
            HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps,
            long timeOutMs, boolean syncPeerHosts) throws Exception {

        HostVirtualSwitch vSwitch;
        vSwitch = hostMo.getHostVirtualSwitchByName(vSwitchName);

        if (vSwitch == null) {
            String msg = "Unable to find vSwitch" + vSwitchName;
            s_logger.error(msg);
            throw new Exception(msg);
        }

        boolean createGCTag = false;
        String networkName;
        Integer vid = null;

        if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
            createGCTag = true;
            vid = Integer.parseInt(vlanId);
        }

        networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, vSwitchName);

        HostNetworkTrafficShapingPolicy shapingPolicy = null;
        if(networkRateMbps != null && networkRateMbps.intValue() > 0) {
            shapingPolicy = new HostNetworkTrafficShapingPolicy();
            shapingPolicy.setEnabled(true);
            shapingPolicy.setAverageBandwidth((long)networkRateMbps.intValue()*1024L*1024L);

            //
            // TODO : people may have different opinion on how to set the following
            //

            // give 50% premium to peek
            shapingPolicy.setPeakBandwidth((long)(shapingPolicy.getAverageBandwidth()*1.5));

            // allow 5 seconds of burst transfer
            shapingPolicy.setBurstSize(5*shapingPolicy.getAverageBandwidth()/8);
        }

        boolean bWaitPortGroupReady = false;
        if (!hostMo.hasPortGroup(vSwitch, networkName)) {
            hostMo.createPortGroup(vSwitch, networkName, vid, shapingPolicy);
            bWaitPortGroupReady = true;
        } else {
            HostPortGroupSpec spec = hostMo.getPortGroupSpec(networkName);
            if(!isSpecMatch(spec, vid, shapingPolicy)) {
                hostMo.updatePortGroup(vSwitch, networkName, vid, shapingPolicy);
                bWaitPortGroupReady = true;
            }
        }

        ManagedObjectReference morNetwork;
        if(bWaitPortGroupReady)
            morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
        else
            morNetwork = hostMo.getNetworkMor(networkName);
        if (morNetwork == null) {
            String msg = "Failed to create guest network " + networkName;
            s_logger.error(msg);
            throw new Exception(msg);
        }

        if(createGCTag) {
            NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
            networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
        }

        if(syncPeerHosts) {
            ManagedObjectReference morParent = hostMo.getParentMor();
            if(morParent != null && morParent.getType().equals("ClusterComputeResource")) {
                // to be conservative, lock cluster
                GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.get_value());
                try {
                    if(lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
                        try {
                            ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getServiceUtil().getDynamicProperty(morParent, "host");
                            if(hosts != null) {
                                for(ManagedObjectReference otherHost: hosts) {
                                    if(!otherHost.get_value().equals(hostMo.getMor().get_value())) {
                                        HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
                                        try {
                                            if(s_logger.isDebugEnabled())
                                                s_logger.debug("Prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
                                            prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId, networkRateMbps, networkRateMulticastMbps, timeOutMs, false);
                                        } catch(Exception e) {
                                            s_logger.warn("Unable to prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
                                        }
                                    }
                                }
                            }
                        } finally {
                            lock.unlock();
                        }
                    } else {
                        s_logger.warn("Unable to lock cluster to prepare guest network, vlan: " + vlanId);
                    }
                } finally {
                    lock.releaseRef();
                }
            }
        }

        s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
        return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
    }

	private static boolean isSpecMatch(HostPortGroupSpec spec, Integer vlanId, HostNetworkTrafficShapingPolicy shapingPolicy) {
		// check VLAN configuration
		if(vlanId != null) {
			if(vlanId.intValue() != spec.getVlanId())
				return false;
		} else {
			if(spec.getVlanId() != 0)
				return false;
		}

		// check traffic shaping configuration
		HostNetworkTrafficShapingPolicy policyInSpec = null;
		if(spec.getPolicy() != null)
			policyInSpec = spec.getPolicy().getShapingPolicy();

		if(policyInSpec != null && shapingPolicy == null || policyInSpec == null && shapingPolicy != null)
			return false;

		if(policyInSpec == null && shapingPolicy == null)
			return true;

		// so far policyInSpec and shapingPolicy should both not be null
		if(policyInSpec.getEnabled() == null || !policyInSpec.getEnabled().booleanValue())
			return false;

		if(policyInSpec.getAverageBandwidth() == null || policyInSpec.getAverageBandwidth().longValue() != shapingPolicy.getAverageBandwidth().longValue())
			return false;

		if(policyInSpec.getPeakBandwidth() == null || policyInSpec.getPeakBandwidth().longValue() != shapingPolicy.getPeakBandwidth().longValue())
			return false;

		if(policyInSpec.getBurstSize() == null || policyInSpec.getBurstSize().longValue() != shapingPolicy.getBurstSize().longValue())
			return false;

		return true;
	}

	public static ManagedObjectReference waitForNetworkReady(HostMO hostMo,
			String networkName, long timeOutMs) throws Exception {

		ManagedObjectReference morNetwork = null;

		// if portGroup is just created, getNetwork may fail to retrieve it, we
		// need to retry
		long startTick = System.currentTimeMillis();
		while (System.currentTimeMillis() - startTick <= timeOutMs) {
			morNetwork = hostMo.getNetworkMor(networkName);
			if (morNetwork != null) {
				break;
			}

			s_logger.info("Waiting for network " + networkName + " to be ready");
			Thread.sleep(1000);
		}

		return morNetwork;
	}

	public static boolean createBlankVm(VmwareHypervisorHost host, String vmName,
		int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier,
		ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {

		if(s_logger.isInfoEnabled())
			s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB);

		// VM config basics
		VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
		vmConfig.setName(vmName);
		VmwareHelper.setBasicVmConfig(vmConfig, cpuCount, cpuSpeedMHz, cpuReservedMHz, memoryMB, memoryReserveMB, guestOsIdentifier, limitCpuUse);

		// Scsi controller
		VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
		scsiController.setSharedBus(VirtualSCSISharing.noSharing);
		scsiController.setBusNumber(0);
		scsiController.setKey(1);
		VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
		scsiControllerSpec.setDevice(scsiController);
		scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);

		VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
		DatastoreMO dsMo = new DatastoreMO(host.getContext(), morDs);
		fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
		vmConfig.setFiles(fileInfo);

		VirtualMachineVideoCard videoCard = new VirtualMachineVideoCard();
		videoCard.setControllerKey(100);
		videoCard.setUseAutoDetect(true);

		VirtualDeviceConfigSpec videoDeviceSpec = new VirtualDeviceConfigSpec();
		videoDeviceSpec.setDevice(videoCard);
		videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.add);

		vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec, videoDeviceSpec });
		if(host.createVm(vmConfig)) {
			VirtualMachineMO vmMo = host.findVmOnHyperHost(vmName);
			assert(vmMo != null);

			int ideControllerKey = -1;
			while(ideControllerKey < 0) {
				ideControllerKey = vmMo.tryGetIDEDeviceControllerKey();
				if(ideControllerKey >= 0)
					break;

				s_logger.info("Waiting for IDE controller be ready in VM: " + vmName);
				Thread.sleep(1000);
			}

			if(snapshotDirToParent) {
				String snapshotDir = String.format("/vmfs/volumes/%s/", dsMo.getName());

				s_logger.info("Switch snapshot working directory to " + snapshotDir + " for " + vmName);
				vmMo.setSnapshotDirectory(snapshotDir);

				// Don't have a good way to test if the VM is really ready for use through normal API after configuration file manipulation,
				// delay 3 seconds
				Thread.sleep(3000);
			}

			s_logger.info("Blank VM: " + vmName + " is ready for use");
			return true;
		}
		return false;
	}

	public static String resolveHostNameInUrl(DatacenterMO dcMo, String url) {

		s_logger.info("Resolving host name in url through vCenter, url: " + url);

		URI uri;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e) {
			s_logger.warn("URISyntaxException on url " + url);
			return url;
		}

		String host = uri.getHost();
		if(NetUtils.isValidIp(host)) {
			s_logger.info("host name in url is already in IP address, url: " + url);
			return url;
		}

		try {
			ManagedObjectReference morHost = dcMo.findHost(host);
			if(morHost != null) {
				HostMO hostMo = new HostMO(dcMo.getContext(), morHost);
				String managementPortGroupName;
				if(hostMo.getHostType() == VmwareHostType.ESXi)
					managementPortGroupName = (String)dcMo.getContext().getStockObject("manageportgroup");
				else
					managementPortGroupName = (String)dcMo.getContext().getStockObject("serviceconsole");

				VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(managementPortGroupName);
				if(summary == null) {
					s_logger.warn("Unable to resolve host name in url through vSphere, url: " + url);
					return url;
				}

				String hostIp = summary.getHostIp();

				try {
					URI resolvedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostIp, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());

					s_logger.info("url " + url + " is resolved to " + resolvedUri.toString() + " through vCenter");
					return resolvedUri.toString();
				} catch (URISyntaxException e) {
					assert(false);
					return url;
				}
			}
		} catch(Exception e) {
			s_logger.warn("Unexpected exception ", e);
		}

		return url;
	}

	public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption,
		ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {

		assert(morRp != null);

		OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
		importSpecParams.setHostSystem(morHost);
		importSpecParams.setLocale("US");
		importSpecParams.setEntityName(vmName);
		importSpecParams.setDeploymentOption("");
		importSpecParams.setDiskProvisioning(diskOption); // diskOption: thin, thick, etc
		importSpecParams.setPropertyMapping(null);

		String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath);
		VmwareContext context = host.getContext();
		OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(
			context.getServiceContent().getOvfManager(), ovfDescriptor, morRp,
			dsMo.getMor(), importSpecParams);

		if(ovfImportResult == null) {
			String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
				+ vmName + ", diskOption: " + diskOption;
			s_logger.error(msg);
			throw new Exception(msg);
		}

		DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
		ManagedObjectReference morLease = context.getService().importVApp(morRp,
			ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
		if(morLease == null) {
			String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
				+ vmName + ", diskOption: " + diskOption;
			s_logger.error(msg);
			throw new Exception(msg);
		}
		final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
		HttpNfcLeaseState state = leaseMo.waitState(
			new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
		try {
			if(state == HttpNfcLeaseState.ready) {
				final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
				File ovfFile = new File(ovfFilePath);

				HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
		        HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
		        long bytesAlreadyWritten = 0;

		        final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
		        try {
			        for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
			        	String deviceKey = deviceUrl.getImportKey();
			        	for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
			        		if (deviceKey.equals(ovfFileItem.getDeviceId())) {
			        			String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
			        			String urlToPost = deviceUrl.getUrl();
			        			urlToPost = resolveHostNameInUrl(dcMo, urlToPost);

		        			  	context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile,
		    			  			bytesAlreadyWritten, new ActionDelegate<Long> () {
									public void action(Long param) {
										progressReporter.reportProgress((int)(param * 100 / totalBytes));
									}
		    			  		});

		        			  	bytesAlreadyWritten += ovfFileItem.getSize();
		        			 }
			        	 }
			        }
		        } finally {
		        	progressReporter.close();
		        }
		        leaseMo.updateLeaseProgress(100);
			}
		} finally {
			leaseMo.completeLease();
		}
	}
}


text:
import simplejson as json
import os
import sys
import urlparse

import redis
from termcolor import colored

from sodatap import createCatalog, ResourceError

REDIS_URL = os.environ["REDIS_URL"]
REDIS_DB = 1
POOL = None

def storeResource(redisClient, resource):
  id = resource.getId()
  meanTimeDelta = resource.getMeanTimeDelta()
  isOverwrite = len(redisClient.keys("*:" + id)) == 1
  payload = {
    "type": resource.getStreamType(),
    "temporalField": resource.getTemporalIndex(),
    "jsonUrl": resource.getJsonUrl(),
    "fieldTypes": resource.getFieldMapping(),
    "meanTimeDelta": str(meanTimeDelta),
    "catalogEntry": resource.json()
  }
  if resource.hasMultipleSeries():
    payload["seriesId"] = resource.getSeriesIdentifier()
    # payload["seriesNames"] = resource.getSeriesNames()
  redisKey = resource.getStreamType() + ":" + id
  redisClient.set(redisKey, json.dumps(payload))
  color = "green"
  if isOverwrite:
    color = "blue"
  print colored(
    "  Stored %s stream \"%s\" (%s %s) by %s"
      % (resource.getStreamType(), resource.getName(), resource.getId(),
         resource.getDomain(), resource.getTemporalIndex()),
    color
  )

def saveAsSkipped(redisClient, resource):
  id = resource.getId()
  skipped = redisClient.get("meta:skipped")
  if skipped is None:
    skipped = {"skipped":[]}
  else:
    skipped = json.loads(skipped)
  skipped["skipped"].append(id)
  redisClient.set("meta:skipped", json.dumps(skipped))

def shouldProcess(redisClient, resource):
  id = resource.getId()
  skipped = redisClient.get("meta:skipped")
  if skipped is None:
    skipped = {"skipped":[]}
  else:
    skipped = json.loads(skipped)
  return id not in skipped["skipped"]

def deleteExistingResource(redisClient, resource):
  id = resource.getId()
  existing = redisClient.keys("*:" + id)
  for key in existing:
    print colored("  Deleting existing resource " + id + ".", "red")
    redisClient.delete(key)

def processResource(redisClient, resource):
  try:
    # If this is a not temporal stream, the function below will raise a
    # ResourceError
    resource.validate()
    storeResource(redisClient, resource)
  except ResourceError as e:
    deleteExistingResource(redisClient, resource)
    print colored(
      "  %s | %s | " % (resource.getName(), resource.getPermalink()),
      "yellow"
    ) + " " + colored(str(e), "magenta")
    saveAsSkipped(redisClient, resource)

def run(offset=0):
  redisUrl = urlparse.urlparse(REDIS_URL)
  redisClient = redis.Redis(
    host=redisUrl.hostname, port=redisUrl.port,
    db=REDIS_DB, password=redisUrl.password
  )
  count = offset
  catalog = createCatalog(offset=offset)

  for page in catalog:
    for resource in page:
      if shouldProcess(redisClient, resource):
        processResource(redisClient, resource)
      else:
        print "Skipped {}".format(resource.getId())
      count += 1
      if count % 10 == 0:
        keyCount = len(redisClient.keys("*"))
        percStored = float(keyCount) / float(count)
        print colored(
          "Inspected %i streams, stored %i temporal streams (%f)."
          % (count, keyCount, percStored),
          "cyan"
        )

if __name__ == "__main__":
  offset = 0
  if len(sys.argv) > 1:
    offset = int(sys.argv[1])
  run(offset)

redpajama_set_name: RedPajamaGithub


text:
module.exports = {

    renderCanvas: require('./DynamicBitmapTextCanvasRenderer'),
    renderWebGL: require('./DynamicBitmapTextWebGLRenderer')

};


text:
var http = require('http');

//Get information from an external API
var getExternalInfo =function(url, callback){
	http.get(url, function(response){

		var parts = [];
		//as data comes through add it to array
		response.on('data', function(part){
			parts.push(part);
		}).on('end', function() {
			//put all the buffers together into a JS
    		var body = JSON.parse(Buffer.concat(parts));
    		console.log(3);
    		callback(body);

    	});
	});
}
module.exports = getExternalInfo;


text:
<!DOCTYPE html>

		<title>three.js - software renderer</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">


text:
// Enable OpenCL C++ exceptions
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cassert>

#include "poclu.h"

static char
kernelSourceCode[] =
"kernel \n"
"void test_kernel(constant char *input,\n"
"                 __global char *output,\n"
"                 float a,\n"
"                 int b) {\n"
"    constant char* pos = input; \n"
"    __global char *outpos = output;\n"
"    while (*pos) {\n"
"        *(outpos++) = *(pos++);\n"
"    }\n"
"    *outpos = '\\0';\n"
"    output[1] = 'O'; \n"
"}\n";

int
main(void)
{
    const int OUTPUT_SIZE = 6;
    const char *input = "PING\0";
    char output[OUTPUT_SIZE];
    float a = 23456.0f;
    int b = 2000001;

    try {
        std::vector<cl::Platform> platformList;

        // Pick platform
        cl::Platform::get(&platformList);

        // Pick first platform
        cl_context_properties cprops[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};
        cl::Context context(CL_DEVICE_TYPE_ACCELERATOR, cprops);

        // Query the set of devices attached to the context
        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

        assert (devices.size() == 1);

        cl::Device device = devices.at(0);

        assert (device.getInfo<CL_DEVICE_NAME>() == "cellspu");

        a = poclu_bswap_cl_float (device(), a);
        b = poclu_bswap_cl_int (device(), b);

        // Create and program from source
        cl::Program::Sources sources(1, std::make_pair(kernelSourceCode, 0));
        cl::Program program(context, sources);

        // Build program
        program.build(devices);

        cl::Buffer inputBuffer = cl::Buffer(
            context,
            CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
            strlen (input), (void *) &input[0]);

        // Create buffer for that uses the host ptr C
        cl::Buffer outputBuffer = cl::Buffer(
            context,
            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
            OUTPUT_SIZE, (void *) &output[0]);

        // Create kernel object
        cl::Kernel kernel(program, "test_kernel");

        // Set kernel args
        kernel.setArg(0, inputBuffer);
        kernel.setArg(1, outputBuffer);
        kernel.setArg(2, a);
        kernel.setArg(3, b);

        // Create command queue
        cl::CommandQueue queue(context, devices[0], CL_QUEUE_PROFILING_ENABLE);

        cl::Event enqEvent;

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel,
            cl::NullRange,
            cl::NDRange(1),
            cl::NullRange,
            NULL, &enqEvent);

        cl::Event mapEvent;
        (int *) queue.enqueueMapBuffer(
            outputBuffer,
            CL_TRUE, // block
            CL_MAP_READ,
            0, OUTPUT_SIZE, NULL, &mapEvent);

        if (std::string(output) == "PONG")
            std::cout << "OK\n";
        else
            std::cerr << "FAIL, received: " << output << "\n";

        cl::Event unmapEvent;
        // Finally release our hold on accessing the memory
        queue.enqueueUnmapMemObject(
            outputBuffer,
            (void *) &output[0],
            NULL,
            &unmapEvent);

        queue.finish();

        assert (enqEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (mapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (unmapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

#if 0
        std::cerr << "exec time: "
                  << enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() -
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() << std::endl;
#endif

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

    }
    catch (cl::Error err) {
         std::cerr
             << "ERROR: "
             << err.what()
             << "("
             << err.err()
             << ")"
             << std::endl;

         return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}


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

public class MeshBuilder {

	private List<Vector3> m_Vertices = new List<Vector3>();
	public List<Vector3> Vertices { get { return m_Vertices; }}

	private List<Vector3> m_Normals = new List<Vector3>();
	public List<Vector3> Normals { get { return m_Normals; }}

	private List<Vector2> m_UVs = new List<Vector2>();
	public List<Vector2> UVs { get { return m_UVs; }}

	private List<Vector4> m_Tangents = new List<Vector4>();
	public List<Vector4> Tangents { get { return m_Tangents; }}

	private List<int> m_Indices = new List<int>();

	public void AddTriangle(int index0, int index1, int index2)
	{
		m_Indices.Add (index0);
		m_Indices.Add (index1);
		m_Indices.Add (index2);
	}

	public Mesh CreateMesh()
	{
		Mesh mesh = new Mesh ();

		mesh.vertices = m_Vertices.ToArray ();
		mesh.triangles = m_Indices.ToArray ();

		// Normals sao opcionais
		if (m_Normals.Count == m_Vertices.Count) {
			mesh.normals = m_Normals.ToArray();
		}

		// UVs sao opcionais
		if (m_UVs.Count == m_Vertices.Count) {
			mesh.uv = m_UVs.ToArray();
		}

		// Tangents sao opcionais
		if (m_Tangents.Count == m_Vertices.Count) {
			mesh.tangents = m_Tangents.ToArray();
		}

		mesh.RecalculateBounds ();

		return mesh;
	}

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_32.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml
Template File: sources-sinks-32.tmpl.cpp
*/
/*
 * @description
 * CWE: 762 Mismatched Memory Management Routines
 * BadSource:  Allocate data using new []
 * GoodSource: Allocate data using malloc()
 * Sinks:
 *    GoodSink: Deallocate data using delete []
 *    BadSink : Deallocate data using free()
 * Flow Variant: 32 Data flow using two pointers to the same value within the same function
 *
 * */

#include "std_testcase.h"

namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_32
{

#ifndef OMITBAD

void bad()
{
    int64_t * data;
    int64_t * *dataPtr1 = &data;
    int64_t * *dataPtr2 = &data;
    /* Initialize data*/
    data = NULL;
    {
        int64_t * data = *dataPtr1;
        /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
        data = new int64_t[100];
        *dataPtr1 = data;
    }
    {
        int64_t * data = *dataPtr2;
        /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may
         * require a call to delete [] to deallocate the memory */
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
    int64_t * data;
    int64_t * *dataPtr1 = &data;
    int64_t * *dataPtr2 = &data;
    /* Initialize data*/
    data = NULL;
    {
        int64_t * data = *dataPtr1;
        /* FIX: Allocate memory from the heap using malloc() */
        data = (int64_t *)malloc(100*sizeof(int64_t));
        *dataPtr1 = data;
    }
    {
        int64_t * data = *dataPtr2;
        /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may
         * require a call to delete [] to deallocate the memory */
        free(data);
    }
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    int64_t * data;
    int64_t * *dataPtr1 = &data;
    int64_t * *dataPtr2 = &data;
    /* Initialize data*/
    data = NULL;
    {
        int64_t * data = *dataPtr1;
        /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
        data = new int64_t[100];
        *dataPtr1 = data;
    }
    {
        int64_t * data = *dataPtr2;
        /* FIX: Deallocate the memory using delete [] */
        delete [] data;
    }
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_32; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using WOSI.CallButler.Data;
using WOSI.CallButler.Data.DataProviders;
using WOSI.CallButler.Data.DataProviders.Local;
using CallButler.Telecom;
using CallButler.Service.Services;
using WOSI.Utilities;
using NET.Remoting;
using System.IO;
using Microsoft.Win32;

namespace CallButler.Service
{
    internal partial class CallButlerService : ServiceBase
    {
        private CallButlerDataProviderBase dataProvider;
        private ManagementInterfaceService managementInterfaceServer;
        private TcpRemotingServer tcpManagementDataServer;
        private PipeRemotingServer pipeManagementDataServer;
        //private KinesisService emService;
        private TelecomProviderBase telecomProvider;
        private ScriptService scriptService;
        private PBXRegistrarService pbxRegistrar;
        //private ExtensionStateService extStateService;
        private VoicemailMailerService vmMailerService;
        private VoicemailService vmService;

        public static DialPlanManagerService DialPlanManager;

        private Utilities.PluginManagement.PluginManager pluginManager;
        private string currentIP;

        private string lastErrorMessage;

        private delegate void ClearMenuItemsDelagate();
        private ClearMenuItemsDelagate clearMenuItemsHandler;

        public CallButlerService()
        {
            // Load our private label file
            Service.Services.PrivateLabelService.LoadPrivateLabelFile();

            clearMenuItemsHandler = new ClearMenuItemsDelagate(ClearMenuItemsProc);

            System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
            Version appVersion = a.GetName().Version;
            string appVersionString = appVersion.ToString();

            currentIP = WOSI.Utilities.NetworkUtils.GetCurrentIpAddress();

            InitializeComponent();

            LoadStartupOption();
            mnuLoadOnStartup.Click += new EventHandler(mnuLoadOnStartup_Click);

            mnuManageCallButler.Click += new EventHandler(mnuManageCallButler_Click);
            mnuManageCallButler.Image = Properties.Resources.nut_and_bolt_16;

            mnuExit.Click += new EventHandler(mnuExit_Click);
            mnuExit.Image = Properties.Resources.exit_16;

            mnuPlugins.Image = Properties.Resources.gear_connection_16;

            // Set our default language
            if (Properties.Settings.Default.DefaultLanguage == null || Properties.Settings.Default.DefaultLanguage.Length == 0)
            {
                Properties.Settings.Default.DefaultLanguage = WOSI.Utilities.GlobalizationUtils.GetTopParentCulture(System.Threading.Thread.CurrentThread.CurrentCulture).IetfLanguageTag;
                Properties.Settings.Default.Save();
            }

            LoggingService.NewLogEntry += new EventHandler<LogEntryEventArgs>(LoggingService_NewLogEntry);
        }

        private void LoadStartupOption()
        {
            /*RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            if (regKey != null)
            {
                if (regKey.GetValue(Properties.Settings.Default.ProductDescription) == null)
                {
                    mnuLoadOnStartup.CheckState = CheckState.Unchecked;
                }
                else
                {
                    mnuLoadOnStartup.CheckState = CheckState.Checked;
                }
            }*/
        }

        void mnuLoadOnStartup_Click(object sender, EventArgs e)
        {
            /*RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);

            if (mnuLoadOnStartup.Checked)
            {
                mnuLoadOnStartup.CheckState = CheckState.Checked;
                regKey.SetValue(Properties.Settings.Default.ProductDescription, Application.ExecutablePath + " -a");
            }
            else
            {
                if (regKey.GetValue(Properties.Settings.Default.ProductDescription) != null)
                {
                    mnuLoadOnStartup.CheckState = CheckState.Unchecked;
                    regKey.DeleteValue(Properties.Settings.Default.ProductDescription);
                }
            }*/
        }

        #region Menu Events
        void mnuManageCallButler_Click(object sender, EventArgs e)
        {
            string callButlerManagerPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), Properties.Settings.Default.CallButlerManagementAppLocation);

            if (File.Exists(callButlerManagerPath))
            {
                System.Diagnostics.Process.Start(callButlerManagerPath);
            }
            else
            {
                MessageBox.Show(Services.PrivateLabelService.ReplaceProductName("The CallButler management application does not appear to be installed on this computer.\r\nPlease run the CallButler setup program again to install it."), Services.PrivateLabelService.ReplaceProductName("CallButler Manager Not Found"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        void mnuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        #region Public Properties
        public bool NotifyIconVisible
        {
            get
            {
                return notifyIcon.Visible;
            }
            set
            {
                notifyIcon.Visible = value;
            }
        }
        #endregion

        #region Public Service Control Methods
        private void CreateManagementChannels()
        {
            // Create our management interface server
            managementInterfaceServer = new ManagementInterfaceService();
            managementInterfaceServer.Initialize(this, null, null, null, null, null, null);

            if (Properties.Settings.Default.EnableRemoteManagement)
            {
                // Create our remoting object for our management server
                tcpManagementDataServer = new TcpRemotingServer("CallButler TCP Management Server (" + Properties.Settings.Default.ProductID + ")", "CallButlerManagementServer", Properties.Settings.Default.ManagementServicePort, (MarshalByRefObject)managementInterfaceServer);
                tcpManagementDataServer.OnAuthentication += new EventHandler<NET.Remoting.Channels.AuthenticationEventArgs>(managementDataServer_OnAuthentication);
                tcpManagementDataServer.OnManagementAllowed += new EventHandler<NET.Remoting.Channels.ManagementAllowedEventArgs>(managementDataServer_OnManagementAllowed);
            }

            pipeManagementDataServer = new PipeRemotingServer("CallButler PIPE Management Server (" + Properties.Settings.Default.ProductID + ")", "CallButlerManagementServer", Properties.Settings.Default.ManagementServicePort, (MarshalByRefObject)managementInterfaceServer);
            pipeManagementDataServer.OnAuthentication += new EventHandler<NET.Remoting.Channels.AuthenticationEventArgs>(managementDataServer_OnAuthentication);
            pipeManagementDataServer.OnManagementAllowed += new EventHandler<NET.Remoting.Channels.ManagementAllowedEventArgs>(managementDataServer_OnManagementAllowed);
            pipeManagementDataServer.StartServer();
        }

        private void Initialize()
        {
            if (Properties.Settings.Default.ProductID != null && Properties.Settings.Default.ProductID.Length > 0)
            {
                lastErrorMessage = null;

                notifyIcon.Text = Properties.Settings.Default.ProductDescription;

                // Load our application permissions
                //Licensing.Management.AppPermissions.LoadPermissionData(Properties.Settings.Default.ProductID, Properties.Resources.Permissions);

                // Load our dataprovider
                System.Collections.Specialized.NameValueCollection settings = new System.Collections.Specialized.NameValueCollection();

                switch (Properties.Settings.Default.DataProviderType)
                {
                    case LocalCallButlerDataProviderTypes.XmlDataProvider:
                        // Create our settings
                        settings["RootDataDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.XmlDataRootDirectory);
                        settings["RootGreetingSoundDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.GreetingSoundRootDirectory);

                        dataProvider = new CallButlerXmlDataProvider();
                        dataProvider.Connect(settings);
                        break;
                    /*case LocalCallButlerDataProviderTypes.SqlServerDataProvider:

                        settings["RootDataDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.XmlDataRootDirectory);
                        settings["RootGreetingSoundDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.GreetingSoundRootDirectory);
                        settings["ConnectionString"] = Properties.Settings.Default.SqlConnectionString;

                        dataProvider = new CallButlerSQLServerDataProvider();
                        dataProvider.Connect(settings);
                        break;*/
                }

                /*if (Properties.Settings.Default.EnableKinesisServer)
                {
                    extStateService = new ExtensionStateService(dataProvider);
                }*/

                // Create our telecom provider
                int lineCount = /*Math.Min(*/ Properties.Settings.Default.LineCount; /*, Licensing.Management.AppPermissions.StatGetPermissionScalar("MaxLineCount"));*/

                switch (Properties.Settings.Default.TelecomProviderType)
                {
                    case TelecomProviders.inTELIPhoneTelecomProvider:
                        {
                            telecomProvider = new inTELIPhoneTelecomProvider(mnuServiceOptions, notifyIcon, lineCount, Properties.Settings.Default.UseStun, Properties.Settings.Default.StunServer, Properties.Settings.Default.SipPort, Properties.Settings.Default.UseInternalAddressForSIPMessages);

                            // Register all of our profiles
                            //if (Licensing.Management.AppPermissions.StatIsPermitted("Providers"))
                            //{
                                WOSI.CallButler.Data.CallButlerDataset.ProvidersDataTable providers = dataProvider.GetProviders(Properties.Settings.Default.CustomerID);

                                foreach (WOSI.CallButler.Data.CallButlerDataset.ProvidersRow provider in providers)
                                {
                                    if (provider.IsEnabled)
                                    {
                                        telecomProvider.Register(provider.ProviderID, provider);
                                    }
                                }
                            //}

                            // Start our PBX registrar engine
                            if (Properties.Settings.Default.EnablePBX /*&& Licensing.Management.AppPermissions.StatIsPermitted("PBX.Registrar")*/)
                            {
                                pbxRegistrar = new PBXRegistrarService(telecomProvider, dataProvider/*, extStateService*/);
                            }

                            break;
                        }
                }

                // Initialize our codecs
                if (Properties.Settings.Default.AudioCodecs != null && Properties.Settings.Default.AudioCodecs.Length > 0)
                    telecomProvider.SetAudioCodecs(Properties.Settings.Default.AudioCodecs);

                // Create our plugin manager object
                pluginManager = new Utilities.PluginManagement.PluginManager();

                // Create our voicemail mailer service
                vmMailerService = new VoicemailMailerService();

                // Initialize our voicemail service
                vmService = new VoicemailService(dataProvider, pbxRegistrar, pluginManager, vmMailerService);

                // Create our script server
                scriptService = new ScriptService(telecomProvider, dataProvider, vmService, vmMailerService, pluginManager, pbxRegistrar/*, extStateService*/);

                // Load our plugins
                CallButler.Service.Plugin.CallButlerServiceContext serviceContext = new CallButler.Service.Plugin.CallButlerServiceContext(scriptService);
                pluginManager.LoadPlugins(WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.PluginDirectory), "*.dll", true, typeof(CallButler.Service.Plugin.CallButlerServicePlugin));

                foreach (CallButler.Service.Plugin.CallButlerServicePlugin plugin in pluginManager.Plugins)
                {
                    try
                    {
                        plugin.Load(serviceContext);
                    }
                    catch
                    {
                    }
                }

                try
                {
                    mnuPlugins.Visible = false;
                    mnuSeparator4.Visible = false;
                }
                catch
                {
                }

                // Initialize our management interface
                managementInterfaceServer.Initialize(this, dataProvider, telecomProvider, scriptService, pluginManager, pbxRegistrar, vmService);

                // Create our default greetings if this the first time we've run
                if (Properties.Settings.Default.FirstTimeRun)
                {
                    WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsDataTable lgTable = new CallButlerDataset.LocalizedGreetingsDataTable();
                    WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsRow lgRow;

                    if (dataProvider.GetGreeting(Properties.Settings.Default.CustomerID, WOSI.CallButler.Data.Constants.WelcomeGreetingGuid) == null)
                    {
                        lgRow = lgTable.NewLocalizedGreetingsRow();

                        lgRow.GreetingID = WOSI.CallButler.Data.Constants.WelcomeGreetingGuid;
                        lgRow.LanguageID = "en";
                        lgRow.LocalizedGreetingID = Guid.NewGuid();
                        lgRow.Type = (short)WOSI.CallButler.Data.GreetingType.SoundGreeting;

                        lgTable.AddLocalizedGreetingsRow(lgRow);
                    }

                    if (dataProvider.GetGreeting(Properties.Settings.Default.CustomerID, WOSI.CallButler.Data.Constants.MainMenuGreetingGuid) == null)
                    {
                        lgRow = lgTable.NewLocalizedGreetingsRow();

                        lgRow.GreetingID = WOSI.CallButler.Data.Constants.MainMenuGreetingGuid;
                        lgRow.LanguageID = "en";
                        lgRow.LocalizedGreetingID = Guid.NewGuid();
                        lgRow.Type = (short)WOSI.CallButler.Data.GreetingType.SoundGreeting;

                        lgTable.AddLocalizedGreetingsRow(lgRow);
                    }

                    managementInterfaceServer.PersistLocalizedGreeting(Properties.Settings.Default.CustomerID, lgTable);

                    Properties.Settings.Default.FirstTimeRun = false;
                    Properties.Settings.Default.Save();
                }

                // Setup our default language
                if (Properties.Settings.Default.DefaultLanguage.Length == 0)
                {
                    Properties.Settings.Default.DefaultLanguage = System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag;
                    Properties.Settings.Default.Save();
                }

                telecomProvider.Startup();

                CallButlerService.DialPlanManager = new DialPlanManagerService(pbxRegistrar, dataProvider, telecomProvider);

                if (tcpManagementDataServer != null)
                    tcpManagementDataServer.StartServer();

                // Create our extension management service
                /*if (Properties.Settings.Default.EnableKinesisServer)
                {
                    emService = new KinesisService(dataProvider, extStateService, scriptService, vmService);
                    emService.Start();
                }*/
            }
        }

        private void ClearMenuItemsProc()
        {
            mnuServiceOptions.DropDownItems.Clear();
        }

        private void DeInitialize()
        {
            if (mnuMain.InvokeRequired)
                mnuMain.Invoke(clearMenuItemsHandler);
            else
                mnuServiceOptions.DropDownItems.Clear();

            /*if (extStateService != null)
            {
                extStateService.ClearState();
                extStateService = null;
            }

            if (emService != null)
            {
                emService.Stop();
                emService.Dispose();
                emService = null;
            }*/

            if (pluginManager != null)
            {
                // Unload our plugins
                foreach (CallButler.Service.Plugin.CallButlerServicePlugin plugin in pluginManager.Plugins)
                {
                    plugin.Unload();
                }

                pluginManager.UnloadPlugins();
                pluginManager = null;
            }

            if (scriptService != null)
            {
                scriptService.Shutdown();
                scriptService = null;
            }

            if (vmMailerService != null)
            {
                vmMailerService = null;
            }

            if (vmService != null)
            {
                vmService = null;
            }

            dataProvider = null;

            if (CallButlerService.DialPlanManager != null)
            {
                CallButlerService.DialPlanManager = null;
            }

            if (pbxRegistrar != null)
            {
                pbxRegistrar.Shutdown();
                pbxRegistrar = null;
            }

            if (telecomProvider != null)
            {
                telecomProvider.Shutdown();
                telecomProvider = null;
            }

            if (tcpManagementDataServer != null)
                tcpManagementDataServer.StopServer();

            GC.Collect();
        }

        public void StartService(string[] args)
        {
            if (Properties.Settings.Default.EnablePerformanceCounters)
                PerformanceCounterService.Initialize();

            CreateManagementChannels();
            Initialize();
        }

        public void StopService()
        {
            /*if (emService != null)
            {
                emService.Stop();
                emService.Dispose();
                emService = null;
            }

            if (extStateService != null)
            {
                extStateService.ClearState();
                extStateService = null;
            }*/

            if(managementInterfaceServer != null)
                managementInterfaceServer = null;

            if (tcpManagementDataServer != null)
            {
                tcpManagementDataServer.StopServer();
                tcpManagementDataServer = null;
            }

            if (pipeManagementDataServer != null)
            {
                pipeManagementDataServer.StopServer();
                pipeManagementDataServer = null;
            }

            if (vmMailerService != null)
            {
                vmMailerService = null;
            }

            if (vmService != null)
            {
                vmService = null;
            }

            DeInitialize();

            PerformanceCounterService.ResetCounters();
        }

        public void RestartService(bool async)
        {
            DeInitialize();
            System.Threading.Thread.Sleep(500);
            Initialize();
        }

        void tcpClientManagementDataServer_OnManagementAllowed(object sender, NET.Remoting.Channels.ManagementAllowedEventArgs e)
        {
            try
            {
                int ext = Convert.ToInt32(e.Extension);
                bool allow = false;
                WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow row = dataProvider.GetExtensionNumber(Properties.Settings.Default.CustomerID, ext);
                if (row != null)
                {
                    allow = row.EnableManagement;
                }
                e.ManagementAllowed = allow;
            }
            catch
            {
                e.ManagementAllowed = false;
            }
        }

        void tcpClientManagementDataServer_OnAuthentication(object sender, NET.Remoting.Channels.AuthenticationEventArgs e)
        {
            e.IsAuthenticated = managementInterfaceServer.Authenticate(e.CustomerID, e.ExtensionNumber, e.Password);
        }

        void managementDataServer_OnManagementAllowed(object sender, NET.Remoting.Channels.ManagementAllowedEventArgs e)
        {
            if (Properties.Settings.Default.EnableRemoteManagement == false)
            {
                if (currentIP.Equals(e.IpAddress) || e.IpAddress.Equals("127.0.0.1") || e.IpAddress.ToLower().Equals("localhost"))
                {
                    e.ManagementAllowed = true;
                }
                else
                {
                    e.ManagementAllowed = false;
                }
            }
            else
            {
                e.ManagementAllowed = true;
            }
        }

        void managementDataServer_OnAuthentication(object sender, NET.Remoting.Channels.AuthenticationEventArgs e)
        {
            e.IsAuthenticated = managementInterfaceServer.Authenticate(e.CustomerID, e.ExtensionNumber, e.Password);
        }
        #endregion

        #region Logging Events
        void LoggingService_NewLogEntry(object sender, LogEntryEventArgs e)
        {
            // Send an Email with our error, but only if it's new.
            if (Properties.Settings.Default.SendLogErrorEmails && e.IsError && e.Message != lastErrorMessage)
            {
                try
                {
                    lastErrorMessage = e.Message;

                    string smtpPassword = "";

                    if (Properties.Settings.Default.SMTPPassword.Length > 0)
                        smtpPassword = WOSI.Utilities.CryptoUtils.Decrypt(Properties.Settings.Default.SMTPPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);

                    WOSI.Utilities.EmailUtils.SendEmail(Properties.Settings.Default.SMTPEmailFrom, Properties.Settings.Default.LogErrorEmailAddress, Services.PrivateLabelService.ReplaceProductName("A CallButler Error Has Been Logged"), e.Message, Properties.Settings.Default.SMTPServer, Properties.Settings.Default.SMTPPort, Properties.Settings.Default.SMTPUseSSL, Properties.Settings.Default.SMTPUsername, smtpPassword);
                }
                catch
                {
                }
            }
        }
        #endregion

        protected override void OnStart(string[] args)
        {
            StartService(null);
        }

        protected override void OnStop()
        {
            StopService();
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
        }
    }
}


text:
```bash
% mvn
% cd target
% unzip nettosphere-jersey-chat.jar
% chmod a+x ./bin/nettosphere.sh
% ./bin/nettosphere.sh
```
Then point the browser to 127.0.0.1:8080


text:
#ifndef itkHDF5TransformIO_h
#define itkHDF5TransformIO_h

#include "ITKIOTransformHDF5Export.h"

#include "itkTransformIOBase.h"
#include <memory>
#include <string>

// Avoids KWStyle error from forward declaration below.
namespace itk
{}

// Forward declaration of class H5::H5File
namespace H5
{
class H5File;
class PredType;
} // namespace H5

namespace itk
{

/** \class HDF5CommonPathNames
 * \brief Secondary bass class of HDF5CommonPathNames common between templates
 *
 * This class provides common non-templated code which can be compiled
 * and used by all templated versions of HDF5TransformIOTemplate.
 *
 * This class must be inherited privately, and light-weight adapting
 * of methods is required for virtual methods or non-private methods
 * for the HDF5TransformIOTemplate interface.
 *
 * \ingroup ITKIOTransformHDF5
 *
 */
struct ITKIOTransformHDF5_EXPORT HDF5CommonPathNames
{
  //
  // HDF uses hierarchical paths to find particular data
  // in a file. These strings are used by both reading and
  // writing.
  static const std::string transformGroupName;
  static const std::string transformTypeName;
  static const std::string transformFixedNameMisspelled;
  static const std::string transformParamsNameMisspelled;
  static const std::string transformFixedName;
  static const std::string transformParamsName;
  static const std::string transformFixedNameCorrected;
  static const std::string transformParamsNameCorrected;
  static const std::string ItkVersion;
  static const std::string HDFVersion;
  static const std::string OSName;
  static const std::string OSVersion;
};

/** \class HDF5TransformIOTemplate
 *  \brief Read&Write transforms in HDF5 Format
 *
 *  See hdfgroup.org/HDF5 -- HDF5 is a physics/astrophysics
 *  format, but it is very general and can store pretty much
 *  any sort of data.
 *
 * \ingroup ITKIOTransformHDF5
 */
template <typename TParametersValueType>
class ITK_TEMPLATE_EXPORT HDF5TransformIOTemplate
  : public TransformIOBaseTemplate<TParametersValueType>
  , private HDF5CommonPathNames
{
public:
  using Self = HDF5TransformIOTemplate;
  using Superclass = TransformIOBaseTemplate<TParametersValueType>;
  using Pointer = SmartPointer<Self>;
  using TransformType = typename Superclass::TransformType;
  using TransformPointer = typename Superclass::TransformPointer;
  using TransformListType = typename Superclass::TransformListType;
  using ParametersType = typename TransformType::ParametersType;
  using ParametersValueType = typename TransformType::ParametersValueType;
  using FixedParametersType = typename TransformType::FixedParametersType;
  using FixedParametersValueType = typename TransformType::FixedParametersValueType;

  using ConstTransformListType = typename TransformIOBaseTemplate<ParametersValueType>::ConstTransformListType;

  /** Run-time type information (and related methods). */
  itkTypeMacro(HDF5TransformIOTemplate, TransformIOBaseTemplate);
  itkNewMacro(Self);

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  bool
  CanReadFile(const char *) override;

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  bool
  CanWriteFile(const char *) override;

  /** Reads the data from disk into the memory buffer provided. */
  void
  Read() override;

  /** Writes the data to disk from the memory buffer provided. Make sure
   * that the IORegions has been set properly. The buffer is cast to a
   * pointer to the beginning of the image data. */
  void
  Write() override;

protected:
  HDF5TransformIOTemplate();
  ~HDF5TransformIOTemplate() override;

private:
  /** Read a parameter array from the file location name */
  ParametersType
  ReadParameters(const std::string & DataSetName) const;
  FixedParametersType
  ReadFixedParameters(const std::string & DataSetName) const;

  /** Write a parameter array to the file location name */
  void
  WriteParameters(const std::string & name, const ParametersType & parameters);
  void
  WriteFixedParameters(const std::string & name, const FixedParametersType & parameters);

  /** write a string variable */
  void
  WriteString(const std::string & path, const std::string & value);
  void
  WriteString(const std::string & path, const char * value);
  void
  WriteOneTransform(const int transformIndex, const TransformType * transform);

  std::unique_ptr<H5::H5File> m_H5File;

  /** Utility function for inferring data storage type
   * from class template.
   * @return H5 code PredType
   */
  H5::PredType
  GetH5TypeFromString() const;
};

const std::string ITKIOTransformHDF5_EXPORT
                  GetTransformName(int);

/** This helps to meet backward compatibility */
using HDF5TransformIO = HDF5TransformIOTemplate<double>;

} // end namespace itk

// Note: Explicit instantiation is done in itkHDF5TransformIO.cxx

#endif // itkHDF5TransformIO_h

/** Explicit instantiations */
#ifndef ITK_TEMPLATE_EXPLICIT_HDF5TransformIO
// Explicit instantiation is required to ensure correct dynamic_cast
// behavior across shared libraries.
//
// IMPORTANT: Since within the same compilation unit,
//            ITK_TEMPLATE_EXPLICIT_<classname> defined and undefined states
//            need to be considered. This code *MUST* be *OUTSIDE* the header
//            guards.
//
#if defined(ITKIOTransformHDF5_EXPORTS)
//   We are building this library
#  define ITKIOTransformHDF5_EXPORT_EXPLICIT ITK_FORWARD_EXPORT
#else
//   We are using this library
#  define ITKIOTransformHDF5_EXPORT_EXPLICIT ITKIOTransformHDF5_EXPORT
#endif
namespace itk
{
ITK_GCC_PRAGMA_DIAG_PUSH()
ITK_GCC_PRAGMA_DIAG(ignored "-Wattributes")

extern template class ITKIOTransformHDF5_EXPORT_EXPLICIT HDF5TransformIOTemplate<double>;
extern template class ITKIOTransformHDF5_EXPORT_EXPLICIT HDF5TransformIOTemplate<float>;

ITK_GCC_PRAGMA_DIAG_POP()

} // end namespace itk
#undef ITKIOTransformHDF5_EXPORT_EXPLICIT
#endif


text:
using System;
using Igneel.Components;
using Igneel.Effects;
using Igneel.Graphics;
using Igneel.Physics;

namespace Igneel.Rendering
{
    public class ActorRender : Render<Actor, RenderMeshIdEffect>, IComponentRender<Actor>
    {
        Mesh _sphere;
        Mesh _box;
        Mesh _capsule;
        Mesh _cylindre;
        private RasterizerState _rasterizer;
        Color4 _color = new Color4(0, 1, 0);

        public ActorRender(GraphicDevice device):base(device)
        {
            _sphere = Mesh.CreateSphere(16, 16, 1);
            _box = Mesh.CreateBox(2, 2, 2);
            _cylindre = Mesh.CreateCylindre(1, 16, 1, 1, false);
            _capsule = Mesh.CreateCapsule(1, 1, 16, 16, 1, 16);

            _rasterizer = GraphicDeviceFactory.Device.CreateRasterizerState(new RasterizerDesc(true)
            {
                 Fill = FillMode.Wireframe,
            });
        }

        public Color4 Color { get { return _color; } set { _color = value; } }

        public override void Draw(Actor comp)
        {
            if (Engine.Scene.ActiveCamera == null)
                return;
            var device = GraphicDeviceFactory.Device;
            device.RasterizerStack.Push(_rasterizer);
            device.PrimitiveTopology = IAPrimitive.TriangleList;

            Bind(Engine.Scene.ActiveCamera);

            Effect.Input.gId = (Vector4)_color;
            foreach (var shape in comp.Shapes)
            {
                DrawShape(shape, device);
            }

            device.RasterizerStack.Pop();
        }

        private void DrawShape(ActorShape shape, GraphicDevice device)
        {
            Matrix scale;
            if (shape is BoxShape)
            {
                BoxShape boxShape = (BoxShape)shape;
                scale = Matrix.Scale(boxShape.Dimensions);
                Effect.Input.World = scale * boxShape.GlobalPose;
                DrawMesh(_box, device);
            }
            else if (shape is SphereShape)
            {
                SphereShape sphereShape = (SphereShape)shape;
                scale = Matrix.Scale(new Vector3(sphereShape.Radius));
                Effect.Input.World = scale * shape.GlobalPose;
                DrawMesh(_sphere, device);
            }
            else if (shape is PlaneShape)
            {
                scale = Matrix.Scale(Engine.Scene.ActiveCamera.ZFar,0, Engine.Scene.ActiveCamera.ZFar);
                Effect.Input.World = scale * shape.GlobalPose;
                DrawMesh(_box, device);
            }
            else if (shape is WheelShape)
            {
                WheelShape wheel = (WheelShape)shape;

                Effect.Input.World = Matrix.Scale(wheel.Radius, 0, wheel.Radius) *
                                         Matrix.RotationZ(Numerics.PIover2) *
                                         Matrix.RotationY(wheel.SteerAngle) *
                                         shape.GlobalPose;

                DrawMesh(_cylindre, device);

            }
            else if (shape is CapsuleShape)
            {
                CapsuleShape capsuleShape = (CapsuleShape)shape;
                float radius = capsuleShape.Radius;
                float height = capsuleShape.Height;
                Effect.Input.World = Matrix.Translate(0, -0.5f, 0) *
                                         Matrix.Scale(radius, radius, radius) *
                                         Matrix.Translate(0, height * 0.5f, 0) * shape.GlobalPose;

                DrawMeshPart(_capsule, _capsule.Layers[0], device);

                Effect.Input.World = Matrix.Translate(0, 0.5f, 0) *
                                          Matrix.Scale(radius, radius, radius) *
                                          Matrix.Translate(0, -(height * 0.5f), 0) * shape.GlobalPose;
                DrawMeshPart(_capsule, _capsule.Layers[2], device);

                Effect.Input.World = Matrix.Scale(radius, height, radius) * shape.GlobalPose;
                DrawMeshPart(_capsule, _capsule.Layers[1], device);
            }
            else if (shape is TriangleMeshShape)
            {
                TriangleMesh tmesh = ((TriangleMeshShape)shape).Mesh;
                var mesh = (Mesh)tmesh.GraphicMesh;
                if (mesh != null)
                {
                    Effect.Input.World = shape.GlobalPose;

                    DrawMesh(mesh, device);

                }
            }
        }

        private void DrawMesh(Mesh mesh, GraphicDevice device)
        {
            device.SetVertexBuffer(0, mesh.VertexBuffer, 0);
            device.SetIndexBuffer(mesh.IndexBuffer);
            var effect = Effect;
            foreach (var pass in effect.Passes())
            {
                effect.Apply(pass);
                device.DrawIndexed(mesh.Layers[0].IndexCount, 0, 0);
            }
        }

        private void DrawMeshPart(Mesh mesh, MeshPart part ,GraphicDevice device)
        {
            device.SetVertexBuffer(0, mesh.VertexBuffer, 0);
            device.SetIndexBuffer(mesh.IndexBuffer);
            var effect = Effect;
            foreach (var pass in effect.Passes())
            {
                effect.Apply(pass);
                device.DrawIndexed(part.IndexCount, part.StartIndex, 0);
            }
        }

        //private void DrawCapsuleLayer(Device device, ShapeLayer layer)
        //{
        //    effect.Apply(() =>
        //                  device.DrawIndexedUserPrimitives(IAPrimitive.TriangleList, layer.StartIndex, layer.StartVertex,
        //                   layer.VertexCount, layer.PrimitiveCount, capsuleBuilder.Indices, Format.Index16, capsuleBuilder.Vertices, vd.Size));
        //}

        //public void DrawPlane(Matrix pose)
        //{
        //    var camera = Engine.Scene.ActiveCamera;
        //    DrawBox(pose, new Vector3(camera.ZFar, 0, camera.ZFar));
        //}

        //public void DrawBox(Matrix pose, Vector3 dimensions)
        //{
        //    var scale = Matrix.Scaling(dimensions);
        //    effect.SetWorldMatrix(scale * pose);
        //    effect.Apply(() =>
        //    GraphicDeviceFactory.Device.DrawIndexedUserPrimitives(IAPrimitive.TriangleList, 0, boxBuilder.Vertices.Length,
        //                            boxBuilder.Indices.Length / 3, boxBuilder.Indices, true, boxBuilder.Vertices));
        //}

        //public override void Draw(object component)
        //{
        //    Draw((Actor)component);
        //}

        public void DrawController(CharacterController characterController)
        {
            var device = GraphicDeviceFactory.Device;
            device.RasterizerStack.Push(_rasterizer);
            device.PrimitiveTopology = IAPrimitive.TriangleList;
            var effect = Effect;
            if (characterController is BoxController)
            {
                BoxController boxController = (BoxController)characterController;
                effect.Input.World = Matrix.Scale(boxController.Extents) * characterController.GlobalPose;
                DrawMesh(_box, GraphicDeviceFactory.Device);
            }
            else
            {
                CapsuleController capsuleController = (CapsuleController)characterController;
                float radius = capsuleController.Radius;
                float height = capsuleController.Height;
                effect.Input.World = Matrix.Translate(0, -0.5f, 0) *
                                         Matrix.Scale(radius, radius, radius) *
                                         Matrix.Translate(0, height * 0.5f, 0) * capsuleController.GlobalPose;

                DrawMeshPart(_capsule, _capsule.Layers[0], GraphicDeviceFactory.Device);

                effect.Input.World = Matrix.Translate(0, 0.5f, 0) *
                                          Matrix.Scale(radius, radius, radius) *
                                          Matrix.Translate(0, -(height * 0.5f), 0) * capsuleController.GlobalPose;
                DrawMeshPart(_capsule, _capsule.Layers[2], GraphicDeviceFactory.Device);

                effect.Input.World = Matrix.Scale(radius, height, radius) * capsuleController.GlobalPose;
                DrawMeshPart(_capsule, _capsule.Layers[1], GraphicDeviceFactory.Device);
            }

            device.RasterizerStack.Pop();
        }
    }

    class ColorActorBinding : RenderBinding<Actor>
    {

        public override void OnBind(Actor value)
        {
            throw new NotImplementedException();
        }

        public override void OnUnBind(Actor value)
        {
            throw new NotImplementedException();
        }
    }

    class IdShapeBinding : RenderBinding<ActorShape>
    {
        public override void OnBind(ActorShape value)
        {
            throw new NotImplementedException();
        }

        public override void OnUnBind(ActorShape value)
        {
            throw new NotImplementedException();
        }
    }
}


text:
When a Slim element requires access to a child element, using *id* attribute and DOM selectors may be troublesome,
especially when the element has multiple instances in the DOM.
Elements declared in a template can be referenced directly to their *bound parent* using `s:id` attribute in the following manner:
```html
<div s:id="myDiv">
    <span>Hello, </span>
    <span s:id="mySpan">World</span>
</div>
```
In the element's class code a developer can access those children directly:
```javascript
class MyTag extends Slim {
  ...
  onCreated() {
    this.mySpan.innerText = "Custom Elements!"
    this.myDiv.style.backgroundColor = 'red';
  }
  ...
}
```

### Slim.prototype.find (selector)
This function runs a search in the element's tree, returning the first element matching the selector.
If no element is found, it returns undefined.
### Slim.prototype.findAll (selector)
Returns all elements matching the selector in an Array.
If no elements are found, it returns an empty Array.

> **Note:** find and findAll methods performs a deep search in the tree, meaning that custom child elements may be holding children that matches the selector.
> If that happens, the find include these elements in the result.
> find and findAll are wrappers for querySelector and querySelectorAll, thus will not search inside a nested shadow DOM.

### Slim::selectRecursive(parent)
Returns all descendants as a flat array. It does not "penetrate" any slim elements, only counts the element itself, disregarding it's descendants.

### Slim.prototype.\[get\] rootElement
This will either return the element's shadow root (if used) or the element itself, depends of the use of shadow DOM.
A developer can search within nested shadow DOMs using access to rootElement.
For example: If a nested Slim element is using shadow DOM and the parent requires searching it's children,
it can be done using *rootElement*:
```javascript
var hiddenDivElements = this.find('child-element').rootElement.findAll('div')
```

### Accessing children and lifecycle
> **Note:** Accessing a child cannot be done before the element has finished the creation cycle.
> Therefore, a developer wishes to access referenced children should avoid doing so in onBeforeCreated hook