text:
package com.jlfex.hermes.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jlfex.hermes.common.Logger;
import com.jlfex.hermes.common.cache.Caches;
import com.jlfex.hermes.common.exception.ServiceException;
import com.jlfex.hermes.common.support.spring.SpringWebApp;
import com.jlfex.hermes.common.utils.Strings;
import com.jlfex.hermes.model.CrediteInfo;
import com.jlfex.hermes.model.InvestProfit;
import com.jlfex.hermes.model.Loan;
import com.jlfex.hermes.model.LoanLog;
import com.jlfex.hermes.model.LoanOverdue;
import com.jlfex.hermes.model.LoanRepay;
import com.jlfex.hermes.model.Repay;
import com.jlfex.hermes.model.Transaction;
import com.jlfex.hermes.model.UserAccount;
import com.jlfex.hermes.model.InvestProfit.Status;
import com.jlfex.hermes.model.LoanLog.Type;
import com.jlfex.hermes.model.LoanRepay.RepayStatus;
import com.jlfex.hermes.repository.InvestProfitRepository;
import com.jlfex.hermes.repository.LoanLogRepository;
import com.jlfex.hermes.repository.LoanOverdueRepository;
import com.jlfex.hermes.repository.LoanRepayRepository;
import com.jlfex.hermes.repository.RepayRepository;
import com.jlfex.hermes.repository.UserAccountRepository;
import com.jlfex.hermes.repository.n.LoanNativeRepository;
import com.jlfex.hermes.repository.n.LoanRepayNativeRepository;
import com.jlfex.hermes.service.CreditInfoService;
import com.jlfex.hermes.service.RepayService;
import com.jlfex.hermes.service.TransactionService;
import com.jlfex.hermes.service.common.Pageables;
import com.jlfex.hermes.service.repay.RepayMethod;

/**
 *
 * 还款方式业务实现
 */
@Service
@Transactional
public class RepayServiceImpl implements RepayService {

	/** 还款方式信息仓库 */
	@Autowired
	private RepayRepository repayRepository;

	/** 还款计划信息仓库 */
	@Autowired
	private LoanRepayRepository loanRepayRepository;

	/** 还款计划信息仓库扩展 */
	@Autowired
	private LoanRepayNativeRepository loanRepayNativeRepository;

	/** 借款逾期信息仓库 */
	@Autowired
	private LoanOverdueRepository loanOverdueRepository;

	/** 理财收益信息仓库 */
	@Autowired
	private InvestProfitRepository investProfitRepository;

	/** 用户账户仓库 */
	@Autowired
	private UserAccountRepository userAccountRepository;

	/** 交易服务 */
	@Autowired
	private TransactionService transactionService;

	/** 借款日志仓库 */
	@Autowired
	private LoanLogRepository loanLogRepository;

	/** 借款信息仓库扩展 */
	@Autowired
	private LoanNativeRepository loanNativeRepository;
	@Autowired
	private CreditInfoService  creditInfoService;

	private static final String CACHE_LOAN_OVERDUE_PREFIX = "com.jlfex.hermes.cache.loan.overdue.";

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.jlfex.hermes.service.RepayService#save(com.jlfex.hermes.model
	 * .Repay)
	 */
	@Override
	public Repay save(Repay repay) {
		// 保存数据并返回
		return repayRepository.save(repay);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.jlfex.hermes.service.RepayService#loadById(java.lang.String)
	 */
	@Override
	@Transactional(readOnly = true)
	public Repay loadById(String id) {
		return repayRepository.findOne(id);
	}

	/**
	 * 此方法用于获取还款记录及最新一期待还
	 *
	 * @param loan
	 * @return
	 */
	public Page<LoanRepay> getloanRepayRecords(Loan loan,Integer page, Integer size) {
		Pageable pageable = Pageables.pageable(page, size);
		List<LoanRepay> loanRepayList = findLoanRepay(loan);
		List<LoanRepay> loanRepayRecords = new ArrayList<LoanRepay>();
		int count = loanRepayList.size();
		// 判断假如有做过放款操作,即loan_repay表中有纪录
		if (count > 0) {
			LoanRepay unRepay = null;
			loanRepayRecords.add(unRepay);
			for (LoanRepay loanRepay : loanRepayList) {
				// 假如正常还款或者逾期还款,
				if (LoanRepay.RepayStatus.NORMAL.equals(loanRepay.getStatus()) || LoanRepay.RepayStatus.OVERDUE_REPAY.equals(loanRepay.getStatus())) {
					loanRepayRecords.add(loanRepay);
					count--;
				}
			}
			// 判断是否存在还未还款的 ,等于0表示全都还款(包括正常和逾期的)了
			if (count > 0) {
				// 获取当期未还
				unRepay = loanRepayList.get(count - 1);
			//	Date now = new Date();
//				// 如果计划时间小于等于当前时间,为正常还款
//				if (unRepay.getPlanDatetime().getTime() <= now.getTime()) {
//					// 计算逾期天数
//					int overdueDay = getOverdueDays(unRepay.getPlanDatetime(), now);
//					// 计算逾期等级
//					Integer rank = (overdueDay - 1) / 30 + 1;
//					LoanOverdue loanOverdue = loanOverdueRepository.findByLoanAndRank(loan, rank);
//					// 根据逾期等级获取费率,如获取为空,则表示坏账,获取为非空,采用获取费率计算
//					if (loanOverdue == null) {
//						loanOverdue = loanOverdueRepository.findByLoanAndRank(loan, 0);
//					}
//					RepayMethod repayMethod = getRepayMethod(loan.getRepay().getId());
//
//					// 计算借款人逾期管理费
//					BigDecimal overduePenalty = repayMethod.getOverduePenalty(overdueDay, loan.getPeriod() - unRepay.getSequence() + 1, unRepay.getOtherAmount(), loanOverdue.getPenalty());
//					// 计算逾期罚息
//					BigDecimal overdueInterest = repayMethod.getOverdueInterest(overdueDay, loan.getPeriod() - unRepay.getSequence() + 1, unRepay.getAmount(), loanOverdue.getInterest());
//
//
//					unRepay.setOverdueDays(unRepay.getOverdueDays());
//					unRepay.setOverdueInterest(unRepay.getOverdueInterest());
//					unRepay.setOverduePenalty(unRepay.getOverduePenalty());
//					//em.clear();
//				}
				loanRepayRecords.set(0, unRepay);
			} else {
				loanRepayRecords.remove(0);
			}
			Long total = Long.valueOf(loanRepayRecords.size());
			Page<LoanRepay> pageLoanRepay = new PageImpl<LoanRepay>(loanRepayRecords, pageable, total);
			return pageLoanRepay;
		} else {
			Long total = Long.valueOf(loanRepayRecords.size());
			Page<LoanRepay> pageLoanRepay = new PageImpl<LoanRepay>(loanRepayRecords, pageable, total);
			return pageLoanRepay;
		}
	}

	/**
	 * 通过借款信息获取还款计划
	 */
	public List<LoanRepay> findLoanRepay(Loan loan) {
		return loanRepayRepository.findByLoan(loan);
	}

	/**
	 * 还款实现
	 *
	 * @param loan
	 * @param sequence
	 */
	@Override
	@Transactional
	public boolean repayment(String id) {
		LoanRepay loanRepay = loanRepayRepository.findOne(id);
		// 判断假如借款还款状态为正常还款或者逾期还款,说明已经还过了,无须再还
		if (Strings.equals(loanRepay.getStatus(), RepayStatus.NORMAL) ||
			Strings.equals(loanRepay.getStatus(), RepayStatus.OVERDUE_REPAY)) {
			return false;
		}
		int success;
		Date now = new Date();
		Loan loan = loanRepay.getLoan();
		if(!(Loan.LoanKinds.NORML_LOAN.equals(loan.getLoanKind()) ||
		   Loan.LoanKinds.OUTSIDE_ASSIGN_LOAN.equals(loan.getLoanKind()))){
			Logger.info("标编号="+loan.getLoanNo()+",类型:loanKind="+loan.getLoanKind()+",不走公共还款业务处理");
			return false;
		}
		// 取得借款还款的最大期数
		Integer loanMaxSequence = loanRepayRepository.findMaxSequenceByloan(loan);
		BigDecimal amount = BigDecimal.ZERO; // 总还款=总本金+总利息+管理费+逾期违约金+逾期罚息
		BigDecimal principal = BigDecimal.ZERO; // 总本金
		BigDecimal interest = BigDecimal.ZERO; // 总利息
		// 还月缴管理费
		transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.LOAN_MONTHLY_FEE, loanRepay.getOtherAmount(), loanRepay.getId(), "缴纳公司月缴管理费");
		// 如果状态为等待还款,为正常还款
		if (Strings.equals(loanRepay.getStatus(), RepayStatus.WAIT)) {
			List<InvestProfit> investProfitList = investProfitRepository.findByLoanRepay(loanRepay);
			for (InvestProfit investProfit : investProfitList) {
				// 还本金
				transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getPrincipal(), investProfit.getId(), "正常还本金");
				principal = principal.add(investProfit.getPrincipal());
				// 还利息
				transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getInterest(), investProfit.getId(), "正常还利息");
				interest = interest.add(investProfit.getInterest());
				// 更新理财收益表
				investProfit.setStatus(InvestProfit.Status.ALREADY);
				investProfitRepository.save(investProfit);
			}
			// 总还款=总本金+总利息+管理费
			// amount =amount.add(principal).add(interest).add(loanRepay.getOtherAmount());
			// 总还款=总本金+总利息
			amount = amount.add(principal).add(interest);
			loanRepay.setRepayDatetime(now);
			loanRepay.setAmount(amount);
			loanRepay.setPrincipal(principal);
			loanRepay.setInterest(interest);
			loanRepay.setStatus(RepayStatus.NORMAL);
			// 更新还款计划表状态,从待还款 至 正常还款
			success = loanRepayNativeRepository.updateStatus(loanRepay, RepayStatus.WAIT);
			if (success != 1) {
				throw new ServiceException("normal repay fail!");
				// 未成功执行,回滚
				// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}

		} else if (Strings.equals(loanRepay.getStatus(), RepayStatus.OVERDUE)) {
			// 计算逾期天数
			int overdueDay = getOverdueDays(loanRepay.getPlanDatetime(), now);
			// 计算逾期等级
			Integer rank = (overdueDay - 1) / 30 + 1;
			LoanOverdue loanOverdue = loanOverdueRepository.findByLoanAndRank(loan, rank);
			// 根据逾期等级获取费率,如获取为空,则表示坏账,默认rank为0的表示坏账的费率,获取为非空,采用获取费率计算
			if (loanOverdue == null) {
				loanOverdue = loanOverdueRepository.findByLoanAndRank(loan, 0);
			}
			RepayMethod repayMethod = getRepayMethod(loan.getRepay().getId());
			// 计算借款人逾期违约金
			BigDecimal overduePenalty = repayMethod.getOverduePenalty(overdueDay, loan.getPeriod() - loanRepay.getSequence() + 1, loanRepay.getOtherAmount(), loanOverdue.getPenalty());
			// 计算逾期罚息
			BigDecimal overdueInterest = repayMethod.getOverdueInterest(overdueDay, loan.getPeriod() - loanRepay.getSequence() + 1, loanRepay.getAmount(), loanOverdue.getInterest());

			BigDecimal allInvestOverDueInterest = BigDecimal.ZERO;
			// 还逾期违约金
			transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.OVERDUE_FEE, overduePenalty, loanRepay.getId(), "还逾期管理费");
			List<InvestProfit> investProfitList = investProfitRepository.findByLoanRepay(loanRepay);
			for (InvestProfit investProfit : investProfitList) {
				BigDecimal investOverDueInterest = investProfit.getInvest().getRatio().multiply(overdueInterest).setScale(2, BigDecimal.ROUND_DOWN); // 单个人的逾期罚息=借款人的逾期罚息X占比(截取2位小数)
				// 假如此笔投标已经垫付,则还款还给垫付账户
				if (Status.ADVANCE.equals(investProfit.getStatus())) {
					transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.RISK, investProfit.getPrincipal(), loanRepay.getId(), "已垫付客户还本金到风险金");
					principal = principal.add(investProfit.getPrincipal());
					transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.RISK, investProfit.getInterest(), loanRepay.getId(), "已垫付客户还利息到风险金");
					interest = interest.add(investProfit.getInterest());
					transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.RISK, investOverDueInterest, loanRepay.getId(), "已垫付客户还预期罚息到风险金");
					allInvestOverDueInterest = allInvestOverDueInterest.add(investOverDueInterest);
				} else {
					// 还本金
					transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getPrincipal(), investProfit.getId(), "还本金");
					principal = principal.add(investProfit.getPrincipal());
					// 还利息
					transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getInterest(), investProfit.getId(), "还利息");
					interest = interest.add(investProfit.getInterest());
					// 还逾期罚息
					transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investOverDueInterest, investProfit.getId(), "还逾期罚息");
					allInvestOverDueInterest = allInvestOverDueInterest.add(investOverDueInterest);

					// 更新理财收益表
					investProfit.setAmount(amount);
					investProfit.setStatus(com.jlfex.hermes.model.InvestProfit.Status.ALREADY); // 状态更新为已收款
					investProfit.setOverdueInterest(overdueInterest); // 逾期利息
					investProfitRepository.save(investProfit);
				}
			}
			// 总还款=总本金+总利息+管理费+逾期违约金+逾期罚息
			amount = amount.add(principal).add(interest).add(loanRepay.getOtherAmount()).add(overduePenalty).add(overdueInterest);
			loanRepay.setRepayDatetime(now);
			loanRepay.setAmount(amount);
			loanRepay.setPrincipal(principal);
			loanRepay.setInterest(interest);
			loanRepay.setOverdueDays(overdueDay);
			loanRepay.setOverdueInterest(allInvestOverDueInterest);
			loanRepay.setOverduePenalty(overduePenalty);
			loanRepay.setStatus(RepayStatus.OVERDUE_REPAY);
			success = loanRepayNativeRepository.updateStatus(loanRepay, RepayStatus.OVERDUE);
			if (success != 1) {
				throw new ServiceException("overdue repay fail!");
				// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		// 判断假如借款最大还款期数等于该笔的还款期数,说明是最后一笔还款,改该笔借款的状态为完成
		if (loanMaxSequence == loanRepay.getSequence()) {
			success = loanNativeRepository.updateStatus(loanRepay.getLoan().getId(), Loan.Status.REPAYING, Loan.Status.COMPLETED);
			if (success != 1) {
				throw new ServiceException("loanNativeRepository updateStatus from REPAYING  to COMPLETED Error!");
			}
			// 插入借款日志
			saveLoanLog(loan.getUser().getId(), loanRepay.getLoan(), Type.COMPLETE, loanRepay.getAmount(), "借款完成");
			// 还款完成时 更新 债权
			if(Loan.LoanKinds.OUTSIDE_ASSIGN_LOAN.equals(loan.getStatus())){
				updateCreditInfoFull(loan);
			}
		}
		// 插入借款日志
		saveLoanLog(loan.getUser().getId(), loanRepay.getLoan(), Type.REPAY, loanRepay.getAmount(),
		String.format("应还本息:%s ,管理费:%s ,逾期违约金:%s ,逾期罚息%s ,逾期天数%s ",
		loanRepay.getAmount(),loanRepay.getOtherAmount(),loanRepay.getOverduePenalty(),loanRepay.getOverdueInterest(),loanRepay.getOverdueDays()));
		return true;
	}

	public void updateCreditInfoFull(Loan loan){
		if(loan != null && loan.getCreditIndex() !=null){
			try {
				CrediteInfo creditInfo = creditInfoService.findById(loan.getCreditIndex());
				creditInfo.setStatus(CrediteInfo.Status.REPAY_FIINISH);
				creditInfoService.save(creditInfo);
			} catch (Exception e) {
				Logger.error("更新债权状态为:"+CrediteInfo.Status.REPAY_FIINISH+"。异常,债权标Id="+loan.getId());
			}
		}
	}

	/**
	 * 插入借款日志
	 *
	 * @param user
	 * @param loan
	 * @param type
	 * @param amount
	 * @param remark
	 */
	public void saveLoanLog(String user, Loan loan, String type, BigDecimal amount, String remark) {
		LoanLog loanLog = new LoanLog();
		loanLog.setUser(user);
		loanLog.setLoan(loan);
		loanLog.setDatetime(new Date());
		loanLog.setType(type);
		loanLog.setAmount(amount);
		loanLog.setRemark(remark);
		loanLogRepository.save(loanLog);
	}

	/**
	 * 计算逾期天数 ( 逾期天数=计划还款日-当前日期)
	 *
	 * @param repayDay
	 * @param edit_date
	 * @return
	 */
	public static int getOverdueDays(Date repayDay, Date now) {
		long temp = 0;
		if (repayDay.getTime() >= now.getTime()) {
			return 0;
		} else {
			temp = now.getTime() - repayDay.getTime();
		}
		return (int) (temp / 86400000);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.jlfex.hermes.service.RepayService#getRepayMethod(java.lang.String)
	 */
	@Override
	public RepayMethod getRepayMethod(String repayId) {
		Repay repay = repayRepository.findOne(repayId);
		if (repay == null)
			throw new ServiceException("repay is invaild.");

		try {
			return SpringWebApp.getBean(repay.getCode(), RepayMethod.class);
		} catch (Exception e) {
			try {
				return RepayMethod.class.cast(Class.forName(repay.getClazz()).newInstance());
			} catch (InstantiationException ex) {
				throw new ServiceException("cannot get class instance '" + repay.getClazz() + "'", ex);
			} catch (IllegalAccessException ex) {
				throw new ServiceException("cannot get class instance '" + repay.getClazz() + "'", ex);
			} catch (ClassNotFoundException ex) {
				throw new ServiceException("cannot get class instance '" + repay.getClazz() + "'", ex);
			}
		}
	}

	@Override
	public List<Repay> findAll() {
		return repayRepository.findAll();
	}

	@Override
	public boolean updateStatus(String id, String fromStatus, String toStatus) {
		int success = loanRepayNativeRepository.updateStatus(id, fromStatus, toStatus);
		if (success == 1) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public List<LoanRepay> findByPlanDatetimeBetweenAndStatus(Date startPlanDatetime, Date endPlanDatetime, String status) {
		return loanRepayRepository.findByPlanDatetimeBetweenAndStatus(startPlanDatetime, endPlanDatetime, status);
	}

	@Override
	public List<LoanRepay> findByStatus(String status) {
		return loanRepayRepository.findByStatus(status);
	}

	@Override
	public boolean overdueCalc(LoanRepay loanRepay) {
		if (!Strings.equals(loanRepay.getStatus(), RepayStatus.OVERDUE)) {
			return false;
		}
		Date now = new Date();
		int success;
		Loan loan = loanRepay.getLoan();
		// 计算逾期天数
		int overdueDay = getOverdueDays(loanRepay.getPlanDatetime(), now);
		// 计算逾期等级
		Integer rank = (overdueDay - 1) / 30 + 1;
		if (Caches.get(CACHE_LOAN_OVERDUE_PREFIX + loanRepay.getId() + "." + rank) == null) {
			LoanOverdue loanOverdue = loanOverdueRepository.findByLoanAndRank(loan, rank);
			// 根据逾期等级获取费率,如获取为空,则表示坏账,默认rank为0的表示坏账的费率,获取为非空,采用获取费率计算
			if (loanOverdue == null) {
				List<LoanOverdue> lists = loanOverdueRepository.findByLoan(loan);
				if(lists ==null || lists.size() == 0){
					Logger.error("标loanNo="+loan.getLoanNo()+",没有配置逾期等级,无法计算逾期费用");
					return false;
				}
				Collections.sort(lists, new Comparator<LoanOverdue>(){
					public int compare(LoanOverdue obj1, LoanOverdue obj2) {
						return obj1.getRank()>obj2.getRank()? 1:-1;
					}
				});
				loanOverdue = lists.get(lists.size()-1);
			}
			Caches.set(CACHE_LOAN_OVERDUE_PREFIX + loanRepay.getId() + "." + rank, loanOverdue, "1d");
		}
		RepayMethod repayMethod = getRepayMethod(loan.getRepay().getId());
		LoanOverdue loanOverdue = Caches.get(CACHE_LOAN_OVERDUE_PREFIX + loanRepay.getId() + "." + rank, LoanOverdue.class);
		if (loanOverdue != null) {
			// 计算借款人逾期管理费
			BigDecimal overduePenalty = repayMethod.getOverduePenalty(overdueDay, loan.getPeriod() - loanRepay.getSequence() + 1, loanRepay.getOtherAmount(), loanOverdue.getPenalty());
			// 计算逾期罚息
			BigDecimal overdueInterest = repayMethod.getOverdueInterest(overdueDay, loan.getPeriod() - loanRepay.getSequence() + 1, loanRepay.getAmount(), loanOverdue.getInterest());
			BigDecimal allInvestOverDueInterest = BigDecimal.ZERO;
			List<InvestProfit> investProfitList = investProfitRepository.findByLoanRepay(loanRepay);
			for (InvestProfit investProfit : investProfitList) {
				BigDecimal investOverDueInterest = investProfit.getInvest().getRatio().multiply(overdueInterest).setScale(2, BigDecimal.ROUND_DOWN); // 单个人的逾期罚息=借款人的逾期罚息X占比(截取2位小数)
				allInvestOverDueInterest = allInvestOverDueInterest.add(investOverDueInterest);
			}
			loanRepay.setOverdueDays(overdueDay);
			loanRepay.setOverdueInterest(allInvestOverDueInterest);
			loanRepay.setOverduePenalty(overduePenalty);
			success = loanRepayNativeRepository.overdueCalc(loanRepay, RepayStatus.OVERDUE);
			if (success != 1) {
				throw new ServiceException("overdue calc fail!");
			} else {
				return true;
			}
		} else {
			return false;
		}

	}

	@Override
	public boolean autoRepayment(String id) throws Exception{
		LoanRepay loanRepay = loanRepayRepository.findOne(id);
		// 判断假如借款还款状态为正常还款说明已经还过了,无须再还
		if (Strings.equals(loanRepay.getStatus(), RepayStatus.NORMAL)) {
			return false;
		}
		// 取得借款还款的最大期数
		Integer loanMaxSequence = loanRepayRepository.findMaxSequenceByloan(loanRepay.getLoan());
		int success;
		Date now = new Date();
		Loan loan = loanRepay.getLoan();
		BigDecimal amount = BigDecimal.ZERO; // 总还款=总本金+总利息+管理费+逾期违约金+逾期罚息
		BigDecimal principal = BigDecimal.ZERO; // 总本金
		BigDecimal interest = BigDecimal.ZERO; // 总利息
		// 还月缴管理费
		transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.LOAN_MONTHLY_FEE, loanRepay.getOtherAmount(), loanRepay.getId(), "自动还款_缴纳月缴管理费");
		// 如果状态为等待还款,为正常还款
		String status = loanRepay.getStatus();
		if (RepayStatus.WAIT.equals(status) || RepayStatus.OVERDUE.equals(status)) {
			List<InvestProfit> investProfitList = investProfitRepository.findByLoanRepay(loanRepay);
			// 还逾期违约金
			if(RepayStatus.OVERDUE.equals(status)){
				transactionService.toCropAccount(Transaction.Type.OUT, loan.getUser(), UserAccount.Type.OVERDUE_FEE, loanRepay.getOverduePenalty(), loanRepay.getId(), "自动还款_还逾期违约金");
			}
			for (InvestProfit investProfit : investProfitList) {
				// 还逾期罚息
				if(RepayStatus.OVERDUE.equals(status)){
					BigDecimal overInerest = investProfit.getInvest().getRatio().multiply(loanRepay.getOverdueInterest()) ;
					transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), overInerest, investProfit.getId(), "自动还款_还逾期罚息");
				}
				// 还本金
				transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getPrincipal(), investProfit.getId(), "自动还款_正常还本金");
				principal = principal.add(investProfit.getPrincipal());
				// 还利息
				transactionService.transact(Transaction.Type.OUT, loan.getUser(), investProfit.getUser(), investProfit.getInterest(), investProfit.getId(), "自动还款_正常还利息");
				interest = interest.add(investProfit.getInterest());
				// 更新理财收益表
				if(RepayStatus.OVERDUE.equals(status)){
					BigDecimal overInerest = investProfit.getInvest().getRatio().multiply(loanRepay.getOverdueInterest()) ;
					investProfit.setOverdueInterest(overInerest);
				}
				investProfit.setStatus(InvestProfit.Status.ALREADY);
				investProfitRepository.save(investProfit);
			}
			// 总还款=总本金+总利息
			amount = amount.add(principal).add(interest);
			loanRepay.setRepayDatetime(now);
			loanRepay.setAmount(amount);
			loanRepay.setPrincipal(principal);
			loanRepay.setInterest(interest);
			if(RepayStatus.WAIT.equals(status)){
				loanRepay.setStatus(RepayStatus.NORMAL);
			}else{
				loanRepay.setStatus(RepayStatus.OVERDUE_REPAY);
			}
			// 更新还款计划表状态,从待还款 至 正常还款
			success = loanRepayNativeRepository.updateStatus(loanRepay,status);
			if (success != 1) {
				throw new ServiceException("auto normal repay fail!");
				// 未成功执行,回滚
				// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}

		}
		// 判断假如借款最大还款期数等于该笔的还款期数,说明是最后一笔还款,改该笔借款的状态为完成
		if (loanMaxSequence == loanRepay.getSequence()) {
			success = loanNativeRepository.updateStatus(loanRepay.getLoan().getId(), Loan.Status.REPAYING, Loan.Status.COMPLETED);
			if (success != 1) {
				throw new ServiceException("loanNativeRepository updateStatus from REPAYING  to COMPLETED Error!");
			}
			// 插入借款日志
			saveLoanLog(loan.getUser().getId(), loanRepay.getLoan(), Type.COMPLETE, loanRepay.getAmount(), "借款自动还款完成");
		}
		// 插入借款日志
		saveLoanLog(loan.getUser().getId(), loanRepay.getLoan(), Type.REPAY, loanRepay.getAmount(), "借款自动还款");
		return true;
	}
    /**
     * 根据名称 和 状态   获取还款方式
     */
	@Override
	public List<Repay> findByNameAndStatusIn(String name, String... status) throws Exception {
		return repayRepository.findByNameAndStatusIn(name, Arrays.asList(status));
	}
	/**
	 * 根据标 和 状态   获取还款计划明细
	 */
	@Override
	public List<LoanRepay> findByLoanAndStatus(Loan loan, String status) {
		return loanRepayRepository.findByLoanAndStatus(loan, status);
	}
}


text:
package com.streamsets.pipeline.api.impl.annotationsprocessor;

import com.streamsets.pipeline.api.ConfigIssue;
import com.streamsets.pipeline.api.service.Service;
import com.streamsets.pipeline.api.service.ServiceDef;

import java.util.List;

@ServiceDef(
  provides = Runnable.class,
  version = 1,
  label = "Dummy service"
)
public class DummyService implements Service, Runnable {
  @Override
  public List<ConfigIssue> init(Context context) {
    return null;
  }

  @Override
  public void destroy() {

  }

  @Override
  public void run() {

  }
}

redpajama_set_name: RedPajamaGithub


text:
package edu.ehu.galan.cvalue.filters.spanish;

import edu.ehu.galan.cvalue.filters.ILinguisticFilter;
import edu.ehu.galan.cvalue.model.Token;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Implements an open filter based in this regular expressions
 * ((<Noun><Preposition>|<Noun>)(<Adjetive>)?<Noun>(<<Adjetive>>)?)+ using POS
 * tags of Freeling POS Analyzer  (EAGLES spanish tagset)
 *
 * @author Angel Conde Manjon
 */
public class NounAdjOpenFilter implements ILinguisticFilter {

    private List<String> list;

    @Override
    public List<String> getCandidates(LinkedList<Token> pSentence) {
        list = new ArrayList<>();
        if (pSentence != null) {
            for (Token token : pSentence) {
                if (token.getPosTag().matches("N.*")) {
                    int pos = pSentence.indexOf(token);
                    findCandidate(pSentence, pos);

                }
            }
        }
        return list;
    }

    private void findCandidate(LinkedList<Token> pSentence, int pPos) {
        Pattern pat = Pattern.compile("((<N......><SP...>|<N......>)(<A.....>)?<N......>(<A.....>)?)+");
        int sentenceSize = pSentence.size();
        StringBuilder sb = new StringBuilder();
        int j = 0;
        sb.append("<").append(pSentence.get(pPos).getPosTag()).append(">");
        for (int i = pPos + 1; i < pSentence.size(); i++) {
            sb.append("<").append(pSentence.get(i).getPosTag()).append(">");
            Matcher mat = pat.matcher(sb.toString());
            if (mat.matches()) {
                String term = "";
                for (int x = pPos; x <= i; x++) {
                    term = term + pSentence.get(x).getWordForm() + " ";
                }
                list.add(term.trim());
                System.out.println(term);

            }
        }

    }

}


text:
from contextlib import contextmanager
import os
import sys

from django.test import TestCase
from django.test.runner import DiscoverRunner
from django.utils.unittest import expectedFailure

try:
    import unittest2
except ImportError:
    unittest2 = None

def expectedFailureIf(condition):
    """Marks a test as an expected failure if ``condition`` is met."""
    if condition:
        return expectedFailure
    return lambda func: func

class DiscoverRunnerTest(TestCase):

    def test_dotted_test_module(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample"],
        ).countTestCases()

        self.assertEqual(count, 3)

    def test_dotted_test_class_vanilla_unittest(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestVanillaUnittest"],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_class_unittest2(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestUnittest2"],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_class_django_testcase(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestDjangoTestCase"],
        ).countTestCases()

        self.assertEqual(count, 1)

    # this test fails if unittest2 is installed from PyPI on Python 2.6
    # refs https://code.djangoproject.com/ticket/20437
    @expectedFailureIf(sys.version_info < (2, 7) and unittest2)
    def test_dotted_test_method_vanilla_unittest(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestVanillaUnittest.test_sample"],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_method_unittest2(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestUnittest2.test_sample"],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_method_django_testcase(self):
        count = DiscoverRunner().build_suite(
            ["test_discovery_sample.tests_sample.TestDjangoTestCase.test_sample"],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_pattern(self):
        count = DiscoverRunner(
            pattern="*_tests.py",
        ).build_suite(["test_discovery_sample"]).countTestCases()

        self.assertEqual(count, 1)

    def test_file_path(self):
        @contextmanager
        def change_cwd_to_tests():
            """Change CWD to tests directory (one level up from this file)"""
            current_dir = os.path.abspath(os.path.dirname(__file__))
            tests_dir = os.path.join(current_dir, '..')
            old_cwd = os.getcwd()
            os.chdir(tests_dir)
            yield
            os.chdir(old_cwd)

        with change_cwd_to_tests():
            count = DiscoverRunner().build_suite(
                ["test_discovery_sample/"],
            ).countTestCases()

        self.assertEqual(count, 4)


text:
function results = vl_test(suite, test)
% VL_TEST  Run test suite
%  RESULTS = VL_TEST() runs all VLFeat test suites. The tests
%  verify that VLFeat is working correctly.
%
%  RESULTS is a structure listing the result of each test.
%  It has fileds:
%
%  TESTNAME:   name of the test
%  SUCCEDED:   a boolean flag indicating whether the test succeded
%  EXCEPTION:  the exception generated if the test failed
%
%  VL_TEST(SUITE) runs only the specified SUITE.
%
%  VL_TEST(SUITE, TEST) runs the specified SUITE/TEST without catching
%  the potential exception. Useful to DBSTOP to debug.
%
%  Author:: Andrea Vedaldi

% AUTORIGHTS
% Copyright (C) 2007-10 Andrea Vedaldi and Brian Fulkerson
%
% This file is part of VLFeat, available under the terms of the
% GNU GPLv2, or (at your option) any later version.

clear functions ;

testRoot = fileparts(mfilename('fullpath')) ;

if nargin == 0
  files = dir(fullfile(testRoot, 'vl_test_*m')) ;
elseif nargin == 1
  files.name = fullfile(['vl_test_' suite '.m']) ;
end

if nargin < 2
  results = {} ;
  for i = 1:length(files)
    testCommand = files(i).name(1:end-2) ;
    if strcmp(testCommand, 'vl_test_init'), continue ; end
    fprintf('vl_test: running %s\n', testCommand) ;
    results{i} = feval(str2func(testCommand)) ;
  end

  results = cat(2, results{:}) ;
  for i = 1:length(results)
    if results(i).succeded
      fprintf('vl_test: %-35s ... passed\n', results(i).testName) ;
    else
      fprintf('vl_test: %-35s ... failed\n', results(i).testName) ;
      fprintf('%s:%d: %s\n', ...
              results(i).exception.stack(1).name, ...
              results(i).exception.stack(1).line, ...
              results(i).exception.message) ;
    end
  end

else
  feval(str2func(sprintf('vl_test_%s', suite)), test) ;
end


text:
namespace Microsoft.WindowsAzure.Storage.File
{
    using Microsoft.Azure.KeyVault;
    using Microsoft.Azure.KeyVault.Core;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.WindowsAzure.Storage.Core;
    using Microsoft.WindowsAzure.Storage.Shared.Protocol;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Security.Cryptography;
    using System.Threading;
    using System.Threading.Tasks;

    [TestClass]
    public class FileServerEncryptionTests : FileTestBase
    {
        private CloudFileShare share;
        private CloudFileDirectory directory;
        private CloudFile file;

        // Use TestInitialize to run code before running each test
        [TestInitialize()]
        public void MyTestInitialize()
        {
            if (TestBase.FileBufferManager != null)
            {
                TestBase.FileBufferManager.OutstandingBufferCount = 0;
            }

            this.share = GetRandomShareReference();
            this.share.CreateIfNotExists();
            CloudFileDirectory directory = share.GetRootDirectoryReference();
            this.directory = directory.GetDirectoryReference("directory");
            this.directory.Create();
            this.file = this.directory.GetFileReference("file");
            this.file.UploadText("test");
        }

        // Use TestCleanup to run code after each test has run
        [TestCleanup()]
        public void MyTestCleanup()
        {
            if (TestBase.FileBufferManager != null)
            {
                Assert.AreEqual(0, TestBase.FileBufferManager.OutstandingBufferCount);
            }

            this.share.DeleteIfExists();
        }

        [TestMethod]
        [Description("Download encrypted file attributes.")]
        [TestCategory(ComponentCategory.File)]
        [TestCategory(TestTypeCategory.UnitTest)]
        [TestCategory(SmokeTestCategory.NonSmoke)]
        [TestCategory(TenantTypeCategory.DevFabric)]
        [TestCategory(TenantTypeCategory.Cloud)]
        public void TestFileAttributesEncryption()
        {
            this.file.FetchAttributes();
            Assert.IsTrue(this.file.Properties.IsServerEncrypted);

            CloudFile testFile = this.directory.GetFileReference(this.file.Name);
            testFile.DownloadText();
            Assert.IsTrue(testFile.Properties.IsServerEncrypted);
        }

        [TestMethod]
        [Description("Upload encrypted file.")]
        [TestCategory(ComponentCategory.File)]
        [TestCategory(TestTypeCategory.UnitTest)]
        [TestCategory(SmokeTestCategory.NonSmoke)]
        [TestCategory(TenantTypeCategory.DevFabric)]
        [TestCategory(TenantTypeCategory.Cloud)]
        public void TestFileEncryption()
        {
            bool requestFound = false;

            OperationContext ctxt = new OperationContext();
            ctxt.RequestCompleted += (sender, args) =>
            {
                Assert.IsTrue(args.RequestInformation.IsRequestServerEncrypted);
                requestFound = true;
            };

            this.file.UploadText("test", null, null, null, ctxt);
            Assert.IsTrue(requestFound);

            requestFound = false;
            this.file.SetProperties(null, null, ctxt);
            Assert.IsTrue(requestFound);

            requestFound = false;
            this.file.SetMetadata(null, null, ctxt);
            Assert.IsTrue(requestFound);
        }

        [TestMethod]
        [Description("Upload encrypted file directory.")]
        [TestCategory(ComponentCategory.File)]
        [TestCategory(TestTypeCategory.UnitTest)]
        [TestCategory(SmokeTestCategory.NonSmoke)]
        [TestCategory(TenantTypeCategory.DevFabric)]
        [TestCategory(TenantTypeCategory.Cloud)]
        public void TestFileDirectoryEncryption()
        {
            bool requestFound = false;

            OperationContext ctxt = new OperationContext();
            ctxt.RequestCompleted += (sender, args) =>
            {
                Assert.IsTrue(args.RequestInformation.IsRequestServerEncrypted);
                requestFound = true;
            };

            CloudFileDirectory dir2 = this.share.GetRootDirectoryReference().GetDirectoryReference("dir2");
            dir2.Create(null, ctxt);
            Assert.IsTrue(requestFound);

            requestFound = false;
            dir2.SetMetadata(null, null, ctxt);
            Assert.IsTrue(requestFound);
        }
    }
}


text:
package org.pcap4j.packet;

import static org.pcap4j.util.ByteArrays.*;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.List;
import org.pcap4j.util.ByteArrays;

/**
 * @author Kaito Yamada
 * @since pcap4j 0.9.11
 */
public final class IcmpV4RedirectPacket extends IcmpV4InvokingPacketPacket {

  /**
   *
   */
  private static final long serialVersionUID = 5987521162450318499L;

  private final IcmpV4RedirectHeader header;

  /**
   * A static factory method.
   * This method validates the arguments by {@link ByteArrays#validateBounds(byte[], int, int)},
   * which may throw exceptions undocumented here.
   *
   * @param rawData rawData
   * @param offset offset
   * @param length length
   * @return a new IcmpV4RedirectPacket object.
   * @throws IllegalRawDataException if parsing the raw data fails.
   */
  public static IcmpV4RedirectPacket newPacket(
    byte[] rawData, int offset, int length
  ) throws IllegalRawDataException {
    ByteArrays.validateBounds(rawData, offset, length);

    IcmpV4RedirectHeader header = new IcmpV4RedirectHeader(rawData, offset, length);

    int payloadLength = length - header.length();
    if (payloadLength > 0) {
      return new IcmpV4RedirectPacket(header, rawData, offset + header.length(), payloadLength);
    }
    else {
      return new IcmpV4RedirectPacket(header);
    }
  }

  private IcmpV4RedirectPacket(IcmpV4RedirectHeader header) {
    this.header = header;
  }

  private IcmpV4RedirectPacket(
    IcmpV4RedirectHeader header, byte[] rawData, int payloadOffset, int payloadLength
  ) {
    super(rawData, payloadOffset, payloadLength);
    this.header = header;
  }

  private IcmpV4RedirectPacket(Builder builder) {
    super(builder);

    if (builder.gatewayInternetAddress == null) {
      StringBuilder sb = new StringBuilder();
      sb.append("builder.gatewayInternetAddress: ")
        .append(builder.gatewayInternetAddress);
      throw new NullPointerException(sb.toString());
    }

    this.header = new IcmpV4RedirectHeader(builder);
  }

  @Override
  public IcmpV4RedirectHeader getHeader() {
    return header;
  }

  @Override
  public Builder getBuilder() {
    return new Builder(this);
  }

  /**
   * @author Kaito Yamada
   * @since pcap4j 0.9.11
   */
  public static final class Builder
  extends org.pcap4j.packet.IcmpV4InvokingPacketPacket.Builder {

    private Inet4Address gatewayInternetAddress;

    /**
     *
     */
    public Builder() {}

    private Builder(IcmpV4RedirectPacket packet) {
      super(packet);
      this.gatewayInternetAddress = packet.header.gatewayInternetAddress;
    }

    /**
     *
     * @param gatewayInternetAddress gatewayInternetAddress
     * @return this Builder object for method chaining.
     */
    public Builder gatewayInternetAddress(Inet4Address gatewayInternetAddress) {
      this.gatewayInternetAddress = gatewayInternetAddress;
      return this;
    }

    @Override
    public Builder payload(Packet payload) {
      super.payload(payload);
      return this;
    }

    @Override
    public IcmpV4RedirectPacket build() {
      return new IcmpV4RedirectPacket(this);
    }

  }

  /**
   * @author Kaito Yamada
   * @since pcap4j 0.9.11
   */
  public static final class IcmpV4RedirectHeader extends AbstractHeader {

    /*
     *  0                            15                              31
     * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     * |                 Gateway Internet Address                      |
     * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     *
     */

    /**
     *
     */
    private static final long serialVersionUID = -7093717116891501880L;

    private static final int GATEWAY_INTERNET_ADDRESS_OFFSET
      = 0;
    private static final int GATEWAY_INTERNET_ADDRESS_SIZE
      = INET4_ADDRESS_SIZE_IN_BYTES;
    private static final int ICMPV4_REDIRECT_HEADER_SIZE
      = GATEWAY_INTERNET_ADDRESS_OFFSET + GATEWAY_INTERNET_ADDRESS_SIZE;

    private final Inet4Address gatewayInternetAddress;

    private IcmpV4RedirectHeader(
      byte[] rawData, int offset, int length
    ) throws IllegalRawDataException {
      if (length < ICMPV4_REDIRECT_HEADER_SIZE) {
        StringBuilder sb = new StringBuilder(80);
        sb.append("The data is too short to build an ICMPv4 Redirect Header(")
          .append(ICMPV4_REDIRECT_HEADER_SIZE)
          .append(" bytes). data: ")
          .append(ByteArrays.toHexString(rawData, " "))
          .append(", offset: ")
          .append(offset)
          .append(", length: ")
          .append(length);
        throw new IllegalRawDataException(sb.toString());
      }

      this.gatewayInternetAddress
        = ByteArrays.getInet4Address(rawData, GATEWAY_INTERNET_ADDRESS_OFFSET + offset);
   }

    private IcmpV4RedirectHeader(Builder builder) {
      this.gatewayInternetAddress = builder.gatewayInternetAddress;
    }

    /**
     *
     * @return gatewayInternetAddress
     */
    public Inet4Address getGatewayInternetAddress() {
      return gatewayInternetAddress;
    }

    @Override
    protected List<byte[]> getRawFields() {
      List<byte[]> rawFields = new ArrayList<byte[]>();
      rawFields.add(ByteArrays.toByteArray(gatewayInternetAddress));
      return rawFields;
    }

    @Override
    public int length() {
      return ICMPV4_REDIRECT_HEADER_SIZE;
    }

    @Override
    protected String buildString() {
      StringBuilder sb = new StringBuilder();
      String ls = System.getProperty("line.separator");

      sb.append("[ICMPv4 Redirect Header (")
        .append(length())
        .append(" bytes)]")
        .append(ls);
      sb.append("  Gateway Internet Address: ")
        .append(gatewayInternetAddress)
        .append(ls);

      return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
      if (obj == this) { return true; }
      if (!this.getClass().isInstance(obj)) { return false; }

      IcmpV4RedirectHeader other = (IcmpV4RedirectHeader)obj;
      return gatewayInternetAddress.equals(other.gatewayInternetAddress);
    }

    @Override
    protected int calcHashCode() {
      int result = 17;
      result = 31 * result + gatewayInternetAddress.hashCode();
      return result;
    }

  }

}


text:
package net.aquadc.vkauth;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.SparseArray;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static java.util.Collections.unmodifiableSet;
import static java.util.EnumSet.of;
import static net.aquadc.vkauth.Util.explodeQueryString;
import static net.aquadc.vkauth.Util.required;

/**
 * Created by mike on 21.02.17
 * Represents an app registered in VK. An entry point for performing auth.
 */

public final class VkApp {

    private static final String VkExtraTokenData = "extra-token-data";
    private static final String VkApiVersion = "5.62";

    /*pkg*/ static final int RcVkAuth = 30_109;

    private static final Intent AuthIntent =
            new Intent("com.vkontakte.android.action.SDK_AUTH").setPackage("com.vkontakte.android");

    private static final Set<AuthenticationWay> VkAppInstalled =
            unmodifiableSet(of(AuthenticationWay.OfficialVkApp, AuthenticationWay.WebView, AuthenticationWay.Auto));
    private static final Set<AuthenticationWay> VkAppNotInstalled =
            unmodifiableSet(of(AuthenticationWay.WebView, AuthenticationWay.Auto));

    // static

    private static final SparseArray<VkApp> Instances = new SparseArray<>(1);

    public static VkApp getInstance(int appId) {
        if (appId <= 0) throw new IllegalArgumentException("invalid appId: " + appId);

        synchronized (Instances) {
            VkApp app = Instances.get(appId);
            if (app == null) {
                app = new VkApp(appId);
                Instances.put(appId, app);
            }
            return app;
        }
    }

    /*pkg*/ static boolean isInstalled(Context context) {
        if (context.getPackageManager().queryIntentActivities(AuthIntent, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) {
            return false;
        }

        try {
            String[] certs = Util.getCertificateFingerprints(context, AuthIntent.getPackage());
            if (certs.length != 1 || !"48761EEF50EE53AFC4CC9C5F10E6BDE7F8F5B82F".equals(certs[0])) {
                // todo complain about wrong VK app
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new AssertionError(); // we've already ensured activity is resolved
        }

        return true;
    }

    /*pkg*/ static Intent createAuthIntent(Bundle extras) {
        Intent intent = new Intent(AuthIntent);
        intent.putExtras(extras);
        return intent;
    }

    // instance

    private final int appId;

    private final Object tokenLock = new Object();
    private VkAccessToken currentToken;

    private VkApp(int appId) {
        this.appId = appId;
    }

    /**
     * Returns a set of available authentication ways.
     * @return returned set may contain {@link AuthenticationWay#OfficialVkApp},
     * and will always contain {@link AuthenticationWay#WebView} and {@link AuthenticationWay#Auto}.
     */
    public Set<AuthenticationWay> getAvailableAuthenticationWays(Context context) {
        if (AuthenticationWay.OfficialVkApp.isAvailable(context)) return VkAppInstalled;
        else return VkAppNotInstalled;
    }

    /**
     * Perform auth from android.app.Activity through native fragment.
     * @param caller            Activity which implements VkAuthCallbackProvider
     * @param scope             permissions
     * @param authenticationWay a way of authentication
     * @param fragmentManager   a fragment manager
     */
    public <A extends Activity & VkAuthCallbackProvider> void login(
            A caller, Set<VkScope> scope, AuthenticationWay authenticationWay, android.app.FragmentManager fragmentManager
    ) {
        required(caller, "caller", scope, "scope", authenticationWay, "authenticationWay", fragmentManager, "fragmentManager");
        authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
    }

    /**
     * Perform auth from android.app.Fragment.
     * @param caller            caller Fragment
     * @param scope             permissions
     * @param authenticationWay a way of authentication
     * @param fragmentManager   a fragment manager
     */
    public void login(
            android.app.Fragment caller, Set<VkScope> scope, AuthenticationWay authenticationWay, android.app.FragmentManager fragmentManager
    ) {
        required(caller, "caller", caller.getActivity(), "caller.getActivity()", scope, "scope", authenticationWay, "authenticationWay");
        authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
    }

    private Support support;
    /**
     * Provides auth via Support libraries.
     */
    public Support support() {
        Support s = support;
        return s == null ? support = new Support() : s;
    }

    /**
     * Provides auth via Support libraries.
     */
    public final class Support {
        /*pkg*/ Support() {}

        /**
         * Perform auth from android.support.v7.app.AppCompatActivity through fragment back-port.
         * @param caller            AppCompatActivity which implements VkAuthCallbackProvider
         * @param scope             permissions
         * @param authenticationWay a way of authentication
         * @param fragmentManager   a fragment manager
         */
        public <A extends android.support.v7.app.AppCompatActivity & VkAuthCallbackProvider> void login(
                A caller, Set<VkScope> scope, AuthenticationWay authenticationWay, android.support.v4.app.FragmentManager fragmentManager
        ) {
            required(caller, "caller", scope, "scope", authenticationWay, "authenticationWay", fragmentManager, "fragmentManager");
            authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
        }

        /**
         * Perform auth from android.support.v4.app.Fragment.
         * @param caller            caller Fragment
         * @param scope             permissions
         * @param authenticationWay a way of authentication
         * @param fragmentManager   a fragment manager
         */
        public void login(
                android.support.v4.app.Fragment caller, Set<VkScope> scope, AuthenticationWay authenticationWay, android.support.v4.app.FragmentManager fragmentManager
        ) {
            required(caller, "caller", caller.getActivity(), "caller.getActivity()", scope, "scope", authenticationWay, "authenticationWay");
            authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
        }

    }

    private AndroidX androidX;
    /**
     * Provides auth via AndroidX libraries.
     */
    public AndroidX androidX() {
        AndroidX x = androidX;
        return x == null ? androidX = new AndroidX() : x;
    }

    /**
     * Provides auth via AndroidX libraries.
     */
    public final class AndroidX {
        /*pkg*/ AndroidX() {}

        /**
         * Perform auth from androidx.appcompat.app.AppCompatActivity through androidx.fragment back-port.
         * @param caller            AppCompatActivity which implements VkAuthCallbackProvider
         * @param scope             permissions
         * @param authenticationWay a way of authentication
         * @param fragmentManager   a fragment manager
         */
        public <A extends androidx.appcompat.app.AppCompatActivity & VkAuthCallbackProvider> void login(
                A caller, Set<VkScope> scope, AuthenticationWay authenticationWay, androidx.fragment.app.FragmentManager fragmentManager
        ) {
            required(caller, "caller", scope, "scope", authenticationWay, "authenticationWay", fragmentManager, "fragmentManager");
            authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
        }

        /**
         * Perform auth from androidx.fragment.
         * @param caller            caller Fragment
         * @param scope             permissions
         * @param authenticationWay a way of authentication
         * @param fragmentManager   a fragment manager
         */
        public void login(
                androidx.fragment.app.Fragment caller, Set<VkScope> scope, AuthenticationWay authenticationWay, androidx.fragment.app.FragmentManager fragmentManager
        ) {
            required(caller, "caller", caller.getActivity(), "caller.getActivity()", scope, "scope", authenticationWay, "authenticationWay");
            authenticationWay.perform(caller, createRequestBundle(scope), fragmentManager);
        }

    }

    private Bundle createRequestBundle(Set<VkScope> scope) {
        Bundle extras = new Bundle(5);
        extras.putString("version", VkApiVersion);
        extras.putInt("client_id", appId);
        extras.putBoolean("revoke", true); // don't know why, just like in original SDK
        extras.putString("scope", VkScope.joined(scope));
        return extras;
    }

    public boolean onActivityResult(int requestCode, int resultCode, Intent data, VkAuthCallback callback) {
        required(callback, "callback");

        if (requestCode != RcVkAuth) return false;

        if (resultCode != Activity.RESULT_OK) {
            callback.onError();
            return true;
        }

        if (data == null) {
            callback.onError();
            return true;
        }

        Bundle extras = data.getExtras();
        Map<String, String> tokenParams = new HashMap<>();
        if (extras.containsKey(VkExtraTokenData)) {
            // answer from WebView
            String tokenInfo = extras.getString(VkExtraTokenData);
            tokenParams = explodeQueryString(tokenInfo);
        } else {
            // answer from VK app
            for (String key : extras.keySet()) {
                tokenParams.put(key, String.valueOf(extras.get(key)));
            }
        }

        VkAccessToken newToken = VkAccessToken.create(tokenParams);
        if (newToken == null) {
            callback.onError();
            return false;
        }

        synchronized (tokenLock) {
            if (currentToken == null) {
                currentToken = newToken;
            } else {
                currentToken = newToken = currentToken.overriddenBy(newToken);
            }
        }

        callback.onResult(newToken);
        return true;
    }

    public interface VkAuthCallbackProvider {
        VkAuthCallback getVkAuthCallback();
    }
    public interface VkAuthCallback {
        void onResult(VkAccessToken token);
        void onError();
    }

}


text:
package demo.inventory.event;

import com.fasterxml.jackson.annotation.JsonIgnore;
import demo.event.Event;
import demo.inventory.controller.InventoryController;
import demo.inventory.domain.Inventory;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.hateoas.Link;

import javax.persistence.*;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

/**
 * The domain event {@link InventoryEvent} tracks the type and state of events as applied to the {@link Inventory} domain
 * object. This event resource can be used to event source the aggregate state of {@link Inventory}.
 * <p>
 * This event resource also provides a transaction log that can be used to append actions to the event.
 *
 * @author Kenny Bastani
 */
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(indexes = { @Index(name = "IDX_INVENTORY_EVENT", columnList = "entity_id") })
public class InventoryEvent extends Event<Inventory, InventoryEventType, Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eventId;

    @Enumerated(EnumType.STRING)
    private InventoryEventType type;

    @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @JsonIgnore
    private Inventory entity;

    @CreatedDate
    private Long createdAt;

    @LastModifiedDate
    private Long lastModified;

    public InventoryEvent() {
    }

    public InventoryEvent(InventoryEventType type) {
        this.type = type;
    }

    public InventoryEvent(InventoryEventType type, Inventory entity) {
        this.type = type;
        this.entity = entity;
    }

    @Override
    public Long getEventId() {
        return eventId;
    }

    @Override
    public void setEventId(Long id) {
        eventId = id;
    }

    @Override
    public InventoryEventType getType() {
        return type;
    }

    @Override
    public void setType(InventoryEventType type) {
        this.type = type;
    }

    @Override
    public Inventory getEntity() {
        return entity;
    }

    @Override
    public void setEntity(Inventory entity) {
        this.entity = entity;
    }

    @Override
    public Long getCreatedAt() {
        return createdAt;
    }

    @Override
    public void setCreatedAt(Long createdAt) {
        this.createdAt = createdAt;
    }

    @Override
    public Long getLastModified() {
        return lastModified;
    }

    @Override
    public void setLastModified(Long lastModified) {
        this.lastModified = lastModified;
    }

    @Override
    public Link getId() {
        return linkTo(InventoryController.class).slash("inventory").slash(getEntity().getIdentity()).slash("events")
                .slash(getEventId()).withSelfRel();
    }

    @Override
    public String toString() {
        return "InventoryEvent{" +
                "eventId=" + eventId +
                ", type=" + type +
                ", entity=" + entity +
                ", createdAt=" + createdAt +
                ", lastModified=" + lastModified +
                "} " + super.toString();
    }
}


text:
@interface WGLogoutResponse : WGResponse

@end


text:
Little script, which will root your ASUS Zenfone 5.

## Tested devices

- ASUS Zenfone 5 (T00F/T00J) with official WW-2.22.40.54 firmware

## Data safety

This script **will not overwrite any of your data** (files, photos, music, settings etc). It's totally safe.

Script **will overwrite**:
- dnx
- ifwi
- fastboot
- recovery

## Requirements

- adb
- fastboot

## Usage for linux

If you're on linux, run `root.sh` script in terminal and follow instructions. Make sure that you have [enabled USB debugging mode](#enabling-usb-debugging-mode) in your phone.

```shell
./root.sh
```

## Usage for non-linux systems (Windows, Mac OS etc.)

I don't have time for develop scripts for other systems, but you can root your phone manually. Your device will be rebooted a few times in whole process.

1. Download [the rooting script](https://github.com/sigo/asus-zenfone-5-root/archive/master.zip) (about 53.4MiB).
2. Extract downloaded package.
3. [Enable USB debugging mode](#enabling-usb-debugging-mode) in your phone.
4. Connect your phone with computer.
5. Open terminal in extracted `asus-zenfone-5-root` directory (you don't need reboot your phone manually, just execute following commands).
6. Reboot to bootloader.

    ```shell
    adb reboot bootloader
    ```

7. Unlock fastboot.

    ```shell
    fastboot flash fastboot files/root/fastboot.img
    fastboot reboot-bootloader
    ```

8. Unlock bootloader (**this can take up to 3 minutes**, please be patient).

    ```shell
    fastboot flash dnx files/vanilla/dnx_fwr_ctp_a500cg.bin
    fastboot flash ifwi files/root/ifwi_ctp_a500cg.bin
    fastboot reboot-bootloader
    ```

9. Root phone (**an error during this part is normal** - just ignore it).

    ```shell
    fastboot flash recovery files/root/recovery.img
    fastboot flash update files/root/dummy.zip
    adb reboot bootloader
    ```

10. Restore vanilla files.

    ```shell
    fastboot flash fastboot files/vanilla/fastboot.img
    fastboot flash recovery files/vanilla/recovery.img
    fastboot flash dnx files/vanilla/dnx_fwr_ctp_a500cg.bin
    fastboot flash ifwi files/vanilla/ifwi_ctp_a500cg.bin
    fastboot reboot
    ```

All done, enjoy your rooted phone.

## Enabling USB debugging mode

1. Go to system **settings**.
2. Click **about**.
3. Open **software information**.
4. Tap **build number** 7 times - until a pop-up hint informs you that you've entered the developer mode.
5. Return to **settings**.
6. Find and open **developer options**.
7. Select **USB debugging** and click **ok**.

## Authors

- Mateusz Jagiełło (http://sigo.pl)
- Vipin Arumugham (http://www.facebook.com/zenfoneindia)
- shakalaca (http://23pin.logdown.com/)


text:
using System.Collections.Generic;

namespace ITSWebMgmt.WebMgmtErrors
{
    public class WebMgmtErrorList
    {
        private List<WebMgmtError> errors;
        private int[] ErrorCount = { 0, 0, 0 };
        public string ErrorMessages;

        public WebMgmtErrorList(List<WebMgmtError> errors)
        {
            this.errors = errors;
            processErrors();
        }

        private void processErrors()
        {
            foreach (WebMgmtError error in errors)
            {
                if (error.HaveError())
                {
                    ErrorCount[error.Severeness]++;
                    ErrorMessages += generateMessage(error);
                }
            }
            if (ErrorMessages == null)
            {
                ErrorMessages = "No warnings found";
            }
        }

        private string generateMessage(WebMgmtError error)
        {
            string messageType = "";

            switch (error.Severeness)
            {
                case Severity.Error:
                    messageType = "negative";
                    break;
                case Severity.Warning:
                    messageType = "warning";
                    break;
                case Severity.Info:
                    messageType = "info";
                    break;
            }

            return $"
" +
                    $"
{error.Heading}
" +
                    $"
{error.Description}
" +
                    $"
";
        }

        public string getErrorCountMessage()
        {
            string messageType = "";
            string heading = "";

            if (ErrorCount[Severity.Error] > 0)
            {
                messageType = "negative";
                heading = "Errors";
            }
            else if (ErrorCount[Severity.Warning] > 0)
            {
                messageType = "warning";
                heading = "Warnings";
            }
            else if (ErrorCount[Severity.Info] > 0)
            {
                messageType = "info";
                heading = "Infos";
            }

            return messageType == "" ? "" : $"
" +
                    $"
{heading} found
" +
                    $"
Found {ErrorCount[Severity.Error]} errors, {ErrorCount[Severity.Warning]} warnings, and {ErrorCount[Severity.Info]} infos.
" +
                    $"
";
        }
    }
}


text:
using Nucleus.Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nucleus.Game
{
    /// <summary>
    /// A cell in a stage map blueprint
    /// </summary>
    [Serializable]
    public class BlueprintCell : IMapCellDataComponent
    {
        #region Properties

        /// <summary>
        /// Private backing member variable for the GenerationType property
        /// </summary>
        private CellGenerationType _GenerationType = CellGenerationType.Untouched;

        /// <summary>
        /// The generation type of the cell
        /// </summary>
        public CellGenerationType GenerationType
        {
            get { return _GenerationType; }
            set { _GenerationType = value; }
        }

        /// <summary>
        /// Private backing member variable for the Room property
        /// </summary>
        private Room _Room = null;

        /// <summary>
        /// The room that the cell occupies
        /// </summary>
        public Room Room
        {
            get { return _Room; }
            set { _Room = value; }
        }

        #endregion
    }
}


text:
package org.apache.yoko.orb.OB;

import static org.apache.yoko.orb.OCI.GiopVersion.GIOP1_0;

import org.apache.yoko.orb.OCI.GiopVersion;

public interface OB_Extras {
    //
    // Whether or not we are building a server capable of the
    // legacy compatible wide-char marshaling/unmarshaling
    //
    public final boolean COMPAT_WIDE_MARSHAL = false;

    //
    // the default GIOP Version to set for the streams
    //
    public final GiopVersion DEFAULT_GIOP_VERSION = GIOP1_0;
}


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

<TITLE>
TokenMgrError
</TITLE>

<META NAME="date" CONTENT="2011-02-10">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.sf.jsqlparser.parser

Class TokenMgrError

java.lang.Object
  java.lang.Throwable
      java.lang.Error
          net.sf.jsqlparser.parser.TokenMgrError

All Implemented Interfaces:
java.io.Serializable

public class TokenMgrError
extends java.lang.Error

Token Manager Error.

See Also:
Serialized Form

Field Summary

(package private)  int
errorCode

          Indicates the reason why the exception is thrown.

(package private) static int
INVALID_LEXICAL_STATE

          Tried to change to an invalid lexical state.

(package private) static int
LEXICAL_ERROR

          Lexical error occurred.

(package private) static int
LOOP_DETECTED

          Detected (and bailed out of) an infinite loop in the token manager.

private static long
serialVersionUID

          The version identifier for this Serializable class.

(package private) static int
STATIC_LEXER_ERROR

          An attempt was made to create a second instance of a static token manager.

Constructor Summary

TokenMgrError()

          No arg constructor.

TokenMgrError(boolean EOFSeen,
              int lexState,
              int errorLine,
              int errorColumn,
              java.lang.String errorAfter,
              char curChar,
              int reason)

          Full Constructor.

TokenMgrError(java.lang.String message,
              int reason)

          Constructor with message and reason.

Method Summary

protected static java.lang.String
addEscapes(java.lang.String str)

          Replaces unprintable characters by their escaped (or unicode escaped)
 equivalents in the given string

 java.lang.String
getMessage()

          You can also modify the body of this method to customize your error messages.

protected static java.lang.String
LexicalError(boolean EOFSeen,
             int lexState,
             int errorLine,
             int errorColumn,
             java.lang.String errorAfter,
             char curChar)

          Returns a detailed message for the Error when it is thrown by the
 token manager to indicate a lexical error.

Methods inherited from class java.lang.Throwable

fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

serialVersionUID

private static final long serialVersionUID

The version identifier for this Serializable class.
 Increment only if the serialized form of the
 class changes.

See Also:
Constant Field Values

LEXICAL_ERROR

static final int LEXICAL_ERROR

Lexical error occurred.

See Also:
Constant Field Values

STATIC_LEXER_ERROR

static final int STATIC_LEXER_ERROR

An attempt was made to create a second instance of a static token manager.

See Also:
Constant Field Values

INVALID_LEXICAL_STATE

static final int INVALID_LEXICAL_STATE

Tried to change to an invalid lexical state.

See Also:
Constant Field Values

LOOP_DETECTED

static final int LOOP_DETECTED

Detected (and bailed out of) an infinite loop in the token manager.

See Also:
Constant Field Values

errorCode

int errorCode

Indicates the reason why the exception is thrown. It will have
 one of the above 4 values.

Constructor Detail

TokenMgrError

public TokenMgrError()

No arg constructor.

TokenMgrError

public TokenMgrError(java.lang.String message,
                     int reason)

Constructor with message and reason.

TokenMgrError

public TokenMgrError(boolean EOFSeen,
                     int lexState,
                     int errorLine,
                     int errorColumn,
                     java.lang.String errorAfter,
                     char curChar,
                     int reason)

Full Constructor.

Method Detail

addEscapes

protected static final java.lang.String addEscapes(java.lang.String str)

Replaces unprintable characters by their escaped (or unicode escaped)
 equivalents in the given string

LexicalError

protected static java.lang.String LexicalError(boolean EOFSeen,
                                               int lexState,
                                               int errorLine,
                                               int errorColumn,
                                               java.lang.String errorAfter,
                                               char curChar)

Returns a detailed message for the Error when it is thrown by the
 token manager to indicate a lexical error.
 Parameters :
    EOFSeen     : indicates if EOF caused the lexical error
    curLexState : lexical state in which this error occurred
    errorLine   : line number when the error occurred
    errorColumn : column number when the error occurred
    errorAfter  : prefix that was seen before this error occurred
    curchar     : the offending character
 Note: You can customize the lexical error message by modifying this method.

getMessage

public java.lang.String getMessage()

You can also modify the body of this method to customize your error messages.
 For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
 of end-users concern, so you can return something like :

     "Internal Error : Please file a bug report .... "

 from this method for such cases in the release version of your parser.

Overrides:
getMessage in class java.lang.Throwable

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
find_package(fcl 0.5.0 CONFIG)
if(NOT FCL_FOUND AND NOT fcl_FOUND)
  find_package(fcl 0.5.0 REQUIRED MODULE)
endif()

# Set target fcl if not set
# Upstream provides the target since 0.5.0 but some package managers don't
# install the config file, which defines the target.
if((FCL_FOUND OR fcl_FOUND) AND NOT TARGET fcl)
  add_library(fcl INTERFACE IMPORTED)
  set_target_properties(fcl PROPERTIES
    INTERFACE_INCLUDE_DIRECTORIES "${FCL_INCLUDE_DIRS}"
    INTERFACE_LINK_LIBRARIES "${FCL_LIBRARIES}"
  )
endif()


text:
namespace Microsoft.Azure.CognitiveServices.Search.LocalSearch
{
    using Microsoft.Rest;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Local operations.
    /// </summary>
    public partial class Local : IServiceOperations<LocalSearchClient>, ILocal
    {
        /// <summary>
        /// Initializes a new instance of the Local class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public Local(LocalSearchClient client)
        {
            if (client == null)
            {
                throw new System.ArgumentNullException("client");
            }
            Client = client;
        }

        /// <summary>
        /// Gets a reference to the LocalSearchClient
        /// </summary>
        public LocalSearchClient Client { get; private set; }

        /// <summary>
        /// The Local Search API lets you send a search query to Bing and get back
        /// search results that include local businesses such as restaurants, hotels,
        /// retail stores, or other local businesses. The query can specify the name of
        /// the local business or it can ask for a list (for example, restaurants near
        /// me).
        /// </summary>
        /// <param name='query'>
        /// The user's search term.
        /// </param>
        /// <param name='acceptLanguage'>
        /// A comma-delimited list of one or more languages to use for user interface
        /// strings. The list is in decreasing order of preference. For additional
        /// information, including expected format, see
        /// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
        /// header and the setLang query parameter are mutually exclusive; do not
        /// specify both. If you set this header, you must also specify the cc query
        /// parameter. Bing will use the first supported language it finds from the
        /// list, and combine that language with the cc parameter value to determine
        /// the market to return results for. If the list does not include a supported
        /// language, Bing will find the closest language and market that supports the
        /// request, and may use an aggregated or default market for the results
        /// instead of a specified one. You should use this header and the cc query
        /// parameter only if you specify multiple languages; otherwise, you should use
        /// the mkt and setLang query parameters. A user interface string is a string
        /// that's used as a label in a user interface. There are very few user
        /// interface strings in the JSON response objects. Any links in the response
        /// objects to Bing.com properties will apply the specified language.
        /// </param>
        /// <param name='pragma'>
        /// By default, Bing returns cached content, if available. To prevent Bing from
        /// returning cached content, set the Pragma header to no-cache (for example,
        /// Pragma: no-cache).
        /// </param>
        /// <param name='userAgent'>
        /// The user agent originating the request. Bing uses the user agent to provide
        /// mobile users with an optimized experience. Although optional, you are
        /// strongly encouraged to always specify this header. The user-agent should be
        /// the same string that any commonly used browser would send. For information
        /// about user agents, see [RFC
        /// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
        /// </param>
        /// <param name='clientId'>
        /// Bing uses this header to provide users with consistent behavior across Bing
        /// API calls. Bing often flights new features and improvements, and it uses
        /// the client ID as a key for assigning traffic on different flights. If you
        /// do not use the same client ID for a user across multiple requests, then
        /// Bing may assign the user to multiple conflicting flights. Being assigned to
        /// multiple conflicting flights can lead to an inconsistent user experience.
        /// For example, if the second request has a different flight assignment than
        /// the first, the experience may be unexpected. Also, Bing can use the client
        /// ID to tailor web results to that client ID's search history, providing a
        /// richer experience for the user. Bing also uses this header to help improve
        /// result rankings by analyzing the activity generated by a client ID. The
        /// relevance improvements help with better quality of results delivered by
        /// Bing APIs and in turn enables higher click-through rates for the API
        /// consumer. IMPORTANT: Although optional, you should consider this header
        /// required. Persisting the client ID across multiple requests for the same
        /// end user and device combination enables 1) the API consumer to receive a
        /// consistent user experience, and 2) higher click-through rates via better
        /// quality of results from the Bing APIs. Each user that uses your application
        /// on the device must have a unique, Bing generated client ID. If you do not
        /// include this header in the request, Bing generates an ID and returns it in
        /// the X-MSEdge-ClientID response header. The only time that you should NOT
        /// include this header in a request is the first time the user uses your app
        /// on that device. Use the client ID for each Bing API request that your app
        /// makes for this user on the device. Persist the client ID. To persist the ID
        /// in a browser app, use a persistent HTTP cookie to ensure the ID is used
        /// across all sessions. Do not use a session cookie. For other apps such as
        /// mobile apps, use the device's persistent storage to persist the ID. The
        /// next time the user uses your app on that device, get the client ID that you
        /// persisted. Bing responses may or may not include this header. If the
        /// response includes this header, capture the client ID and use it for all
        /// subsequent Bing requests for the user on that device. If you include the
        /// X-MSEdge-ClientID, you must not include cookies in the request.
        /// </param>
        /// <param name='clientIp'>
        /// The IPv4 or IPv6 address of the client device. The IP address is used to
        /// discover the user's location. Bing uses the location information to
        /// determine safe search behavior. Although optional, you are encouraged to
        /// always specify this header and the X-Search-Location header. Do not
        /// obfuscate the address (for example, by changing the last octet to 0).
        /// Obfuscating the address results in the location not being anywhere near the
        /// device's actual location, which may result in Bing serving erroneous
        /// results.
        /// </param>
        /// <param name='location'>
        /// A semicolon-delimited list of key/value pairs that describe the client's
        /// geographical location. Bing uses the location information to determine safe
        /// search behavior and to return relevant local content. Specify the key/value
        /// pair as <key>:<value>. The following are the keys that you use
        /// to specify the user's location. lat (required): The latitude of the
        /// client's location, in degrees. The latitude must be greater than or equal
        /// to -90.0 and less than or equal to +90.0. Negative values indicate southern
        /// latitudes and positive values indicate northern latitudes. long (required):
        /// The longitude of the client's location, in degrees. The longitude must be
        /// greater than or equal to -180.0 and less than or equal to +180.0. Negative
        /// values indicate western longitudes and positive values indicate eastern
        /// longitudes. re (required): The radius, in meters, which specifies the
        /// horizontal accuracy of the coordinates. Pass the value returned by the
        /// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
        /// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
        /// (optional): The UTC UNIX timestamp of when the client was at the location.
        /// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
        /// (optional): The client's relative heading or direction of travel. Specify
        /// the direction of travel as degrees from 0 through 360, counting clockwise
        /// relative to true north. Specify this key only if the sp key is nonzero. sp
        /// (optional): The horizontal velocity (speed), in meters per second, that the
        /// client device is traveling. alt (optional): The altitude of the client
        /// device, in meters. are (optional): The radius, in meters, that specifies
        /// the vertical accuracy of the coordinates. Specify this key only if you
        /// specify the alt key. Although many of the keys are optional, the more
        /// information that you provide, the more accurate the location results are.
        /// Although optional, you are encouraged to always specify the user's
        /// geographical location. Providing the location is especially important if
        /// the client's IP address does not accurately reflect the user's physical
        /// location (for example, if the client uses VPN). For optimal results, you
        /// should include this header and the X-MSEdge-ClientIP header, but at a
        /// minimum, you should include this header.
        /// </param>
        /// <param name='countryCode'>
        /// A 2-character country code of the country where the results come from. This
        /// API supports only the United States market. If you specify this query
        /// parameter, it must be set to us. If you set this parameter, you must also
        /// specify the Accept-Language header. Bing uses the first supported language
        /// it finds from the languages list, and combine that language with the
        /// country code that you specify to determine the market to return results
        /// for. If the languages list does not include a supported language, Bing
        /// finds the closest language and market that supports the request, or it may
        /// use an aggregated or default market for the results instead of a specified
        /// one. You should use this query parameter and the Accept-Language query
        /// parameter only if you specify multiple languages; otherwise, you should use
        /// the mkt and setLang query parameters. This parameter and the mkt query
        /// parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='market'>
        /// The market where the results come from. You are strongly encouraged to
        /// always specify the market, if known. Specifying the market helps Bing route
        /// the request and return an appropriate and optimal response. This parameter
        /// and the cc query parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='localCategories'>
        /// comma-delimiated list of business categories to search for. Supported
        /// categories can be high-level such as EatDrink, Shop, SeeDo.
        /// </param>
        /// <param name='localCircularView'>
        /// Preferred location to search around, expressed as Latitude, longitude and
        /// radius in meters. For example 47.61503,-122.1719,5000. Note that circular
        /// view should only be used to indicate a search around a point on the map,
        /// not as an approximation for a view port of a map rectangle.
        /// </param>
        /// <param name='localMapView'>
        /// Preferred bounding box for results, specified in NW_latitude, NW_Longitude,
        /// SE_Latitude, SE_Longitude format. For example 47.64,-122.13,47.63,-122.12.
        /// These values are lat, long pairs for the Northwest corner and the Southeast
        /// corner of a rectangle.
        /// </param>
        /// <param name='count'>
        /// Preferred number of results to return. If not specified, then Bing returns
        /// 1-20 of the most relevant results.
        /// </param>
        /// <param name='first'>
        /// First result to return. zero-based. default is 0.
        /// </param>
        /// <param name='responseFormat'>
        /// The media type to use for the response. The following are the possible
        /// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
        /// JSONLD, the response body includes JSON-LD objects that contain the search
        /// results.
        /// </param>
        /// <param name='safeSearch'>
        /// A filter used to filter adult content. Off: Return webpages with adult
        /// text, images, or videos. Moderate: Return webpages with adult text, but not
        /// adult images or videos. Strict: Do not return webpages with adult text,
        /// images, or videos. The default is Moderate. If the request comes from a
        /// market that Bing's adult policy requires that safeSearch is set to Strict,
        /// Bing ignores the safeSearch value and uses Strict. If you use the site:
        /// query operator, there is the chance that the response may contain adult
        /// content regardless of what the safeSearch query parameter is set to. Use
        /// site: only if you are aware of the content on the site and your scenario
        /// supports the possibility of adult content. Possible values include: 'Off',
        /// 'Moderate', 'Strict'
        /// </param>
        /// <param name='setLang'>
        /// The language to use for user interface strings. Specify the language using
        /// the ISO 639-1 2-letter language code. For example, the language code for
        /// English is EN. The default is EN (English). Although optional, you should
        /// always specify the language. Typically, you set setLang to the same
        /// language specified by mkt unless the user wants the user interface strings
        /// displayed in a different language. This parameter and the Accept-Language
        /// header are mutually exclusive; do not specify both. A user interface string
        /// is a string that's used as a label in a user interface. There are few user
        /// interface strings in the JSON response objects. Also, any links to Bing.com
        /// properties in the response objects apply the specified language.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<HttpOperationResponse<SearchResponse>> SearchWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string localCategories = default(string), string localCircularView = default(string), string localMapView = default(string), string count = default(string), string first = default(string), IList<string> responseFormat = default(IList<string>), string safeSearch = default(string), string setLang = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (query == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "query");
            }
            string xBingApisSDK = "true";
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("xBingApisSDK", xBingApisSDK);
                tracingParameters.Add("acceptLanguage", acceptLanguage);
                tracingParameters.Add("pragma", pragma);
                tracingParameters.Add("userAgent", userAgent);
                tracingParameters.Add("clientId", clientId);
                tracingParameters.Add("clientIp", clientIp);
                tracingParameters.Add("location", location);
                tracingParameters.Add("countryCode", countryCode);
                tracingParameters.Add("market", market);
                tracingParameters.Add("query", query);
                tracingParameters.Add("localCategories", localCategories);
                tracingParameters.Add("localCircularView", localCircularView);
                tracingParameters.Add("localMapView", localMapView);
                tracingParameters.Add("count", count);
                tracingParameters.Add("first", first);
                tracingParameters.Add("responseFormat", responseFormat);
                tracingParameters.Add("safeSearch", safeSearch);
                tracingParameters.Add("setLang", setLang);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "localbusinesses/v7.0/search").ToString();
            List<string> _queryParameters = new List<string>();
            if (countryCode != null)
            {
                _queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
            }
            if (market != null)
            {
                _queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
            }
            if (query != null)
            {
                _queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
            }
            if (localCategories != null)
            {
                _queryParameters.Add(string.Format("localcategories={0}", System.Uri.EscapeDataString(localCategories)));
            }
            if (localCircularView != null)
            {
                _queryParameters.Add(string.Format("localcircularview={0}", System.Uri.EscapeDataString(localCircularView)));
            }
            if (localMapView != null)
            {
                _queryParameters.Add(string.Format("localmapview={0}", System.Uri.EscapeDataString(localMapView)));
            }
            if (count != null)
            {
                _queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(count)));
            }
            if (first != null)
            {
                _queryParameters.Add(string.Format("first={0}", System.Uri.EscapeDataString(first)));
            }
            if (responseFormat != null)
            {
                _queryParameters.Add(string.Format("ResponseFormat={0}", System.Uri.EscapeDataString(string.Join(",", responseFormat))));
            }
            if (safeSearch != null)
            {
                _queryParameters.Add(string.Format("SafeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
            }
            if (setLang != null)
            {
                _queryParameters.Add(string.Format("SetLang={0}", System.Uri.EscapeDataString(setLang)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (xBingApisSDK != null)
            {
                if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
                {
                    _httpRequest.Headers.Remove("X-BingApis-SDK");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
            }
            if (acceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("Accept-Language"))
                {
                    _httpRequest.Headers.Remove("Accept-Language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
            }
            if (pragma != null)
            {
                if (_httpRequest.Headers.Contains("Pragma"))
                {
                    _httpRequest.Headers.Remove("Pragma");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Pragma", pragma);
            }
            if (userAgent != null)
            {
                if (_httpRequest.Headers.Contains("User-Agent"))
                {
                    _httpRequest.Headers.Remove("User-Agent");
                }
                _httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
            }
            if (clientId != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientID");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
            }
            if (clientIp != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientIP");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
            }
            if (location != null)
            {
                if (_httpRequest.Headers.Contains("X-Search-Location"))
                {
                    _httpRequest.Headers.Remove("X-Search-Location");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
            }

            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    ErrorResponse _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse<SearchResponse>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SearchResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

    }
}


text:
// These are all variables needed at some point during our work.
// They keep track of the JSON we have received, storing it in the browser,
// Thus lightening the load on the backend (caching and such)

var _VERSION_ = "0.12-SNAPSHOT" // Current version (as far as we know)
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
var d_ppp = 15; // results per page
var c_page = 0; // current page position for list view
var open_emails = [] // cache index for loaded emails
var list_year = {}
var DEFAULT_RETENTION = "lte=1M" // default timespan for list view
var current_retention = DEFAULT_RETENTION
var current_cal_min = 1997 // don't go further back than 1997 in case everything blows up, date-wise
var keywords = ""
var current_thread = 0 // marker for list view; currently open thread/email
var current_thread_mids = {} // duplicate guard for threading
var saved_emails = {} // JSON cache for emails
var current_query = "" // currently active search query
var old_json = {} // pointer to previously loaded JSON object
var all_lists = {}
var current_json = {} // pointer to currently loaded JSON
var current_thread_json = {}
var current_flat_json = {}
var current_email_msgs = []
var current_reply_eid = null
var last_opened_email = null
var firstVisit = true
var global_deep = false
var old_state = {}
var nest = ""
var xlist = ""
var domlist = {}
var compose_headers = {}
var login = {}
var xyz
var start = new Date().getTime()
var latestEmailInThread = 0
var composeType = "reply"
var gxdomain = ""
var fl = null
var kiddos = [] // DOM tree for traverse functions
var pending_urls = {} // URL list for GetAsync's support functions (such as the spinner)
var pb_refresh = 0
var treeview_guard = {}
var mbox_month = null

var URL_BASE = pm_config.URLBase ? pm_config.URLBase.replace(/\/+/g, "/") : ""

function isStorageAvailable(type) {
    try {
        var storage = window[type],
            x = 'pm_test';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return false;
    }
}

var localStorageAvailable   = isStorageAvailable('localStorage')
var sessionStorageAvailable = isStorageAvailable('sessionStorage')

// Links from viewmode to the function that handles them
var viewModes = {
    threaded: {
        email: loadEmails_threaded,
        list: loadList_threaded,
        description: 'Grouped by threads'
    },
    flat: {
        email: loadEmails_flat,
        list: loadList_flat,
        description: 'Flat list (one email per line)'
    },
    treeview: {
        email: loadEmails_flat,
        list: loadList_treeview,
        description: 'Threaded with treeview'
    },
}