text:
package com.swfarm.biz.chain.srv;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.swfarm.biz.chain.bo.ShippingMethod;
import com.swfarm.biz.chain.bo.ywapi.ExpressTypeXmlBuilder;
import com.swfarm.biz.chain.utils.PdfUtils;
import com.swfarm.biz.chain.web.ChainFrontHelper;
import com.swfarm.biz.ebay.bo.CountryMap;
import com.swfarm.biz.oa.bo.Country;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherDTO;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherItemDTO;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherListDTO;
import com.swfarm.biz.warehouse.dto.WarehouseCheckOutVoucherDTO;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.AppContext;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.DateUtils;

@SuppressWarnings("unchecked")
public class SfpyShippingOrderGenerator extends CommonShippingOrderGenerator implements ShippingOrderGenerator {
	Logger logger = Logger.getLogger(SfpyShippingOrderGenerator.class);

	private WarehouseService warehouseService = null;

	private ChainService chainService = null;

	private BarCodeGenerator barCodeGenerator;

	// 欧洲10国流向
	private static final String[] COUNTRY_EU10 = new String[] { "Belarus", "BY", "Latvia", "Poland", "Norway",
			"Ukraine", "Russian", "Sweden", "Estonia", "Finland", "Lithuania", "BY", "LV", "PL", "NO", "UA", "RU", "SE",
			"EE", "FI", "LT" };

	// 欧亚16国流向
	private static final String[] COUNTRY_ASIA16 = new String[] { "Philippines", "PH", "Indonesia", "ID", "Malaysia",
			"MY", "New Zealand", "NZ", "South Korea", "KR", "Thailand", "TH", "Sri Lanka", "LK", "India", "IN",
			"Pakistan", "PK", "Brazil", "BR", "Vietnam", "VN", "Cambodia", "KH", "Brunei Darussalam", "BN", "Greenland",
			"GL", "Faroe Islands", "FO", "MALTA", "MT" };

	private static final Map<String, String> PY_DEST_CODE = new LinkedHashMap<String, String>() {
		private static final long serialVersionUID = 3801124242820219132L;

		{

			super.put("RU", "5-EE-RU-P");
			super.put("LT", "7-EE-LT-P");
			super.put("EE", "9-EE-EE-P");
			super.put("LV", "11-EE-LV-P");
			super.put("FI", "13-EE-FI-P");
			super.put("SE", "15-EE-SE-P");
			super.put("NO", "17-EE-NO-P");
			super.put("BY", "19-EE-BY-P");
			super.put("UA", "21-EE-UA-P");
			super.put("PL", "23-EE-PL-P");

		}
	};

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public BarCodeGenerator getBarCodeGenerator() {
		if (this.barCodeGenerator == null) {
			this.barCodeGenerator = new BarCodeGenerator();
			this.barCodeGenerator.setWarehouseService(warehouseService);
		}
		return this.barCodeGenerator;
	}

	public ByteArrayOutputStream generateShippingOrders(Long apvlId) {
		AllocationProductVoucherList apvl = warehouseService.findAllocationProductVoucherList(apvlId);
		AllocationProductVoucherListDTO apvlDTO = ChainFrontHelper.getApvlDTOFromApvl(apvl);
		return generateShippingOrders(apvlDTO);
	}

	public ByteArrayOutputStream generateShippingOrders(AllocationProductVoucherListDTO apvlDTO) {
		BarCodeGenerator barCodeGenerator = new BarCodeGenerator();
		barCodeGenerator.setWarehouseService(warehouseService);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(100d);
			float height = PdfUtils.mmToPound(100d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(2, 2, 2, 2);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte canvas = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			this.generateFrontCover(apvlDTO, document, canvas, baseFont);
			document.newPage();
			if (AppContext.getContextData().getPayload() instanceof Boolean) {
				Boolean includecheckoutvoucher = (Boolean) AppContext.getContextData().getPayload();
				if (includecheckoutvoucher != null && includecheckoutvoucher == true) {
					WarehouseCheckOutVoucherDTO wcovDTO = this.chainService
							.generateTransitWarehouseCheckOutVoucherDTOByApvl(apvlDTO.getApvlId());
					this.generateCheckoutVoucherTable(apvlDTO.getApvlNo(), wcovDTO, document,
							canvas, baseFont);
					document.newPage();
				}
			}
			int currentIndex = 1;
			List apvDTOs = apvlDTO.getAllocationProductVoucherDTOs();
			if (CollectionUtils.isNotEmpty(apvDTOs)) {
				int totalIndex = apvDTOs.size();
				for (Iterator apvIter = apvDTOs.iterator(); apvIter.hasNext();) {
					AllocationProductVoucherDTO apvDTO = (AllocationProductVoucherDTO) apvIter.next();
					List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
					if (!CollectionUtils.isEmpty(apviDTOs)) {
						generateShippingInfoTable(apvDTO, currentIndex + "/" + totalIndex, document, canvas, baseFont);
						document.newPage();
						if (ChainFrontHelper.getIsGenerateApvTable() == true) {
							generateAllocationProductVoucherTable(apvDTO, document, baseFont, canvas);
							document.newPage();
						}
						currentIndex++;
					}
				}
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public ByteArrayOutputStream generateShippingOrder(Long apvId) {
		AllocationProductVoucher apv = warehouseService.findAllocationProductVoucher(apvId);
		AllocationProductVoucherDTO apvDTO = ChainFrontHelper.getApvDTOFromApv(apv);
		return generateShippingOrder(apvDTO);
	}

	public ByteArrayOutputStream generateShippingOrder(AllocationProductVoucherDTO apvDTO) {
		BarCodeGenerator barCodeGenerator = new BarCodeGenerator();
		barCodeGenerator.setWarehouseService(warehouseService);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(100d);
			float height = PdfUtils.mmToPound(100d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(2, 2, 2, 2);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte canvas = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
			if (!CollectionUtils.isEmpty(apviDTOs)) {
				generateShippingInfoTable(apvDTO, "1/1", document, canvas, baseFont);
				if (ChainFrontHelper.checkGenerateApvTableEligible(apvDTO) == true) {
					document.newPage();
					generateAllocationProductVoucherTable(apvDTO, document, baseFont, canvas);
					document.newPage();
				}
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public void generateShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
		if (CollectionUtils.isNotEmpty(apvDTO.getAllocationProductVoucherItemDTOs())) {
			Country country = CountryMap.getCountry(apvDTO.getBuyerCountry());
			if (country != null) {
				if ("USA".equalsIgnoreCase(country.getName()) || "US".equalsIgnoreCase(country.getName())) {
					this.generateUsShippingInfoTable(apvDTO, pageIndex, document, canvas, baseFont);
				} else if ("Australia".equalsIgnoreCase(country.getName())
						|| "AU".equalsIgnoreCase(country.getName())) {
					this.generateAuShippingInfoTable(apvDTO, pageIndex, document, canvas, baseFont);
				} else if (ArrayUtils.contains(COUNTRY_EU10, country.getName())
						|| ArrayUtils.contains(COUNTRY_EU10, country.getShortName())) { // 欧洲10国
					this.generateEuShippingInfoTable(apvDTO, pageIndex, document, canvas, baseFont);
				} else if (ArrayUtils.contains(COUNTRY_ASIA16, country.getName())
						|| ArrayUtils.contains(COUNTRY_ASIA16, country.getShortName())) { // 亚洲16国
					this.generateAsiaShippingInfoTable(apvDTO, pageIndex, document, canvas, baseFont);
				} else { // 其他流向
					this.generateOtherShippingInfoTable(apvDTO, pageIndex, document, canvas, baseFont);
				}
			} else {
				throw new RuntimeException("系统未找到此订单对应的国家信息, 请检查[" + apvDTO.getApvNo() + "]");
			}
		}
	}

	private void generateOtherShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
		// TODO Auto-generated method stub

	}

	private void generateAsiaShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
		// TODO Auto-generated method stub

	}

	private void generateAuShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
		Rectangle pageSize = document.getPageSize();
		float width = pageSize.getWidth();
		PdfPTable table = new PdfPTable(new float[] { 3, 2, 1 });
		table.setLockedWidth(true);
		table.setTotalWidth(width - 4);
		table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setMinimumHeight(0f);
		table.getDefaultCell().disableBorderSide(PdfPCell.TOP);
		table.getDefaultCell().disableBorderSide(PdfPCell.RIGHT);
		table.getDefaultCell().disableBorderSide(PdfPCell.BOTTOM);
		table.getDefaultCell().disableBorderSide(PdfPCell.LEFT);

		Font msyhFont = new Font(baseFont, 8, Font.NORMAL);
		String returnAddress = "If undelivered return to: SF express c/o AMS 118 denison stress Hillsdale NSW 2036";
		PdfPCell returnAddressCell = new PdfPCell(new Paragraph(returnAddress, msyhFont));
		returnAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		returnAddressCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		returnAddressCell.setBorder(0);
		table.addCell(returnAddressCell);

		Image sfLogoImg = Image.getInstance(Env.APP_REAL_PATH + "images/sflogo.png");
		sfLogoImg.setAlignment(Element.ALIGN_CENTER);
		sfLogoImg.scaleAbsolute(80, 30);
		PdfPCell myCell1 = new PdfPCell();
		myCell1.addElement(sfLogoImg);
		myCell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		myCell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		myCell1.setBorder(0);
		table.addCell(myCell1);

		msyhFont = new Font(baseFont, 14, Font.BOLD);
		StringBuffer countryCodeBuffer = new StringBuffer();
		String countryCode = CountryMap.getCountry(apvDTO.getBuyerCountry()).getShortName();
		countryCodeBuffer.append(countryCode);
		Paragraph countryCodePara = new Paragraph(countryCodeBuffer.toString(), msyhFont);
		PdfPCell countryCodeCell = new PdfPCell(countryCodePara);
		countryCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		countryCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		countryCodeCell.setBorder(0);
		table.addCell(countryCodeCell);

		PdfPCell spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		spaceCell.setBorder(0);
		table.addCell(spaceCell);

		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		PdfPCell sfgjghCell = new PdfPCell(new Paragraph("顺丰国际小包平邮", msyhFont));
		sfgjghCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		sfgjghCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		sfgjghCell.setBorder(0);
		table.addCell(sfgjghCell);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		StringBuffer buyerAddress = this.getBuyerFullAddress1(apvDTO);
		PdfPCell buyerAddressCell = new PdfPCell(new Paragraph(buyerAddress.toString(), msyhFont));
		buyerAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		buyerAddressCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		buyerAddressCell.setBorder(0);
		table.addCell(buyerAddressCell);

		spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		spaceCell.setBorder(0);
		spaceCell.setColspan(2);
		table.addCell(spaceCell);

		String shippingOrderNo = apvDTO.getShippingOrderNo();
		if (StringUtils.isEmpty(shippingOrderNo)) {
			shippingOrderNo = apvDTO.getApvNo();
		}
		if (shippingOrderNo.contains(",")) {
			String[] trackingNos = shippingOrderNo.split(",");
			shippingOrderNo = trackingNos[0];
		}
		PdfPCell shippingOrderNoCell = new PdfPCell();
		if (StringUtils.isNotEmpty(shippingOrderNo)) {
			Image sfOrderNoImage = this.getBarCodeGenerator().getShippingOrderNo(shippingOrderNo, canvas);
			int imageWidth = PdfUtils.mmToPound(60d);
			int imageHeihgt = PdfUtils.mmToPound(20d);
			sfOrderNoImage.scaleAbsolute(imageWidth, imageHeihgt);
			shippingOrderNoCell.addElement(sfOrderNoImage);
		}
		shippingOrderNoCell.setLeading(2f, 1f);
		shippingOrderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		shippingOrderNoCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		shippingOrderNoCell.setBorder(0);
		shippingOrderNoCell.setColspan(2);
		table.addCell(shippingOrderNoCell);

		Image startImg = Image.getInstance(Env.APP_REAL_PATH + "images/sfstar.png");
		startImg.setAlignment(Element.ALIGN_CENTER);
		startImg.scaleAbsolute(50, 50);
		PdfPCell startCell1 = new PdfPCell();
		startCell1.addElement(startImg);
		startCell1.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		startCell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		startCell1.setBorder(0);
		table.addCell(startCell1);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		String buyerTel = apvDTO.getBuyerMobile();
		if (StringUtils.isEmpty(buyerTel)) {
			buyerTel = apvDTO.getBuyerMobile();
		}
		PdfPCell buyerTelCell = new PdfPCell(new Paragraph("TEL:" + buyerTel + "\n" + apvDTO.getShippingOrderNo() + "\n"
				+ DateUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), msyhFont));
		buyerTelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		buyerTelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		buyerTelCell.setBorder(0);
		table.addCell(buyerTelCell);

		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		PdfPCell destCodeCell = new PdfPCell(new Paragraph(PY_DEST_CODE.get(countryCode), msyhFont));
		destCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		destCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		destCodeCell.setBorder(0);
		destCodeCell.setColspan(2);
		table.addCell(destCodeCell);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		PdfPCell productCodeCell = new PdfPCell(new Paragraph("Accecity\n" + "Ref No:" + apvDTO.getApvNo(), msyhFont));
		productCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		productCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		productCodeCell.setBorder(0);
		productCodeCell.setColspan(3);
		table.addCell(productCodeCell);

		document.add(table);
		document.newPage();
		generateCustomsDeclarationTable(apvDTO, document, canvas, baseFont);
	}

	private StringBuffer getBuyerFullAddress1(AllocationProductVoucherDTO apvDTO) {
		StringBuffer buyerInfoBuffer = new StringBuffer();
		buyerInfoBuffer.append("Deliver To:\n");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerFullname())) {
			buyerInfoBuffer.append(apvDTO.getBuyerFullname());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1()) || StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
			buyerInfoBuffer.append("\n");
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1())) {
				buyerInfoBuffer.append(apvDTO.getBuyerAddress1());
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
				buyerInfoBuffer.append(" ");
				buyerInfoBuffer.append(apvDTO.getBuyerAddress2());
			}
			buyerInfoBuffer.append("\n");
		}
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCity())) {
			sb.append(apvDTO.getBuyerCity());
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerState())) {
			sb.append(" ");
			sb.append(apvDTO.getBuyerState());
		}
		String buyerCityState = sb.toString();
		if (StringUtils.isNotEmpty(buyerCityState)) {
			buyerInfoBuffer.append(buyerCityState);
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerZip())) {
			buyerInfoBuffer.append("\n");
			buyerInfoBuffer.append(apvDTO.getBuyerZip());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
			sb = new StringBuffer();
			if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
				String originalCountry = apvDTO.getBuyerCountry();
				String mappingCountry = CountryMap.getMappingCountry(originalCountry);
				sb.append(mappingCountry);
			}
			buyerInfoBuffer.append(sb.toString().toUpperCase());
		}
		return buyerInfoBuffer;
	}

	private void generateUsShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws Exception {

		Rectangle pageSize = document.getPageSize();
		float width = pageSize.getWidth();
		PdfPTable table = new PdfPTable(new float[] { 3, 2, 1 });
		table.setLockedWidth(true);
		table.setTotalWidth(width - 4);
		table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setMinimumHeight(0f);
		table.getDefaultCell().disableBorderSide(PdfPCell.TOP);
		table.getDefaultCell().disableBorderSide(PdfPCell.RIGHT);
		table.getDefaultCell().disableBorderSide(PdfPCell.BOTTOM);
		table.getDefaultCell().disableBorderSide(PdfPCell.LEFT);

		Font msyhFont = new Font(baseFont, 8, Font.NORMAL);
		PdfPCell spaceCell = new PdfPCell();
		spaceCell.setBorder(0);
		table.addCell(spaceCell);

		Image sfLogoImg = Image.getInstance(Env.APP_REAL_PATH + "images/sflogo.png");
		sfLogoImg.setAlignment(Element.ALIGN_CENTER);
		sfLogoImg.scaleAbsolute(80, 30);
		PdfPCell myCell1 = new PdfPCell();
		myCell1.addElement(sfLogoImg);
		myCell1.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		myCell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		myCell1.setBorder(0);
		table.addCell(myCell1);

		msyhFont = new Font(baseFont, 14, Font.BOLD);
		StringBuffer countryCodeBuffer = new StringBuffer();
		String countryCode = CountryMap.getCountry(apvDTO.getBuyerCountry()).getShortName();
		countryCodeBuffer.append(countryCode);
		Paragraph countryCodePara = new Paragraph(countryCodeBuffer.toString(), msyhFont);
		PdfPCell countryCodeCell = new PdfPCell(countryCodePara);
		countryCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		countryCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		countryCodeCell.setBorder(0);
		table.addCell(countryCodeCell);

		spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		spaceCell.setBorder(0);
		table.addCell(spaceCell);

		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		PdfPCell sfgjghCell = new PdfPCell(new Paragraph("顺丰国际小包平邮", msyhFont));
		sfgjghCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		sfgjghCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		sfgjghCell.setBorder(0);
		table.addCell(sfgjghCell);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		StringBuffer buyerAddress = this.getBuyerFullAddress1(apvDTO);
		PdfPCell buyerAddressCell = new PdfPCell(new Paragraph(buyerAddress.toString(), msyhFont));
		buyerAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		buyerAddressCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		buyerAddressCell.setBorder(0);
		table.addCell(buyerAddressCell);

		spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		spaceCell.setBorder(0);
		spaceCell.setColspan(2);
		table.addCell(spaceCell);

		String shippingOrderNo = apvDTO.getShippingOrderNo();
		if (StringUtils.isEmpty(shippingOrderNo)) {
			shippingOrderNo = apvDTO.getApvNo();
		}
		if (shippingOrderNo.contains(",")) {
			String[] trackingNos = shippingOrderNo.split(",");
			shippingOrderNo = trackingNos[0];
		}
		PdfPCell shippingOrderNoCell = new PdfPCell();
		if (StringUtils.isNotEmpty(shippingOrderNo)) {
			Image sfOrderNoImage = this.getBarCodeGenerator().getShippingOrderNo(shippingOrderNo, canvas);
			int imageWidth = PdfUtils.mmToPound(60d);
			int imageHeihgt = PdfUtils.mmToPound(20d);
			sfOrderNoImage.scaleAbsolute(imageWidth, imageHeihgt);
			shippingOrderNoCell.addElement(sfOrderNoImage);
		}
		shippingOrderNoCell.setLeading(2f, 1f);
		shippingOrderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		shippingOrderNoCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		shippingOrderNoCell.setBorder(0);
		shippingOrderNoCell.setColspan(2);
		table.addCell(shippingOrderNoCell);

		Image startImg = Image.getInstance(Env.APP_REAL_PATH + "images/sfstar.png");
		startImg.setAlignment(Element.ALIGN_CENTER);
		startImg.scaleAbsolute(50, 50);
		PdfPCell startCell1 = new PdfPCell();
		startCell1.addElement(startImg);
		startCell1.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		startCell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		startCell1.setBorder(0);
		table.addCell(startCell1);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		String buyerTel = apvDTO.getBuyerMobile();
		if (StringUtils.isEmpty(buyerTel)) {
			buyerTel = apvDTO.getBuyerMobile();
		}
		PdfPCell buyerTelCell = new PdfPCell(new Paragraph("TEL:" + buyerTel + "\n" + apvDTO.getShippingOrderNo() + "\n"
				+ DateUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), msyhFont));
		buyerTelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		buyerTelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		buyerTelCell.setBorder(0);
		table.addCell(buyerTelCell);

		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		PdfPCell destCodeCell = new PdfPCell(new Paragraph(PY_DEST_CODE.get(countryCode), msyhFont));
		destCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		destCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		destCodeCell.setBorder(0);
		destCodeCell.setColspan(2);
		table.addCell(destCodeCell);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		PdfPCell productCodeCell = new PdfPCell(new Paragraph("Accecity\n" + "Ref No:" + apvDTO.getApvNo(), msyhFont));
		productCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		productCodeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		productCodeCell.setBorder(0);
		productCodeCell.setColspan(3);
		table.addCell(productCodeCell);

		document.add(table);
		document.newPage();
		generateCustomsDeclarationTable(apvDTO, document, canvas, baseFont);
	}

	private void generateEuShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws Exception {
		Rectangle pageSize = document.getPageSize();
		float width = pageSize.getWidth();
		float height = pageSize.getHeight();
		PdfPTable table = new PdfPTable(new float[] { 20, 1, 18, 1, 20 });
		table.setLockedWidth(true);
		table.setTotalWidth(width - 4);
		table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setMinimumHeight(0f);
		table.getDefaultCell().disableBorderSide(PdfPCell.TOP);
		table.getDefaultCell().disableBorderSide(PdfPCell.RIGHT);
		table.getDefaultCell().disableBorderSide(PdfPCell.BOTTOM);
		table.getDefaultCell().disableBorderSide(PdfPCell.LEFT);

		Font msyhFont = new Font(baseFont, 8, Font.NORMAL);
		StringBuffer fromAddressBuffer = new StringBuffer();
		fromAddressBuffer.append("From: " + Env.SF_JCOMPANY + "\n");
		fromAddressBuffer.append("   Forward SF-EXPRESS\n");
		fromAddressBuffer.append("   P.O. Box 7023,14002 Tallinn,\n");
		fromAddressBuffer.append("   Estonia");
		Paragraph fromAddressPara = new Paragraph(fromAddressBuffer.toString(), msyhFont);
		PdfPCell fromAddressCell = new PdfPCell(fromAddressPara);
		fromAddressCell.setMinimumHeight(12f);
		fromAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		fromAddressCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		fromAddressCell.setColspan(3);
		table.addCell(fromAddressCell);

		PdfPCell spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(spaceCell);

		StringBuffer payeBuffer = new StringBuffer();
		payeBuffer.append("POSTIMAKS\n");
		payeBuffer.append("TASUTUD TAXE\n");
		payeBuffer.append("PERÇUE ESTONIE\n");
		payeBuffer.append("No. 199");
		Paragraph payePara = new Paragraph(payeBuffer.toString(), msyhFont);
		PdfPCell payeCell = new PdfPCell(payePara);
		payeCell.setMinimumHeight(12f);
		payeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		payeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		payeCell.enableBorderSide(PdfPCell.TOP);
		payeCell.enableBorderSide(PdfPCell.RIGHT);
		payeCell.enableBorderSide(PdfPCell.BOTTOM);
		payeCell.enableBorderSide(PdfPCell.LEFT);
		table.addCell(payeCell);

		Paragraph spacePara = new Paragraph("\n", msyhFont);
		spaceCell = new PdfPCell(spacePara);
		spaceCell.setColspan(5);
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(spaceCell);

		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		StringBuffer priorityBuffer = new StringBuffer();
		priorityBuffer.append("PRIORITY");
		Paragraph priorityPara = new Paragraph(priorityBuffer.toString(), msyhFont);
		PdfPCell priorityCell = new PdfPCell(priorityPara);
		priorityCell.setMinimumHeight(50f);
		priorityCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		priorityCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.addCell(priorityCell);

		spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(spaceCell);

		msyhFont = new Font(baseFont, 8, Font.NORMAL);
		StringBuffer toBuffer = new StringBuffer();
		toBuffer.append(getBuyerFullAddress(apvDTO));
		Paragraph toPara = new Paragraph(toBuffer.toString(), msyhFont);
		PdfPCell toCell = new PdfPCell(toPara);
		toCell.setMinimumHeight(12f);
		toCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		toCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		toCell.setColspan(3);
		toCell.setRowspan(2);
		toCell.enableBorderSide(PdfPCell.TOP);
		toCell.enableBorderSide(PdfPCell.RIGHT);
		toCell.enableBorderSide(PdfPCell.BOTTOM);
		toCell.enableBorderSide(PdfPCell.LEFT);
		table.addCell(toCell);

		spaceCell = new PdfPCell();
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		spaceCell.setMinimumHeight(50f);
		spaceCell.setColspan(2);
		table.addCell(spaceCell);

		spacePara = new Paragraph("\n\n\n\n\n\n", msyhFont);
		spaceCell = new PdfPCell(spacePara);
		spaceCell.setColspan(5);
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(spaceCell);

		String sfOrderNo = apvDTO.getRefShippingOrderNo();
		if (StringUtils.isEmpty(sfOrderNo)) {
			sfOrderNo = apvDTO.getShippingOrderNo();
		}
		if (StringUtils.isEmpty(sfOrderNo)) {
			sfOrderNo = apvDTO.getApvNo();
		}
		PdfPCell sfOrderNoCell = new PdfPCell();
		if (StringUtils.isNotEmpty(sfOrderNo)) {
			Image sfOrderNoImage = this.getBarCodeGenerator().getShippingOrderNo(sfOrderNo, canvas);
			int imageWidth = PdfUtils.mmToPound(46d);
			int imageHeihgt = PdfUtils.mmToPound(11d);
			sfOrderNoImage.scaleAbsolute(imageWidth, imageHeihgt);
			sfOrderNoCell.addElement(sfOrderNoImage);
		}
		sfOrderNoCell.setLeading(2f, 1f);
		sfOrderNoCell.setPaddingLeft(20);
		sfOrderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		sfOrderNoCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		sfOrderNoCell.disableBorderSide(PdfPCell.TOP);
		sfOrderNoCell.disableBorderSide(PdfPCell.RIGHT);
		sfOrderNoCell.disableBorderSide(PdfPCell.BOTTOM);
		sfOrderNoCell.disableBorderSide(PdfPCell.LEFT);
		sfOrderNoCell.setColspan(3);
		sfOrderNoCell.setRowspan(2);
		table.addCell(sfOrderNoCell);

		spaceCell = new PdfPCell();
		spaceCell.setRowspan(2);
		spaceCell.disableBorderSide(PdfPCell.TOP);
		spaceCell.disableBorderSide(PdfPCell.RIGHT);
		spaceCell.disableBorderSide(PdfPCell.BOTTOM);
		spaceCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(spaceCell);

		PdfPCell sfLogoCell = new PdfPCell();
		Image sfOrderNoImage = this.getImage("sflogo.png");
		int imageWidth = PdfUtils.mmToPound(20d);
		int imageHeihgt = PdfUtils.mmToPound(8d);
		sfOrderNoImage.scaleAbsolute(imageWidth, imageHeihgt);
		sfLogoCell.addElement(sfOrderNoImage);
		sfLogoCell.setLeading(2f, 1f);
		sfLogoCell.setPaddingLeft(15);
		sfLogoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		sfLogoCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		sfLogoCell.disableBorderSide(PdfPCell.TOP);
		sfLogoCell.disableBorderSide(PdfPCell.RIGHT);
		sfLogoCell.disableBorderSide(PdfPCell.BOTTOM);
		sfLogoCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(sfLogoCell);

		// 更换流向国家代码
		String destCode = getDestCode(apvDTO.getBuyerCountry());
		msyhFont = new Font(baseFont, 14, Font.NORMAL);
		Paragraph destCodePara = new Paragraph(destCode, msyhFont);
		PdfPCell destCodeCell = new PdfPCell(destCodePara);
		destCodeCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		destCodeCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
		destCodeCell.disableBorderSide(PdfPCell.TOP);
		destCodeCell.disableBorderSide(PdfPCell.RIGHT);
		destCodeCell.disableBorderSide(PdfPCell.BOTTOM);
		destCodeCell.disableBorderSide(PdfPCell.LEFT);
		table.addCell(destCodeCell);

		document.add(table);
		document.newPage();
		generateCustomsDeclarationTable(apvDTO, document, canvas, baseFont);
	}

	private String getDestCode(String buyerCountry) {
		if (StringUtils.isNotEmpty(buyerCountry)) {
			String mappedCountry = CountryMap.getMappingCountry(buyerCountry);
			Country country = CountryMap.getCountry(mappedCountry);
			String twoWordCountryName = country.getTwoWordName();
			return PY_DEST_CODE.get(twoWordCountryName);
		}
		return null;
	}

	private void generateCustomsDeclarationTable(AllocationProductVoucherDTO apvDTO, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
		if (CollectionUtils.isNotEmpty(apvDTO.getAllocationProductVoucherItemDTOs())) {

			Font msyhFont = new Font(baseFont, 2, Font.NORMAL);

			Paragraph spacePara = new Paragraph("\n", msyhFont);
			document.add(spacePara);

			Rectangle pageSize = document.getPageSize();
			float width = pageSize.getWidth();
			float height = pageSize.getHeight();
			float shareWidth = width / 20;
			PdfPTable table = new PdfPTable(new float[] { shareWidth * 6, shareWidth, shareWidth * 4, shareWidth,
					shareWidth * 3, shareWidth * 5 });

			table.setLockedWidth(true);
			table.setTotalWidth(width - 4);
			table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
			table.setSpacingBefore(0f);
			table.setSpacingAfter(0f);
			table.getDefaultCell().setBackgroundColor(null);
			table.getDefaultCell().setNoWrap(false);
			table.getDefaultCell().setMinimumHeight(0f);

			msyhFont = new Font(baseFont, 10, Font.NORMAL);

			StringBuffer postalAdminBuffer = new StringBuffer();
			postalAdminBuffer.append("CUSTOMS DECLARATION");
			Paragraph postalAdminPara = new Paragraph(postalAdminBuffer.toString(), msyhFont);
			PdfPCell postalAdminCell = new PdfPCell(postalAdminPara);
			postalAdminCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			postalAdminCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			postalAdminCell.setColspan(2);
			postalAdminCell.setMinimumHeight(20f);
			postalAdminCell.disableBorderSide(PdfPCell.RIGHT);
			table.addCell(postalAdminCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer declareLabelBuffer = new StringBuffer();
			declareLabelBuffer.append("May be opened officially");
			Paragraph declareLabelPara = new Paragraph(declareLabelBuffer.toString(), msyhFont);
			PdfPCell declareLabelCell = new PdfPCell(declareLabelPara);
			declareLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			declareLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			declareLabelCell.setColspan(3);
			declareLabelCell.disableBorderSide(PdfPCell.LEFT);
			declareLabelCell.disableBorderSide(PdfPCell.RIGHT);
			table.addCell(declareLabelCell);

			msyhFont = new Font(baseFont, 10, Font.BOLD);
			StringBuffer cn22LabelBuffer = new StringBuffer();
			cn22LabelBuffer.append("CN22");
			Paragraph cn22LabelPara = new Paragraph(cn22LabelBuffer.toString(), msyhFont);
			PdfPCell cn22LabelCell = new PdfPCell(cn22LabelPara);
			cn22LabelCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
			cn22LabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			cn22LabelCell.disableBorderSide(PdfPCell.LEFT);
			table.addCell(cn22LabelCell);

			msyhFont = new Font(baseFont, 8, Font.BOLD);
			StringBuffer operatorBuffer = new StringBuffer();
			operatorBuffer.append("Designated operator");
			Paragraph operatorPara = new Paragraph(operatorBuffer.toString(), msyhFont);
			PdfPCell operatorCell = new PdfPCell(operatorPara);
			operatorCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			operatorCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			operatorCell.setColspan(5);
			operatorCell.disableBorderSide(PdfPCell.RIGHT);
			table.addCell(operatorCell);

			msyhFont = new Font(baseFont, 8, Font.BOLD);
			StringBuffer instructionBuffer = new StringBuffer();
			instructionBuffer.append("Important!\n");
			instructionBuffer.append("See instructions!\n");
			instructionBuffer.append("on the back");
			Paragraph instructionPara = new Paragraph(instructionBuffer.toString(), msyhFont);
			PdfPCell instructionCell = new PdfPCell(instructionPara);
			instructionCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			instructionCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			instructionCell.disableBorderSide(PdfPCell.LEFT);
			table.addCell(instructionCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer giftBuffer = new StringBuffer();
			giftBuffer.append("   Gift");
			Paragraph giftPara = new Paragraph(giftBuffer.toString(), msyhFont);
			PdfPCell giftCell = new PdfPCell(giftPara);
			giftCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			giftCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			giftCell.disableBorderSide(PdfPCell.BOTTOM);
			giftCell.setColspan(2);
			table.addCell(giftCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer goodsTypeBuffer = new StringBuffer();
			goodsTypeBuffer.append("    Commercial sample");
			Paragraph goodsTypePara = new Paragraph(goodsTypeBuffer.toString(), msyhFont);
			PdfPCell goodsTypeCell = new PdfPCell(goodsTypePara);
			goodsTypeCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			goodsTypeCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			goodsTypeCell.disableBorderSide(PdfPCell.LEFT);
			goodsTypeCell.disableBorderSide(PdfPCell.BOTTOM);
			goodsTypeCell.disableBorderSide(PdfPCell.RIGHT);
			goodsTypeCell.setColspan(3);
			table.addCell(goodsTypeCell);

			PdfPCell spaceCell = new PdfPCell();
			spaceCell.disableBorderSide(PdfPCell.LEFT);
			spaceCell.disableBorderSide(PdfPCell.BOTTOM);
			table.addCell(spaceCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer documentsBuffer = new StringBuffer();
			documentsBuffer.append("   Documents");
			Paragraph documentsPara = new Paragraph(documentsBuffer.toString(), msyhFont);
			PdfPCell documentsCell = new PdfPCell(documentsPara);
			documentsCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			documentsCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			documentsCell.disableBorderSide(PdfPCell.TOP);
			documentsCell.setColspan(2);
			table.addCell(documentsCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer otherBuffer = new StringBuffer();
			otherBuffer.append("√   Other");
			Paragraph otherPara = new Paragraph(otherBuffer.toString(), msyhFont);
			PdfPCell otherCell = new PdfPCell(otherPara);
			otherCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			otherCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			otherCell.disableBorderSide(PdfPCell.LEFT);
			otherCell.disableBorderSide(PdfPCell.TOP);
			otherCell.disableBorderSide(PdfPCell.RIGHT);
			otherCell.setColspan(3);
			table.addCell(otherCell);

			msyhFont = new Font(baseFont, 8, Font.ITALIC);

			StringBuffer tickBuffer = new StringBuffer();
			tickBuffer.append("Tick one or more boxes");
			Paragraph tickPara = new Paragraph(tickBuffer.toString(), msyhFont);

			spaceCell = new PdfPCell(tickPara);
			spaceCell.disableBorderSide(PdfPCell.LEFT);
			spaceCell.disableBorderSide(PdfPCell.TOP);
			table.addCell(spaceCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer itemDescLabelBuffer = new StringBuffer();
			itemDescLabelBuffer.append("Quantity " + "and detailed description of contents");
			Paragraph itemDescLabelPara = new Paragraph(itemDescLabelBuffer.toString(), msyhFont);
			PdfPCell itemDescLabelCell = new PdfPCell(itemDescLabelPara);
			itemDescLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			itemDescLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			itemDescLabelCell.setColspan(3);
			table.addCell(itemDescLabelCell);

			StringBuffer weightLabelBuffer = new StringBuffer();
			weightLabelBuffer.append("Weight(Kg)");
			Paragraph weightLabelPara = new Paragraph(weightLabelBuffer.toString(), msyhFont);
			PdfPCell weightLabelCell = new PdfPCell(weightLabelPara);
			weightLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			weightLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			weightLabelCell.setColspan(2);
			table.addCell(weightLabelCell);

			StringBuffer valueLabelBuffer = new StringBuffer();
			valueLabelBuffer.append("Value");
			Paragraph valueLabelPara = new Paragraph(valueLabelBuffer.toString(), msyhFont);
			PdfPCell valueLabelCell = new PdfPCell(valueLabelPara);
			valueLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			valueLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(valueLabelCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			AllocationProductVoucherItemDTO firstApviDTO = (AllocationProductVoucherItemDTO) apvDTO
					.getAllocationProductVoucherItemDTOs().iterator().next();
			StringBuffer itemDescBuffer = new StringBuffer();

			String declareEnName = firstApviDTO.getDeclareEnName();

			if (StringUtils.isNotEmpty(declareEnName)) {
				itemDescBuffer.append(declareEnName);
			}
			itemDescBuffer.append("\n");

			ExpressTypeXmlBuilder expressBuilder = new ExpressTypeXmlBuilder("", apvDTO, false);

			Paragraph itemDescPara = new Paragraph(itemDescBuffer.toString(), msyhFont);
			PdfPCell itemDescCell = new PdfPCell(itemDescPara);
			itemDescCell.setMinimumHeight(15f);
			itemDescCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			itemDescCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			itemDescCell.setColspan(3);
			table.addCell(itemDescCell);

			StringBuffer weightBuffer = new StringBuffer();
			weightBuffer.append(expressBuilder.getGoodsNameWeightInKg());
			Paragraph weightPara = new Paragraph(weightBuffer.toString(), msyhFont);
			PdfPCell weightCell = new PdfPCell(weightPara);
			weightCell.setMinimumHeight(15f);
			weightCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			weightCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			weightCell.setColspan(2);
			table.addCell(weightCell);

			Double declareValue = Double.valueOf(expressBuilder.getGoodsNameDeclaredValue());
			if (declareValue >= 15) {
				declareValue = 14.9d;
			}
			StringBuffer valueBuffer = new StringBuffer();
			valueBuffer.append(declareValue);
			Paragraph valuePara = new Paragraph(valueBuffer.toString(), msyhFont);
			PdfPCell valueCell = new PdfPCell(valuePara);
			valueCell.setMinimumHeight(15f);
			valueCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			valueCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(valueCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer originLabelBuffer = new StringBuffer();
			originLabelBuffer.append("HS tariff number and country of orgin of " + "goods(For commercial items only)");
			Paragraph originLabelPara = new Paragraph(originLabelBuffer.toString(), msyhFont);
			PdfPCell originLabelCell = new PdfPCell(originLabelPara);
			originLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			originLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			originLabelCell.setColspan(3);
			table.addCell(originLabelCell);

			StringBuffer totalWeightLabelBuffer = new StringBuffer();
			totalWeightLabelBuffer.append("Total weight (Kg)");
			Paragraph totalWeightLabelPara = new Paragraph(totalWeightLabelBuffer.toString(), msyhFont);
			PdfPCell totalWeightLabelCell = new PdfPCell(totalWeightLabelPara);
			totalWeightLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			totalWeightLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			totalWeightLabelCell.setColspan(2);
			table.addCell(totalWeightLabelCell);

			StringBuffer totalValueLabelBuffer = new StringBuffer();
			totalValueLabelBuffer.append("Total value");
			Paragraph totalValueLabelPara = new Paragraph(totalValueLabelBuffer.toString(), msyhFont);
			PdfPCell totalValueLabelCell = new PdfPCell(totalValueLabelPara);
			totalValueLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			totalValueLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(totalValueLabelCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer originBuffer = new StringBuffer();
			originBuffer.append("CN");
			Paragraph originPara = new Paragraph(originBuffer.toString(), msyhFont);
			PdfPCell originCell = new PdfPCell(originPara);
			originCell.setMinimumHeight(15f);
			originCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			originCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			originCell.setColspan(3);
			table.addCell(originCell);

			StringBuffer totalWeightBuffer = new StringBuffer();
			totalWeightBuffer.append(expressBuilder.getGoodsNameWeightInKg());
			Paragraph totalWeightPara = new Paragraph(totalWeightBuffer.toString(), msyhFont);
			PdfPCell totalWeightCell = new PdfPCell(totalWeightPara);
			totalWeightCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			totalWeightCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			totalWeightCell.setColspan(2);
			table.addCell(totalWeightCell);

			StringBuffer totalValueBuffer = new StringBuffer();
			totalValueBuffer.append(declareValue);
			Paragraph totalValuePara = new Paragraph(totalValueBuffer.toString(), msyhFont);
			PdfPCell totalValueCell = new PdfPCell(totalValuePara);
			totalValueCell.setMinimumHeight(15f);
			totalValueCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			totalValueCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(totalValueCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer declarationBuffer = new StringBuffer();
			declarationBuffer.append("I,the undersigned,whose name and address "
					+ "are given on the item,certify that the partioulars given "
					+ "in this declaration are correct and that this item does "
					+ "not contain any dangerous article or articles prohibited "
					+ "by legislation or by postal or customs regulations.\n");
			declarationBuffer.append("Date and sender's signature" + "           " + Env.SF_SIGNATURE + "           "
					+ DateUtils.dateToString(new Date(), "yyyy/MM/dd"));
			Paragraph declarationPara = new Paragraph(declarationBuffer.toString(), msyhFont);
			PdfPCell declarationCell = new PdfPCell(declarationPara);
			declarationCell.setMinimumHeight(50f);
			declarationCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			declarationCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			declarationCell.disableBorderSide(PdfPCell.BOTTOM);
			declarationCell.setColspan(6);
			table.addCell(declarationCell);

			PdfPCell shippingOderNoCell = new PdfPCell();
			String apvno = apvDTO.getApvNo();
			if (StringUtils.isNotEmpty(apvno)) {
				Image sfOrderNoImage = this.getBarCodeGenerator().getShippingOrderNo(apvno, canvas);
				int imageWidth = PdfUtils.mmToPound(40d);
				int imageHeihgt = PdfUtils.mmToPound(15d);
				sfOrderNoImage.scaleAbsolute(imageWidth, imageHeihgt);
				shippingOderNoCell.addElement(sfOrderNoImage);
			}
			shippingOderNoCell.setLeading(2f, 1f);
			shippingOderNoCell.setMinimumHeight(40f);
			shippingOderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			shippingOderNoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			shippingOderNoCell.disableBorderSide(PdfPCell.TOP);
			shippingOderNoCell.setRowspan(2);
			shippingOderNoCell.setColspan(6);
			table.addCell(shippingOderNoCell);

			document.add(table);
		}
	}

	private StringBuffer getBuyerFullAddress(AllocationProductVoucherDTO apvDTO) {
		StringBuffer buyerInfoBuffer = new StringBuffer();
		buyerInfoBuffer.append("To:");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerFullname())) {
			buyerInfoBuffer.append(apvDTO.getBuyerFullname());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1()) || StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
			buyerInfoBuffer.append("\n");
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1())) {
				buyerInfoBuffer.append(apvDTO.getBuyerAddress1());
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
				buyerInfoBuffer.append(" ");
				buyerInfoBuffer.append(apvDTO.getBuyerAddress2());
			}
			buyerInfoBuffer.append("\n");
		}
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCity())) {
			sb.append(apvDTO.getBuyerCity());
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerState())) {
			sb.append(" ");
			sb.append(apvDTO.getBuyerState());
		}
		String buyerCityState = sb.toString();
		if (StringUtils.isNotEmpty(buyerCityState)) {
			buyerInfoBuffer.append(buyerCityState);
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerZip())) {
			buyerInfoBuffer.append("\n");
			buyerInfoBuffer.append("ZIP: " + apvDTO.getBuyerZip());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerPhoneNumber()) || StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
			if (StringUtils.isNotEmpty(apvDTO.getBuyerPhoneNumber())) {
				buyerInfoBuffer.append("Tel: " + apvDTO.getBuyerPhoneNumber());
			} else {
				if (StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
					buyerInfoBuffer.append("Tel: " + apvDTO.getBuyerMobile());
				}
			}
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
			sb = new StringBuffer();
			if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
				String originalCountry = apvDTO.getBuyerCountry();
				String mappingCountry = CountryMap.getMappingCountry(originalCountry);
				sb.append(mappingCountry);
			}
			buyerInfoBuffer.append(sb.toString());
		}
		return buyerInfoBuffer;
	}

	public BaseFont getBaseFont() throws Exception {
		String fontFileName = "arialuni.ttf";
		String osName = System.getProperty("os.name");
		if ("Windows 7".equals(osName) || "Windows 8".equals(osName)) {
			fontFileName = "MSYHBD.TTF";
		}

		return BaseFont.createFont(this.getClass().getResource("/") + "/fonts/" + fontFileName, BaseFont.IDENTITY_H,
				BaseFont.EMBEDDED, BaseFont.NOT_CACHED, null, null);
	}

	private Image getImage(String imageFile) {
		try {
			Image image = Image.getInstance(Env.APP_REAL_PATH + "images/" + imageFile);
			return image;
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return null;
	}

	public String getShippingForwarderMethodName(String shippingForwarderMethod) {
		if (StringUtils.isNotEmpty(shippingForwarderMethod)) {
			ShippingMethod shippingMethod = this.chainService.findShippingMethodByCode(shippingForwarderMethod);
			if (shippingMethod != null) {
				return shippingMethod.getName();
			}
		}
		return shippingForwarderMethod;
	}

}


text:
package gov.nasa.jpf.constraints.solvers.smtinterpol;

import gov.nasa.jpf.constraints.solvers.smtinterpol.SMTInterpolSolver;
import de.uni_freiburg.informatik.ultimate.logic.Annotation;
import de.uni_freiburg.informatik.ultimate.logic.Logics;
import de.uni_freiburg.informatik.ultimate.logic.SMTLIBException;
import de.uni_freiburg.informatik.ultimate.logic.Script;
import de.uni_freiburg.informatik.ultimate.logic.Script.LBool;
import de.uni_freiburg.informatik.ultimate.logic.Sort;
import de.uni_freiburg.informatik.ultimate.logic.Term;
import de.uni_freiburg.informatik.ultimate.smtinterpol.smtlib2.SMTInterpol;
import gov.nasa.jpf.constraints.api.Expression;
import gov.nasa.jpf.constraints.api.Variable;
import gov.nasa.jpf.constraints.expressions.Constant;
import gov.nasa.jpf.constraints.expressions.LogicalOperator;
import gov.nasa.jpf.constraints.expressions.NumericBooleanExpression;
import gov.nasa.jpf.constraints.expressions.NumericComparator;
import gov.nasa.jpf.constraints.expressions.PropositionalCompound;
import gov.nasa.jpf.constraints.types.BuiltinTypes;
import gov.nasa.jpf.constraints.util.ExpressionUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import junit.framework.TestCase;

import org.testng.annotations.Test;

public class SMTInterpolTest {

    @Test
    public void test1() {
        System.out.println("--- test 1");
        try {
            de.uni_freiburg.informatik.ultimate.smtinterpol.
                    DefaultLogger smtLogger =
                        new de.uni_freiburg.informatik.ultimate.smtinterpol
                          .DefaultLogger();
            Script s = new SMTInterpol(smtLogger, true);
            s.setOption(":produce-interpolants", true);
            s.setLogic(Logics.QF_LIA);
            s.declareFun("x", new Sort[0], s.sort("Int"));
            s.declareFun("y", new Sort[0], s.sort("Int"));
            s.assertTerm(s.annotate(
                    s.term(">", s.term("x"), s.term("y")),
                    new Annotation(":named", "phi_1")));
            s.assertTerm(s.annotate(
                    s.term("=", s.term("x"), s.numeral("0")),
                    new Annotation(":named", "phi_2")));
            s.assertTerm(s.annotate(
                    s.term(">", s.term("y"), s.numeral("0")),
                    new Annotation(":named", "phi_3")));
            if (s.checkSat() == LBool.UNSAT) {
                Term[] interpolants;
                interpolants = s.getInterpolants(new Term[]{
                    s.term("phi_1"),
                    s.term("phi_2"),
                    s.term("phi_3")});
                System.out.println(Arrays.toString(interpolants));
                interpolants = s.getInterpolants(new Term[]{
                    s.term("phi_2"),
                    s.term("and", s.term("phi_1"), s.term("phi_3"))});
                System.err.println(Arrays.toString(interpolants));
            }
        } catch (SMTLIBException ex) {
            System.out.println("unknown");
            ex.printStackTrace(System.err);
        }
    }

    @Test
    public void test2() {

        System.out.println("--- test 2");

//        s.declareFun("x", new Sort[0], s.sort("Int"));
//        s.declareFun("y", new Sort[0], s.sort("Int"));
        Variable x = new Variable(BuiltinTypes.SINT32 , "x");
        Variable y = new Variable(BuiltinTypes.SINT32 , "y");

//        s.assertTerm(s.annotate(
//                s.term(">", s.term("x"), s.term("y")),
//                new Annotation(":named", "phi_1")));
        Expression<Boolean> phi_1 = new NumericBooleanExpression(
                x, NumericComparator.GT, y);

//        s.assertTerm(s.annotate(
//                s.term("=", s.term("x"), s.numeral("0")),
//                new Annotation(":named", "phi_2")));
        Expression<Boolean> phi_2 = new NumericBooleanExpression(
                x, NumericComparator.EQ, Constant.createParsed(BuiltinTypes.SINT32, "0"));

//        s.assertTerm(s.annotate(
//                s.term(">", s.term("y"), s.numeral("0")),
//                new Annotation(":named", "phi_3")));
        Expression<Boolean> phi_3 = new NumericBooleanExpression(
                y, NumericComparator.GT, Constant.createParsed(BuiltinTypes.SINT32, "0"));

        ArrayList<Expression<Boolean>> terms = new ArrayList<>();
        terms.add(phi_1);
        terms.add(phi_2);
        terms.add(phi_3);

        SMTInterpolSolver solver = new SMTInterpolSolver();
        Collection<Expression<Boolean>> interpolants =
                solver.getInterpolants(terms);

        System.out.println(Arrays.toString(interpolants.toArray()));

        terms.clear();
        terms.add(phi_2);
        terms.add(new PropositionalCompound(phi_1, LogicalOperator.AND, phi_3));
        interpolants = solver.getInterpolants(terms);

        System.out.println(Arrays.toString(interpolants.toArray()));

    }

    @Test
    public void test3() {

        System.out.println("--- test 3");
        ArrayList<Expression<Boolean>> terms = new ArrayList<>();
        Variable x1 = new Variable(BuiltinTypes.SINT32 , "this.sink");
        Variable x2 = new Variable(BuiltinTypes.SINT32 , "this.sinkConnected");
        Variable x3 = new Variable(BuiltinTypes.SINT32 , "snk");
        Variable x4 = new Variable(BuiltinTypes.SINT32 , "conn");

        //(true && (((('this.sink' == 0) && ('this.sinkConnected' == 0)) && ('snk' == 0)) && ('conn' == 0)))

        Expression<Boolean> phi_2 = ExpressionUtil.and(
                ExpressionUtil.and(
                        ExpressionUtil.and(
                            new NumericBooleanExpression(
                                    x1, NumericComparator.EQ, Constant.createParsed(BuiltinTypes.SINT32, "0")),
                            new NumericBooleanExpression(
                                    x2, NumericComparator.EQ, Constant.createParsed(BuiltinTypes.SINT32, "0"))),
                        new NumericBooleanExpression(
                                x3, NumericComparator.EQ, Constant.createParsed(BuiltinTypes.SINT32, "0"))),
                    new NumericBooleanExpression(
                            x4, NumericComparator.EQ, Constant.createParsed(BuiltinTypes.SINT32, "0")));

        terms.add(ExpressionUtil.and(ExpressionUtil.TRUE, phi_2));
        terms.add(ExpressionUtil.FALSE);

        SMTInterpolSolver solver = new SMTInterpolSolver();
        Collection<Expression<Boolean>> interpolants =
                solver.getInterpolants(terms);

        System.out.println(Arrays.toString(interpolants.toArray()));

    }

    @Test
    public void test4() {
        System.out.println("--- test 4");
        ArrayList<Expression<Boolean>> terms = new ArrayList<>();
        Variable x1 = new Variable(BuiltinTypes.BOOL , "x1");
        Variable x2 = new Variable(BuiltinTypes.BOOL , "x2");

        Expression<Boolean> phi_2 =new PropositionalCompound(x1, LogicalOperator.AND, x2);
        terms.add(phi_2);
        terms.add(ExpressionUtil.FALSE);

        SMTInterpolSolver solver = new SMTInterpolSolver();
        Collection<Expression<Boolean>> interpolants =
                solver.getInterpolants(terms);

        System.out.println(Arrays.toString(interpolants.toArray()));

    }
}

redpajama_set_name: RedPajamaGithub


text:
VBA-Utils
=========

Module
------
- [Utils](Utils.bas)
- [File](File.bas)

Reference
---------
- [Array](array.md)
- [File](file.md)

VB Editor Color Scheme
--------------------------------
- [Dark](color scheme/dark.reg)


text:
/**
 */
package COSEM.COSEMObjects;

import COSEM.InterfaceClasses.Scripttable;

/**
 *
 * A representation of the model object 'Tariffication'.
 *
 *
 *
 * @see COSEM.COSEMObjects.COSEMObjectsPackage#getTariffication()
 * @model
 * @generated
 */
public interface Tariffication extends Scripttable {
} // Tariffication


text:
<?php

namespace Illuminate\Tests\Broadcasting;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Broadcasting\Broadcasters\Broadcaster;
use Illuminate\Broadcasting\Broadcasters\UsePusherChannelConventions;

class UsePusherChannelConventionsTest extends TestCase
{
    /**
     * @var \Illuminate\Broadcasting\Broadcasters\RedisBroadcaster
     */
    public $broadcaster;

    protected function setUp(): void
    {
        parent::setUp();

        $this->broadcaster = new FakeBroadcasterUsingPusherChannelsNames();
    }

    protected function tearDown(): void
    {
        m::close();
    }

    /**
     * @dataProvider channelsProvider
     */
    public function testChannelNameNormalization($requestChannelName, $normalizedName)
    {
        $this->assertEquals(
            $normalizedName,
            $this->broadcaster->normalizeChannelName($requestChannelName)
        );
    }

    /**
     * @dataProvider channelsProvider
     */
    public function testIsGuardedChannel($requestChannelName, $_, $guarded)
    {
        $this->assertEquals(
            $guarded,
            $this->broadcaster->isGuardedChannel($requestChannelName)
        );
    }

    public function channelsProvider()
    {
        $prefixesInfos = [
            ['prefix' => 'private-', 'guarded' => true],
            ['prefix' => 'presence-', 'guarded' => true],
            ['prefix' => '', 'guarded' => false],
        ];

        $channels = [
            'test',
            'test-channel',
            'test-private-channel',
            'test-presence-channel',
            'abcd.efgh',
            'abcd.efgh.ijkl',
            'test.{param}',
            'test-{param}',
            '{a}.{b}',
            '{a}-{b}',
            '{a}-{b}.{c}',
        ];

        $tests = [];
        foreach ($prefixesInfos as $prefixInfos) {
            foreach ($channels as $channel) {
                $tests[] = [
                    $prefixInfos['prefix'].$channel,
                    $channel,
                    $prefixInfos['guarded'],
                ];
            }
        }

        $tests[] = ['private-private-test', 'private-test', true];
        $tests[] = ['private-presence-test', 'presence-test', true];
        $tests[] = ['presence-private-test', 'private-test', true];
        $tests[] = ['presence-presence-test', 'presence-test', true];
        $tests[] = ['public-test', 'public-test', false];

        return $tests;
    }
}

class FakeBroadcasterUsingPusherChannelsNames extends Broadcaster
{
    use UsePusherChannelConventions;

    public function auth($request)
    {
    }

    public function validAuthenticationResponse($request, $result)
    {
    }

    public function broadcast(array $channels, $event, array $payload = [])
    {
    }
}


text:
/**
 * @author Tom Deneau
 */

import javax.crypto.Cipher;

public class TestAESEncode extends TestAESBase {
  @Override
  public void run() {
    try {
      if (!noReinit) cipher.init(Cipher.ENCRYPT_MODE, key, algParams);
      if (checkOutput) {
        // checked version creates new output buffer each time
        encode = cipher.doFinal(input, 0, msgSize);
        compareArrays(encode, expectedEncode);
      } else {
        // non-checked version outputs to existing encode buffer for maximum speed
        encode = new byte[cipher.getOutputSize(msgSize)];
        cipher.doFinal(input, 0, msgSize, encode);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }

  @Override
  void childShowCipher() {
    showCipher(cipher, "Encryption");
  }

}


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

Alloy.apiCall = function(endPoint, data, success, fail){
  var xhr = new XHR();

  var localSuccess = function(e){
    success(e);
    xhr = null;
  }

  var failed = function(e){
    fail(e);
    xhr = null;
  }

  xhr.post(endPoint, JSON.stringify(data), localSuccess, failed);
};

Alloy.downloadImage = function(endPoint, filename, success, fail){
  var xhr = Titanium.Network.createHTTPClient({
  	onload: function() {
  		var f = Ti.Filesystem.getFile(Alloy.playerImages.nativePath,filename);
  		f.write(this.responseData);
      success();
  	},
    onerror: function(){
      fail();
    },
  	timeout: 10000
  });
  xhr.open('GET', endPoint);
  xhr.send();
};

var playerImages = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,"PlayerImages");
playerImages.createDirectory();
playerImages.remoteBackup = false;
Alloy.playerImages = playerImages;


text:
package lmu.de.unificiencyandroid.utils;

import android.view.View;
import android.view.ViewGroup;

public final class LoadingUtils {
  private LoadingUtils() {}

  public static void enableView(View view, boolean enabled) {
    view.setEnabled(enabled);
    if (view instanceof ViewGroup) {
      ViewGroup viewGroup = (ViewGroup) view;
      for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        enableView(child, enabled);
      }
    }
  }

  public static void showView(View view, boolean enabled) {
    view.setVisibility(enabled ? View.VISIBLE : View.INVISIBLE);
    if (view instanceof ViewGroup) {
      ViewGroup viewGroup = (ViewGroup) view;
      for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        showView(child, enabled);
      }
    }
  }

}


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

namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{
    public class Atom : IUnifiable
    {
        private static Dictionary<string, Atom> _atomStore = new Dictionary<string, Atom>();
        public readonly string _name;
        public readonly Atom _module;

        /// <summary>
        /// You should not call this constructor, but use Atom.a instead.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="module"></param>
        private Atom(string name, Atom module)
        {
            _name = name;
            _module = module;
        }

        /// <summary>
        /// Return the unique Atom object for name where module is null. You should use this to create
        /// an Atom instead of calling the Atom constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Atom a(string name)
        {
            Atom atom;
            if (!_atomStore.TryGetValue(name, out atom))
            {
                atom = new Atom(name, null);
                _atomStore[name] = atom;
            }
            return atom;
        }

        /// <summary>
        /// Return an Atom object with the name and module.  If module is null or Atom.NIL,
        /// this behaves like Atom.a(name) and returns the unique object where the module is null.
        /// If module is not null or Atom.NIL, this may or may not be the same object as another Atom
        /// with the same name and module.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        public static Atom a(string name, Atom module)
        {
            if (module == null || module == Atom.NIL)
                return a(name);
            return new Atom(name, module);
        }

        /// <summary>
        /// If Obj is an Atom unify its _module with Module.  If the Atom's _module is null, use Atom.NIL.
        /// </summary>
        /// <param name="Atom"></param>
        /// <param name="Module"></param>
        /// <returns></returns>
        public static IEnumerable<bool> module(object Obj, object Module)
        {
            Obj = YP.getValue(Obj);
            if (Obj is Atom)
            {
                if (((Atom)Obj)._module == null)
                    return YP.unify(Module, Atom.NIL);
                else
                    return YP.unify(Module, ((Atom)Obj)._module);
            }
            return YP.fail();
        }

        public static readonly Atom NIL = Atom.a("[]");
        public static readonly Atom DOT = Atom.a(".");
        public static readonly Atom F = Atom.a("f");
        public static readonly Atom SLASH = Atom.a("/");
        public static readonly Atom HAT = Atom.a("^");
        public static readonly Atom RULE = Atom.a(":-");

        public IEnumerable<bool> unify(object arg)
        {
            arg = YP.getValue(arg);
            if (arg is Atom)
                return Equals(arg) ? YP.succeed() : YP.fail();
            else if (arg is Variable)
                return ((Variable)arg).unify(this);
            else
                return YP.fail();
        }

        public void addUniqueVariables(List<Variable> variableSet)
        {
            // Atom does not contain variables.
        }

        public object makeCopy(Variable.CopyStore copyStore)
        {
            // Atom does not contain variables that need to be copied.
            return this;
        }

        public bool termEqual(object term)
        {
            return Equals(YP.getValue(term));
        }

        public bool ground()
        {
            // Atom is always ground.
            return true;
        }

        public override bool Equals(object obj)
        {
            if (obj is Atom)
            {
                if (_module == null && ((Atom)obj)._module == null)
                    // When _declaringClass is null, we always use an identical object from _atomStore.
                    return this == obj;
                // Otherwise, ignore _declaringClass and do a normal string compare on the _name.
                return _name == ((Atom)obj)._name;
            }
            return false;
        }

        public override string ToString()
        {
            return _name;
        }

        public override int GetHashCode()
        {
            // Debug: need to check _declaringClass.
            return _name.GetHashCode();
        }

        public string toQuotedString()
        {
            if (_name.Length == 0)
                return "''";
            else if (this == Atom.NIL)
                return "[]";

            StringBuilder result = new StringBuilder(_name.Length);
            bool useQuotes = false;
            foreach (char c in _name)
            {
                int cInt = (int)c;
                if (c == '\'')
                {
                    result.Append("''");
                    useQuotes = true;
                }
                else if (c == '_' || cInt >= (int)'a' && cInt <= (int)'z' ||
                         cInt >= (int)'A' && cInt <= (int)'Z' || cInt >= (int)'0' && cInt <= (int)'9')
                    result.Append(c);
                else
                {
                    // Debug: Need to handle non-printable chars.
                    result.Append(c);
                    useQuotes = true;
                }
            }

            if (!useQuotes && (int)_name[0] >= (int)'a' && (int)_name[0] <= (int)'z')
                return result.ToString();
            else
            {
                // Surround in single quotes.
                result.Append('\'');
                return "'" + result;
            }
        }

        /// <summary>
        /// Return true if _name is lexicographically less than atom._name.
        /// </summary>
        /// <param name="atom"></param>
        /// <returns></returns>
        public bool lessThan(Atom atom)
        {
            return _name.CompareTo(atom._name) < 0;
        }
    }
}


text:
package org.jkiss.dbeaver.model.struct;

import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;

/**
 * DBSEntityAssociationLazy
 */
public interface DBSEntityAssociationLazy extends DBSEntityAssociation {

    @Nullable
    DBSEntityConstraint getReferencedConstraint(DBRProgressMonitor monitor) throws DBException;

    DBSEntity getAssociatedEntity(DBRProgressMonitor monitor) throws DBException;
}


text:
package org.fcrepo.oai;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Chris Wilper
 */
public interface OAIProvider {

    /**
     * Get a human readable name for the repository.
     *
     * @return the repository name.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract String getRepositoryName() throws RepositoryException;

    /**
     * Get the HTTP endpoint for the OAI-PMH interface.
     *
     * @return the base URL.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract String getBaseURL(String protocol, String port)
            throws RepositoryException;

    /**
     * Get the version of the OAI-PMH supported by the repository.
     *
     * @return the protocol version number.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract String getProtocolVersion() throws RepositoryException;

    /**
     * Get a Date (in UTC) that is the guaranteed lower limit of all datestamps
     * recording changes, modifications, or deletions in the repository. A
     * repository must not use datestamps lower than this.
     *
     * @return the earliest datetime stamp.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Date getEarliestDatestamp() throws RepositoryException;

    /**
     * Get the manner in which the repository supports the notion of deleted
     * records.
     *
     * @return manner in which repository supports the notion of deletion.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract DeletedRecordSupport getDeletedRecordSupport()
            throws RepositoryException;

    /**
     * Get the finest harvesting granularity supported by the repository.
     *
     * @return the finest harvesting granularity supported by the repository.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract DateGranularitySupport getDateGranularitySupport()
            throws RepositoryException;

    /**
     * Get the email addresses of administrators of the repository. This set
     * must contain at least one item.
     *
     * @return the email addresses of administrators of the repository.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Set getAdminEmails() throws RepositoryException;

    /**
     * Get the compression encodings supported by the repository. This set may
     * be empty. Recommended values are those in RFC 2616 Section 14.11
     *
     * @return the compression encodings supported by the repository.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Set getSupportedCompressionEncodings()
            throws RepositoryException;

    /**
     * Get XML descriptions of the repository. Each Set element must be a String
     * containing a description according to some W3C schema, where the
     * xsi:schemaLocation attribute is used on the root element. See
     * http://www.openarchives.org/OAI/2.0/guidelines.htm for guidelines
     * regarding these repository-level descriptions.
     *
     * @return XML descriptions of the repository.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Set getDescriptions() throws RepositoryException;

    /**
     * Get an individual metadata record from the repository.
     *
     * @param identifier
     *        the record identifier.
     * @param metadataPrefix
     *        the metadata prefix identifier.
     * @return an individual metadata record from the repository.
     * @throws CannotDisseminateFormatException
     * @throws IDDoesNotExistException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Record getRecord(String identifier, String metadataPrefix)
            throws CannotDisseminateFormatException, IDDoesNotExistException,
            RepositoryException;

    /**
     * Get the Records in the repository matching the given criteria. Any of the
     * arguments (except metadataPrefix) may be null, indicating "any". If the
     * size of the returned list is over getMaxRecords(), the last element is a
     * resumptionToken (a String) which can be used to get the rest of the list.
     *
     * @param from
     *        the beginning date of the date range.
     * @param until
     *        the ending date of the date range.
     * @param metadataPrefix
     *        the metadata prefix.
     * @param set
     *        the set of criteria
     * @return the Records in the repository matching the given criteria.
     * @throws CannotDisseminateFormatException
     * @throws NoRecordsMatchException
     * @throws NoSetHierarchyException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getRecords(Date from,
                                    Date until,
                                    String metadataPrefix,
                                    String set)
            throws CannotDisseminateFormatException, NoRecordsMatchException,
            NoSetHierarchyException, RepositoryException;

    /**
     * Get the remaining portion of a set of Records. If the size of the
     * returned list is over getMaxRecords(), the last element is another
     * resumptionToken (a String) which can be used to get the rest of the list.
     *
     * @param resumptionToken
     *        a string that can be used to get the rest of the list.
     * @return the remaining portion of a set of Records.
     * @throws CannotDisseminateFormatException
     * @throws NoRecordsMatchException
     * @throws NoSetHierarchyException
     * @throws BadResumptionTokenException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getRecords(String resumptionToken)
            throws CannotDisseminateFormatException, NoRecordsMatchException,
            NoSetHierarchyException, BadResumptionTokenException,
            RepositoryException;

    /**
     * Just like getRecords, but returns Header objects. If the size of the
     * returned list is over getMaxHeaders(), the last element is a
     * resumptionToken (a String) which can be used to get the rest of the list.
     *
     * @param from
     *        the beginning date range.
     * @param until
     *        the end of the date range.
     * @param metadataPrefix
     *        the metadata prefix.
     * @param set
     *        the set of criteria.
     * @return the remaining portion of a set of Header objects.
     * @throws CannotDisseminateFormatException
     * @throws NoRecordsMatchException
     * @throws NoSetHierarchyException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getHeaders(Date from,
                                    Date until,
                                    String metadataPrefix,
                                    String set)
            throws CannotDisseminateFormatException, NoRecordsMatchException,
            NoSetHierarchyException, RepositoryException;

    /**
     * Get the remaining portion of a set of Headers. If the size of the
     * returned list is over getMaxHeaders() the last element is another
     * resumptionToken (a String) which can be used to get the rest of the list.
     *
     * @param resumptionToken
     *        a string that can be used to get the rest of the list.
     * @return the remaining portion of a set of Headers.
     * @throws CannotDisseminateFormatException
     * @throws NoRecordsMatchException
     * @throws NoSetHierarchyException
     * @throws BadResumptionTokenException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getHeaders(String resumptionToken)
            throws CannotDisseminateFormatException, NoRecordsMatchException,
            NoSetHierarchyException, BadResumptionTokenException,
            RepositoryException;

    /**
     * Get the setSpecs, setNames, and setDescriptions of sets in the
     * repository. Each set has a setSpec, a name, and zero or more
     * descriptions, held by a SetInfo object. If the size of the returned list
     * is over getMaxSets(), the last element is a resumptionToken (a String)
     * which can be used to get the rest of the list.
     *
     * @return the setSpecs, setNames, and setDescriptions of sets in the
     *         repository.
     * @throws NoSetHierarchyException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getSets() throws NoSetHierarchyException,
            RepositoryException;

    /**
     * Get the remaining portion of a set of Sets. If the size of the returned
     * list is over getMaxSets(), the last element is another resumptionToken (a
     * String) which can be used to get the rest of the list.
     *
     * @param resumptionToken
     *        a string that can be used to get the rest of the list.
     * @return the remaining portion of a set of Sets.
     * @throws BadResumptionTokenException
     * @throws NoSetHierarchyException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract List getSets(String resumptionToken)
            throws BadResumptionTokenException, NoSetHierarchyException,
            RepositoryException;

    /**
     * Get the MetadataFormats supported across the repository or for an
     * individual item in the repository.
     *
     * @param id
     *        The item identifier, or null, meaning "the entire repository"
     * @return the set of metadata formats supported by the repository.
     * @throws IDDoesNotExistException
     * @throws NoMetadataFormatsException
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract Set getMetadataFormats(String id)
            throws IDDoesNotExistException, NoMetadataFormatsException,
            RepositoryException;

    /**
     * Get the maximum number of sets that are returned at a time. A negative
     * value signifies no maximum.
     *
     * @return the maximum number of sets that are returned at a time.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract long getMaxSets() throws RepositoryException;

    /**
     * Get the maximum number of records that are returned at a time. A negative
     * value signifies no maximum.
     *
     * @return the maximum number of records that are returned at a time.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract long getMaxRecords() throws RepositoryException;

    /**
     * Get the maximum number of headers that are returned at a time. A negative
     * value signifies no maximum.
     *
     * @return the maximum number of headers that are returned at a time.
     * @throws RepositoryException
     *         if an error has occurred.
     */
    public abstract long getMaxHeaders() throws RepositoryException;
}


text:
package org.wso2.carbon.siddhi.editor.core.internal;

import io.siddhi.core.event.Event;
import io.siddhi.query.api.definition.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.siddhi.editor.core.exception.NoSuchStreamException;
import org.wso2.carbon.streaming.integrator.common.EventStreamService;
import org.wso2.carbon.streaming.integrator.common.exception.ResourceNotFoundException;

import java.util.List;

/**
 * Class which provides necessary apis for event stream related operations.
 */
public class DebuggerEventStreamService implements EventStreamService {

    private static Logger log = LoggerFactory.getLogger(DebuggerEventStreamService.class);

    @Override
    public List<String> getStreamNames(String siddhiAppName) {

        DebugRuntime runtimeHolder = EditorDataHolder.getSiddhiAppMap().get(siddhiAppName);
        if (runtimeHolder != null) {
            return runtimeHolder.getStreams();
        } else {
            log.error("Siddhi App with name : " + siddhiAppName + " is not available");
        }
        return null;
    }

    @Override
    public List<Attribute> getStreamAttributes(String siddhiAppName, String streamName)
            throws ResourceNotFoundException {

        DebugRuntime runtimeHolder = EditorDataHolder.getSiddhiAppMap().get(siddhiAppName);
        if (runtimeHolder != null) {
            try {
                return runtimeHolder.getStreamAttributes(streamName);
            } catch (NoSuchStreamException e) {
                throw new ResourceNotFoundException("Siddhi App '" + siddhiAppName + "' does not contain " +
                        "stream '" + streamName + "'.", ResourceNotFoundException.ResourceType.STREAM_NAME, streamName);
            }
        } else {
            throw new ResourceNotFoundException("Siddhi App '" + siddhiAppName + "' does not exist.",
                    ResourceNotFoundException.ResourceType.SIDDHI_APP_NAME, siddhiAppName);
        }
    }

    @Override
    public void pushEvent(String siddhiAppName, String streamName, Event event) {

        DebugRuntime runtimeHolder = EditorDataHolder.getSiddhiAppMap().get(siddhiAppName);
        if (runtimeHolder != null) {
            try {
                runtimeHolder.getInputHandler(streamName).send(event);
            } catch (Exception e) {
                log.error("Error when pushing events to Siddhi debugger engine ", e);
            }
        }
    }
}


text:
package com.trsvax.tapestry.aws.services;

import java.util.Map;

import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.ServiceBuilder;
import org.apache.tapestry5.ioc.ServiceResources;
import org.apache.tapestry5.ioc.annotations.Local;
import org.apache.tapestry5.services.ApplicationStatePersistenceStrategy;
import org.apache.tapestry5.services.AssetFactory;
import org.apache.tapestry5.services.LibraryMapping;

import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer.Parameters;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.trsvax.tapestry.aws.AWSConstants;
import com.trsvax.tapestry.aws.internal.DynamoDBApplicationStatePersistenceStrategy;
import com.trsvax.tapestry.aws.services.impl.EmailImpl;
import com.trsvax.tapestry.aws.services.impl.KeyImpl;

public class AWSModule {
    public static void bind(ServiceBinder binder) {
    	binder.bind(Email.class,EmailImpl.class);
		binder.bind(AssetFactory.class,S3AssetFactory.class).withId("S3AssetFactory");
		binder.bind(URLChangedEventHub.class,URLChangedEventHubImpl.class);
		binder.bind(Key.class,KeyImpl.class);

		binder.bind(DynamoDBMapperConfig.class, new ServiceBuilder<DynamoDBMapperConfig>() {

			public DynamoDBMapperConfig buildService(ServiceResources resources) {
				return DynamoDBMapperConfig.DEFAULT;
			}
		});

		binder.bind(AttributeTransformer.class, new ServiceBuilder<AttributeTransformer>() {

			public AttributeTransformer buildService(ServiceResources resources) {
				return new AttributeTransformer() {

					public Map<String, AttributeValue> untransform(Parameters<?> parameters) {
						// TODO Auto-generated method stub
						return parameters.getAttributeValues();
					}

					public Map<String, AttributeValue> transform(Parameters<?> parameters) {
						// TODO Auto-generated method stub
						return parameters.getAttributeValues();
					}
				};
			}
		});

        binder.bind(DynamoDBMapper.class, new ServiceBuilder<DynamoDBMapper>() {

			public DynamoDBMapper buildService(ServiceResources resources) {
				return resources.autobuild("Mapper", DynamoDBMapper.class);

			}
		});
    }

    public void contributeAssetSource(MappedConfiguration<String, AssetFactory> configuration,
			@Local AssetFactory s3AssetFactory) {
        configuration.add("s3", s3AssetFactory);
    }

	public static void contributeComponentClassResolver(Configuration<LibraryMapping> configuration) {
		configuration.add(new LibraryMapping("aws", "com.trsvax.tapestry.aws"));
	}

	 public void contributeApplicationStatePersistenceStrategySource(MappedConfiguration<String, ApplicationStatePersistenceStrategy> configuration) {
			          configuration.addInstance(AWSConstants.DYNAMOENTITY, DynamoDBApplicationStatePersistenceStrategy.class);
	 }

}


text:
package edu.mit.simile.rdfizer.oai;

public class Schema {

    public String prefix;
    public String schema;
    public String namespace;

    public Schema() {}

    public Schema(String p) {
        this.prefix = p;
    }

    public void setPrefix(String p) {
        this.prefix = p;
    }
    public void setSchema(String s) {
        this.schema = s;
    }
    public void setNamespace(String n) {
        this.namespace = n;
    }
}


text:
package ecs

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// UnassociateEipAddress invokes the ecs.UnassociateEipAddress API synchronously
// api document: https://help.aliyun.com/api/ecs/unassociateeipaddress.html
func (client *Client) UnassociateEipAddress(request *UnassociateEipAddressRequest) (response *UnassociateEipAddressResponse, err error) {
	response = CreateUnassociateEipAddressResponse()
	err = client.DoAction(request, response)
	return
}

// UnassociateEipAddressWithChan invokes the ecs.UnassociateEipAddress API asynchronously
// api document: https://help.aliyun.com/api/ecs/unassociateeipaddress.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) UnassociateEipAddressWithChan(request *UnassociateEipAddressRequest) (<-chan *UnassociateEipAddressResponse, <-chan error) {
	responseChan := make(chan *UnassociateEipAddressResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.UnassociateEipAddress(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// UnassociateEipAddressWithCallback invokes the ecs.UnassociateEipAddress API asynchronously
// api document: https://help.aliyun.com/api/ecs/unassociateeipaddress.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) UnassociateEipAddressWithCallback(request *UnassociateEipAddressRequest, callback func(response *UnassociateEipAddressResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *UnassociateEipAddressResponse
		var err error
		defer close(result)
		response, err = client.UnassociateEipAddress(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// UnassociateEipAddressRequest is the request struct for api UnassociateEipAddress
type UnassociateEipAddressRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	InstanceId           string           `position:"Query" name:"InstanceId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	InstanceType         string           `position:"Query" name:"InstanceType"`
	AllocationId         string           `position:"Query" name:"AllocationId"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
}

// UnassociateEipAddressResponse is the response struct for api UnassociateEipAddress
type UnassociateEipAddressResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
}

// CreateUnassociateEipAddressRequest creates a request to invoke UnassociateEipAddress API
func CreateUnassociateEipAddressRequest() (request *UnassociateEipAddressRequest) {
	request = &UnassociateEipAddressRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Ecs", "2014-05-26", "UnassociateEipAddress", "ecs", "openAPI")
	return
}

// CreateUnassociateEipAddressResponse creates a response to parse from UnassociateEipAddress response
func CreateUnassociateEipAddressResponse() (response *UnassociateEipAddressResponse) {
	response = &UnassociateEipAddressResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
'use strict';

/* Directives */

var qzrDirectives = angular.module('qzr.directives', []);


text:
"""Test manipulate.py for vimiv's test suite."""

import os
import shutil
from unittest import main

from vimiv_testcase import (VimivTestCase, compare_files, compare_pixbufs,
                            refresh_gui)

class ManipulateTest(VimivTestCase):
    """Manipulate Tests."""

    @classmethod
    def setUpClass(cls):
        if os.path.isdir("vimiv/testimages_man"):
            shutil.rmtree("vimiv/testimages_man")
        shutil.copytree("vimiv/testimages", "vimiv/testimages_man")
        cls.init_test(cls, ["vimiv/testimages_man/arch-logo.png"])
        cls.manipulate = cls.vimiv["manipulate"]
        # Wait for image as this is used in manipulate
        while not cls.vimiv["image"].get_pixbuf():
            refresh_gui(0.1)

    def setUp(self):
        """Set up by opening manipulate. Test half of toggling."""
        self.manipulate.toggle()
        refresh_gui()
        self.assertTrue(self.manipulate.is_visible())
        self.assertTrue(self.manipulate.sliders["bri"].is_focus())

    def test_manipulate_image(self):
        """Test manipulate image."""
        # Copy image before manipulation
        tmpfile = "tmp.jpg"
        if os.path.exists(tmpfile):
            os.remove(tmpfile)
        shutil.copyfile(self.vimiv.get_path(), tmpfile)
        # Leaving with False should not change the image
        self.manipulate.cmd_edit("bri", "20")
        self.manipulate.finish(False)
        self.assertTrue(compare_files(tmpfile, self.vimiv.get_path()))
        # Image is different to copied backup after manipulations
        self.manipulate.toggle()
        self.manipulate.cmd_edit("bri", "20")
        self.manipulate.finish(True)
        self.assertFalse(compare_files(tmpfile, self.vimiv.get_path()))
        self.manipulate.toggle()  # Re-open to keep state equal

    def test_write_image(self):
        """Write an image to disk from manipulate."""
        # Copy image before manipulation
        tmpfile = "tmp.jpg"
        if os.path.exists(tmpfile):
            os.remove(tmpfile)
        shutil.copyfile(self.vimiv.get_path(), tmpfile)
        # Image is different to copied backup after manipulations
        self.manipulate.cmd_edit("bri", "20")
        self.vimiv["transform"].write()
        self.assertFalse(compare_files(tmpfile, self.vimiv.get_path()))
        self.manipulate.toggle()  # Re-open to keep state equal

    def test_focus_sliders(self):
        """Focusing sliders in manipulate."""
        self.assertTrue(self.manipulate.sliders["bri"].is_focus())
        self.manipulate.focus_slider("con")
        self.assertTrue(self.manipulate.sliders["con"].is_focus())
        self.manipulate.focus_slider("sat")
        self.assertTrue(self.manipulate.sliders["sat"].is_focus())
        self.manipulate.focus_slider("bri")
        self.assertTrue(self.manipulate.sliders["bri"].is_focus())
        # Slider does not exist
        self.manipulate.focus_slider("val")
        self.check_statusbar("ERROR: No slider called val")

    def test_change_slider_value(self):
        """Change slider value in manipulate."""
        # Change value
        self.manipulate.focus_slider("bri")
        self.manipulate.change_slider("-1")
        received_value = self.manipulate.sliders["bri"].get_value()
        self.assertEqual(received_value, -1)
        # Change value with a numstr
        self.vimiv["eventhandler"].set_num_str(5)
        self.manipulate.change_slider("2")
        received_value = self.manipulate.sliders["bri"].get_value()
        self.assertEqual(received_value, -1 + 2 * 5)
        # Not an integer
        self.manipulate.change_slider("hi")
        self.check_statusbar("ERROR: Could not convert 'hi' to int")
        received_value = self.manipulate.sliders["bri"].get_value()
        self.assertEqual(received_value, -1 + 2 * 5)

    def test_cmd_edit(self):
        """Test manipulating from command line commands."""
        pb_1 = self.vimiv["image"].get_pixbuf()
        # Just call the function
        self.manipulate.cmd_edit("sat", "20")
        self.assertEqual(self.manipulate.sliders["sat"].get_value(), 20)
        self.assertTrue(self.manipulate.sliders["sat"].is_focus())
        pb_2 = self.vimiv["image"].get_pixbuf()
        self.assertFalse(compare_pixbufs(pb_1, pb_2))
        # Set contrast via command line
        self.run_command("edit con 35")
        self.assertEqual(self.manipulate.sliders["con"].get_value(), 35)
        self.assertTrue(self.manipulate.sliders["con"].is_focus())
        pb_3 = self.vimiv["image"].get_pixbuf()
        self.assertFalse(compare_pixbufs(pb_2, pb_3))
        # No argument means 0
        self.run_command("edit con")
        self.assertEqual(self.manipulate.sliders["con"].get_value(), 0)
        pb_4 = self.vimiv["image"].get_pixbuf()
        self.assertFalse(compare_pixbufs(pb_3, pb_4))
        self.assertTrue(compare_pixbufs(pb_2, pb_4))  # We reset contrast
        # Close via command line
        self.run_command("discard_changes")
        self.assertFalse(self.manipulate.sliders["sat"].is_focus())
        # Error: not a valid integer for manipulation
        self.run_command("edit bri value")
        self.assertFalse(self.manipulate.sliders["bri"].is_focus())
        self.check_statusbar("ERROR: Argument must be of type integer")

    def test_check_for_edit(self):
        """Check if an image was edited."""
        self.assertEqual(0, self.manipulate.check_for_edit(False))
        self.manipulate.cmd_edit("bri", "10")
        self.assertEqual(1, self.manipulate.check_for_edit(False))
        self.assertEqual(0, self.manipulate.check_for_edit(True))

    def test_quit_with_edited_image(self):
        """Quit vimiv with an edited image."""
        self.manipulate.cmd_edit("bri", "10")
        self.vimiv.quit_wrapper()
        self.check_statusbar("WARNING: Image has been edited, add ! to force")

    def tearDown(self):
        """Tear down by closing manipulate. Test other half of toggling."""
        self.manipulate.finish(False)
        self.assertFalse(self.manipulate.sliders["bri"].is_focus())

    @classmethod
    def tearDownClass(cls):
        cls.vimiv.quit()
        os.chdir(cls.working_directory)
        if os.path.isdir("./vimiv/testimages_man"):
            shutil.rmtree("vimiv/testimages_man")

if __name__ == "__main__":
    main()


text:
@interface AIMQuestionView : UIView <AIMAnswerViewDelegate,UIWebViewDelegate>
@property (nonatomic) float userScore;
@property (nonatomic) long long lastQuestionID;
@property (nonatomic,strong) AIMQuestion *question;

-(id)initWithFrame:(CGRect)frame andQuestion:(AIMQuestion*)question;
-(float)calculateScore;
-(BOOL)isAllowNext;
-(NSString*)getNextQuestion;
-(void)deselectAll;
@end


text:
obj = Object.new
obj.singleton_class # => #<Class:#<Object:0x00000100866ab8>>

# You can access the singleton class like this
class << obj
  def greet
    'Howdy, partner.'
  end
end
obj.singleton_class.instance_methods false # => [:greet]
obj.singleton_methods # => [:greet]
obj.greet # => "Howdy, partner."

# Shortcut syntax for the above
def obj.about
  "A plain old object with a few tricks."
end

obj.about # => "A plain old object with a few tricks."
obj.singleton_methods # => [:greet, :about]

# Question: if everything is an object, and every object
#   has a singleton class, then do singleton classes have
#   singleton classes?
#
#   How can you test your answer out?