text:
/*-
 * Copyright (c) 2004-2006 Kip Macy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_inet6.h"
#include "opt_inet.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sockio.h>
#include <sys/mbuf.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/queue.h>
#include <sys/lock.h>
#include <sys/sx.h>

#include <net/if.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <net/if_dl.h>
#include <net/if_media.h>

#include <net/bpf.h>

#include <net/if_types.h>
#include <net/if_vlan_var.h>
#include <net/if.h>

#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip6.h>

#include <vm/vm.h>
#include <vm/vm_param.h>
#include <vm/vm_kern.h>
#include <vm/pmap.h>

#include <machine/bus.h>
#include <machine/resource.h>
#include <machine/frame.h>
#include <machine/vmparam.h>

#include <sys/bus.h>
#include <sys/rman.h>
#include <sys/mutex.h>
#include <sys/errno.h>
#include <sys/types.h>
#include <machine/atomic.h>

#include <machine/intr_machdep.h>

#include <machine/in_cksum.h>

#include <dev/hyperv/include/hyperv.h>
#include "hv_net_vsc.h"
#include "hv_rndis.h"
#include "hv_rndis_filter.h"

/* Short for Hyper-V network interface */
#define NETVSC_DEVNAME    "hn"

/*
 * It looks like offset 0 of buf is reserved to hold the softc pointer.
 * The sc pointer evidently not needed, and is not presently populated.
 * The packet offset is where the netvsc_packet starts in the buffer.
 */
#define HV_NV_SC_PTR_OFFSET_IN_BUF         0
#define HV_NV_PACKET_OFFSET_IN_BUF         16

/*
 * Data types
 */

struct hv_netvsc_driver_context {
	uint32_t		drv_inited;
};

/*
 * Be aware that this sleepable mutex will exhibit WITNESS errors when
 * certain TCP and ARP code paths are taken.  This appears to be a
 * well-known condition, as all other drivers checked use a sleeping
 * mutex to protect their transmit paths.
 * Also Be aware that mutexes do not play well with semaphores, and there
 * is a conflicting semaphore in a certain channel code path.
 */
#define NV_LOCK_INIT(_sc, _name) \
	    mtx_init(&(_sc)->hn_lock, _name, MTX_NETWORK_LOCK, MTX_DEF)
#define NV_LOCK(_sc)		mtx_lock(&(_sc)->hn_lock)
#define NV_LOCK_ASSERT(_sc)	mtx_assert(&(_sc)->hn_lock, MA_OWNED)
#define NV_UNLOCK(_sc)		mtx_unlock(&(_sc)->hn_lock)
#define NV_LOCK_DESTROY(_sc)	mtx_destroy(&(_sc)->hn_lock)

/*
 * Globals
 */

int hv_promisc_mode = 0;    /* normal mode by default */

/* The one and only one */
static struct hv_netvsc_driver_context g_netvsc_drv;

/*
 * Forward declarations
 */
static void hn_stop(hn_softc_t *sc);
static void hn_ifinit_locked(hn_softc_t *sc);
static void hn_ifinit(void *xsc);
static int  hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
static int  hn_start_locked(struct ifnet *ifp);
static void hn_start(struct ifnet *ifp);

/*
 * NetVsc get message transport protocol type
 */
static uint32_t get_transport_proto_type(struct mbuf *m_head)
{
	uint32_t ret_val = TRANSPORT_TYPE_NOT_IP;
	uint16_t ether_type = 0;
	int ether_len = 0;
	struct ether_vlan_header *eh;
#ifdef INET
	struct ip *iph;
#endif
#ifdef INET6
	struct ip6_hdr *ip6;
#endif

	eh = mtod(m_head, struct ether_vlan_header*);
	if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
		ether_len = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
		ether_type = eh->evl_proto;
	} else {
		ether_len = ETHER_HDR_LEN;
		ether_type = eh->evl_encap_proto;
	}

	switch (ntohs(ether_type)) {
#ifdef INET6
	case ETHERTYPE_IPV6:
		ip6 = (struct ip6_hdr *)(m_head->m_data + ether_len);

		if (IPPROTO_TCP == ip6->ip6_nxt) {
			ret_val = TRANSPORT_TYPE_IPV6_TCP;
		} else if (IPPROTO_UDP == ip6->ip6_nxt) {
			ret_val = TRANSPORT_TYPE_IPV6_UDP;
		}
		break;
#endif
#ifdef INET
	case ETHERTYPE_IP:
		iph = (struct ip *)(m_head->m_data + ether_len);

		if (IPPROTO_TCP == iph->ip_p) {
			ret_val = TRANSPORT_TYPE_IPV4_TCP;
		} else if (IPPROTO_UDP == iph->ip_p) {
			ret_val = TRANSPORT_TYPE_IPV4_UDP;
		}
		break;
#endif
	default:
		ret_val = TRANSPORT_TYPE_NOT_IP;
		break;
	}

	return (ret_val);
}

/*
 * NetVsc driver initialization
 * Note:  Filter init is no longer required
 */
static int
netvsc_drv_init(void)
{
	return (0);
}

/*
 * NetVsc global initialization entry point
 */
static void
netvsc_init(void)
{
	if (bootverbose)
		printf("Netvsc initializing... ");

	/*
	 * XXXKYS: cleanup initialization
	 */
	if (!cold && !g_netvsc_drv.drv_inited) {
		g_netvsc_drv.drv_inited = 1;
		netvsc_drv_init();
		if (bootverbose)
			printf("done!\n");
	} else if (bootverbose)
		printf("Already initialized!\n");
}

/* {F8615163-DF3E-46c5-913F-F2D2F965ED0E} */
static const hv_guid g_net_vsc_device_type = {
	.data = {0x63, 0x51, 0x61, 0xF8, 0x3E, 0xDF, 0xc5, 0x46,
		0x91, 0x3F, 0xF2, 0xD2, 0xF9, 0x65, 0xED, 0x0E}
};

/*
 * Standard probe entry point.
 *
 */
static int
netvsc_probe(device_t dev)
{
	const char *p;

	p = vmbus_get_type(dev);
	if (!memcmp(p, &g_net_vsc_device_type.data, sizeof(hv_guid))) {
		device_set_desc(dev, "Synthetic Network Interface");
		if (bootverbose)
			printf("Netvsc probe... DONE \n");

		return (BUS_PROBE_DEFAULT);
	}

	return (ENXIO);
}

/*
 * Standard attach entry point.
 *
 * Called when the driver is loaded.  It allocates needed resources,
 * and initializes the "hardware" and software.
 */
static int
netvsc_attach(device_t dev)
{
	struct hv_device *device_ctx = vmbus_get_devctx(dev);
	netvsc_device_info device_info;
	hn_softc_t *sc;
	int unit = device_get_unit(dev);
	struct ifnet *ifp;
	int ret;

	netvsc_init();

	sc = device_get_softc(dev);
	if (sc == NULL) {
		return (ENOMEM);
	}

	bzero(sc, sizeof(hn_softc_t));
	sc->hn_unit = unit;
	sc->hn_dev = dev;

	NV_LOCK_INIT(sc, "NetVSCLock");

	sc->hn_dev_obj = device_ctx;

	ifp = sc->hn_ifp = sc->arpcom.ac_ifp = if_alloc(IFT_ETHER);
	ifp->if_softc = sc;

	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
	ifp->if_dunit = unit;
	ifp->if_dname = NETVSC_DEVNAME;

	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
	ifp->if_ioctl = hn_ioctl;
	ifp->if_start = hn_start;
	ifp->if_init = hn_ifinit;
	/* needed by hv_rf_on_device_add() code */
	ifp->if_mtu = ETHERMTU;
	IFQ_SET_MAXLEN(&ifp->if_snd, 512);
	ifp->if_snd.ifq_drv_maxlen = 511;
	IFQ_SET_READY(&ifp->if_snd);

	/*
	 * Tell upper layers that we support full VLAN capability.
	 */
	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
	ifp->if_capabilities |=
	    IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO;
	ifp->if_capenable |=
	    IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO;
	/*
	 * Only enable UDP checksum offloading when it is on 2012R2 or
	 * later. UDP checksum offloading doesn't work on earlier
	 * Windows releases.
	 */
	if (hv_vmbus_protocal_version >= HV_VMBUS_VERSION_WIN8_1)
		ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_TSO;
	else
		ifp->if_hwassist = CSUM_TCP | CSUM_TSO;

	ret = hv_rf_on_device_add(device_ctx, &device_info);
	if (ret != 0) {
		if_free(ifp);

		return (ret);
	}
	if (device_info.link_state == 0) {
		sc->hn_carrier = 1;
	}

	ether_ifattach(ifp, device_info.mac_addr);

	return (0);
}

/*
 * Standard detach entry point
 */
static int
netvsc_detach(device_t dev)
{
	struct hv_device *hv_device = vmbus_get_devctx(dev);

	if (bootverbose)
		printf("netvsc_detach\n");

	/*
	 * XXXKYS:  Need to clean up all our
	 * driver state; this is the driver
	 * unloading.
	 */

	/*
	 * XXXKYS:  Need to stop outgoing traffic and unregister
	 * the netdevice.
	 */

	hv_rf_on_device_remove(hv_device, HV_RF_NV_DESTROY_CHANNEL);

	return (0);
}

/*
 * Standard shutdown entry point
 */
static int
netvsc_shutdown(device_t dev)
{
	return (0);
}

/*
 * Send completion processing
 *
 * Note:  It looks like offset 0 of buf is reserved to hold the softc
 * pointer.  The sc pointer is not currently needed in this function, and
 * it is not presently populated by the TX function.
 */
void
netvsc_xmit_completion(void *context)
{
	netvsc_packet *packet = (netvsc_packet *)context;
	struct mbuf *mb;
	uint8_t *buf;

	mb = (struct mbuf *)(uintptr_t)packet->compl.send.send_completion_tid;
	buf = ((uint8_t *)packet) - HV_NV_PACKET_OFFSET_IN_BUF;

	free(buf, M_NETVSC);

	if (mb != NULL) {
		m_freem(mb);
	}
}

/*
 * Start a transmit of one or more packets
 */
static int
hn_start_locked(struct ifnet *ifp)
{
	hn_softc_t *sc = ifp->if_softc;
	struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
	netvsc_dev *net_dev = sc->net_dev;
	device_t dev = device_ctx->device;
	uint8_t *buf;
	netvsc_packet *packet;
	struct mbuf *m_head, *m;
	struct mbuf *mc_head = NULL;
	struct ether_vlan_header *eh;
	rndis_msg *rndis_mesg;
	rndis_packet *rndis_pkt;
	rndis_per_packet_info *rppi;
	ndis_8021q_info *rppi_vlan_info;
	rndis_tcp_ip_csum_info *csum_info;
	rndis_tcp_tso_info *tso_info;
	int ether_len;
	int i;
	int num_frags;
	int len;
	int retries = 0;
	int ret = 0;
	uint32_t rndis_msg_size = 0;
	uint32_t trans_proto_type;
	uint32_t send_buf_section_idx =
	    NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX;

	while (!IFQ_DRV_IS_EMPTY(&sc->hn_ifp->if_snd)) {
		IFQ_DRV_DEQUEUE(&sc->hn_ifp->if_snd, m_head);
		if (m_head == NULL) {
			break;
		}

		len = 0;
		num_frags = 0;

		/* Walk the mbuf list computing total length and num frags */
		for (m = m_head; m != NULL; m = m->m_next) {
			if (m->m_len != 0) {
				num_frags++;
				len += m->m_len;
			}
		}

		/*
		 * Reserve the number of pages requested.  Currently,
		 * one page is reserved for the message in the RNDIS
		 * filter packet
		 */
		num_frags += HV_RF_NUM_TX_RESERVED_PAGE_BUFS;

		/* If exceeds # page_buffers in netvsc_packet */
		if (num_frags > NETVSC_PACKET_MAXPAGE) {
			device_printf(dev, "exceed max page buffers,%d,%d\n",
			    num_frags, NETVSC_PACKET_MAXPAGE);
			m_freem(m_head);
			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
			return (EINVAL);
		}

		/*
		 * Allocate a buffer with space for a netvsc packet plus a
		 * number of reserved areas.  First comes a (currently 16
		 * bytes, currently unused) reserved data area.  Second is
		 * the netvsc_packet. Third is an area reserved for an
		 * rndis_filter_packet struct. Fourth (optional) is a
		 * rndis_per_packet_info struct.
		 * Changed malloc to M_NOWAIT to avoid sleep under spin lock.
		 * No longer reserving extra space for page buffers, as they
		 * are already part of the netvsc_packet.
		 */
		buf = malloc(HV_NV_PACKET_OFFSET_IN_BUF +
			sizeof(netvsc_packet) +
			sizeof(rndis_msg) +
			RNDIS_VLAN_PPI_SIZE +
			RNDIS_TSO_PPI_SIZE +
			RNDIS_CSUM_PPI_SIZE,
			M_NETVSC, M_ZERO | M_NOWAIT);
		if (buf == NULL) {
			device_printf(dev, "hn:malloc packet failed\n");
			m_freem(m_head);
			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
			return (ENOMEM);
		}

		packet = (netvsc_packet *)(buf + HV_NV_PACKET_OFFSET_IN_BUF);
		*(vm_offset_t *)buf = HV_NV_SC_PTR_OFFSET_IN_BUF;

		packet->is_data_pkt = TRUE;

		/* Set up the rndis header */
		packet->page_buf_count = num_frags;

		/* Initialize it from the mbuf */
		packet->tot_data_buf_len = len;

		/*
		 * extension points to the area reserved for the
		 * rndis_filter_packet, which is placed just after
		 * the netvsc_packet (and rppi struct, if present;
		 * length is updated later).
		 */
		packet->rndis_mesg = packet + 1;
		rndis_mesg = (rndis_msg *)packet->rndis_mesg;
		rndis_mesg->ndis_msg_type = REMOTE_NDIS_PACKET_MSG;

		rndis_pkt = &rndis_mesg->msg.packet;
		rndis_pkt->data_offset = sizeof(rndis_packet);
		rndis_pkt->data_length = packet->tot_data_buf_len;
		rndis_pkt->per_pkt_info_offset = sizeof(rndis_packet);

		rndis_msg_size = RNDIS_MESSAGE_SIZE(rndis_packet);

		/*
		 * If the Hyper-V infrastructure needs to embed a VLAN tag,
		 * initialize netvsc_packet and rppi struct values as needed.
		 */
		if (m_head->m_flags & M_VLANTAG) {
			/*
			 * set up some additional fields so the Hyper-V infrastructure will stuff the VLAN tag
			 * into the frame.
			 */
			packet->vlan_tci = m_head->m_pkthdr.ether_vtag;

			rndis_msg_size += RNDIS_VLAN_PPI_SIZE;

			rppi = hv_set_rppi_data(rndis_mesg, RNDIS_VLAN_PPI_SIZE,
			    ieee_8021q_info);

			/* VLAN info immediately follows rppi struct */
			rppi_vlan_info = (ndis_8021q_info *)((char*)rppi +
			    rppi->per_packet_info_offset);
			/* FreeBSD does not support CFI or priority */
			rppi_vlan_info->u1.s1.vlan_id =
			    packet->vlan_tci & 0xfff;
		}

		if (0 == m_head->m_pkthdr.csum_flags) {
			goto pre_send;
		}

		eh = mtod(m_head, struct ether_vlan_header*);
		if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
			ether_len = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
		} else {
			ether_len = ETHER_HDR_LEN;
		}

		trans_proto_type = get_transport_proto_type(m_head);
		if (TRANSPORT_TYPE_NOT_IP == trans_proto_type) {
			goto pre_send;
		}

		/*
		 * TSO packet needless to setup the send side checksum
		 * offload.
		 */
		if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
			goto do_tso;
		}

		/* setup checksum offload */
		rndis_msg_size += RNDIS_CSUM_PPI_SIZE;
		rppi = hv_set_rppi_data(rndis_mesg, RNDIS_CSUM_PPI_SIZE,
		    tcpip_chksum_info);
		csum_info = (rndis_tcp_ip_csum_info *)((char*)rppi +
		    rppi->per_packet_info_offset);

		if (trans_proto_type & (TYPE_IPV4 << 16)) {
			csum_info->xmit.is_ipv4 = 1;
		} else {
			csum_info->xmit.is_ipv6 = 1;
		}

		if (trans_proto_type & TYPE_TCP) {
			csum_info->xmit.tcp_csum = 1;
			csum_info->xmit.tcp_header_offset = 0;
		} else if (trans_proto_type & TYPE_UDP) {
			csum_info->xmit.udp_csum = 1;
		}

		goto pre_send;

do_tso:
		/* setup TCP segmentation offload */
		rndis_msg_size += RNDIS_TSO_PPI_SIZE;
		rppi = hv_set_rppi_data(rndis_mesg, RNDIS_TSO_PPI_SIZE,
		    tcp_large_send_info);

		tso_info = (rndis_tcp_tso_info *)((char *)rppi +
		    rppi->per_packet_info_offset);
		tso_info->lso_v2_xmit.type =
		    RNDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE;

#ifdef INET
		if (trans_proto_type & (TYPE_IPV4 << 16)) {
			struct ip *ip =
			    (struct ip *)(m_head->m_data + ether_len);
			unsigned long iph_len = ip->ip_hl << 2;
			struct tcphdr *th =
			    (struct tcphdr *)((caddr_t)ip + iph_len);

			tso_info->lso_v2_xmit.ip_version =
			    RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV4;
			ip->ip_len = 0;
			ip->ip_sum = 0;

			th->th_sum = in_pseudo(ip->ip_src.s_addr,
			    ip->ip_dst.s_addr,
			    htons(IPPROTO_TCP));
		}
#endif
#if defined(INET6) && defined(INET)
		else
#endif
#ifdef INET6
		{
			struct ip6_hdr *ip6 =
			    (struct ip6_hdr *)(m_head->m_data + ether_len);
			struct tcphdr *th = (struct tcphdr *)(ip6 + 1);

			tso_info->lso_v2_xmit.ip_version =
			    RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV6;
			ip6->ip6_plen = 0;
			th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
		}
#endif
		tso_info->lso_v2_xmit.tcp_header_offset = 0;
		tso_info->lso_v2_xmit.mss = m_head->m_pkthdr.tso_segsz;

pre_send:
		rndis_mesg->msg_len = packet->tot_data_buf_len + rndis_msg_size;
		packet->tot_data_buf_len = rndis_mesg->msg_len;

		/* send packet with send buffer */
		if (packet->tot_data_buf_len < net_dev->send_section_size) {
			send_buf_section_idx =
			    hv_nv_get_next_send_section(net_dev);
			if (send_buf_section_idx !=
			    NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX) {
				char *dest = ((char *)net_dev->send_buf +
				    send_buf_section_idx *
				    net_dev->send_section_size);

				memcpy(dest, rndis_mesg, rndis_msg_size);
				dest += rndis_msg_size;
				for (m = m_head; m != NULL; m = m->m_next) {
					if (m->m_len) {
						memcpy(dest,
						    (void *)mtod(m, vm_offset_t),
						    m->m_len);
						dest += m->m_len;
					}
				}

				packet->send_buf_section_idx =
				    send_buf_section_idx;
				packet->send_buf_section_size =
				    packet->tot_data_buf_len;
				packet->page_buf_count = 0;
				goto do_send;
			}
		}

		/* send packet with page buffer */
		packet->page_buffers[0].pfn =
		    atop(hv_get_phys_addr(rndis_mesg));
		packet->page_buffers[0].offset =
		    (unsigned long)rndis_mesg & PAGE_MASK;
		packet->page_buffers[0].length = rndis_msg_size;

		/*
		 * Fill the page buffers with mbuf info starting at index
		 * HV_RF_NUM_TX_RESERVED_PAGE_BUFS.
		 */
		i = HV_RF_NUM_TX_RESERVED_PAGE_BUFS;
		for (m = m_head; m != NULL; m = m->m_next) {
			if (m->m_len) {
				vm_offset_t paddr =
				    vtophys(mtod(m, vm_offset_t));
				packet->page_buffers[i].pfn =
				    paddr >> PAGE_SHIFT;
				packet->page_buffers[i].offset =
				    paddr & (PAGE_SIZE - 1);
				packet->page_buffers[i].length = m->m_len;
				i++;
			}
		}

		packet->send_buf_section_idx =
		    NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX;
		packet->send_buf_section_size = 0;

do_send:

		/*
		 * If bpf, copy the mbuf chain.  This is less expensive than
		 * it appears; the mbuf clusters are not copied, only their
		 * reference counts are incremented.
		 * Needed to avoid a race condition where the completion
		 * callback is invoked, freeing the mbuf chain, before the
		 * bpf_mtap code has a chance to run.
		 */
		if (ifp->if_bpf) {
			mc_head = m_copypacket(m_head, M_DONTWAIT);
		}
retry_send:
		/* Set the completion routine */
		packet->compl.send.on_send_completion = netvsc_xmit_completion;
		packet->compl.send.send_completion_context = packet;
		packet->compl.send.send_completion_tid = (uint64_t)(uintptr_t)m_head;

		/* Removed critical_enter(), does not appear necessary */
		ret = hv_nv_on_send(device_ctx, packet);
		if (ret == 0) {
			ifp->if_opackets++;
			/* if bpf && mc_head, call bpf_mtap code */
			if (mc_head) {
				ETHER_BPF_MTAP(ifp, mc_head);
			}
		} else {
			retries++;
			if (retries < 4) {
				goto retry_send;
			}

			IF_PREPEND(&ifp->if_snd, m_head);
			ifp->if_drv_flags |= IFF_DRV_OACTIVE;

			/*
			 * Null the mbuf pointer so the completion function
			 * does not free the mbuf chain.  We just pushed the
			 * mbuf chain back on the if_snd queue.
			 */
			packet->compl.send.send_completion_tid = 0;

			/*
			 * Release the resources since we will not get any
			 * send completion
			 */
			netvsc_xmit_completion(packet);
			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
		}

		/* if bpf && mc_head, free the mbuf chain copy */
		if (mc_head) {
			m_freem(mc_head);
		}
	}

	return (ret);
}

/*
 * Link up/down notification
 */
void
netvsc_linkstatus_callback(struct hv_device *device_obj, uint32_t status)
{
	hn_softc_t *sc = device_get_softc(device_obj->device);

	if (sc == NULL) {
		return;
	}

	if (status == 1) {
		sc->hn_carrier = 1;
	} else {
		sc->hn_carrier = 0;
	}
}

/*
 * Append the specified data to the indicated mbuf chain,
 * Extend the mbuf chain if the new data does not fit in
 * existing space.
 *
 * This is a minor rewrite of m_append() from sys/kern/uipc_mbuf.c.
 * There should be an equivalent in the kernel mbuf code,
 * but there does not appear to be one yet.
 *
 * Differs from m_append() in that additional mbufs are
 * allocated with cluster size MJUMPAGESIZE, and filled
 * accordingly.
 *
 * Return 1 if able to complete the job; otherwise 0.
 */
static int
hv_m_append(struct mbuf *m0, int len, c_caddr_t cp)
{
	struct mbuf *m, *n;
	int remainder, space;

	for (m = m0; m->m_next != NULL; m = m->m_next)
		;
	remainder = len;
	space = M_TRAILINGSPACE(m);
	if (space > 0) {
		/*
		 * Copy into available space.
		 */
		if (space > remainder)
			space = remainder;
		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
		m->m_len += space;
		cp += space;
		remainder -= space;
	}
	while (remainder > 0) {
		/*
		 * Allocate a new mbuf; could check space
		 * and allocate a cluster instead.
		 */
		n = m_getjcl(M_DONTWAIT, m->m_type, 0, MJUMPAGESIZE);
		if (n == NULL)
			break;
		n->m_len = min(MJUMPAGESIZE, remainder);
		bcopy(cp, mtod(n, caddr_t), n->m_len);
		cp += n->m_len;
		remainder -= n->m_len;
		m->m_next = n;
		m = n;
	}
	if (m0->m_flags & M_PKTHDR)
		m0->m_pkthdr.len += len - remainder;

	return (remainder == 0);
}

/*
 * Called when we receive a data packet from the "wire" on the
 * specified device
 *
 * Note:  This is no longer used as a callback
 */
int
netvsc_recv(struct hv_device *device_ctx, netvsc_packet *packet,
    rndis_tcp_ip_csum_info *csum_info)
{
	hn_softc_t *sc = (hn_softc_t *)device_get_softc(device_ctx->device);
	struct mbuf *m_new;
	struct ifnet *ifp;
	device_t dev = device_ctx->device;
	int size;

	if (sc == NULL) {
		return (0); /* TODO: KYS how can this be! */
	}

	ifp = sc->hn_ifp;

	ifp = sc->arpcom.ac_ifp;

	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
		return (0);
	}

	/*
	 * Bail out if packet contains more data than configured MTU.
	 */
	if (packet->tot_data_buf_len > (ifp->if_mtu + ETHER_HDR_LEN)) {
		return (0);
	}

	/*
	 * Get an mbuf with a cluster.  For packets 2K or less,
	 * get a standard 2K cluster.  For anything larger, get a
	 * 4K cluster.  Any buffers larger than 4K can cause problems
	 * if looped around to the Hyper-V TX channel, so avoid them.
	 */
	size = MCLBYTES;

	if (packet->tot_data_buf_len > MCLBYTES) {
		/* 4096 */
		size = MJUMPAGESIZE;
	}

	m_new = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, size);

	if (m_new == NULL) {
		device_printf(dev, "alloc mbuf failed.\n");
		return (0);
	}

	hv_m_append(m_new, packet->tot_data_buf_len,
			packet->data);

	m_new->m_pkthdr.rcvif = ifp;

	/* receive side checksum offload */
	m_new->m_pkthdr.csum_flags = 0;
	if (NULL != csum_info) {
		/* IP csum offload */
		if (csum_info->receive.ip_csum_succeeded) {
			m_new->m_pkthdr.csum_flags |=
			    (CSUM_IP_CHECKED | CSUM_IP_VALID);
		}

		/* TCP csum offload */
		if (csum_info->receive.tcp_csum_succeeded) {
			m_new->m_pkthdr.csum_flags |=
			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
			m_new->m_pkthdr.csum_data = 0xffff;
		}
	}

	if ((packet->vlan_tci != 0) &&
	    (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0) {
		m_new->m_pkthdr.ether_vtag = packet->vlan_tci;
		m_new->m_flags |= M_VLANTAG;
	}

	/*
	 * Note:  Moved RX completion back to hv_nv_on_receive() so all
	 * messages (not just data messages) will trigger a response.
	 */

	ifp->if_ipackets++;

	/* We're not holding the lock here, so don't release it */
	(*ifp->if_input)(ifp, m_new);

	return (0);
}

/*
 * Rules for using sc->temp_unusable:
 * 1.  sc->temp_unusable can only be read or written while holding NV_LOCK()
 * 2.  code reading sc->temp_unusable under NV_LOCK(), and finding
 *     sc->temp_unusable set, must release NV_LOCK() and exit
 * 3.  to retain exclusive control of the interface,
 *     sc->temp_unusable must be set by code before releasing NV_LOCK()
 * 4.  only code setting sc->temp_unusable can clear sc->temp_unusable
 * 5.  code setting sc->temp_unusable must eventually clear sc->temp_unusable
 */

/*
 * Standard ioctl entry point.  Called when the user wants to configure
 * the interface.
 */
static int
hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
	hn_softc_t *sc = ifp->if_softc;
	struct ifreq *ifr = (struct ifreq *)data;
#ifdef INET
	struct ifaddr *ifa = (struct ifaddr *)data;
#endif
	netvsc_device_info device_info;
	struct hv_device *hn_dev;
	int mask, error = 0;
	int retry_cnt = 500;

	switch(cmd) {

	case SIOCSIFADDR:
#ifdef INET
		if (ifa->ifa_addr->sa_family == AF_INET) {
			ifp->if_flags |= IFF_UP;
			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
				hn_ifinit(sc);
			arp_ifinit(ifp, ifa);
		} else
#endif
		error = ether_ioctl(ifp, cmd, data);
		break;
	case SIOCSIFMTU:
		hn_dev = vmbus_get_devctx(sc->hn_dev);

		/* Check MTU value change */
		if (ifp->if_mtu == ifr->ifr_mtu)
			break;

		if (ifr->ifr_mtu > NETVSC_MAX_CONFIGURABLE_MTU) {
			error = EINVAL;
			break;
		}

		/* Obtain and record requested MTU */
		ifp->if_mtu = ifr->ifr_mtu;

		do {
			NV_LOCK(sc);
			if (!sc->temp_unusable) {
				sc->temp_unusable = TRUE;
				retry_cnt = -1;
			}
			NV_UNLOCK(sc);
			if (retry_cnt > 0) {
				retry_cnt--;
				DELAY(5 * 1000);
			}
		} while (retry_cnt > 0);

		if (retry_cnt == 0) {
			error = EINVAL;
			break;
		}

		/* We must remove and add back the device to cause the new
		 * MTU to take effect.  This includes tearing down, but not
		 * deleting the channel, then bringing it back up.
		 */
		error = hv_rf_on_device_remove(hn_dev, HV_RF_NV_RETAIN_CHANNEL);
		if (error) {
			NV_LOCK(sc);
			sc->temp_unusable = FALSE;
			NV_UNLOCK(sc);
			break;
		}
		error = hv_rf_on_device_add(hn_dev, &device_info);
		if (error) {
			NV_LOCK(sc);
			sc->temp_unusable = FALSE;
			NV_UNLOCK(sc);
			break;
		}

		hn_ifinit_locked(sc);

		NV_LOCK(sc);
		sc->temp_unusable = FALSE;
		NV_UNLOCK(sc);
		break;
	case SIOCSIFFLAGS:
		do {
                       NV_LOCK(sc);
                       if (!sc->temp_unusable) {
                               sc->temp_unusable = TRUE;
                               retry_cnt = -1;
                       }
                       NV_UNLOCK(sc);
                       if (retry_cnt > 0) {
                      	        retry_cnt--;
                        	DELAY(5 * 1000);
                       }
                } while (retry_cnt > 0);

                if (retry_cnt == 0) {
                       error = EINVAL;
                       break;
                }

		if (ifp->if_flags & IFF_UP) {
			/*
			 * If only the state of the PROMISC flag changed,
			 * then just use the 'set promisc mode' command
			 * instead of reinitializing the entire NIC. Doing
			 * a full re-init means reloading the firmware and
			 * waiting for it to start up, which may take a
			 * second or two.
			 */
#ifdef notyet
			/* Fixme:  Promiscuous mode? */
			if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
			    ifp->if_flags & IFF_PROMISC &&
			    !(sc->hn_if_flags & IFF_PROMISC)) {
				/* do something here for Hyper-V */
			} else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
			    !(ifp->if_flags & IFF_PROMISC) &&
			    sc->hn_if_flags & IFF_PROMISC) {
				/* do something here for Hyper-V */
			} else
#endif
				hn_ifinit_locked(sc);
		} else {
			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
				hn_stop(sc);
			}
		}
		NV_LOCK(sc);
		sc->temp_unusable = FALSE;
		NV_UNLOCK(sc);
		sc->hn_if_flags = ifp->if_flags;
		error = 0;
		break;
	case SIOCSIFCAP:
		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
		if (mask & IFCAP_TXCSUM) {
			if (IFCAP_TXCSUM & ifp->if_capenable) {
				ifp->if_capenable &= ~IFCAP_TXCSUM;
				ifp->if_hwassist &= ~(CSUM_TCP | CSUM_UDP);
			} else {
				ifp->if_capenable |= IFCAP_TXCSUM;
				/*
				 * Only enable UDP checksum offloading on
				 * Windows Server 2012R2 or later releases.
				 */
				if (hv_vmbus_protocal_version >=
				    HV_VMBUS_VERSION_WIN8_1) {
					ifp->if_hwassist |=
					    (CSUM_TCP | CSUM_UDP);
				} else {
					ifp->if_hwassist |= CSUM_TCP;
				}
			}
		}

		if (mask & IFCAP_RXCSUM) {
			if (IFCAP_RXCSUM & ifp->if_capenable) {
				ifp->if_capenable &= ~IFCAP_RXCSUM;
			} else {
				ifp->if_capenable |= IFCAP_RXCSUM;
			}
		}

		if (mask & IFCAP_TSO4) {
			ifp->if_capenable ^= IFCAP_TSO4;
			ifp->if_hwassist ^= CSUM_IP_TSO;
		}

		if (mask & IFCAP_TSO6) {
			ifp->if_capenable ^= IFCAP_TSO6;
			ifp->if_hwassist ^= CSUM_IP6_TSO;
		}

		error = 0;
		break;
	case SIOCADDMULTI:
	case SIOCDELMULTI:
#ifdef notyet
		/* Fixme:  Multicast mode? */
		if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
			NV_LOCK(sc);
			netvsc_setmulti(sc);
			NV_UNLOCK(sc);
			error = 0;
		}
#endif
		/* FALLTHROUGH */
	case SIOCSIFMEDIA:
	case SIOCGIFMEDIA:
		error = EINVAL;
		break;
	default:
		error = ether_ioctl(ifp, cmd, data);
		break;
	}

	return (error);
}

/*
 *
 */
static void
hn_stop(hn_softc_t *sc)
{
	struct ifnet *ifp;
	int ret;
	struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);

	ifp = sc->hn_ifp;

	if (bootverbose)
		printf(" Closing Device ...\n");

	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
	if_link_state_change(ifp, LINK_STATE_DOWN);
	sc->hn_initdone = 0;

	ret = hv_rf_on_close(device_ctx);
}

/*
 * FreeBSD transmit entry point
 */
static void
hn_start(struct ifnet *ifp)
{
	hn_softc_t *sc;

	sc = ifp->if_softc;
	NV_LOCK(sc);
	if (sc->temp_unusable) {
		NV_UNLOCK(sc);
		return;
	}
	hn_start_locked(ifp);
	NV_UNLOCK(sc);
}

/*
 *
 */
static void
hn_ifinit_locked(hn_softc_t *sc)
{
	struct ifnet *ifp;
	struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
	int ret;

	ifp = sc->hn_ifp;

	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
		return;
	}

	hv_promisc_mode = 1;

	ret = hv_rf_on_open(device_ctx);
	if (ret != 0) {
		return;
	} else {
		sc->hn_initdone = 1;
	}
	ifp->if_drv_flags |= IFF_DRV_RUNNING;
	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
	if_link_state_change(ifp, LINK_STATE_UP);
}

/*
 *
 */
static void
hn_ifinit(void *xsc)
{
	hn_softc_t *sc = xsc;

	NV_LOCK(sc);
	if (sc->temp_unusable) {
		NV_UNLOCK(sc);
		return;
	}
	sc->temp_unusable = TRUE;
	NV_UNLOCK(sc);

	hn_ifinit_locked(sc);

	NV_LOCK(sc);
	sc->temp_unusable = FALSE;
	NV_UNLOCK(sc);
}

#ifdef LATER
/*
 *
 */
static void
hn_watchdog(struct ifnet *ifp)
{
	hn_softc_t *sc;
	sc = ifp->if_softc;

	printf("hn%d: watchdog timeout -- resetting\n", sc->hn_unit);
	hn_ifinit(sc);    /*???*/
	ifp->if_oerrors++;
}
#endif

static device_method_t netvsc_methods[] = {
        /* Device interface */
        DEVMETHOD(device_probe,         netvsc_probe),
        DEVMETHOD(device_attach,        netvsc_attach),
        DEVMETHOD(device_detach,        netvsc_detach),
        DEVMETHOD(device_shutdown,      netvsc_shutdown),

        { 0, 0 }
};

static driver_t netvsc_driver = {
        NETVSC_DEVNAME,
        netvsc_methods,
        sizeof(hn_softc_t)
};

static devclass_t netvsc_devclass;

DRIVER_MODULE(hn, vmbus, netvsc_driver, netvsc_devclass, 0, 0);
MODULE_VERSION(hn, 1);
MODULE_DEPEND(hn, vmbus, 1, 1, 1);
SYSINIT(netvsc_initx, SI_SUB_KTHREAD_IDLE, SI_ORDER_MIDDLE + 1, netvsc_init,
     NULL);


text:
/* Author: Ioan Sucan, E. Gil Jones */

#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/profiler/profiler.h>
#include <ros/ros.h>

#include <memory>
#include <typeinfo>

namespace robot_model_loader
{
RobotModelLoader::RobotModelLoader(const std::string& robot_description, bool load_kinematics_solvers)
{
  Options opt(robot_description);
  opt.load_kinematics_solvers_ = load_kinematics_solvers;
  configure(opt);
}

RobotModelLoader::RobotModelLoader(const Options& opt)
{
  configure(opt);
}

RobotModelLoader::~RobotModelLoader()
{
  // Make sure we destroy the robot model first. It contains the loaded
  // kinematics plugins, and those must be destroyed before the pluginlib class
  // that implements them is destroyed (that happens when kinematics_loader_ is
  // destroyed below). This is a workaround - ideally pluginlib would handle
  // this better.
  model_.reset();
  rdf_loader_.reset();
  kinematics_loader_.reset();
}

namespace
{
bool canSpecifyPosition(const moveit::core::JointModel* jmodel, const unsigned int index)
{
  bool ok = false;
  if (jmodel->getType() == moveit::core::JointModel::PLANAR && index == 2)
    ROS_ERROR("Cannot specify position limits for orientation of planar joint '%s'", jmodel->getName().c_str());
  else if (jmodel->getType() == moveit::core::JointModel::FLOATING && index > 2)
    ROS_ERROR("Cannot specify position limits for orientation of floating joint '%s'", jmodel->getName().c_str());
  else if (jmodel->getType() == moveit::core::JointModel::REVOLUTE &&
           static_cast<const moveit::core::RevoluteJointModel*>(jmodel)->isContinuous())
    ROS_ERROR("Cannot specify position limits for continuous joint '%s'", jmodel->getName().c_str());
  else
    ok = true;
  return ok;
}
}  // namespace

void RobotModelLoader::configure(const Options& opt)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RobotModelLoader::configure");

  ros::WallTime start = ros::WallTime::now();
  if (!opt.urdf_string_.empty() && !opt.srdf_string_.empty())
    rdf_loader_ = std::make_shared<rdf_loader::RDFLoader>(opt.urdf_string_, opt.srdf_string_);
  else
    rdf_loader_ = std::make_shared<rdf_loader::RDFLoader>(opt.robot_description_);
  if (rdf_loader_->getURDF())
  {
    const srdf::ModelSharedPtr& srdf =
        rdf_loader_->getSRDF() ? rdf_loader_->getSRDF() : std::make_shared<srdf::Model>();
    model_ = std::make_shared<moveit::core::RobotModel>(rdf_loader_->getURDF(), srdf);
  }

  if (model_ && !rdf_loader_->getRobotDescription().empty())
  {
    moveit::tools::Profiler::ScopedBlock prof_block2("RobotModelLoader::configure joint limits");

    // if there are additional joint limits specified in some .yaml file, read those in
    ros::NodeHandle nh("~");

    for (moveit::core::JointModel* joint_model : model_->getJointModels())
    {
      std::vector<moveit_msgs::JointLimits> joint_limit = joint_model->getVariableBoundsMsg();
      for (std::size_t joint_id = 0; joint_id < joint_limit.size(); ++joint_id)
      {
        std::string prefix =
            rdf_loader_->getRobotDescription() + "_planning/joint_limits/" + joint_limit[joint_id].joint_name + "/";

        double max_position;
        if (nh.getParam(prefix + "max_position", max_position))
        {
          if (canSpecifyPosition(joint_model, joint_id))
          {
            joint_limit[joint_id].has_position_limits = true;
            joint_limit[joint_id].max_position = max_position;
          }
        }
        double min_position;
        if (nh.getParam(prefix + "min_position", min_position))
        {
          if (canSpecifyPosition(joint_model, joint_id))
          {
            joint_limit[joint_id].has_position_limits = true;
            joint_limit[joint_id].min_position = min_position;
          }
        }
        double max_velocity;
        if (nh.getParam(prefix + "max_velocity", max_velocity))
        {
          joint_limit[joint_id].has_velocity_limits = true;
          joint_limit[joint_id].max_velocity = max_velocity;
        }
        bool has_vel_limits;
        if (nh.getParam(prefix + "has_velocity_limits", has_vel_limits))
          joint_limit[joint_id].has_velocity_limits = has_vel_limits;

        double max_acc;
        if (nh.getParam(prefix + "max_acceleration", max_acc))
        {
          joint_limit[joint_id].has_acceleration_limits = true;
          joint_limit[joint_id].max_acceleration = max_acc;
        }
        bool has_acc_limits;
        if (nh.getParam(prefix + "has_acceleration_limits", has_acc_limits))
          joint_limit[joint_id].has_acceleration_limits = has_acc_limits;
      }
      joint_model->setVariableBounds(joint_limit);
    }
  }

  if (model_ && opt.load_kinematics_solvers_)
    loadKinematicsSolvers();

  ROS_DEBUG_STREAM_NAMED("robot_model_loader",
                         "Loaded kinematic model in " << (ros::WallTime::now() - start).toSec() << " seconds");
}

void RobotModelLoader::loadKinematicsSolvers(const kinematics_plugin_loader::KinematicsPluginLoaderPtr& kloader)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RobotModelLoader::loadKinematicsSolvers");

  if (rdf_loader_ && model_)
  {
    // load the kinematics solvers
    if (kloader)
      kinematics_loader_ = kloader;
    else
      kinematics_loader_ =
          std::make_shared<kinematics_plugin_loader::KinematicsPluginLoader>(rdf_loader_->getRobotDescription());
    moveit::core::SolverAllocatorFn kinematics_allocator =
        kinematics_loader_->getLoaderFunction(rdf_loader_->getSRDF());
    const std::vector<std::string>& groups = kinematics_loader_->getKnownGroups();
    std::stringstream ss;
    std::copy(groups.begin(), groups.end(), std::ostream_iterator<std::string>(ss, " "));
    ROS_DEBUG_STREAM("Loaded information about the following groups: '" << ss.str() << "'");
    if (groups.empty() && !model_->getJointModelGroups().empty())
      ROS_WARN("No kinematics plugins defined. Fill and load kinematics.yaml!");

    std::map<std::string, moveit::core::SolverAllocatorFn> imap;
    for (const std::string& group : groups)
    {
      // Check if a group in kinematics.yaml exists in the srdf
      if (!model_->hasJointModelGroup(group))
        continue;

      const moveit::core::JointModelGroup* jmg = model_->getJointModelGroup(group);

      kinematics::KinematicsBasePtr solver = kinematics_allocator(jmg);
      if (solver)
      {
        std::string error_msg;
        if (solver->supportsGroup(jmg, &error_msg))
        {
          imap[group] = kinematics_allocator;
        }
        else
        {
          const auto& s = *solver;  // avoid clang-tidy's -Wpotentially-evaluated-expression
          ROS_ERROR("Kinematics solver %s does not support joint group %s.  Error: %s", typeid(s).name(), group.c_str(),
                    error_msg.c_str());
        }
      }
      else
      {
        ROS_ERROR("Kinematics solver could not be instantiated for joint group %s.", group.c_str());
      }
    }
    model_->setKinematicsAllocators(imap);

    // set the default IK timeouts
    const std::map<std::string, double>& timeout = kinematics_loader_->getIKTimeout();
    for (const std::pair<const std::string, double>& it : timeout)
    {
      if (!model_->hasJointModelGroup(it.first))
        continue;
      moveit::core::JointModelGroup* jmg = model_->getJointModelGroup(it.first);
      jmg->setDefaultIKTimeout(it.second);
    }
  }
}
}  // namespace robot_model_loader

redpajama_set_name: RedPajamaGithub


text:
from utils.header import Header, NonEncodingField

class LcStr(Header):
    FIELDS = (
        NonEncodingField('value'),
    )

    def __init__(self, desc, bytes_):
        self.desc = desc
        assert bytes_[-1] == '\x00'  # must be C NULL terminated
        self.value = None
        super(LcStr, self).__init__('lc_str: %s' % desc, value=bytes_[:-1])

    def __len__(self):
        return len(self.value) + 1

    @staticmethod
    def find_str(desc, bytes_):
        for idx in xrange(len(bytes_)):
            if bytes_[idx] == '\x00':
                return LcStr(desc, bytes_[:idx+1])
        return None


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  newRuleExpressionIndex: 0,  // Default value
  ruleExpressions: [
    {
      index: 0,
      expression: { id: 'meta', label: 'Meta' },
      keys: [
        { id: 'length', label: 'Longitud del paquete' },
        { id: 'protocol', label: 'Protocolo' },
        { id: 'priority', label: 'Prioridad del paquete' },
        { id: 'mark', label: 'Marca del paquete' },
        { id: 'iif', label: 'Índice de la interfaz de entrada' },
        { id: 'iffname', label: 'Nombre de la interfaz de entrada' },
        { id: 'ifftype', label: 'Tipo de la interfaz de entrada' },
        { id: 'oif', label: 'Índice de la interfaz de salida' },
        { id: 'oifname', label: 'Nombre de la interfaz de salida' },
        { id: 'ofitype', label: 'Tipo de hardware de la interfaz de salida' },
        { id: 'skuid', label: 'UID asociada al socket de origen' },
        { id: 'skgid', label: 'GID asociada al socket de origen' },
        { id: 'rtclassid', label: 'Reino de enrutamiento' },
      ]
    },
    {
      index: 1,
      expression: { id: 'ether', label: 'Ethernet' },
      keys: [
        { id: 'daddr', label: 'Dirección MAC de destino' },
        { id: 'saddr', label: 'Dirección MAC de origen' },
        { id: 'type', label: 'EtherType' },
      ]
    },
    {
      index: 2,
      expression: { id: 'vlan', label: 'VLAN' },
      keys: [
        { id: 'id', label: 'VLAN ID (VID)' },
        { id: 'cfi', label: 'Indicador de formato canónico' },
        { id: 'pcp', label: 'Punto de código de prioridad' },
        { id: 'type', label: 'EtherType' },
      ]
    },
    {
      index: 3,
      expression: { id: 'arp', label: 'ARP' },
      keys: [
        { id: 'htype', label: 'Tipo de hardware ARP' },
        { id: 'ptype', label: 'EtherType' },
        { id: 'hlen', label: 'Longitud de la dirección hardware' },
        { id: 'plen', label: 'Longitudo de la dirección del protocolo' },
        { id: 'op', label: 'Operación' },
      ]
    },
    {
      index: 4,
      expression: { id: 'ip', label: 'IPv4' },
      keys: [
        { id: 'version', label: 'Versión de la cabecera IP' },
        { id: 'hdrlength', label: 'Longitud de la cabecera IP (incluye opciones)' },
        { id: 'tos', label: 'Tipo de servicio' },
        { id: 'length', label: 'Longitud del paquete' },
        { id: 'id', label: 'ID de la IP' },
        { id: 'frag-off', label: 'Offset del framento' },
        { id: 'ttl', label: 'Tiempo de vida' },
        { id: 'protocol', label: 'Protocolo de la capa superior' },
        { id: 'checksum', label: 'Checksum de la cabecera IP' },
        { id: 'saddr', label: 'Dirección de origen' },
        { id: 'daddr', label: 'Dirección de destino' },
      ]
    },
    {
      index: 5,
      expression: { id: 'ip6', label: 'IPv6' },
      keys: [
        { id: 'version', label: 'Versión de la cabecera IP' },
        { id: 'flowlabel', label: 'Etiqueta de flujo' },
        { id: 'length', label: 'Longitud del campo de datos' },
        { id: 'nexthdr', label: 'Cabecera siguiente' },
        { id: 'hoplimit', label: 'Límite de saltos' },
        { id: 'saddr', label: 'Dirección de origen' },
        { id: 'daddr', label: 'Dirección de destino' },
      ]
    },
    {
      index: 6,
      expression: { id: 'tcp', label: 'TCP' },
      keys: [
        { id: 'sport', label: 'Puerto de origen' },
        { id: 'dport', label: 'Puerto de destino' },
        { id: 'sequence', label: 'Número de secuencia' },
        { id: 'ackseq', label: 'Número de acuse de recibo' },
        { id: 'doff', label: 'Offset de los datos' },
        { id: 'reserved', label: 'Area reservada' },
        { id: 'flags', label: 'TCP Flags' },
        { id: 'window', label: 'Ventana' },
        { id: 'checksum', label: 'Suma de verificación' },
        { id: 'urgptr', label: 'Puntero urgente' },
      ]
    },
    {
      index: 7,
      expression: { id: 'udp', label: 'UDP' },
      keys: [
        { id: 'sport', label: 'Puerto de origen' },
        { id: 'dport', label: 'Puerto de destino' },
        { id: 'length', label: 'Longitud del mensaje' },
        { id: 'checksum', label: 'Suma de verificación' },
      ]
    },
    {
      index: 8,
      expression: { id: 'udplite', label: 'UDP-Lite' },
      keys: [
        { id: 'sport', label: 'Puerto de origen' },
        { id: 'dport', label: 'Puerto de destino' },
        { id: 'cscov', label: 'Covertura de la suma de verificación' },
        { id: 'checksum', label: 'Suma de verificación' },
      ]
    },
    {
      index: 9,
      expression: { id: 'sctp', label: 'SCTP' },
      keys: [
        { id: 'sport', label: 'Puerto de origen' },
        { id: 'dport', label: 'Puerto de destino' },
        { id: 'vtag', label: 'Etiqueta de verificación' },
        { id: 'checksum', label: 'Suma de verificación' },
      ]
    },
    {
      index: 10,
      expression: { id: 'dccp', label: 'DCCP' },
      keys: [
        { id: 'sport', label: 'Puerto de origen' },
        { id: 'dport', label: 'Puerto de destino' },
      ]
    },
    {
      index: 11,
      expression: { id: 'ah', label: 'Cabecera de autenticación' },
      keys: [
        { id: 'nexthdr', label: 'Protocolo de la cabecera siguiente' },
        { id: 'hdrlength', label: 'Longitud de la cabecera' },
        { id: 'reserved', label: 'Área reservada' },
        { id: 'spi', label: 'Índice del parámetro de seguridad' },
        { id: 'sequence', label: 'Número de secuencia' },
      ]
    },
    {
      index: 12,
      expression: { id: 'esp', label: 'ESP' },
      keys: [
        { id: 'spi', label: 'Índice del parámetro de seguridad' },
        { id: 'sequence', label: 'Número de secuencia' },
      ]
    },
    {
      index: 13,
      expression: { id: 'ipcomp', label: 'IPComp' },
      keys: [
        { id: 'nexthdr', label: 'Protocolo de la cabecera siguiente' },
        { id: 'flags', label: 'Flags' },
        { id: 'cfi', label: 'Índice del parámetro de compresión' },
      ]
    },
    {
      index: 14,
      expression: { id: 'ct', label: 'Conntrack' },
      keys: [
        { id: 'state', label: 'Estado de la conexión (State)' },
        { id: 'direction', label: 'Dirección del paquete respecto a la conexión' },
        { id: 'status', label: 'Estado de la conexión (Status)' },
        { id: 'mark', label: 'Marca de la conexión' },
        { id: 'expiration', label: 'Expiración de la conexión' },
        { id: 'helper', label: 'Asistente asociado a la conexión' },
        { id: 'l3proto', label: 'Protocolo de capa de 3 de la conexión' },
        { id: 'saddr', label: 'Dirección de origen de la conexión para la dirección dada' },
        { id: 'daddr', label: 'Dirección de destino de la conexión para la direción dada' },
        { id: 'protocol', label: 'Protocolo de la capa 4 de la conexión para la dirección dada' },
        { id: 'proto-src', label: 'Protocolo de origen de la capa 4 de la conexión para la direción dada' },
        { id: 'proto-dst', label: 'Protocolo de destino de la capa 4 de la conexión para la direción dada' },
      ]
    }
  ],
  newRuleStatementType: 'hardcoded',  // Default value
  statementType: [
    { id: 'hardcoded', label: 'Directamente' },
    { id: 'set', label: 'Conjunto' },
    { id: 'dictionary', label: 'Diccionario' },
  ],
  newRuleHardcodedArgs: [],

  selectedExpression: function () {
    let i = this.get('newRuleExpressionIndex');
    return this.get('ruleExpressions').objectAt(i);
  }.property('newRuleExpressionIndex'),
  selectedExpressionKeys: function () {
    let keys = this.get('selectedExpression').keys;
    this.set('newRuleKey', keys.objectAt(0).id);  // Default value
    return keys;
  }.property('newRuleExpressionIndex'),
  newRuleStatementHardcoded: function () {
    return this.get('newRuleStatementType') === 'hardcoded';
  }.property('newRuleStatementType'),
  newRuleStatementSet: function () {
    return this.get('newRuleStatementType') === 'set';
  }.property('newRuleStatementType'),
  newRuleStatementDictionary: function () {
    return this.get('newRuleStatementType') === 'dictionary';
  }.property('newRuleStatementType'),

  actions: {
    showAddRuleModal: function () {
      this.get('addRuleModal').send('show');
    },
    showEditModal: function () {
      this.get('editChainModal').send('show');
    },
    showEmptyConfirmationModal: function () {
      this.get('emptyConfirmationModal').send('show');
    },
    showDeleteConfirmationModal: function () {
      this.get('deleteConfirmationModal').send('show');
    },
    removeStatementRow: function (index) {
      this.get('newRuleHardcodedArgs').removeAt(index);
    },
    addStatementRow: function () {
      this.get('newRuleHardcodedArgs').pushObject({ match: this.get('newRuleMatch'), action: this.get('newRuleJumps') });
      // Reset values
      this.set('newRuleMatch', '');
      this.set('newRuleJumps', '');
    },
    saveNewRule: function () {
      this.get('newRuleHardcodedArgs').pushObject({ match: this.get('newRuleMatch'), action: this.get('newRuleJumps') });
      let rule = this.store.createRecord('rule', {
        expression: this.get('selectedExpression').expression.id,
        key: this.get('newRuleKey'),
        chain: this.get('chain')
      });
      if (this.get('newRuleStatementHardcoded')) {
        rule.statements = this.get('newRuleHardcodedArgs').toArray();
      }
      else if (this.get('newRuleStatementSet')) {
        if (this.get('chain.table.sets.length') > 0 && ! this.get('newRuleSetArg')) {
          this.set('newRuleSetArg', this.get('chain.table.sets').objectAt(0).get('name'));
        }
        rule.statements = [{ set: '@' + this.get('newRuleSetArg'), action: this.get('newRuleSetArgActions') }];
      }
      else {
        rule.statements = ['vmap @' + this.get('newRuleDictionaryArg')];
      }
      rule.save()
        .then((model) => {
          // Reset values
          this.set('selectedExpressionIndex', 0);
          this.set('newRuleMatch', '');
          this.set('newRuleJumps', '');
          this.get('newRuleHardcodedArgs').clear();
        })
        .catch((err) => {
          console.log('SAVING RULE ERROR')
          console.log(err);
          rule.deleteRecord();
          Ember.$.notification('error', err.errors.message);
          this.get('newRuleHardcodedArgs').clear();
        });
    },
    emptyChain: function () {
      this.get('chain.rules').toArray().forEach(x => x.destroyRecord());
    },
    deleteChain: function () {
      let chain = this.get('chain');
      let chainTable = this.get('chain.table');
      chain.one('didDelete', () => this.transitionToRoute('table', chainTable));
      chain.destroyRecord();
    }
  }
});


text:
<?php defined('SYSPATH') or die('No direct script access.');
/*
 * Submenu widget for admin pages
 */
class Controller_Widgets_Submenu extends Controller_Widgets {

    public $template = 'admin/w/';    // Path to widgets folder to be concatenated with file name

    public function before()
    {
        $this->template .= ( $this->request->param( 'param' ) )
                ?  $this->request->param( 'param' )
                : strtolower( $this->request->initial()->controller() ) . '_' . $this->request->initial()->action();
        parent::before();

        $this->cache_lifetime = 0;
    }

    public function action_index()
    {
        $this->template->instance = ORM::factory( $this->request->initial()->controller(), $this->request->initial()->param( 'id' ) );
    }

}


text:
package de.uni_jena.min.in0043.nine_mens_morris.gui;

import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import de.uni_jena.min.in0043.nine_mens_morris.net.LogInClient;

public class TestLogIn extends Panel implements ActionListener {

	private static final long serialVersionUID = 8838423681956882828L;
	private static Logger log = LogManager.getLogger();
	private Frame screen;
	private int width = 300;
	private int height = 300;
	private int width2 = 600;
	private int height2 = 600;
	private String user;
	private char[] pass;
	private boolean newU;
	private JTextField username = new JTextField();
	private JPasswordField password = new JPasswordField();
	private JButton ok, cancel;
	private JCheckBox newUser;
	private boolean nextLine;
	private LogInClient client;

	private List<JButton> Players;
	private int[] numbers;
	private String[] names;

	public TestLogIn()
	{
		screen = new Frame("LogIn Menu");
		screen.setSize(width, height);
		user = null;
		pass = null;
		ok = new JButton("Ok");
		cancel = new JButton("Cancel");
		newUser = new JCheckBox("Register me!");
		newU = false;
		nextLine = false;
		Players = new ArrayList<JButton>();
		client = new LogInClient();
	}

	public void LoggingIn() {
		screen.setLayout(null);
		username.setBounds(width/2 - 100, height/2 - 15, 200, 30);
		password.setBounds(width/2 - 100, height/2 + 15, 200, 30);
		newUser.setBounds(width/2 - 100, height/2 + 50, 200, 30);
		ok.setBounds(width/2 - 100, height/2 + 100, 100, 20);
		cancel.setBounds(width/2, height/2 + 100, 100, 20);
		this.setBounds(0, 0, width, height);
		screen.add(username);
		screen.add(password);
		screen.add(newUser);
		screen.add(ok);
		screen.add(cancel);
		screen.setForeground(new Color(0, 0, 0));
		screen.setBackground(new Color(255, 255, 255));
		screen.setVisible(true);
		screen.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				int n = JOptionPane.showConfirmDialog(
						screen,
						"Would you like to close the application?",
						"A stupid question",
						JOptionPane.YES_NO_OPTION);
				if(n == 0)
					System.exit(0);
			}
		});

		ok.addActionListener(this);
		cancel.addActionListener(this);
		newUser.addActionListener(this);

		if(nextLine) {
			screen.remove(username);
			screen.remove(password);
			screen.remove(newUser);
			screen.remove(ok);
			screen.remove(cancel);
			screen.setSize(width2, height2);

			numbers = new int[20];
			names = new String[numbers.length];
			JButton x;
			for(int i = 0; i < names.length; i++) {
				screen.setLayout(new GridLayout(names.length, 0));
				names[i] = "" + (i+1);
				JButton d = new JButton(names[i]);
				Players.add(d);
				x = Players.get(i);
				screen.add(x);
				Players.get(i).addActionListener(this);
			}
			screen.setVisible(false);
			screen.setVisible(true);
		}

	}

	public static void main(String[] args)
	{
		TestLogIn G = new TestLogIn();
		G.LoggingIn();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(!nextLine) {
		 user = username.getText();
		 pass = password.getPassword();
		 String g = "\nUsername: " + user + "\nPassword: ";
		 for(int i = 0; i < pass.length; i++) {
			 g += pass[i];
		 }
		 log.debug(g + "\nNewUser: " + newU);

		 if(newUser == e.getSource()){
			 if(newU == false)
			 newU = true;
			 else newU = false;
		 }
		 if( ok == e.getSource())
		 {
			 if(newU == true)
			 {
				 boolean register = client.register(user, pass);
				 if(!register)
					 log.trace("Username taken");
				 else { pass = null;
				 		nextLine = true;
				 		this.LoggingIn(); }
			 }
			 else {
				 boolean login = client.loggingIn(user, pass);
				 if(login) { pass = null;
				 			 nextLine = true;
				 			 this.LoggingIn(); }
				 else log.trace("Wrong user, password combination");
			 }
		 }
		 else if( cancel == e.getSource())
		 {
			 client.disconnect();
			 System.exit(0);
		 }
		}//!newline
		else {
			Object source = e.getSource();
			int number = Integer.parseInt(((JButton)source).getText());
			log.trace(number + " was pressed");
			//TODO an den Server senden
		}
	}
}


text:
package plugin

import (
	"fmt"
	"path"
	"plugin"
	"reflect"

	"github.com/skydive-project/skydive/config"
	"github.com/skydive-project/skydive/logging"
	"github.com/skydive-project/skydive/probe"
	"github.com/skydive-project/skydive/topology/probes"
)

// TopologyPlugin defines topology plugin
type TopologyPlugin struct {
	Name         string
	Register     func()
	AgentCtor    func(ctx probes.Context, bundle *probe.Bundle) (probes.Handler, error)
	AnalyzerCtor func(ctx probes.Context, bundle *probe.Bundle) (probes.Handler, error)
}

// LoadTopologyPlugins load topology plugins
func LoadTopologyPlugins() ([]TopologyPlugin, error) {
	var plugins []TopologyPlugin

	pluginsDir := config.GetString("plugin.plugins_dir")
	probeList := config.GetStringSlice("plugin.topology.probes")

	logging.GetLogger().Infof("Topology plugins: %v", probeList)

	for _, so := range probeList {
		filename := path.Join(pluginsDir, so+".so")
		logging.GetLogger().Infof("Loading plugin %s", filename)

		plugin, err := plugin.Open(filename)
		if err != nil {
			return nil, fmt.Errorf("Failed to load plugin %s: %s", so, err)
		}

		tp := TopologyPlugin{Name: so}

		if symbol, err := plugin.Lookup("Register"); err == nil {
			fnc, ok := symbol.(func())
			if !ok {
				return nil, fmt.Errorf("Invalid plugin %s, %s", so, reflect.TypeOf(symbol))
			}

			tp.Register = fnc
		}

		if symbol, err := plugin.Lookup("NewAgentProbe"); err == nil {
			fnc, ok := symbol.(func(ctx probes.Context, bundle *probe.Bundle) (probes.Handler, error))
			if !ok {
				return nil, fmt.Errorf("Invalid plugin %s, %s", so, reflect.TypeOf(symbol))
			}

			tp.AgentCtor = fnc
		}

		if symbol, err := plugin.Lookup("NewAnalyzerProbe"); err == nil {
			fnc, ok := symbol.(func(ctx probes.Context, bundle *probe.Bundle) (probes.Handler, error))
			if !ok {
				return nil, fmt.Errorf("Invalid plugin %s, %s", so, reflect.TypeOf(symbol))
			}

			tp.AnalyzerCtor = fnc
		}

		if tp.Register == nil {
			return nil, fmt.Errorf("Non compliant plugin '%s': Register function not found", so)
		}

		if tp.AgentCtor == nil && tp.AnalyzerCtor == nil {
			return nil, fmt.Errorf("Non compliant plugin '%s': no constructor found", so)
		}

		plugins = append(plugins, tp)
	}

	return plugins, nil
}


text:
<?php
/*
 * This file is part of NeutronTreeBundle
 *
 * (c) Zender <azazen09@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Neutron\TreeBundle\Tree;

use Doctrine\ORM\EntityManager;

use Neutron\TreeBundle\Model\TreeManager;

use Symfony\Component\HttpFoundation\Request;

use Neutron\Bundle\AsseticBundle\Controller\AsseticController;

/**
 * Factory to create a tree
 *
 * @author Nikolay Georgiev <nikolay.georgiev@zend.bg>
 * @since 1.0
 */
class TreeFactory implements FactoryInterface
{

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @var \Neutron\Bundle\AsseticBundle\Controller\AsseticController
     */
    protected $neutronAssetic;

    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $paths;

    /**
     * Construct
     *
     * @param AsseticController $neutronAssetic
     * @param Request $request
     * @param array $paths
     */
    public function __construct(EntityManager $em, AsseticController $neutronAssetic, Request $request, array $paths)
    {
        $this->em = $em;
        $this->neutronAssetic = $neutronAssetic;
        $this->request = $request;
        $this->paths = $paths;
    }

    /**
     * (non-PHPdoc)
     *
     * @see Neutron\Bundle\DataGridBundle\DataGrid.FactoryInterface::createDataGrid()
     */
    public function createTree ($name, array $options = array())
    {

        $this->neutronAssetic->appendJavascript($this->paths['path_to_jstree'] . '/jquery.jstree.js');
        $this->neutronAssetic->appendJavascript($this->paths['path_to_jquery_cookie_js']);
        $this->neutronAssetic->appendJavascript('bundles/neutrontree/js/init.js');

        $tree = new Tree($name);

        /* merging options */
        $options = array_merge(
            array(
                'name' => null,
                'plugins' => array(),
            ), $options
        );

        /* setting object */
        $tree
            ->setPlugins($options['plugins'])

        ;

        return $tree;
    }

    /**
     * (non-PHPdoc)
     * @see Neutron\TreeBundle\Tree.FactoryInterface::createTreeFromArray()
     */
    public function createTreeFromArray (Array $data)
    {
        $name = isset($data['name']) ? $data['name'] : $name;

        return $this->createTree($name);
    }

    /**
     * (non-PHPdoc)
     * @see Neutron\TreeBundle\Tree.FactoryInterface::createPlugin()
     */
    public function createPlugin($plugin, array $options = array())
    {

        switch (strtolower($plugin)){
            case 'ui':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\UI';
                break;
            case 'contextmenu':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\ContextMenu';
                break;
            case 'dnd':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\Dnd';
                break;
            case 'crrm':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\Crrm';
                break;
            case 'themes':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\Themes';
                break;
            case 'types':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\Types';
                break;
            case 'cookies':
                $plugin = '\Neutron\TreeBundle\Tree\Plugin\Cookies';
                break;
            default:
                throw new \InvalidArgumentException(sprintf('Invalid plugin "%s"!',  $plugin));
        }

        return new $plugin($options);
    }

    /**
     * (non-PHPdoc)
     * @see Neutron\TreeBundle\Tree.FactoryInterface::createManager()
     */
    public function createManager($class)
    {
        $manager = new TreeManager($this->em, $class);

        return $manager;
    }
}


text:
var jsonFile = require('jsonfile')
var json = require('./json')

var fs, fse = {}

try {
  // optional dependency
  fs = require("graceful-fs")
} catch (er) {
  fs = require("fs")
}

//attach fs methods to fse
Object.keys(fs).forEach(function(key) {
  var func = fs[key]
  if (typeof func == 'function')
    fse[key] = func
})
fs = fse

var copy = require('./copy')
fs.copy = copy.copy
fs.copySync = copy.copySync

var remove = require('./remove')
fs.remove = remove.remove
fs.removeSync = remove.removeSync
fs['delete'] = fs.remove
fs.deleteSync = fs.removeSync

var mkdir = require('./mkdir')
fs.mkdirs = mkdir.mkdirs
fs.mkdirsSync = mkdir.mkdirsSync
fs.mkdirp = fs.mkdirs
fs.mkdirpSync = fs.mkdirsSync

var create = require('./create')
fs.createFile = create.createFile
fs.createFileSync = create.createFileSync

fs.ensureFile = create.createFile
fs.ensureFileSync = create.createFileSync
fs.ensureDir = mkdir.mkdirs
fs.ensureDirSync = mkdir.mkdirsSync

var move = require('./move')
fs.move = function(src, dest, opts, callback) {
  if (typeof opts == 'function') {
    callback = opts
    opts = {}
  }

  if (opts.mkdirp == null) opts.mkdirp = true
  if (opts.clobber == null) opts.clobber = false

  move(src, dest, opts, callback)
}

var output = require('./output')
fs.outputFile = output.outputFile
fs.outputFileSync = output.outputFileSync

fs.readJsonFile = jsonFile.readFile
fs.readJSONFile = jsonFile.readFile
fs.readJsonFileSync = jsonFile.readFileSync
fs.readJSONFileSync = jsonFile.readFileSync

fs.readJson = jsonFile.readFile
fs.readJSON = jsonFile.readFile
fs.readJsonSync = jsonFile.readFileSync
fs.readJSONSync = jsonFile.readFileSync

fs.outputJsonSync = json.outputJsonSync
fs.outputJSONSync = json.outputJsonSync
fs.outputJson = json.outputJson
fs.outputJSON = json.outputJson

fs.writeJsonFile = jsonFile.writeFile
fs.writeJSONFile = jsonFile.writeFile
fs.writeJsonFileSync = jsonFile.writeFileSync
fs.writeJSONFileSync = jsonFile.writeFileSync

fs.writeJson = jsonFile.writeFile
fs.writeJSON = jsonFile.writeFile
fs.writeJsonSync = jsonFile.writeFileSync
fs.writeJSONSync = jsonFile.writeFileSync

module.exports = fs

jsonFile.spaces = 2 //set to 2
module.exports.jsonfile = jsonFile //so users of fs-extra can modify jsonFile.spaces


text:
require 'spec_helper'
require 'support/shipping_options'

describe UPS::Connection do
  describe "when setting test mode" do
    subject { UPS::Connection.new(test_mode: true) }

    it "should set the uri to the test url" do
      subject.url.must_equal UPS::Connection::TEST_URL
    end
  end

  describe "when setting live mode" do
    subject { UPS::Connection.new }

    it "should set the uri to the live url" do
      subject.url.must_equal UPS::Connection::LIVE_URL
    end
  end
end


text:
<?php

namespace Slim\Tests\Mocks;

/**
 * Mock object for Slim\Tests\CallableResolverTest
 */
class InvokableTest
{
    public static $CalledCount = 0;
    public function __invoke()
    {
        return static::$CalledCount++;
    }
}


text:
import importlib
import unittest

try:
    import unittest.mock as mock
except ImportError:
    import mock

class TestPrivilege(unittest.TestCase):

    def setUp(self):
        self._win32process_mock = mock.MagicMock()
        self._win32security_mock = mock.MagicMock()
        self._module_patcher = mock.patch.dict(
            'sys.modules',
            {'win32process': self._win32process_mock,
             'win32security': self._win32security_mock})

        self._module_patcher.start()
        self.privilege_module = importlib.import_module(
            "cloudbaseinit.utils.windows.privilege")

    def tearDown(self):
        self._module_patcher.stop()

    def test_privilege_context_manager(self):
        fake_process = mock.MagicMock()
        fake_token = True
        LUID = 'fakeid'
        self._win32process_mock.GetCurrentProcess.return_value = fake_process
        self._win32security_mock.OpenProcessToken.return_value = fake_token
        self._win32security_mock.LookupPrivilegeValue.return_value = LUID
        privilege_enabled = [(LUID,
                             self._win32security_mock.SE_PRIVILEGE_ENABLED)]
        privilege_removed = [(LUID,
                             self._win32security_mock.SE_PRIVILEGE_REMOVED)]
        with self.privilege_module.acquire_privilege(mock.sentinel.privilege):

            self._win32security_mock.AdjustTokenPrivileges.assert_called_with(
                fake_token, False, privilege_enabled)

            self._win32security_mock.OpenProcessToken.assert_called_with(
                fake_process,
                self._win32security_mock.TOKEN_ADJUST_PRIVILEGES |
                self._win32security_mock.TOKEN_QUERY)

        self._win32security_mock.AdjustTokenPrivileges.assert_called_with(
            fake_token, False, privilege_removed)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.citydevs.hazmeelparo.InstructionsActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hola2"/>

</RelativeLayout>


text:
/*
 *  Icedeer 2010 All Rights Reserved.   Classification – Confidential.
 */

package com.icedeer.common.util.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Description: a utility class for manipulate XML DOM tree by using DOM2 mode, and JAXP API.
 *

 * Revision:
 *

 *
 Peter W -- Apr 8, 2010 -- Initial Draft

 *

 *

 *
 */
public class DomHelper {

    private static DocumentBuilder domBuilder = null;

    /**
     * Parses an XML input stream and returns a DOM document. If validating is true, the contents is validated against the DTD specified in
     * the file.
     *
     * @param inputStream
     * @param validating
     * @return
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static Document parseXml(InputStream inputStream, boolean validating) throws DOMException, ParserConfigurationException,
            SAXException, IOException {
        if (domBuilder == null) {
            // Create a builder factory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validating);
            // Configure it to ignore comments
            factory.setIgnoringComments(true);
            // check namespace
            factory.setNamespaceAware(true);

            // Create the builder and parse the file
            domBuilder = factory.newDocumentBuilder();
            // if (!domBuilder.getDOMImplementation().hasFeature("traversal", "2.0")) {
            // supportTraversal = false;
            // }
        }
        Document doc = domBuilder.parse(inputStream);
        // do the normalization
        doc.normalize();

        return doc;

    }

    public static Document parseXml(String xmlContent, boolean validating) throws DOMException, ParserConfigurationException, SAXException,
            IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(xmlContent.getBytes());
        return parseXml(bis, validating);
    }

    /**
     * serializing a XML DOM Document into XML String
     *
     * @param doc
     * @return the string in XML format
     * @throws TransformerException
     */
    public static String saveToXmlStr(Document doc) throws DOMException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();
        return xmlString;

    }

    public static void saveToXml(Document doc, OutputStream os) throws DOMException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        // factory.setAttribute("indent-number", new Integer(2));

        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(os);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);

    }

    public static List<Element> getElementByFilter(Document doc, NodeFilter filter) throws DOMException {
        List<Element> result = new ArrayList<Element>();
        DocumentTraversal traversable = (DocumentTraversal) doc;
        int whatToShow = NodeFilter.SHOW_ELEMENT;
        NodeIterator iterator = traversable.createNodeIterator(doc, whatToShow, filter, true);
        Node current = null;
        while ((current = iterator.nextNode()) != null) {
            result.add((Element) current);
        }
        return result;
    }

    /**
     * a utility method for finding the first child XML element of given XML element
     *
     * @param ele
     * @return
     */
    public static Element getFirstChildElement(Element ele) {
        Element resultEle = null;
        NodeList childNodes = ele.getChildNodes();
        if (childNodes != null) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    resultEle = (Element) node;
                    break;
                }
            }
        }
        return resultEle;
    }

    /**
     * return all the child Elements under given Element parentNode and with the same tag name of tagName ;
     * it's not deep search, so only the first generation children list is scanned
Note: the given tagName is just local
     * name; namespace is not support right now.
     *
     * @param parentNode
     * @param tagName
     * @return
     * @throws DOMException
     */
    public static List<Element> getChildElementsByTagName(Element parentNode, String tagName) {
        if (parentNode == null) {
            return null;
        }
        // if there is no tag name given, treat it as returning all the child Elements
        if (tagName == null || tagName.trim().length() == 0) {
            return getChildElements(parentNode);
        }
        List<Element> resultList = new ArrayList<Element>();
        NodeList childNodes = parentNode.getChildNodes();
        if (childNodes != null) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE && node.getParentNode() == parentNode && node.getLocalName().equals(tagName)) {
                    resultList.add((Element) node);
                }
            }
        }
        return resultList;
    }

    /**
     * return all the child Elements of given Element; it's not deep search, so only the first generation children list is scanned.
     *
     * @param parentNode
     * @return an empty list if nothing found
     * @throws DOMException
     */
    public static List<Element> getChildElements(Element parentNode) throws DOMException {
        if (parentNode == null) {
            return null;
        }
        List<Element> resultList = new ArrayList<Element>();
        NodeList childNodes = parentNode.getChildNodes();
        if (childNodes != null) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE && node.getParentNode() == parentNode) {
                    resultList.add((Element) node);
                }
            }
        }
        return resultList;
    }

    /**
     * create an empty DOM Document with root tag as given in the parameter rootTag
     *
     * @param rootTag
     * @return
     * @throws ParserConfigurationException
     */
    public static Document createDocument(String rootTag) throws ParserConfigurationException {
        // Create a builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation domImpl = builder.getDOMImplementation();

        Document doc = domImpl.createDocument(null, rootTag, null);
        return doc;
    }

    public static Element createElement(Document doc, String tagName) {
        return doc.createElementNS(null, tagName);
    }

    /**
     * Parses a string containing XML and returns a DocumentFragment containing the nodes of the parsed XML.
     *
     * @param doc
     * @param fragment
     * @return
     */
    public static DocumentFragment parseXmlFragmentStr(Document doc, String fragment) {
        // Wrap the fragment in an arbitrary element
        fragment = "<fragment>" + fragment + "</fragment>";
        try {
            // Create a DOM builder and parse the fragment
            Document d = domBuilder.parse(new InputSource(new StringReader(fragment)));

            // Import the nodes of the new document into doc so that they
            // will be compatible with doc
            Node node = doc.importNode(d.getDocumentElement(), true);

            // Create the document fragment node to hold the new nodes
            DocumentFragment docfrag = doc.createDocumentFragment();

            // Move the nodes into the fragment
            while (node.hasChildNodes()) {
                docfrag.appendChild(node.removeChild(node.getFirstChild()));
            }

            // Return the fragment
            return docfrag;
        } catch (SAXException e) {
            // A parsing error occurred; the xml input is not valid
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * generating simple XML string for element with following limitation: 1) only generate non-namespace elements and attributes 2) only
     * consider element, text, attribute nodes
     *
     * @param ele
     * @return
     */
    public static String simpleElementToString(Element ele) {
        StringBuffer sb = new StringBuffer();
        sb.append("<" + ele.getLocalName());
        NamedNodeMap attMap = ele.getAttributes();
        if (attMap != null) {
            for (int i = 0; i < attMap.getLength(); i++) {
                Node att = attMap.item(i);
                sb.append(" " + att.getNodeName() + "=\"");
                sb.append(att.getNodeValue() + "\"");
            }
        }
        sb.append(">");
        List<Element> childEleList = getChildElements(ele);
        if (childEleList != null && !childEleList.isEmpty()) {
            for (Element childEle : childEleList) {
                sb.append(simpleElementToString(childEle));
            }
        } else {
            sb.append(ele.getTextContent());
        }
        sb.append("</" + ele.getLocalName() + ">");
        return sb.toString();
    }

    public static String getValueOfChildElement(Element ele, String tagName){
        List<Element> childElements = getChildElementsByTagName(ele, tagName);
        if(childElements == null || childElements.isEmpty()){
            return null;
        }
        Element childEle = childElements.get(0);
        NodeList childNodes = childEle.getChildNodes();
        if (childNodes != null) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node.getNodeType() == Node.TEXT_NODE ){
                    return node.getTextContent();
                }
                else if(node.getNodeType() == Node.CDATA_SECTION_NODE){
                    return node.getNodeValue();
                }
            }
        }
        return null;
    }

}


text:
namespace ui {
class Event;
}

namespace aura {
class RootWindow;

namespace client {
class ActivationChangeObserver;

// An interface implemented by an object that manages window activation.
class AURA_EXPORT ActivationClient {
 public:
  // Adds/Removes ActivationChangeObservers.
  virtual void AddObserver(ActivationChangeObserver* observer) = 0;
  virtual void RemoveObserver(ActivationChangeObserver* observer) = 0;

  // Activates |window|. If |window| is NULL, nothing happens.
  virtual void ActivateWindow(Window* window) = 0;

  // Deactivates |window|. What (if anything) is activated next is up to the
  // client. If |window| is NULL, nothing happens.
  virtual void DeactivateWindow(Window* window) = 0;

  // Retrieves the active window, or NULL if there is none.
  virtual Window* GetActiveWindow() = 0;

  // Retrieves the activatable window for |window|, or NULL if there is none.
  // Note that this is often but not always the toplevel window (see
  // GetToplevelWindow() below), as the toplevel window may not be activatable
  // (for example it may be blocked by a modal transient, or some other
  // condition).
  virtual Window* GetActivatableWindow(Window* window) = 0;

  // Retrieves the toplevel window for |window|, or NULL if there is none.
  virtual Window* GetToplevelWindow(Window* window) = 0;

  // Invoked prior to |window| getting focus as a result of the |event|. |event|
  // may be NULL. Returning false blocks |window| from getting focus.
  virtual bool OnWillFocusWindow(Window* window, const ui::Event* event) = 0;

  // Returns true if |window| can be activated, false otherwise. If |window| has
  // a modal child it can not be activated.
  virtual bool CanActivateWindow(Window* window) const = 0;

 protected:
  virtual ~ActivationClient() {}
};

// Sets/Gets the activation client on the RootWindow.
AURA_EXPORT void SetActivationClient(RootWindow* root_window,
                                     ActivationClient* client);
AURA_EXPORT ActivationClient* GetActivationClient(RootWindow* root_window);

// Some types of transient window are only visible when active.
// The transient parents of these windows may have visual appearance properties
// that differ from transient parents that can be deactivated.
// The presence of this property implies these traits.
// TODO(beng): currently the UI framework (views) implements the actual
//             close-on-deactivate component of this feature but it should be
//             possible to implement in the aura client.
AURA_EXPORT void SetHideOnDeactivate(Window* window, bool hide_on_deactivate);
AURA_EXPORT bool GetHideOnDeactivate(Window* window);

}  // namespace clients
}  // namespace aura

#endif  // UI_AURA_CLIENT_ACTIVATION_CLIENT_H_


text:
namespace KaiFighterGame.Objects.DynamicObjects.Characters.Enemies
{
    using Microsoft.Xna.Framework;

    using Utilities;

    public class Boss : Wizard
    {
        private const int NormalFireCooldownTime = 60;
        private int fireTime = NormalFireCooldownTime;

        public Boss(Vector2 position, string imageLocation, ObjectType objectType, Color objColor, float scale, float rotation, float layerDepth, float movementSpeed, double damage, double health)
            : base(position, imageLocation, objectType, objColor, scale, rotation, layerDepth, movementSpeed, damage,  health)
        {
        }

        public override void Update(GameTime gameTime)
        {
            this.fireTime--;

            if (this.fireTime <= 0)
            {
                this.Shoot(Vector2.Normalize(new Vector2(-2, 0)));
                this.Shoot(Vector2.Normalize(new Vector2(0, 2)));
                this.Shoot(Vector2.Normalize(new Vector2(2, 0)));
                this.Shoot(Vector2.Normalize(new Vector2(0, -2)));

                this.fireTime = NormalFireCooldownTime;
            }

            base.Update(gameTime);
        }
    }
}


text:
module RequestHelpers
  extend ActiveSupport::Concern

  included do
    let(:default_env) do
      username = Settings.auth_username
      password = Settings.auth_password

      {
        'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(username, password)
      }
    end
    let(:env) { default_env }
  end

  def get(*args)
    args[2] ||= env
    super(*args)
  end

  def post(*args)
    args[2] ||= env
    super(*args)
  end

  def put(*args)
    args[2] ||= env
    super(*args)
  end

  def delete(*args)
    args[2] ||= env
    super(*args)
  end
end

RSpec.configure do |config|
  config.include RequestHelpers, type: :request
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

        <title>Questions and Exercises: Implementations (The Java™ Tutorials >
            Collections > Implementations)
</title>

     <meta name="description" content="This collections Java tutorial describes interfaces, implementations, and algorithms in the Java Collections framework" />
     <meta name="keywords" content="java programming, learn java, java sample code, java collections, set, list, queue, map, array, arraylist" />

A browser with JavaScript enabled is required for this page to operate properly.

                            Download
                                the JDK

                            Search the
                                Tutorials

                            Hide the TOC

        Trail: Collections

Lesson: Implementations

Implementations

Set Implementations

List Implementations

Map Implementations

Queue Implementations

Wrapper Implementations

Convenience Implementations

Summary of Implementations

Questions and Exercises

                Home Page
                >
                Collections
                >
                Implementations

                « Previous • Trail • Next »

Questions and Exercises: Implementations

Questions

You plan to write a program that uses several basic
collection interfaces: Set, List,
Queue, and Map. You're not sure which
implementations will work best, so you decide to use general-purpose
implementations until you get a better idea how your program will work
in the real world. Which implementations are these?

If you need a Set implementation that provides value-ordered iteration, which class should you use?

Which class do you use to access wrapper implementations?

Exercises

Write a program that reads a text file, specified by the first
    command line argument, into a List. The program
    should then print random lines from the file, the number of lines
    printed to be specified by the second command line argument.
    Write the program so that a correctly-sized collection is
    allocated all at once, instead of being gradually expanded as the
    file is read in. Hint: To determine the number of lines in the
    file, use
java.io.File.length
to obtain the size of the file, then divide by an assumed size of an
average line.

Check your answers.

            « Previous
            •
            Trail
            •
            Next »

Problems with the examples? Try Compiling and Running
        the Examples: FAQs.

    Complaints? Compliments? Suggestions? Give
    us your feedback.

Your use of this page and all the material on pages under "The Java Tutorials" banner,
and all the material on pages under "The Java Tutorials" banner is subject to the Java SE Tutorial Copyright
and License.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
Code
Sample License.

About Oracle | Oracle Technology Network | Terms of Service

Copyright © 1995, 2011 Oracle and/or its affiliates. All rights reserved.

        Previous page: Summary of Implementations

Next page: Algorithms

A browser with JavaScript enabled is required for this page to operate properly.