text:
/*	$FreeBSD: src/sys/netinet/icmp6.h,v 1.8 2002/05/06 16:28:25 ume Exp $	*/
/*	$KAME: icmp6.h,v 1.46 2001/04/27 15:09:48 itojun Exp $	*/

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * 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.
 * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
 */

/*
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
 *
 *	@(#)ip_icmp.h	8.1 (Berkeley) 6/10/93
 */

#ifndef _NETINET_ICMP6_H_
#define _NETINET_ICMP6_H_

#define ICMPV6_PLD_MAXLEN	1232	/* IPV6_MMTU - sizeof(struct ip6_hdr)
					   - sizeof(struct icmp6_hdr) */

struct icmp6_hdr {
	u_int8_t	icmp6_type;	/* type field */
	u_int8_t	icmp6_code;	/* code field */
	u_int16_t	icmp6_cksum;	/* checksum field */
	union {
		u_int32_t	icmp6_un_data32[1]; /* type-specific field */
		u_int16_t	icmp6_un_data16[2]; /* type-specific field */
		u_int8_t	icmp6_un_data8[4];  /* type-specific field */
	} icmp6_dataun;
} __attribute__((__packed__));

#define icmp6_data32	icmp6_dataun.icmp6_un_data32
#define icmp6_data16	icmp6_dataun.icmp6_un_data16
#define icmp6_data8	icmp6_dataun.icmp6_un_data8
#define icmp6_pptr	icmp6_data32[0]		/* parameter prob */
#define icmp6_mtu	icmp6_data32[0]		/* packet too big */
#define icmp6_id	icmp6_data16[0]		/* echo request/reply */
#define icmp6_seq	icmp6_data16[1]		/* echo request/reply */
#define icmp6_maxdelay	icmp6_data16[0]		/* mcast group membership */

#define ICMP6_DST_UNREACH		1	/* dest unreachable, codes: */
#define ICMP6_PACKET_TOO_BIG		2	/* packet too big */
#define ICMP6_TIME_EXCEEDED		3	/* time exceeded, code: */
#define ICMP6_PARAM_PROB		4	/* ip6 header bad */

#define ICMP6_ECHO_REQUEST		128	/* echo service */
#define ICMP6_ECHO_REPLY		129	/* echo reply */
#define ICMP6_MEMBERSHIP_QUERY		130	/* group membership query */
#define MLD_LISTENER_QUERY		130 	/* multicast listener query */
#define ICMP6_MEMBERSHIP_REPORT		131	/* group membership report */
#define MLD_LISTENER_REPORT		131	/* multicast listener report */
#define ICMP6_MEMBERSHIP_REDUCTION	132	/* group membership termination */
#define MLD_LISTENER_DONE		132	/* multicast listener done */

#ifndef _KERNEL
/* the followings are for backward compatibility to old KAME apps. */
#define MLD6_LISTENER_QUERY	MLD_LISTENER_QUERY
#define MLD6_LISTENER_REPORT	MLD_LISTENER_REPORT
#define MLD6_LISTENER_DONE	MLD_LISTENER_DONE
#endif

#define ND_ROUTER_SOLICIT		133	/* router solicitation */
#define ND_ROUTER_ADVERT		134	/* router advertisment */
#define ND_NEIGHBOR_SOLICIT		135	/* neighbor solicitation */
#define ND_NEIGHBOR_ADVERT		136	/* neighbor advertisment */
#define ND_REDIRECT			137	/* redirect */

#define ICMP6_ROUTER_RENUMBERING	138	/* router renumbering */

#define ICMP6_WRUREQUEST		139	/* who are you request */
#define ICMP6_WRUREPLY			140	/* who are you reply */
#define ICMP6_FQDN_QUERY		139	/* FQDN query */
#define ICMP6_FQDN_REPLY		140	/* FQDN reply */
#define ICMP6_NI_QUERY			139	/* node information request */
#define ICMP6_NI_REPLY			140	/* node information reply */

/* The definitions below are experimental. TBA */
#define MLD_MTRACE_RESP			200	/* mtrace resp (to sender) */
#define MLD_MTRACE			201	/* mtrace messages */

#define ICMP6_HADISCOV_REQUEST		202	/* XXX To be defined */
#define ICMP6_HADISCOV_REPLY		203	/* XXX To be defined */

#ifndef _KERNEL
#define MLD6_MTRACE_RESP	MLD_MTRACE_RESP
#define MLD6_MTRACE		MLD_MTRACE
#endif

#define ICMP6_MAXTYPE			203

#define ICMP6_DST_UNREACH_NOROUTE	0	/* no route to destination */
#define ICMP6_DST_UNREACH_ADMIN	 	1	/* administratively prohibited */
#define ICMP6_DST_UNREACH_NOTNEIGHBOR	2	/* not a neighbor(obsolete) */
#define ICMP6_DST_UNREACH_BEYONDSCOPE	2	/* beyond scope of source address */
#define ICMP6_DST_UNREACH_ADDR		3	/* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT	4	/* port unreachable */

#define ICMP6_TIME_EXCEED_TRANSIT 	0	/* ttl==0 in transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY	1	/* ttl==0 in reass */

#define ICMP6_PARAMPROB_HEADER 	 	0	/* erroneous header field */
#define ICMP6_PARAMPROB_NEXTHEADER	1	/* unrecognized next header */
#define ICMP6_PARAMPROB_OPTION		2	/* unrecognized option */

#define ICMP6_INFOMSG_MASK		0x80	/* all informational messages */

#define ICMP6_NI_SUBJ_IPV6	0	/* Query Subject is an IPv6 address */
#define ICMP6_NI_SUBJ_FQDN	1	/* Query Subject is a Domain name */
#define ICMP6_NI_SUBJ_IPV4	2	/* Query Subject is an IPv4 address */

#define ICMP6_NI_SUCCESS	0	/* node information successful reply */
#define ICMP6_NI_REFUSED	1	/* node information request is refused */
#define ICMP6_NI_UNKNOWN	2	/* unknown Qtype */

#define ICMP6_ROUTER_RENUMBERING_COMMAND  0	/* rr command */
#define ICMP6_ROUTER_RENUMBERING_RESULT   1	/* rr result */
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET   255	/* rr seq num reset */

/* Used in kernel only */
#define ND_REDIRECT_ONLINK	0	/* redirect to an on-link node */
#define ND_REDIRECT_ROUTER	1	/* redirect to a better router */

/*
 * Multicast Listener Discovery
 */
struct mld_hdr {
	struct icmp6_hdr	mld_icmp6_hdr;
	struct in6_addr		mld_addr; /* multicast address */
} __attribute__((__packed__));

/* definitions to provide backward compatibility to old KAME applications */
#ifndef _KERNEL
#define mld6_hdr	mld_hdr
#define mld6_type	mld_type
#define mld6_code	mld_code
#define mld6_cksum	mld_cksum
#define mld6_maxdelay	mld_maxdelay
#define mld6_reserved	mld_reserved
#define mld6_addr	mld_addr
#endif

/* shortcut macro definitions */
#define mld_type	mld_icmp6_hdr.icmp6_type
#define mld_code	mld_icmp6_hdr.icmp6_code
#define mld_cksum	mld_icmp6_hdr.icmp6_cksum
#define mld_maxdelay	mld_icmp6_hdr.icmp6_data16[0]
#define mld_reserved	mld_icmp6_hdr.icmp6_data16[1]

/*
 * Neighbor Discovery
 */

struct nd_router_solicit {	/* router solicitation */
	struct icmp6_hdr 	nd_rs_hdr;
	/* could be followed by options */
} __attribute__((__packed__));

#define nd_rs_type	nd_rs_hdr.icmp6_type
#define nd_rs_code	nd_rs_hdr.icmp6_code
#define nd_rs_cksum	nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved	nd_rs_hdr.icmp6_data32[0]

struct nd_router_advert {	/* router advertisement */
	struct icmp6_hdr	nd_ra_hdr;
	u_int32_t		nd_ra_reachable;	/* reachable time */
	u_int32_t		nd_ra_retransmit;	/* retransmit timer */
	/* could be followed by options */
} __attribute__((__packed__));

#define nd_ra_type		nd_ra_hdr.icmp6_type
#define nd_ra_code		nd_ra_hdr.icmp6_code
#define nd_ra_cksum		nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit	nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved	nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED	0x80
#define ND_RA_FLAG_OTHER	0x40
#define ND_RA_FLAG_HA		0x20

/*
 * Router preference values based on draft-draves-ipngwg-router-selection-01.
 * These are non-standard definitions.
 */
#define ND_RA_FLAG_RTPREF_MASK	0x18 /* 00011000 */

#define ND_RA_FLAG_RTPREF_HIGH	0x08 /* 00001000 */
#define ND_RA_FLAG_RTPREF_MEDIUM	0x00 /* 00000000 */
#define ND_RA_FLAG_RTPREF_LOW	0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_RSV	0x10 /* 00010000 */

#define nd_ra_router_lifetime	nd_ra_hdr.icmp6_data16[1]

struct nd_neighbor_solicit {	/* neighbor solicitation */
	struct icmp6_hdr	nd_ns_hdr;
	struct in6_addr		nd_ns_target;	/*target address */
	/* could be followed by options */
} __attribute__((__packed__));

#define nd_ns_type		nd_ns_hdr.icmp6_type
#define nd_ns_code		nd_ns_hdr.icmp6_code
#define nd_ns_cksum		nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved		nd_ns_hdr.icmp6_data32[0]

struct nd_neighbor_advert {	/* neighbor advertisement */
	struct icmp6_hdr	nd_na_hdr;
	struct in6_addr		nd_na_target;	/* target address */
	/* could be followed by options */
} __attribute__((__packed__));

#define nd_na_type		nd_na_hdr.icmp6_type
#define nd_na_code		nd_na_hdr.icmp6_code
#define nd_na_cksum		nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved	nd_na_hdr.icmp6_data32[0]
#if BYTE_ORDER == BIG_ENDIAN
#define ND_NA_FLAG_ROUTER		0x80000000
#define ND_NA_FLAG_SOLICITED		0x40000000
#define ND_NA_FLAG_OVERRIDE		0x20000000
#else
#if BYTE_ORDER == LITTLE_ENDIAN
#define ND_NA_FLAG_ROUTER		0x80
#define ND_NA_FLAG_SOLICITED		0x40
#define ND_NA_FLAG_OVERRIDE		0x20
#endif
#endif

struct nd_redirect {		/* redirect */
	struct icmp6_hdr	nd_rd_hdr;
	struct in6_addr		nd_rd_target;	/* target address */
	struct in6_addr		nd_rd_dst;	/* destination address */
	/* could be followed by options */
} __attribute__((__packed__));

#define nd_rd_type		nd_rd_hdr.icmp6_type
#define nd_rd_code		nd_rd_hdr.icmp6_code
#define nd_rd_cksum		nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved		nd_rd_hdr.icmp6_data32[0]

struct nd_opt_hdr {		/* Neighbor discovery option header */
	u_int8_t	nd_opt_type;
	u_int8_t	nd_opt_len;
	/* followed by option specific data*/
} __attribute__((__packed__));

#define ND_OPT_SOURCE_LINKADDR		1
#define ND_OPT_TARGET_LINKADDR		2
#define ND_OPT_PREFIX_INFORMATION	3
#define ND_OPT_REDIRECTED_HEADER	4
#define ND_OPT_MTU			5

#define ND_OPT_ROUTE_INFO		200	/* draft-ietf-ipngwg-router-preference, not officially assigned yet */

struct nd_opt_prefix_info {	/* prefix information */
	u_int8_t	nd_opt_pi_type;
	u_int8_t	nd_opt_pi_len;
	u_int8_t	nd_opt_pi_prefix_len;
	u_int8_t	nd_opt_pi_flags_reserved;
	u_int32_t	nd_opt_pi_valid_time;
	u_int32_t	nd_opt_pi_preferred_time;
	u_int32_t	nd_opt_pi_reserved2;
	struct in6_addr	nd_opt_pi_prefix;
} __attribute__((__packed__));

#define ND_OPT_PI_FLAG_ONLINK		0x80
#define ND_OPT_PI_FLAG_AUTO		0x40

struct nd_opt_rd_hdr {		/* redirected header */
	u_int8_t	nd_opt_rh_type;
	u_int8_t	nd_opt_rh_len;
	u_int16_t	nd_opt_rh_reserved1;
	u_int32_t	nd_opt_rh_reserved2;
	/* followed by IP header and data */
} __attribute__((__packed__));

struct nd_opt_mtu {		/* MTU option */
	u_int8_t	nd_opt_mtu_type;
	u_int8_t	nd_opt_mtu_len;
	u_int16_t	nd_opt_mtu_reserved;
	u_int32_t	nd_opt_mtu_mtu;
} __attribute__((__packed__));

struct nd_opt_route_info {	/* route info */
	u_int8_t	nd_opt_rti_type;
	u_int8_t	nd_opt_rti_len;
	u_int8_t	nd_opt_rti_prefixlen;
	u_int8_t	nd_opt_rti_flags;
	u_int32_t	nd_opt_rti_lifetime;
	/* prefix follows */
} __attribute__((__packed__));

/*
 * icmp6 namelookup
 */

struct icmp6_namelookup {
	struct icmp6_hdr 	icmp6_nl_hdr;
	u_int8_t	icmp6_nl_nonce[8];
	int32_t		icmp6_nl_ttl;
#if 0
	u_int8_t	icmp6_nl_len;
	u_int8_t	icmp6_nl_name[3];
#endif
	/* could be followed by options */
} __attribute__((__packed__));

/*
 * icmp6 node information
 */
struct icmp6_nodeinfo {
	struct icmp6_hdr icmp6_ni_hdr;
	u_int8_t icmp6_ni_nonce[8];
	/* could be followed by reply data */
} __attribute__((__packed__));

#define ni_type		icmp6_ni_hdr.icmp6_type
#define ni_code		icmp6_ni_hdr.icmp6_code
#define ni_cksum	icmp6_ni_hdr.icmp6_cksum
#define ni_qtype	icmp6_ni_hdr.icmp6_data16[0]
#define ni_flags	icmp6_ni_hdr.icmp6_data16[1]

#define NI_QTYPE_NOOP		0 /* NOOP  */
#define NI_QTYPE_SUPTYPES	1 /* Supported Qtypes */
#define NI_QTYPE_FQDN		2 /* FQDN (draft 04) */
#define NI_QTYPE_DNSNAME	2 /* DNS Name */
#define NI_QTYPE_NODEADDR	3 /* Node Addresses */
#define NI_QTYPE_IPV4ADDR	4 /* IPv4 Addresses */

#if BYTE_ORDER == BIG_ENDIAN
#define NI_SUPTYPE_FLAG_COMPRESS	0x1
#define NI_FQDN_FLAG_VALIDTTL		0x1
#elif BYTE_ORDER == LITTLE_ENDIAN
#define NI_SUPTYPE_FLAG_COMPRESS	0x0100
#define NI_FQDN_FLAG_VALIDTTL		0x0100
#endif

#ifdef NAME_LOOKUPS_04
#if BYTE_ORDER == BIG_ENDIAN
#define NI_NODEADDR_FLAG_LINKLOCAL	0x1
#define NI_NODEADDR_FLAG_SITELOCAL	0x2
#define NI_NODEADDR_FLAG_GLOBAL		0x4
#define NI_NODEADDR_FLAG_ALL		0x8
#define NI_NODEADDR_FLAG_TRUNCATE	0x10
#define NI_NODEADDR_FLAG_ANYCAST	0x20 /* just experimental. not in spec */
#elif BYTE_ORDER == LITTLE_ENDIAN
#define NI_NODEADDR_FLAG_LINKLOCAL	0x0100
#define NI_NODEADDR_FLAG_SITELOCAL	0x0200
#define NI_NODEADDR_FLAG_GLOBAL		0x0400
#define NI_NODEADDR_FLAG_ALL		0x0800
#define NI_NODEADDR_FLAG_TRUNCATE	0x1000
#define NI_NODEADDR_FLAG_ANYCAST	0x2000 /* just experimental. not in spec */
#endif
#else  /* draft-ietf-ipngwg-icmp-name-lookups-05 (and later?) */
#if BYTE_ORDER == BIG_ENDIAN
#define NI_NODEADDR_FLAG_TRUNCATE	0x1
#define NI_NODEADDR_FLAG_ALL		0x2
#define NI_NODEADDR_FLAG_COMPAT		0x4
#define NI_NODEADDR_FLAG_LINKLOCAL	0x8
#define NI_NODEADDR_FLAG_SITELOCAL	0x10
#define NI_NODEADDR_FLAG_GLOBAL		0x20
#define NI_NODEADDR_FLAG_ANYCAST	0x40 /* just experimental. not in spec */
#elif BYTE_ORDER == LITTLE_ENDIAN
#define NI_NODEADDR_FLAG_TRUNCATE	0x0100
#define NI_NODEADDR_FLAG_ALL		0x0200
#define NI_NODEADDR_FLAG_COMPAT		0x0400
#define NI_NODEADDR_FLAG_LINKLOCAL	0x0800
#define NI_NODEADDR_FLAG_SITELOCAL	0x1000
#define NI_NODEADDR_FLAG_GLOBAL		0x2000
#define NI_NODEADDR_FLAG_ANYCAST	0x4000 /* just experimental. not in spec */
#endif
#endif

struct ni_reply_fqdn {
	u_int32_t ni_fqdn_ttl;	/* TTL */
	u_int8_t ni_fqdn_namelen; /* length in octets of the FQDN */
	u_int8_t ni_fqdn_name[3]; /* XXX: alignment */
} __attribute__((__packed__));

/*
 * Router Renumbering. as router-renum-08.txt
 */
struct icmp6_router_renum {	/* router renumbering header */
	struct icmp6_hdr	rr_hdr;
	u_int8_t	rr_segnum;
	u_int8_t	rr_flags;
	u_int16_t	rr_maxdelay;
	u_int32_t	rr_reserved;
} __attribute__((__packed__));

#define ICMP6_RR_FLAGS_TEST		0x80
#define ICMP6_RR_FLAGS_REQRESULT	0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY	0x20
#define ICMP6_RR_FLAGS_SPECSITE		0x10
#define ICMP6_RR_FLAGS_PREVDONE		0x08

#define rr_type		rr_hdr.icmp6_type
#define rr_code		rr_hdr.icmp6_code
#define rr_cksum	rr_hdr.icmp6_cksum
#define rr_seqnum 	rr_hdr.icmp6_data32[0]

struct rr_pco_match {		/* match prefix part */
	u_int8_t	rpm_code;
	u_int8_t	rpm_len;
	u_int8_t	rpm_ordinal;
	u_int8_t	rpm_matchlen;
	u_int8_t	rpm_minlen;
	u_int8_t	rpm_maxlen;
	u_int16_t	rpm_reserved;
	struct	in6_addr	rpm_prefix;
} __attribute__((__packed__));

#define RPM_PCO_ADD		1
#define RPM_PCO_CHANGE		2
#define RPM_PCO_SETGLOBAL	3
#define RPM_PCO_MAX		4

struct rr_pco_use {		/* use prefix part */
	u_int8_t	rpu_uselen;
	u_int8_t	rpu_keeplen;
	u_int8_t	rpu_ramask;
	u_int8_t	rpu_raflags;
	u_int32_t	rpu_vltime;
	u_int32_t	rpu_pltime;
	u_int32_t	rpu_flags;
	struct	in6_addr rpu_prefix;
} __attribute__((__packed__));
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK	0x80
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO	0x40

#if BYTE_ORDER == BIG_ENDIAN
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME     0x80000000
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME     0x40000000
#elif BYTE_ORDER == LITTLE_ENDIAN
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME     0x80
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME     0x40
#endif

struct rr_result {		/* router renumbering result message */
	u_int16_t	rrr_flags;
	u_int8_t	rrr_ordinal;
	u_int8_t	rrr_matchedlen;
	u_int32_t	rrr_ifid;
	struct	in6_addr rrr_prefix;
} __attribute__((__packed__));
#if BYTE_ORDER == BIG_ENDIAN
#define ICMP6_RR_RESULT_FLAGS_OOB		0x0002
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN		0x0001
#elif BYTE_ORDER == LITTLE_ENDIAN
#define ICMP6_RR_RESULT_FLAGS_OOB		0x0200
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN		0x0100
#endif

/*
 * icmp6 filter structures.
 */

struct icmp6_filter {
	u_int32_t icmp6_filt[8];
};

#ifdef _KERNEL
#define	ICMP6_FILTER_SETPASSALL(filterp) \
do {								\
	int i; u_char *p;					\
	p = (u_char *)filterp;					\
	for (i = 0; i < sizeof(struct icmp6_filter); i++)	\
		p[i] = 0xff;					\
} while (0)
#define	ICMP6_FILTER_SETBLOCKALL(filterp) \
	bzero(filterp, sizeof(struct icmp6_filter))
#else /* _KERNEL */
#define	ICMP6_FILTER_SETPASSALL(filterp) \
	memset(filterp, 0xff, sizeof(struct icmp6_filter))
#define	ICMP6_FILTER_SETBLOCKALL(filterp) \
	memset(filterp, 0x00, sizeof(struct icmp6_filter))
#endif /* _KERNEL */

#define	ICMP6_FILTER_SETPASS(type, filterp) \
	(((filterp)->icmp6_filt[(type) >> 5]) |= (1 << ((type) & 31)))
#define	ICMP6_FILTER_SETBLOCK(type, filterp) \
	(((filterp)->icmp6_filt[(type) >> 5]) &= ~(1 << ((type) & 31)))
#define	ICMP6_FILTER_WILLPASS(type, filterp) \
	((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) != 0)
#define	ICMP6_FILTER_WILLBLOCK(type, filterp) \
	((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) == 0)

/*
 * Variables related to this implementation
 * of the internet control message protocol version 6.
 */
struct icmp6errstat {
	u_quad_t icp6errs_dst_unreach_noroute;
	u_quad_t icp6errs_dst_unreach_admin;
	u_quad_t icp6errs_dst_unreach_beyondscope;
	u_quad_t icp6errs_dst_unreach_addr;
	u_quad_t icp6errs_dst_unreach_noport;
	u_quad_t icp6errs_packet_too_big;
	u_quad_t icp6errs_time_exceed_transit;
	u_quad_t icp6errs_time_exceed_reassembly;
	u_quad_t icp6errs_paramprob_header;
	u_quad_t icp6errs_paramprob_nextheader;
	u_quad_t icp6errs_paramprob_option;
	u_quad_t icp6errs_redirect; /* we regard redirect as an error here */
	u_quad_t icp6errs_unknown;
};

struct icmp6stat {
/* statistics related to icmp6 packets generated */
	u_quad_t icp6s_error;		/* # of calls to icmp6_error */
	u_quad_t icp6s_canterror;	/* no error 'cuz old was icmp */
	u_quad_t icp6s_toofreq;		/* no error 'cuz rate limitation */
	u_quad_t icp6s_outhist[256];
/* statistics related to input message processed */
	u_quad_t icp6s_badcode;		/* icmp6_code out of range */
	u_quad_t icp6s_tooshort;	/* packet < sizeof(struct icmp6_hdr) */
	u_quad_t icp6s_checksum;	/* bad checksum */
	u_quad_t icp6s_badlen;		/* calculated bound mismatch */
	/*
	 * number of responses: this member is inherited from netinet code, but
	 * for netinet6 code, it is already available in icp6s_outhist[].
	 */
	u_quad_t icp6s_reflect;
	u_quad_t icp6s_inhist[256];
	u_quad_t icp6s_nd_toomanyopt;	/* too many ND options */
	struct icmp6errstat icp6s_outerrhist;
#define icp6s_odst_unreach_noroute \
	icp6s_outerrhist.icp6errs_dst_unreach_noroute
#define icp6s_odst_unreach_admin icp6s_outerrhist.icp6errs_dst_unreach_admin
#define icp6s_odst_unreach_beyondscope \
	icp6s_outerrhist.icp6errs_dst_unreach_beyondscope
#define icp6s_odst_unreach_addr icp6s_outerrhist.icp6errs_dst_unreach_addr
#define icp6s_odst_unreach_noport icp6s_outerrhist.icp6errs_dst_unreach_noport
#define icp6s_opacket_too_big icp6s_outerrhist.icp6errs_packet_too_big
#define icp6s_otime_exceed_transit \
	icp6s_outerrhist.icp6errs_time_exceed_transit
#define icp6s_otime_exceed_reassembly \
	icp6s_outerrhist.icp6errs_time_exceed_reassembly
#define icp6s_oparamprob_header icp6s_outerrhist.icp6errs_paramprob_header
#define icp6s_oparamprob_nextheader \
	icp6s_outerrhist.icp6errs_paramprob_nextheader
#define icp6s_oparamprob_option icp6s_outerrhist.icp6errs_paramprob_option
#define icp6s_oredirect icp6s_outerrhist.icp6errs_redirect
#define icp6s_ounknown icp6s_outerrhist.icp6errs_unknown
	u_quad_t icp6s_pmtuchg;		/* path MTU changes */
	u_quad_t icp6s_nd_badopt;	/* bad ND options */
	u_quad_t icp6s_badns;		/* bad neighbor solicitation */
	u_quad_t icp6s_badna;		/* bad neighbor advertisement */
	u_quad_t icp6s_badrs;		/* bad router advertisement */
	u_quad_t icp6s_badra;		/* bad router advertisement */
	u_quad_t icp6s_badredirect;	/* bad redirect message */
};

/*
 * Names for ICMP sysctl objects
 */
#define ICMPV6CTL_STATS		1
#define ICMPV6CTL_REDIRACCEPT	2	/* accept/process redirects */
#define ICMPV6CTL_REDIRTIMEOUT	3	/* redirect cache time */
#if 0	/*obsoleted*/
#define ICMPV6CTL_ERRRATELIMIT	5	/* ICMPv6 error rate limitation */
#endif
#define ICMPV6CTL_ND6_PRUNE	6
#define ICMPV6CTL_ND6_DELAY	8
#define ICMPV6CTL_ND6_UMAXTRIES	9
#define ICMPV6CTL_ND6_MMAXTRIES		10
#define ICMPV6CTL_ND6_USELOOPBACK	11
/*#define ICMPV6CTL_ND6_PROXYALL	12	obsoleted, do not reuse here */
#define ICMPV6CTL_NODEINFO	13
#define ICMPV6CTL_ERRPPSLIMIT	14	/* ICMPv6 error pps limitation */
#define ICMPV6CTL_ND6_MAXNUDHINT	15
#define ICMPV6CTL_MTUDISC_HIWAT	16
#define ICMPV6CTL_MTUDISC_LOWAT	17
#define ICMPV6CTL_ND6_DEBUG	18
#define ICMPV6CTL_ND6_DRLIST	19
#define ICMPV6CTL_ND6_PRLIST	20
#define ICMPV6CTL_MAXID		21

#define ICMPV6CTL_NAMES { \
	{ 0, 0 }, \
	{ 0, 0 }, \
	{ "rediraccept", CTLTYPE_INT }, \
	{ "redirtimeout", CTLTYPE_INT }, \
	{ 0, 0 }, \
	{ 0, 0 }, \
	{ "nd6_prune", CTLTYPE_INT }, \
	{ 0, 0 }, \
	{ "nd6_delay", CTLTYPE_INT }, \
	{ "nd6_umaxtries", CTLTYPE_INT }, \
	{ "nd6_mmaxtries", CTLTYPE_INT }, \
	{ "nd6_useloopback", CTLTYPE_INT }, \
	{ 0, 0 }, \
	{ "nodeinfo", CTLTYPE_INT }, \
	{ "errppslimit", CTLTYPE_INT }, \
	{ "nd6_maxnudhint", CTLTYPE_INT }, \
	{ "mtudisc_hiwat", CTLTYPE_INT }, \
	{ "mtudisc_lowat", CTLTYPE_INT }, \
	{ "nd6_debug", CTLTYPE_INT }, \
	{ 0, 0 }, \
	{ 0, 0 }, \
}

#define RTF_PROBEMTU	RTF_PROTO1

#ifdef _KERNEL
# ifdef __STDC__
struct	rtentry;
struct	rttimer;
struct	in6_multi;
# endif
void	icmp6_init(void);
void	icmp6_paramerror(struct mbuf *, int);
void	icmp6_error(struct mbuf *, int, int, int);
int	icmp6_input(struct mbuf **, int *, int);
void	icmp6_fasttimo(void);
void	icmp6_reflect(struct mbuf *, size_t);
void	icmp6_prepare(struct mbuf *);
void	icmp6_redirect_input(struct mbuf *, int);
void	icmp6_redirect_output(struct mbuf *, struct rtentry *);

struct	ip6ctlparam;
void	icmp6_mtudisc_update(struct ip6ctlparam *, int);

/* XXX: is this the right place for these macros? */
#define icmp6_ifstat_inc(ifp, tag) \
do {								\
	if ((ifp) && (ifp)->if_index <= if_index			\
	 && (ifp)->if_index < icmp6_ifstatmax			\
	 && icmp6_ifstat && icmp6_ifstat[(ifp)->if_index]) {	\
		icmp6_ifstat[(ifp)->if_index]->tag++;		\
	}							\
} while (0)

#define icmp6_ifoutstat_inc(ifp, type, code) \
do { \
		icmp6_ifstat_inc(ifp, ifs6_out_msg); \
 		if (type < ICMP6_INFOMSG_MASK) \
 			icmp6_ifstat_inc(ifp, ifs6_out_error); \
		switch(type) { \
		 case ICMP6_DST_UNREACH: \
			 icmp6_ifstat_inc(ifp, ifs6_out_dstunreach); \
			 if (code == ICMP6_DST_UNREACH_ADMIN) \
				 icmp6_ifstat_inc(ifp, ifs6_out_adminprohib); \
			 break; \
		 case ICMP6_PACKET_TOO_BIG: \
			 icmp6_ifstat_inc(ifp, ifs6_out_pkttoobig); \
			 break; \
		 case ICMP6_TIME_EXCEEDED: \
			 icmp6_ifstat_inc(ifp, ifs6_out_timeexceed); \
			 break; \
		 case ICMP6_PARAM_PROB: \
			 icmp6_ifstat_inc(ifp, ifs6_out_paramprob); \
			 break; \
		 case ICMP6_ECHO_REQUEST: \
			 icmp6_ifstat_inc(ifp, ifs6_out_echo); \
			 break; \
		 case ICMP6_ECHO_REPLY: \
			 icmp6_ifstat_inc(ifp, ifs6_out_echoreply); \
			 break; \
		 case MLD_LISTENER_QUERY: \
			 icmp6_ifstat_inc(ifp, ifs6_out_mldquery); \
			 break; \
		 case MLD_LISTENER_REPORT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_mldreport); \
			 break; \
		 case MLD_LISTENER_DONE: \
			 icmp6_ifstat_inc(ifp, ifs6_out_mlddone); \
			 break; \
		 case ND_ROUTER_SOLICIT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_routersolicit); \
			 break; \
		 case ND_ROUTER_ADVERT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_routeradvert); \
			 break; \
		 case ND_NEIGHBOR_SOLICIT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_neighborsolicit); \
			 break; \
		 case ND_NEIGHBOR_ADVERT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_neighboradvert); \
			 break; \
		 case ND_REDIRECT: \
			 icmp6_ifstat_inc(ifp, ifs6_out_redirect); \
			 break; \
		} \
} while (0)

extern int	icmp6_rediraccept;	/* accept/process redirects */
extern int	icmp6_redirtimeout;	/* cache time for redirect routes */
#endif /* _KERNEL */

#endif /* not _NETINET_ICMP6_H_ */


text:
package org.jboss.aesh.extensions.text.highlight.scanner;

import org.jboss.aesh.extensions.text.highlight.Encoder;
import org.jboss.aesh.extensions.text.highlight.Scanner;
import org.jboss.aesh.extensions.text.highlight.Syntax;
import org.jboss.aesh.extensions.text.highlight.encoder.AssertEncoder;
import org.junit.Assert;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class AbstractScannerTestCase {

    public static final String ASSERT_ENCODER = "TEST";

    {
        Syntax.builtIns();
        Encoder.Factory.registrer(ASSERT_ENCODER, AssertEncoder.class);
    }

    public static String OUTPUT = "target/examples";
    public static String BASE_URL = "https://raw.github.com/rubychan/coderay-scanner-tests/master/";
    public static Pattern MATCH_DATA = Pattern.compile("(.*)\\..*\\..*");

    protected String fetch(String type, String example) throws Exception {
        Path sourcePath = Paths.get(OUTPUT, type, example);
        if (!Files.exists(sourcePath)) {
            sourcePath.getParent().toFile().mkdirs();
            URL source = new URL(BASE_URL + type + "/" + example);
            System.out.println("Fetching " + source);
            Files.write(sourcePath, asByteArray(new BufferedInputStream(source.openStream())), StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE);
        }
        return new String(Files.readAllBytes(sourcePath));
    }

    private String expectedName(String example) {
        Matcher result = MATCH_DATA.matcher(example);
        result.find();

        return result.group(1) + ".expected.raydebug";
    }

    protected void assertMatchExample(Syntax.Builder builder, String type, String exampleName) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        String exampleContent = fetch(type, exampleName);
        String expectedContent = fetch(type, expectedName(exampleName));

        builder.output(out);
        builder.encoderType(ASSERT_ENCODER);
        builder.scanner(Scanner.Factory.byFileName(exampleName));
        builder.execute(exampleContent);
        out.flush();

        String result = new String(out.toByteArray());

        String[] resultLines = result.split("\n");
        String[] expectedLines = expectedContent.split("\n");

        for (int i = 0; i < resultLines.length; i++) {
            String s = resultLines[i];
            String t = expectedLines[i];

            if (!s.equals(t)) {
                System.out.println("--------------------------->" + (i + 1));
                System.out.println(exampleContent.split("\n")[i]);
                System.out.println("---------------------------");
                System.out.println("> " + s);
                System.out.println("< " + t);
                System.out.println("---------------------------");
                Assert.assertEquals("verify line: " + (i + 1), t, s);
            }
        }
        Assert.assertEquals(expectedContent, result);
    }

    static byte[] asByteArray(final InputStream in) throws IllegalArgumentException {
        // Precondition check
        if (in == null) {
            throw new IllegalArgumentException("stream must be specified");
        }

        // Get content as an array of bytes
        final ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
        final int len = 4096;
        final byte[] buffer = new byte[len];
        int read = 0;
        try {
            while (((read = in.read(buffer)) != -1)) {
                out.write(buffer, 0, read);
            }
        }
        catch (final IOException ioe) {
            throw new RuntimeException("Error in obtainting bytes from " + in, ioe);
        }
        finally {
            try {
                in.close();
            }
            catch (final IOException ignore) {
            }
            // We don't need to close the outstream, it's a byte array out
        }

        // Represent as byte array
        final byte[] content = out.toByteArray();

        // Return
        return content;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.xengar.android.conjugaisonfrancaise.ui;

import android.app.SearchManager;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;

import com.xengar.android.conjugaisonfrancaise.R;
import com.xengar.android.conjugaisonfrancaise.adapter.VerbHolder;
import com.xengar.android.conjugaisonfrancaise.data.Verb;
import com.xengar.android.conjugaisonfrancaise.data.VerbContract.VerbEntry;
import com.xengar.android.conjugaisonfrancaise.utils.ActivityUtils;

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

import static com.xengar.android.conjugaisonfrancaise.utils.Constants.LIST;
import static com.xengar.android.conjugaisonfrancaise.utils.Constants.LOG;

/**
 * SearchActivity
 */
public class SearchActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private List<Verb> mVerbs; // all verbs in the database
    private SearchView mSearchView;
    private SearchAdapter mAdapter;
    private TextToSpeech tts = null;

    //private FirebaseAnalytics mFirebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.search_recycler_view);
        mSearchView = (SearchView) findViewById(R.id.search_view);
        setupActionBar();
        setupSearchView();

        mVerbs = new ArrayList<>();
        mAdapter = new SearchAdapter();
        // Get all verbs
        FetchVerbs fetch = new FetchVerbs(getContentResolver(), mVerbs, mAdapter.getVerbs());
        fetch.execute();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);

        // initialize Speaker
        tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = tts.setLanguage(Locale.FRENCH);
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        if (LOG) {
                            Log.e("TTS", "This Language is not supported");
                        }
                    }
                } else {
                    if (LOG) {
                        Log.e("TTS", "Initilization Failed!");
                    }
                }
            }
        });

        // Obtain the FirebaseAnalytics instance.
        //mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        //ActivityUtils.firebaseAnalyticsLogEventSelectContent(mFirebaseAnalytics,
        //        PAGE_SEARCH, PAGE_SEARCH, TYPE_PAGE);
    }

    @Override
    public void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    private void setupActionBar() {
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupSearchView() {
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        mSearchView.setIconified(false);
        mSearchView.setQueryHint(getString(R.string.action_search));
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchView.clearFocus();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() >= 1) {
                    mAdapter.getFilter().filter(newText);
                    return true;
                }

                return false;
            }
        });
        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                finish();
                return true;
            }
        });
    }

    /**
     * SearchAdapter
     */
    class SearchAdapter extends RecyclerView.Adapter<VerbHolder> implements Filterable {

        private final List<Verb> mMultiSearchItems = new ArrayList<>();

        public SearchAdapter() {
        }

        public List<Verb> getVerbs(){ return mMultiSearchItems; }

        @Override
        public VerbHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View v = inflater.inflate(R.layout.verbs_list_item, parent, false);
            return new VerbHolder(v);
        }

        @Override
        public void onBindViewHolder(VerbHolder holder, int position) {
            Verb item = mMultiSearchItems.get(position);
            holder.bindVerb(item, LIST, tts);
        }

        @Override
        public int getItemCount() {
            return mMultiSearchItems.size();
        }

        @Override
        public Filter getFilter() {

            return new Filter() {
                @Override
                protected FilterResults performFiltering(final CharSequence charSequence) {
                    final FilterResults results = new FilterResults();

                    // Iterate though the list and get the verbs that contain the string
                    mMultiSearchItems.clear();
                    for(Verb verb : mVerbs){
                        if (verb.getInfinitive().contains(charSequence)){
                            mMultiSearchItems.add(verb);
                        }
                    }
                    results.values = mMultiSearchItems;
                    results.count = mMultiSearchItems.size();

                    //ActivityUtils.firebaseAnalyticsLogEventSearch(
                    //        mFirebaseAnalytics, charSequence.toString());
                    //ActivityUtils.firebaseAnalyticsLogEventViewSearchResults(
                    //        mFirebaseAnalytics, charSequence.toString());

                    return results;
                }

                @Override
                protected void publishResults(CharSequence charSequence,
                                              FilterResults filterResults) {
                    notifyDataSetChanged();
                }
            };
        }
    }

    /**
     * FetchVerbs from the database.
     */
    public class FetchVerbs extends AsyncTask<Void, Void, ArrayList<Verb>> {

        private final String TAG = FetchVerbs.class.getSimpleName();
        private final ContentResolver contentResolver;
        private final List<Verb> verbs; // list of all verbs
        private final List<Verb> search; // list of search result verbs

        // Constructor
        public FetchVerbs(final ContentResolver contentResolver, final List<Verb> verbs,
                          final List<Verb> search) {
            this.contentResolver = contentResolver;
            this.verbs = verbs;
            this.search = search;
        }

        @Override
        protected ArrayList<Verb> doInBackground(Void... voids) {
            // Define a projection that specifies the columns from the table we care about.
            String[] columns = ActivityUtils.allVerbColumns();
            String sortOrder = VerbEntry.COLUMN_INFINITIVE + " ASC";
            Cursor cursor = contentResolver.query(
                    VerbEntry.CONTENT_VERBS_URI, columns, null, null, sortOrder);

            ArrayList<Verb> verbs = new ArrayList<>();
            if (cursor != null && cursor.getCount() != 0) {
                while (cursor.moveToNext()) {
                    verbs.add(ActivityUtils.verbFromCursor(cursor));
                }
            } else {
                if (LOG) {
                    Log.d(TAG, "Cursor is empty");
                }
            }
            if (cursor != null)
                cursor.close();
            return verbs;
        }

        @Override
        protected void onPostExecute(ArrayList<Verb> list) {
            super.onPostExecute(list);
            if (list != null) {
                verbs.addAll(list);
                search.addAll(list); // begin search with all verbs in screen.
            }
        }
    }

}


text:
- intro to AngularJS
- AngularJS controller and scope

## How to use
- `bower install`
- open index.html on your browser

## This Material is made for EEPIS Front-End development workshop


text:
/* global describe: false, it: false */

var assert = require('assert')

var helpers = require('./env/helpers.js')

var request = helpers.request

var getURL = helpers.getURL

var Controller = require('../lib/controller/index.js')

describe('controller', function () {
  it('should support normal function', function (done) {
    request.get(getURL('/controller/normal-func'), function (error, response, body) {
      assert.equal(body, 'done')
      assert.equal(response.statusCode, 200)
      done()
    })
  })

  it('should support generator', function (done) {
    request.get(getURL('/controller/generator'), function (error, response, body) {
      assert.equal(body, 'done')
      assert.equal(response.statusCode, 200)
      done()
    })
  })

  it('should support yielding nested generators', function (done) {
    request.get(getURL('/nested-generators'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'Nested Generators')
      done()
    })
  })

  it('should support yielding nested promises', function (done) {
    request.get(getURL('/nested-promises'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'Nested Promises')
      done()
    })
  })

  it('should support yielding nested generators and promises', function (done) {
    request.get(getURL('/nested-generators-and-promises'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'works')
      done()
    })
  })

  it('should support yielding primitive data types', function (done) {
    request.get(getURL('/primitive'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'Hello World')
      done()
    })
  })

  it('should emit onSTATUS', function (done) {
    request.get(getURL('/controller/on'), function (error, response, body) {
      assert.equal(body, 'Nothing here')
      assert.equal(response.statusCode, 404)
      done()
    })
  })
})

describe('controller.isController()', function () {
  it('should return true for Controller type', function () {
    var ctrl = new Controller()

    assert.equal(Controller.isController(ctrl), true)
    assert.equal(Controller.isController(true), false)
  })
})

describe('controller.addAction()', function () {
  it('should add action', function (done) {
    request.get(getURL('/ctrl/addAction'), function (err, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'works')
      done()
    })
  })

  it('should throw exception when using "addAction" as action name', function () {
    var ctrl = new Controller()

    try {
      ctrl.addAction('addAction', function () {})
    } catch (ex) {
      assert.equal(ex.message, '"addAction" is a preserved keyword!')
    }
  })

  it('should throw exception when setting non-function or non-generator function', function () {
    var ctrl = new Controller()

    try {
      ctrl.addAction('demo', true)
    } catch (ex) {
      assert.equal(ex.message, 'Action must be a function or generator.')
    }
  })
})

describe('controller.on()', function () {
  it('should run status handler for specified status', function (done) {
    Promise.all([
      new Promise(function (res) {
        request.get(getURL('/ctrl/not-found'), function (err, response, body) {
          assert.equal(response.statusCode, 404)
          assert.equal(body, 'works')
          res()
        })
      }),

      new Promise(function (res) {
        request.post(getURL('/ctrl/not-found'), function (err, response, body) {
          assert.equal(response.statusCode, 405)
          assert.equal(body, 'works')
          res()
        })
      })
    ]).then(function () {
      done()
    })
  })

  it('should pass excetion to router when status handler thrown exception', function (done) {
    request.get(getURL('/ctrl/401'), function (err, response, body) {
      assert.equal(response.statusCode, 500)
      assert.equal(body.indexOf('401 error') > -1, true)
      done()
    })
  })
})

describe('controller.beforeAction', function () {
  it('should support function and generator', function (done) {
    request.get(getURL('/ba/ok'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'Hello')
      done()
    })
  })

  it('should skip controller and go to 404 if returns any values except undefined and null', function (done) {
    request.get(getURL('/ba/not-ok'), function (error, response) {
      assert.equal(response.statusCode, 404)
      done()
    })
  })

  it('should go to controller if returns undefined or null', function (done) {
    request.get(getURL('/ba/ok'), function (error, response, body) {
      assert.equal(response.statusCode, 200)
      assert.equal(body, 'Hello')
      done()
    })
  })
})


text:
package org.medipi.concentrator.dao;

import org.medipi.medication.model.DoseUnit;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Data Access Object for Hardware
 *
 * @author rick@robinsonhq.com
 */
@Repository
public class DoseUnitImpl extends GenericDAOImpl<DoseUnit> implements DoseUnitDAO {
    @Override
    public DoseUnit findByDoseUnitId(int doseUnitId) {
        return this.getEntityManager().createNamedQuery("DoseUnit.findByDoseUnitId", DoseUnit.class)
                .setParameter("id", doseUnitId)
                .getSingleResult();
    }

    @Override
    public List<DoseUnit> findAll() {
        return this.getEntityManager().createNamedQuery("DoseUnit.findAll", DoseUnit.class)
                .getResultList();
    }
}


text:
import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { SelectableItem, SocialMediaItem, Tweet } from '../../common-types';
import { Attributes } from '../../perspectiveapi-types';
import { getInfluenceScore } from '../common/social_media_item_utils';

@Component({
  selector: 'app-comment-info',
  templateUrl: './comment-info.component.html',
  styleUrls: ['./comment-info.component.scss'],
})
export class CommentInfoComponent implements OnChanges {
  @Input() comment?: SelectableItem<SocialMediaItem>;
  tweet?: SelectableItem<Tweet>;
  @Output() selectChange = new EventEmitter<boolean>();
  @Output() deleteClicked = new EventEmitter<void>();

  // Controls whether text/image blurring should be enabled at all.
  private blurringEnabled = false;

  @Input() set enableBlurring(enableBlurring: boolean) {
    this.blurringEnabled = enableBlurring;
    this.shouldBlur = enableBlurring;
  }
  @Input() showCheckbox = true;
  @Input() showFullText = false;
  @Input() showFullMedia = false;
  @Input() showDetails = false;
  @Input() showDeleteButton = false;
  @Input() disabled = false;

  // Controls the blurred state when users hover over/out of the comment
  // text/image.
  shouldBlur = false;

  harmfulStatus = 'Unable to score';
  influence = 'Popularity';
  time = 'Time';

  timeframe = '';

  // The selected state of the component. This variable can be set as an input
  // from the parent component and also from the ngModel on the checkbox.
  selectedInternal = false;
  @Input() set selected(selected: boolean) {
    this.selectedInternal = selected;
    if (this.comment) {
      this.comment.selected = selected;
    }
  }

  get selected() {
    return this.selectedInternal;
  }

  // Whether the expansion panel is open.
  panelOpen = false;

  ngOnChanges(changes: SimpleChanges) {
    if (changes['comment']) {
      if (this.comment && this.comment.item) {
        this.tweet = this.comment;
      }

      this.computeHighLevelInfo();
    }
  }

  notifyCheckedStateChange() {
    if (this.comment) {
      // Update the data model to reflect the checkbox state.
      this.comment.selected = this.selectedInternal;
    }
    this.selectChange.emit(this.selectedInternal);
  }

  handleCheckboxClicked(event: MouseEvent) {
    if (!this.disabled) {
      this.selectedInternal = !this.selectedInternal;
    }
    this.notifyCheckedStateChange();
    event.stopPropagation();
  }

  handleDeleteClicked() {
    this.deleteClicked.emit();
  }

  computeHighLevelInfo() {
    if (!this.comment || !this.comment.item) {
      this.harmfulStatus = 'Unable to score';
      this.influence = 'Popularity';
      this.time = 'Time';
      return;
    }

    const toxicityScore = this.comment.scores[Attributes.TOXICITY];
    if (!toxicityScore) {
      this.harmfulStatus = 'Unable to score';
    } else if (toxicityScore >= 0.85) {
      this.harmfulStatus = 'Likely harmful';
    } else if (toxicityScore >= 0.6 && toxicityScore < 0.85) {
      this.harmfulStatus = 'Potentially harmful';
    } else if (toxicityScore >= 0.4 && toxicityScore < 0.6) {
      this.harmfulStatus = 'Unsure if harmful';
    } else {
      this.harmfulStatus = 'Unlikely harmful';
    }

    if (getInfluenceScore(this.comment.item) > 100) {
      this.influence = 'Popular';
    } else {
      this.influence = 'Unpopular';
    }

    const timeMs = Date.now() - this.comment.item.date.getTime();
    const timeSecs = Math.round(timeMs / 1000);
    const timeMins = Math.round(timeMs / (1000 * 60));
    const timeHrs = Math.round(timeMs / (1000 * 60 * 60));
    const timeDays = Math.round(timeMs / (1000 * 60 * 60 * 24));
    if (timeDays === 1) {
      this.time = '1 day';
    } else if (timeDays > 1) {
      this.time = `${timeDays} days`;
    } else if (timeHrs === 1) {
      this.time = '1 hour';
    } else if (timeHrs > 1) {
      this.time = `${timeHrs} hours`;
    } else if (timeMins === 1) {
      this.time = '1 minute';
    } else if (timeMins > 1) {
      this.time = `${timeMins} minutes`;
    } else if (timeSecs === 1) {
      this.time = '1 second';
    } else {
      this.time = `${timeSecs} seconds`;
    }

    if (timeDays >= 1) {
      this.timeframe = 'days';
    } else if (timeHrs >= 1) {
      this.timeframe = 'hours';
    } else if (timeMins >= 1) {
      this.timeframe = 'minutes';
    }
  }

  getFormattedDate(timeMs: number): string {
    return new Date(timeMs).toLocaleString('en-US', { timeZone: 'UTC' });
  }

  formatScore(score: number): number {
    return Math.round(score * 100);
  }

  toggleBlur() {
    this.shouldBlur = !this.shouldBlur;
  }

  // For the given comment returns the image filename and image alt text.
  getPriorityIconAndAltText(): string[] {
    if (this.harmfulStatus === 'Likely harmful') {
      return ['high_priority_icon.svg', 'high priority'];
    } else if (this.harmfulStatus === 'Potentially harmful') {
      return ['possible_priority_icon.svg', 'possible priority'];
    } else if (this.harmfulStatus === 'Unlikely harmful') {
      return ['low_priority_icon.svg', 'low priority'];
    } else {
      return ['unknown_priority_icon.svg', 'unknown priority'];
    }
  }

  getAriaLabelForCheckbox() {
    if (!this.comment || !this.comment.item) {
      return '';
    } else {
      return `Comment by ${
        this.tweet
          ? this.comment.item.authorScreenName
          : this.comment.item.authorName
      }
       ', ' ${this.getFormattedDate(this.comment.item.date.getTime())}`;
    }
  }
}


text:
#ifndef SFDHOLDER_H
#define SFDHOLDER_H

#include "config.h"
#include "LangTypes.h"
#include <map>
#include <vector>

class BitBuffer;
class MC2SimpleString;
class SFDFileHeader;
class ServerTileMapFormatDesc;

/**
 * Class that holds a number of pre made tile cache files.
 *
 */
class SFDHolder {
public:
   /**
    * Creates a holder for the SFD files in path.
    */
   SFDHolder( const MC2SimpleString& path );

   ~SFDHolder();

   /**
    * Get a tile from cached files.
    *
    * @param desc The tile to get.
    * @param tmfd The format description.
    */
   BitBuffer* requestCached( const MC2SimpleString& desc,
                             const ServerTileMapFormatDesc& tmfd );

private:
   typedef vector< SFDFileHeader* > SFDFileHeaderCont;
   typedef map< LangTypes::language_t, SFDFileHeaderCont > SFDCont;
   /**
    * The actual maps, not all bytes just some header stuff.
    */
   SFDCont m_maps;
};

#endif // SFDHOLDER_H


text:
import 'materialize-css';
import React from 'react';
import TestRenderer from 'react-test-renderer';

import { Carousel } from '../carousel';

describe('Carousel', () => {
  it('should renders correctly', () => {
    const renderer = TestRenderer.create(
      <Carousel />,
    );
    expect(renderer).toMatchSnapshot();
    renderer.unmount();
  });
});


text:
from msrest.serialization import Model

class TroubleshootingParameters(Model):
    """Parameters that define the resource to troubleshoot.

    All required parameters must be populated in order to send to Azure.

    :param target_resource_id: Required. The target resource to troubleshoot.
    :type target_resource_id: str
    :param storage_id: Required. The ID for the storage account to save the
     troubleshoot result.
    :type storage_id: str
    :param storage_path: Required. The path to the blob to save the
     troubleshoot result in.
    :type storage_path: str
    """

    _validation = {
        'target_resource_id': {'required': True},
        'storage_id': {'required': True},
        'storage_path': {'required': True},
    }

    _attribute_map = {
        'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
        'storage_id': {'key': 'properties.storageId', 'type': 'str'},
        'storage_path': {'key': 'properties.storagePath', 'type': 'str'},
    }

    def __init__(self, *, target_resource_id: str, storage_id: str, storage_path: str, **kwargs) -> None:
        super(TroubleshootingParameters, self).__init__(**kwargs)
        self.target_resource_id = target_resource_id
        self.storage_id = storage_id
        self.storage_path = storage_path


text:
SpecBegin(A0LockConfiguration)

describe(@"A0LockConfiguration", ^{

    __block A0Application *application;

    describe(@"initialisation", ^{

        before(^{
            application = mock(A0Application.class);
        });

        it(@"should build with application and list of connection names", ^{
            expect([[A0LockConfiguration alloc] initWithApplication:application filter:@[@"facebook"]]).toNot.beNil();
        });

        it(@"should fail when application is nil", ^{
            expect(^{
                expect([[A0LockConfiguration alloc] initWithApplication:nil filter:@[@"facebook"]]).to.beNil();
            }).to.raiseWithReason(NSInternalInconsistencyException, @"Must supply a non-nil application");
        });

        it(@"should accept nil filter list", ^{
            expect([[A0LockConfiguration alloc] initWithApplication:application filter:nil]).toNot.beNil();
        });

    });

    describe(@"filter connections", ^{

        before(^{
            NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:self.class] pathForResource:@"AppInfo" ofType:@"json"]];
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
            application = [[A0Application alloc] initWithJSONDictionary:json];
        });

        sharedExamplesFor(kFilteredEnterpriseAndSocialExample, ^(NSDictionary *data) {

            __block A0LockConfiguration *config;

            before(^{
                config = data[kLockConfig];
            });

            it(@"should have social connections", ^{
                __block NSMutableArray *names = [@[] mutableCopy];
                [config.socialStrategies enumerateObjectsUsingBlock:^(A0Strategy *stragegy, NSUInteger idx, BOOL *stop) {
                    [names addObject:stragegy.name];
                }];
                NSArray *expected = [data[kSocialConnectionNames] mutableCopy];
                expect(names).to.beSupersetOf(expected);
                expect(names).to.haveCountOf(expected.count);
            });

            it(@"should have enterprise connections", ^{
                __block NSMutableArray *names = [@[] mutableCopy];
                [config.enterpriseStrategies enumerateObjectsUsingBlock:^(A0Strategy *stragegy, NSUInteger idx, BOOL *stop) {
                    [stragegy.connections enumerateObjectsUsingBlock:^(A0Connection *connection, NSUInteger idx, BOOL *stop) {
                        [names addObject:connection.name];
                    }];
                }];
                NSArray *expected = [data[kEnterpriseConnectionNames] mutableCopy];
                expect(names).to.beSupersetOf(expected);
                expect(names).to.haveCountOf(expected.count);
            });
        });

        itBehavesLike(kFilteredEnterpriseAndSocialExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[]],
                     kSocialConnectionNames: @[@"google-oauth2", @"facebook", @"twitter", @"instagram"],
                     kEnterpriseConnectionNames: @[@"auth0.com", @"MyAD", @"mySeconAD"],
                     };
        });

        itBehavesLike(kFilteredEnterpriseAndSocialExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[@"facebook", @"twitter", @"instagram"]],
                     kSocialConnectionNames: @[@"facebook", @"twitter", @"instagram"],
                     kEnterpriseConnectionNames: @[],
                     };
        });

        itBehavesLike(kFilteredEnterpriseAndSocialExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[@"auth0.com", @"mySeconAD"]],
                     kSocialConnectionNames: @[],
                     kEnterpriseConnectionNames: @[@"auth0.com", @"mySeconAD"],
                     };
        });

        sharedExamplesFor(kActiveDirectoryExample, ^(NSDictionary *data) {

            __block A0LockConfiguration *config;

            before(^{
                config = data[kLockConfig];
            });

            itBehavesLike(kFilteredEnterpriseAndSocialExample, data);

            it(@"should return an active directory strategy", ^{
                expect(config.activeDirectoryStrategy).toNot.beNil();
                expect(config.activeDirectoryStrategy.name).to.equal(A0StrategyNameActiveDirectory);
            });

            it(@"should return the correct default AD connection", ^{
                expect(config.defaultActiveDirectoryConnection.name).to.equal(data[kDefaultADConnectionName]);
            });
        });

        itBehavesLike(kActiveDirectoryExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[]],
                     kSocialConnectionNames: @[@"google-oauth2", @"facebook", @"twitter", @"instagram"],
                     kEnterpriseConnectionNames: @[@"auth0.com", @"MyAD", @"mySeconAD"],
                     kDefaultADConnectionName: @"MyAD",
                     };
        });

        itBehavesLike(kActiveDirectoryExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[@"auth0.com", @"MyAD", @"mySeconAD"]],
                     kSocialConnectionNames: @[],
                     kEnterpriseConnectionNames: @[@"auth0.com", @"MyAD", @"mySeconAD"],
                     kDefaultADConnectionName: @"MyAD",
                     };
        });

        itBehavesLike(kActiveDirectoryExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[@"auth0.com", @"mySeconAD"]],
                     kSocialConnectionNames: @[],
                     kEnterpriseConnectionNames: @[@"auth0.com", @"mySeconAD"],
                     kDefaultADConnectionName: @"mySeconAD",
                     };
        });

        it(@"should return nil default DB when no DB connection is present", ^{
            A0LockConfiguration *config = [[A0LockConfiguration alloc] initWithApplication:application filter:@[@"auth0.com", @"mySeconAD"]];
            expect(config.defaultDatabaseConnection).to.beNil();
        });

        sharedExamplesFor(kDatabaseConnectionExample, ^(NSDictionary *data) {

            __block A0LockConfiguration *config;

            before(^{
                config = data[kLockConfig];
            });

            it(@"should return a default DB connection", ^{
                expect(config.defaultDatabaseConnection.name).to.equal(data[kDefaultDatabaseConnectionName]);
            });
        });

        itShouldBehaveLike(kDatabaseConnectionExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[]],
                     kDefaultDatabaseConnectionName: kAuth0DatabaseConnectionName,
                     };
        });

        itShouldBehaveLike(kDatabaseConnectionExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[kAuth0DatabaseConnectionName, @"MyAD", @"mySeconAD"]],
                     kDefaultDatabaseConnectionName: kAuth0DatabaseConnectionName,
                     };
        });

        itShouldBehaveLike(kDatabaseConnectionExample, ^id{
            return @{
                     kLockConfig: [[A0LockConfiguration alloc] initWithApplication:application filter:@[kCustomDatabaseConnectionName, @"MyAD", @"mySeconAD"]],
                     kDefaultDatabaseConnectionName: kCustomDatabaseConnectionName,
                     };
        });

        itShouldBehaveLike(kDatabaseConnectionExample, ^id{
            A0LockConfiguration *configuration = [[A0LockConfiguration alloc] initWithApplication:application filter:@[]];
            configuration.defaultDatabaseConnectionName = kCustomDatabaseConnectionName;
            return @{
                     kLockConfig: configuration,
                     kDefaultDatabaseConnectionName: kCustomDatabaseConnectionName,
                     };
        });

        itShouldBehaveLike(kDatabaseConnectionExample, ^id{
            A0LockConfiguration *configuration = [[A0LockConfiguration alloc] initWithApplication:application
                                                                                filter:@[
                                                                                kAuth0DatabaseConnectionName,
                                                                                kCustomDatabaseConnectionName
                                                                                ]];
            configuration.defaultDatabaseConnectionName = kCustomDatabaseConnectionName;
            return @{
                     kLockConfig: configuration,
                     kDefaultDatabaseConnectionName: kCustomDatabaseConnectionName,
                     };
        });

    });

    describe(@"disable Sign Up & Reset Password", ^{

        __block A0LockConfiguration *configuration;

        before(^{
            NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:self.class] pathForResource:@"AppInfo" ofType:@"json"]];
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
            application = [[A0Application alloc] initWithJSONDictionary:json];
            configuration = [[A0LockConfiguration alloc] initWithApplication:application filter:@[]];
        });

        context(@"when enabled in connection", ^{

            beforeEach(^{
                configuration.defaultDatabaseConnectionName = @"Username-PasswordAuthentication";
            });

            it(@"should disable Sign Up", ^{
                expect([configuration shouldDisableSignUp:YES]).to.beTruthy();
            });

            it(@"should not disable Sign Up", ^{
                expect([configuration shouldDisableSignUp:NO]).to.beFalsy();
            });

            it(@"should disable Reset Password", ^{
                expect([configuration shouldDisableResetPassword:YES]).to.beTruthy();
            });

            it(@"should not disable Reset Password", ^{
                expect([configuration shouldDisableResetPassword:NO]).to.beFalsy();
            });

        });

        context(@"when disabled in connection", ^{

            beforeEach(^{
                configuration.defaultDatabaseConnectionName = @"LoginOnly";
            });

            it(@"should disable Sign Up", ^{
                expect([configuration shouldDisableSignUp:YES]).to.beTruthy();
            });

            it(@"should not disable Sign Up", ^{
                expect([configuration shouldDisableSignUp:NO]).to.beTruthy();
            });

            it(@"should disable Reset Password", ^{
                expect([configuration shouldDisableResetPassword:YES]).to.beTruthy();
            });

            it(@"should not disable Reset Password", ^{
                expect([configuration shouldDisableResetPassword:NO]).to.beTruthy();
            });

        });

    });
});

SpecEnd


text:
package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Chant_RustCurse extends Chant
{
	public String ID() { return "Chant_RustCurse"; }
	public String name(){return "Rust Curse";}
	public String displayText(){return "(Rust Curse)";}
    public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_DEEPMAGIC;}
	public int abstractQuality(){ return Ability.QUALITY_MALICIOUS;}
	protected int canAffectCode(){return CAN_MOBS;}
	protected int canTargetCode(){return CAN_MOBS;}

	public void unInvoke()
	{
		MOB M=null;
		if(affected instanceof MOB)
			M=(MOB)affected;
		super.unInvoke();
		if((canBeUninvoked())&&(M!=null)&&(!M.amDead()))
			M.tell("You don't feel so damp any more.");
	}

	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID))
			return false;
		if(affected instanceof MOB)
		{
			boolean goodChoices=false;
			Vector choices=new Vector();
			MOB mob=(MOB)affected;
			for(int i=0;i<mob.inventorySize();i++)
			{
				Item I=mob.fetchInventory(i);
				if((I!=null)&&(I.subjectToWearAndTear())
				   &&(((I.material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_METAL)
					  ||((I.material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_MITHRIL)))
				{
					if(!I.amWearingAt(Item.IN_INVENTORY))
					{
						goodChoices=true;
						choices.addElement(I);
					}
					else
					if(!goodChoices)
						choices.addElement(I);
				}
			}
			if(goodChoices)
			for(int i=choices.size()-1;i>=0;i--)
				if(((Item)choices.elementAt(i)).amWearingAt(Item.IN_INVENTORY))
					choices.removeElementAt(i);
			if(choices.size()>0)
			{
				Item I=(Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1));
				if(((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_MITHRIL)
				||(CMLib.dice().rollPercentage()<10))
				{
					CMMsg msg=CMClass.getMsg(mob,I,this,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_WATER,"<T-NAME> rusts!","You rust!",null);
					if(mob.location().okMessage(mob,msg))
					{
						mob.location().send(mob,msg);
						I.setUsesRemaining(I.usesRemaining()-1);
						if(I.usesRemaining()<=0)
						{
							mob.tell(I.name()+" is destroyed!");
							I.destroy();
						}
						else
						if(I.usesRemaining()<=10)
						{
							mob.tell(I.name()+" is looking really bad.");
						}
					}
				}
			}
		}

		return true;
	}

	public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
	{
		MOB target=getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.

			CMMsg msg = CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":"^S<S-NAME> chant(s) at <T-NAME> rustily!^?");
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				if(msg.value()<=0)
				{
					maliciousAffect(mob,target,asLevel,0,-1);
					target.tell("You feel damp!");
				}
			}
		}
		else
			return maliciousFizzle(mob,target,"<S-NAME> chant(s) at <T-NAME>, but the magic fizzles.");

		// return whether it worked
		return success;
	}
}


text:
class Matcher(object):
    def __eq__(self, other):
        raise NotImplementedError

    def __ne__(self, other):
        raise NotImplementedError

    def __hash__(self):
        raise NotImplementedError

    def matches(self, value):
        raise NotImplementedError

class ExactValueMatcher(Matcher):
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        if not isinstance(other, ExactValueMatcher):
            return False

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)

    def matches(self, value):
        return self.value == value

class AnyValueMatcher(Matcher):
    def __eq__(self, other):
        return isinstance(other, AnyValueMatcher)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(AnyValueMatcher)

    def matches(self, value):
        return True

class AnyArgumentsMatcher(Matcher):
    def __eq__(self, other):
        return isinstance(other, AnyArgumentsMatcher)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(AnyArgumentsMatcher)

    def matches(self, value):
        return True

class AnyKeywordArgumentsMatcher(Matcher):
    def __eq__(self, other):
        return isinstance(other, AnyKeywordArgumentsMatcher)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(AnyKeywordArgumentsMatcher)

    def matches(self, value):
        return True

class AnyValuesMatcher(Matcher):
    def __eq__(self, other):
        return isinstance(other, AnyValuesMatcher)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(AnyValuesMatcher)

    def matches(self, value):
        return True

def make_exact_value_matcher(arg_or_matcher):
    if isinstance(arg_or_matcher, Matcher):
        return arg_or_matcher
    else:
        return ExactValueMatcher(arg_or_matcher)

class MatchCriteria(object):
    def __init__(self, args, kwargs):
        self.arg_matchers = [make_exact_value_matcher(arg) for arg in args]
        self.kwarg_matchers = dict(((key, make_exact_value_matcher(value)) for key, value in kwargs.items()))

        self.any_args = False
        self.any_kwargs = False
        self.any_values = False
        while AnyArgumentsMatcher() in self.arg_matchers:
            self.any_args = True
            self.arg_matchers.remove(AnyArgumentsMatcher())
        while AnyKeywordArgumentsMatcher() in self.arg_matchers:
            self.any_kwargs = True
            self.arg_matchers.remove(AnyKeywordArgumentsMatcher())
        while AnyValuesMatcher() in self.arg_matchers:
            self.any_values = True
            self.arg_matchers.remove(AnyValuesMatcher())

    def __eq__(self, other):
        if not isinstance(other, MatchCriteria):
            return False

        return self.arg_matchers == other.arg_matchers and self.kwarg_matchers == other.kwarg_matchers

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(tuple(self.arg_matchers)) + hash(tuple(sorted(self.kwarg_matchers.items())))

    def matches(self, args, kwargs):
        arg_matchers = self.arg_matchers[:]
        if self.any_args or self.any_values:
            arg_matchers.extend([AnyArgumentsMatcher()] * (len(args) - len(arg_matchers)))

        kwarg_matchers = self.kwarg_matchers
        if self.any_kwargs or self.any_values:
            kwarg_matchers = dict(((key, make_exact_value_matcher(value)) for key, value in kwargs.items()))
            kwarg_matchers.update(self.kwarg_matchers)

        if len(arg_matchers) != len(args) or set(kwarg_matchers.keys()) != set(kwargs.keys()):
            return False

        for i in range(len(arg_matchers)):
            if not arg_matchers[i].matches(args[i]):
                return False

        for key, value in kwargs.items():
            if not kwarg_matchers[key].matches(value):
                return False

        return True


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

using ManagedSteam.Exceptions;

namespace ManagedSteam
{
    static class Error
    {
        [Conditional("STEAMAPIWRAP_LITE")]
        public static void NotAvailableInLite()
        {
            throw new NotAvailableInLiteException();
        }

        public static void ThrowError(ErrorCodes code, params object[] args)
        {
            switch (code)
            {
                // <Native>
                case ErrorCodes.AlreadyLoaded:
                    throw new AlreadyLoadedException(code, args);
                case ErrorCodes.SteamInitializeFailed:
                    throw new SteamInitializeFailedException(code, args);
                case ErrorCodes.SteamInterfaceInitializeFailed:
                    throw new SteamInterfaceInitializeFailedException(code, args);
                // </Native>

                // <Managed>
                case ErrorCodes.InvalidInterfaceVersion:
                    throw new InvalidInterfaceVersionException(code, args);
                case ErrorCodes.UsageAfterAPIShutdown:
                    throw new UsageAfterAPIShutdownException(code, args);
                case ErrorCodes.CallbackStructSizeMissmatch:
                    throw new CallbackStructSizeMismatchException(code, args);
                // </Managed>
            }

            if (code >= ErrorCodes.StartOfNativeErrors && code <= ErrorCodes.EndOfNativeErrors)
            {
                throw new NativeException(code);
            }
            if (code >= ErrorCodes.StartOfManagedErrors && code <= ErrorCodes.EndOfManagedErrors)
            {
                throw new ManagedException(code);
            }
            throw new UnexpectedException(code);
        }
    }
}


text:
A tiny product management application in Elixir using the awesome Phoenix framework. Written with a focus on performance and idiomatic design.

## Getting started

To start your Phoenix app:

  1. Install dependencies with `mix deps.get`
  2. Create and migrate your database with `mix ecto.create && mix ecto.migrate`
  3. Start Phoenix endpoint with `mix phoenix.server`

Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.

## Development

 1. Make sure you have Node JS installed locally.
 2. Install Node/static file dependencies using `npm install` and `bower install`
 3. Make your changes
 4. Start Phoenix as described above.

Gulp is included for running/compiling the custom Bootstrap files.

Ready to run in production? Please [check the official Phoenix Framework deployment guides](http://www.phoenixframework.org/docs/deployment).


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

<TITLE>
CounterGenerator
</TITLE>

<META NAME="date" CONTENT="2013-11-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.usc.bg.base.generator

Class CounterGenerator

java.lang.Object
  edu.usc.bg.base.generator.Generator
      edu.usc.bg.base.generator.IntegerGenerator
          edu.usc.bg.base.generator.CounterGenerator

public class CounterGenerator
extends IntegerGenerator

Generates a sequence of integers 0, 1, ...

Constructor Summary

CounterGenerator(int countstart)

          Create a counter that starts at countstart

Method Summary

 int
lastInt()

          Return the previous int generated by the distribution.

 double
mean()

          Return the expected value (mean) of the values this generator will return.

 int
nextInt()

          If the generator returns numeric (integer) values, return the next value as an int.

Methods inherited from class edu.usc.bg.base.generator.IntegerGenerator

lastString, nextString

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CounterGenerator

public CounterGenerator(int countstart)

Create a counter that starts at countstart

Method Detail

nextInt

public int nextInt()

If the generator returns numeric (integer) values, return the next value as an int. Default is to return -1, which
 is appropriate for generators that do not return numeric values.

Specified by:
nextInt in class IntegerGenerator

lastInt

public int lastInt()

Description copied from class: IntegerGenerator

Return the previous int generated by the distribution. This call is unique to IntegerGenerator subclasses, and assumes
 IntegerGenerator subclasses always return ints for nextInt() (e.g. not arbitrary strings).

Overrides:
lastInt in class IntegerGenerator

mean

public double mean()

Description copied from class: IntegerGenerator

Return the expected value (mean) of the values this generator will return.

Specified by:
mean in class IntegerGenerator

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package fate.qq4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.qq.connect.QQConnect;
import com.qq.connect.QQConnectException;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.utils.QQConnectConfig;
import com.qq.connect.utils.RandomStatusGenerator;
import com.qq.connect.utils.http.PostParameter;

/**
 * 对原qq登录的API做了点修改,不再从文件读取授权信息,而是从数据库中读取
 * @author Fate
 *
 */
public class Oauth extends QQConnect
{
  private static final long serialVersionUID = -7860508274941797293L;

  private String[] extractionAuthCodeFromUrl(String url)
    throws QQConnectException
  {
    if (url == null) {
      throw new QQConnectException("you pass a null String object");
    }
    Matcher m = Pattern.compile("code=(\\w+)&state=(\\w+)&?").matcher(url);
    String authCode = "";
    String state = "";
    if (m.find()) {
      authCode = m.group(1);
      state = m.group(2);
    }

    return new String[] { authCode, state };
  }

  public AccessToken getAccessTokenByRequest(ServletRequest request, String client_id, String client_secret, String redirect_uri)
    throws QQConnectException
  {
    String queryString = ((HttpServletRequest)request).getQueryString();
    if (queryString == null) {
      return new AccessToken();
    }
    String state = (String)((HttpServletRequest)request).getSession().getAttribute("qq_connect_state");
    if ((state == null) || (state.equals(""))) {
      return new AccessToken();
    }

    String[] authCodeAndState = extractionAuthCodeFromUrl(queryString);
    String returnState = authCodeAndState[1];
    String returnAuthCode = authCodeAndState[0];

    AccessToken accessTokenObj = null;

    if ((returnState.equals("")) || (returnAuthCode.equals("")))
    {
      accessTokenObj = new AccessToken();
    }
    else if (!state.equals(returnState))
    {
      accessTokenObj = new AccessToken();
    }
    else accessTokenObj = new AccessToken(this.client.post(QQConnectConfig.getValue("accessTokenURL"), new PostParameter[] { new PostParameter("client_id", client_id), new PostParameter("client_secret", client_secret), new PostParameter("grant_type", "authorization_code"), new PostParameter("code", returnAuthCode), new PostParameter("redirect_uri", redirect_uri) }, Boolean.valueOf(false)));

    return accessTokenObj;
  }

  /** @deprecated */
  public AccessToken getAccessTokenByQueryString(String queryString, String state, String client_id, String client_secret, String redirect_uri)
    throws QQConnectException
  {
    if (queryString == null) {
      return new AccessToken();
    }

    String[] authCodeAndState = extractionAuthCodeFromUrl(queryString);
    String returnState = authCodeAndState[1];
    String returnAuthCode = authCodeAndState[0];

    AccessToken accessTokenObj = null;

    if ((returnState.equals("")) || (returnAuthCode.equals("")))
    {
      accessTokenObj = new AccessToken();
    }
    else if (!state.equals(returnState))
    {
      accessTokenObj = new AccessToken();
    }
    else accessTokenObj = new AccessToken(this.client.post(QQConnectConfig.getValue("accessTokenURL"), new PostParameter[] { new PostParameter("client_id", client_id), new PostParameter("client_secret", client_secret), new PostParameter("grant_type", "authorization_code"), new PostParameter("code", returnAuthCode), new PostParameter("redirect_uri", redirect_uri) }, Boolean.valueOf(false)));

    return accessTokenObj;
  }

  /** @deprecated */
  public String getAuthorizeURL(String scope, String state, String client_id, String redirect_uri)
    throws QQConnectException
  {
    return QQConnectConfig.getValue("authorizeURL").trim() + "?client_id=" + client_id.trim() + "&redirect_uri=" + redirect_uri.trim() + "&response_type=" + "code" + "&state=" + state + "&scope=" + scope;
  }

  /** @deprecated */
  public String getAuthorizeURL(String state, String client_id, String redirect_uri)
    throws QQConnectException
  {
    String scope = QQConnectConfig.getValue("scope");
    if ((scope != null) && (!scope.equals(""))) {
      return getAuthorizeURL("code", state, scope, client_id, redirect_uri);
    }
    return QQConnectConfig.getValue("authorizeURL").trim() + "?client_id=" + client_id.trim() + "&redirect_uri=" + redirect_uri.trim() + "&response_type=" + "code" + "&state=" + state;
  }

  /** @deprecated */
  public String getAuthorizeURLByScope(String scope, ServletRequest request, String client_id, String redirect_uri)
    throws QQConnectException
  {
    String state = RandomStatusGenerator.getUniqueState();
    ((HttpServletRequest)request).setAttribute("qq_connect_state", state);

    return QQConnectConfig.getValue("authorizeURL").trim() + "?client_id=" + client_id.trim() + "&redirect_uri=" + redirect_uri.trim() + "&response_type=" + "code" + "&state=" + state + "&scope=" + scope;
  }

  public String getAuthorizeURL(ServletRequest request,String client_id, String redirect_uri)
    throws QQConnectException
  {
    String state = RandomStatusGenerator.getUniqueState();
    ((HttpServletRequest)request).getSession().setAttribute("qq_connect_state", state);
    String scope = QQConnectConfig.getValue("scope");
    if ((scope != null) && (!scope.equals(""))) {
      return getAuthorizeURL("code", state, scope, client_id, redirect_uri);
    }
    return QQConnectConfig.getValue("authorizeURL").trim() + "?client_id=" + client_id.trim() + "&redirect_uri=" + redirect_uri.trim() + "&response_type=" + "code" + "&state=" + state;
  }

  /** @deprecated */
  public String getAuthorizeURL(String response_type, String state, String scope, String client_id, String redirect_uri)
    throws QQConnectException
  {
    return QQConnectConfig.getValue("authorizeURL").trim() + "?client_id=" + client_id.trim() + "&redirect_uri=" + redirect_uri.trim() + "&response_type=" + response_type + "&state=" + state + "&scope=" + scope;
  }
}


text:
<!DOCTYPE HTML>

		<link href="/style.css" rel="stylesheet" type="text/css">
		<title>Shout</title>

Tell others to connect to here and shout at each other via ShareJS.

      <input type="text" id="input" placeholder="Shout something…"/>
      <input type="button" id="shout" value="shout"/>


text:
@implementation IIFireWeaponByGestureBehavior

- (void) handleTapGesture: (UITapGestureRecognizer *) sender {
    //CGPoint clickedPoint = [sender locationInView: sender.view];
    [weapon fire];
}

- (id) initWithManager: (IIGestureManager *) theManager
               gesture: (NSString *) gestureTag
             andWeapon: (IIWeapon *) theWeapon {

    if ((self = [super init])) {

        [theManager addTarget: self action: @selector(handleTapGesture:) toRecognizer: gestureTag];
        weapon = theWeapon;
        [weapon retain];
    }

    return self;
}

- (BOOL) doUpdate: (id<IIBehavioralNodeProtocol>) theTarget timeSinceLastFrame: (ccTime) timeElapsedSinceLastFrame {

    [weapon update: timeElapsedSinceLastFrame];

    return YES;
}

- (void) dealloc {
    [weapon release];

    [super dealloc];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1385131952489_0" label="Window Working Set" name="Aggregate for window 1385131952489"/>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1385132669105_1" label="Window Working Set" name="Aggregate for window 1385132669105"/>
</workingSetManager>


text:
- Allow `selectedValue`'s type to be a boolean.

### 2.1.0 (July 26th 2015)
- Library now no longer wraps your children function return with a `div`. It now checks that you return a single component (or `null`) from the function. #18

### 2.0.2 (June 14th 2015)
- Make the library work with browser globals.

### 2.0.1 (June 14th 2015)
- Compile to UMD so you can import this hackily from a browser script.

## 2.0.0 (June 14th 2015)
- API overhaul. See README for the new, cleaner API!
- Drop Bower support.
- Add npm support.

## 1.0.0
- Initial release.


text:
using LNF.Impl.Repository.Data;

namespace LNF.Impl.Mappings.Data
{
    internal abstract class ClientAccountInfoBaseMap<T> : ClientOrgInfoBaseMap<T> where T : ClientAccountInfoBase
    {
        internal ClientAccountInfoBaseMap()
        {
            MapClientAccountID();
            Map(x => x.IsDefault);
            Map(x => x.Manager);
            Map(x => x.ClientAccountActive);
            Map(x => x.AccountID);
            Map(x => x.AccountName);
            Map(x => x.AccountNumber);
            Map(x => x.ShortCode);
            Map(x => x.BillAddressID);
            Map(x => x.ShipAddressID);
            Map(x => x.InvoiceNumber);
            Map(x => x.InvoiceLine1);
            Map(x => x.InvoiceLine2);
            Map(x => x.PoEndDate);
            Map(x => x.PoInitialFunds);
            Map(x => x.PoRemainingFunds);
            Map(x => x.AccountActive);
            Map(x => x.FundingSourceID);
            Map(x => x.FundingSourceName);
            Map(x => x.TechnicalFieldID);
            Map(x => x.TechnicalFieldName);
            Map(x => x.SpecialTopicID);
            Map(x => x.SpecialTopicName);
            Map(x => x.AccountTypeID);
            Map(x => x.AccountTypeName);
        }

        protected override void MapClientID()
        {
            Map(x => x.ClientID);
        }

        protected override void MapClientOrgID()
        {
            Map(x => x.ClientOrgID);
        }

        protected abstract void MapClientAccountID();
    }
}


text:
from nova.compute import api as compute_api
from nova.compute import manager as compute_manager
from nova import context
from nova import db
from nova import objects
from nova.tests.api.openstack import fakes
from nova.tests import fake_block_device
from nova.tests import fake_instance
from nova.tests.integrated.v3 import test_servers
from nova.volume import cinder

class ExtendedVolumesSampleJsonTests(test_servers.ServersSampleBase):
    extension_name = "os-extended-volumes"

    def _stub_compute_api_get_instance_bdms(self, server_id):

        def fake_bdms_get_all_by_instance(context, instance_uuid,
                                          use_slave=False):
            bdms = [
                fake_block_device.FakeDbBlockDeviceDict(
                {'id': 1, 'volume_id': 'a26887c6-c47b-4654-abb5-dfadf7d3f803',
                'instance_uuid': server_id, 'source_type': 'volume',
                'destination_type': 'volume', 'device_name': '/dev/sdd'}),
                fake_block_device.FakeDbBlockDeviceDict(
                {'id': 2, 'volume_id': 'a26887c6-c47b-4654-abb5-dfadf7d3f804',
                'instance_uuid': server_id, 'source_type': 'volume',
                'destination_type': 'volume', 'device_name': '/dev/sdc'})
            ]
            return bdms

        self.stubs.Set(db, 'block_device_mapping_get_all_by_instance',
                       fake_bdms_get_all_by_instance)

    def _stub_compute_api_get(self):
        def fake_compute_api_get(self, context, instance_id, **kwargs):
            want_objects = kwargs.get('want_objects')
            if want_objects:
                return fake_instance.fake_instance_obj(
                        context, **{'uuid': instance_id})
            else:
                return {'uuid': instance_id}

        self.stubs.Set(compute_api.API, 'get', fake_compute_api_get)

    def test_show(self):
        uuid = self._post_server()
        self.stubs.Set(db, 'block_device_mapping_get_all_by_instance',
                       fakes.stub_bdm_get_all_by_instance)
        response = self._do_get('servers/%s' % uuid)
        subs = self._get_regexes()
        subs['hostid'] = '[a-f0-9]+'
        self._verify_response('server-get-resp', subs, response, 200)

    def test_detail(self):
        uuid = self._post_server()
        self.stubs.Set(db, 'block_device_mapping_get_all_by_instance',
                       fakes.stub_bdm_get_all_by_instance)
        response = self._do_get('servers/detail')
        subs = self._get_regexes()
        subs['id'] = uuid
        subs['hostid'] = '[a-f0-9]+'
        self._verify_response('servers-detail-resp', subs, response, 200)

    def test_attach_volume(self):
        bdm = objects.BlockDeviceMapping()
        device_name = '/dev/vdd'
        bdm['device_name'] = device_name
        self.stubs.Set(cinder.API, 'get', fakes.stub_volume_get)
        self.stubs.Set(cinder.API, 'check_attach', lambda *a, **k: None)
        self.stubs.Set(cinder.API, 'reserve_volume', lambda *a, **k: None)
        self.stubs.Set(compute_manager.ComputeManager,
                       "reserve_block_device_name",
                       lambda *a, **k: bdm)
        self.stubs.Set(compute_manager.ComputeManager,
                       'attach_volume',
                       lambda *a, **k: None)

        volume = fakes.stub_volume_get(None, context.get_admin_context(),
                                       'a26887c6-c47b-4654-abb5-dfadf7d3f803')
        subs = {
            'volume_id': volume['id'],
            'device': device_name,
            'disk_bus': 'ide',
            'device_type': 'cdrom'
        }
        server_id = self._post_server()
        response = self._do_post('servers/%s/action'
                                 % server_id,
                                 'attach-volume-req', subs)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(response.content, '')

    def test_detach_volume(self):
        server_id = self._post_server()
        attach_id = "a26887c6-c47b-4654-abb5-dfadf7d3f803"
        self._stub_compute_api_get_instance_bdms(server_id)
        self._stub_compute_api_get()
        self.stubs.Set(cinder.API, 'get', fakes.stub_volume_get)
        self.stubs.Set(compute_api.API, 'detach_volume', lambda *a, **k: None)
        subs = {
            'volume_id': attach_id,
        }
        response = self._do_post('servers/%s/action'
                                 % server_id, 'detach-volume-req', subs)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(response.content, '')

    def test_swap_volume(self):
        server_id = self._post_server()
        old_volume_id = "a26887c6-c47b-4654-abb5-dfadf7d3f803"
        old_new_volume = 'a26887c6-c47b-4654-abb5-dfadf7d3f805'
        self._stub_compute_api_get_instance_bdms(server_id)

        def stub_volume_get(self, context, volume_id):
            if volume_id == old_volume_id:
                return fakes.stub_volume(volume_id, instance_uuid=server_id)
            else:
                return fakes.stub_volume(volume_id, instance_uuid=None,
                                         attach_status='detached')

        self.stubs.Set(cinder.API, 'get', stub_volume_get)
        self.stubs.Set(cinder.API, 'begin_detaching', lambda *a, **k: None)
        self.stubs.Set(cinder.API, 'check_attach', lambda *a, **k: None)
        self.stubs.Set(cinder.API, 'check_detach', lambda *a, **k: None)
        self.stubs.Set(cinder.API, 'reserve_volume', lambda *a, **k: None)
        self.stubs.Set(compute_manager.ComputeManager, 'swap_volume',
                       lambda *a, **k: None)
        subs = {
            'old_volume_id': old_volume_id,
            'new_volume_id': old_new_volume
        }
        response = self._do_post('servers/%s/action' % server_id,
                                 'swap-volume-req', subs)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(response.content, '')


text:
Simple photo gallery using viewPager. The effect is similar to the Google Play gallery. For that, I overwrite the getPageWidth method of the FragmentStatePagerAdapter. The gallery accommodates both vertical and horizontal images automatically. To achieve this, you must include the width and height of the images in the json object

You can wath a sample video [here](http://youtu.be/KqUdL4FJ5YQ)

##Usage

If you download your images from URL, your json should be something as:

```json
[
	{
      width: 400,
      height: 200,
      imageUrl: "http://lorempixel.com/400/200/sports/0"
    },
	{
      width: 400,
      height: 200,
      imageUrl: "http://lorempixel.com/400/200/sports/1"
	},
	{
      width: 400,
      height: 200,
      imageUrl: "http://lorempixel.com/400/200/sports/2"
	},
	{
      width: 200,
      height: 400,
      imageUrl: "http://lorempixel.com/200/400/sports/3"
	},
	{
      width: 400,
      height: 200,
      imageUrl: "http://lorempixel.com/400/200/sports/4"
	}
]
```
You can use my API fake in order to test your code.
http://fakapi.eu01.aws.af.cm/v2/portals/personal_juegos_android/sample_images/

In order to adapt the images, you need to indicate to the gallery, the height and width of images. It is for this reason that we have to add the height and width.

You only need copy in your project the fragment, adapter and model folder and set in your dimens.xml a value for the gallery height. Something like this

```xml
<dimen name="screenshots_height">160dp</dimen>
```
After that, include in your layout the viewPager
```xml
    <FrameLayout
        android:id="@+id/galleryFrame"
        android:layout_width="match_parent"
        android:layout_height="@dimen/screenshots_height" />

```
and finally replace the fragment in your activity or fragment

```java
Fragment fragment = getSupportFragmentManager().findFragmentByTag("fragment_gallery");

		if (fragment == null && imageList != null) {

			fragment = GalleryFragment.newInstance(imageList);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.galleryFrame, fragment, "fragment_gallery")
					.commit();
		}
```

Feel free to contact me if you have any problem.


text:
class Prime
  # List of primes, each entry is odd and the first is for 3
  @prime_list = [true, true, true]   # 3, 5, and 7

  class << self
    attr_accessor :prime_list
  end

  # 0th (invalid) and 1st are taken care of here
  def self.nth( ord )
    raise ArgumentError if ord < 1
    return 2 if ord == 1

    new( ord ).nth
  end

  def initialize( ord )
    @ord = ord
  end

  # Attempt to find the nth prime, extending the list as necessary
  def nth
    loop do
      value = search( @ord )
      return value unless value.nil?
      build_out_prime_list
    end
  end

  private

  # Access the class list of primes
  def prime_list
    self.class.prime_list
  end

  # Search through the list for the ord'th prime. It may not be there, in which case
  # the list will be extended
  def search( ord )
    prime_list.each_with_index do |prime, idx|
      next unless prime

      return idx_to_value( idx ) if (ord -= 1) == 1
    end

    nil
  end

  # Extend the prime list by doubling its size each time.
  def build_out_prime_list
    new_size = prime_list.size + prime_list.size
    loop_end = Math.sqrt( idx_to_value( new_size ) ).ceil

    (prime_list.size..new_size).each { |idx| prime_list[idx] = true }

    prime_list.each_with_index do |prime, idx|
      next unless prime

      divisor = idx_to_value( idx )
      break if divisor > loop_end

      (idx+1..new_size).each { |i| prime_list[i] = false if idx_to_value( i ) % divisor == 0 }
    end
  end

  def idx_to_value( idx )
    idx * 2 + 3
  end
end


text:
package rx.functions;

/**
 * Represents a function with one argument.
 * @param <T> the first argument type
 * @param <R> the result type
 */
public interface Func1<T, R> extends Function {
    R call(T t);
}