text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/errno.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/miscdevice.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nftl.h>
#include <linux/mtd/inftl.h>
#include <linux/mtd/compatmac.h>

char inftlmountrev[]="$Revision: 1.18 $";

extern int inftl_read_oob(struct mtd_info *mtd, loff_t offs, size_t len,
			  size_t *retlen, uint8_t *buf);
extern int inftl_write_oob(struct mtd_info *mtd, loff_t offs, size_t len,
			   size_t *retlen, uint8_t *buf);

/*
 * find_boot_record: Find the INFTL Media Header and its Spare copy which
 *	contains the various device information of the INFTL partition and
 *	Bad Unit Table. Update the PUtable[] table according to the Bad
 *	Unit Table. PUtable[] is used for management of Erase Unit in
 *	other routines in inftlcore.c and inftlmount.c.
 */
static int find_boot_record(struct INFTLrecord *inftl)
{
	struct inftl_unittail h1;
	//struct inftl_oob oob;
	unsigned int i, block;
	u8 buf[SECTORSIZE];
	struct INFTLMediaHeader *mh = &inftl->MediaHdr;
	struct mtd_info *mtd = inftl->mbd.mtd;
	struct INFTLPartition *ip;
	size_t retlen;

	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: find_boot_record(inftl=%p)\n", inftl);

        /*
	 * Assume logical EraseSize == physical erasesize for starting the
	 * scan. We'll sort it out later if we find a MediaHeader which says
	 * otherwise.
	 */
	inftl->EraseSize = inftl->mbd.mtd->erasesize;
        inftl->nb_blocks = inftl->mbd.mtd->size / inftl->EraseSize;

	inftl->MediaUnit = BLOCK_NIL;

	/* Search for a valid boot record */
	for (block = 0; block < inftl->nb_blocks; block++) {
		int ret;

		/*
		 * Check for BNAND header first. Then whinge if it's found
		 * but later checks fail.
		 */
		ret = mtd->read(mtd, block * inftl->EraseSize,
				SECTORSIZE, &retlen, buf);
		/* We ignore ret in case the ECC of the MediaHeader is invalid
		   (which is apparently acceptable) */
		if (retlen != SECTORSIZE) {
			static int warncount = 5;

			if (warncount) {
				printk(KERN_WARNING "INFTL: block read at 0x%x "
					"of mtd%d failed: %d\n",
					block * inftl->EraseSize,
					inftl->mbd.mtd->index, ret);
				if (!--warncount)
					printk(KERN_WARNING "INFTL: further "
						"failures for this block will "
						"not be printed\n");
			}
			continue;
		}

		if (retlen < 6 || memcmp(buf, "BNAND", 6)) {
			/* BNAND\0 not found. Continue */
			continue;
		}

		/* To be safer with BIOS, also use erase mark as discriminant */
		if ((ret = inftl_read_oob(mtd, block * inftl->EraseSize +
					  SECTORSIZE + 8, 8, &retlen,
					  (char *)&h1) < 0)) {
			printk(KERN_WARNING "INFTL: ANAND header found at "
				"0x%x in mtd%d, but OOB data read failed "
				"(err %d)\n", block * inftl->EraseSize,
				inftl->mbd.mtd->index, ret);
			continue;
		}

		/*
		 * This is the first we've seen.
		 * Copy the media header structure into place.
		 */
		memcpy(mh, buf, sizeof(struct INFTLMediaHeader));

		/* Read the spare media header at offset 4096 */
		mtd->read(mtd, block * inftl->EraseSize + 4096,
			  SECTORSIZE, &retlen, buf);
		if (retlen != SECTORSIZE) {
			printk(KERN_WARNING "INFTL: Unable to read spare "
			       "Media Header\n");
			return -1;
		}
		/* Check if this one is the same as the first one we found. */
		if (memcmp(mh, buf, sizeof(struct INFTLMediaHeader))) {
			printk(KERN_WARNING "INFTL: Primary and spare Media "
			       "Headers disagree.\n");
			return -1;
		}

		mh->NoOfBootImageBlocks = le32_to_cpu(mh->NoOfBootImageBlocks);
		mh->NoOfBinaryPartitions = le32_to_cpu(mh->NoOfBinaryPartitions);
		mh->NoOfBDTLPartitions = le32_to_cpu(mh->NoOfBDTLPartitions);
		mh->BlockMultiplierBits = le32_to_cpu(mh->BlockMultiplierBits);
		mh->FormatFlags = le32_to_cpu(mh->FormatFlags);
		mh->PercentUsed = le32_to_cpu(mh->PercentUsed);

#ifdef CONFIG_MTD_DEBUG_VERBOSE
		if (CONFIG_MTD_DEBUG_VERBOSE >= 2) {
			printk("INFTL: Media Header ->\n"
				"    bootRecordID          = %s\n"
				"    NoOfBootImageBlocks   = %d\n"
				"    NoOfBinaryPartitions  = %d\n"
				"    NoOfBDTLPartitions    = %d\n"
				"    BlockMultiplerBits    = %d\n"
				"    FormatFlgs            = %d\n"
				"    OsakVersion           = 0x%x\n"
				"    PercentUsed           = %d\n",
				mh->bootRecordID, mh->NoOfBootImageBlocks,
				mh->NoOfBinaryPartitions,
				mh->NoOfBDTLPartitions,
				mh->BlockMultiplierBits, mh->FormatFlags,
				mh->OsakVersion, mh->PercentUsed);
		}
#endif

		if (mh->NoOfBDTLPartitions == 0) {
			printk(KERN_WARNING "INFTL: Media Header sanity check "
				"failed: NoOfBDTLPartitions (%d) == 0, "
				"must be at least 1\n", mh->NoOfBDTLPartitions);
			return -1;
		}

		if ((mh->NoOfBDTLPartitions + mh->NoOfBinaryPartitions) > 4) {
			printk(KERN_WARNING "INFTL: Media Header sanity check "
				"failed: Total Partitions (%d) > 4, "
				"BDTL=%d Binary=%d\n", mh->NoOfBDTLPartitions +
				mh->NoOfBinaryPartitions,
				mh->NoOfBDTLPartitions,
				mh->NoOfBinaryPartitions);
			return -1;
		}

		if (mh->BlockMultiplierBits > 1) {
			printk(KERN_WARNING "INFTL: sorry, we don't support "
				"UnitSizeFactor 0x%02x\n",
				mh->BlockMultiplierBits);
			return -1;
		} else if (mh->BlockMultiplierBits == 1) {
			printk(KERN_WARNING "INFTL: support for INFTL with "
				"UnitSizeFactor 0x%02x is experimental\n",
				mh->BlockMultiplierBits);
			inftl->EraseSize = inftl->mbd.mtd->erasesize <<
				mh->BlockMultiplierBits;
			inftl->nb_blocks = inftl->mbd.mtd->size / inftl->EraseSize;
			block >>= mh->BlockMultiplierBits;
		}

		/* Scan the partitions */
		for (i = 0; (i < 4); i++) {
			ip = &mh->Partitions[i];
			ip->virtualUnits = le32_to_cpu(ip->virtualUnits);
			ip->firstUnit = le32_to_cpu(ip->firstUnit);
			ip->lastUnit = le32_to_cpu(ip->lastUnit);
			ip->flags = le32_to_cpu(ip->flags);
			ip->spareUnits = le32_to_cpu(ip->spareUnits);
			ip->Reserved0 = le32_to_cpu(ip->Reserved0);

#ifdef CONFIG_MTD_DEBUG_VERBOSE
			if (CONFIG_MTD_DEBUG_VERBOSE >= 2) {
				printk("    PARTITION[%d] ->\n"
					"        virtualUnits    = %d\n"
					"        firstUnit       = %d\n"
					"        lastUnit        = %d\n"
					"        flags           = 0x%x\n"
					"        spareUnits      = %d\n",
					i, ip->virtualUnits, ip->firstUnit,
					ip->lastUnit, ip->flags,
					ip->spareUnits);
			}
#endif

			if (ip->Reserved0 != ip->firstUnit) {
				struct erase_info *instr = &inftl->instr;

				instr->mtd = inftl->mbd.mtd;

				/*
				 * 	Most likely this is using the
				 * 	undocumented qiuck mount feature.
				 * 	We don't support that, we will need
				 * 	to erase the hidden block for full
				 * 	compatibility.
				 */
				instr->addr = ip->Reserved0 * inftl->EraseSize;
				instr->len = inftl->EraseSize;
				mtd->erase(mtd, instr);
			}
			if ((ip->lastUnit - ip->firstUnit + 1) < ip->virtualUnits) {
				printk(KERN_WARNING "INFTL: Media Header "
					"Partition %d sanity check failed\n"
					"    firstUnit %d : lastUnit %d  >  "
					"virtualUnits %d\n", i, ip->lastUnit,
					ip->firstUnit, ip->Reserved0);
				return -1;
			}
			if (ip->Reserved1 != 0) {
				printk(KERN_WARNING "INFTL: Media Header "
					"Partition %d sanity check failed: "
					"Reserved1 %d != 0\n",
					i, ip->Reserved1);
				return -1;
			}

			if (ip->flags & INFTL_BDTL)
				break;
		}

		if (i >= 4) {
			printk(KERN_WARNING "INFTL: Media Header Partition "
				"sanity check failed:\n       No partition "
				"marked as Disk Partition\n");
			return -1;
		}

		inftl->nb_boot_blocks = ip->firstUnit;
		inftl->numvunits = ip->virtualUnits;
		if (inftl->numvunits > (inftl->nb_blocks -
		    inftl->nb_boot_blocks - 2)) {
			printk(KERN_WARNING "INFTL: Media Header sanity check "
				"failed:\n        numvunits (%d) > nb_blocks "
				"(%d) - nb_boot_blocks(%d) - 2\n",
				inftl->numvunits, inftl->nb_blocks,
				inftl->nb_boot_blocks);
			return -1;
		}

		inftl->mbd.size  = inftl->numvunits *
			(inftl->EraseSize / SECTORSIZE);

		/*
		 * Block count is set to last used EUN (we won't need to keep
		 * any meta-data past that point).
		 */
		inftl->firstEUN = ip->firstUnit;
		inftl->lastEUN = ip->lastUnit;
		inftl->nb_blocks = ip->lastUnit + 1;

		/* Memory alloc */
		inftl->PUtable = kmalloc(inftl->nb_blocks * sizeof(u16), GFP_KERNEL);
		if (!inftl->PUtable) {
			printk(KERN_WARNING "INFTL: allocation of PUtable "
				"failed (%zd bytes)\n",
				inftl->nb_blocks * sizeof(u16));
			return -ENOMEM;
		}

		inftl->VUtable = kmalloc(inftl->nb_blocks * sizeof(u16), GFP_KERNEL);
		if (!inftl->VUtable) {
			kfree(inftl->PUtable);
			printk(KERN_WARNING "INFTL: allocation of VUtable "
				"failed (%zd bytes)\n",
				inftl->nb_blocks * sizeof(u16));
			return -ENOMEM;
		}

		/* Mark the blocks before INFTL MediaHeader as reserved */
		for (i = 0; i < inftl->nb_boot_blocks; i++)
			inftl->PUtable[i] = BLOCK_RESERVED;
		/* Mark all remaining blocks as potentially containing data */
		for (; i < inftl->nb_blocks; i++)
			inftl->PUtable[i] = BLOCK_NOTEXPLORED;

		/* Mark this boot record (NFTL MediaHeader) block as reserved */
		inftl->PUtable[block] = BLOCK_RESERVED;

		/* Read Bad Erase Unit Table and modify PUtable[] accordingly */
		for (i = 0; i < inftl->nb_blocks; i++) {
			int physblock;
			/* If any of the physical eraseblocks are bad, don't
			   use the unit. */
			for (physblock = 0; physblock < inftl->EraseSize; physblock += inftl->mbd.mtd->erasesize) {
				if (inftl->mbd.mtd->block_isbad(inftl->mbd.mtd, i * inftl->EraseSize + physblock))
					inftl->PUtable[i] = BLOCK_RESERVED;
			}
		}

		inftl->MediaUnit = block;
		return 0;
	}

	/* Not found. */
	return -1;
}

static int memcmpb(void *a, int c, int n)
{
	int i;
	for (i = 0; i < n; i++) {
		if (c != ((unsigned char *)a)[i])
			return 1;
	}
	return 0;
}

/*
 * check_free_sector: check if a free sector is actually FREE,
 *	i.e. All 0xff in data and oob area.
 */
static int check_free_sectors(struct INFTLrecord *inftl, unsigned int address,
	int len, int check_oob)
{
	u8 buf[SECTORSIZE + inftl->mbd.mtd->oobsize];
	struct mtd_info *mtd = inftl->mbd.mtd;
	size_t retlen;
	int i;

	for (i = 0; i < len; i += SECTORSIZE) {
		if (mtd->read(mtd, address, SECTORSIZE, &retlen, buf))
			return -1;
		if (memcmpb(buf, 0xff, SECTORSIZE) != 0)
			return -1;

		if (check_oob) {
			if(inftl_read_oob(mtd, address, mtd->oobsize,
					  &retlen, &buf[SECTORSIZE]) < 0)
				return -1;
			if (memcmpb(buf + SECTORSIZE, 0xff, mtd->oobsize) != 0)
				return -1;
		}
		address += SECTORSIZE;
	}

	return 0;
}

/*
 * INFTL_format: format a Erase Unit by erasing ALL Erase Zones in the Erase
 *		 Unit and Update INFTL metadata. Each erase operation is
 *		 checked with check_free_sectors.
 *
 * Return: 0 when succeed, -1 on error.
 *
 * ToDo: 1. Is it neceressary to check_free_sector after erasing ??
 */
int INFTL_formatblock(struct INFTLrecord *inftl, int block)
{
	size_t retlen;
	struct inftl_unittail uci;
	struct erase_info *instr = &inftl->instr;
	struct mtd_info *mtd = inftl->mbd.mtd;
	int physblock;

	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: INFTL_formatblock(inftl=%p,"
		"block=%d)\n", inftl, block);

	memset(instr, 0, sizeof(struct erase_info));

	/* FIXME: Shouldn't we be setting the 'discarded' flag to zero
	   _first_? */

	/* Use async erase interface, test return code */
	instr->mtd = inftl->mbd.mtd;
	instr->addr = block * inftl->EraseSize;
	instr->len = inftl->mbd.mtd->erasesize;
	/* Erase one physical eraseblock at a time, even though the NAND api
	   allows us to group them.  This way we if we have a failure, we can
	   mark only the failed block in the bbt. */
	for (physblock = 0; physblock < inftl->EraseSize;
	     physblock += instr->len, instr->addr += instr->len) {
		mtd->erase(inftl->mbd.mtd, instr);

		if (instr->state == MTD_ERASE_FAILED) {
			printk(KERN_WARNING "INFTL: error while formatting block %d\n",
				block);
			goto fail;
		}

		/*
		 * Check the "freeness" of Erase Unit before updating metadata.
		 * FixMe: is this check really necessary? Since we have check
		 * the return code after the erase operation.
		 */
		if (check_free_sectors(inftl, instr->addr, instr->len, 1) != 0)
			goto fail;
	}

	uci.EraseMark = cpu_to_le16(ERASE_MARK);
	uci.EraseMark1 = cpu_to_le16(ERASE_MARK);
	uci.Reserved[0] = 0;
	uci.Reserved[1] = 0;
	uci.Reserved[2] = 0;
	uci.Reserved[3] = 0;
	instr->addr = block * inftl->EraseSize + SECTORSIZE * 2;
	if (inftl_write_oob(mtd, instr->addr + 8, 8, &retlen, (char *)&uci) < 0)
		goto fail;
	return 0;
fail:
	/* could not format, update the bad block table (caller is responsible
	   for setting the PUtable to BLOCK_RESERVED on failure) */
	inftl->mbd.mtd->block_markbad(inftl->mbd.mtd, instr->addr);
	return -1;
}

/*
 * format_chain: Format an invalid Virtual Unit chain. It frees all the Erase
 *	Units in a Virtual Unit Chain, i.e. all the units are disconnected.
 *
 *	Since the chain is invalid then we will have to erase it from its
 *	head (normally for INFTL we go from the oldest). But if it has a
 *	loop then there is no oldest...
 */
static void format_chain(struct INFTLrecord *inftl, unsigned int first_block)
{
	unsigned int block = first_block, block1;

	printk(KERN_WARNING "INFTL: formatting chain at block %d\n",
		first_block);

	for (;;) {
		block1 = inftl->PUtable[block];

		printk(KERN_WARNING "INFTL: formatting block %d\n", block);
		if (INFTL_formatblock(inftl, block) < 0) {
			/*
			 * Cannot format !!!! Mark it as Bad Unit,
			 */
			inftl->PUtable[block] = BLOCK_RESERVED;
		} else {
			inftl->PUtable[block] = BLOCK_FREE;
		}

		/* Goto next block on the chain */
		block = block1;

		if (block == BLOCK_NIL || block >= inftl->lastEUN)
			break;
	}
}

void INFTL_dumptables(struct INFTLrecord *s)
{
	int i;

	printk("-------------------------------------------"
		"----------------------------------\n");

	printk("VUtable[%d] ->", s->nb_blocks);
	for (i = 0; i < s->nb_blocks; i++) {
		if ((i % 8) == 0)
			printk("\n%04x: ", i);
		printk("%04x ", s->VUtable[i]);
	}

	printk("\n-------------------------------------------"
		"----------------------------------\n");

	printk("PUtable[%d-%d=%d] ->", s->firstEUN, s->lastEUN, s->nb_blocks);
	for (i = 0; i <= s->lastEUN; i++) {
		if ((i % 8) == 0)
			printk("\n%04x: ", i);
		printk("%04x ", s->PUtable[i]);
	}

	printk("\n-------------------------------------------"
		"----------------------------------\n");

	printk("INFTL ->\n"
		"  EraseSize       = %d\n"
		"  h/s/c           = %d/%d/%d\n"
		"  numvunits       = %d\n"
		"  firstEUN        = %d\n"
		"  lastEUN         = %d\n"
		"  numfreeEUNs     = %d\n"
		"  LastFreeEUN     = %d\n"
		"  nb_blocks       = %d\n"
		"  nb_boot_blocks  = %d",
		s->EraseSize, s->heads, s->sectors, s->cylinders,
		s->numvunits, s->firstEUN, s->lastEUN, s->numfreeEUNs,
		s->LastFreeEUN, s->nb_blocks, s->nb_boot_blocks);

	printk("\n-------------------------------------------"
		"----------------------------------\n");
}

void INFTL_dumpVUchains(struct INFTLrecord *s)
{
	int logical, block, i;

	printk("-------------------------------------------"
		"----------------------------------\n");

	printk("INFTL Virtual Unit Chains:\n");
	for (logical = 0; logical < s->nb_blocks; logical++) {
		block = s->VUtable[logical];
		if (block > s->nb_blocks)
			continue;
		printk("  LOGICAL %d --> %d ", logical, block);
		for (i = 0; i < s->nb_blocks; i++) {
			if (s->PUtable[block] == BLOCK_NIL)
				break;
			block = s->PUtable[block];
			printk("%d ", block);
		}
		printk("\n");
	}

	printk("-------------------------------------------"
		"----------------------------------\n");
}

int INFTL_mount(struct INFTLrecord *s)
{
	struct mtd_info *mtd = s->mbd.mtd;
	unsigned int block, first_block, prev_block, last_block;
	unsigned int first_logical_block, logical_block, erase_mark;
	int chain_length, do_format_chain;
	struct inftl_unithead1 h0;
	struct inftl_unittail h1;
	size_t retlen;
	int i;
	u8 *ANACtable, ANAC;

	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: INFTL_mount(inftl=%p)\n", s);

	/* Search for INFTL MediaHeader and Spare INFTL Media Header */
	if (find_boot_record(s) < 0) {
		printk(KERN_WARNING "INFTL: could not find valid boot record?\n");
		return -ENXIO;
	}

	/* Init the logical to physical table */
	for (i = 0; i < s->nb_blocks; i++)
		s->VUtable[i] = BLOCK_NIL;

	logical_block = block = BLOCK_NIL;

	/* Temporary buffer to store ANAC numbers. */
	ANACtable = kmalloc(s->nb_blocks * sizeof(u8), GFP_KERNEL);
	if (!ANACtable) {
		printk(KERN_WARNING "INFTL: allocation of ANACtable "
				"failed (%zd bytes)\n",
				s->nb_blocks * sizeof(u8));
		return -ENOMEM;
	}
	memset(ANACtable, 0, s->nb_blocks);

	/*
	 * First pass is to explore each physical unit, and construct the
	 * virtual chains that exist (newest physical unit goes into VUtable).
	 * Any block that is in any way invalid will be left in the
	 * NOTEXPLORED state. Then at the end we will try to format it and
	 * mark it as free.
	 */
	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 1, explore each unit\n");
	for (first_block = s->firstEUN; first_block <= s->lastEUN; first_block++) {
		if (s->PUtable[first_block] != BLOCK_NOTEXPLORED)
			continue;

		do_format_chain = 0;
		first_logical_block = BLOCK_NIL;
		last_block = BLOCK_NIL;
		block = first_block;

		for (chain_length = 0; ; chain_length++) {

			if ((chain_length == 0) &&
			    (s->PUtable[block] != BLOCK_NOTEXPLORED)) {
				/* Nothing to do here, onto next block */
				break;
			}

			if (inftl_read_oob(mtd, block * s->EraseSize + 8,
					   8, &retlen, (char *)&h0) < 0 ||
			    inftl_read_oob(mtd, block * s->EraseSize +
					   2 * SECTORSIZE + 8, 8, &retlen,
					   (char *)&h1) < 0) {
				/* Should never happen? */
				do_format_chain++;
				break;
			}

			logical_block = le16_to_cpu(h0.virtualUnitNo);
			prev_block = le16_to_cpu(h0.prevUnitNo);
			erase_mark = le16_to_cpu((h1.EraseMark | h1.EraseMark1));
			ANACtable[block] = h0.ANAC;

			/* Previous block is relative to start of Partition */
			if (prev_block < s->nb_blocks)
				prev_block += s->firstEUN;

			/* Already explored partial chain? */
			if (s->PUtable[block] != BLOCK_NOTEXPLORED) {
				/* Check if chain for this logical */
				if (logical_block == first_logical_block) {
					if (last_block != BLOCK_NIL)
						s->PUtable[last_block] = block;
				}
				break;
			}

			/* Check for invalid block */
			if (erase_mark != ERASE_MARK) {
				printk(KERN_WARNING "INFTL: corrupt block %d "
					"in chain %d, chain length %d, erase "
					"mark 0x%x?\n", block, first_block,
					chain_length, erase_mark);
				/*
				 * Assume end of chain, probably incomplete
				 * fold/erase...
				 */
				if (chain_length == 0)
					do_format_chain++;
				break;
			}

			/* Check for it being free already then... */
			if ((logical_block == BLOCK_FREE) ||
			    (logical_block == BLOCK_NIL)) {
				s->PUtable[block] = BLOCK_FREE;
				break;
			}

			/* Sanity checks on block numbers */
			if ((logical_block >= s->nb_blocks) ||
			    ((prev_block >= s->nb_blocks) &&
			     (prev_block != BLOCK_NIL))) {
				if (chain_length > 0) {
					printk(KERN_WARNING "INFTL: corrupt "
						"block %d in chain %d?\n",
						block, first_block);
					do_format_chain++;
				}
				break;
			}

			if (first_logical_block == BLOCK_NIL) {
				first_logical_block = logical_block;
			} else {
				if (first_logical_block != logical_block) {
					/* Normal for folded chain... */
					break;
				}
			}

			/*
			 * Current block is valid, so if we followed a virtual
			 * chain to get here then we can set the previous
			 * block pointer in our PUtable now. Then move onto
			 * the previous block in the chain.
			 */
			s->PUtable[block] = BLOCK_NIL;
			if (last_block != BLOCK_NIL)
				s->PUtable[last_block] = block;
			last_block = block;
			block = prev_block;

			/* Check for end of chain */
			if (block == BLOCK_NIL)
				break;

			/* Validate next block before following it... */
			if (block > s->lastEUN) {
				printk(KERN_WARNING "INFTL: invalid previous "
					"block %d in chain %d?\n", block,
					first_block);
				do_format_chain++;
				break;
			}
		}

		if (do_format_chain) {
			format_chain(s, first_block);
			continue;
		}

		/*
		 * Looks like a valid chain then. It may not really be the
		 * newest block in the chain, but it is the newest we have
		 * found so far. We might update it in later iterations of
		 * this loop if we find something newer.
		 */
		s->VUtable[first_logical_block] = first_block;
		logical_block = BLOCK_NIL;
	}

#ifdef CONFIG_MTD_DEBUG_VERBOSE
	if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
		INFTL_dumptables(s);
#endif

	/*
	 * Second pass, check for infinite loops in chains. These are
	 * possible because we don't update the previous pointers when
	 * we fold chains. No big deal, just fix them up in PUtable.
	 */
	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 2, validate virtual chains\n");
	for (logical_block = 0; logical_block < s->numvunits; logical_block++) {
		block = s->VUtable[logical_block];
		last_block = BLOCK_NIL;

		/* Check for free/reserved/nil */
		if (block >= BLOCK_RESERVED)
			continue;

		ANAC = ANACtable[block];
		for (i = 0; i < s->numvunits; i++) {
			if (s->PUtable[block] == BLOCK_NIL)
				break;
			if (s->PUtable[block] > s->lastEUN) {
				printk(KERN_WARNING "INFTL: invalid prev %d, "
					"in virtual chain %d\n",
					s->PUtable[block], logical_block);
				s->PUtable[block] = BLOCK_NIL;

			}
			if (ANACtable[block] != ANAC) {
				/*
				 * Chain must point back to itself. This is ok,
				 * but we will need adjust the tables with this
				 * newest block and oldest block.
				 */
				s->VUtable[logical_block] = block;
				s->PUtable[last_block] = BLOCK_NIL;
				break;
			}

			ANAC--;
			last_block = block;
			block = s->PUtable[block];
		}

		if (i >= s->nb_blocks) {
			/*
			 * Uhoo, infinite chain with valid ANACS!
			 * Format whole chain...
			 */
			format_chain(s, first_block);
		}
	}

#ifdef CONFIG_MTD_DEBUG_VERBOSE
	if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
		INFTL_dumptables(s);
	if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
		INFTL_dumpVUchains(s);
#endif

	/*
	 * Third pass, format unreferenced blocks and init free block count.
	 */
	s->numfreeEUNs = 0;
	s->LastFreeEUN = BLOCK_NIL;

	DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 3, format unused blocks\n");
	for (block = s->firstEUN; block <= s->lastEUN; block++) {
		if (s->PUtable[block] == BLOCK_NOTEXPLORED) {
			printk("INFTL: unreferenced block %d, formatting it\n",
				block);
			if (INFTL_formatblock(s, block) < 0)
				s->PUtable[block] = BLOCK_RESERVED;
			else
				s->PUtable[block] = BLOCK_FREE;
		}
		if (s->PUtable[block] == BLOCK_FREE) {
			s->numfreeEUNs++;
			if (s->LastFreeEUN == BLOCK_NIL)
				s->LastFreeEUN = block;
		}
	}

	kfree(ANACtable);
	return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Many times the intention of hiring an employee needs to be sent to
     a third party.  The person is technically not an employee, but information
     needs to be sent ahead of time.  Typically, this is so that the third party
     can meet contractual obligations (e.g. allow the employee to do online benefit
     enrollment on their first day of work.

     The <ProposedHireInfo> element is used to indicate when they are expected to
     become an employee.  Notice that the <IsEmployed> status is set to false, as
     the potential employee has not yet been 'hired'.

	Scenario: This XML document represents a bare boned information exchange.  Merely just
	reflecting the intention to have the person become an employee.  See example
	JimmyPreHireDetailed.xml for a document where the employee details are sent along
	with the propsed information (i.e. need information in advance to do eligibility calculations).

	WARNING:  EmploymentInfo/HireInfo should not be sent as they have not been hired!  That is the
	          purpose of the <ProposedHireInfo> node - to model the intention of becoming an employee
	          without stating that they actually have!  HireInfo would typically be sent when they
	          have actually become and employee.
-->
<IndicativeBatch xmlns="http://ns.hr-xml.org/2007-04-15" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.hr-xml.org/2007-04-15
 IndicativeBatch.xsd">
	<TransactionType>Change</TransactionType>
	<CreateDate>2004-09-16</CreateDate>
	<BaselineDate>2004-09-16</BaselineDate>
	<IndicativeData>
		<Employer>
			<OrganizationId>
				<IdValue>12345</IdValue>
			</OrganizationId>
		</Employer>
		<Employee>
			<PersonInfo>
				<!-- For now, using a legal id for identification (no employee id yet) -->
				<PersonLegalId idOwner="US:SSA">
					<IdValue name="SSN">555-11-1111</IdValue>
				</PersonLegalId>
			</PersonInfo>
			<EmploymentInfo>
				<IsEmployed>false</IsEmployed>
				<ProposedHireInfo>
					<ExpectedStartDate>2004-10-01</ExpectedStartDate>
				</ProposedHireInfo>
			</EmploymentInfo>
		</Employee>
	</IndicativeData>
</IndicativeBatch>

redpajama_set_name: RedPajamaGithub


text:
package build

import (
	"context"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	"golang.org/x/time/rate"
	"google.golang.org/protobuf/types/known/structpb"

	"go.chromium.org/luci/common/clock/testclock"
	. "go.chromium.org/luci/common/testing/assertions"
	"go.chromium.org/luci/luciexe/build/internal/testpb"
)

func mustNewStruct(data map[string]interface{}) *structpb.Struct {
	ret, err := structpb.NewStruct(data)
	So(err, ShouldBeNil)
	return ret
}

func TestOutputProperties(t *testing.T) {
	// Intentionally forgo t.Parallel() due to global reservation structures.

	Convey(`Properties Output`, t, func() {
		defer propModifierReservations.clear()

		var setter func(context.Context, *testpb.Module)
		var merger func(context.Context, *testpb.Module)
		MakePropertyModifier("ns", &setter, &merger)

		lastBuildVers := newBuildWaiter()

		ctx, _ := testclock.UseTime(context.Background(), testclock.TestRecentTimeUTC)
		opt := OptSend(rate.Inf, lastBuildVers.sendFn)

		Convey(`empty output`, func() {
			st, ctx, err := Start(ctx, nil, opt)
			So(err, ShouldBeNil)
			defer func() { st.End(nil) }()

			setter(ctx, nil)
			merger(ctx, nil)

			step, _ := StartStep(ctx, "wat")
			defer func() { step.End(nil) }()

			So(lastBuildVers.waitFor(2).Output.Properties, ShouldBeNil)
		})

		Convey(`populate output`, func() {
			st, ctx, err := Start(ctx, nil, opt)
			So(err, ShouldBeNil)
			defer func() { st.End(nil) }()

			setter(ctx, &testpb.Module{
				Field: "stuff",
			})

			So(lastBuildVers.waitFor(1).Output.Properties, ShouldResembleProto, mustNewStruct(map[string]interface{}{
				"ns": map[string]interface{}{
					"field": "stuff",
				},
			}))

			Convey(`merge`, func() {
				merger(ctx, &testpb.Module{
					JsonNameField: "things",
				})

				So(lastBuildVers.waitFor(2).Output.Properties, ShouldResembleProto, mustNewStruct(map[string]interface{}{
					"ns": map[string]interface{}{
						"field": "stuff",
						"$cool": "things",
					},
				}))
			})
		})

		Convey(`top level output`, func() {
			var topWriter func(*testpb.TopLevel)
			var topMerger func(*testpb.TopLevel)

			st, ctx, err := Start(ctx, nil, opt, OptOutputProperties(&topWriter, &topMerger))
			So(err, ShouldBeNil)
			defer func() { st.End(nil) }()

			setter(ctx, &testpb.Module{
				Field: "stuff",
			})

			topMerger(&testpb.TopLevel{
				JsonNameField: "nice",
			})
			topWriter(&testpb.TopLevel{ // overwrites previous value
				Field: "woot",
			})

			So(lastBuildVers.waitFor(3).Output.Properties, ShouldResembleProto, mustNewStruct(map[string]interface{}{
				"field": "woot",
				"ns": map[string]interface{}{
					"field": "stuff",
				},
			}))
		})

		Convey(`top level conflicts with reservations`, func() {
			var badWriter func(context.Context, *testpb.Module)
			MakePropertyModifier("$cool", &badWriter, nil)

			var topWriter func(*testpb.TopLevel)
			var topMerger func(*testpb.TopLevel)
			_, _, err := Start(ctx, nil, opt, OptOutputProperties(&topWriter, &topMerger))
			So(err, ShouldErrLike, `output property "$cool" conflicts with field`)
		})

		Convey(`late binding panics`, func() {
			var topMerger func(*testpb.TopLevel)

			st, ctx, err := Start(ctx, nil, opt, OptOutputProperties(nil, &topMerger))
			So(err, ShouldBeNil)
			defer func() { st.End(nil) }()

			var badSetter func(context.Context, *testpb.Module)
			MakePropertyModifier("field", &badSetter, nil) // note that "field" would overlap TopLevel.Field.

			So(func() {
				badSetter(ctx, &testpb.Module{
					Field: "whoops!",
				})
			}, ShouldPanicLike,
				`MakePropertyModifier[writing] for namespace "field"`,
				`was created after the current build started`,
				`luciexe/build/output_properties_test.go`)

		})

	})

}


text:
var winston = require('winston');
var conf = require(process.cwd() + '/lib/conf.js').logger;
var fs = require('fs');
var logdirectory = process.cwd() + '/logs'

try {
  var stats = fs.statSync(logdirectory);

  if (!stats.isDirectory()) {
    fs.mkdirSync(logdirectory);
  }
} catch (e) {
  fs.mkdirSync(logdirectory);
}

module.exports = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      name: conf.console.name,
      level: conf.console.level
    }),
    new (winston.transports.File)({
      name: conf.file.name,
      filename: logdirectory + '/' + conf.file.filename,
      level: conf.file.level
    })
  ]
});


text:
#if !defined(FUSION_SEQUENCE_TUPLE_SIZE_HPP)
#define FUSION_SEQUENCE_TUPLE_SIZE_HPP

#include <boost/spirit/fusion/sequence/size.hpp>
#include <boost/mpl/int.hpp>

#include <utility>

namespace boost { namespace fusion
{
    ///////////////////////////////////////////////////////////////////////////
    //
    //  tuple_size metafunction
    //
    //      Get the size of Sequence. Usage:
    //
    //          tuple_size<Sequence>::value
    //
    //  This metafunction is provided here for compatibility with the
    //  tuples TR1 specification. This metafunction forwards to
    //  meta::size<Sequence>.
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename Sequence>
    struct tuple_size : meta::size<Sequence> {};

    template<typename T1, typename T2>
    struct tuple_size<std::pair<T1, T2> > : boost::mpl::int_<2> { };
}}

#endif


text:
function calculator(){
	var firstValue=document.getElementById("firstNumber").value;
	var secondValue=document.getElementById("secondNumber").value;
	//判断输入框是否为空
	if (firstValue != null && firstValue != "" && secondValue != null && secondValue != "") {
		var opra=document.getElementById("operator").value;
		var result=0;
		switch(opra) {
			case "+":
				result=parseInt(firstValue)+parseInt(secondValue);
				break;
			case "-":
				result=parseInt(firstValue)-parseInt(secondValue);
				break;
			case "*":
				result=parseInt(firstValue)*parseInt(secondValue);
				break;
			case "/":
				if(parseInt(secondValue)!=0){
					result=parseInt(firstValue)/parseInt(secondValue);
				}
				else{
					alert("除数不能为0");
					return;
				}
				break;
			default:
				break;
		}
		// 将结果显示
		document.getElementById("result").value=result;
	}else{
		alert("请输入数字!");
	};

}
//限制只输入数字
function keyPress() {
	var keyCode = event.keyCode;
	if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105))
	{
		event.returnValue = true;
	} else {
		event.returnValue = false;
	}
}


text:
<?php

namespace Omnipay\RentMoola;

use Omnipay\Tests\GatewayTestCase;

class GatewayTest extends GatewayTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->gateway = new Gateway(
            $this->getHttpClient(),
            $this->getHttpRequest()
        );
        $this->gateway->setTestMode(true);
        $this->options = array(
            "userId" => "24a58d3c-4774-48bb-803a-b0ccc6b2d8d5",
            "paymentMethodId" => "c4ec7ad4-5b20-456a-8ab5-5ad5c2300a17",
            "destinationAccountId" => "23535718-e3a9-4b13-a28c-85f0838083b1",
            "code" => "global.payments.other",
            "amount" => '10.00',
            "username" => '32b53506-d3b2-405a-8c83-9b5c82b67575',
            "password" => 'test',
        );
    }

    public function testCreateUser()
    {
        $this->gateway->setFirstName("firstname");
        $this->gateway->setLastName("lastname");
        $this->gateway->setEmail("email@email.com");
        $this->gateway->setPropertyId("12345678");
        $this->gateway->setPrimaryPaymentMethodId("23456789");
        $this->gateway->setSuite("5");

        $this->assertSame($this->gateway->getFirstName(), "firstname");
        $this->assertSame($this->gateway->getLastName(), "lastname");
        $this->assertSame($this->gateway->getEmail(), "email@email.com");
        $this->assertSame($this->gateway->getPropertyId(), "12345678");
        $this->assertSame($this->gateway->getPrimaryPaymentMethodId(), "23456789");
        $this->assertSame($this->gateway->getSuite(), "5");

        $request = $this->gateway->createUser();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\CreateUserRequest',
            $request
        );

        $this->assertSame($request->getFirstName(), "firstname");
        $this->assertSame($request->getLastName(), "lastname");
        $this->assertSame($request->getEmail(), "email@email.com");
        $this->assertSame($request->getPropertyId(), "12345678");
        $this->assertSame($request->getPrimaryPaymentMethodId(), "23456789");
        $this->assertSame($request->getSuite(), "5");
    }

    public function testFetchUser()
    {
        $this->options = array(
            "userId" => '0ff7ba61-1560-4d10-a1de-1b0edf29852f'
        );

        $request = $this->gateway->fetchUser($this->options);

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\FetchUserRequest',
            $request
        );
    }

    public function testPurchase()
    {
        $request = $this->gateway->purchase($this->options);

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\PurchaseRequest',
            $request
        );
        $this->assertSame($request->getAmount(), '10.00');
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     */
    public function testPurchaseInvalidAmount()
    {
        $this->options['amount'] = '';

        $request = $this->gateway->purchase($this->options);
        $this->assertEmpty($request->getAmount());
    }

    public function testCreateCCPaymentMethodRequest()
    {
        $request = $this->gateway->createCCPaymentMethod();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\CreateCCPaymentMethodRequest',
            $request
        );
    }

    public function testFetchPaymentMethodRequest()
    {
        $request = $this->gateway->fetchPaymentMethod();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\FetchPaymentMethodRequest',
            $request
        );
    }

    public function testFetchPaymentMethods()
    {
        $request = $this->gateway->fetchPaymentMethods();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\FetchPaymentMethodsRequest',
            $request
        );
    }

    public function testUpdateCCPaymentMethod()
    {
        $request = $this->gateway->updateCCPaymentMethod();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\UpdateCCPaymentMethodRequest',
            $request
        );
    }

    public function testFetchPayment()
    {
        $request = $this->gateway->fetchPayment();

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\FetchPaymentRequest',
            $request
        );
    }

    public function testRefund()
    {
        $request = $this->gateway->refund($this->options);

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\RefundRequest',
            $request
        );
    }

    public function testAuthorizationValue()
    {
        $this->gateway->setUserName("username");
        $this->gateway->setPassword("password");

        $this->assertSame('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', $this->gateway->getAuthorizationValue());
    }

    public function testTransactionReference()
    {
        $this->assertSame($this->gateway, $this->gateway->setTransactionReference('abc123'));
        $this->assertSame('abc123', $this->gateway->getTransactionReference());
    }

    public function testDeletePaymentMethod()
    {
        $request = $this->gateway->deletePaymentMethod($this->options);

        $this->assertInstanceOf(
            'Omnipay\RentMoola\Message\DeletePaymentMethodRequest',
            $request
        );
    }
}


text:
#include "mitkPlanarFigureMapper2D.h"

#include "mitkBaseRenderer.h"
#include "mitkColorProperty.h"
#include "mitkGL.h"
#include "mitkPlaneGeometry.h"
#include "mitkProperties.h"

#include "mitkTextAnnotation2D.h"

#define _USE_MATH_DEFINES
#include <math.h>

// offset which moves the planarfigures on top of the other content
// the crosshair is rendered into the z = 1 layer.
static const float PLANAR_OFFSET = 0.5f;

mitk::PlanarFigureMapper2D::PlanarFigureMapper2D()
  : m_NodeModified(true), m_NodeModifiedObserverTag(0), m_NodeModifiedObserverAdded(false)
{
  m_AnnotationAnnotation = mitk::TextAnnotation2D::New();
  m_QuantityAnnotation = mitk::TextAnnotation2D::New();

  this->InitializeDefaultPlanarFigureProperties();
}

mitk::PlanarFigureMapper2D::~PlanarFigureMapper2D()
{
  if (m_NodeModifiedObserverAdded && GetDataNode() != NULL)
  {
    GetDataNode()->RemoveObserver(m_NodeModifiedObserverTag);
  }
}

void mitk::PlanarFigureMapper2D::Paint(mitk::BaseRenderer *renderer)
{
  bool visible = true;

  m_AnnotationAnnotation->SetVisibility(false);

  m_QuantityAnnotation->SetVisibility(false);

  GetDataNode()->GetVisibility(visible, renderer, "visible");
  if (!visible)
    return;

  // Get PlanarFigure from input
  mitk::PlanarFigure *planarFigure =
    const_cast<mitk::PlanarFigure *>(static_cast<const mitk::PlanarFigure *>(GetDataNode()->GetData()));

  // Check if PlanarFigure has already been placed; otherwise, do nothing
  if (!planarFigure->IsPlaced())
  {
    return;
  }

  // Get 2D geometry frame of PlanarFigure
  const mitk::PlaneGeometry *planarFigurePlaneGeometry = planarFigure->GetPlaneGeometry();
  if (planarFigurePlaneGeometry == NULL)
  {
    MITK_ERROR << "PlanarFigure does not have valid PlaneGeometry!";
    return;
  }

  // Get current world 2D geometry from renderer
  const mitk::PlaneGeometry *rendererPlaneGeometry = renderer->GetCurrentWorldPlaneGeometry();

  // If the PlanarFigure geometry is a plane geometry, check if current
  // world plane is parallel to and within the planar figure geometry bounds
  // (otherwise, display nothing)

  if ((planarFigurePlaneGeometry != NULL) && (rendererPlaneGeometry != NULL))
  {
    double planeThickness = planarFigurePlaneGeometry->GetExtentInMM(2);
    if (!planarFigurePlaneGeometry->IsParallel(rendererPlaneGeometry) ||
        !(planarFigurePlaneGeometry->DistanceFromPlane(rendererPlaneGeometry) < planeThickness / 3.0))
    {
      // Planes are not parallel or renderer plane is not within PlanarFigure
      // geometry bounds --> exit
      return;
    }
  }
  else
  {
    // Plane is not valid (curved reformations are not possible yet)
    return;
  }

  // Apply visual appearance properties from the PropertyList
  ApplyColorAndOpacityProperties(renderer);

  // Enable line antialiasing
  glEnable(GL_LINE_SMOOTH);
  glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
  glEnable(GL_DEPTH_TEST);

  // Get properties from node (if present)
  const mitk::DataNode *node = this->GetDataNode();
  this->InitializePlanarFigurePropertiesFromDataNode(node);

  PlanarFigureDisplayMode lineDisplayMode = PF_DEFAULT;

  if (m_IsSelected)
  {
    lineDisplayMode = PF_SELECTED;
  }
  else if (m_IsHovering)
  {
    lineDisplayMode = PF_HOVER;
  }

  mitk::Point2D anchorPoint;
  anchorPoint[0] = 0;
  anchorPoint[1] = 1;

  // render the actual lines of the PlanarFigure
  RenderLines(lineDisplayMode, planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

  // position-offset of the annotations, is set in RenderAnnotations() and
  // used in RenderQuantities()
  double annotationOffset = 0.0;

  // Get Global Opacity
  float globalOpacity = 1.0;
  node->GetFloatProperty("opacity", globalOpacity);

  if (m_DrawControlPoints)
  {
    // draw the control-points
    RenderControlPoints(planarFigure, lineDisplayMode, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);
  }

  // draw name near the anchor point (point located on the right)
  const std::string name = node->GetName();
  if (m_DrawName && !name.empty())
  {
    RenderAnnotations(renderer, name, anchorPoint, globalOpacity, lineDisplayMode, annotationOffset);
  }

  // draw feature quantities (if requested) next to the anchor point,
  // but under the name (that is where 'annotationOffset' is used)
  if (m_DrawQuantities)
  {
    RenderQuantities(planarFigure, renderer, anchorPoint, annotationOffset, globalOpacity, lineDisplayMode);
  }

  glLineWidth(1.0f);
}

void mitk::PlanarFigureMapper2D::PaintPolyLine(const mitk::PlanarFigure::PolyLineType vertices,
                                               bool closed,
                                               Point2D &anchorPoint,
                                               const PlaneGeometry *planarFigurePlaneGeometry,
                                               const PlaneGeometry *rendererPlaneGeometry,
                                               const mitk::BaseRenderer *renderer)
{
  mitk::Point2D rightMostPoint;
  rightMostPoint.Fill(itk::NumericTraits<float>::min());

  // transform all vertices into Point2Ds in display-Coordinates and store them in vector
  std::vector<mitk::Point2D> pointlist;
  for (auto iter = vertices.cbegin(); iter != vertices.cend(); ++iter)
  {
    // Draw this 2D point as OpenGL vertex
    mitk::Point2D displayPoint;
    this->TransformObjectToDisplay(*iter, displayPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    pointlist.push_back(displayPoint);

    if (displayPoint[0] > rightMostPoint[0])
      rightMostPoint = displayPoint;
  }

  // If the planarfigure is closed, we add the first control point again.
  // Thus we can always use 'GL_LINE_STRIP' and get rid of strange flickering
  // effect when using the MESA OpenGL library.
  if (closed)
  {
    mitk::Point2D displayPoint;
    this->TransformObjectToDisplay(
      vertices.cbegin()[0], displayPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    pointlist.push_back(displayPoint);
  }

  // now paint all the points in one run

  glBegin(GL_LINE_STRIP);
  for (auto pointIter = pointlist.cbegin(); pointIter != pointlist.cend(); pointIter++)
  {
    glVertex3f((*pointIter)[0], (*pointIter)[1], PLANAR_OFFSET);
  }
  glEnd();

  anchorPoint = rightMostPoint;
}

void mitk::PlanarFigureMapper2D::DrawMainLines(mitk::PlanarFigure *figure,
                                               Point2D &anchorPoint,
                                               const PlaneGeometry *planarFigurePlaneGeometry,
                                               const PlaneGeometry *rendererPlaneGeometry,
                                               const mitk::BaseRenderer *renderer)
{
  const auto numberOfPolyLines = figure->GetPolyLinesSize();
  for (auto loop = 0; loop < numberOfPolyLines; ++loop)
  {
    const auto polyline = figure->GetPolyLine(loop);

    this->PaintPolyLine(
      polyline, figure->IsClosed(), anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);
  }
}

void mitk::PlanarFigureMapper2D::DrawHelperLines(mitk::PlanarFigure *figure,
                                                 Point2D &anchorPoint,
                                                 const PlaneGeometry *planarFigurePlaneGeometry,
                                                 const PlaneGeometry *rendererPlaneGeometry,
                                                 const mitk::BaseRenderer *renderer)
{
  const auto numberOfHelperPolyLines = figure->GetHelperPolyLinesSize();

  // Draw helper objects
  for (unsigned int loop = 0; loop < numberOfHelperPolyLines; ++loop)
  {
    const auto helperPolyLine =
      figure->GetHelperPolyLine(loop, renderer->GetScaleFactorMMPerDisplayUnit(), renderer->GetViewportSize()[1]);

    // Check if the current helper objects is to be painted
    if (!figure->IsHelperToBePainted(loop))
    {
      continue;
    }

    // ... and once normally above the shadow.
    this->PaintPolyLine(helperPolyLine, false, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);
  }
}

void mitk::PlanarFigureMapper2D::TransformObjectToDisplay(const mitk::Point2D &point2D,
                                                          mitk::Point2D &displayPoint,
                                                          const mitk::PlaneGeometry *objectGeometry,
                                                          const mitk::PlaneGeometry * /*rendererGeometry*/,
                                                          const mitk::BaseRenderer *renderer)
{
  mitk::Point3D point3D;

  // Map circle point from local 2D geometry into 3D world space
  objectGeometry->Map(point2D, point3D);

  // Project 3D world point onto display geometry
  renderer->WorldToDisplay(point3D, displayPoint);
}

void mitk::PlanarFigureMapper2D::DrawMarker(const mitk::Point2D &point,
                                            float *lineColor,
                                            float lineOpacity,
                                            float *markerColor,
                                            float markerOpacity,
                                            float lineWidth,
                                            PlanarFigureControlPointStyleProperty::Shape shape,
                                            const mitk::PlaneGeometry *objectGeometry,
                                            const mitk::PlaneGeometry *rendererGeometry,
                                            const mitk::BaseRenderer *renderer)
{
  if (this->GetDataNode() != nullptr && this->GetDataNode()->GetDataInteractor().IsNull())
    return;

  if (markerOpacity == 0 && lineOpacity == 0)
    return;

  mitk::Point2D displayPoint;

  this->TransformObjectToDisplay(point, displayPoint, objectGeometry, rendererGeometry, renderer);

  glColor4f(markerColor[0], markerColor[1], markerColor[2], markerOpacity);
  glLineWidth(lineWidth);

  switch (shape)
  {
    case PlanarFigureControlPointStyleProperty::Square:
    default:
    {
      // Paint filled square

      // Disable line antialiasing (does not look nice for squares)
      glDisable(GL_LINE_SMOOTH);
      if (markerOpacity > 0)
      {
        glRectf(displayPoint[0] - 4, displayPoint[1] - 4, displayPoint[0] + 4, displayPoint[1] + 4);
      }
      // Paint outline
      glColor4f(lineColor[0], lineColor[1], lineColor[2], lineOpacity);
      glBegin(GL_LINE_LOOP);
      glVertex3f(displayPoint[0] - 4, displayPoint[1] - 4, PLANAR_OFFSET);
      glVertex3f(displayPoint[0] - 4, displayPoint[1] + 4, PLANAR_OFFSET);
      glVertex3f(displayPoint[0] + 4, displayPoint[1] + 4, PLANAR_OFFSET);
      glVertex3f(displayPoint[0] + 4, displayPoint[1] - 4, PLANAR_OFFSET);
      glEnd();
      break;
    }

    case PlanarFigureControlPointStyleProperty::Circle:
    {
      float radius = 4.0;

      if (markerOpacity > 0)
      {
        // Paint filled circle
        glBegin(GL_POLYGON);
        for (int angle = 0; angle < 8; ++angle)
        {
          float angleRad = angle * (float)3.14159 / 4.0;
          float x = displayPoint[0] + radius * (float)cos(angleRad);
          float y = displayPoint[1] + radius * (float)sin(angleRad);
          glVertex3f(x, y, PLANAR_OFFSET);
        }
        glEnd();
      }

      // Paint outline
      glColor4f(lineColor[0], lineColor[1], lineColor[2], lineOpacity);
      glBegin(GL_LINE_LOOP);
      for (int angle = 0; angle < 8; ++angle)
      {
        float angleRad = angle * (float)3.14159 / 4.0;
        float x = displayPoint[0] + radius * (float)cos(angleRad);
        float y = displayPoint[1] + radius * (float)sin(angleRad);
        glVertex3f(x, y, PLANAR_OFFSET);
      }
      glEnd();
      break;
    }

  } // end switch
}

void mitk::PlanarFigureMapper2D::InitializeDefaultPlanarFigureProperties()
{
  m_IsSelected = false;
  m_IsHovering = false;
  m_DrawOutline = false;
  m_DrawQuantities = false;
  m_DrawShadow = false;
  m_DrawControlPoints = false;
  m_DrawName = true;
  m_DrawDashed = false;
  m_DrawHelperDashed = false;
  m_AnnotationsShadow = false;

  m_ShadowWidthFactor = 1.2;
  m_LineWidth = 1.0;
  m_OutlineWidth = 4.0;
  m_HelperlineWidth = 2.0;

  m_DevicePixelRatio = 1.0;

  m_ControlPointShape = PlanarFigureControlPointStyleProperty::Square;

  this->SetColorProperty(m_LineColor, PF_DEFAULT, 1.0, 1.0, 1.0);
  this->SetFloatProperty(m_LineOpacity, PF_DEFAULT, 1.0);
  this->SetColorProperty(m_OutlineColor, PF_DEFAULT, 0.0, 0.0, 1.0);
  this->SetFloatProperty(m_OutlineOpacity, PF_DEFAULT, 1.0);
  this->SetColorProperty(m_HelperlineColor, PF_DEFAULT, 0.4, 0.8, 0.2);
  this->SetFloatProperty(m_HelperlineOpacity, PF_DEFAULT, 0.4);
  this->SetColorProperty(m_MarkerlineColor, PF_DEFAULT, 1.0, 1.0, 1.0);
  this->SetFloatProperty(m_MarkerlineOpacity, PF_DEFAULT, 1.0);
  this->SetColorProperty(m_MarkerColor, PF_DEFAULT, 1.0, 1.0, 1.0);
  this->SetFloatProperty(m_MarkerOpacity, PF_DEFAULT, 0.0);
  this->SetColorProperty(m_AnnotationColor, PF_DEFAULT, 1.0, 1.0, 1.0);

  this->SetColorProperty(m_LineColor, PF_HOVER, 1.0, 0.7, 0.0);
  this->SetFloatProperty(m_LineOpacity, PF_HOVER, 1.0);
  this->SetColorProperty(m_OutlineColor, PF_HOVER, 0.0, 0.0, 1.0);
  this->SetFloatProperty(m_OutlineOpacity, PF_HOVER, 1.0);
  this->SetColorProperty(m_HelperlineColor, PF_HOVER, 0.4, 0.8, 0.2);
  this->SetFloatProperty(m_HelperlineOpacity, PF_HOVER, 0.4);
  this->SetColorProperty(m_MarkerlineColor, PF_HOVER, 1.0, 1.0, 1.0);
  this->SetFloatProperty(m_MarkerlineOpacity, PF_HOVER, 1.0);
  this->SetColorProperty(m_MarkerColor, PF_HOVER, 1.0, 0.6, 0.0);
  this->SetFloatProperty(m_MarkerOpacity, PF_HOVER, 0.2);
  this->SetColorProperty(m_AnnotationColor, PF_HOVER, 1.0, 0.7, 0.0);

  this->SetColorProperty(m_LineColor, PF_SELECTED, 1.0, 0.0, 0.0);
  this->SetFloatProperty(m_LineOpacity, PF_SELECTED, 1.0);
  this->SetColorProperty(m_OutlineColor, PF_SELECTED, 0.0, 0.0, 1.0);
  this->SetFloatProperty(m_OutlineOpacity, PF_SELECTED, 1.0);
  this->SetColorProperty(m_HelperlineColor, PF_SELECTED, 0.4, 0.8, 0.2);
  this->SetFloatProperty(m_HelperlineOpacity, PF_SELECTED, 0.4);
  this->SetColorProperty(m_MarkerlineColor, PF_SELECTED, 1.0, 1.0, 1.0);
  this->SetFloatProperty(m_MarkerlineOpacity, PF_SELECTED, 1.0);
  this->SetColorProperty(m_MarkerColor, PF_SELECTED, 1.0, 0.6, 0.0);
  this->SetFloatProperty(m_MarkerOpacity, PF_SELECTED, 1.0);
  this->SetColorProperty(m_AnnotationColor, PF_SELECTED, 1.0, 0.0, 0.0);
}

void mitk::PlanarFigureMapper2D::InitializePlanarFigurePropertiesFromDataNode(const mitk::DataNode *node)
{
  if (node == NULL)
  {
    return;
  }

  // if we have not added an observer for ModifiedEvents on the DataNode,
  // we add one now.
  if (!m_NodeModifiedObserverAdded)
  {
    itk::SimpleMemberCommand<mitk::PlanarFigureMapper2D>::Pointer nodeModifiedCommand =
      itk::SimpleMemberCommand<mitk::PlanarFigureMapper2D>::New();
    nodeModifiedCommand->SetCallbackFunction(this, &mitk::PlanarFigureMapper2D::OnNodeModified);
    m_NodeModifiedObserverTag = node->AddObserver(itk::ModifiedEvent(), nodeModifiedCommand);
    m_NodeModifiedObserverAdded = true;
  }

  // If the DataNode has not been modified since the last execution of
  // this method, we do not run it now.
  if (!m_NodeModified)
    return;

  // Mark the current properties as unmodified
  m_NodeModified = false;

  // Get Global Opacity
  float globalOpacity = 1.0;
  node->GetFloatProperty("opacity", globalOpacity);

  node->GetBoolProperty("selected", m_IsSelected);
  node->GetBoolProperty("planarfigure.ishovering", m_IsHovering);
  node->GetBoolProperty("planarfigure.drawoutline", m_DrawOutline);
  node->GetBoolProperty("planarfigure.drawshadow", m_DrawShadow);
  node->GetBoolProperty("planarfigure.drawquantities", m_DrawQuantities);
  node->GetBoolProperty("planarfigure.drawcontrolpoints", m_DrawControlPoints);
  node->GetBoolProperty("planarfigure.drawname", m_DrawName);

  node->GetBoolProperty("planarfigure.drawdashed", m_DrawDashed);
  node->GetBoolProperty("planarfigure.helperline.drawdashed", m_DrawHelperDashed);

  node->GetFloatProperty("planarfigure.line.width", m_LineWidth);
  node->GetFloatProperty("planarfigure.shadow.widthmodifier", m_ShadowWidthFactor);
  node->GetFloatProperty("planarfigure.outline.width", m_OutlineWidth);
  node->GetFloatProperty("planarfigure.helperline.width", m_HelperlineWidth);

  node->GetFloatProperty("planarfigure.devicepixelratio", m_DevicePixelRatio);
  node->GetStringProperty("planarfigure.annotations.font.family", m_AnnotationFontFamily);
  node->GetBoolProperty("planarfigure.annotations.font.bold", m_DrawAnnotationBold);
  node->GetBoolProperty("planarfigure.annotations.font.italic", m_DrawAnnotationItalic);
  node->GetIntProperty("planarfigure.annotations.font.size", m_AnnotationSize);
  if (!node->GetBoolProperty("planarfigure.annotations.shadow", m_AnnotationsShadow))
  {
    node->GetBoolProperty("planarfigure.drawshadow", m_AnnotationsShadow);
  }

  PlanarFigureControlPointStyleProperty::Pointer styleProperty =
    dynamic_cast<PlanarFigureControlPointStyleProperty *>(node->GetProperty("planarfigure.controlpointshape"));
  if (styleProperty.IsNotNull())
  {
    m_ControlPointShape = styleProperty->GetShape();
  }

  // Set default color and opacity
  // If property "planarfigure.default.*.color" exists, then use that color. Otherwise global "color" property is used.
  if (!node->GetColor(m_LineColor[PF_DEFAULT], NULL, "planarfigure.default.line.color"))
  {
    node->GetColor(m_LineColor[PF_DEFAULT], NULL, "color");
  }
  node->GetFloatProperty("planarfigure.default.line.opacity", m_LineOpacity[PF_DEFAULT]);

  if (!node->GetColor(m_OutlineColor[PF_DEFAULT], NULL, "planarfigure.default.outline.color"))
  {
    node->GetColor(m_OutlineColor[PF_DEFAULT], NULL, "color");
  }
  node->GetFloatProperty("planarfigure.default.outline.opacity", m_OutlineOpacity[PF_DEFAULT]);

  if (!node->GetColor(m_HelperlineColor[PF_DEFAULT], NULL, "planarfigure.default.helperline.color"))
  {
    node->GetColor(m_HelperlineColor[PF_DEFAULT], NULL, "color");
  }
  node->GetFloatProperty("planarfigure.default.helperline.opacity", m_HelperlineOpacity[PF_DEFAULT]);

  node->GetColor(m_MarkerlineColor[PF_DEFAULT], NULL, "planarfigure.default.markerline.color");
  node->GetFloatProperty("planarfigure.default.markerline.opacity", m_MarkerlineOpacity[PF_DEFAULT]);
  node->GetColor(m_MarkerColor[PF_DEFAULT], NULL, "planarfigure.default.marker.color");
  node->GetFloatProperty("planarfigure.default.marker.opacity", m_MarkerOpacity[PF_DEFAULT]);
  if (!node->GetColor(m_AnnotationColor[PF_DEFAULT], NULL, "planarfigure.default.annotation.color"))
  {
    if (!node->GetColor(m_AnnotationColor[PF_DEFAULT], NULL, "planarfigure.default.line.color"))
    {
      node->GetColor(m_AnnotationColor[PF_DEFAULT], NULL, "color");
    }
  }

  // Set hover color and opacity
  node->GetColor(m_LineColor[PF_HOVER], NULL, "planarfigure.hover.line.color");
  node->GetFloatProperty("planarfigure.hover.line.opacity", m_LineOpacity[PF_HOVER]);
  node->GetColor(m_OutlineColor[PF_HOVER], NULL, "planarfigure.hover.outline.color");
  node->GetFloatProperty("planarfigure.hover.outline.opacity", m_OutlineOpacity[PF_HOVER]);
  node->GetColor(m_HelperlineColor[PF_HOVER], NULL, "planarfigure.hover.helperline.color");
  node->GetFloatProperty("planarfigure.hover.helperline.opacity", m_HelperlineOpacity[PF_HOVER]);
  node->GetColor(m_MarkerlineColor[PF_HOVER], NULL, "planarfigure.hover.markerline.color");
  node->GetFloatProperty("planarfigure.hover.markerline.opacity", m_MarkerlineOpacity[PF_HOVER]);
  node->GetColor(m_MarkerColor[PF_HOVER], NULL, "planarfigure.hover.marker.color");
  node->GetFloatProperty("planarfigure.hover.marker.opacity", m_MarkerOpacity[PF_HOVER]);
  if (!node->GetColor(m_AnnotationColor[PF_HOVER], NULL, "planarfigure.hover.annotation.color"))
  {
    if (!node->GetColor(m_AnnotationColor[PF_HOVER], NULL, "planarfigure.hover.line.color"))
    {
      node->GetColor(m_AnnotationColor[PF_HOVER], NULL, "color");
    }
  }

  // Set selected color and opacity
  node->GetColor(m_LineColor[PF_SELECTED], NULL, "planarfigure.selected.line.color");
  node->GetFloatProperty("planarfigure.selected.line.opacity", m_LineOpacity[PF_SELECTED]);
  node->GetColor(m_OutlineColor[PF_SELECTED], NULL, "planarfigure.selected.outline.color");
  node->GetFloatProperty("planarfigure.selected.outline.opacity", m_OutlineOpacity[PF_SELECTED]);
  node->GetColor(m_HelperlineColor[PF_SELECTED], NULL, "planarfigure.selected.helperline.color");
  node->GetFloatProperty("planarfigure.selected.helperline.opacity", m_HelperlineOpacity[PF_SELECTED]);
  node->GetColor(m_MarkerlineColor[PF_SELECTED], NULL, "planarfigure.selected.markerline.color");
  node->GetFloatProperty("planarfigure.selected.markerline.opacity", m_MarkerlineOpacity[PF_SELECTED]);
  node->GetColor(m_MarkerColor[PF_SELECTED], NULL, "planarfigure.selected.marker.color");
  node->GetFloatProperty("planarfigure.selected.marker.opacity", m_MarkerOpacity[PF_SELECTED]);
  if (!node->GetColor(m_AnnotationColor[PF_SELECTED], NULL, "planarfigure.selected.annotation.color"))
  {
    if (!node->GetColor(m_AnnotationColor[PF_SELECTED], NULL, "planarfigure.selected.line.color"))
    {
      node->GetColor(m_AnnotationColor[PF_SELECTED], NULL, "color");
    }
  }

  // adapt opacity values to global "opacity" property
  for (unsigned int i = 0; i < PF_COUNT; ++i)
  {
    m_LineOpacity[i] *= globalOpacity;
    m_OutlineOpacity[i] *= globalOpacity;
    m_HelperlineOpacity[i] *= globalOpacity;
    m_MarkerlineOpacity[i] *= globalOpacity;
    m_MarkerOpacity[i] *= globalOpacity;
  }
}

void mitk::PlanarFigureMapper2D::OnNodeModified()
{
  m_NodeModified = true;
}

void mitk::PlanarFigureMapper2D::SetDefaultProperties(mitk::DataNode *node,
                                                      mitk::BaseRenderer *renderer,
                                                      bool overwrite)
{
  node->AddProperty("visible", mitk::BoolProperty::New(true), renderer, overwrite);

  // node->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true));
  node->AddProperty("planarfigure.isextendable", mitk::BoolProperty::New(false));
  // node->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) );
  node->AddProperty("planarfigure.drawoutline", mitk::BoolProperty::New(false));
  // node->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(true) );
  node->AddProperty("planarfigure.drawshadow", mitk::BoolProperty::New(true));
  node->AddProperty("planarfigure.drawcontrolpoints", mitk::BoolProperty::New(true));
  node->AddProperty("planarfigure.drawname", mitk::BoolProperty::New(true));
  node->AddProperty("planarfigure.drawdashed", mitk::BoolProperty::New(false));
  node->AddProperty("planarfigure.helperline.drawdashed", mitk::BoolProperty::New(false));

  node->AddProperty("planarfigure.annotations.font.family", mitk::StringProperty::New("Arial"));
  node->AddProperty("planarfigure.annotations.font.bold", mitk::BoolProperty::New(false));
  node->AddProperty("planarfigure.annotations.font.italic", mitk::BoolProperty::New(false));
  node->AddProperty("planarfigure.annotations.font.size", mitk::IntProperty::New(12));

  node->AddProperty("planarfigure.line.width", mitk::FloatProperty::New(2.0));
  node->AddProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0));
  node->AddProperty("planarfigure.outline.width", mitk::FloatProperty::New(2.0));
  node->AddProperty("planarfigure.helperline.width", mitk::FloatProperty::New(1.0));

  node->AddProperty("planarfigure.default.line.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.default.outline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.default.helperline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.default.markerline.color", mitk::ColorProperty::New(1.0, 1.0, 1.0));
  node->AddProperty("planarfigure.default.markerline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.default.marker.color", mitk::ColorProperty::New(1.0, 1.0, 1.0));
  node->AddProperty("planarfigure.default.marker.opacity", mitk::FloatProperty::New(1.0));

  node->AddProperty("planarfigure.hover.line.color", mitk::ColorProperty::New(0.0, 1.0, 0.0));
  node->AddProperty("planarfigure.hover.line.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.hover.outline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0));
  node->AddProperty("planarfigure.hover.outline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.hover.helperline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0));
  node->AddProperty("planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.hover.markerline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0));
  node->AddProperty("planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.hover.marker.color", mitk::ColorProperty::New(0.0, 1.0, 0.0));
  node->AddProperty("planarfigure.hover.marker.opacity", mitk::FloatProperty::New(1.0));

  node->AddProperty("planarfigure.selected.line.color", mitk::ColorProperty::New(1.0, 0.0, 0.0));
  node->AddProperty("planarfigure.selected.line.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0));
  node->AddProperty("planarfigure.selected.outline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0));
  node->AddProperty("planarfigure.selected.helperline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0));
  node->AddProperty("planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(1.0));
  node->AddProperty("planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0, 0.0, 0.0));
  node->AddProperty("planarfigure.selected.marker.opacity", mitk::FloatProperty::New(1.0));
}

void mitk::PlanarFigureMapper2D::RenderControlPoints(const mitk::PlanarFigure *planarFigure,
                                                     const PlanarFigureDisplayMode lineDisplayMode,
                                                     const mitk::PlaneGeometry *planarFigurePlaneGeometry,
                                                     const mitk::PlaneGeometry *rendererPlaneGeometry,
                                                     mitk::BaseRenderer *renderer)
{
  bool isEditable = true;
  m_DataNode->GetBoolProperty("planarfigure.iseditable", isEditable);

  PlanarFigureDisplayMode pointDisplayMode = PF_DEFAULT;

  const unsigned int selectedControlPointsIdx = (unsigned int)planarFigure->GetSelectedControlPoint();
  const unsigned int numberOfControlPoints = planarFigure->GetNumberOfControlPoints();
  // Draw markers at control points (selected control point will be colored)
  for (unsigned int i = 0; i < numberOfControlPoints; ++i)
  {
    // Only if planar figure is marked as editable: display markers (control points) in a
    // different style if mouse is over them or they are selected
    if (isEditable)
    {
      if (i == selectedControlPointsIdx)
      {
        pointDisplayMode = PF_SELECTED;
      }
      else if (m_IsHovering && isEditable)
      {
        pointDisplayMode = PF_HOVER;
      }
    }

    if (m_MarkerOpacity[pointDisplayMode] == 0 && m_MarkerlineOpacity[pointDisplayMode] == 0)
    {
      continue;
    }

    if (m_DrawOutline)
    {
      // draw outlines for markers as well
      // linewidth for the contour is only half, as full width looks
      // much too thick!
      this->DrawMarker(planarFigure->GetControlPoint(i),
                       m_OutlineColor[lineDisplayMode],
                       m_MarkerlineOpacity[pointDisplayMode],
                       m_OutlineColor[lineDisplayMode],
                       m_MarkerOpacity[pointDisplayMode],
                       m_OutlineWidth / 2,
                       m_ControlPointShape,
                       planarFigurePlaneGeometry,
                       rendererPlaneGeometry,
                       renderer);
    }

    this->DrawMarker(planarFigure->GetControlPoint(i),
                     m_MarkerlineColor[pointDisplayMode],
                     m_MarkerlineOpacity[pointDisplayMode],
                     m_MarkerColor[pointDisplayMode],
                     m_MarkerOpacity[pointDisplayMode],
                     m_LineWidth,
                     m_ControlPointShape,
                     planarFigurePlaneGeometry,
                     rendererPlaneGeometry,
                     renderer);
  }

  if (planarFigure->IsPreviewControlPointVisible())
  {
    this->DrawMarker(planarFigure->GetPreviewControlPoint(),
                     m_MarkerlineColor[PF_HOVER],
                     m_MarkerlineOpacity[PF_HOVER],
                     m_MarkerColor[PF_HOVER],
                     m_MarkerOpacity[PF_HOVER],
                     m_LineWidth,
                     m_ControlPointShape,
                     planarFigurePlaneGeometry,
                     rendererPlaneGeometry,
                     renderer);
  }
}

void mitk::PlanarFigureMapper2D::RenderAnnotations(mitk::BaseRenderer *renderer,
                                                   const std::string name,
                                                   const mitk::Point2D anchorPoint,
                                                   float globalOpacity,
                                                   const PlanarFigureDisplayMode lineDisplayMode,
                                                   double &annotationOffset)
{
  if (anchorPoint[0] < mitk::eps || anchorPoint[1] < mitk::eps)
  {
    return;
  }

  m_AnnotationAnnotation->SetText(name);
  m_AnnotationAnnotation->SetColor(m_AnnotationColor[lineDisplayMode][0],
                                m_AnnotationColor[lineDisplayMode][1],
                                m_AnnotationColor[lineDisplayMode][2]);
  m_AnnotationAnnotation->SetOpacity(globalOpacity);
  m_AnnotationAnnotation->SetFontSize(m_AnnotationSize * m_DevicePixelRatio);
  m_AnnotationAnnotation->SetBoolProperty("drawShadow", m_AnnotationsShadow);
  m_AnnotationAnnotation->SetVisibility(true);
  m_AnnotationAnnotation->SetStringProperty("font.family", m_AnnotationFontFamily);
  m_AnnotationAnnotation->SetBoolProperty("font.bold", m_DrawAnnotationBold);
  m_AnnotationAnnotation->SetBoolProperty("font.italic", m_DrawAnnotationItalic);

  mitk::Point2D offset;
  offset.Fill(5);

  mitk::Point2D scaledAnchorPoint;
  scaledAnchorPoint[0] = anchorPoint[0] * m_DevicePixelRatio;
  scaledAnchorPoint[1] = anchorPoint[1] * m_DevicePixelRatio;

  offset[0] = offset[0] * m_DevicePixelRatio;
  offset[1] = offset[1] * m_DevicePixelRatio;

  m_AnnotationAnnotation->SetPosition2D(scaledAnchorPoint);
  m_AnnotationAnnotation->SetOffsetVector(offset);

  m_AnnotationAnnotation->Update(renderer);
  m_AnnotationAnnotation->Paint(renderer);
  annotationOffset -= 15.0;
  //  annotationOffset -= m_AnnotationAnnotation->GetBoundsOnDisplay( renderer ).Size[1];
}

void mitk::PlanarFigureMapper2D::RenderQuantities(const mitk::PlanarFigure *planarFigure,
                                                  mitk::BaseRenderer *renderer,
                                                  const mitk::Point2D anchorPoint,
                                                  double &annotationOffset,
                                                  float globalOpacity,
                                                  const PlanarFigureDisplayMode lineDisplayMode)
{
  if (anchorPoint[0] < mitk::eps || anchorPoint[1] < mitk::eps)
  {
    return;
  }

  std::stringstream quantityString;
  quantityString.setf(ios::fixed, ios::floatfield);
  quantityString.precision(1);

  bool firstActiveFeature = true;
  for (unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i)
  {
    if (planarFigure->IsFeatureActive(i) && planarFigure->IsFeatureVisible(i))
    {
      if (!firstActiveFeature)
      {
        quantityString << " x ";
      }
      quantityString << planarFigure->GetQuantity(i) << " ";
      quantityString << planarFigure->GetFeatureUnit(i);
      firstActiveFeature = false;
    }
  }

  m_QuantityAnnotation->SetColor(m_AnnotationColor[lineDisplayMode][0],
                              m_AnnotationColor[lineDisplayMode][1],
                              m_AnnotationColor[lineDisplayMode][2]);

  m_QuantityAnnotation->SetOpacity(globalOpacity);
  m_QuantityAnnotation->SetFontSize(m_AnnotationSize * m_DevicePixelRatio);
  m_QuantityAnnotation->SetBoolProperty("drawShadow", m_DrawShadow);
  m_QuantityAnnotation->SetVisibility(true);

  m_AnnotationAnnotation->SetStringProperty("font.family", m_AnnotationFontFamily);
  m_AnnotationAnnotation->SetBoolProperty("font.bold", m_DrawAnnotationBold);
  m_AnnotationAnnotation->SetBoolProperty("font.italic", m_DrawAnnotationItalic);

  m_QuantityAnnotation->SetText(quantityString.str().c_str());
  mitk::Point2D offset;
  offset.Fill(5);
  offset[1] += annotationOffset;

  mitk::Point2D scaledAnchorPoint;
  scaledAnchorPoint[0] = anchorPoint[0] * m_DevicePixelRatio;
  scaledAnchorPoint[1] = anchorPoint[1] * m_DevicePixelRatio;

  offset[0] = offset[0] * m_DevicePixelRatio;
  offset[1] = offset[1] * m_DevicePixelRatio;

  m_QuantityAnnotation->SetPosition2D(scaledAnchorPoint);
  m_QuantityAnnotation->SetOffsetVector(offset);

  m_QuantityAnnotation->Update(renderer);
  m_QuantityAnnotation->Paint(renderer);
  //  annotationOffset -= m_QuantityAnnotation->GetBoundsOnDisplay( renderer ).Size[1];
  annotationOffset -= 15.0;
}

void mitk::PlanarFigureMapper2D::RenderLines(const PlanarFigureDisplayMode lineDisplayMode,
                                             mitk::PlanarFigure *planarFigure,
                                             mitk::Point2D &anchorPoint,
                                             const mitk::PlaneGeometry *planarFigurePlaneGeometry,
                                             const mitk::PlaneGeometry *rendererPlaneGeometry,
                                             const mitk::BaseRenderer *renderer)
{
  glLineStipple(1, 0x00FF);

  // If we want to draw an outline, we do it here
  if (m_DrawOutline)
  {
    const float *color = m_OutlineColor[lineDisplayMode];
    const float opacity = m_OutlineOpacity[lineDisplayMode];

    // convert to a float array that also contains opacity, faster GL
    float *colorVector = new float[4];
    colorVector[0] = color[0];
    colorVector[1] = color[1];
    colorVector[2] = color[2];
    colorVector[3] = opacity;

    // set the color and opacity here as it is common for all outlines
    glColor4fv(colorVector);
    glLineWidth(m_OutlineWidth);

    if (m_DrawDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw the outline for all polylines if requested
    this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    glLineWidth(m_HelperlineWidth);

    if (m_DrawHelperDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw the outline for all helper objects if requested
    this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    // cleanup
    delete[] colorVector;
  }

  // If we want to draw a shadow, we do it here
  if (m_DrawShadow)
  {
    // determine the shadow opacity
    const float opacity = m_OutlineOpacity[lineDisplayMode];
    float shadowOpacity = 0.0f;
    if (opacity > 0.2f)
      shadowOpacity = opacity - 0.2f;

    // convert to a float array that also contains opacity, faster GL
    float *shadow = new float[4];
    shadow[0] = 0;
    shadow[1] = 0;
    shadow[2] = 0;
    shadow[3] = shadowOpacity;

    // set the color and opacity here as it is common for all shadows
    glColor4fv(shadow);
    glLineWidth(m_OutlineWidth * m_ShadowWidthFactor);

    if (m_DrawDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw the outline for all polylines if requested
    this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    glLineWidth(m_HelperlineWidth);

    if (m_DrawHelperDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw the outline for all helper objects if requested
    this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    // cleanup
    delete[] shadow;
  }

  // set this in brackets to avoid duplicate variables in the same scope
  {
    const float *color = m_LineColor[lineDisplayMode];
    const float opacity = m_LineOpacity[lineDisplayMode];

    // convert to a float array that also contains opacity, faster GL
    float *colorVector = new float[4];
    colorVector[0] = color[0];
    colorVector[1] = color[1];
    colorVector[2] = color[2];
    colorVector[3] = opacity;

    // set the color and opacity here as it is common for all mainlines
    glColor4fv(colorVector);
    glLineWidth(m_LineWidth);

    if (m_DrawDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw the main line for all polylines
    this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    const float *helperColor = m_HelperlineColor[lineDisplayMode];
    const float helperOpacity = m_HelperlineOpacity[lineDisplayMode];
    // convert to a float array that also contains opacity, faster GL
    float *helperColorVector = new float[4];
    helperColorVector[0] = helperColor[0];
    helperColorVector[1] = helperColor[1];
    helperColorVector[2] = helperColor[2];
    helperColorVector[3] = helperOpacity;

    // we only set the color for the helperlines as the linewidth is unchanged
    glColor4fv(helperColorVector);

    glLineWidth(m_HelperlineWidth);

    if (m_DrawHelperDashed)
      glEnable(GL_LINE_STIPPLE);
    else
      glDisable(GL_LINE_STIPPLE);

    // Draw helper objects
    this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer);

    // cleanup
    delete[] colorVector;
    delete[] helperColorVector;
  }

  if (m_DrawDashed || m_DrawHelperDashed)
    glDisable(GL_LINE_STIPPLE);
}


text:
swinden
=======

Website for renting out our apartment. Test


text:
set(_compiler_id_pp_test "defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)")

set(_compiler_id_version_compute "
#if defined(__VISUALDSPVERSION__)
  /* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__VISUALDSPVERSION__>>24)
# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__VISUALDSPVERSION__>>16 & 0xFF)
# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__VISUALDSPVERSION__>>8  & 0xFF)
#endif")


text:
module Gitlab
  module CycleAnalytics
    module BaseQuery
      include MetricsTables
      include Gitlab::Database::Median
      include Gitlab::Database::DateTime

      private

      def base_query
        @base_query ||= stage_query(@project.id) # rubocop:disable Gitlab/ModuleWithInstanceVariables
      end

      def stage_query(project_ids)
        query = mr_closing_issues_table.join(issue_table).on(issue_table[:id].eq(mr_closing_issues_table[:issue_id]))
          .join(issue_metrics_table).on(issue_table[:id].eq(issue_metrics_table[:issue_id]))
          .project(issue_table[:project_id].as("project_id"))
          .where(issue_table[:project_id].in(project_ids))
          .where(issue_table[:created_at].gteq(@options[:from])) # rubocop:disable Gitlab/ModuleWithInstanceVariables

        # Load merge_requests
        query = query.join(mr_table, Arel::Nodes::OuterJoin)
          .on(mr_table[:id].eq(mr_closing_issues_table[:merge_request_id]))
          .join(mr_metrics_table)
          .on(mr_table[:id].eq(mr_metrics_table[:merge_request_id]))

        query
      end
    end
  end
end


text:
package com.astoev.cave.survey.service.imp;

import static com.astoev.cave.survey.model.Option.CODE_AZIMUTH_UNITS;
import static com.astoev.cave.survey.model.Option.CODE_DISTANCE_UNITS;
import static com.astoev.cave.survey.model.Option.CODE_SLOPE_UNITS;

import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;

import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.R;
import com.astoev.cave.survey.activity.UIUtilities;
import com.astoev.cave.survey.model.Gallery;
import com.astoev.cave.survey.model.Leg;
import com.astoev.cave.survey.model.Location;
import com.astoev.cave.survey.model.Note;
import com.astoev.cave.survey.model.Point;
import com.astoev.cave.survey.model.Project;
import com.astoev.cave.survey.model.Vector;
import com.astoev.cave.survey.service.Options;
import com.astoev.cave.survey.service.Workspace;
import com.astoev.cave.survey.service.export.excel.ExcelExport;
import com.astoev.cave.survey.util.ConfigUtil;
import com.astoev.cave.survey.util.DaoUtil;
import com.astoev.cave.survey.util.GalleryUtil;
import com.astoev.cave.survey.util.LocationUtil;
import com.astoev.cave.survey.util.PointUtil;
import com.astoev.cave.survey.util.StreamUtil;
import com.astoev.cave.survey.util.StringUtils;
import com.j256.ormlite.misc.TransactionManager;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

/**
 * Created by astoev on 6/15/16.
 */
public class ExcelImport {

    public static Object importExcelFile(Uri aPath, @NonNull final Project aProject) throws SQLException, IOException {

        Log.i(Constants.LOG_TAG_SERVICE, "Requested to import " + aPath + " as " + aProject.getName());

        // load
        final ProjectData data = loadProjectData(aPath);

        // no errors while reading, start creating as atomic operation
        return TransactionManager.callInTransaction(Workspace.getCurrentInstance().getDBHelper().getConnectionSource(), new Callable() {
            @Override
            public Object call() throws Exception {

                // project config
                updateProjectConfig(data);

                // project data
                Set<Leg> lastMiddleLegs = new HashSet<>();
                int rowCounter = 1;
                for (LegData leg : data.getLegs()) {
                    Log.i(Constants.LOG_TAG_SERVICE, "Processing record " + rowCounter ++);

                    // ensure gallery exists
                    Gallery fromGallery = getOrInitializeGallery(aProject, leg.getFromGallery());
                    Gallery toGallery = getOrInitializeGallery(aProject, leg.getToGallery());

                    if (leg.isMiddlePoint()) {

                        String fromRealName = PointUtil.getMiddleFromName(leg.getFromPoint());
                        String toRealName = PointUtil.getMiddleToName(leg.getToPoint());

                        if (fromRealName.equals(leg.getFromPoint())) {

                            lastMiddleLegs.clear();
                            // actual leg
                            Log.i(Constants.LOG_TAG_SERVICE, "Creating leg for middle " + leg.getFromGallery() + leg.getFromPoint()
                                    + " -> " + leg.getToGallery() + leg.getToPoint());

                            Point from = getOrInitializePoint(aProject, fromGallery, fromRealName);
                            Point to = getOrInitializePoint(aProject, toGallery, toRealName);

                            Leg fullLeg = DaoUtil.getLegByFromToPointId(toGallery, from, to);
                            if (fullLeg == null) {
                                Log.i(Constants.LOG_TAG_SERVICE, "Creating the full leg ");
                                fullLeg = new Leg(from, to, aProject, toGallery.getId());
                                fullLeg.setDistance(leg.getLength()); // leg will be updated later
                                fullLeg.setAzimuth(leg.getAzimuth());
                                fullLeg.setSlope(leg.getSlope());
                                fullLeg.setTop(leg.getUp());
                                fullLeg.setDown(leg.getDown());
                                fullLeg.setLeft(leg.getLeft());
                                fullLeg.setRight(leg.getRight());

                                Workspace.getCurrentInstance().getDBHelper().getLegDao().create(fullLeg);
                            }
                        } else {
                            // regular middle point
                            Log.i(Constants.LOG_TAG_SERVICE, "Middle " + leg.getFromGallery() + leg.getFromPoint()
                                    + " -> " + leg.getToGallery() + leg.getToPoint());

                            Point from = getOrInitializePoint(aProject, fromGallery, fromRealName);
                            Point to = getOrInitializePoint(aProject, toGallery, toRealName);

                            // create the leg, real length will be updated later
                            Leg middleLeg = new Leg(from, to, fromGallery.getProject(), toGallery.getId());
                            middleLeg.setMiddlePointDistance(PointUtil.getMiddleLength(leg.getFromPoint()));
                            middleLeg.setAzimuth(leg.getAzimuth());
                            middleLeg.setSlope(leg.getSlope());
                            middleLeg.setTop(leg.getUp());
                            middleLeg.setDown(leg.getDown());
                            middleLeg.setLeft(leg.getLeft());
                            middleLeg.setRight(leg.getRight());
                            Workspace.getCurrentInstance().getDBHelper().getLegDao().create(middleLeg);
                            lastMiddleLegs.add(middleLeg);

                            if (toRealName.equals(leg.getToPoint())) {

                                Log.i(Constants.LOG_TAG_SERVICE, "Last middle, adjusting lengths");

                                // apply actual leg distance
                                Leg fullLeg = DaoUtil.getLegByFromToPointId(toGallery, from, to);
                                Float actualLegDistance = leg.getLength() + PointUtil.getMiddleLength(leg.getFromPoint());
                                fullLeg.setDistance(actualLegDistance);
                                Workspace.getCurrentInstance().getDBHelper().getLegDao().update(fullLeg);

                                // all middle points have no proper distance
                                for (Leg l : lastMiddleLegs) {
                                    l.setDistance(actualLegDistance);
                                    Workspace.getCurrentInstance().getDBHelper().getLegDao().update(l);
                                }
                            }
                        }

                    } else if (leg.isVector()) {
                        Log.i(Constants.LOG_TAG_SERVICE, "Vector " + leg.getFromGallery() + leg.getFromPoint() + " -> " + leg.getNote());

                        // plain legs
                        Point from = getOrInitializePoint(aProject, fromGallery, leg.getFromPoint());

                        Vector vector = new Vector();
                        vector.setDistance(leg.getLength());
                        vector.setAzimuth(leg.getAzimuth());
                        vector.setSlope(leg.getSlope());
                        vector.setPoint(from);
                        vector.setGalleryId(fromGallery.getId());
                        DaoUtil.saveVector(vector);
                    } else {

                        Log.i(Constants.LOG_TAG_SERVICE, "Leg " +  leg.getFromGallery() + leg.getFromPoint() + " -> "
                                + leg.getToGallery() + leg.getToPoint() + " : " + leg.getLength());

                        // plain legs
                        Point from = getOrInitializePoint(aProject, fromGallery, leg.getFromPoint());
                        Point to = getOrInitializePoint(aProject, toGallery, leg.getToPoint());

                        Leg dbLeg = DaoUtil.getLegByFromToPointId(toGallery, from, to);
                        if (dbLeg == null) {
                            // not the first leg already created with the project
                            Log.i(Constants.LOG_TAG_SERVICE, "Creating leg");
                            dbLeg = new Leg(from, to, aProject, toGallery.getId());
                        }
                        dbLeg.setDistance(leg.getLength());
                        dbLeg.setAzimuth(leg.getAzimuth());
                        dbLeg.setSlope(leg.getSlope());
                        dbLeg.setTop(leg.getUp());
                        dbLeg.setDown(leg.getDown());
                        dbLeg.setLeft(leg.getLeft());
                        dbLeg.setRight(leg.getRight());

                        Workspace.getCurrentInstance().getDBHelper().getLegDao().createOrUpdate(dbLeg);

                        if (StringUtils.isNotEmpty(leg.getNote())) {
                            Note n = new Note(leg.getNote());
                            n.setPoint(from);
                            n.setGalleryId(fromGallery.getId());
                            Workspace.getCurrentInstance().getDBHelper().getNoteDao().create(n);
                        }

                        if (leg.getLat() != null && leg.getLon() != null) {
                            Log.i(Constants.LOG_TAG_SERVICE, "Import location");
                            Location location = new Location();
                            location.setLatitude(leg.getLat());
                            location.setLongitude(leg.getLon());
                            if (leg.getAlt() != null) {
                                location.setAltitude(leg.getAlt().intValue());
                            }
                            if (leg.getAccuracy() != null) {
                                location.setAccuracy(leg.getAccuracy().intValue());
                            }
                            DaoUtil.saveLocationToPoint(from, location);
                        }
                    }

                }
                UIUtilities.showNotification(R.string.import_success);
                return null;
            }

            private Point getOrInitializePoint(Project aProject, Gallery aGallery, String aName) throws SQLException {

                // point can be already created
                Long pointId = DaoUtil.getFromPointId(aProject.getId(), aGallery, aName);
                if (pointId == null) {
                    pointId = DaoUtil.getToPointId(aProject.getId(), aGallery, aName);
                    if (pointId == null) {
                        Log.i(Constants.LOG_TAG_SERVICE, "Creating to point for " + aGallery.getName() + aName);
                        Point point = new Point();
                        point.setName(aName);
                        Workspace.getCurrentInstance().getDBHelper().getPointDao().create(point);
                        return  point;
                    }
                }
                return DaoUtil.getPoint(pointId.intValue());
            }

            private Gallery getOrInitializeGallery(Project aProject, String aGalleryName) throws SQLException {
                Gallery gallery = null;
                if (StringUtils.isNotEmpty(aGalleryName)) {
                    gallery = DaoUtil.getGallery(aProject.getId(), aGalleryName);
                            Log.i(Constants.LOG_TAG_SERVICE, "Got gallery " + gallery);
                    if (gallery == null) {
                        Log.i(Constants.LOG_TAG_SERVICE, "Creating gallery " + aGalleryName);
                        gallery = GalleryUtil.createGallery(aProject, aGalleryName);
                    }
                }
                return gallery;
            }
        });
    }

    public static ProjectData loadProjectData(Uri aPath) throws IOException {
        return loadProjectData(ConfigUtil.getContext().getContentResolver().openInputStream(aPath));
    }

    public static ProjectData loadProjectData(InputStream stream) throws IOException {
        // locate and open
        ProjectData data = new ProjectData();
        int rowNum = 1;
        try (HSSFWorkbook workbook = new HSSFWorkbook(stream)) {
            HSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            // read header
            readProjectConfig(rowIterator.next(), data);

            // load all rows
            final List<LegData> legs = data.getLegs();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                rowNum++;
                LegData leg = new LegData();
                Cell cellFrom = row.getCell(ExcelExport.CELL_FROM);
                if (cellFrom == null) {
                    Log.i(Constants.LOG_TAG_SERVICE, "End of cells");
                    break;
                }
                String from = getStringCellValue(cellFrom);
                if (StringUtils.isEmpty(from)) {
                    Log.i(Constants.LOG_TAG_SERVICE, "End of non-empty rows");
                    break;
                }
                leg.setFromGallery(PointUtil.getPointGalleryName(from));
                leg.setFromPoint(PointUtil.getPointName(from));

                Cell cellTo = row.getCell(ExcelExport.CELL_TO);
                String to = cellTo == null ? null : getStringCellValue(cellTo);
                leg.setToGallery(PointUtil.getPointGalleryName(to));
                leg.setToPoint(PointUtil.getPointName(to));
                leg.setVector(PointUtil.isVector(to));
                leg.setMiddlePoint(PointUtil.isMiddlePoint(from, to));
                leg.setLength(getNotNullFloatCellValue(row, ExcelExport.CELL_LENGHT));
                leg.setAzimuth(getNotNullFloatCellValue(row, ExcelExport.CELL_AZIMUTH));
                leg.setSlope(getNotNullFloatCellValue(row, ExcelExport.CELL_SLOPE));

                leg.setUp(getNotNullFloatCellValue(row, ExcelExport.CELL_UP));
                leg.setDown(getNotNullFloatCellValue(row, ExcelExport.CELL_DOWN));
                leg.setLeft(getNotNullFloatCellValue(row, ExcelExport.CELL_LEFT));
                leg.setRight(getNotNullFloatCellValue(row, ExcelExport.CELL_RIGHT));

                Cell noteCell = row.getCell(ExcelExport.CELL_NOTE);
                if (noteCell != null) {
                    leg.setNote(getStringCellValue(noteCell));
                }

                Cell latCell = row.getCell(ExcelExport.CELL_LATITUDE);
                if (latCell != null) {
                    leg.setLat(LocationUtil.descriptionToValue(latCell));
                }
                Cell lonCell = row.getCell(ExcelExport.CELL_LONGITUDE);
                if (lonCell != null) {
                    leg.setLon(LocationUtil.descriptionToValue(lonCell));
                }
                Cell altCell = row.getCell(ExcelExport.CELL_ALTTITUDE);
                if (altCell != null) {
                    leg.setAlt(altCell.getNumericCellValue());
                }
                Cell accuracyCell = row.getCell(ExcelExport.CELL_ACCURACY);
                if (accuracyCell != null) {
                    leg.setAccuracy(accuracyCell.getNumericCellValue());
                }
                Cell sketcesCell = row.getCell(ExcelExport.CELL_DRAWING);
                if (sketcesCell != null) {
                    leg.setSketch(getStringCellValue(sketcesCell));
                }

                legs.add(leg);
            }

            Log.i(Constants.LOG_TAG_SERVICE, legs.size() + " records found");
            return data;
        } catch (Exception e) {
            Log.e(Constants.LOG_TAG_SERVICE, "Error during import on row " + rowNum, e);
            String errorMessage = ConfigUtil.getContext().getString(R.string.settings_import_error,
                    rowNum, e.getClass().getSimpleName(), e.getMessage());
            UIUtilities.showNotification(errorMessage);
        } finally {
            StreamUtil.closeQuietly(stream);
        }
        return null;
    }

    public static void readProjectConfig(Row aRow, ProjectData aProjectData) {

        // units from the file
        Map<String, String> options = aProjectData.getOptions();
        options.put(CODE_DISTANCE_UNITS, getUnitFromHeaderCell(aRow, ExcelExport.CELL_LENGHT));
        options.put(CODE_AZIMUTH_UNITS, getUnitFromHeaderCell(aRow, ExcelExport.CELL_AZIMUTH));
        options.put(CODE_SLOPE_UNITS, getUnitFromHeaderCell(aRow, ExcelExport.CELL_SLOPE));
    }

    public static void updateProjectConfig(ProjectData aProjectData) throws SQLException {

        Map<String, String> options = aProjectData.getOptions();
        Options.updateOption(CODE_DISTANCE_UNITS, options.get(CODE_DISTANCE_UNITS));
        Options.updateOption(CODE_AZIMUTH_UNITS, options.get(CODE_AZIMUTH_UNITS));
        Options.updateOption(CODE_SLOPE_UNITS, options.get(CODE_SLOPE_UNITS));
    }

    private static String getUnitFromHeaderCell(@NonNull Row aRow, int aCellIndex) {
        Cell header = aRow.getCell(aCellIndex);
        String headerValue = header.getStringCellValue();
        String units = headerValue.substring(
                headerValue.indexOf(ExcelExport.MEASUREMENT_UNIT_DELIMITER) + ExcelExport.MEASUREMENT_UNIT_DELIMITER.length());
        //  TODO no validation
        return  units;
    }

    private static Float getNotNullFloatCellValue(@NonNull Row row, int index) {
        Cell cell = row.getCell(index);
        if (cell != null) {
            String val = getStringCellValue(cell);
            if (StringUtils.isNotEmpty(val)) {
                return Float.parseFloat(val.replace(',', '.'));
            }
        }
        return  null;
    }

    private static String getStringCellValue(Cell cell) {
        if (cell != null) {
            DataFormatter formatter = new DataFormatter();
            return formatter.formatCellValue(cell);
        }
        return  null;
    }

}


text:
using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using log4net;

using Commanigy.Iquomi.Data;

#endregion

namespace Commanigy.Iquomi.Web {
	/// <summary>
	///
	/// </summary>
	public partial class ServiceRoleTemplatesPage : Commanigy.Iquomi.Web.WebPage {
		private static readonly ILog log = LogManager.GetLogger("WebSite");
		protected UiService service;

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			service = new UiService();
			service.Id = GetInt32("Service.Id");
			service.AuthorId = UiAuthor.Get().Id;
			service.DbFindByAuthorId();
		}

		protected void Page_Load(object sender, System.EventArgs e) {

			SiteMapNode n = SiteMap.CurrentNode;
			n.Url = this.Request.Url.ToString();

			if (!Page.IsPostBack) {
				ServiceTab.DataItem = service;
			}
		}

		protected void AddRoleButton_Click(object sender, System.EventArgs e) {
			this.Redirect("service.role_template.create.aspx", new object[] { service.Id });
		}

		protected void DeleteRoleButton_Click(object sender, System.EventArgs e) {
			foreach (GridViewRow r in GridView1.Rows) {
				CheckBox a = (r.FindControl("RowChecked") as CheckBox);
				if (a.Checked) {
					string rowId = (r.FindControl("RowId") as Literal).Text;
					int id = Convert.ToInt32(rowId);

					DbRoleTemplate d = new DbRoleTemplate();
					d.Id = id;
					d.DbDelete();
				}
			}

			GridView1.DataBind();
		}

		protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
			e.InputParameters["serviceId"] = GetInt32("Service.Id");
		}

	}
}