text:
/*	$NetBSD: lfs.h,v 1.14 1999/03/25 21:39:18 perseant Exp $	*/

/*-
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Konrad E. Schroder <perseant@hhhh.org>.
 *
 * 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 NetBSD
 *      Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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) 1991, 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.
 *
 *	@(#)lfs.h	8.9 (Berkeley) 5/8/95
 */

/*
 * Compile-time options for LFS.
 */
#define LFS_EAGAIN_FAIL          /* markv fail with EAGAIN if ino is locked */
#define LFS_TRACK_IOS            /* attempt to avoid cleaning segments not yet fully written to disk */
#define LFS_CANNOT_ROLLFW       /* No roll-forward agent exists */

/* #define DEBUG_LFS */              /* Intensive debugging of LFS subsystem */

/* #define LFS_ATIME_IFILE */         /* Store atime in Ifile, don't push */
/* #define LFS_HONOR_RDONLY */        /* Don't write blocks if mounted ro */

/*
 * Parameters and generic definitions
 */
#define BW_CLEAN 1
#define MIN_FREE_SEGS 4
#define LFS_MAX_ACTIVE          10

#ifndef LFS_ATIME_IFILE
# define LFS_ITIMES(ip, acc, mod, cre) FFS_ITIMES((ip),(acc),(mod),(cre))
#else
# define LFS_ITIMES(ip, acc, mod, cre) {                                \
	struct buf *ibp;						\
	IFILE *ifp;							\
									\
        if ((ip)->i_flag & IN_ACCESS) {                         	\
	LFS_IENTRY(ifp, ip->i_lfs, ip->i_number, ibp);			\
       		ifp->if_atime = (mod);					\
       		VOP_BWRITE(bp);						\
		(ip)->i_flag &= ~IN_ACCESS;				\
        }                                                       	\
        if ((ip)->i_flag & (IN_CHANGE | IN_UPDATE)) {       		\
                (ip)->i_flag |= IN_MODIFIED;                            \
                if ((ip)->i_flag & IN_UPDATE) {                         \
                        (ip)->i_ffs_mtime = (mod)->tv_sec;		\
                        (ip)->i_ffs_mtimensec = (mod)->tv_nsec;         \
                        (ip)->i_modrev++;                               \
                }                                                       \
                if ((ip)->i_flag & IN_CHANGE) {                         \
                        (ip)->i_ffs_ctime = (cre)->tv_sec;		\
                        (ip)->i_ffs_ctimensec = (cre)->tv_nsec;         \
                }                                                       \
                (ip)->i_flag &= ~(IN_CHANGE | IN_UPDATE);   		\
        }                                                               \
}
#endif

#define WRITEINPROG(vp) (vp->v_dirtyblkhd.lh_first && !(VTOI(vp)->i_flag & (IN_MODIFIED|IN_CLEANING)))

/* Here begins the berkeley code */

#define	LFS_LABELPAD	8192		/* LFS label size */
#define	LFS_SBPAD	8192		/* LFS superblock size */

/*
 * XXX
 * This is a kluge and NEEDS to go away.
 *
 * Right now, ufs code handles most of the calls for directory operations
 * such as create, mkdir, link, etc.  As a result VOP_UPDATE is being
 * called with waitfor set (since ffs does these things synchronously).
 * Since LFS does not want to do these synchronously, we treat the last
 * argument to lfs_update as a set of flags.  If LFS_SYNC is set, then
 * the update should be synchronous, if not, do it asynchronously.
 * Unfortunately, this means that LFS won't work with NFS yet because
 * NFS goes through paths that will make normal calls to ufs which will
 * call lfs with a last argument of 1.
 */
#define	LFS_SYNC	0x02

/* On-disk and in-memory checkpoint segment usage structure. */
typedef struct segusage SEGUSE;
struct segusage {
	u_int32_t su_nbytes;		/* number of live bytes */
	u_int32_t su_lastmod;		/* SEGUSE last modified timestamp */
	u_int16_t su_nsums;		/* number of summaries in segment */
	u_int16_t su_ninos;		/* number of inode blocks in seg */

#define	SEGUSE_ACTIVE		0x01	/* segment is currently being written */
#define	SEGUSE_DIRTY		0x02	/* segment has data in it */
#define	SEGUSE_SUPERBLOCK	0x04	/* segment contains a superblock */
	u_int32_t su_flags;
};

#define	SEGUPB(fs)	(1 << (fs)->lfs_sushift)
#define	SEGTABSIZE_SU(fs)						\
	(((fs)->lfs_nseg + SEGUPB(fs) - 1) >> (fs)->lfs_sushift)

/* On-disk file information.  One per file with data blocks in the segment. */
typedef struct finfo FINFO;
struct finfo {
	u_int32_t fi_nblocks;		/* number of blocks */
	u_int32_t fi_version;		/* version number */
	u_int32_t fi_ino;		/* inode number */
	u_int32_t fi_lastlength;	/* length of last block in array */
	ufs_daddr_t	  fi_blocks[1];		/* array of logical block numbers */
};

/* On-disk super block. */
struct dlfs {
#define	LFS_MAGIC	0x070162
        u_int32_t dlfs_magic;     /* 0: magic number */
#define	LFS_VERSION	1
        u_int32_t dlfs_version;   /* 4: version number */

        u_int32_t dlfs_size;      /* 8: number of blocks in fs */
        u_int32_t dlfs_ssize;     /* 12: number of blocks per segment */
        u_int32_t dlfs_dsize;     /* 16: number of disk blocks in fs */
        u_int32_t dlfs_bsize;     /* 20: file system block size */
        u_int32_t dlfs_fsize;     /* 24: size of frag blocks in fs */
        u_int32_t dlfs_frag;      /* 28: number of frags in a block in fs */

/* Checkpoint region. */
        ino_t     dlfs_free;      /* 32: start of the free list */
        u_int32_t dlfs_bfree;     /* 36: number of free disk blocks */
        u_int32_t dlfs_nfiles;    /* 40: number of allocated inodes */
        int32_t   dlfs_avail;     /* 44: blocks available for writing */
        u_int32_t dlfs_uinodes;   /* 48: inodes in cache not yet on disk */
        ufs_daddr_t  dlfs_idaddr; /* 52: inode file disk address */
        ino_t     dlfs_ifile;     /* 56: inode file inode number */
        ufs_daddr_t  dlfs_lastseg; /* 60: address of last segment written */
        ufs_daddr_t  dlfs_nextseg; /* 64: address of next segment to write */
        ufs_daddr_t  dlfs_curseg; /* 68: current segment being written */
        ufs_daddr_t  dlfs_offset; /* 72: offset in curseg for next partial */
        ufs_daddr_t  dlfs_lastpseg; /* 76: address of last partial written */
        u_int32_t dlfs_tstamp;    /* 80: time stamp */

/* These are configuration parameters. */
        u_int32_t dlfs_minfree;   /* 84: minimum percentage of free blocks */

/* These fields can be computed from the others. */
        u_int64_t dlfs_maxfilesize; /* 88: maximum representable file size */
        u_int32_t dlfs_dbpseg;    /* 96: disk blocks per segment */
        u_int32_t dlfs_inopb;     /* 100: inodes per block */
        u_int32_t dlfs_ifpb;      /* 104: IFILE entries per block */
        u_int32_t dlfs_sepb;      /* 108: SEGUSE entries per block */
        u_int32_t dlfs_nindir;    /* 112: indirect pointers per block */
        u_int32_t dlfs_nseg;      /* 116: number of segments */
        u_int32_t dlfs_nspf;      /* 120: number of sectors per fragment */
        u_int32_t dlfs_cleansz;   /* 124: cleaner info size in blocks */
        u_int32_t dlfs_segtabsz;  /* 128: segment table size in blocks */
        u_int32_t dlfs_segmask;   /* 132: calculate offset within a segment */
        u_int32_t dlfs_segshift;  /* 136: fast mult/div for segments */
        u_int32_t dlfs_bshift;    /* 140: calc block number from file offset */
        u_int32_t dlfs_ffshift;   /* 144: fast mult/div for frag from file */
        u_int32_t dlfs_fbshift;   /* 148: fast mult/div for frag from block */
        u_int64_t dlfs_bmask;     /* 152: calc block offset from file offset */
        u_int64_t dlfs_ffmask;    /* 160: calc frag offset from file offset */
        u_int64_t dlfs_fbmask;    /* 168: calc frag offset from block offset */
        u_int32_t dlfs_fsbtodb;   /* 176: fsbtodb and dbtofsb shift constant */
        u_int32_t dlfs_sushift;   /* 180: fast mult/div for segusage table */

        int32_t   dlfs_maxsymlinklen; /* 184: max length of an internal symlink */

#define	LFS_MIN_SBINTERVAL	5  /* minimum superblock segment spacing */
#define LFS_MAXNUMSB            10 /* 188: superblock disk offsets */
        ufs_daddr_t       dlfs_sboffs[LFS_MAXNUMSB];

	u_int32_t dlfs_nclean;    /* 228: Number of clean segments */
	u_char	  dlfs_fsmnt[MNAMELEN];	 /* 232: name mounted on */
	/* XXX this is 2 bytes only to pad to a quad boundary */
	u_int16_t dlfs_clean;     /* 322: file system is clean flag */
        int8_t    dlfs_pad[184];  /* 324: round to 512 bytes */
/* Checksum -- last valid disk field. */
        u_int32_t dlfs_cksum;     /* 328: checksum for superblock checking */
};

/* Maximum number of io's we can have pending at once */
#define LFS_THROTTLE  16 /* XXX should be better paramtrized - ? */

/* In-memory super block. */
struct lfs {
        struct dlfs lfs_dlfs;           /* on-disk parameters */
#define lfs_magic lfs_dlfs.dlfs_magic
#define lfs_version lfs_dlfs.dlfs_version
#define lfs_size lfs_dlfs.dlfs_size
#define lfs_ssize lfs_dlfs.dlfs_ssize
#define lfs_dsize lfs_dlfs.dlfs_dsize
#define lfs_bsize lfs_dlfs.dlfs_bsize
#define lfs_fsize lfs_dlfs.dlfs_fsize
#define lfs_frag lfs_dlfs.dlfs_frag
#define lfs_free lfs_dlfs.dlfs_free
#define lfs_bfree lfs_dlfs.dlfs_bfree
#define lfs_nfiles lfs_dlfs.dlfs_nfiles
#define lfs_avail lfs_dlfs.dlfs_avail
#define lfs_uinodes lfs_dlfs.dlfs_uinodes
#define lfs_idaddr lfs_dlfs.dlfs_idaddr
#define lfs_ifile lfs_dlfs.dlfs_ifile
#define lfs_lastseg lfs_dlfs.dlfs_lastseg
#define lfs_nextseg lfs_dlfs.dlfs_nextseg
#define lfs_curseg lfs_dlfs.dlfs_curseg
#define lfs_offset lfs_dlfs.dlfs_offset
#define lfs_lastpseg lfs_dlfs.dlfs_lastpseg
#define lfs_tstamp lfs_dlfs.dlfs_tstamp
#define lfs_minfree lfs_dlfs.dlfs_minfree
#define lfs_maxfilesize lfs_dlfs.dlfs_maxfilesize
#define lfs_dbpseg lfs_dlfs.dlfs_dbpseg
#define lfs_inopb lfs_dlfs.dlfs_inopb
#define lfs_ifpb lfs_dlfs.dlfs_ifpb
#define lfs_sepb lfs_dlfs.dlfs_sepb
#define lfs_nindir lfs_dlfs.dlfs_nindir
#define lfs_nseg lfs_dlfs.dlfs_nseg
#define lfs_nspf lfs_dlfs.dlfs_nspf
#define lfs_cleansz lfs_dlfs.dlfs_cleansz
#define lfs_segtabsz lfs_dlfs.dlfs_segtabsz
#define lfs_segmask lfs_dlfs.dlfs_segmask
#define lfs_segshift lfs_dlfs.dlfs_segshift
#define lfs_bmask lfs_dlfs.dlfs_bmask
#define lfs_bshift lfs_dlfs.dlfs_bshift
#define lfs_ffmask lfs_dlfs.dlfs_ffmask
#define lfs_ffshift lfs_dlfs.dlfs_ffshift
#define lfs_fbmask lfs_dlfs.dlfs_fbmask
#define lfs_fbshift lfs_dlfs.dlfs_fbshift
#define lfs_fsbtodb lfs_dlfs.dlfs_fsbtodb
#define lfs_sushift lfs_dlfs.dlfs_sushift
#define lfs_maxsymlinklen lfs_dlfs.dlfs_maxsymlinklen
#define lfs_sboffs lfs_dlfs.dlfs_sboffs
#define lfs_cksum lfs_dlfs.dlfs_cksum
#define lfs_clean lfs_dlfs.dlfs_clean
#define lfs_fsmnt lfs_dlfs.dlfs_fsmnt
#define lfs_nclean lfs_dlfs.dlfs_nclean
/* These fields are set at mount time and are meaningless on disk. */
	struct segment *lfs_sp;		/* current segment being written */
	struct vnode *lfs_ivnode;	/* vnode for the ifile */
	u_int32_t  lfs_seglock;		/* single-thread the segment writer */
	pid_t	  lfs_lockpid;		/* pid of lock holder */
	u_int32_t lfs_iocount;		/* number of ios pending */
	u_int32_t lfs_writer;		/* don't allow any dirops to start */
	u_int32_t lfs_dirops;		/* count of active directory ops */
	u_int32_t lfs_doifile;		/* Write ifile blocks on next write */
	u_int32_t lfs_nactive;		/* Number of segments since last ckp */
	int8_t	  lfs_fmod;		/* super block modified flag */
	int8_t	  lfs_ronly;		/* mounted read-only flag */
	int8_t	  lfs_flags;		/* currently unused flag */
	u_int16_t lfs_activesb;         /* toggle between superblocks */
#ifdef LFS_TRACK_IOS
	daddr_t   lfs_pending[LFS_THROTTLE]; /* daddrs of pending writes */
#endif /* LFS_TRACK_IOS */
# define LFS_MAXDIROP 32
	int       lfs_dirvcount;        /* number of VDIROP-marked vnodes */
#ifdef LFS_CANNOT_ROLLFW
	daddr_t   lfs_sbactive;         /* disk address of in-progress sb write */
#endif
	struct vnode *lfs_flushvp;      /* vnode being flushed */
};

/*
 * Inode 0:	out-of-band inode number
 * Inode 1:	IFILE inode number
 * Inode 2:	root inode
 * Inode 3:	lost+found inode number
 */
#define	LFS_UNUSED_INUM	0		/* out of band inode number */
#define	LFS_IFILE_INUM	1		/* IFILE inode number */
#define	LOSTFOUNDINO	3		/* lost+found inode number */
#define	LFS_FIRST_INUM	4		/* first free inode number */

/* Address calculations for metadata located in the inode */
#define	S_INDIR(fs)	-NDADDR
#define	D_INDIR(fs)	(S_INDIR(fs) - NINDIR(fs) - 1)
#define	T_INDIR(fs)	(D_INDIR(fs) - NINDIR(fs) * NINDIR(fs) - 1)

/* Unassigned disk address. */
#define	UNASSIGNED	-1

/* Unused logical block number */
#define LFS_UNUSED_LBN	-1

typedef struct ifile IFILE;
struct ifile {
	u_int32_t if_version;		/* inode version number */
#define	LFS_UNUSED_DADDR	0	/* out-of-band daddr */
	ufs_daddr_t if_daddr;		/* inode disk address */
	ino_t	  if_nextfree;		/* next-unallocated inode */
#ifdef LFS_ATIME_IFILE
	struct timespec if_atime;	/* Last access time */
#endif
};

/*
 * Cleaner information structure.  This resides in the ifile and is used
 * to pass information between the cleaner and the kernel.
 */
typedef struct _cleanerinfo {
	u_int32_t clean;		/* K: number of clean segments */
	u_int32_t dirty;		/* K: number of dirty segments */
} CLEANERINFO;

#define	CLEANSIZE_SU(fs)						\
	((sizeof(CLEANERINFO) + (fs)->lfs_bsize - 1) >> (fs)->lfs_bshift)

/*
 * All summary blocks are the same size, so we can always read a summary
 * block easily from a segment.
 */
#define	LFS_SUMMARY_SIZE	512

/* On-disk segment summary information */
typedef struct segsum SEGSUM;
struct segsum {
	u_int32_t ss_sumsum;		/* check sum of summary block */
	u_int32_t ss_datasum;		/* check sum of data */
	u_int32_t ss_magic;		/* segment summary magic number */
#define SS_MAGIC	0x061561
	ufs_daddr_t ss_next;		/* next segment */
	u_int32_t ss_create;		/* creation time stamp */
	u_int16_t ss_nfinfo;		/* number of file info structures */
	u_int16_t ss_ninos;		/* number of inodes in summary */

#define	SS_DIROP	0x01		/* segment begins a dirop */
#define	SS_CONT		0x02		/* more partials to finish this write*/
	u_int16_t ss_flags;		/* used for directory operations */
	u_int16_t ss_pad;		/* extra space */
	/* FINFO's and inode daddr's... */
};

/* NINDIR is the number of indirects in a file system block. */
#define	NINDIR(fs)	((fs)->lfs_nindir)

/* INOPB is the number of inodes in a secondary storage block. */
#define	INOPB(fs)	((fs)->lfs_inopb)

#define	blksize(fs, ip, lbn) \
	(((lbn) >= NDADDR || (ip)->i_ffs_size >= ((lbn) + 1) << (fs)->lfs_bshift) \
	    ? (fs)->lfs_bsize \
	    : (fragroundup(fs, blkoff(fs, (ip)->i_ffs_size))))
#define	blkoff(fs, loc)		((int)(loc) & (fs)->lfs_bmask)
#define fragoff(fs, loc)    /* calculates (loc % fs->lfs_fsize) */ \
    ((int)((loc) & (fs)->lfs_ffmask))
#define	fsbtodb(fs, b)		((b) << (fs)->lfs_fsbtodb)
#define	dbtofsb(fs, b)		((b) >> (fs)->lfs_fsbtodb)
#define fragstodb(fs, b)	((b) << ((fs)->lfs_fsbtodb - (fs)->lfs_fbshift))
#define dbtofrags(fs, b)	((b) >> ((fs)->lfs_fsbtodb - (fs)->lfs_fbshift))
#define	lblkno(fs, loc)		((loc) >> (fs)->lfs_bshift)
#define	lblktosize(fs, blk)	((blk) << (fs)->lfs_bshift)
#define numfrags(fs, loc)	/* calculates (loc / fs->lfs_fsize) */	\
	((loc) >> (fs)->lfs_ffshift)
#define blkroundup(fs, size)	/* calculates roundup(size, fs->lfs_bsize) */ \
	((int)(((size) + (fs)->lfs_bmask) & (~(fs)->lfs_bmask)))
#define fragroundup(fs, size)	/* calculates roundup(size, fs->lfs_fsize) */ \
	((int)(((size) + (fs)->lfs_ffmask) & (~(fs)->lfs_ffmask)))
#define fragstoblks(fs, frags)	/* calculates (frags / fs->lfs_frag) */ \
	((frags) >> (fs)->lfs_fbshift)
#define blkstofrags(fs, blks)	/* calculates (blks * fs->lfs_frag) */ \
	((blks) << (fs)->lfs_fbshift)
#define fragnum(fs, fsb)	/* calculates (fsb % fs->lfs_frag) */ \
	((fsb) & ((fs)->lfs_frag - 1))
#define blknum(fs, fsb)		/* calculates rounddown(fsb, fs->lfs_frag) */ \
	((fsb) &~ ((fs)->lfs_frag - 1))
#define dblksize(fs, dip, lbn) \
	(((lbn) >= NDADDR || (dip)->di_size >= ((lbn) + 1) << (fs)->lfs_bshift)\
	    ? (fs)->lfs_bsize \
	    : (fragroundup(fs, blkoff(fs, (dip)->di_size))))
#define	datosn(fs, daddr)	/* disk address to segment number */	\
	(((daddr) - (fs)->lfs_sboffs[0]) / fsbtodb((fs), (fs)->lfs_ssize))
#define sntoda(fs, sn) 		/* segment number to disk address */	\
	((ufs_daddr_t)((sn) * ((fs)->lfs_ssize << (fs)->lfs_fsbtodb) +	\
	    (fs)->lfs_sboffs[0]))

/* Read in the block with the cleaner info from the ifile. */
#define LFS_CLEANERINFO(CP, F, BP) {					\
	VTOI((F)->lfs_ivnode)->i_flag |= IN_ACCESS;			\
	if (bread((F)->lfs_ivnode,					\
	    (ufs_daddr_t)0, (F)->lfs_bsize, NOCRED, &(BP)))		\
		panic("lfs: ifile read");				\
	(CP) = (CLEANERINFO *)(BP)->b_data;				\
}

/* Read in the block with a specific inode from the ifile. */
#define	LFS_IENTRY(IP, F, IN, BP) {					\
	int _e;								\
	VTOI((F)->lfs_ivnode)->i_flag |= IN_ACCESS;			\
	if ((_e = bread((F)->lfs_ivnode,				\
	    (IN) / (F)->lfs_ifpb + (F)->lfs_cleansz + (F)->lfs_segtabsz,\
	    (F)->lfs_bsize, NOCRED, &(BP))) != 0)			\
		panic("lfs: ifile read %d", _e);			\
	(IP) = (IFILE *)(BP)->b_data + (IN) % (F)->lfs_ifpb;		\
}

/* Read in the block with a specific segment usage entry from the ifile. */
#define	LFS_SEGENTRY(SP, F, IN, BP) {					\
	int _e;								\
	VTOI((F)->lfs_ivnode)->i_flag |= IN_ACCESS;			\
	if ((_e = bread((F)->lfs_ivnode,				\
	    ((IN) >> (F)->lfs_sushift) + (F)->lfs_cleansz,		\
	    (F)->lfs_bsize, NOCRED, &(BP))) != 0)			\
		panic("lfs: ifile read: %d", _e);			\
	(SP) = (SEGUSE *)(BP)->b_data + ((IN) & ((F)->lfs_sepb - 1));	\
}

/* Determine if a buffer belongs to the ifile */
#define IS_IFILE(bp)	(VTOI(bp->b_vp)->i_number == LFS_IFILE_INUM)

/*
 * Structures used by lfs_bmapv and lfs_markv to communicate information
 * about inodes and data blocks.
 */
typedef struct block_info {
	ino_t	bi_inode;		/* inode # */
	ufs_daddr_t bi_lbn;		/* logical block w/in file */
	ufs_daddr_t bi_daddr;		/* disk address of block */
	time_t	bi_segcreate;		/* origin segment create time */
	int	bi_version;		/* file version number */
	void	*bi_bp;			/* data buffer */
	int     bi_size;		/* size of the block (if fragment) */
} BLOCK_INFO;

/* In-memory description of a segment about to be written. */
struct segment {
	struct lfs	 *fs;		/* file system pointer */
	struct buf	**bpp;		/* pointer to buffer array */
	struct buf	**cbpp;		/* pointer to next available bp */
	struct buf	**start_bpp;	/* pointer to first bp in this set */
	struct buf	 *ibp;		/* buffer pointer to inode page */
	struct finfo	 *fip;		/* current fileinfo pointer */
	struct vnode	 *vp;		/* vnode being gathered */
	void	 *segsum;		/* segment summary info */
	u_int32_t ninodes;		/* number of inodes in this segment */
	u_int32_t seg_bytes_left;	/* bytes left in segment */
	u_int32_t sum_bytes_left;	/* bytes left in summary block */
	u_int32_t seg_number;		/* number of this segment */
	ufs_daddr_t *start_lbp;		/* beginning lbn for this set */

#define	SEGM_CKP	0x01		/* doing a checkpoint */
#define	SEGM_CLEAN	0x02		/* cleaner call; don't sort */
#define	SEGM_SYNC	0x04		/* wait for segment */
	u_int16_t seg_flags;		/* run-time flags for this segment */
};

#define ISSPACE(F, BB, C)						\
	(((C)->cr_uid == 0 && (F)->lfs_bfree >= (BB)) ||		\
	((C)->cr_uid != 0 && IS_FREESPACE(F, BB)))

#define IS_FREESPACE(F, BB)						\
	((F)->lfs_bfree > ((F)->lfs_dsize * (F)->lfs_minfree / 100 + (BB)))

#define ISSPACE_XXX(F, BB)						\
	((F)->lfs_bfree >= (BB))

/* Statistics Counters */
struct lfs_stats {
	u_int	segsused;
	u_int	psegwrites;
	u_int	psyncwrites;
	u_int	pcleanwrites;
	u_int	blocktot;
	u_int	cleanblocks;
	u_int	ncheckpoints;
	u_int	nwrites;
	u_int	nsync_writes;
	u_int	wait_exceeded;
	u_int	write_exceeded;
	u_int	flush_invoked;
	u_int	vflush_invoked;
};
extern struct lfs_stats lfs_stats;


text:
<readable><title>2882589788_cb0b407a8d</title><content>
A girl in a blue uniform raises her arm .
A young cheerleader is cheering
A young female cheerleader dressed in a blue uniform is cheering in front of a group of band members .
A young girl in a blue and white cheerleading costume holds her right arm up while her other hand is on her hip .
Girl in blue and white uniform doing cheers
</content></readable>

redpajama_set_name: RedPajamaGithub


text:
function [x,w,mxy] = SStest
% Test Bloch Equation simulation of a pulse
% 1ms 3-lobe sinc has BW = 6000Hz
% 1G/cm = 4200 Hz/cm
% Slice width = 6000/4200 = 1.4cm
%
% The MIT License (MIT)
%
% Copyright (c) 2016 Mike Tyszka
%
%   Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
%   documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
%   rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
%   permit persons to whom the Software is furnished to do so, subject to the following conditions:
%
%   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
%   Software.
%
%   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
%   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
%   COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
%   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

PW = 1e-3;
dt = 8e-6;
t = (0:dt:(PW-dt))-PW/2;   % 1ms pulse in 8us increments
w = 3.0*2*pi/PW;           % 3-lobe sinc
phi = w*t;
B1t = sin(phi)./(phi);
B1t(isnan(B1t)) = 1.0;

B1t = B1t / 1e6; % Scale B1 into low flip angle regime

Gt = 1.0e-2*ones(size(B1t)); % 1 G/cm gradient

[x,w,mxy] = SSBlochSim(t,Gt,B1t);

surfl(w,x,abs(mxy)); shading interp;


text:
package org.g4studio.core.mvc.xstruts.actions;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.g4studio.core.mvc.xstruts.Globals;
import org.g4studio.core.mvc.xstruts.action.ActionForm;
import org.g4studio.core.mvc.xstruts.action.ActionForward;
import org.g4studio.core.mvc.xstruts.action.ActionMapping;

/**
 * Implementation of Action that changes the user's
 * {@link java.util.Locale} and forwards to a page, based on request level
 * parameters that are set (language, country, & page).
 */
public final class LocaleAction extends BaseAction {

	/**
	 * Commons Logging instance.
	 */
	private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// Extract attributes we will need
		HttpSession session = request.getSession();
		Locale locale = getLocale(request);

		String language = null;
		String country = null;
		String page = null;

		try {
			language = (String) PropertyUtils.getSimpleProperty(form, "language");
			country = (String) PropertyUtils.getSimpleProperty(form, "country");
			page = (String) PropertyUtils.getSimpleProperty(form, "page");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		boolean isLanguage = ((language != null) && (language.length() > 0));
		boolean isCountry = ((country != null) && (country.length() > 0));

		if ((isLanguage) && (isCountry)) {
			locale = new java.util.Locale(language, country);
		} else if (isLanguage) {
			locale = new java.util.Locale(language, "");
		}

		session.setAttribute(Globals.LOCALE_KEY, locale);

		if (null == page) {
			return mapping.findForward("success");
		} else {
			return new ActionForward(page);
		}
	}
}


text:
#ifndef _lmic_compliance_h_	/* prevent multiple includes */
#define _lmic_compliance_h_

#ifdef __cplusplus
extern "C"{
#endif

#ifndef _lmic_h_
# include "lmic.h"
#endif

#include <stdbool.h>
#include <stdint.h>

typedef struct lmic_compliance_s lmic_compliance_t;

// concrete type for the state enumeration for the compliance engine.
typedef uint8_t lmic_compliance_state_t;

enum lmic_compliance_state_e {
    LMIC_COMPLIANCE_STATE_IDLE = 0,       // app state
    LMIC_COMPLIANCE_STATE_STOPPING = 1,   // transitioning back to app
    LMIC_COMPLIANCE_STATE_ACTIVATING = 2, // transitioning to compliance state
    LMIC_COMPLIANCE_STATE_ACTIVE = 3,     // in compliance state
};

// return true if a state value indicates that the FSM is active.
static inline bool
lmic_compliance_state_IsActive(lmic_compliance_state_t s) {
    return s >= LMIC_COMPLIANCE_STATE_ACTIVATING;
}

// events from the outside world to the FSM
typedef uint8_t lmic_compliance_eventflags_t;

enum lmic_compliance_eventflags_e {
    LMIC_COMPLIANCE_EVENT_ACTIVATE      = 1u << 0,
    LMIC_COMPLIANCE_EVENT_DEACTIVATE    = 1u << 1,
    LMIC_COMPLIANCE_EVENT_TIMER_EXPIRED = 1u << 2,
    LMIC_COMPLIANCE_EVENT_UPLINK_COMPLETE = 1u << 3,
    LMIC_COMPLIANCE_EVENT_ECHO_REQUEST  = 1u << 4,
};

typedef uint8_t lmic_compliance_fsmflags_t;
enum lmic_compliance_fsmflags_e {
    LMIC_COMPLIANCE_FSM_ACTIVE          = 1u << 0,
    LMIC_COMPLIANCE_FSM_REENTERED       = 1u << 1,
    LMIC_COMPLIANCE_FSM_CONFIRM         = 1u << 2,
};

typedef uint8_t lmic_compliance_fsmstate_t;
enum lmic_compliance_fsmstate_e {
    LMIC_COMPLIANCE_FSMSTATE_INITIAL = 0,
    LMIC_COMPLIANCE_FSMSTATE_NOCHANGE = 1,
    LMIC_COMPLIANCE_FSMSTATE_ACTIVE = 2,
    LMIC_COMPLIANCE_FSMSTATE_INACTIVE = 3,
    LMIC_COMPLIANCE_FSMSTATE_TESTMODE = 4,   // sending test uplinks
    LMIC_COMPLIANCE_FSMSTATE_ECHOING = 5,
    LMIC_COMPLIANCE_FSMSTATE_REPORTING = 6,
    LMIC_COMPLIANCE_FSMSTATE_RECOVERY = 7,
    LMIC_COMPLIANCE_FSMSTATE_TXBUSY = 8,
};

#define LMIC_COMPLIANCE_FSMSTATE__NAMES   \
    "INITIAL", "NOCHANGE", "ACTIVE", "INACTIVE", "TESTMODE",   \
    "ECHOING", "REPORTING", "RECOVERY", "TXBUSY"

typedef struct lmic_compliance_eventcb_s lmic_compliance_eventcb_t;
struct lmic_compliance_eventcb_s {
	// save the user's event CB while active.
	lmic_event_cb_t		*pEventCb;
	// save the user's event data while active.
	void			*pUserData;
};

// structure for saving band settings during test
typedef struct lmic_compliance_band_s lmic_compliance_band_t;
struct lmic_compliance_band_s {
    u2_t    txcap;  // saved 1/duty cycle
};

// the state of the compliance engine.
struct lmic_compliance_s {
        // uint64
        // uintptr
        osjob_t                     timerJob;       // the job for driving uplinks
        osjob_t                     fsmJob;         // job for reevaluating the FSM.
        lmic_compliance_eventcb_t   saveEvent;      // the user's event handler.

        // uint32

        // uint16
#if CFG_LMIC_EU_like
        lmic_compliance_band_t      saveBands[MAX_BANDS];
#endif // CFG_LMIC_EU_like

        // we are required to maintain a downlink count
        // that is reset on join/test entry and incremented for
        // each valid test message.
        uint16_t                    downlinkCount;

        // uint8

        lmic_compliance_state_t         state;      // current state of compliance engine.
        lmic_compliance_eventflags_t    eventflags; // incoming events.
        lmic_compliance_fsmflags_t      fsmFlags;   // FSM operational flags
        lmic_compliance_fsmstate_t      fsmState;   // FSM current state

        uint8_t                 uplinkSize;
        uint8_t                 uplinkMessage[MAX_LEN_PAYLOAD];
};

extern lmic_compliance_t LMIC_Compliance;

#ifdef __cplusplus
} // extern "C"
#endif

#endif /* _lmic_compliance_h_ */


text:
title: "ui.routingtable.source.newtab"
---

`ui.routingtable.source.scheme` configures the scheme protocol for the link of the source on the routing table.  This is useful when the scheme is different than the current page
or to force the traffic to a certain protocol.

This is only applicable if the [linkenabled](/ref/ui.routingtable.source.linkenabled/) is set to true.

The default is

    ui.routingtable.source.scheme = http


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

// ---
// Author: Craig Silverstein
//
// This is just a very thin wrapper over densehashtable.h, just
// like sgi stl's stl_hash_set is a very thin wrapper over
// stl_hashtable.  The major thing we define is operator[], because
// we have a concept of a data_type which stl_hashtable doesn't
// (it only has a key and a value).
//
// This is more different from dense_hash_map than you might think,
// because all iterators for sets are const (you obviously can't
// change the key, and for sets there is no value).
//
// NOTE: this is exactly like sparse_hash_set.h, with the word
// "sparse" replaced by "dense", except for the addition of
// set_empty_key().
//
//   YOU MUST CALL SET_EMPTY_KEY() IMMEDIATELY AFTER CONSTRUCTION.
//
// Otherwise your program will die in mysterious ways.
//
// In other respects, we adhere mostly to the STL semantics for
// hash-set.  One important exception is that insert() invalidates
// iterators entirely.  On the plus side, though, erase() doesn't
// invalidate iterators at all, or even change the ordering of elements.
//
// Here are a few "power user" tips:
//
//    1) set_deleted_key():
//         If you want to use erase() you must call set_deleted_key(),
//         in addition to set_empty_key(), after construction.
//         The deleted and empty keys must differ.
//
//    2) resize(0):
//         When an item is deleted, its memory isn't freed right
//         away.  This allows you to iterate over a hashtable,
//         and call erase(), without invalidating the iterator.
//         To force the memory to be freed, call resize(0).
//
// Guide to what kind of hash_set to use:
//   (1) dense_hash_set: fastest, uses the most memory
//   (2) sparse_hash_set: slowest, uses the least memory
//   (3) hash_set (STL): in the middle
// Typically I use sparse_hash_set when I care about space and/or when
// I need to save the hashtable on disk.  I use hash_set otherwise.  I
// don't personally use dense_hash_set ever; the only use of
// dense_hash_set I know of is to work around malloc() bugs in some
// systems (dense_hash_set has a particularly simple allocation scheme).
//
// - dense_hash_set has, typically, a factor of 2 memory overhead (if your
//   data takes up X bytes, the hash_set uses X more bytes in overhead).
// - sparse_hash_set has about 2 bits overhead per entry.
// - sparse_hash_map can be 3-7 times slower than the others for lookup and,
//   especially, inserts.  See time_hash_map.cc for details.
//
// See /usr/(local/)?doc/sparsehash-0.1/dense_hash_set.html
// for information about how to use this class.

#ifndef _DENSE_HASH_SET_H_
#define _DENSE_HASH_SET_H_

//#include <google/sparsehash/sparseconfig.h>
#include <stdio.h>                   // for FILE * in read()/write()
#include <algorithm>                 // for the default template args
#include <functional>                // for equal_to
#include <memory>                    // for alloc<>
#include <utility>                   // for pair<>
//#include HASH_FUN_H                  // defined in config.h
#include "densehashtable.h"

using std::pair;

template <class Value,
          class HashFcn,
          class EqualKey = std::equal_to<Value>,
          class Alloc = std::allocator<Value> >
class dense_hash_set {
 private:
  // Apparently identity is not stl-standard, so we define our own
  struct Identity {
    Value& operator()(Value& v) const { return v; }
    const Value& operator()(const Value& v) const { return v; }
  };

  // The actual data
  typedef dense_hashtable<Value, Value, HashFcn, Identity, EqualKey, Alloc> ht;
  ht rep;

 public:
  typedef typename ht::key_type key_type;
  typedef typename ht::value_type value_type;
  typedef typename ht::hasher hasher;
  typedef typename ht::key_equal key_equal;

  typedef typename ht::size_type size_type;
  typedef typename ht::difference_type difference_type;
  typedef typename ht::const_pointer pointer;
  typedef typename ht::const_pointer const_pointer;
  typedef typename ht::const_reference reference;
  typedef typename ht::const_reference const_reference;

  typedef typename ht::const_iterator iterator;
  typedef typename ht::const_iterator const_iterator;

  // Iterator functions -- recall all iterators are const
  iterator begin() const              { return rep.begin(); }
  iterator end() const                { return rep.end(); }

  // Accessor functions
  hasher hash_funct() const { return rep.hash_funct(); }
  key_equal key_eq() const  { return rep.key_eq(); }

  // Constructors
  explicit dense_hash_set(size_type n = 0,
                          const hasher& hf = hasher(),
                          const key_equal& eql = key_equal())
    : rep(n, hf, eql) { }

  template <class InputIterator>
  dense_hash_set(InputIterator f, InputIterator l,
                 size_type n = 0,
                 const hasher& hf = hasher(),
                 const key_equal& eql = key_equal())
	: rep(n, hf, eql) {
    rep.insert(f, l);
  }
  // We use the default copy constructor
  // We use the default operator=()
  // We use the default destructor

  void clear()                        { rep.clear(); }
  // This clears the hash set without resizing it down to the minimum
  // bucket count, but rather keeps the number of buckets constant
  void clear_no_resize()              { rep.clear_no_resize(); }
  void swap(dense_hash_set& hs)       { rep.swap(hs.rep); }

  // Functions concerning size
  size_type size() const              { return rep.size(); }
  size_type max_size() const          { return rep.max_size(); }
  bool empty() const                  { return rep.empty(); }
  size_type bucket_count() const      { return rep.bucket_count(); }
  size_type max_bucket_count() const  { return rep.max_bucket_count(); }

  void resize(size_type hint)         { rep.resize(hint); }

  // Lookup routines
  iterator find(const key_type& key) const           { return rep.find(key); }

  size_type count(const key_type& key) const         { return rep.count(key); }

  pair<iterator, iterator> equal_range(const key_type& key) const {
    return rep.equal_range(key);
  }

  // Insertion routines
  pair<iterator, bool> insert(const value_type& obj) {
    pair<typename ht::iterator, bool> p = rep.insert(obj);
    return pair<iterator, bool>(p.first, p.second);   // const to non-const
  }
  template <class InputIterator>
  void insert(InputIterator f, InputIterator l)      { rep.insert(f, l); }
  void insert(const_iterator f, const_iterator l)    { rep.insert(f, l); }
  // required for std::insert_iterator; the passed-in iterator is ignored
  iterator insert(iterator, const value_type& obj)   { return insert(obj).first; }

  // Deletion and empty routines
  // THESE ARE NON-STANDARD!  I make you specify an "impossible" key
  // value to identify deleted and empty buckets.  You can change the
  // deleted key as time goes on, or get rid of it entirely to be insert-only.
  void set_empty_key(const key_type& key)     { rep.set_empty_key(key); }
  void set_deleted_key(const key_type& key)   { rep.set_deleted_key(key); }
  void clear_deleted_key()                    { rep.clear_deleted_key(); }

  // These are standard
  size_type erase(const key_type& key)               { return rep.erase(key); }
  void erase(iterator it)                            { rep.erase(it); }
  void erase(iterator f, iterator l)                 { rep.erase(f, l); }

  // Comparison
  bool operator==(const dense_hash_set& hs) const    { return rep == hs.rep; }
  bool operator!=(const dense_hash_set& hs) const    { return rep != hs.rep; }
};

template <class Val, class HashFcn, class EqualKey, class Alloc>
inline void swap(dense_hash_set<Val, HashFcn, EqualKey, Alloc>& hs1,
                 dense_hash_set<Val, HashFcn, EqualKey, Alloc>& hs2) {
  hs1.swap(hs2);
}

#endif /* _DENSE_HASH_SET_H_ */


text:
package org.kie.workbench.common.forms.adf.definitions.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.kie.workbench.common.forms.adf.definitions.annotations.i18n.I18nSettings;
import org.kie.workbench.common.forms.adf.definitions.annotations.layout.Layout;
import org.kie.workbench.common.forms.adf.definitions.settings.FieldPolicy;
import org.kie.workbench.common.forms.adf.definitions.settings.LabelPosition;
import org.kie.workbench.common.forms.adf.service.definitions.FormDefinitionSettings;

/**
 * Indicates to the ADF engine to generate the {@link FormDefinitionSettings} for the annotated class.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface FormDefinition {

    /**
     * Determines how labesl are going to be aligned on the form
     */
    LabelPosition labelPosition() default LabelPosition.DEFAULT;

    /**
     * Indicates to the ADF engine to add fields from all the superclasses of the annotated class
     */
    boolean allowInheritance() default true;

    /**
     * Determines the policy to add form elements.
     */
    FieldPolicy policy() default FieldPolicy.ALL;

    /**
     * Defines the i18nSettings to get the field labels
     */
    I18nSettings i18n() default @I18nSettings;

    /**
     * Defines the form layout
     */
    Layout layout() default @Layout;

    /**
     * Determines what's the element name of first form element
     */
    String startElement() default "";

    /**
     * List of default settings to configure the fields
     */
    FieldParam[] defaultFieldSettings() default {};
}


text:
namespace sg_gui {

class WindowClass {

public:

	static char* getDummyWindowClass();

	static char* getDefaultWindowClass();

private:

	static bool _dummyWindowClassRegistered;

	static bool _defaultWindowClassRegistered;
};

} // namespace sg_gui

#endif // SG_GUI_WINDOWS_WINDOW_CLASS_H__


text:
package com.adyen.v6.converters;

import com.adyen.model.checkout.PaymentsDetailsResponse;
import com.adyen.model.checkout.PaymentsResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.core.convert.converter.Converter;

import java.lang.reflect.InvocationTargetException;

public class PaymentsDetailsResponseConverter implements Converter<PaymentsDetailsResponse, PaymentsResponse> {
    @Override
    public PaymentsResponse convert(PaymentsDetailsResponse paymentsDetailsResponse) {
        if (paymentsDetailsResponse == null) {
            throw new IllegalArgumentException("Null PaymentsDetailsResponse");
        }
        PaymentsResponse paymentsResponse = new PaymentsResponse();

        try {
            BeanUtils.copyProperties(paymentsResponse, paymentsDetailsResponse);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("Bean copy error, Cannot convert from PaymentsDetailsResponse to PaymentsResponse", e);
        }
        return paymentsResponse;
    }
}


text:
#include "../include/lambdacommon/path.h"
#include "../include/lambdacommon/lstring.h"
#include "lambdacommon/lerror.h"
#include <sstream>

#ifdef LAMBDA_WINDOWS
#  pragma warning(push)
#  pragma warning(disable:4101)
#endif

namespace lambdacommon
{
    std::string fix_path(const std::string& path) {
        return lstring::replace_all(path, '\\', '/');
    }

    AbstractPath::AbstractPath() : _path() {}

    AbstractPath::AbstractPath(std::string path) : _path(std::move(lstring::replace_all(std::move(path), '\\', '/'))) {}

    AbstractPath::AbstractPath(const AbstractPath& other) = default;

    AbstractPath::AbstractPath(AbstractPath&& other) noexcept : _path(std::move(other._path)) {}

    void AbstractPath::append(const std::string& path) {
        if (lstring::starts_with(path, "/"))
            throw std::invalid_argument("Cannot append an absolute path to the current path.");
        _path += fix_path(path);
    }

    void AbstractPath::append(const AbstractPath& path) {
        if (!path.is_absolute())
            throw std::invalid_argument("Cannot append an absolute path to the current path.");
        _path += path._path;
    }

    const std::string& AbstractPath::get_path() const {
        return _path;
    }

    void AbstractPath::clear() noexcept {
        this->_path.clear();
    }

    bool AbstractPath::empty() const {
        return this->_path.empty();
    }

    bool AbstractPath::is_absolute() const {
        return lstring::starts_with(_path, "/") && _path.find("..") == std::string::npos;
    }

    std::string AbstractPath::to_string() const {
        return _path;
    }

    std::string AbstractPath::to_string(char delimiter) const {
        if (this->empty())
            return "";
        return std::move(lstring::replace_all(_path, '/', delimiter));
    }

    bool AbstractPath::operator==(const AbstractPath& other) const {
        return this->_path == other._path;
    }

    bool AbstractPath::operator<(const AbstractPath& other) const {
        return this->_path < other._path;
    }
}


text:
<?php

defined( 'SYS_CORE_PATH') OR exit( 'No direct script access allowed') ;

/**
 * SQLite Result Class
 *
 * This class extends the parent result class: CI_DB_result
 *
 * @category	Database
 * @author		EllisLab Dev Team
 * @link		http://codeigniter.com/user_guide/database/
 */
class CI_DB_sqlite_result extends CI_DB_result {

	/**
	 * Number of rows in the result set
	 *
	 * @return	int
	 */
	public function num_rows()
	{
		return  is_int( $this->num_rows)
			? $this->num_rows
			: $this->num_rows = @sqlite_num_rows( $this->result_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Number of fields in the result set
	 *
	 * @return	int
	 */
	public function num_fields()
	{
		return  @sqlite_num_fields( $this->result_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch Field Names
	 *
	 * Generates an array of column names
	 *
	 * @return	array
	 */
	public function list_fields()
	{
		$field_names = array();
		for( $i = 0, $c = $this->num_fields(); $i < $c; $i++)
		{
			$field_names[$i] = sqlite_field_name( $this->result_id, $i);
		}

		return  $field_names;
	}

	// --------------------------------------------------------------------

	/**
	 * Field data
	 *
	 * Generates an array of objects containing field meta-data
	 *
	 * @return	array
	 */
	public function field_data()
	{
		$retval = array();
		for( $i = 0, $c = $this->num_fields(); $i < $c; $i++)
		{
			$retval[$i]			= new stdClass();
			$retval[$i]->name		= sqlite_field_name( $this->result_id, $i);
			$retval[$i]->type		= NULL;
			$retval[$i]->max_length		= NULL;
		}

		return  $retval;
	}

	// --------------------------------------------------------------------

	/**
	 * Data Seek
	 *
	 * Moves the internal pointer to the desired offset. We call
	 * this internally before fetching results to make sure the
	 * result set starts at zero.
	 *
	 * @param	int	$n
	 * @return	bool
	 */
	public function data_seek( $n = 0)
	{
		return  sqlite_seek( $this->result_id, $n);
	}

	// --------------------------------------------------------------------

	/**
	 * Result - associative array
	 *
	 * Returns the result set as an array
	 *
	 * @return	array
	 */
	protected function _fetch_assoc()
	{
		return  sqlite_fetch_array( $this->result_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Result - object
	 *
	 * Returns the result set as an object
	 *
	 * @param	string	$class_name
	 * @return	object
	 */
	protected function _fetch_object( $class_name = 'stdClass')
	{
		return  sqlite_fetch_object( $this->result_id, $class_name);
	}

}


text:
var gl;
var vertices;
var points;

const NumPoints = 250000;

window.onload = function init()
{
    canvas = document.getElementById( "gl-canvas" );

    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { alert( "WebGL isn't available" ); }

    //
    //  Initialize our data for the Sierpinski Gasket
    //

    // First, initialize the corners of our gasket with three points.
    vertices = [
        vec2( -1, -1 ),
        vec2(  -1,  1 ),
        vec2(  1,  1 ),
        vec2(  1, -1 )
    ];

    var scaleConst = 1/2.1;
    var u = add( vertices[0], vertices[1] );
    var v = add( vertices[1], vertices[2] );
    var p = scale( scaleConst, add( u, v ) );

    // Add our randomly chosen point into our array of points
    points = [ p ];

    for ( var i = 0; points.length < NumPoints; ++i ) {
        var j = Math.floor(Math.random() * 4);
        p = add( points[i], vertices[j] );
        p = scale( scaleConst, p );
        points.push( p );
    }

    //
    //  Configure WebGL
    //
    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.clearColor( 1.0, 1.0, 1.0, 1.0 );

    //  Load shaders and initialize attribute buffers
    var program = initShaders( gl, "vertex-shader", "fragment-shader" );
    gl.useProgram( program );

    // Load the data into the GPU
    var bufferId = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );

    var vPos = gl.getAttribLocation( program, "vPosition" );
    gl.vertexAttribPointer( vPos, 2, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPos );

    render();
};

function render()
{
    gl.clear( gl.COLOR_BUFFER_BIT );
    gl.drawArrays( gl.POINTS, 0, points.length );
};


text:
//-----------------------------------------------------------------------
// <copyright file="UdpListener.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Linq;
using System.Net.Sockets;
using Akka.Actor;
using Akka.Annotations;
using Akka.Dispatch;
using Akka.Event;
using Akka.Util.Internal;

namespace Akka.IO
{
    using static Udp;
    using ByteBuffer = ArraySegment<byte>;

    /// <summary>
    /// INTERNAL API
    /// </summary>
    [InternalApi]
    class UdpListener : WithUdpSend, IRequiresMessageQueue<IUnboundedMessageQueueSemantics>
    {
        private readonly IActorRef _bindCommander;
        private readonly Bind _bind;

        protected readonly ILoggingAdapter Log = Context.GetLogger();

        private IActorRef _selector;

        public UdpListener(UdpExt udp, IActorRef bindCommander, Bind bind)
        {
            Udp = udp;
            _bindCommander = bindCommander;
            _bind = bind;

            _selector = Context.Parent;

            Context.Watch(bind.Handler);        // sign death pact

            Socket = (bind.Options.OfType<Inet.DatagramChannelCreator>().FirstOrDefault() ?? new Inet.DatagramChannelCreator()).Create();
            Socket.Blocking = false;

            try
            {
                foreach (var option in bind.Options)
                {
                    option.BeforeDatagramBind(Socket);
                }

                Socket.Bind(bind.LocalAddress);
                var ret = Socket.LocalEndPoint;
                if (ret == null)
                    throw new ArgumentException($"bound to unknown SocketAddress [{Socket.LocalEndPoint}]");

                Log.Debug("Successfully bound to [{0}]", ret);
                bind.Options.OfType<Inet.SocketOptionV2>().ForEach(x => x.AfterBind(Socket));

                ReceiveAsync();
            }
            catch (Exception e)
            {
                bindCommander.Tell(new CommandFailed(bind));
                Log.Error(e, "Failed to bind UDP channel to endpoint [{0}]", bind.LocalAddress);
                Context.Stop(Self);
            }
        }

        protected sealed override Socket Socket { get; }
        /// <summary>
        /// TBD
        /// </summary>
        protected sealed override UdpExt Udp { get; }

        protected override void PreStart()
        {
            _bindCommander.Tell(new Bound(Socket.LocalEndPoint));
            Context.Become(m => ReadHandlers(m) || SendHandlers(m));
        }

        protected override bool Receive(object message)
        {
            throw new NotSupportedException();
        }

        private bool ReadHandlers(object message)
        {
            if (message is SuspendReading)
            {
                // TODO: What should we do here - we cant cancel a pending ReceiveAsync
                return true;
            }
            if (message is ResumeReading)
            {
                ReceiveAsync();
                return true;
            }
            if (message is SocketReceived)
            {
                var received = (SocketReceived) message;
                DoReceive(received.EventArgs, _bind.Handler);
                return true;
            }

            if (message is Unbind)
            {
                Log.Debug("Unbinding endpoint [{0}]", _bind.LocalAddress);
                try
                {
                    Socket.Dispose();
                    Sender.Tell(Unbound.Instance);
                    Log.Debug("Unbound endpoint [{0}], stopping listener", _bind.LocalAddress);
                }
                finally
                {
                    Context.Stop(Self);
                }
                return true;
            }
            return false;
        }

        private void DoReceive(SocketAsyncEventArgs e, IActorRef handler)
        {
            try
            {
                handler.Tell(new Received(ByteString.FromBytes(e.Buffer, e.Offset, e.BytesTransferred), e.RemoteEndPoint));
                ReceiveAsync();
            }
            finally
            {
                var buffer = new ByteBuffer(e.Buffer, e.Offset, e.Count);
                Udp.SocketEventArgsPool.Release(e);
                Udp.BufferPool.Release(buffer);
            }
        }

        /// <summary>
        /// TBD
        /// </summary>
        protected override void PostStop()
        {
            if (Socket.Connected)
            {
                Log.Debug("Closing DatagramChannel after being stopped");
                try
                {
                    Socket.Dispose();
                }
                catch (Exception e)
                {
                    Log.Debug("Error closing DatagramChannel: {0}", e);
                }
            }
        }

        private void ReceiveAsync()
        {
            var e = Udp.SocketEventArgsPool.Acquire(Self);
            var buffer = Udp.BufferPool.Rent();
            e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
            e.RemoteEndPoint = Socket.LocalEndPoint;
            if (!Socket.ReceiveFromAsync(e))
                Self.Tell(new SocketReceived(e));
        }
    }
}


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactOwner;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RuleErrorConsumer;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationCollection;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetKey;
import com.google.devtools.build.lib.skyframe.SkyFunctionEnvironmentForTesting;
import com.google.devtools.build.lib.skyframe.StarlarkBuiltinsValue;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.devtools.build.skyframe.SkyFunction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;

/** Base class for tests that work with resource artifacts. */
public abstract class ResourceTestBase extends AndroidBuildViewTestCase {
  public static final String RESOURCE_ROOT = "java/android/res";

  private static final ImmutableSet<String> TOOL_FILENAMES =
      ImmutableSet.of(
          "static_aapt_tool",
          "aapt.static",
          "aapt",
          "static_aapt2_tool",
          "aapt2",
          "empty.sh",
          "android_blaze.jar",
          "android.jar",
          "ResourceProcessorBusyBox_deploy.jar");

  private static final ArtifactOwner OWNER =
      () -> {
        try {
          return Label.create("java", "all");
        } catch (LabelSyntaxException e) {
          assertWithMessage(e.getMessage()).fail();
          return null;
        }
      };

  /** A faked {@link RuleErrorConsumer} that validates that only expected errors were reported. */
  public static final class FakeRuleErrorConsumer implements RuleErrorConsumer {
    private String ruleErrorMessage = null;
    private String attributeErrorAttribute = null;
    private String attributeErrorMessage = null;

    private final List<String> ruleWarnings = new ArrayList<>();

    // Use an ArrayListMultimap since it allows duplicates - we'll want to know if a warning is
    // reported twice.
    private final Multimap<String, String> attributeWarnings = ArrayListMultimap.create();

    @Override
    public void ruleWarning(String message) {
      ruleWarnings.add(message);
    }

    @Override
    public void ruleError(String message) {
      ruleErrorMessage = message;
    }

    @Override
    public void attributeWarning(String attrName, String message) {
      attributeWarnings.put(attrName, message);
    }

    @Override
    public void attributeError(String attrName, String message) {
      attributeErrorAttribute = attrName;
      attributeErrorMessage = message;
    }

    @Override
    public boolean hasErrors() {
      return ruleErrorMessage != null || attributeErrorMessage != null;
    }

    public Collection<String> getAndClearRuleWarnings() {
      Collection<String> warnings = ImmutableList.copyOf(ruleWarnings);
      ruleWarnings.clear();
      return warnings;
    }

    public void assertNoRuleWarnings() {
      assertThat(ruleWarnings).isEmpty();
    }

    public Collection<String> getAndClearAttributeWarnings(String attrName) {
      if (!attributeWarnings.containsKey(attrName)) {
        return ImmutableList.of();
      }

      return attributeWarnings.removeAll(attrName);
    }

    public void assertNoAttributeWarnings(String attrName) {
      assertThat(attributeWarnings).doesNotContainKey(attrName);
    }

    /**
     * Called at the end of a test to assert that that test produced a rule error
     *
     * @param expectedMessage a substring of the expected message
     */
    public void assertRuleError(String expectedMessage) {
      // Clear the message before asserting so that if we fail here the error is not masked by the
      // @After call to assertNoUnexpectedErrors.

      String message = ruleErrorMessage;
      ruleErrorMessage = null;

      assertThat(message).contains(expectedMessage);
    }

    /**
     * Called at the end of a test to assert that that test produced an attribute error
     *
     * @param expectedAttribute the attribute that caused the error
     * @param expectedMessage a substring of the expected message
     */
    public void assertAttributeError(String expectedAttribute, String expectedMessage) {
      // Clear the message before asserting so that if we fail here the error is not masked by the
      // @After call to assertNoUnexpectedErrors.
      String attr = attributeErrorAttribute;
      String message = attributeErrorMessage;
      attributeErrorAttribute = null;
      attributeErrorMessage = null;

      assertThat(message).contains(expectedMessage);
      assertThat(attr).isEqualTo(expectedAttribute);
    }

    /**
     * Asserts this {@link RuleErrorConsumer} encountered no unexpected errors. To consume an
     * expected error, call {@link #assertRuleError(String)} or {@link #assertAttributeError(String,
     * String)} in your test after the error is produced.
     */
    private void assertNoUnexpectedErrors() {
      assertThat(ruleErrorMessage).isNull();
      assertThat(attributeErrorMessage).isNull();
      assertThat(attributeErrorAttribute).isNull();
    }
  }

  public FakeRuleErrorConsumer errorConsumer;
  public ArtifactRoot artifactRoot;

  @Before
  public void setup() throws Exception {
    errorConsumer = new FakeRuleErrorConsumer();
    fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
    artifactRoot = ArtifactRoot.asSourceRoot(Root.fromPath(fileSystem.getPath("/")));
  }

  @After
  public void assertNoErrors() {
    errorConsumer.assertNoUnexpectedErrors();
  }

  public ImmutableList<Artifact> getResources(String... pathStrings) {
    ImmutableList.Builder<Artifact> builder = ImmutableList.builder();
    for (String pathString : pathStrings) {
      builder.add(getResource(pathString));
    }

    return builder.build();
  }

  Artifact getResource(String pathString) {
    return getArtifact(RESOURCE_ROOT, pathString);
  }

  private Artifact getArtifact(String subdir, String pathString) {
    Path path = fileSystem.getPath("/" + subdir + "/" + pathString);
    return new Artifact.SourceArtifact(
        artifactRoot,
        artifactRoot.getExecPath().getRelative(artifactRoot.getRoot().relativize(path)),
        OWNER);
  }

  /**
   * Gets a RuleContext that can be used to register actions and test that they are created
   * correctly.
   *
   * <p>Takes in a dummy target which will be used to configure the RuleContext's {@link
   * AndroidConfiguration}.
   */
  public RuleContext getRuleContextForActionTesting(ConfiguredTarget dummyTarget) throws Exception {
    RuleContext dummy = getRuleContext(dummyTarget);
    ExtendedEventHandler eventHandler = new StoredEventHandler();

    SkyFunction.Environment skyframeEnv =
        new SkyFunctionEnvironmentForTesting(eventHandler, skyframeExecutor);
    StarlarkBuiltinsValue starlarkBuiltinsValue =
        (StarlarkBuiltinsValue)
            Preconditions.checkNotNull(skyframeEnv.getValue(StarlarkBuiltinsValue.key()));
    CachingAnalysisEnvironment analysisEnv =
        new CachingAnalysisEnvironment(
            view.getArtifactFactory(),
            skyframeExecutor.getActionKeyContext(),
            ConfiguredTargetKey.builder()
                .setLabel(dummyTarget.getLabel())
                .setConfiguration(targetConfig)
                .build(),
            targetConfig.extendedSanityChecks(),
            targetConfig.allowAnalysisFailures(),
            eventHandler,
            skyframeEnv,
            starlarkBuiltinsValue);

    return view.getRuleContextForTesting(
        eventHandler,
        dummyTarget,
        analysisEnv,
        new BuildConfigurationCollection(dummy.getConfiguration(), dummy.getHostConfiguration()));
  }

  /**
   * Assets that the action used to generate the given outputs has the expected inputs and outputs.
   */
  static void assertActionArtifacts(
      RuleContext ruleContext, ImmutableList<Artifact> inputs, ImmutableList<Artifact> outputs) {
    // Actions must have at least one output
    assertThat(outputs).isNotEmpty();

    // Get the action from one of the outputs
    ActionAnalysisMetadata action =
        ruleContext.getAnalysisEnvironment().getLocalGeneratingAction(outputs.get(0));
    assertThat(action).isNotNull();

    assertThat(removeToolingArtifacts(action.getInputs())).containsExactlyElementsIn(inputs);

    assertThat(action.getOutputs()).containsExactlyElementsIn(outputs);
  }

  /** Remove busybox and aapt2 tooling artifacts from a list of action inputs */
  private static Iterable<Artifact> removeToolingArtifacts(NestedSet<Artifact> inputArtifacts) {
    return inputArtifacts.toList().stream()
        .filter(
            artifact ->
                // Not a known tool
                !TOOL_FILENAMES.contains(artifact.getFilename())
                    // Not one of the various busybox tools (we get different ones on different OSs)
                    && !artifact.getFilename().contains("busybox")
                    // Not a params file
                    && !artifact.getFilename().endsWith(".params"))
        .collect(Collectors.toList());
  }
}


text:
using namespace gl;

namespace rx
{
namespace
{
bool AttributeNeedsStreaming(const VertexAttribute &attribute)
{
    return (attribute.enabled && attribute.buffer.get() == nullptr);
}

}  // anonymous namespace

VertexArrayGL::VertexArrayGL(const VertexArray::Data &data,
                             const FunctionsGL *functions,
                             StateManagerGL *stateManager)
    : VertexArrayImpl(data),
      mFunctions(functions),
      mStateManager(stateManager),
      mVertexArrayID(0),
      mAppliedElementArrayBuffer(),
      mStreamingElementArrayBufferSize(0),
      mStreamingElementArrayBuffer(0),
      mStreamingArrayBufferSize(0),
      mStreamingArrayBuffer(0)
{
    ASSERT(mFunctions);
    ASSERT(mStateManager);
    mFunctions->genVertexArrays(1, &mVertexArrayID);

    // Set the cached vertex attribute array size
    GLint maxVertexAttribs;
    mFunctions->getIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxVertexAttribs);
    mAppliedAttributes.resize(maxVertexAttribs);
}

VertexArrayGL::~VertexArrayGL()
{
    mStateManager->deleteVertexArray(mVertexArrayID);
    mVertexArrayID = 0;

    mStateManager->deleteBuffer(mStreamingElementArrayBuffer);
    mStreamingElementArrayBufferSize = 0;
    mStreamingElementArrayBuffer = 0;

    mStateManager->deleteBuffer(mStreamingArrayBuffer);
    mStreamingArrayBufferSize = 0;
    mStreamingArrayBuffer = 0;

    mAppliedElementArrayBuffer.set(nullptr);
    for (size_t idx = 0; idx < mAppliedAttributes.size(); idx++)
    {
        mAppliedAttributes[idx].buffer.set(nullptr);
    }
}

gl::Error VertexArrayGL::syncDrawArraysState(const gl::AttributesMask &activeAttributesMask,
                                             GLint first,
                                             GLsizei count,
                                             GLsizei instanceCount) const
{
    return syncDrawState(activeAttributesMask, first, count, GL_NONE, nullptr, instanceCount,
                         nullptr);
}

gl::Error VertexArrayGL::syncDrawElementsState(const gl::AttributesMask &activeAttributesMask,
                                               GLsizei count,
                                               GLenum type,
                                               const GLvoid *indices,
                                               GLsizei instanceCount,
                                               const GLvoid **outIndices) const
{
    return syncDrawState(activeAttributesMask, 0, count, type, indices, instanceCount, outIndices);
}

gl::Error VertexArrayGL::syncDrawState(const gl::AttributesMask &activeAttributesMask,
                                       GLint first,
                                       GLsizei count,
                                       GLenum type,
                                       const GLvoid *indices,
                                       GLsizei instanceCount,
                                       const GLvoid **outIndices) const
{
    mStateManager->bindVertexArray(mVertexArrayID, getAppliedElementArrayBufferID());

    // Check if any attributes need to be streamed, determines if the index range needs to be computed
    bool attributesNeedStreaming = mAttributesNeedStreaming.any();

    // Determine if an index buffer needs to be streamed and the range of vertices that need to be copied
    RangeUI indexRange(0, 0);
    if (type != GL_NONE)
    {
        Error error =
            syncIndexData(count, type, indices, attributesNeedStreaming, &indexRange, outIndices);
        if (error.isError())
        {
            return error;
        }
    }
    else
    {
        // Not an indexed call, set the range to [first, first + count - 1]
        indexRange.start = first;
        indexRange.end = first + count - 1;
    }

    if (attributesNeedStreaming)
    {
        Error error = streamAttributes(activeAttributesMask, instanceCount, indexRange);
        if (error.isError())
        {
            return error;
        }
    }

    return Error(GL_NO_ERROR);
}

Error VertexArrayGL::syncIndexData(GLsizei count,
                                   GLenum type,
                                   const GLvoid *indices,
                                   bool attributesNeedStreaming,
                                   RangeUI *outIndexRange,
                                   const GLvoid **outIndices) const
{
    ASSERT(outIndices);

    gl::Buffer *elementArrayBuffer = mData.getElementArrayBuffer().get();

    // Need to check the range of indices if attributes need to be streamed
    if (elementArrayBuffer != nullptr)
    {
        if (elementArrayBuffer != mAppliedElementArrayBuffer.get())
        {
            const BufferGL *bufferGL = GetImplAs<BufferGL>(elementArrayBuffer);
            mStateManager->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferGL->getBufferID());
            mAppliedElementArrayBuffer.set(elementArrayBuffer);
        }

        // Only compute the index range if the attributes also need to be streamed
        if (attributesNeedStreaming)
        {
            ptrdiff_t elementArrayBufferOffset = reinterpret_cast<ptrdiff_t>(indices);
            Error error = mData.getElementArrayBuffer()->getIndexRange(
                type, static_cast<size_t>(elementArrayBufferOffset), count, outIndexRange);
            if (error.isError())
            {
                return error;
            }
        }

        // Indices serves as an offset into the index buffer in this case, use the same value for the draw call
        *outIndices = indices;
    }
    else
    {
        // Need to stream the index buffer
        // TODO: if GLES, nothing needs to be streamed

        // Only compute the index range if the attributes also need to be streamed
        if (attributesNeedStreaming)
        {
            *outIndexRange = ComputeIndexRange(type, indices, count);
        }

        // Allocate the streaming element array buffer
        if (mStreamingElementArrayBuffer == 0)
        {
            mFunctions->genBuffers(1, &mStreamingElementArrayBuffer);
            mStreamingElementArrayBufferSize = 0;
        }

        mStateManager->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, mStreamingElementArrayBuffer);
        mAppliedElementArrayBuffer.set(nullptr);

        // Make sure the element array buffer is large enough
        const Type &indexTypeInfo          = GetTypeInfo(type);
        size_t requiredStreamingBufferSize = indexTypeInfo.bytes * count;
        if (requiredStreamingBufferSize > mStreamingElementArrayBufferSize)
        {
            // Copy the indices in while resizing the buffer
            mFunctions->bufferData(GL_ELEMENT_ARRAY_BUFFER, requiredStreamingBufferSize, indices, GL_DYNAMIC_DRAW);
            mStreamingElementArrayBufferSize = requiredStreamingBufferSize;
        }
        else
        {
            // Put the indices at the beginning of the buffer
            mFunctions->bufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, requiredStreamingBufferSize, indices);
        }

        // Set the index offset for the draw call to zero since the supplied index pointer is to client data
        *outIndices = nullptr;
    }

    return Error(GL_NO_ERROR);
}

void VertexArrayGL::computeStreamingAttributeSizes(const gl::AttributesMask &activeAttributesMask,
                                                   GLsizei instanceCount,
                                                   const gl::RangeUI &indexRange,
                                                   size_t *outStreamingDataSize,
                                                   size_t *outMaxAttributeDataSize) const
{
    *outStreamingDataSize    = 0;
    *outMaxAttributeDataSize = 0;

    ASSERT(mAttributesNeedStreaming.any());

    const auto &attribs = mData.getVertexAttributes();
    for (unsigned int idx : angle::IterateBitSet(mAttributesNeedStreaming & activeAttributesMask))
    {
        const auto &attrib = attribs[idx];
        ASSERT(AttributeNeedsStreaming(attrib));

        const size_t vertexCount = indexRange.end - indexRange.start + 1;

        // If streaming is going to be required, compute the size of the required buffer
        // and how much slack space at the beginning of the buffer will be required by determining
        // the attribute with the largest data size.
        size_t typeSize = ComputeVertexAttributeTypeSize(attrib);
        *outStreamingDataSize +=
            typeSize * ComputeVertexAttributeElementCount(attrib, vertexCount, instanceCount);
        *outMaxAttributeDataSize = std::max(*outMaxAttributeDataSize, typeSize);
    }
}

gl::Error VertexArrayGL::streamAttributes(const gl::AttributesMask &activeAttributesMask,
                                          GLsizei instanceCount,
                                          const gl::RangeUI &indexRange) const
{
    // Sync the vertex attribute state and track what data needs to be streamed
    size_t streamingDataSize    = 0;
    size_t maxAttributeDataSize = 0;

    computeStreamingAttributeSizes(activeAttributesMask, instanceCount, indexRange,
                                   &streamingDataSize, &maxAttributeDataSize);

    if (streamingDataSize == 0)
    {
        return gl::Error(GL_NO_ERROR);
    }

    if (mStreamingArrayBuffer == 0)
    {
        mFunctions->genBuffers(1, &mStreamingArrayBuffer);
        mStreamingArrayBufferSize = 0;
    }

    // If first is greater than zero, a slack space needs to be left at the beginning of the buffer so that
    // the same 'first' argument can be passed into the draw call.
    const size_t bufferEmptySpace = maxAttributeDataSize * indexRange.start;
    const size_t requiredBufferSize = streamingDataSize + bufferEmptySpace;

    mStateManager->bindBuffer(GL_ARRAY_BUFFER, mStreamingArrayBuffer);
    if (requiredBufferSize > mStreamingArrayBufferSize)
    {
        mFunctions->bufferData(GL_ARRAY_BUFFER, requiredBufferSize, nullptr, GL_DYNAMIC_DRAW);
        mStreamingArrayBufferSize = requiredBufferSize;
    }

    // Unmapping a buffer can return GL_FALSE to indicate that the system has corrupted the data
    // somehow (such as by a screen change), retry writing the data a few times and return OUT_OF_MEMORY
    // if that fails.
    GLboolean unmapResult = GL_FALSE;
    size_t unmapRetryAttempts = 5;
    while (unmapResult != GL_TRUE && --unmapRetryAttempts > 0)
    {
        uint8_t *bufferPointer = reinterpret_cast<uint8_t*>(mFunctions->mapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY));
        size_t curBufferOffset = bufferEmptySpace;

        const size_t vertexCount = indexRange.end - indexRange.start + 1;

        const auto &attribs = mData.getVertexAttributes();
        for (unsigned int idx :
             angle::IterateBitSet(mAttributesNeedStreaming & activeAttributesMask))
        {
            const auto &attrib = attribs[idx];
            ASSERT(AttributeNeedsStreaming(attrib));

            const size_t streamedVertexCount =
                ComputeVertexAttributeElementCount(attrib, vertexCount, instanceCount);

            const size_t sourceStride = ComputeVertexAttributeStride(attrib);
            const size_t destStride   = ComputeVertexAttributeTypeSize(attrib);

            const uint8_t *inputPointer = reinterpret_cast<const uint8_t *>(attrib.pointer);

            // Pack the data when copying it, user could have supplied a very large stride that
            // would cause the buffer to be much larger than needed.
            if (destStride == sourceStride)
            {
                // Can copy in one go, the data is packed
                memcpy(bufferPointer + curBufferOffset,
                       inputPointer + (sourceStride * indexRange.start),
                       destStride * streamedVertexCount);
            }
            else
            {
                // Copy each vertex individually
                for (size_t vertexIdx = 0; vertexIdx < streamedVertexCount; vertexIdx++)
                {
                    uint8_t *out = bufferPointer + curBufferOffset + (destStride * vertexIdx);
                    const uint8_t *in =
                        inputPointer + sourceStride * (vertexIdx + indexRange.start);
                    memcpy(out, in, destStride);
                }
            }

            // Compute where the 0-index vertex would be.
            const size_t vertexStartOffset = curBufferOffset - (indexRange.start * destStride);

            if (attrib.pureInteger)
            {
                ASSERT(!attrib.normalized);
                mFunctions->vertexAttribIPointer(
                    idx, attrib.size, attrib.type, static_cast<GLsizei>(destStride),
                    reinterpret_cast<const GLvoid *>(vertexStartOffset));
            }
            else
            {
                mFunctions->vertexAttribPointer(
                    idx, attrib.size, attrib.type, attrib.normalized,
                    static_cast<GLsizei>(destStride),
                    reinterpret_cast<const GLvoid *>(vertexStartOffset));
            }

            curBufferOffset += destStride * streamedVertexCount;

            // Mark the applied attribute as dirty by setting an invalid size so that if it doesn't
            // need to be streamed later, there is no chance that the caching will skip it.
            mAppliedAttributes[idx].size = static_cast<GLuint>(-1);
        }

        unmapResult = mFunctions->unmapBuffer(GL_ARRAY_BUFFER);
    }

    if (unmapResult != GL_TRUE)
    {
        return Error(GL_OUT_OF_MEMORY, "Failed to unmap the client data streaming buffer.");
    }

    return Error(GL_NO_ERROR);
}

GLuint VertexArrayGL::getVertexArrayID() const
{
    return mVertexArrayID;
}

GLuint VertexArrayGL::getAppliedElementArrayBufferID() const
{
    if (mAppliedElementArrayBuffer.get() == nullptr)
    {
        return mStreamingElementArrayBuffer;
    }

    return GetImplAs<BufferGL>(mAppliedElementArrayBuffer.get())->getBufferID();
}

void VertexArrayGL::updateNeedsStreaming(size_t attribIndex)
{
    const VertexAttribute &attrib = mData.getVertexAttribute(attribIndex);
    mAttributesNeedStreaming.set(attribIndex, AttributeNeedsStreaming(attrib));
}

void VertexArrayGL::updateAttribEnabled(size_t attribIndex)
{
    const VertexAttribute &attrib = mData.getVertexAttribute(attribIndex);
    if (mAppliedAttributes[attribIndex].enabled == attrib.enabled)
    {
        return;
    }

    updateNeedsStreaming(attribIndex);

    mStateManager->bindVertexArray(mVertexArrayID, getAppliedElementArrayBufferID());
    if (attrib.enabled)
    {
        mFunctions->enableVertexAttribArray(static_cast<GLuint>(attribIndex));
    }
    else
    {
        mFunctions->disableVertexAttribArray(static_cast<GLuint>(attribIndex));
    }
    mAppliedAttributes[attribIndex].enabled = attrib.enabled;
}

void VertexArrayGL::updateAttribPointer(size_t attribIndex)
{
    const VertexAttribute &attrib = mData.getVertexAttribute(attribIndex);
    if (mAppliedAttributes[attribIndex] == attrib)
    {
        return;
    }

    updateNeedsStreaming(attribIndex);

    // If we need to stream, defer the attribPointer to the draw call.
    if (mAttributesNeedStreaming[attribIndex])
    {
        return;
    }

    mStateManager->bindVertexArray(mVertexArrayID, getAppliedElementArrayBufferID());
    const Buffer *arrayBuffer = attrib.buffer.get();
    if (arrayBuffer != nullptr)
    {
        const BufferGL *arrayBufferGL = GetImplAs<BufferGL>(arrayBuffer);
        mStateManager->bindBuffer(GL_ARRAY_BUFFER, arrayBufferGL->getBufferID());
    }
    else
    {
        mStateManager->bindBuffer(GL_ARRAY_BUFFER, 0);
    }
    mAppliedAttributes[attribIndex].buffer = attrib.buffer;

    if (attrib.pureInteger)
    {
        mFunctions->vertexAttribIPointer(static_cast<GLuint>(attribIndex), attrib.size, attrib.type,
                                         attrib.stride, attrib.pointer);
    }
    else
    {
        mFunctions->vertexAttribPointer(static_cast<GLuint>(attribIndex), attrib.size, attrib.type,
                                        attrib.normalized, attrib.stride, attrib.pointer);
    }
    mAppliedAttributes[attribIndex].size        = attrib.size;
    mAppliedAttributes[attribIndex].type        = attrib.type;
    mAppliedAttributes[attribIndex].normalized  = attrib.normalized;
    mAppliedAttributes[attribIndex].pureInteger = attrib.pureInteger;
    mAppliedAttributes[attribIndex].stride      = attrib.stride;
    mAppliedAttributes[attribIndex].pointer     = attrib.pointer;
}

void VertexArrayGL::syncState(const VertexArray::DirtyBits &dirtyBits)
{
    for (unsigned long dirtyBit : angle::IterateBitSet(dirtyBits))
    {
        if (dirtyBit == VertexArray::DIRTY_BIT_ELEMENT_ARRAY_BUFFER)
        {
            // TODO(jmadill): Element array buffer bindings
        }
        else if (dirtyBit >= VertexArray::DIRTY_BIT_ATTRIB_0_ENABLED &&
                 dirtyBit < VertexArray::DIRTY_BIT_ATTRIB_MAX_ENABLED)
        {
            size_t attribIndex =
                static_cast<size_t>(dirtyBit) - VertexArray::DIRTY_BIT_ATTRIB_0_ENABLED;
            updateAttribEnabled(attribIndex);
        }
        else if (dirtyBit >= VertexArray::DIRTY_BIT_ATTRIB_0_POINTER &&
                 dirtyBit < VertexArray::DIRTY_BIT_ATTRIB_MAX_POINTER)
        {
            size_t attribIndex =
                static_cast<size_t>(dirtyBit) - VertexArray::DIRTY_BIT_ATTRIB_0_POINTER;
            updateAttribPointer(attribIndex);
        }
        else if (dirtyBit >= VertexArray::DIRTY_BIT_ATTRIB_0_DIVISOR &&
                 dirtyBit < VertexArray::DIRTY_BIT_ATTRIB_MAX_DIVISOR)
        {
            size_t attribIndex =
                static_cast<size_t>(dirtyBit) - VertexArray::DIRTY_BIT_ATTRIB_0_DIVISOR;
            const VertexAttribute &attrib = mData.getVertexAttribute(attribIndex);

            if (mAppliedAttributes[attribIndex].divisor != attrib.divisor)
            {
                mStateManager->bindVertexArray(mVertexArrayID, getAppliedElementArrayBufferID());
                mFunctions->vertexAttribDivisor(static_cast<GLuint>(attribIndex), attrib.divisor);
                mAppliedAttributes[attribIndex].divisor = attrib.divisor;
            }
        }
        else
            UNREACHABLE();
    }
}

}  // rx


text:
import {Component, OnInit} from '@angular/core';
import {NavParams, ViewController} from 'ionic-angular';
import {Recipe, RecipeProvider} from "../../providers/recipe/recipe";
import {RawMaterial, RawMaterialProvider} from "../../providers/raw-material/raw-material";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/do'
import {AngularFireDatabase} from "angularfire2/database";
import {Subscription} from "rxjs/Subscription";

/**
 * Generated class for the EditProductionPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@Component({
  selector: 'page-edit-production',
  templateUrl: 'edit-production.html',
})
export class EditProductionPage implements OnInit{
  dateKey: string;
  recipes: Observable<Recipe[]>;
  loadingRecipes: boolean;
  recipesProduced: {[key: string]: number}[];

  composedMaterials: Observable<RawMaterial[]>;
  loadingComposedMaterials: boolean;
  composedMaterialsProduced: {[key: string]: number}[];

  private sub: Subscription;

  constructor(public navParams: NavParams,
              public viewCtrl: ViewController,
              private recipeProvider: RecipeProvider,
              private rawMaterialProvider: RawMaterialProvider,
              private db: AngularFireDatabase) {
  }

  ngOnInit() {
    this.dateKey = this.navParams.get("dateKey");

    this.recipesProduced = [];
    this.composedMaterialsProduced = [];

    this.loadingRecipes = true;
    this.loadingComposedMaterials = true;

    this.recipes = this.recipeProvider.getRecipes().do(
      () => this.loadingRecipes = false,
      () => this.loadingRecipes = false
    );
    this.composedMaterials = this.rawMaterialProvider.getRawMaterials(null, true).do(
      () => this.loadingComposedMaterials = false,
      () => this.loadingComposedMaterials = false
    );

    this.sub = this.db.object("/journal/" + this.dateKey + "/production").subscribe(data => {
      if (data.recipes) {
        this.recipesProduced = data.recipes;
      }
      if (data.stock) {
        this.composedMaterialsProduced = data.stock;
      }
    });
  }

  ionViewDidLeave() {
    this.sub.unsubscribe();
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }

  searchProduction(event) {
    this.recipes = this.recipeProvider.getRecipes();
    this.composedMaterials = this.rawMaterialProvider.getRawMaterials(null, true);

    let searchName: string = event.target.value;
    if (searchName && searchName.trim() !== '') {
      this.recipes = this.recipeProvider.getRecipes(searchName);
      this.composedMaterials = this.rawMaterialProvider.getRawMaterials(searchName, true);
    }
  }

  saveProduction() {
    for (const key in this.recipesProduced) {
      if (this.recipesProduced[key].valueOf() === "") {
        delete this.recipesProduced[key];
      }
    }
    for (const key in this.composedMaterialsProduced) {
      if (this.composedMaterialsProduced[key].valueOf() === "") {
        delete this.composedMaterialsProduced[key];
      }
    }
    this.db.database.ref("/journal/" + this.dateKey + "/production/recipes").set(this.recipesProduced);
    this.db.database.ref("/journal/" + this.dateKey + "/production/stock").set(this.composedMaterialsProduced);
    //this.productionDb.set("recipes", this.recipesProduced); // TODO - replace when rc2 of angularfire2
    //this.productionDb.set("composed_materials", this.composedMaterialsProduced);
    this.dismiss();
  }

}


text:
from setuptools import setup, find_packages

setup(
    name = "hellobuildout",
    version = "1.0",
    url = 'https://github.com/soxofaan/hellobuildout',
    license = 'MIT',
    description = "Mimimal toy project to get the hang of Buildout.",
    author = 'Stefaan Lippens',
    # Search in the root folder for source file packages
    packages = find_packages('.'),
    # Define some console scripts, triggering functionality from the hellobuildout package.
    entry_points={
        'console_scripts': [
            'hellobuildout = hellobuildout:hello_buildout',
            'helloworld = hellobuildout:hello_world',
        ],
    },
)


text:
package uk.co.transputersystems.occam.metadata;

public class Variable extends NamedOperand<Object> {
    private int index;

    public Variable(String name, int index, String typeName) {
        super(name, typeName);

        this.index = index;
    }

    public int getIndex() {
        return index;
    }

    @Override
    public void verify(VerificationContext ctx) {
        super.verify(ctx);

        assert (index > -1);
    }
}


text:
* void pause(void)

## Description
Pauses playing the clip.